diff --git a/CHANGELOG.md b/CHANGELOG.md index d61ce95..fe82604 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ One line per merged PR, newest first. +- 2026-11-11 · Add a preview of the V4D viewer v0.6.0 (Atelier) at `/v4d-next/`: noindex and linked from nowhere; the live `/v4d/` (still v0.1.0) is unchanged. - 2026-11-02 · v26.81 New favicon and app icons (sculpted head): recompressed `favicon.ico`, `favicon.svg`, `apple-touch-icon.png`, `icon-192.png`, `icon-512.png`. - 2026-10-30 · v26.80 Add V4D to the site: homepage slide, Generative Art card (replacing Melancholic Toons there), Journal story (`v4d-virtual-fourth-dimension.html`), Software entry. - 2026-10-29 · Add the V4D viewer at `/v4d/` (a built copy of the private V4D app: WebGPU point viewer with the walker, presets and particle looks). diff --git a/CLAUDE.md b/CLAUDE.md index fbd52f8..04ebf6e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -73,7 +73,8 @@ js/inline-video.js looping videos: siteVideo.play/pause, iOS autoplay fallbac Images// artwork; Images/og/ = 1200x630 social cards webfonts/ self-hosted PT Sans (the only font) archive/ superseded pages; three journal posts here are still live -v4d/ V4D viewer: a build of the private V4D repo (`VITE_BASE=/v4d/ pnpm build` in apps/viewer, then copy dist/ here). Don't edit by hand; not a live page for the checks +v4d/ V4D viewer: a build of the private V4D repo (`node scripts/publish.mjs v4d` in its apps/viewer). Don't edit by hand; not a live page for the checks +v4d-next/ a preview build of the V4D viewer (same script, `v4d-next`): noindex, linked from nowhere, replaced or removed freely ``` ## Design in one breath diff --git a/docs/SITE-OVERVIEW.md b/docs/SITE-OVERVIEW.md index 10b692a..2f07add 100644 --- a/docs/SITE-OVERVIEW.md +++ b/docs/SITE-OVERVIEW.md @@ -33,6 +33,7 @@ generative-art.html Generative-art hub (VOID card, V4D card, Moondust car photogrammetry.html 3D scan work (experiments.html is a copy, canonical -> photogrammetry) software.html OpenLayer, VOID, Moondust, V4D, Window-Drift v4d/ V4D viewer: built copy of the private V4D app, not hand-written +v4d-next/ preview build of the V4D viewer (noindex, unlinked), for checking a version before it replaces v4d/ v4d-virtual-fourth-dimension.html V4D story, listed in the Journal Moondust.html Moondust product page (wishlist = mailto link) PStoComfy2026.html OpenLayer article diff --git a/v4d-next/apple-touch-icon.png b/v4d-next/apple-touch-icon.png new file mode 100644 index 0000000..85425ce Binary files /dev/null and b/v4d-next/apple-touch-icon.png differ diff --git a/v4d-next/assets/GLTFLoader-DXt_9DaB.js b/v4d-next/assets/GLTFLoader-DXt_9DaB.js new file mode 100644 index 0000000..54684a0 --- /dev/null +++ b/v4d-next/assets/GLTFLoader-DXt_9DaB.js @@ -0,0 +1 @@ +import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as v,S as ee,T as te,U as ne,V as y,W as re,X as b,Y as x,Z as ie,_ as ae,a as oe,at as S,b as se,c as C,d as w,et as ce,f as le,g as ue,h as de,i as T,it as fe,j as pe,k as E,l as me,m as he,n as ge,nt as _e,o as ve,ot as D,p as ye,q as be,r as xe,rt as O,s as k,st as A,t as j,tt as M,u as N,v as Se,w as Ce,x as we,y as P,z as Te}from"./synth.worker-D-Qhg7ac.js";function F(e,t){if(t===0)return console.warn(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.`),e;if(t===2||t===1){let n=e.getIndex();if(n===null){let t=[],r=e.getAttribute(`position`);if(r!==void 0){for(let e=0;e=2.0 are supported.`));return}let c=new it(i,{path:t||this.resourcePath||``,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let e=0;e=0&&o[t]===void 0&&console.warn(`THREE.GLTFLoader: Unknown extension "`+t+`".`)}}c.setExtensions(a),c.setPlugins(o),c.parse(n,r)}parseAsync(e,t){let n=this;return new Promise(function(r,i){n.parse(e,t,r,i)})}};function De(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}const I={KHR_BINARY_GLTF:`KHR_binary_glTF`,KHR_DRACO_MESH_COMPRESSION:`KHR_draco_mesh_compression`,KHR_LIGHTS_PUNCTUAL:`KHR_lights_punctual`,KHR_MATERIALS_CLEARCOAT:`KHR_materials_clearcoat`,KHR_MATERIALS_DISPERSION:`KHR_materials_dispersion`,KHR_MATERIALS_IOR:`KHR_materials_ior`,KHR_MATERIALS_SHEEN:`KHR_materials_sheen`,KHR_MATERIALS_SPECULAR:`KHR_materials_specular`,KHR_MATERIALS_TRANSMISSION:`KHR_materials_transmission`,KHR_MATERIALS_IRIDESCENCE:`KHR_materials_iridescence`,KHR_MATERIALS_ANISOTROPY:`KHR_materials_anisotropy`,KHR_MATERIALS_UNLIT:`KHR_materials_unlit`,KHR_MATERIALS_VOLUME:`KHR_materials_volume`,KHR_TEXTURE_BASISU:`KHR_texture_basisu`,KHR_TEXTURE_TRANSFORM:`KHR_texture_transform`,KHR_MESH_QUANTIZATION:`KHR_mesh_quantization`,KHR_MATERIALS_EMISSIVE_STRENGTH:`KHR_materials_emissive_strength`,EXT_MATERIALS_BUMP:`EXT_materials_bump`,EXT_TEXTURE_WEBP:`EXT_texture_webp`,EXT_TEXTURE_AVIF:`EXT_texture_avif`,EXT_MESHOPT_COMPRESSION:`EXT_meshopt_compression`,EXT_MESH_GPU_INSTANCING:`EXT_mesh_gpu_instancing`};var Oe=class{constructor(e){this.parser=e,this.name=I.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n=0)throw Error(`THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures`);return null}return t.loadTextureImage(e,i.source,a)}},Ve=class{constructor(e){this.parser=e,this.name=I.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},He=class{constructor(e){this.parser=e,this.name=I.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},Ue=class{constructor(e){this.name=I.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let e=n.extensions[this.name],r=this.parser.getDependency(`buffer`,e.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files`);return null}return r.then(function(t){let n=e.byteOffset||0,r=e.byteLength||0,a=e.count,o=e.byteStride,s=new Uint8Array(t,n,r);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(a,o,s,e.mode,e.filter).then(function(e){return e.buffer}):i.ready.then(function(){let t=new ArrayBuffer(a*o);return i.decodeGltfBuffer(new Uint8Array(t),a,o,s,e.mode,e.filter),t})})}return null}},We=class{constructor(e){this.name=I.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let r=t.meshes[n.mesh];for(let e of r.primitives)if(e.mode!==V.TRIANGLES&&e.mode!==V.TRIANGLE_STRIP&&e.mode!==V.TRIANGLE_FAN&&e.mode!==void 0)return null;let i=n.extensions[this.name].attributes,a=[],o={};for(let e in i)a.push(this.parser.getDependency(`accessor`,i[e]).then(t=>(o[e]=t,o[e])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(e=>{let t=e.pop(),n=t.isGroup?t.children:[t],r=e[0].count,i=[];for(let e of n){let t=new p,n=new D,a=new x,s=new D(1,1,1),l=new he(e.geometry,e.material,r);for(let e=0;e0||e.search(/^data\:image\/jpeg/)===0?`image/jpeg`:e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?`image/webp`:e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0?`image/ktx2`:`image/png`}const rt=new p;var it=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new De,this.associations=/* @__PURE__ */ new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,r=-1,i=!1,a=-1;if(typeof navigator<`u`){let e=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(e)===!0;let t=e.match(/Version\/(\d+)/);r=n&&t?parseInt(t[1],10):-1,i=e.indexOf(`Firefox`)>-1,a=i?e.match(/Firefox\/([0-9]+)\./)[1]:-1}this.textureLoader=typeof createImageBitmap>`u`||n&&r<17||i&&a<98?new fe(this.options.manager):new le(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new N(this.options.manager),this.fileLoader.setResponseType(`arraybuffer`),this.options.crossOrigin===`use-credentials`&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,r=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(e){return e._markDefs&&e._markDefs()}),Promise.all(this._invokeAll(function(e){return e.beforeRoot&&e.beforeRoot()})).then(function(){return Promise.all([n.getDependencies(`scene`),n.getDependencies(`animation`),n.getDependencies(`camera`)])}).then(function(t){let a={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:n,userData:{}};return Y(i,a,r),X(a,r),Promise.all(n._invokeAll(function(e){return e.afterRoot&&e.afterRoot(a)})).then(function(){for(let e of a.scenes)e.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let n=0,r=t.length;n{let n=this.associations.get(e);n!=null&&this.associations.set(t,n);for(let[n,r]of e.children.entries())i(r,t.children[n])};return i(n,r),r.name+=`_instance_`+e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n=2&&p.setY(t,u[e*a+1]),a>=3&&p.setZ(t,u[e*a+2]),a>=4&&p.setW(t,u[e*a+3]),a>=5)throw Error(`THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.`)}p.normalized=d}return p})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r],a=this.textureLoader;if(i.uri){let e=n.manager.getHandler(i.uri);e!==null&&(a=e)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let r=this,i=this.json,a=i.textures[e],o=i.images[t],s=(o.uri||o.bufferView)+`:`+a.sampler;if(this.textureCache[s])return this.textureCache[s];let c=this.loadImageSource(t,n).then(function(t){t.flipY=!1,t.name=a.name||o.name||``,t.name===``&&typeof o.uri==`string`&&o.uri.startsWith(`data:image/`)===!1&&(t.name=o.uri);let n=(i.samplers||{})[a.sampler]||{};return t.magFilter=U[n.magFilter]||1006,t.minFilter=U[n.minFilter]||1008,t.wrapS=W[n.wrapS]||1e3,t.wrapT=W[n.wrapT]||1e3,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==1003&&t.minFilter!==1006,r.associations.set(t,{textures:e}),t}).catch(function(){return null});return this.textureCache[s]=c,c}loadImageSource(e,t){let n=this,r=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let a=r.images[e],o=self.URL||self.webkitURL,s=a.uri||``,c=!1;if(a.bufferView!==void 0)s=n.getDependency(`bufferView`,a.bufferView).then(function(e){c=!0;let t=new Blob([e],{type:a.mimeType});return s=o.createObjectURL(t),s});else if(a.uri===void 0)throw Error(`THREE.GLTFLoader: Image `+e+` is missing URI and bufferView`);let l=Promise.resolve(s).then(function(e){return new Promise(function(n,r){let a=n;t.isImageBitmapLoader===!0&&(a=function(e){let t=new O(e);t.needsUpdate=!0,n(t)}),t.load(E.resolveURL(e,i.path),a,void 0,r)})}).then(function(e){return c===!0&&o.revokeObjectURL(s),X(e,a),e.userData.mimeType=a.mimeType||nt(a.uri),e}).catch(function(e){throw console.error(`THREE.GLTFLoader: Couldn't load texture`,s),e});return this.sourceCache[e]=l,l}assignTexture(e,t,n,r){let i=this;return this.getDependency(`texture`,n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),i.extensions[I.KHR_TEXTURE_TRANSFORM]){let e=n.extensions===void 0?void 0:n.extensions[I.KHR_TEXTURE_TRANSFORM];if(e){let t=i.associations.get(a);a=i.extensions[I.KHR_TEXTURE_TRANSFORM].extendTexture(a,e),i.associations.set(a,t)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let n=e.geometry,r=e.material,i=n.attributes.tangent===void 0,a=n.attributes.color!==void 0,o=n.attributes.normal===void 0;if(e.isPoints){let e=`PointsMaterial:`+r.uuid,n=this.cache.get(e);n||(n=new be,t.prototype.copy.call(n,r),n.color.copy(r.color),n.map=r.map,n.sizeAttenuation=!1,this.cache.add(e,n)),r=n}else if(e.isLine){let e=`LineBasicMaterial:`+r.uuid,n=this.cache.get(e);n||(n=new we,t.prototype.copy.call(n,r),n.color.copy(r.color),n.map=r.map,this.cache.add(e,n)),r=n}if(i||a||o){let e=`ClonedMaterial:`+r.uuid+`:`;i&&(e+=`derivative-tangents:`),a&&(e+=`vertex-colors:`),o&&(e+=`flat-shading:`);let t=this.cache.get(e);t||(t=r.clone(),a&&(t.vertexColors=!0),o&&(t.flatShading=!0),i&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(r))),r=t}e.material=r}getMaterialType(){return l}loadMaterial(e){let t=this,n=this.json,r=this.extensions,a=n.materials[e],o,s={},c=a.extensions||{},l=[];if(c[I.KHR_MATERIALS_UNLIT]){let e=r[I.KHR_MATERIALS_UNLIT];o=e.getMaterialType(),l.push(e.extendParams(s,a,t))}else{let n=a.pbrMetallicRoughness||{};if(s.color=new k(1,1,1),s.opacity=1,Array.isArray(n.baseColorFactor)){let e=n.baseColorFactor;s.color.setRGB(e[0],e[1],e[2],i),s.opacity=e[3]}n.baseColorTexture!==void 0&&l.push(t.assignTexture(s,`map`,n.baseColorTexture,_)),s.metalness=n.metallicFactor===void 0?1:n.metallicFactor,s.roughness=n.roughnessFactor===void 0?1:n.roughnessFactor,n.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(s,`metalnessMap`,n.metallicRoughnessTexture)),l.push(t.assignTexture(s,`roughnessMap`,n.metallicRoughnessTexture))),o=this._invokeOne(function(t){return t.getMaterialType&&t.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,s)})))}a.doubleSided===!0&&(s.side=2);let u=a.alphaMode||J.OPAQUE;if(u===J.BLEND?(s.transparent=!0,s.depthWrite=!1):(s.transparent=!1,u===J.MASK&&(s.alphaTest=a.alphaCutoff===void 0?.5:a.alphaCutoff)),a.normalTexture!==void 0&&o!==g&&(l.push(t.assignTexture(s,`normalMap`,a.normalTexture)),s.normalScale=new S(1,1),a.normalTexture.scale!==void 0)){let e=a.normalTexture.scale;s.normalScale.set(e,e)}if(a.occlusionTexture!==void 0&&o!==g&&(l.push(t.assignTexture(s,`aoMap`,a.occlusionTexture)),a.occlusionTexture.strength!==void 0&&(s.aoMapIntensity=a.occlusionTexture.strength)),a.emissiveFactor!==void 0&&o!==g){let e=a.emissiveFactor;s.emissive=new k().setRGB(e[0],e[1],e[2],i)}return a.emissiveTexture!==void 0&&o!==g&&l.push(t.assignTexture(s,`emissiveMap`,a.emissiveTexture,_)),Promise.all(l).then(function(){let n=new o(s);return a.name&&(n.name=a.name),X(n,a),t.associations.set(n,{materials:e}),a.extensions&&Y(r,n,a),n})}createUniqueName(e){let t=u.sanitizeNodeName(e||``);return t in this.nodeNamesUsed?t+`_`+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,r=this.primitiveCache;function i(e){return n[I.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(n){return $(n,e,t)})}let a=[];for(let n=0,o=e.length;n0&&et(p,a),p.name=t.createUniqueName(a.name||`mesh_`+e),X(p,a),f.extensions&&Y(i,p,f),t.assignFinalMaterial(p),l.push(p)}for(let n=0,r=l.length;n1?new w:t.length===1?t[0]:new c,o!==t[0])for(let e=0,n=t.length;e1){let e=r.associations.get(o);r.associations.set(o,{...e})}return r.associations.get(o).nodes=e,o}),this.nodeCache[e]}loadScene(e){let n=this.extensions,r=this.json.scenes[e],i=this,a=new w;r.name&&(a.name=i.createUniqueName(r.name)),X(a,r),r.extensions&&Y(n,a,r);let o=r.nodes||[],s=[];for(let e=0,t=o.length;e{let n=/* @__PURE__ */ new Map;for(let[e,r]of i.associations)(e instanceof t||e instanceof O)&&n.set(e,r);return e.traverse(e=>{let t=i.associations.get(e);t!=null&&n.set(e,t)}),n})(a),a})}_createAnimationTracks(e,t,n,r,i){let a=[],o=e.name?e.name:e.uuid,s=[];q[i.path]===q.weights?e.traverse(function(e){e.morphTargetInfluences&&s.push(e.name?e.name:e.uuid)}):s.push(o);let c;switch(q[i.path]){case q.weights:c=y;break;case q.rotation:c=b;break;case q.translation:case q.scale:c=A;break;default:switch(n.itemSize){case 1:c=y;break;default:c=A}}let l=r.interpolation===void 0?P:Ze[r.interpolation],u=this._getArrayFromAccessor(n);for(let e=0,n=s.length;enull):null,a=i?[...i.features.has(`shader-f16`)?[[`webgpu`,`fp16`]]:[],[`webgpu`,`fp32`],[`wasm`,`fp32`]]:[[`wasm`,`fp32`]],o=/* @__PURE__ */ new Map,s=t=>{if(t.status===`progress_total`)return e((t.progress??0)/100);if(t.status!==`progress`||!t.file||!t.total)return;o.set(t.file,{loaded:t.loaded??0,total:t.total});let n=0,r=0;for(let e of o.values())n+=e.loaded,r+=e.total;e(r?n/r:0)},c=null;for(let[e,r]of a)try{let i=await t(`depth-estimation`,`onnx-community/depth-anything-v2-small`,{device:e,dtype:r,progress_callback:s}),a=async(e,t,r)=>{let a=await i(new n(e,t,r,4)),o=(Array.isArray(a)?a[0]:a).predicted_depth;o.type!==`float32`&&(o=o.to(`float32`));let[s,c]=o.dims.slice(-2);return{data:Float32Array.from(o.data),width:c,height:s}};if(!(await a((/* @__PURE__ */ new Uint8ClampedArray(9408)).fill(128),56,42)).data.every(Number.isFinite))throw Error(`${e} ${r} gave non-finite depth`);return{name:`Depth Anything V2 Small (${e}, ${r})`,estimate:e=>a(e.rgba,e.width,e.height),dispose:async()=>{await i.dispose()}}}catch(e){c=e}throw c instanceof Error?c:Error(String(c))}export{e as loadDepthModel}; \ No newline at end of file diff --git a/v4d-next/assets/index-BX3PuS-K.css b/v4d-next/assets/index-BX3PuS-K.css new file mode 100644 index 0000000..1d75641 --- /dev/null +++ b/v4d-next/assets/index-BX3PuS-K.css @@ -0,0 +1 @@ +:root{--ink:#ecebe8;--dim:#9b9890;--faint:#7d7a73;--line:#ecebe829;--glass:#08080880;--halo:0 0 6px #000000e6, 0 0 2px #000000e6;--glass-line:#ecebe814;--accent:#8fd3ff;--edge:40px;--track:.18em;color:var(--ink);background:#000;font:11px/1.5 ui-sans-serif,system-ui,-apple-system,Segoe UI,Helvetica Neue,sans-serif}.app.light{--ink:#141414;--dim:#55524d;--faint:#6b6862;--line:#14141433;--glass:#faf9f68c;--glass-line:#14141414;--halo:0 0 6px #ffffffe6;color:var(--ink)}*{box-sizing:border-box}html,body,#root,.app{background:#000;height:100%;margin:0;overflow:hidden}.stage{place-items:center;display:grid;position:absolute;inset:0;container-type:size}.viewport{touch-action:none;cursor:grab;width:100%;height:100%;display:block}.viewport:active{cursor:grabbing}button,select,input{font:inherit;color:inherit}button{cursor:pointer;text-transform:uppercase;letter-spacing:var(--track);color:var(--dim);background:0 0;border:none;padding:0}button:hover{color:var(--ink)}button:focus-visible,label:focus-within{outline:1px solid var(--accent);outline-offset:3px}select{border:none;border-bottom:1px solid var(--line);cursor:pointer;text-transform:uppercase;letter-spacing:.12em;background:0 0;border-radius:0;padding:1px 0}select option{color:#ecebe8;background:#111}kbd{font:inherit;color:var(--faint);letter-spacing:.1em;text-transform:uppercase;margin-left:9px}input[type=range]{appearance:none;cursor:pointer;background:0 0;width:100%;height:16px;margin:0}input[type=range]::-webkit-slider-runnable-track{background:var(--line);height:1px}input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;background:var(--ink);border:none;border-radius:50%;width:9px;height:9px;margin-top:-4px}input[type=range]::-moz-range-track{background:var(--line);height:1px}input[type=range]::-moz-range-thumb{background:var(--ink);border:none;border-radius:50%;width:9px;height:9px}.lbl{color:var(--dim);text-transform:uppercase;letter-spacing:var(--track);white-space:nowrap}.val{color:var(--dim);text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}.row{grid-template-columns:86px 1fr 62px;align-items:center;gap:10px;margin:4px 0;display:grid}.row select{grid-column:2/4}.opts{flex-wrap:wrap;align-items:baseline;gap:4px 13px;display:flex}.opts .lbl{margin-right:4px}.opts button{border-bottom:1px solid #0000;padding:2px 0 3px}.opts button.on{color:var(--ink);border-bottom-color:var(--ink)}.meta{color:var(--dim);margin:6px 0 0;line-height:1.6}button.link{color:var(--ink);text-transform:none;letter-spacing:0;padding:0;text-decoration:underline}.ui{text-shadow:var(--halo);transition:opacity .35s;position:absolute}.app.bare .ui{opacity:0;pointer-events:none}.app.studio{--rail:212px;--panel:328px;--bar:56px;font-size:12px}.app.studio.no-panels{--panel:0px}.app.studio .stage{left:var(--rail);right:var(--panel);bottom:var(--bar)}.app.studio.bare .stage{bottom:0;left:0;right:0}.app.studio .stage.framed{background:#060606;padding:30px}.app.studio.light .stage.framed{background:#e2dfd9}.stage.framed .viewport{width:min(100cqw, calc(100cqh * var(--aspect)));height:min(100cqh, calc(100cqw / var(--aspect)));box-shadow:0 0 0 1px #80808059}.rail,.inspector,.bar{--ink:#ecebe8;--dim:#a3a098;--faint:#7d7a73;--line:#ecebe824;--glass-line:#ecebe817;color:var(--ink);text-shadow:none;background:#0a0a0a}.rail{width:var(--rail);border-right:1px solid var(--line);flex-direction:column;display:flex;top:0;bottom:0;left:0}.rail-head{padding:26px 22px 10px}.rail-head h1{letter-spacing:.62em;margin:0 0 6px;font-size:15px;font-weight:400}.rail-head p{color:var(--dim);text-transform:uppercase;letter-spacing:var(--track);margin:0 0 14px;font-size:10.5px}.rail-head .back{font-size:10.5px}.rail-body{scrollbar-width:thin;scrollbar-color:#2a2a2a transparent;flex:1;padding:0 22px 16px;overflow-y:auto}.rail-foot{color:var(--faint);letter-spacing:.08em;padding:10px 22px 14px;font-size:10px}.rail h2,.lib h2{font:inherit;color:var(--faint);text-transform:uppercase;letter-spacing:.26em;margin:22px 0 8px;font-size:10px}.lib-list{flex-direction:column;align-items:stretch;display:flex}.lib-list>button,.lib-list .add,.look-own .look{text-align:left;text-transform:none;letter-spacing:.03em;width:100%;color:var(--dim);cursor:pointer;align-items:baseline;gap:8px;padding:3px 0;font-size:12.5px;display:flex}.lib-list>button:hover,.lib-list .add:hover,.look-own .look:hover,.lib-list>button.on{color:var(--ink)}.lib-list>button.on:before{content:"";background:var(--ink);border-radius:50%;flex:none;align-self:center;width:4px;height:4px;margin-right:2px}.lib-list kbd,.lib-list .tag{margin-left:auto}.lib-list .tag+kbd{margin-left:8px}.tag{color:var(--faint);letter-spacing:.1em;text-transform:uppercase;white-space:nowrap;font-size:9.5px}.lib-list .add{color:var(--faint)}.lib-list .add input,label.file input{opacity:0;width:1px;height:1px;position:absolute}.lib-list .sub{margin:4px 0 6px}.lib-list .sub .row{grid-template-columns:40px 1fr 46px}.look-own{align-items:baseline;gap:8px;display:flex}.look-own .x{color:var(--faint);letter-spacing:0;font-size:14px;line-height:1}.look-own .x:hover{color:var(--ink)}.look-name{align-items:baseline;gap:8px;padding:4px 0;display:flex}.look-name input{border:none;border-bottom:1px solid var(--line);min-width:0;color:var(--ink);background:0 0;outline:none;flex:1;padding:2px 0}.look-name input:focus{border-bottom-color:var(--ink)}.look-name button:disabled{opacity:.35;cursor:default}.live-sub{margin:0 0 4px}.present{top:24px;left:var(--rail);right:var(--panel);text-align:center;pointer-events:none;padding:0 32px}.preset-name{letter-spacing:.5em;text-indent:.5em;font-size:12px}.idea{color:var(--dim);letter-spacing:.03em;max-width:520px;margin:8px auto 0;font-style:italic}.status{color:var(--dim);letter-spacing:.04em;margin-top:8px}.inspector{top:0;right:0;bottom:var(--bar);width:var(--panel);border-left:1px solid var(--line);flex-direction:column;display:flex}.tabs{border-bottom:1px solid var(--line);padding:20px 18px 0;display:flex}.tabs button{letter-spacing:.13em;white-space:nowrap;border-bottom:1px solid #0000;flex:1;margin-bottom:-1px;padding:8px 0 10px;font-size:10.5px}.tabs button.on{color:var(--ink);border-bottom-color:var(--ink)}.panel{scrollbar-width:thin;scrollbar-color:#2a2a2a transparent;flex:1;padding:4px 18px 22px;overflow-y:auto}.panel .row{grid-template-columns:88px 1fr 60px}.panel .opts{margin:5px 0}.panel .opts>.lbl{width:88px;margin-right:6px}.panel .opts button{letter-spacing:.1em;font-size:10.5px}.panel .meta{font-size:11.5px}.panel .meta.live{color:var(--faint);font-variant-numeric:tabular-nums}button.link.act{text-underline-offset:3px;font-size:12.5px}label.link{color:var(--ink);cursor:pointer;text-decoration:underline}.lib{padding-bottom:8px}.section{border-top:1px solid var(--glass-line);padding:12px 0 8px}.section:first-of-type{border-top:none}.section summary{cursor:pointer;color:var(--ink);text-transform:uppercase;letter-spacing:.24em;margin-bottom:8px;font-size:10.5px;list-style:none}.section summary::-webkit-details-marker{display:none}.section summary:before{content:"+";width:14px;color:var(--faint);display:inline-block}.section[open] summary:before{content:"–"}.swatch{cursor:pointer;border-radius:50%;align-self:center;width:15px;height:15px;padding:0;display:inline-block;position:relative;box-shadow:inset 0 0 0 1px #ffffff1f}.swatch.on{outline:1px solid var(--ink);outline-offset:3px}.palettes{align-items:center;gap:8px 11px}.swatch.custom{box-shadow:inset 0 0 0 1px #ffffff1f, 0 0 0 1px var(--faint)}.swatch.custom input{opacity:0;cursor:pointer;border:none;width:100%;height:100%;padding:0;position:absolute;inset:0}.bar{left:var(--rail);height:var(--bar);border-top:1px solid var(--line);align-items:center;gap:22px;padding:0 20px;display:flex;bottom:0;right:0}.bar .play{min-width:66px;color:var(--ink);align-items:baseline;display:flex}.bar .glyph{letter-spacing:0;width:20px;font-size:8px}.bar .opts{flex-wrap:nowrap}.bar-time{flex:1;min-width:60px}.clock{font-variant-numeric:tabular-nums;letter-spacing:.1em;min-width:104px;color:var(--ink);white-space:nowrap}.clock span{color:var(--dim)}.bar-end{align-items:center;gap:16px;display:flex}.bar-end button{white-space:nowrap;font-size:10.5px}.bar-end button.on{color:var(--ink)}.bar-end button:disabled{opacity:.3;cursor:default}.bar-end .icon{color:var(--ink);place-items:center;display:grid}.only-narrow{display:none}.reveal{right:var(--edge);color:var(--faint);opacity:.6;position:absolute;bottom:22px}.reveal:hover{opacity:1}@media (width<=900px){.app.studio{--rail:0px;--panel:0px;--sheet:44vh;--bar:50px}.app.studio.no-panels{--sheet:0px}.rail{display:none}.app.studio .stage{bottom:calc(var(--bar) + var(--sheet))}.app.studio .stage.framed{padding:14px}.inspector{width:auto;height:var(--sheet);border-left:none;border-top:1px solid var(--line);top:auto;left:0}.tabs{padding:4px 12px 0;overflow-x:auto}.tabs button{padding:8px 9px 9px}.panel{padding:2px 14px 16px}.present{padding:0 14px;top:12px}.present .idea{display:none}.bar{gap:12px;padding:0 12px}.bar .speeds,.bar .clock span,.bar-end .wide{display:none}.clock{min-width:0}.only-narrow{display:initial}}.fatal{z-index:10;text-align:center;background:#000;place-content:center;justify-items:center;gap:4px;padding:24px;font-size:12px;line-height:1.6;display:grid;position:fixed;inset:0}.fatal p{max-width:520px;margin:0}.fatal img{max-width:100%;max-height:62vh;margin-bottom:16px}.fatal-name{letter-spacing:var(--track);text-transform:uppercase;font-size:11px;margin-bottom:20px!important}.fatal-why{color:var(--dim);font-size:11px}.import{background:var(--glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--glass-line);border-radius:10px;width:min(440px,100% - 32px);padding:10px 14px;font-size:11px;position:absolute;bottom:150px;left:50%;transform:translate(-50%)}.import-head{justify-content:space-between;align-items:center;gap:8px;display:flex}.import-head span{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.import .bar{background:var(--line);height:1px;margin:9px 0 6px;overflow:hidden}.import .bar div{background:var(--ink);height:100%;transition:width .15s linear}.import-stage{color:var(--dim);font-variant-numeric:tabular-nums}.alert{background:var(--glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--accent);border-radius:10px;align-items:flex-start;gap:12px;max-width:min(560px,100% - 32px);padding:9px 12px;font-size:11px;display:flex;position:absolute;top:90px;left:50%;transform:translate(-50%)}.alert.error{border-color:#ff5a4a}.alert button{letter-spacing:0;font-size:15px;line-height:1}.dropzone{border:1px dashed var(--ink);pointer-events:none;text-transform:uppercase;letter-spacing:.3em;background:#0000008c;place-content:center;font-size:11px;display:grid;position:absolute;inset:0}body.shot .ui,body.shot .reveal,body.shot .import,body.shot .alert,body.shot .v-loading{display:none}body.shot .app.studio .stage{bottom:0;left:0;right:0}.app.viewer{font-size:13px}.app.light,.app.light .viewport{background:#f5f2ed}.app.quiet .ui{opacity:0;pointer-events:none}.app .ui{transition:opacity 1.2s}.v-masthead{top:32px;left:var(--edge);pointer-events:none;max-width:340px}.v-masthead h1{letter-spacing:.62em;margin:0 0 12px;font-size:15px;font-weight:400}.v-masthead p{margin:0;line-height:1.55}.v-line{color:var(--ink)}.v-by{color:var(--dim)}.v-corner{top:30px;right:var(--edge);align-items:center;gap:22px;display:flex}.v-corner button{text-transform:none;letter-spacing:.04em;color:var(--dim)}.v-corner button.on,.v-corner button:hover{color:var(--ink)}.v-corner .icon{color:var(--ink);place-items:center;display:grid}.v-bottom{left:var(--edge);right:var(--edge);flex-direction:column;align-items:center;gap:14px;display:flex;bottom:30px}.v-sentence{min-height:1.5em;color:var(--dim);letter-spacing:.01em;text-align:center;max-width:560px;margin:0;font-style:italic}.v-time{width:min(720px,100%)}.v-lenses{flex-wrap:wrap;justify-content:center;gap:6px 30px;display:flex}.v-lenses button{text-transform:none;letter-spacing:.06em;color:var(--dim);border-bottom:1px solid #0000;padding:4px 0 5px;font-size:13px}.v-lenses button.on{color:var(--ink);border-bottom-color:var(--ink)}.v-lenses button.sit{margin-left:10px}.v-lenses button:disabled{opacity:.35;cursor:default}.v-sit{flex-direction:column;align-items:center;gap:8px;display:flex}.v-sit .v-sentence{color:var(--ink);font-style:normal}.v-sit-actions{flex-wrap:wrap;justify-content:center;gap:22px;margin:0;display:flex}.v-sit-actions button{text-transform:none;letter-spacing:.04em;color:var(--dim);border-bottom:1px solid var(--line);padding-bottom:2px}.v-sit-actions button:first-child{color:var(--ink);border-bottom-color:var(--ink)}.v-hint{white-space:nowrap;color:var(--dim);letter-spacing:.06em;pointer-events:none;opacity:0;margin:0;transition:opacity 1.5s;bottom:150px;left:50%;transform:translate(-50%)}.v-hint.show{opacity:1}.app.quiet .v-hint{opacity:0}@media (width<=760px){.v-masthead{top:18px}.v-masthead .v-by{display:none}.v-corner{top:18px}.v-bottom{gap:12px;bottom:18px}.v-lenses{gap:6px 20px}.v-lenses button{padding:8px 0}}.about{z-index:20;-webkit-backdrop-filter:blur(12px);color:#ecebe8;background:#000000e0;font:15px/1.65 ui-serif,Georgia,Times New Roman,serif;position:fixed;inset:0;overflow-y:auto}.about[hidden]{display:none}.about-inner{max-width:620px;margin:0 auto;padding:72px 24px 96px}.about h2{letter-spacing:.62em;margin:0 0 28px;font:400 15px/1 ui-sans-serif,system-ui,sans-serif}.about h3{letter-spacing:.18em;text-transform:uppercase;color:#9b9890;margin:36px 0 10px;font:400 12px/1.4 ui-sans-serif,system-ui,sans-serif}.about p,.about li{color:#d8d6d1}.about dl{margin:0}.about dt{color:#ecebe8;margin-top:14px}.about dd{color:#b5b2ab;margin:2px 0 0}.about a{color:inherit}.about button{letter-spacing:.18em;color:#9b9890;font:400 12px/1 ui-sans-serif,system-ui,sans-serif}.about button:hover{color:#ecebe8}.about .about-close{top:30px;right:var(--edge);position:fixed}.about .about-studio{text-transform:uppercase;text-underline-offset:4px;text-decoration:underline}.about small{color:#9b9890}.camera-on{z-index:5;letter-spacing:.12em;text-transform:uppercase;color:var(--ink);text-shadow:var(--halo);pointer-events:none;font-size:11px;position:absolute;top:12px;left:50%;transform:translate(-50%)}.camera-on span{color:#ff4a3d}.live-sub{flex-direction:column;gap:4px;max-width:240px;display:flex}.live-sub .meta{text-transform:none;letter-spacing:.02em;margin:0}.live-sub .warn{color:#ffb08a}.live-sub .opts button:disabled{opacity:.5;cursor:default}.v-loading{pointer-events:none;place-items:center;display:grid;position:absolute;inset:0}.v-loading span{background:#ecebe8;border-radius:50%;width:5px;height:5px;animation:2.6s ease-in-out infinite v-breathe;box-shadow:0 0 14px 2px #ffd6aa80}@keyframes v-breathe{0%,to{opacity:.2;transform:scale(.8)}50%{opacity:1;transform:scale(1.3)}}@media (prefers-reduced-motion:reduce){.app .ui,.v-hint{transition:none}.v-loading span{opacity:.8;animation:none}} diff --git a/v4d-next/assets/index-D43qSr3Y.js b/v4d-next/assets/index-D43qSr3Y.js new file mode 100644 index 0000000..10e9186 --- /dev/null +++ b/v4d-next/assets/index-D43qSr3Y.js @@ -0,0 +1,681 @@ +import{n as e,r as t,t as n}from"./rolldown-runtime-XKyaHtl9.js";import{A as r,B as i,C as a,D as o,E as s,F as c,G as l,H as u,I as d,L as f,M as p,N as m,O as h,P as g,R as _,S as v,T as y,U as b,V as x,W as S,_ as C,a as w,b as T,c as E,d as ee,f as D,g as te,h as ne,i as re,j as O,k as ie,l as ae,m as oe,n as se,o as ce,p as k,r as A,s as le,t as ue,u as de,v as fe,w as pe,x as me,y as he,z as ge}from"./store-BW4Lw9fM.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var _e=n((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=typeof setTimeout==`function`?setTimeout:null,_=typeof clearTimeout==`function`?clearTimeout:null,v=typeof setImmediate<`u`?setImmediate:null;typeof navigator<`u`&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function b(e){if(h=!1,y(e),!m){if(n(c)!==null)m=!0,O(x);else{var t=n(l);t!==null&&ie(b,t.startTime-e)}}}function x(t,i){m=!1,h&&(h=!1,_(w),w=-1),p=!0;var a=f;try{for(y(i),d=n(c);d!==null&&(!(d.expirationTime>i)||t&&!ee());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=i);i=e.unstable_now(),typeof s==`function`?d.callback=s:d===n(c)&&r(c),y(i)}else r(c);d=n(c)}if(d!==null)var u=!0;else{var g=n(l);g!==null&&ie(b,g.startTime-i),u=!1}return u}finally{d=null,f=a,p=!1}}var S=!1,C=null,w=-1,T=5,E=-1;function ee(){return!(e.unstable_now()-Ee||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(_(w),w=-1):h=!0,ie(b,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,O(x))),r},e.unstable_shouldYield=ee,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),ve=n(((e,t)=>{t.exports=_e()})),ye=n((e=>{var t=l(),n=ve();function r(e){for(var t=`https://reactjs.org/docs/error-decoder.html?invariant=`+e,n=1;nt}return!1}function _(e,t,n,r,i,a,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=o}var v={};`children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style`.split(` `).forEach(function(e){v[e]=new _(e,0,!1,e,null,!1,!1)}),[[`acceptCharset`,`accept-charset`],[`className`,`class`],[`htmlFor`,`for`],[`httpEquiv`,`http-equiv`]].forEach(function(e){var t=e[0];v[t]=new _(t,1,!1,e[1],null,!1,!1)}),[`contentEditable`,`draggable`,`spellCheck`,`value`].forEach(function(e){v[e]=new _(e,2,!1,e.toLowerCase(),null,!1,!1)}),[`autoReverse`,`externalResourcesRequired`,`focusable`,`preserveAlpha`].forEach(function(e){v[e]=new _(e,2,!1,e,null,!1,!1)}),`allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope`.split(` `).forEach(function(e){v[e]=new _(e,3,!1,e.toLowerCase(),null,!1,!1)}),[`checked`,`multiple`,`muted`,`selected`].forEach(function(e){v[e]=new _(e,3,!0,e,null,!1,!1)}),[`capture`,`download`].forEach(function(e){v[e]=new _(e,4,!1,e,null,!1,!1)}),[`cols`,`rows`,`size`,`span`].forEach(function(e){v[e]=new _(e,6,!1,e,null,!1,!1)}),[`rowSpan`,`start`].forEach(function(e){v[e]=new _(e,5,!1,e.toLowerCase(),null,!1,!1)});var y=/[\-:]([a-z])/g;function b(e){return e[1].toUpperCase()}`accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height`.split(` `).forEach(function(e){var t=e.replace(y,b);v[t]=new _(t,1,!1,e,null,!1,!1)}),`xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type`.split(` `).forEach(function(e){var t=e.replace(y,b);v[t]=new _(t,1,!1,e,`http://www.w3.org/1999/xlink`,!1,!1)}),[`xml:base`,`xml:lang`,`xml:space`].forEach(function(e){var t=e.replace(y,b);v[t]=new _(t,1,!1,e,`http://www.w3.org/XML/1998/namespace`,!1,!1)}),[`tabIndex`,`crossOrigin`].forEach(function(e){v[e]=new _(e,1,!1,e.toLowerCase(),null,!1,!1)}),v.xlinkHref=new _(`xlinkHref`,1,!1,`xlink:href`,`http://www.w3.org/1999/xlink`,!0,!1),[`src`,`href`,`action`,`formAction`].forEach(function(e){v[e]=new _(e,1,!1,e.toLowerCase(),null,!0,!0)});function x(e,t,n,r){var i=v.hasOwnProperty(t)?v[t]:null;(i===null?r||!(2s||i[o]!==a[s]){var c=` +`+i[o].replace(` at new `,` at `);return e.displayName&&c.includes(``)&&(c=c.replace(``,e.displayName)),c}while(1<=o&&0<=s);break}}}finally{ue=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:``)?le(e):``}function fe(e){switch(e.tag){case 5:return le(e.type);case 16:return le(`Lazy`);case 13:return le(`Suspense`);case 19:return le(`SuspenseList`);case 0:case 2:case 15:return e=de(e.type,!1),e;case 11:return e=de(e.type.render,!1),e;case 1:return e=de(e.type,!0),e;default:return``}}function pe(e){if(e==null)return null;if(typeof e==`function`)return e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case T:return`Fragment`;case w:return`Portal`;case ee:return`Profiler`;case E:return`StrictMode`;case re:return`Suspense`;case O:return`SuspenseList`}if(typeof e==`object`)switch(e.$$typeof){case te:return(e.displayName||`Context`)+`.Consumer`;case D:return(e._context.displayName||`Context`)+`.Provider`;case ne:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case ie:return t=e.displayName||null,t===null?pe(e.type)||`Memo`:t;case ae:t=e._payload,e=e._init;try{return pe(e(t))}catch{}}return null}function me(e){var t=e.type;switch(e.tag){case 24:return`Cache`;case 9:return(t.displayName||`Context`)+`.Consumer`;case 10:return(t._context.displayName||`Context`)+`.Provider`;case 18:return`DehydratedFragment`;case 11:return e=t.render,e=e.displayName||e.name||``,t.displayName||(e===``?`ForwardRef`:`ForwardRef(`+e+`)`);case 7:return`Fragment`;case 5:return t;case 4:return`Portal`;case 3:return`Root`;case 6:return`Text`;case 16:return pe(t);case 8:return t===E?`StrictMode`:`Mode`;case 22:return`Offscreen`;case 12:return`Profiler`;case 21:return`Scope`;case 13:return`Suspense`;case 19:return`SuspenseList`;case 25:return`TracingMarker`;case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t==`function`)return t.displayName||t.name||null;if(typeof t==`string`)return t}return null}function he(e){switch(typeof e){case`boolean`:case`number`:case`string`:case`undefined`:return e;case`object`:return e;default:return``}}function ge(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()===`input`&&(t===`checkbox`||t===`radio`)}function _e(e){var t=ge(e)?`checked`:`value`,n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=``+e[t];if(!e.hasOwnProperty(t)&&n!==void 0&&typeof n.get==`function`&&typeof n.set==`function`){var i=n.get,a=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(e){r=``+e,a.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=``+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ye(e){e._valueTracker||=_e(e)}function be(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r=``;return e&&(r=ge(e)?e.checked?`true`:`false`:e.value),e=r,e!==n&&(t.setValue(e),!0)}function xe(e){if(e||=typeof document<`u`?document:void 0,e===void 0)return null;try{return e.activeElement||e.body}catch{return e.body}}function j(e,t){var n=t.checked;return k({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Se(e,t){var n=t.defaultValue==null?``:t.defaultValue,r=t.checked==null?t.defaultChecked:t.checked;n=he(t.value==null?n:t.value),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type===`checkbox`||t.type===`radio`?t.checked!=null:t.value!=null}}function Ce(e,t){t=t.checked,t!=null&&x(e,`checked`,t,!1)}function we(e,t){Ce(e,t);var n=he(t.value),r=t.type;if(n!=null)r===`number`?(n===0&&e.value===``||e.value!=n)&&(e.value=``+n):e.value!==``+n&&(e.value=``+n);else if(r===`submit`||r===`reset`){e.removeAttribute(`value`);return}t.hasOwnProperty(`value`)?Ee(e,t.type,n):t.hasOwnProperty(`defaultValue`)&&Ee(e,t.type,he(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Te(e,t,n){if(t.hasOwnProperty(`value`)||t.hasOwnProperty(`defaultValue`)){var r=t.type;if(!(r!==`submit`&&r!==`reset`||t.value!==void 0&&t.value!==null))return;t=``+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==``&&(e.name=``),e.defaultChecked=!!e._wrapperState.initialChecked,n!==``&&(e.name=n)}function Ee(e,t,n){(t!==`number`||xe(e.ownerDocument)!==e)&&(n==null?e.defaultValue=``+e._wrapperState.initialValue:e.defaultValue!==``+n&&(e.defaultValue=``+n))}var M=Array.isArray;function De(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i`+t.valueOf().toString()+``,t=Pe.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ie(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Le={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Re=[`Webkit`,`ms`,`Moz`,`O`];Object.keys(Le).forEach(function(e){Re.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Le[t]=Le[e]})});function ze(e,t,n){return t==null||typeof t==`boolean`||t===``?``:n||typeof t!=`number`||t===0||Le.hasOwnProperty(e)&&Le[e]?(``+t).trim():t+`px`}function Be(e,t){for(var n in e=e.style,t)if(t.hasOwnProperty(n)){var r=n.indexOf(`--`)===0,i=ze(n,t[n],r);n===`float`&&(n=`cssFloat`),r?e.setProperty(n,i):e[n]=i}}var Ve=k({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function He(e,t){if(t){if(Ve[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(r(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(r(60));if(typeof t.dangerouslySetInnerHTML!=`object`||!(`__html`in t.dangerouslySetInnerHTML))throw Error(r(61))}if(t.style!=null&&typeof t.style!=`object`)throw Error(r(62))}}function Ue(e,t){if(e.indexOf(`-`)===-1)return typeof t.is==`string`;switch(e){case`annotation-xml`:case`color-profile`:case`font-face`:case`font-face-src`:case`font-face-uri`:case`font-face-format`:case`font-face-name`:case`missing-glyph`:return!1;default:return!0}}var We=null;function Ge(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ke=null,qe=null,Je=null;function Ye(e){if(e=Bi(e)){if(typeof Ke!=`function`)throw Error(r(280));var t=e.stateNode;t&&(t=Hi(t),Ke(e.stateNode,e.type,t))}}function Xe(e){qe?Je?Je.push(e):Je=[e]:qe=e}function Ze(){if(qe){var e=qe,t=Je;if(Je=qe=null,Ye(e),t)for(e=0;e>>=0,e===0?32:31-(Mt(e)/Nt|0)|0}var Ft=64,F=4194304;function It(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function I(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,i=e.suspendedLanes,a=e.pingedLanes,o=n&268435455;if(o!==0){var s=o&~i;s===0?(a&=o,a!==0&&(r=It(a))):r=It(s)}else o=n&~i,o===0?a!==0&&(r=It(a)):r=It(o);if(r===0)return 0;if(t!==0&&t!==r&&(t&i)===0&&(i=r&-r,a=t&-t,i>=a||i===16&&a&4194240))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Vt(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-jt(t),e[t]=n}function Ht(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=er),rr=` `,ir=!1;function ar(e,t){switch(e){case`keyup`:return Qn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function or(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var sr=!1;function cr(e,t){switch(e){case`compositionend`:return or(t);case`keypress`:return t.which===32?(ir=!0,rr):null;case`textInput`:return e=t.data,e===rr&&ir?null:e;default:return null}}function lr(e,t){if(sr)return e===`compositionend`||!$n&&ar(e,t)?(e=En(),Tn=wn=Cn=null,sr=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=jr(n)}}function Nr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Nr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Pr(){for(var e=window,t=xe();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=xe(e.document)}return t}function Fr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}function Ir(e){var t=Pr(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Nr(n.ownerDocument.documentElement,n)){if(r!==null&&Fr(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),`selectionStart`in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=n.textContent.length,a=Math.min(r.start,i);r=r.end===void 0?a:Math.min(r.end,i),!e.extend&&a>r&&(i=r,r=a,a=i),i=Mr(n,a);var o=Mr(n,r);i&&o&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),a>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus==`function`&&n.focus(),n=0;n=document.documentMode,Rr=null,zr=null,Br=null,Vr=!1;function Hr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Vr||Rr==null||Rr!==xe(r)||(r=Rr,`selectionStart`in r&&Fr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Br&&Ar(Br,r)||(Br=r,r=pi(zr,`onSelect`),0Wi||(e.current=Ui[Wi],Ui[Wi]=null,Wi--)}function W(e,t){Wi++,Ui[Wi]=e.current,e.current=t}var Ki={},qi=Gi(Ki),Ji=Gi(!1),Yi=Ki;function Xi(e,t){var n=e.type.contextTypes;if(!n)return Ki;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},a;for(a in n)i[a]=t[a];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function Zi(e){return e=e.childContextTypes,e!=null}function Qi(){U(Ji),U(qi)}function $i(e,t,n){if(qi.current!==Ki)throw Error(r(168));W(qi,t),W(Ji,n)}function ea(e,t,n){var i=e.stateNode;if(t=t.childContextTypes,typeof i.getChildContext!=`function`)return n;for(var a in i=i.getChildContext(),i)if(!(a in t))throw Error(r(108,me(e)||`Unknown`,a));return k({},n,i)}function ta(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ki,Yi=qi.current,W(qi,e),W(Ji,Ji.current),!0}function na(e,t,n){var i=e.stateNode;if(!i)throw Error(r(169));n?(e=ea(e,t,Yi),i.__reactInternalMemoizedMergedChildContext=e,U(Ji),U(qi),W(qi,e)):U(Ji),W(Ji,n)}var ra=null,ia=!1,aa=!1;function oa(e){ra===null?ra=[e]:ra.push(e)}function sa(e){ia=!0,oa(e)}function ca(){if(!aa&&ra!==null){aa=!0;var e=0,t=R;try{var n=ra;for(R=1;e>=o,i-=o,ga=1<<32-jt(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(r,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(r,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(r,d),G&&va(r,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),G&&va(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return G&&va(a,g),u}for(h=i(a,h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),G&&va(a,g),u}function _(e,r,i,o){if(typeof i==`object`&&i&&i.type===T&&i.key===null&&(i=i.props.children),typeof i==`object`&&i){switch(i.$$typeof){case C:a:{for(var c=i.key,l=r;l!==null;){if(l.key===c){if(c=i.type,c===T){if(l.tag===7){n(e,l.sibling),r=a(l,i.props.children),r.return=e,e=r;break a}}else if(l.elementType===c||typeof c==`object`&&c&&c.$$typeof===ae&&La(c)===l.type){n(e,l.sibling),r=a(l,i.props),r.ref=Fa(e,l,i),r.return=e,e=r;break a}n(e,l);break}t(e,l),l=l.sibling}i.type===T?(r=Zl(i.props.children,e.mode,o,i.key),r.return=e,e=r):(o=Xl(i.type,i.key,i.props,null,e.mode,o),o.ref=Fa(e,r,i),o.return=e,e=o)}return s(e);case w:a:{for(l=i.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===i.containerInfo&&r.stateNode.implementation===i.implementation){n(e,r.sibling),r=a(r,i.children||[]),r.return=e,e=r;break a}n(e,r);break}t(e,r),r=r.sibling}r=eu(i,e.mode,o),r.return=e,e=r}return s(e);case ae:return l=i._init,_(e,r,l(i._payload),o)}if(M(i))return h(e,r,i,o);if(ce(i))return g(e,r,i,o);Ia(e,i)}return typeof i==`string`&&i!==``||typeof i==`number`?(i=``+i,r!==null&&r.tag===6?(n(e,r.sibling),r=a(r,i),r.return=e,e=r):(n(e,r),r=$l(i,e.mode,o),r.return=e,e=r),s(e)):n(e,r)}return _}var za=Ra(!0),Ba=Ra(!1),Va=Gi(null),Ha=null,Ua=null,Wa=null;function Ga(){Wa=Ua=Ha=null}function Ka(e){var t=Va.current;U(Va),e._currentValue=t}function qa(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)===t?r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t):(e.childLanes|=t,r!==null&&(r.childLanes|=t)),e===n)break;e=e.return}}function Ja(e,t){Ha=e,Wa=Ua=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Fs=!0),e.firstContext=null)}function Ya(e){var t=e._currentValue;if(Wa!==e){if(e={context:e,memoizedValue:t,next:null},Ua===null){if(Ha===null)throw Error(r(308));Ua=e,Ha.dependencies={lanes:0,firstContext:e}}else Ua=Ua.next=e}return t}var Xa=null;function Za(e){Xa===null?Xa=[e]:Xa.push(e)}function Qa(e,t,n,r){var i=t.interleaved;return i===null?(n.next=n,Za(t)):(n.next=i.next,i.next=n),t.interleaved=n,$a(e,r)}function $a(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var eo=!1;function to(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function no(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function ro(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function io(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,X&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,$a(e,n)}return i=r.interleaved,i===null?(t.next=t,Za(r)):(t.next=i.next,i.next=t),r.interleaved=t,$a(e,n)}function ao(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194240)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ut(e,n)}}function oo(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,effects:r.effects},e.updateQueue=n}else e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function so(e,t,n,r){var i=e.updateQueue;eo=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane,p=s.eventTime;if((r&f)===f){u!==null&&(u=u.next={eventTime:p,lane:0,tag:s.tag,payload:s.payload,callback:s.callback,next:null});a:{var m=e,h=s;switch(f=t,p=n,h.tag){case 1:if(m=h.payload,typeof m==`function`){d=m.call(p,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m==`function`?m.call(p,d,f):m,f==null)break a;d=k({},d,f);break a;case 2:eo=!0}}s.callback!==null&&s.lane!==0&&(e.flags|=64,f=i.effects,f===null?i.effects=[s]:f.push(s))}else p={eventTime:p,lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;f=s,s=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(1);if(u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,t=i.shared.interleaved,t!==null){i=t;do o|=i.lane,i=i.next;while(i!==t)}else a===null&&(i.shared.lanes=0);Yc|=o,e.lanes=o,e.memoizedState=d}}function co(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Co.transition;Co.transition={};try{e(!1),t()}finally{R=n,Co.transition=r}}function cs(){return Fo().memoizedState}function ls(e,t,n){var r=ml(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},ds(e))fs(t,n);else if(n=Qa(e,t,n,r),n!==null){var i=pl();hl(n,e,r,i),ps(n,t,r)}}function us(e,t,n){var r=ml(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(ds(e))fs(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,kr(s,o)){var c=t.interleaved;c===null?(i.next=i,Za(t)):(i.next=c.next,c.next=i),t.interleaved=i;return}}catch{}n=Qa(e,t,i,r),n!==null&&(i=pl(),hl(n,e,r,i),ps(n,t,r))}}function ds(e){var t=e.alternate;return e===q||t!==null&&t===q}function fs(e,t){Do=Eo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function ps(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ut(e,n)}}var ms={readContext:Ya,useCallback:Ao,useContext:Ao,useEffect:Ao,useImperativeHandle:Ao,useInsertionEffect:Ao,useLayoutEffect:Ao,useMemo:Ao,useReducer:Ao,useRef:Ao,useState:Ao,useDebugValue:Ao,useDeferredValue:Ao,useTransition:Ao,useMutableSource:Ao,useSyncExternalStore:Ao,useId:Ao,unstable_isNewReconciler:!1},hs={readContext:Ya,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:Ya,useEffect:Zo,useImperativeHandle:function(e,t,n){return n=n==null?null:n.concat([e]),Yo(4194308,4,ts.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Yo(4194308,4,e,t)},useInsertionEffect:function(e,t){return Yo(4,2,e,t)},useMemo:function(e,t){var n=Po();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Po();return t=n===void 0?t:n(t),r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=ls.bind(null,q,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:Ko,useDebugValue:rs,useDeferredValue:function(e){return Po().memoizedState=e},useTransition:function(){var e=Ko(!1),t=e[0];return e=ss.bind(null,e[1]),Po().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var i=q,a=Po();if(G){if(n===void 0)throw Error(r(407));n=n()}else{if(n=t(),Wc===null)throw Error(r(349));wo&30||Vo(i,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,Zo(Uo.bind(null,i,o,e),[e]),i.flags|=2048,qo(9,Ho.bind(null,i,o,n,t),void 0,null),n},useId:function(){var e=Po(),t=Wc.identifierPrefix;if(G){var n=_a,r=ga;n=(r&~(1<<32-jt(r)-1)).toString(32)+n,t=`:`+t+`R`+n,n=Oo++,0<\/script>`,e=e.removeChild(e.firstChild)):typeof i.is==`string`?e=c.createElement(n,{is:i.is}):(e=c.createElement(n),n===`select`&&(c=e,i.multiple?c.multiple=!0:i.size&&(c.size=i.size))):e=c.createElementNS(e,n),e[Ni]=t,e[Pi]=i,ac(e,t,!1,!1),t.stateNode=e;a:{switch(c=Ue(n,i),n){case`dialog`:H(`cancel`,e),H(`close`,e),o=i;break;case`iframe`:case`object`:case`embed`:H(`load`,e),o=i;break;case`video`:case`audio`:for(o=0;otl&&(t.flags|=128,i=!0,cc(s,!1),t.lanes=4194304)}}else{if(!i){if(e=yo(c),e!==null){if(t.flags|=128,i=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),cc(s,!0),s.tail===null&&s.tailMode===`hidden`&&!c.alternate&&!G)return lc(t),null}else 2*P()-s.renderingStartTime>tl&&n!==1073741824&&(t.flags|=128,i=!0,cc(s,!1),t.lanes=4194304)}s.isBackwards?(c.sibling=t.child,t.child=c):(n=s.last,n===null?t.child=c:n.sibling=c,s.last=c)}return s.tail===null?(lc(t),null):(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=P(),t.sibling=null,n=K.current,W(K,i?n&1|2:n&1),t);case 22:case 23:return Tl(),i=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==i&&(t.flags|=8192),i&&t.mode&1?Kc&1073741824&&(lc(t),t.subtreeFlags&6&&(t.flags|=8192)):lc(t),null;case 24:return null;case 25:return null}throw Error(r(156,t.tag))}function dc(e,t){switch(xa(t),t.tag){case 1:return Zi(t.type)&&Qi(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return go(),U(Ji),U(qi),xo(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return vo(t),null;case 13:if(U(K),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(r(340));Ma()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return U(K),null;case 4:return go(),null;case 10:return Ka(t.type._context),null;case 22:case 23:return Tl(),null;case 24:return null;default:return null}}var fc=!1,pc=!1,mc=typeof WeakSet==`function`?WeakSet:Set,Y=null;function hc(e,t){var n=e.ref;if(n!==null){if(typeof n==`function`)try{n(null)}catch(n){$(e,t,n)}else n.current=null}}function gc(e,t,n){try{n()}catch(n){$(e,t,n)}}var _c=!1;function vc(e,t){if(xi=gn,e=Pr(),Fr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var i=n.getSelection&&n.getSelection();if(i&&i.rangeCount!==0){n=i.anchorNode;var a=i.anchorOffset,o=i.focusNode;i=i.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||i!==0&&f.nodeType!==3||(l=s+i),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===i&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Si={focusedElem:e,selectionRange:n},gn=!1,Y=t;Y!==null;)if(t=Y,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,Y=e;else for(;Y!==null;){t=Y;try{var h=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(h!==null){var g=h.memoizedProps,_=h.memoizedState,v=t.stateNode;v.__reactInternalSnapshotBeforeUpdate=v.getSnapshotBeforeUpdate(t.elementType===t.type?g:vs(t.type,g),_)}break;case 3:var y=t.stateNode.containerInfo;y.nodeType===1?y.textContent=``:y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(r(163))}}catch(e){$(t,t.return,e)}if(e=t.sibling,e!==null){e.return=t.return,Y=e;break}Y=t.return}return h=_c,_c=!1,h}function yc(e,t,n){var r=t.updateQueue;if(r=r===null?null:r.lastEffect,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var a=i.destroy;i.destroy=void 0,a!==void 0&&gc(t,n,a)}i=i.next}while(i!==r)}}function bc(e,t){if(t=t.updateQueue,t=t===null?null:t.lastEffect,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function xc(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t==`function`?t(e):t.current=e}}function Sc(e){var t=e.alternate;t!==null&&(e.alternate=null,Sc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Ni],delete t[Pi],delete t[Ii],delete t[Li],delete t[Ri])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Cc(e){return e.tag===5||e.tag===3||e.tag===4}function wc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Cc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Tc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=bi));else if(r!==4&&(e=e.child,e!==null))for(Tc(e,t,n),e=e.sibling;e!==null;)Tc(e,t,n),e=e.sibling}function Ec(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ec(e,t,n),e=e.sibling;e!==null;)Ec(e,t,n),e=e.sibling}var Dc=null,Oc=!1;function kc(e,t,n){for(n=n.child;n!==null;)Ac(e,t,n),n=n.sibling}function Ac(e,t,n){if(kt&&typeof kt.onCommitFiberUnmount==`function`)try{kt.onCommitFiberUnmount(Ot,n)}catch{}switch(n.tag){case 5:pc||hc(n,t);case 6:var r=Dc,i=Oc;Dc=null,kc(e,t,n),Dc=r,Oc=i,Dc!==null&&(Oc?(e=Dc,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Dc.removeChild(n.stateNode));break;case 18:Dc!==null&&(Oc?(e=Dc,n=n.stateNode,e.nodeType===8?ki(e.parentNode,n):e.nodeType===1&&ki(e,n),mn(e)):ki(Dc,n.stateNode));break;case 4:r=Dc,i=Oc,Dc=n.stateNode.containerInfo,Oc=!0,kc(e,t,n),Dc=r,Oc=i;break;case 0:case 11:case 14:case 15:if(!pc&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var a=i,o=a.destroy;a=a.tag,o!==void 0&&(a&2||a&4)&&gc(n,t,o),i=i.next}while(i!==r)}kc(e,t,n);break;case 1:if(!pc&&(hc(n,t),r=n.stateNode,typeof r.componentWillUnmount==`function`))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(e){$(n,t,e)}kc(e,t,n);break;case 21:kc(e,t,n);break;case 22:n.mode&1?(pc=(r=pc)||n.memoizedState!==null,kc(e,t,n),pc=r):kc(e,t,n);break;default:kc(e,t,n)}}function jc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new mc),t.forEach(function(t){var r=Hl.bind(null,e,t);n.has(t)||(n.add(t),t.then(r,r))})}}function Mc(e,t){var n=t.deletions;if(n!==null)for(var i=0;ia&&(a=s),i&=~o}if(i=a,i=P()-i,i=(120>i?120:480>i?480:1080>i?1080:1920>i?1920:3e3>i?3e3:4320>i?4320:1960*Bc(i/1960))-i,10e?16:e,sl===null)var i=!1;else{if(e=sl,sl=null,cl=0,X&6)throw Error(r(331));var a=X;for(X|=4,Y=e.current;Y!==null;){var o=Y,s=o.child;if(Y.flags&16){var c=o.deletions;if(c!==null){for(var l=0;lP()-el?El(e,0):Zc|=n),gl(e,t)}function Bl(e,t){t===0&&(e.mode&1?(t=F,F<<=1,!(F&130023424)&&(F=4194304)):t=1);var n=pl();e=$a(e,t),e!==null&&(Vt(e,t,n),gl(e,n))}function Vl(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Bl(e,n)}function Hl(e,t){var n=0;switch(e.tag){case 13:var i=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:i=e.stateNode;break;default:throw Error(r(314))}i!==null&&i.delete(t),Bl(e,n)}var Ul=function(e,t,n){if(e!==null){if(e.memoizedProps!==t.pendingProps||Ji.current)Fs=!0;else{if((e.lanes&n)===0&&!(t.flags&128))return Fs=!1,ic(e,t,n);Fs=!!(e.flags&131072)}}else Fs=!1,G&&t.flags&1048576&&ya(t,fa,t.index);switch(t.lanes=0,t.tag){case 2:var i=t.type;nc(e,t),e=t.pendingProps;var a=Xi(t,qi.current);Ja(t,n),a=Mo(null,t,i,e,a,n);var o=No();return t.flags|=1,typeof a==`object`&&a&&typeof a.render==`function`&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Zi(i)?(o=!0,ta(t)):o=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,to(t),a.updater=bs,t.stateNode=a,a._reactInternals=t,ws(t,i,e,n),t=Ws(null,t,i,!0,o,n)):(t.tag=0,G&&o&&ba(t),Is(null,t,a,n),t=t.child),t;case 16:i=t.elementType;a:{switch(nc(e,t),e=t.pendingProps,a=i._init,i=a(i._payload),t.type=i,a=t.tag=Jl(i),e=vs(i,e),a){case 0:t=Hs(null,t,i,e,n);break a;case 1:t=Us(null,t,i,e,n);break a;case 11:t=Ls(null,t,i,e,n);break a;case 14:t=Rs(null,t,i,vs(i.type,e),n);break a}throw Error(r(306,i,``))}return t;case 0:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:vs(i,a),Hs(e,t,i,a,n);case 1:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:vs(i,a),Us(e,t,i,a,n);case 3:a:{if(Gs(t),e===null)throw Error(r(387));i=t.pendingProps,o=t.memoizedState,a=o.element,no(e,t),so(t,i,null,n);var s=t.memoizedState;if(i=s.element,o.isDehydrated){if(o={element:i,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){a=Ts(Error(r(423)),t),t=Ks(e,t,i,n,a);break a}if(i!==a){a=Ts(Error(r(424)),t),t=Ks(e,t,i,n,a);break a}for(Ca=Ai(t.stateNode.containerInfo.firstChild),Sa=t,G=!0,wa=null,n=Ba(t,null,i,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling}else{if(Ma(),i===a){t=rc(e,t,n);break a}Is(e,t,i,n)}t=t.child}return t;case 5:return _o(t),e===null&&Oa(t),i=t.type,a=t.pendingProps,o=e===null?null:e.memoizedProps,s=a.children,Ci(i,a)?s=null:o!==null&&Ci(i,o)&&(t.flags|=32),Vs(e,t),Is(e,t,s,n),t.child;case 6:return e===null&&Oa(t),null;case 13:return Ys(e,t,n);case 4:return ho(t,t.stateNode.containerInfo),i=t.pendingProps,e===null?t.child=za(t,null,i,n):Is(e,t,i,n),t.child;case 11:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:vs(i,a),Ls(e,t,i,a,n);case 7:return Is(e,t,t.pendingProps,n),t.child;case 8:return Is(e,t,t.pendingProps.children,n),t.child;case 12:return Is(e,t,t.pendingProps.children,n),t.child;case 10:a:{if(i=t.type._context,a=t.pendingProps,o=t.memoizedProps,s=a.value,W(Va,i._currentValue),i._currentValue=s,o!==null){if(kr(o.value,s)){if(o.children===a.children&&!Ji.current){t=rc(e,t,n);break a}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var c=o.dependencies;if(c!==null){s=o.child;for(var l=c.firstContext;l!==null;){if(l.context===i){if(o.tag===1){l=ro(-1,n&-n),l.tag=2;var u=o.updateQueue;if(u!==null){u=u.shared;var d=u.pending;d===null?l.next=l:(l.next=d.next,d.next=l),u.pending=l}}o.lanes|=n,l=o.alternate,l!==null&&(l.lanes|=n),qa(o.return,n,t),c.lanes|=n;break}l=l.next}}else if(o.tag===10)s=o.type===t.type?null:o.child;else if(o.tag===18){if(s=o.return,s===null)throw Error(r(341));s.lanes|=n,c=s.alternate,c!==null&&(c.lanes|=n),qa(s,n,t),s=o.sibling}else s=o.child;if(s!==null)s.return=o;else for(s=o;s!==null;){if(s===t){s=null;break}if(o=s.sibling,o!==null){o.return=s.return,s=o;break}s=s.return}o=s}}Is(e,t,a.children,n),t=t.child}return t;case 9:return a=t.type,i=t.pendingProps.children,Ja(t,n),a=Ya(a),i=i(a),t.flags|=1,Is(e,t,i,n),t.child;case 14:return i=t.type,a=vs(i,t.pendingProps),a=vs(i.type,a),Rs(e,t,i,a,n);case 15:return zs(e,t,t.type,t.pendingProps,n);case 17:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:vs(i,a),nc(e,t),t.tag=1,Zi(i)?(e=!0,ta(t)):e=!1,Ja(t,n),Ss(t,i,a),ws(t,i,a,n),Ws(null,t,i,!0,e,n);case 19:return tc(e,t,n);case 22:return Bs(e,t,n)}throw Error(r(156,t.tag))};function Wl(e,t){return vt(e,t)}function Gl(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Kl(e,t,n,r){return new Gl(e,t,n,r)}function ql(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Jl(e){if(typeof e==`function`)return+!!ql(e);if(e!=null){if(e=e.$$typeof,e===ne)return 11;if(e===ie)return 14}return 2}function Yl(e,t){var n=e.alternate;return n===null?(n=Kl(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Xl(e,t,n,i,a,o){var s=2;if(i=e,typeof e==`function`)ql(e)&&(s=1);else if(typeof e==`string`)s=5;else a:switch(e){case T:return Zl(n.children,a,o,t);case E:s=8,a|=8;break;case ee:return e=Kl(12,n,t,a|2),e.elementType=ee,e.lanes=o,e;case re:return e=Kl(13,n,t,a),e.elementType=re,e.lanes=o,e;case O:return e=Kl(19,n,t,a),e.elementType=O,e.lanes=o,e;case oe:return Ql(n,a,o,t);default:if(typeof e==`object`&&e)switch(e.$$typeof){case D:s=10;break a;case te:s=9;break a;case ne:s=11;break a;case ie:s=14;break a;case ae:s=16,i=null;break a}throw Error(r(130,e==null?e:typeof e,``))}return t=Kl(s,n,t,a),t.elementType=e,t.type=i,t.lanes=o,t}function Zl(e,t,n,r){return e=Kl(7,e,r,t),e.lanes=n,e}function Ql(e,t,n,r){return e=Kl(22,e,r,t),e.elementType=oe,e.lanes=n,e.stateNode={isHidden:!1},e}function $l(e,t,n){return e=Kl(6,e,null,t),e.lanes=n,e}function eu(e,t,n){return t=Kl(4,e.children===null?[]:e.children,e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function tu(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Bt(0),this.expirationTimes=Bt(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Bt(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function nu(e,t,n,r,i,a,o,s,c){return e=new tu(e,t,n,s,c),t===1?(t=1,!0===a&&(t|=8)):t=0,a=Kl(3,null,null,t),e.current=a,a.stateNode=e,a.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},to(a),e}function ru(e,t,n){var r=3{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=ye()})),xe=n((e=>{var t=be();e.createRoot=t.createRoot,e.hydrateRoot=t.hydrateRoot})),j=t(l(),1),Se=xe(),Ce=[86,52,68,0],we=16,Te=16,Ee={u8:1,u16:2,u32:4,f32:4},M=class extends Error{},De=e=>Math.ceil(e/Te)*Te;function Oe(e,t,n,r){if(n===t)return 0;let i=Math.floor((e-t)/(n-t)*r+.5);return i<0?0:i>r?r:i}function ke(e,t){let n=t.byteLength/Ee[t.type];switch(t.type){case`u8`:return new Uint8Array(e,t.offset,n);case`u16`:return new Uint16Array(e,t.offset,n);case`u32`:return new Uint32Array(e,t.offset,n);case`f32`:return new Float32Array(e,t.offset,n)}}function Ae(e){let t,n=0,r;e instanceof Uint8Array?(e.byteOffset%Te===0&&e.buffer instanceof ArrayBuffer?(t=e.buffer,n=e.byteOffset):t=e.slice().buffer,r=e.byteLength):(t=e,r=e.byteLength);let i=new DataView(t,n,r);if(i.byteLengthi.byteLength)throw new M(`truncated header`);let s=new TextDecoder().decode(new Uint8Array(t,n+we,o)),c=JSON.parse(s),l={};for(let e of c.sections){if(e.offset%Te!==0)throw new M(`section ${e.name} is not 16-byte aligned`);if(e.offset+e.byteLength>i.byteLength)throw new M(`section ${e.name} is truncated`);l[e.name]=ke(t,{...e,offset:n+e.offset})}let u=(e,t)=>{let n=l[e];if(!n)throw new M(`missing section ${e}`);if(n.length!==c.pointCount*t)throw new M(`section ${e} has ${n.length} values, expected ${c.pointCount*t}`);return n},d={},f=new Set([`position`,`time`,`color`,`trackId`,`frameStart`,`observed`,`rawPosition`]);for(let e of c.sections)f.has(e.name)||(d[e.name]=new Uint8Array(t,n+e.offset,e.byteLength));let p={header:c,position:u(`position`,3),time:u(`time`,1),color:u(`color`,3),extra:d};if(l.trackId&&(p.trackId=u(`trackId`,1)),l.observed&&(p.observed=u(`observed`,1)),l.rawPosition){if(!(l.rawPosition instanceof Uint16Array))throw new M(`rawPosition must be u16`);p.rawPosition=u(`rawPosition`,3)}if(l.frameStart){let e=l.frameStart;if(e.length!==c.frameCount+1)throw new M(`frameStart length must be frameCount + 1`);p.frameStart=e}return p}function je(e,t){if(t instanceof Uint8Array)return`u8`;if(t instanceof Uint16Array)return`u16`;if(t instanceof Uint32Array)return`u32`;if(t instanceof Float32Array)return`f32`;throw new M(`unsupported array type for ${e}`)}function Me(e){let t=[[`position`,e.position,3],[`time`,e.time,1],[`color`,e.color,3]];e.trackId&&t.push([`trackId`,e.trackId,1]),e.frameStart&&t.push([`frameStart`,e.frameStart,1]),e.observed&&t.push([`observed`,e.observed,1]),e.rawPosition&&t.push([`rawPosition`,e.rawPosition,3]);let n=n=>{let r=n,i=[];for(let[e,n,a]of t)i.push({name:e,type:je(e,n),components:a,offset:r,byteLength:n.byteLength}),r=De(r+n.byteLength);for(let[t,n]of Object.entries(e.extra))i.push({name:t,type:`u8`,components:1,offset:r,byteLength:n.byteLength}),r=De(r+n.byteLength);return i},r=t=>new TextEncoder().encode(JSON.stringify({...e.header,sections:t})),i=De(we+r(n(0)).length+64),a=n(i),o=r(a);De(we+o.length)>i&&(i=De(we+o.length),a=n(i),o=r(a));let s=a[a.length-1],c=s?s.offset+s.byteLength:i,l=new Uint8Array(c),u=new DataView(l.buffer);l.set(Ce,0),u.setUint16(4,1,!0),u.setUint16(6,e.observed||e.rawPosition?1:0,!0),u.setUint32(8,o.length,!0),l.set(o,we);let d=[...t.map(([,e])=>e),...Object.values(e.extra)];return a.forEach((e,t)=>{let n=d[t];l.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength),e.offset)}),l}function Ne(e){let t=e.times.length;if(e.positions.length!==3*t||e.colors.length!==3*t)throw new M(`positions and colors must have 3 values per point`);if(e.trackIds&&e.trackIds.length!==t)throw new M(`trackIds must have 1 value per point`);if(e.observed&&e.observed.length!==t)throw new M(`observed must have 1 value per point`);if(e.rawPositions&&e.rawPositions.length!==3*t)throw new M(`rawPositions must have 3 values per point`);let n=1/0,r=-1/0;for(let i=0;ir&&(r=t)}let i=e.time??{start:t?n:0,end:t?r:0},a=e.bounds;if(!a){let n=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];for(let i of e.rawPositions?[e.positions,e.rawPositions]:[e.positions])for(let e=0;er[t]&&(r[t]=a)}a=t?{min:n,max:r}:{min:[0,0,0],max:[0,0,0]}}let o=null;for(let n=1;nt);n.sort((t,n)=>e.times[t]-e.times[n]||t-n),o=Uint32Array.from(n);break}let s=e=>o?o[e]:e,c=new Uint16Array(3*t),l=new Uint16Array(t),u=new Uint8Array(3*t),d=e.trackIds?new Uint32Array(t):void 0,f=e.observed?new Uint8Array(t):void 0,p=e.rawPositions?new Uint16Array(3*t):void 0;for(let n=0;n0?e.fps:0,h=0,g;if(m>0&&t>0){let n=t=>Math.round((e.times[s(t)]-i.start)*m);h=n(t-1)+1,g=new Uint32Array(h+1);let r=0;for(let e=0;e=128?0:255;if(!t)return r;for(let e=0;e=0&&r[n]!==0&&(r[n]=Math.min(r[n],Math.min(255,r[e]+1)))}let i=Uint8Array.from(r),a=new Uint8Array(n);for(let t=0;t=128?0:255;for(let e=n-1;e>=0;e--){let n=t[e];n>=0&&a[e]!==0&&(a[e]=Math.min(a[e],Math.min(255,a[n]+1))),a[e]=128&&t++;return e.length?t/e.length:1}function Le(e){return Math.round(255*Math.sqrt(Math.min(1,Math.max(0,e/4))))}function Re(e,t){let{header:n,frameStart:r,position:i}=e,a=n.pointCount,o=new Float32Array(a);if(!(i instanceof Uint16Array)||n.fps<=0)return o;let{min:s,max:c}=n.bounds,l=[0,1,2].map(e=>(c[e]-s[e])/65535),u=n.fps,d=r?Array.from({length:n.frameCount},(e,t)=>[r[t],r[t+1]]):[[0,a]],f=new Float32Array(3);for(let[e,n]of d){let r=new Float64Array(3),a=0;for(let o=e;o0)for(let e=0;e<3;e++)r[e]=r[e]/a;for(let a=e;a=0&&t[n]<0&&(o[n]=o[e])}return o}function ze(e,t){let n=e.observed?Fe(e.observed,t):null,r=t?Re(e,t):null;if(!n&&!r)return null;let i=e.header.pointCount,a=new Uint16Array(i+(i&1));for(let e=0;eo&&(o=n)}let s=o<1<<24?new Int32Array(o+1):null,c=s?null:new Map;for(let e=0;e+1{let r=new Worker(new URL(`/v4d-next/assets/synth.worker-D-Qhg7ac.js`,``+import.meta.url),{type:`module`});r.onmessage=i=>{r.terminate(),`error`in i.data?n(Error(i.data.error)):t({...i.data,label:e})},r.onerror=e=>{r.terminate(),n(Error(e.message))};let i=Ge?new URL(Ge,location.href).href:null;r.postMessage({kind:e,model:i})})}var Je={dancer:{file:`demo/dancer.v4d`,megabytes:34,note:`a dancer generated with Kling AI 4.0 and lifted by ReLift: not a capture of a real person`}},Ye=e=>!!e&&Object.hasOwn(Je,e),Xe=new Map;async function Ze(e,t){let n=Je[e],r=Xe.get(e);if(r)return{...r,note:n.note};let i=await fetch(`/v4d-next/${n.file}`);if(!i.ok||!i.body)throw Error(`${n.file}: ${i.status}`);let a=Number(i.headers.get(`content-length`))||n.megabytes*1e6,o=[],s=0;for(let e=i.body.getReader();;){let{done:n,value:r}=await e.read();if(n)break;o.push(r),s+=r.byteLength,t?.(Math.min(1,s/a))}let c=new Uint8Array(s),l=0;for(let e of o)c.set(e,l),l+=e.byteLength;let u=Ae(c.buffer),d=We(u),f={block:u,next:d,aux:ze(u,d),label:e};return Xe.set(e,f),{...f,note:n.note}}async function Qe(e){let t=Ae(await e.arrayBuffer()),n=We(t);return{block:t,next:n,aux:ze(t,n),label:e.name}}var $e=n((e=>{var t=l(),n=Symbol.for(`react.element`),r=Symbol.for(`react.fragment`),i=Object.prototype.hasOwnProperty,a=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function s(e,t,r){var s,c={},l=null,u=null;for(s in r!==void 0&&(l=``+r),t.key!==void 0&&(l=``+t.key),t.ref!==void 0&&(u=t.ref),t)i.call(t,s)&&!o.hasOwnProperty(s)&&(c[s]=t[s]);if(e&&e.defaultProps)for(s in t=e.defaultProps,t)c[s]===void 0&&(c[s]=t[s]);return{$$typeof:n,type:e,key:l,ref:u,props:c,_owner:a.current}}e.Fragment=r,e.jsx=s,e.jsxs=s})),N=n(((e,t)=>{t.exports=$e()}))();function et(){let e=w(e=>e.developed),t=w(e=>e.darkroom.passes);return e<=0?null:(0,N.jsx)(`div`,{className:`status`,children:e>=t?`developed · ${t} passes`:`developing ${e} / ${t}`})}function tt(){document.fullscreenElement?document.exitFullscreen():document.documentElement.requestFullscreen?.().catch(()=>{})}var nt=`/v4d-next/assets/vision_wasm_module_internal-3CmJfNd5.wasm`,rt=`/v4d-next/assets/vision_wasm_module_internal-DpeA7n9s.js`,it=`modulepreload`,at=function(e){return`/v4d-next/`+e},ot={},st=function(e){return e.pathname.endsWith(`.css`)},ct=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},lt=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=at(t,n);let r=s(t),i=st(r);return ct(ot,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:it,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})};function ut(e){let t=-1;for(let n=0;n`u`?null:dt(e=>MediaRecorder.isTypeSupported(e)),this.type&&(this.begin(0),this.timers.push(window.setTimeout(()=>this.begin(1),6e4)))}begin(e){if(!this.type||this.stopped)return;let t=new MediaRecorder(this.stream,{mimeType:this.type.mimeType,videoBitsPerSecond:6e6}),n={rec:t,chunks:[],startedAt:this.clock()};t.ondataavailable=e=>{e.data.size&&n.chunks.push(e.data)},t.start(1e3),this.slots[e]=n,window.clearTimeout(this.timers[2+e]),this.timers[2+e]=window.setTimeout(()=>this.restart(e),12e4)}restart(e){let t=this.slots[e];this.slots[e]=null,t&&t.rec.state!==`inactive`&&t.rec.stop(),this.begin(e)}stopped=!1;async take(){let e=ut(this.slots.map(e=>e?.startedAt??NaN)),t=e>=0?this.slots[e]:null;if(!t||!this.type)return null;let n=new Promise(e=>t.rec.addEventListener(`stop`,()=>e(),{once:!0}));return this.slots[e]=null,t.rec.stop(),await n,this.begin(e),{blob:new Blob(t.chunks,{type:this.type.mimeType}),startedAt:t.startedAt,ext:this.type.ext}}stop(){this.stopped=!0;for(let e of this.timers)window.clearTimeout(e);for(let e of this.slots)e&&e.rec.state!==`inactive`&&e.rec.stop();this.slots=[null,null]}},pt=65535,mt=(e,t)=>e-t*Math.floor(e/t);function ht(e,t){return Math.min(65534,Math.floor(mt(e,t)/t*65535))}var gt=class{slots;perSlot;span;block;slotTime;slotCount;next=0;constructor(e,t,n,r){if(this.slots=e,this.perSlot=t,this.span=n,t%4!=0)throw Error(`perSlot must be a multiple of 4 (GPU writes are 4-byte aligned)`);let i=e*t;this.slotTime=new Float64Array(e).fill(NaN),this.slotCount=new Uint32Array(e),this.block={header:{pointCount:i,frameCount:0,fps:r,time:{start:0,end:n},bounds:s,space:{units:`m`,up:`+y`,handedness:`right`},sections:[],meta:{source:`live`}},position:new Uint16Array(3*i),time:new Uint16Array(i).fill(pt),color:new Uint8Array(3*i),extra:{}}}get frames(){let e=0;for(let t of this.slotTime)Number.isNaN(t)||e++;return e}write(e,t,n){let r=this.next;this.next=(this.next+1)%this.slots;let i=r*this.perSlot,a=Math.min(this.perSlot,Math.floor(t.length/3)),{min:o,max:c}=s,l=this.block.position,u=this.block.time,d=this.block.color,f=ht(e,this.span);for(let e=0;e0?e:NaN,this.slotCount[r]=a,{first:i,count:this.perSlot}}expire(e){let t=[],n=this.block.time;for(let r=0;re-this.span*.98||(n.fill(pt,r*this.perSlot,(r+1)*this.perSlot),this.slotTime[r]=NaN,this.slotCount[r]=0,t.push({first:r*this.perSlot,count:this.perSlot}))}return t}freeze(e,t={}){let n=[...this.slotTime.keys()].filter(e=>!Number.isNaN(this.slotTime[e])).sort((e,t)=>this.slotTime[e]-this.slotTime[t]);if(!n.length)throw Error(`nothing has been seen yet`);let r=this.slotTime[n[0]],i=0;for(let e of n)i+=this.slotCount[e];let a=new Float32Array(3*i),o=new Float32Array(i),c=new Uint8Array(3*i),{min:l,max:u}=s,d=this.block.position,f=this.block.color,p=0;for(let e of n){let t=this.slotTime[e]-r;for(let n=e*this.perSlot;ne.kind===`videoinput`).map((e,t)=>({id:e.deviceId,label:e.label||`camera ${t+1}`})):[]}function St(e){let t=w.getState();t.setLive(t.live?{...t.live,...e}:null)}async function Ct(e={}){Dt();let t=w.getState();if(!navigator.mediaDevices?.getUserMedia){t.setStatus(`This browser cannot open a camera here (it needs a secure page, https or localhost).`,`error`);return}t.setLive({device:``,stage:`Asking for the camera…`,matte:``,depth:``,notes:[],fps:0,held:0});let n;try{n=await navigator.mediaDevices.getUserMedia({video:{...e.deviceId?{deviceId:{exact:e.deviceId}}:{},width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},audio:!1})}catch(e){t.setLive(null),t.setStatus(`The camera did not open: ${e.message}`,`error`);return}let r=n.getVideoTracks()[0],i=document.createElement(`video`);i.muted=!0,i.playsInline=!0,i.srcObject=n,await i.play();let a=new Worker(new URL(`/v4d-next/assets/live.worker-B9vktp9Y.js`,``+import.meta.url),{type:`module`}),o=performance.now(),s=()=>(performance.now()-o)/1e3,c={stream:n,video:i,worker:a,ring:null,recorder:new ft(n,s),start:o,last:0,inFlight:!1,lastGrab:0,stopped:!1,arrivals:[],device:r.label||`camera`};yt=c,St({device:c.device,stage:`Loading`}),r.addEventListener(`ended`,()=>{yt===c&&Dt(`The camera was disconnected.`)});let l=w.getState().liveSettings;if(await new Promise((t,n)=>{a.onerror=e=>n(Error(e.message||`the live worker crashed`)),a.onmessage=e=>{let r=e.data;r.type===`progress`?St({stage:r.stage}):r.type===`ready`?(St({stage:``,matte:r.matte,depth:r.depth,notes:r.notes}),t()):r.type===`error`&&n(Error(r.message))},a.postMessage({type:`start`,settings:l,depth:e.depth??`auto`,segmenter:e.segmenter??`https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_segmenter/float16/latest/selfie_segmenter.tflite`,wasm:{loader:rt,binary:nt}})}).catch(e=>{throw yt===c&&Dt(`Live capture could not start: ${e.message}`),e}),yt!==c)return;wt(c,l),a.onmessage=e=>{let t=e.data;if(yt===c){if(t.type===`frame`){if(c.inFlight=!1,!c.ring)return;let e=[];if(t.positions.length)for(e.push(c.ring.write(t.t,t.positions,t.colors)),c.last=t.t,c.arrivals.push(t.t);c.arrivals.length>30;)c.arrivals.shift();e.push(...c.ring.expire(c.last)),e.length&&vt.write?.(c.ring.block,e)}else t.type===`error`&&(c.inFlight=!1,w.getState().setStatus(`Live frame failed: ${t.message}`,`warn`))}},Tt(c,s);let u=window.setInterval(()=>{if(yt!==c)return window.clearInterval(u);let e=c.arrivals,t=e.length>1?(e.length-1)/Math.max(.001,e[e.length-1]-e[0]):0;c.ring&&t>0&&(c.ring.block.header.fps=Math.min(30,Math.max(4,t*.9))),St({fps:t,held:c.ring?c.ring.frames/Math.max(t,.001):0})},500)}function wt(e,t){let n=Math.max(4,Math.ceil(t.pointsPerFrame/4)*4);e.ring=new gt(Math.ceil(t.seconds*15),n,t.seconds,15),e.ring.block.header.meta={source:`live`,liveSpan:t.seconds};let r=w.getState();r.setLoaded({block:e.ring.block,next:null,label:`camera`}),r.setOrbit(r.studio?h(t):b())}function Tt(e,t){let n=()=>{if(yt!==e||e.stopped)return;i();let n=t();if(e.inFlight||!w.getState().playing||n-e.lastGrab<1/15-.004)return;let r=e.video.videoWidth,a=e.video.videoHeight;if(!r||!a)return;e.lastGrab=n,e.inFlight=!0;let o=Math.min(1,_t/Math.max(r,a));createImageBitmap(e.video,{resizeWidth:Math.round(r*o),resizeHeight:Math.round(a*o),resizeQuality:`medium`}).then(t=>{if(yt!==e)return t.close();e.worker.postMessage({type:`frame`,bitmap:t,t:n},[t])}).catch(()=>{e.inFlight=!1})},r=e.video,i=()=>r.requestVideoFrameCallback?r.requestVideoFrameCallback(n):requestAnimationFrame(n);i()}function Et(e){let t=w.getState(),n=t.liveSettings,r={...n,...e};t.setLiveSettings(r),y(r);let i=yt;if(i){if(i.worker.postMessage({type:`settings`,settings:r}),r.matte!==n.matte)return void Ct({deviceId:i.stream.getVideoTracks()[0]?.getSettings().deviceId});(r.pointsPerFrame!==n.pointsPerFrame||r.seconds!==n.seconds)&&wt(i,r)}}function Dt(e){let t=yt;if(yt=null,t){t.stopped=!0,t.recorder.stop(),t.worker.terminate();for(let e of t.stream.getTracks())e.stop();t.video.srcObject=null}let n=w.getState();n.live&&n.setLive(null),e&&n.setStatus(e,`warn`)}function Ot(){let e=yt;return e?(wt(e,w.getState().liveSettings),!0):!1}function kt(e={}){let t=yt;if(!t?.ring)return null;try{return t.ring.freeze(15,{generator:`v4d-viewer sitting 0.5.0`,...e})}catch{return null}}function At(){return yt!==null}function jt(e=new Date){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}function Mt(e,t){let n=document.createElement(`a`);n.href=URL.createObjectURL(e),n.download=t,n.click(),setTimeout(()=>URL.revokeObjectURL(n.href),1e4)}async function Nt(){let e=yt,t=w.getState();if(!e?.ring)return null;let n=`v4d-sitter-${jt()}`,r=t.liveSettings,i=Math.min(...[...e.ring.slotTime].filter(e=>!Number.isNaN(e))),a=await e.recorder.take(),o={generator:`v4d-viewer live capture 0.2.0`,source:`camera`,camera:e.device,matte:t.live?.matte,depth:t.live?.depth,distance:r.distance,hfov:r.hfov,relief:r.relief,pointsPerFrame:r.pointsPerFrame,mirror:r.mirror,...a?{rawVideo:{file:`${n}.${a.ext}`,blockStartsAt:Math.max(0,Math.round((i-a.startedAt)*1e3)/1e3)}}:{}},s;try{s=e.ring.freeze(15,o)}catch(e){return t.setStatus(`Nothing to keep yet: ${e.message}.`,`warn`),null}return Mt(new Blob([Me(s)],{type:`application/octet-stream`}),`${n}.v4d`),a&&Mt(a.blob,`${n}.${a.ext}`),t.addKept({label:n,block:s}),t.setStatus(`Kept ${s.header.time.end.toFixed(1)} s as ${n}.v4d${a?` with the camera's video (${a.ext})`:``}.`),n}function Pt(){let e=w(e=>e.loaded),t=w(e=>e.lens.window.t0),{setT0:n,setPlaying:r}=w.getState();if(!e||xt(e.block))return null;let{start:i,end:a}=e.block.header.time;return(0,N.jsx)(`input`,{className:`scrub`,type:`range`,"aria-label":`Time`,min:i,max:a,step:(a-i)/2e3||.001,value:t,onPointerDown:()=>r(!1),onChange:e=>n(Number(e.target.value))})}var Ft=e=>Number.isFinite(e)?Math.abs(e)>=100?e.toFixed(0):Math.abs(e)>=1?e.toFixed(2):e.toPrecision(2):`∞`;function F({label:e,value:t,min:n,max:r,step:i,log:a,unit:o,onChange:s}){let c=e=>a?Math.log10(Math.max(n,Math.min(r,e))):e,l=e=>a?10**e:e,u=c(n),d=c(r);return(0,N.jsxs)(`label`,{className:`row`,children:[(0,N.jsx)(`span`,{className:`lbl`,children:e}),(0,N.jsx)(`input`,{type:`range`,min:u,max:d,step:a?(d-u)/400:i??(r-n)/400,value:c(Number.isFinite(t)?t:r),onChange:e=>s(l(Number(e.target.value)))}),(0,N.jsxs)(`span`,{className:`val`,children:[Ft(t),o??``]})]})}function It({label:e,value:t,options:n,onChange:r}){return(0,N.jsxs)(`label`,{className:`row`,children:[(0,N.jsx)(`span`,{className:`lbl`,children:e}),(0,N.jsx)(`select`,{value:t,onChange:e=>r(e.target.value),children:n.map(e=>(0,N.jsx)(`option`,{value:e,children:e},e))})]})}function I({title:e,children:t,closed:n}){return(0,N.jsxs)(`details`,{className:`section`,open:!n,children:[(0,N.jsx)(`summary`,{children:e}),t]})}function L({label:e,value:t,options:n,names:r,onChange:i}){return(0,N.jsxs)(`div`,{className:`opts`,role:`group`,"aria-label":e,children:[e&&(0,N.jsx)(`span`,{className:`lbl`,children:e}),n.map(e=>(0,N.jsx)(`button`,{className:e===t?`on`:``,"aria-pressed":e===t,onClick:()=>i(e),children:r?.[e]??e},e))]})}var Lt=e({filmHook:()=>Rt,filmPlan:()=>Bt,filmSize:()=>zt,makeFilm:()=>Ut,pickCodec:()=>Vt}),Rt={frame:null,aspect:()=>16/9,begin:null,end:null};function zt(e,t){let n=e=>Math.max(2,2*Math.round(e/2));return t>=1?[n(e),n(e/t)]:[n(e*t),n(e)]}function Bt(e,t){return{frames:Math.max(1,Math.round(e*t)),timestamp:e=>Math.round(e*1e6/t),duration:Math.round(1e6/t)}}async function Vt(e,t,n,r){let i=e*t>2228224?`33`:`28`;for(let a of[`6400`,`4d00`,`4200`]){let o={codec:`avc1.${a}${i}`,width:e,height:t,framerate:n,bitrate:Math.round(e*t*n*.35),avc:{format:`avc`},latencyMode:`quality`};if(await r(o))return o}return null}function Ht(e=new Date){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}async function Ut(e){let t=w.getState();if(!Rt.frame||t.printing!==null)return null;if(typeof VideoEncoder>`u`)return t.setStatus(`This browser cannot encode video here (WebCodecs needs a current Chrome or Edge, on https or localhost).`,`error`),null;let[n,r]=zt(e.long,Rt.aspect()),i=await Vt(n,r,e.fps,async e=>!!(await VideoEncoder.isConfigSupported(e)).supported);if(!i)return t.setStatus(`This browser cannot encode H.264 at ${n} × ${r}. Try a smaller size.`,`error`),null;let{createFile:a}=await lt(async()=>{let{createFile:e}=await import(`./mp4box.all-BeiT1km5.js`);return{createFile:e}},[]),o=Bt(e.seconds,e.fps),s=[],c=null,l=null,u=new VideoEncoder({output:(e,t)=>{let n=new Uint8Array(e.byteLength);e.copyTo(n),s.push({data:n,timestamp:e.timestamp,key:e.type===`key`});let r=t?.decoderConfig?.description;r&&!c&&(c=r instanceof ArrayBuffer?r.slice(0):new Uint8Array(r.buffer).slice().buffer)},error:e=>{l=e}});u.configure(i),t.setPrinting(0),Rt.begin?.();try{for(let t=0;t4;)await new Promise(e=>setTimeout(e,5));if(w.getState().setPrinting((t+1)/o.frames),l)throw l}if(await u.flush(),l)throw l;if(!c)throw Error(`the encoder gave no decoder configuration`);let t=e.fps*1e3,i=a(),d=i.addTrack({timescale:t,width:n,height:r,avcDecoderConfigRecord:c,name:`V4D`}),f=Math.round(t/e.fps);for(let e of s){let n=Math.round(e.timestamp*t/1e6);i.addSample(d,e.data,{duration:f,dts:n,cts:n,is_sync:e.key})}let p=new Blob([i.getBuffer().buffer],{type:`video/mp4`}),m=`v4d-film-${Ht()}-${n}x${r}-${e.fps}fps.mp4`,h=document.createElement(`a`);return h.href=URL.createObjectURL(p),h.download=m,h.click(),setTimeout(()=>URL.revokeObjectURL(h.href),6e4),w.getState().setStatus(`Filmed ${e.seconds} s at ${n} × ${r}, ${e.passes} passes a frame: ${m}.`),{name:m,blob:p}}catch(e){return w.getState().setStatus(`The film failed: ${e.message}`,`error`),null}finally{u.state!==`closed`&&u.close(),Rt.end?.(),w.getState().setPrinting(null)}}var R=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function Wt(e,t=4294967295){let n=t;for(let t=0;t>>8;return n}function Gt(e,t){let n=new Uint8Array(12+t.length),r=new DataView(n.buffer);r.setUint32(0,t.length);for(let t=0;t<4;t++)n[4+t]=e.charCodeAt(t);return n.set(t,8),r.setUint32(8+t.length,(Wt(n.subarray(4,8+t.length))^4294967295)>>>0),n}function Kt(e,t,n){let r=1+t*6,i=new Uint8Array(r*n);for(let a=0;a0?e[(a-1)*t*3+r]:0;i[n+1+2*r]=(o>>8)-(s>>8)&255,i[n+2+2*r]=(o&255)-(s&255)&255}}return i}async function qt(e){let t=new CompressionStream(`deflate`),n=new Blob([e]).stream().pipeThrough(t);return new Uint8Array(await new Response(n).arrayBuffer())}async function Jt(e,t,n,r={}){let i=new Uint8Array(13),a=new DataView(i.buffer);a.setUint32(0,t),a.setUint32(4,n),i[8]=16,i[9]=2;let o=[Uint8Array.from([137,80,78,71,13,10,26,10]),Gt(`IHDR`,i)];o.push(Gt(`sRGB`,Uint8Array.from([0])));let s=new TextEncoder;for(let[e,t]of Object.entries(r)){let n=s.encode(e.slice(0,79)),r=new TextEncoder().encode(t.replace(/[^\x20-\x7e\n]/g,`?`)),i=new Uint8Array(n.length+1+r.length);i.set(n,0),i.set(r,n.length+1),o.push(Gt(`tEXt`,i))}return o.push(Gt(`IDAT`,await qt(Kt(e,t,n)))),o.push(Gt(`IEND`,new Uint8Array)),new Blob(o,{type:`image/png`})}var Yt=e({makePrint:()=>en,makeStill:()=>Xt,printHook:()=>Zt,printSize:()=>Qt});function Xt(e=2,t=64){return en({long:Math.round(Zt.pixels()*e),passes:t,kind:`still`})}var Zt={render:null,aspect:()=>1.6,pixels:()=>1600};function Qt(e,t){return t>=1?[e,Math.max(1,Math.round(e/t))]:[Math.max(1,Math.round(e*t)),e]}function $t(e=new Date){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}async function en(e){let t=w.getState();if(!Zt.render||t.printing!==null)return null;let[n,r]=Qt(e.long,Zt.aspect());t.setPrinting(0);try{let{rgb:t,text:i}=await Zt.render(n,r,e.passes,e.tile,e=>w.getState().setPrinting(e));e.title&&(i.Title=e.title);let a=await Jt(t,n,r,i),o=`${e.title===`V4D sitting`?`v4d-sitting`:e.kind===`still`?`v4d-still`:`v4d-print`}-${$t()}-${n}x${r}.png`,s=document.createElement(`a`);return s.href=URL.createObjectURL(a),s.download=o,s.click(),setTimeout(()=>URL.revokeObjectURL(s.href),3e4),w.getState().setStatus(`${e.kind===`still`?`Saved a still`:`Printed`} ${n} × ${r}, ${e.passes} passes: ${o}.`),{name:o,blob:a}}catch(e){return w.getState().setStatus(`The print failed: ${e.message}`,`error`),null}finally{w.getState().setPrinting(null)}}function tn(){let e=w(e=>e.live),[t,n]=(0,j.useState)(!1);if(!e)return null;let r=e.stage||`${e.fps.toFixed(0)} fps · ${e.held.toFixed(1)} s held`;return(0,N.jsxs)(`div`,{className:`live-sub`,children:[(0,N.jsx)(`p`,{className:`meta`,children:r}),!e.stage&&(0,N.jsxs)(`p`,{className:`meta`,children:[e.matte,` · `,e.depth]}),e.notes.map(e=>(0,N.jsx)(`p`,{className:`meta warn`,children:e},e)),(0,N.jsxs)(`div`,{className:`opts`,children:[(0,N.jsxs)(`button`,{disabled:t||!!e.stage,onClick:()=>{n(!0),Nt().finally(()=>n(!1))},children:[t?`keeping…`:`keep`,(0,N.jsx)(`kbd`,{children:`K`})]}),(0,N.jsx)(`button`,{onClick:()=>Dt(),children:`close camera`})]})]})}function nn(){let e=w(e=>e.liveSettings),t=w(e=>e.live),[n,r]=(0,j.useState)([]);return(0,j.useEffect)(()=>{P().then(r)},[t?.device]),(0,N.jsxs)(I,{title:`Camera`,closed:!t,children:[n.length>1&&(0,N.jsx)(It,{label:`camera`,value:n.find(e=>e.label===t?.device)?.label??n[0].label,options:n.map(e=>e.label),onChange:e=>void Ct({deviceId:n.find(t=>t.label===e)?.id})}),(0,N.jsx)(L,{label:`cut`,value:e.matte,options:[`person`,`green`],names:{person:`person`,green:`green screen`},onChange:e=>Et({matte:e})}),(0,N.jsx)(F,{label:`distance`,value:e.distance,min:.4,max:4,step:.01,unit:` m`,onChange:e=>Et({distance:e})}),(0,N.jsx)(F,{label:`field of view`,value:e.hfov,min:30,max:120,step:1,unit:`°`,onChange:e=>Et({hfov:Math.round(e)})}),(0,N.jsx)(F,{label:`depth relief`,value:e.relief,min:0,max:.8,step:.01,unit:` m`,onChange:e=>Et({relief:e})}),(0,N.jsx)(F,{label:`steady`,value:e.calm,min:0,max:1.5,step:.01,unit:` s`,onChange:e=>Et({calm:e})}),(0,N.jsx)(F,{label:`breathing`,value:e.breath,min:0,max:40,step:.5,unit:`×`,onChange:e=>Et({breath:e})}),(0,N.jsx)(F,{label:`points / frame`,value:e.pointsPerFrame,min:1e3,max:2e4,log:!0,onChange:e=>Et({pointsPerFrame:Math.round(e/500)*500||500})}),(0,N.jsx)(F,{label:`seconds kept`,value:e.seconds,min:5,max:30,step:1,unit:` s`,onChange:e=>Et({seconds:Math.round(e)})}),(0,N.jsx)(L,{label:`view`,value:e.mirror?`mirror`:`camera`,options:[`mirror`,`camera`],onChange:e=>Et({mirror:e===`mirror`})}),(0,N.jsxs)(`p`,{className:`meta`,children:[`Relief sets how deep the body is, front to back; steady holds each point's depth over that many seconds, so a still sitter keeps one shape (0: every frame on its own). Breathing amplifies the rise and fall of the chest, a preview of the Lab's; hold still for a few seconds before it shows. `,(0,N.jsx)(`button`,{className:`link`,onClick:()=>Et({...o,matte:e.matte}),children:`defaults`})]}),(0,N.jsx)(`p`,{className:`meta`,children:`Nothing leaves this device. Keep saves the seconds held as a .v4d and the camera's own video, for the Lab.`})]})}function rn(){return w(e=>e.live)?(0,N.jsxs)(`div`,{className:`camera-on`,role:`status`,children:[(0,N.jsx)(`span`,{"aria-hidden":`true`,children:`●`}),` camera on`]}):null}async function an(e,t=30,n=960,r=1){let i=URL.createObjectURL(e),a=document.createElement(`video`);a.muted=!0,a.preload=`auto`,a.src=i,await new Promise((e,t)=>{a.onloadedmetadata=()=>e(),a.onerror=()=>t(Error(`this browser cannot play the file`))});let o=Math.max(1,Math.floor(a.duration*t)),s=Math.min(1,n/Math.max(a.videoWidth,a.videoHeight)),c={width:a.videoWidth,height:a.videoHeight,fps:t,frameCount:o,codec:`element`};if(r<=0)return URL.revokeObjectURL(i),{info:c,frames:(async function*(){})()};async function*l(){try{for(let e=0;e{a.onseeked=()=>e()}),yield await createImageBitmap(a,{resizeWidth:Math.round(a.videoWidth*s),resizeHeight:Math.round(a.videoHeight*s),resizeQuality:`high`})}finally{URL.revokeObjectURL(i)}}return{info:c,frames:l()}}var on=/\.(mp4|m4v|mov|webm|mkv|ogv)$/i;function sn(e){return e.type.startsWith(`video/`)||on.test(e.name)}var cn=null,ln=null,un=null;function dn(){cn?.terminate(),cn=null,ln=null,un?.(),un=null;let e=w.getState();e.setJob(null),e.setImported(null)}function fn(e,t={}){dn();let n=w.getState(),r=new Worker(new URL(`/v4d-next/assets/video.worker-DUP1KR4N.js`,``+import.meta.url),{type:`module`});cn=r,ln={file:e,opts:t},n.setStatus(``),n.setJob({label:e.name,stage:`Starting`,fraction:0});let i=0,a=null,o=!0,s=async t=>{let n=await an(e,30,960,t);r.postMessage({type:`info`,info:n.info});for await(let e of n.frames){let t=e;if(cn!==r){t.close();return}for(;i>=2;)await new Promise(e=>{a=e});i++,r.postMessage({type:`frame`,bitmap:t},[t])}r.postMessage({type:`end`})};return new Promise(c=>{let l=t=>{cn===r&&dn(),w.getState().setStatus(`Could not import ${e.name}: ${t}`,`error`),c()};r.onerror=e=>l(e.message||`the import worker crashed`),r.onmessage=t=>{let n=t.data,r=w.getState();switch(n.type){case`progress`:r.setJob({label:e.name,stage:n.stage,fraction:n.fraction});break;case`need-frames`:s(n.step).catch(e=>l(e.message));break;case`ack`:i--,a?.(),a=null;break;case`done`:r.setJob(null),r.setLoaded({block:n.block,next:null,label:e.name}),r.setImported({label:e.name,maxPointsPerFrame:n.maxPointsPerFrame,budgetPointsPerFrame:Math.floor(ge/Math.max(1,n.block.header.frameCount)),frames:n.block.header.frameCount}),o&&(r.setStatus(n.note?`${e.name}: ${n.note}.`:`${e.name}: depth by ${n.depth}.`,n.note&&n.depth.includes(`stand-in`)?`warn`:`info`),o=!1,c()),un?.(),un=null;break;case`error`:o?l(n.message):r.setStatus(`Could not rebuild ${e.name}: ${n.message}`,`error`)}},r.postMessage({type:`start`,file:e,settings:n.importSettings,depth:t.depth??`auto`,plate:t.plate??!0,snap:t.snap??!0})})}function pn(e){let t=w.getState(),n=t.imported;if(!cn||!n||t.job||n.label!==t.loaded?.label)return Promise.resolve(!1);un?.();let r={...e,pointsPerFrame:Math.min(e.pointsPerFrame,n.maxPointsPerFrame)};return new Promise(e=>{un=()=>e(!0),cn.postMessage({type:`rebuild`,settings:r})})}function mn(){if(!ln)return Promise.resolve();let{file:e,opts:t}=ln;return fn(e,t)}var hn=[`NOW`,`EXPOSURE`,`STROBE`,`ECHO`,`SCULPT`,`SLIT3D`,`DISSOLVE`,`FIREBRAND`,`KALAM`,`TRACE`,`ANATOMY`,`WITNESS`];function gn(e,t=!1){return e!==null&&!Be.includes(e)?null:`${e!==null&&String(e).startsWith(`walker`)?String(e).startsWith(`walker-2m`)?`walker-2m`:`walker`:Ue()}${t?`-kalam`:``}`}function _n(){return{share:.05,width:.004,kind:`path`,points:!1}}function vn(){return{show:`all`,before:0,doubt:.06,unseenLight:1,rings:!0}}function yn(e,t=0){return{kind:`shear`,shear:{dir:[-e,0,-t],k:1}}}function bn(e){return e!==null&&!Be.includes(e)?null:e===`witness`||e===`witness-2m`?e:Ue()===`walker-2m`?`witness-2m`:`witness`}function xn(e){let t=Math.max(.001,e);return{profile:`decay`,thickness:t,tau:t/3}}function Sn(e,t,n={}){let r=f(),i=re(),a=r.window,o=gn(t.current),s=``,c=1;switch(e){case`NOW`:s=`A thin present: one instant of the block.`;break;case`EXPOSURE`:s=`The shutter never closes (Sugimoto, Wesely).`,a.thickness=1/0,Object.assign(i,{blend:`additive`,gain:.06});break;case`STROBE`:{s=`Instants at fixed intervals, fixed in place (Marey, Muybridge, Edgerton).`;let e=t.fps&&t.fps>0?t.fps:30;Object.assign(a,{profile:`comb`,thickness:1/0,period:Math.max(1,Math.floor(.5*e+1e-9))/e,pulse:1/e,combPhase:`block`}),Object.assign(i,{blend:`additive`,gain:.9});break}case`ECHO`:s=`Retention: the just-past still sounds (Husserl's comet tail; Bragaglia).`,Object.assign(a,{profile:`decay`,thickness:3,tau:.8}),Object.assign(i,{blend:`additive`,gain:.12});break;case`SCULPT`:s=`Time laid into depth: orbit to see it (Marey's gull, Boccioni).`,a.thickness=1/0,r.mapping.kind=`shear`,r.mapping.shear={dir:[0,0,-1],k:.3};break;case`SLIT3D`:s=`A photo-finish: a thin slab of space, all of time (Akten, vinils).`,r.mapping.kind=`swapXT`,r.mapping.swap={axis:0,k:t.subjectSpeed,slit:0},a.thickness=.03/t.subjectSpeed,i.pointSize=.014;break;case`DISSOLVE`:s=`The present holds; past and future come apart into dust.`,Object.assign(a,{profile:`saddle`,thickness:8,plateau:.9}),r.age={fadePast:.35,fadeFuture:.08,drift:[-.45,.25,0],turbulence:1,noiseScale:3,shrink:.3},Object.assign(i,{background:A});break;case`FIREBRAND`:s=`Continuity is made by the window, not by the world (Rumi, Masnavi I:1144).`,o=`firebrand`,Object.assign(a,xn(.001)),Object.assign(i,{blend:`additive`,gain:1,pointSize:.03,minPx:2,background:ue});break;case`KALAM`:s=n.kalam?`Kalām: no particle lasts two instants; each is created anew.`:`Tracked: the same particles persist from instant to instant.`,o=gn(t.current,n.kalam),r.identity=n.kalam?`kalam`:`tracked`,c=.25;break;case`TRACE`:s=`Each point keeps its path, in the body's own frame: a body as a bundle of histories (Marey).`,Object.assign(a,{profile:`decay`,thickness:3,tau:1.2}),Object.assign(r.mapping,yn(t.carry??t.subjectSpeed,.25)),Object.assign(i,{blend:`additive`,gain:.5,background:ue,thread:_n()});break;case`ANATOMY`:s=`Each part keeps its own time: what rests stays dark, what moves becomes light.`,Object.assign(a,{profile:`decay`,thickness:4,tau:1.6}),Object.assign(r.mapping,yn(t.carry??t.subjectSpeed)),Object.assign(i,{blend:`additive`,gain:.1,background:ue,motionRef:2,lookOverride:{color:`motion`,a:[.16,.17,.2],b:[1,.84,.6]}});break;case`WITNESS`:s=`What the camera saw is ink; what was filled in is a ring, and doubt grows while unseen.`,o=bn(t.current),Object.assign(a,{profile:`box`,thickness:1.05/(t.fps&&t.fps>0?t.fps:30)}),Object.assign(i,{background:A,witness:vn(),pointSize:.008,thread:{share:.08,width:.0015,kind:`repair`,points:!0},lookOverride:{color:`tint`,a:[.13,.12,.11],b:[.13,.12,.11]}})}return{idea:s,lens:r,style:i,block:o,speed:c}}function Cn(){let e=w(e=>e.style),t=w(e=>e.loaded),{setStyle:n}=w.getState();if(!t?.next&&!t?.block.rawPosition)return null;let r=e.thread,i=e=>n({thread:{...r??_n(),...e}});return(0,N.jsxs)(I,{title:`Threads`,closed:!r,children:[(0,N.jsx)(It,{label:`draw`,value:r?r.points?`both`:`threads`:`points`,options:[`points`,`threads`,`both`],onChange:e=>e===`points`?n({thread:void 0}):i({points:e===`both`})}),r&&(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(It,{label:`thread`,value:r.kind,options:t.block.rawPosition?[`path`,`repair`]:[`path`],onChange:e=>i({kind:e})}),(0,N.jsx)(F,{label:`share`,value:r.share,min:.002,max:1,log:!0,onChange:e=>i({share:e})}),(0,N.jsx)(F,{label:`width`,value:r.width*1e3,min:.3,max:30,log:!0,unit:` mm`,onChange:e=>i({width:e/1e3})}),(0,N.jsx)(`p`,{className:`meta`,children:r.kind===`path`?`Each kept track drawn from one frame to the next: its path through time.`:`From where the raw lift put each point to where the repair put it.`})]}),(0,N.jsx)(F,{label:`motion ref`,value:e.motionRef??1.5,min:.1,max:4,log:!0,unit:` m/s`,onChange:e=>n({motionRef:e})})]})}function wn(){let e=w(e=>e.style),t=w(e=>e.loaded),{setStyle:n}=w.getState(),r=t?.block.observed;if(!r)return null;let i=e.witness??{...vn(),rings:!1,doubt:0},a=e=>n({witness:{...i,...e}}),o=t.block.header.meta?.witness?.simulated;return(0,N.jsxs)(I,{title:`Witness`,children:[(0,N.jsx)(It,{label:`show`,value:i.show,options:[`all`,`seen`,`unseen`],onChange:e=>a({show:e})}),t.block.rawPosition&&(0,N.jsx)(F,{label:`before`,value:i.before,min:0,max:1,onChange:e=>a({before:e})}),(0,N.jsx)(F,{label:`doubt`,value:i.doubt,min:0,max:1,unit:` m/s`,onChange:e=>a({doubt:e})}),(0,N.jsx)(F,{label:`unseen light`,value:i.unseenLight,min:0,max:1,onChange:e=>a({unseenLight:e})}),(0,N.jsx)(It,{label:`unseen as`,value:i.rings?`rings`:`points`,options:[`rings`,`points`],onChange:e=>a({rings:e===`rings`})}),(0,N.jsxs)(`p`,{className:`meta`,children:[`The camera saw `,Math.round(Ie(r)*100),` % of the samples.`,` `,o?`Simulated: one camera in front of the walk; the model's own positions stand in for the repair.`:`From the block's observed section (a ReLift import, or another reconstruction).`,t.block.rawPosition?` before = 1 shows the raw lift: what was first believed.`:``]})]})}var Tn=[`free`,`1:1`,`4:5`,`2:3`,`3:2`,`16:9`,`9:16`];function En(e){if(e===`free`)return null;let[t,n]=e.split(`:`).map(Number);return t/n}var Dn={silver:{background:[.96,.95,.93],look:{color:`tint`,a:[.13,.12,.11],b:[.13,.12,.11],grain:.6}},light:{background:[0,0,0],look:{color:`tint`,a:[1,.9,.78],b:[1,.9,.78],grain:.6}}},On=[`NOW`,`ECHO`,`FIREBRAND`,`DISSOLVE`,`EXPOSURE`],kn=`ECHO`,z={NOW:{preset:`NOW`,name:`Now`,material:`silver`,frame:`present`},ECHO:{preset:`ECHO`,name:`Echo`,material:`light`,gain:.8,frame:`present`,window:{thickness:1.5,tau:.45},reveal:{hold:3,seconds:17,from:1/30},darkroom:{timeFocus:.05}},FIREBRAND:{preset:`FIREBRAND`,name:`Firebrand`,material:`light`,frame:`block`,window:xn(1.1),gain:1,reveal:{hold:1.5,seconds:10,from:.001},darkroom:{auto:!1}},DISSOLVE:{preset:`DISSOLVE`,name:`Dissolve`,material:`silver`,frame:`present`},EXPOSURE:{preset:`EXPOSURE`,name:`Exposure`,material:`light`,gain:1.2,frame:`block`}};async function An(e){Dt();let t=w.getState();t.setStatus(`Building ${e}…`);try{let{note:n,...r}=await qe(e);t.setLoaded(r),t.setStatus(n?`${e}: ${n}.`:``)}catch(n){t.setStatus(`Could not build ${e}: ${n.message}`,`error`)}}async function jn(e){Dt();let t=w.getState();t.setStatus(`Fetching ${e} (${Je[e].megabytes} MB)…`),w.setState({fetching:0});try{let{note:n,...r}=await Ze(e,e=>w.setState({fetching:e}));t.setLoaded(r),t.setStatus(`${e}: ${n}.`)}catch(n){t.setStatus(`Could not fetch ${e}: ${n.message}`,`error`)}finally{w.setState({fetching:null})}}async function Mn(e,t=w.getState().kalam){let n=w.getState(),r=n.loaded?.block.header.meta?.speed,i=Sn(e,{current:n.loaded?.label??null,subjectSpeed:typeof r==`number`&&r>0?r:.55,...typeof r==`number`?{carry:r}:{},fps:n.loaded?.block.header.fps},{kalam:t});i.block&&i.block!==n.loaded?.label&&await An(i.block);let a=x.t;w.setState({lens:{...i.lens,window:{...i.lens.window,t0:a}},style:i.style,speed:i.speed,kalam:t}),n.setPreset(e,i.idea)}async function Nn(e,t=!1){let n=z[e],r=w.getState(),i=r.sitting??(r.sit?null:r.work);if(r.sit&&!r.sitting&&n.preset===`FIREBRAND`)return;i&&n.preset!==`FIREBRAND`&&r.loaded?.block!==i.block&&(r.sitting?r.setLoaded({block:r.sitting.block,next:null,label:r.sitting.label}):Fn(r.work)),await Mn(n.preset,!1);let a=w.getState();w.setState({lens:{...a.lens,window:{...a.lens.window,...n.window,t0:x.t}},style:{...a.style,gain:a.style.gain*(n.gain??1)},viewerLens:e,revealStart:n.reveal&&!t?performance.now():null})}async function Pn(e,t={}){Dt();let n=w.getState();if(sn(e))return fn(e,t);if(!/\.v4d$/i.test(e.name))n.setStatus(`${e.name} is neither a .v4d block nor a video (mp4, mov, webm).`,`error`);else{n.setStatus(`Reading ${e.name}…`);try{n.setLoaded(await Qe(e)),n.setStatus(``)}catch(t){n.setStatus(`Could not read ${e.name}: ${t.message}`,`error`)}}}function Fn(e){Dt(),w.getState().setLoaded({block:e.block,next:null,label:e.label})}async function In(){let e=w.getState().work;e?Fn(e):await An(Ue())}function Ln(e){Dt();let t=w.getState(),n=t.kept.find(t=>t.label===e);n&&t.setLoaded({block:n.block,next:null,label:n.label})}function Rn(){let e=w.getState().loaded;if(!e)return;let t=Me(e.block),n=document.createElement(`a`);n.href=URL.createObjectURL(new Blob([t],{type:`application/octet-stream`})),n.download=e.label.replace(/\.[^.]+$/,``)+`.v4d`,n.click(),setTimeout(()=>URL.revokeObjectURL(n.href),1e4)}function zn(e){return{past:[],present:e,future:[]}}function Bn(e,t,n,r=80){if(n(e.present,t))return e;let i=[...e.past,e.present];return{past:i.slice(Math.max(0,i.length-r)),present:t,future:[]}}function Vn(e){return e.past.length?{past:e.past.slice(0,-1),present:e.past[e.past.length-1],future:[e.present,...e.future]}:e}function Hn(e){return e.future.length?{past:[...e.past,e.present],present:e.future[0],future:e.future.slice(1)}:e}var Un=[0,0,0];function Wn(){return{pointSize:.012,minPx:.75,blend:`opaque`,background:Un,gain:1,mark:0,markColor:[1,.59,.24]}}function Gn(){return{v:1,name:``,subject:null,preset:null,idea:``,kalam:!1,speed:1,lens:f(),style:Wn(),look:{...m(),m:null},darkroom:ne(),frame:`free`,move:le(),orbit:null,t:null}}var Kn=`Infinity`;function qn(e){if(Array.isArray(e))return e.map(qn);if(typeof e==`object`&&e){let t=e;return Object.fromEntries(Object.keys(t).sort().filter(e=>t[e]!==void 0).map(e=>[e,qn(t[e])]))}return e}function Jn(e){return JSON.stringify(qn(e),(e,t)=>t===1/0?Kn:t)}function Yn(e,t){if(typeof e==`number`)return t===Kn?1/0:typeof t==`number`&&!Number.isNaN(t)?t:e;if(typeof e==`string`)return typeof t==`string`?t:e;if(typeof e==`boolean`)return typeof t==`boolean`?t:e;if(Array.isArray(e))return!Array.isArray(t)||t.length!==e.length?e:e.map((e,n)=>Yn(e,t[n]));if(typeof e==`object`&&e){let n=typeof t==`object`&&t?t:{},r={};for(let t of Object.keys(e))r[t]=Yn(e[t],n[t]);return r}return e}var B=(e,t,n)=>Math.min(n,Math.max(t,e)),Xn=(e,t,n)=>e.includes(t)?t:n,Zn=e=>Array.isArray(e)&&e.length===3&&e.every(e=>typeof e==`number`&&e>=0&&e<=1)?e:null,V=(e,t)=>Number.isFinite(e)?e:t;function Qn(e){if(typeof e!=`object`||!e)return null;let t=Yn(b(),e);return{target:t.target.map(e=>B(V(e,0),-1e3,1e3)),distance:B(V(t.distance,6.5),.3,80),yaw:B(V(t.yaw,0),-1e3,1e3),pitch:B(V(t.pitch,0),-1.5,1.5),fovY:B(V(t.fovY,.7),.1,2.4)}}function $n(e){let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{return null}if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t,r=Gn(),i=Yn(r,n);i.v=1,i.name=i.name.slice(0,80),i.idea=i.idea.slice(0,400),i.subject=typeof n.subject==`string`?n.subject.slice(0,40):null,i.preset=typeof n.preset==`string`?n.preset.slice(0,40):null,i.speed=B(V(i.speed,1),0,8);let a=i.lens.window,o=i.lens.mapping,s=i.lens.age;a.t0=0,a.profile=Xn([`box`,`decay`,`comb`,`saddle`],a.profile,`box`),a.combPhase=Xn([`now`,`block`],a.combPhase,`block`),a.thickness=Math.max(1e-5,a.thickness),a.tau=B(V(a.tau,.8),1e-6,1e3),a.period=B(V(a.period,.5),.001,1e3),a.pulse=B(V(a.pulse,1/30),1e-4,1e3),a.plateau=B(V(a.plateau,.3),0,1),o.kind=Xn([`identity`,`shear`,`swapXT`,`tilt`],o.kind,`identity`),o.swap.axis=o.swap.axis===1||o.swap.axis===2?o.swap.axis:0,s.fadePast=Math.max(0,s.fadePast),s.fadeFuture=Math.max(0,s.fadeFuture),i.lens.identity=Xn([`tracked`,`kalam`],i.lens.identity,`tracked`);let c=i.style,l=n.style??{};if(c.blend=Xn([`additive`,`opaque`],c.blend,`opaque`),c.pointSize=B(V(c.pointSize,.012),3e-4,.5),c.minPx=B(V(c.minPx,.75),.1,8),c.gain=B(V(c.gain,1),0,50),c.mark=B(V(c.mark,0),0,1),c.background=Zn(c.background)??Un,c.markColor=Zn(c.markColor)??[1,.59,.24],typeof l.motionRef==`number`&&Number.isFinite(l.motionRef)&&(c.motionRef=B(l.motionRef,.01,20)),l.thread!==null&&typeof l.thread==`object`){let e=Yn({share:.05,width:.004,kind:`path`,points:!1},l.thread);c.thread={share:B(V(e.share,.05),0,1),width:B(V(e.width,.004),1e-4,.2),kind:Xn([`path`,`repair`],e.kind,`path`),points:e.points}}if(l.witness!==null&&typeof l.witness==`object`){let e=Yn({show:`all`,before:0,doubt:.06,unseenLight:1,rings:!0},l.witness);c.witness={show:Xn([`all`,`seen`,`unseen`],e.show,`all`),before:B(V(e.before,0),0,1),doubt:B(V(e.doubt,0),0,5),unseenLight:B(V(e.unseenLight,1),0,1),rings:e.rings}}if(l.lookOverride!==null&&typeof l.lookOverride==`object`){let e=l.lookOverride,t=Zn(e.a),n=Zn(e.b),r=Zn(e.m);t&&n&&(c.lookOverride={color:Xn(ie,e.color,`tint`),a:t,b:n,...r?{m:r}:{}})}let u=n.look??{};i.look={color:Xn(ie,i.look.color,r.look.color),a:Zn(i.look.a)??r.look.a,b:Zn(i.look.b)??r.look.b,m:Zn(u.m),grain:B(V(i.look.grain,.6),.05,3)};let d=i.darkroom;d.ev=B(V(d.ev,0),-12,12),d.shutter=B(V(d.shutter,0),0,5),d.timeFocus=B(V(d.timeFocus,0),0,2),d.shade=B(V(d.shade,.35),0,1),d.grain=B(V(d.grain,.035),0,.5),d.passes=Math.round(B(V(d.passes,128),1,512)),d.glow=B(V(d.glow,0),0,4),d.glowSpread=B(V(d.glowSpread,.5),0,1),d.halation=B(V(d.halation,0),0,1),d.aperture=B(V(d.aperture,0),0,5),d.focus=B(V(d.focus,0),-80,80),d.vignette=B(V(d.vignette,0),0,1),i.frame=Xn(Tn,i.frame,`free`);let f=n.move??{};return i.move={kind:Xn(ce,i.move.kind,`still`),degrees:B(V(i.move.degrees,40),-3600,3600),push:B(V(i.move.push,.75),.05,20),ease:Xn([`linear`,`soft`],i.move.ease,`soft`),a:Qn(f.a),b:Qn(f.b)},i.orbit=Qn(n.orbit),i.t=typeof n.t==`number`&&Number.isFinite(n.t)?n.t:null,i}var er=e=>{let t=``;for(let n=0;n{let t=atob(e.replace(/-/g,`+`).replace(/_/g,`/`)),n=new Uint8Array(t.length);for(let e=0;e`u`?`j`+er(t):`z`+er(await nr(t,new CompressionStream(`deflate-raw`)))}async function ar(e){if(!e||e.length>rr)return null;try{let t=tr(e.slice(1)),n=e[0]===`z`?await nr(t,new DecompressionStream(`deflate-raw`)):e[0]===`j`?t:null;return!n||n.length>2e5?null:$n(new TextDecoder().decode(n))}catch{return null}}function or(e){let t=/(?:^#|&)look=([A-Za-z0-9_-]+)/.exec(e);return t?t[1]:null}function sr(e,t){let n=new URL(t);return n.search=``,n.hash=`look=${e}`,n.toString()}function cr(e){return e&&(Be.includes(e)||Ye(e))?e:null}function lr(e,t){return Ye(e)?e:Be.includes(e)?e.startsWith(`walker`)?`${t}${e.endsWith(`-kalam`)?`-kalam`:``}`:e.startsWith(`witness`)?t===`walker-2m`?`witness-2m`:`witness`:e:null}function ur(e=``,t=!1){let n=w.getState(),r={...n.style};return delete r.palette,{v:1,name:e,subject:cr(n.loaded?.label),preset:n.preset,idea:n.idea,kalam:n.kalam,speed:n.speed,lens:{...n.lens,window:{...n.lens.window,t0:0}},style:r,look:{...n.look,m:n.look.m??null},darkroom:n.darkroom,frame:n.frame,move:n.move,orbit:t?n.orbit:null,t:t?x.t:null}}async function dr(e,t={}){let n=t.view!==!1,r=e.subject?lr(e.subject,Ue()):null;r&&r!==w.getState().loaded?.label&&(Ye(r)?await jn(r):await An(r)),n&&e.t!==null&&(x.t=e.t),w.setState({lens:{...e.lens,window:{...e.lens.window,t0:x.t}},style:e.style,look:e.look,darkroom:e.darkroom,frame:e.frame,move:e.move,speed:e.speed,kalam:e.kalam,preset:e.preset,idea:e.idea,movePreview:null,...n&&e.orbit?{orbit:e.orbit}:{}})}async function fr(e){let t=lr(e.subject,Ue());t&&t!==w.getState().loaded?.label&&(Ye(t)?await jn(t):await An(t)),await Mn(e.preset,!1);let n=w.getState(),r=e.colour?O[e.colour.palette]:null,i={...n.style,...e.style,...e.thread&&n.style.thread?{thread:{...n.style.thread,...e.thread}}:{}};r&&delete i.lookOverride,e.t!==void 0&&(x.t=e.t),w.setState({lens:{...n.lens,window:{...n.lens.window,...e.window,t0:x.t}},style:i,look:{...n.look,...r&&e.colour?{color:e.colour.mode,a:r.a,b:r.b,m:r.m??null}:{},...e.grain?{grain:e.grain}:{}},darkroom:{...ne(),...e.darkroom},orbit:{...b(),...e.orbit},frame:e.frame??`free`,move:le(),movePreview:null,idea:`“${e.name}”: ${e.line}.`})}var pr=`v4d.looks`;function mr(e){w.setState({looks:e});try{localStorage.setItem(pr,`[${e.map(Jn).join(`,`)}]`)}catch{}}function hr(){try{let e=JSON.parse(localStorage.getItem(pr)??`[]`),t=Array.isArray(e)?e.map($n).filter(e=>e!==null&&e.name!==``):[];w.setState({looks:t})}catch{w.setState({looks:[]})}}function gr(e){let t=e.trim().slice(0,80);if(!t)return null;let n=ur(t,!0);return n.t=null,mr([...w.getState().looks.filter(e=>e.name!==t),n]),w.getState().setStatus(`Saved the look “${t}”.`),n}function _r(e){mr(w.getState().looks.filter(t=>t.name!==e))}function vr(e,t){let n=document.createElement(`a`);n.href=URL.createObjectURL(new Blob([t],{type:`application/json`})),n.download=e,n.click(),setTimeout(()=>URL.revokeObjectURL(n.href),1e4)}function yr(){let e=w.getState().looks;e.length&&vr(`v4d-looks.json`,`{"v4dLooks":[${e.map(Jn).join(`,`)}]}`)}async function br(e){let t;try{t=JSON.parse(await e.text())}catch{t=null}let n=(Array.isArray(t?.v4dLooks)?t.v4dLooks:[t]).slice(0,200).map($n).filter(e=>e!==null&&e.name!==``),r=w.getState();if(!n.length)return r.setStatus(`${e.name} holds no looks.`,`warn`),0;let i=new Set(n.map(e=>e.name));return mr([...r.looks.filter(e=>!i.has(e.name)),...n]),r.setStatus(`${n.length} look${n.length>1?`s`:``} added from ${e.name}.`),n.length}async function xr(){return sr(await ir(ur(``,!0)),location.href)}async function Sr(){let e=await xr(),t=w.getState();try{await navigator.clipboard.writeText(e),t.setStatus(`Link copied: it reopens this look, this view and this moment.`)}catch{history.replaceState(null,``,e),t.setStatus(`The link is in the address bar: copy it from there.`)}}async function Cr(e){let t=or(e);return t?ar(t):null}var wr=null,Tr,Er=null,Dr=(e,t)=>e===t,Or=()=>w.setState({history:{undo:wr?.past.length??0,redo:wr?.future.length??0}});function kr(){wr=zn(Jn(ur())),Or();let e=w.subscribe(()=>{if(!wr)return;let e=Jn(ur());e===wr.present?(clearTimeout(Tr),Er=null):e!==Er&&(Er=e,clearTimeout(Tr),Tr=setTimeout(()=>{Er=null,wr&&(wr=Bn(wr,e,Dr),Or())},400))});return()=>{e(),clearTimeout(Tr),wr=null}}async function Ar(e){if(!wr||e===wr)return;clearTimeout(Tr),Er=null,wr=e,Or();let t=$n(e.present);t&&await dr(t,{view:!1})}var jr=()=>wr?Ar(Vn(wr)):Promise.resolve(),Mr=()=>wr?Ar(Hn(wr)):Promise.resolve(),Nr=[{name:`Threads of light`,line:`every point's path, glowing`,subject:`dancer`,preset:`TRACE`,t:1.6,thread:{share:.25},darkroom:{glow:.5,glowSpread:.6,halation:.4,vignette:.35},orbit:{yaw:.05,pitch:.05,distance:4.2,target:[0,1.3,0]}},{name:`Shallow time`,line:`the present sharp, the past out of focus`,subject:`dancer`,preset:`TRACE`,t:1.6,thread:{share:.4,width:.003},darkroom:{glow:.35,glowSpread:.4,halation:.2,aperture:.1,focus:-.1,vignette:.5},orbit:{yaw:.6,pitch:.1,distance:4.6,target:[0,1.3,-.2]},frame:`4:5`},{name:`Gilded anatomy`,line:`what rests is dark, what moves is gold`,subject:`dancer`,preset:`ANATOMY`,t:1.9,darkroom:{glow:.45,glowSpread:.7,halation:.55,vignette:.3},orbit:{yaw:.1,pitch:.05,distance:4.2,target:[0,1.3,0]}},{name:`Dusk exposure`,line:`all of its time, early to late in colour`,subject:`dancer`,preset:`EXPOSURE`,t:2.9,colour:{mode:`time`,palette:`dusk`},darkroom:{glow:.4,glowSpread:.8,halation:.15,vignette:.4},orbit:{yaw:-.2,pitch:.05,distance:4.4,target:[0,1.3,0]}},{name:`Kiln procession`,line:`a walk laid into depth, fired`,subject:`walker`,preset:`SCULPT`,t:9.9,style:{blend:`additive`,gain:.03},colour:{mode:`time`,palette:`kiln`},darkroom:{glow:.4,glowSpread:.6,halation:.3,aperture:.12,focus:-3,vignette:.45},orbit:{yaw:.95,pitch:.32,distance:14,target:[-1.3,-.9,-1.5]},frame:`16:9`}];function Pr(){let e=w(e=>e.loaded),t=w(e=>e.live),n=w(e=>e.kept),r=w(e=>e.fetching),i=e?.label,a=e=>n.some(t=>t.label===e),o=i&&!Be.includes(i)&&!Ye(i)&&i!==`camera`&&!a(i),s=[[`walker`,Ue(),!!i?.startsWith(`walker`)],[`firebrand`,`firebrand`,i===`firebrand`],[`witness`,Ue()===`walker-2m`?`witness-2m`:`witness`,!!i?.startsWith(`witness`)]];return(0,N.jsxs)(`nav`,{className:`lib-list blocks`,"aria-label":`Subjects`,children:[s.map(([e,t,n])=>(0,N.jsx)(`button`,{className:n?`on`:``,"aria-pressed":n,onClick:()=>void An(t),children:e},e)),Object.keys(Je).map(e=>(0,N.jsxs)(`button`,{className:i===e?`on`:``,"aria-pressed":i===e,onClick:()=>void jn(e),title:`${Je[e].note}. ${Je[e].megabytes} MB, fetched when opened.`,children:[e,(0,N.jsx)(`span`,{className:`tag`,children:r!==null&&i!==e?`${Math.round(r*100)} %`:`generated`})]},e)),o&&(0,N.jsx)(`button`,{className:`on`,"aria-pressed":`true`,children:i}),(0,N.jsx)(`button`,{className:t?`on`:``,"aria-pressed":!!t,onClick:()=>{t||Ct().catch(()=>{})},title:`A live camera: the last seconds as a subject`,children:`camera`}),(0,N.jsx)(tn,{}),n.map(e=>(0,N.jsx)(`button`,{className:i===e.label?`on`:``,onClick:()=>void Ln(e.label),children:e.label.replace(`v4d-sitter-`,`kept `)},e.label)),(0,N.jsxs)(`label`,{className:`add`,title:`A .v4d block, or a green-screen video. You can also drop either onto the window.`,children:[`+ open a block or a video`,(0,N.jsx)(`input`,{type:`file`,accept:`.v4d,video/*,.mp4,.mov,.m4v,.webm`,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&Pn(t)}})]}),(o||i&&a(i))&&(0,N.jsx)(`button`,{onClick:Rn,children:`↓ save as .v4d`})]})}function Fr(){let e=w(e=>e.preset),t=w(e=>e.kalam),n=w(e=>e.lens.window.thickness),r=e?.replace(`*`,``)??null;return(0,N.jsxs)(`nav`,{className:`lib-list presets`,"aria-label":`Ways of seeing`,children:[hn.map((t,n)=>(0,N.jsxs)(`button`,{className:r===t?`on`:``,"aria-pressed":r===t,onClick:()=>void Mn(t),children:[t.toLowerCase(),e===`${t}*`&&(0,N.jsx)(`span`,{className:`tag`,children:`changed`}),n<9&&(0,N.jsx)(`kbd`,{children:n+1})]},t)),r===`FIREBRAND`&&(0,N.jsx)(`div`,{className:`sub`,children:(0,N.jsx)(F,{label:`trail`,value:n,min:0,max:3,step:.01,unit:` s`,onChange:e=>w.getState().setWindow(xn(e))})}),r===`KALAM`&&(0,N.jsx)(`div`,{className:`sub`,children:(0,N.jsx)(L,{value:t?`kalām`:`tracked`,options:[`tracked`,`kalām`],onChange:e=>void Mn(`KALAM`,e===`kalām`)})})]})}function Ir(){let e=w(e=>e.looks),[t,n]=(0,j.useState)(!1),[r,i]=(0,j.useState)(``),a=()=>{gr(r)&&(n(!1),i(``))};return(0,N.jsxs)(`div`,{className:`lib-list looks`,role:`group`,"aria-label":`Looks`,children:[Nr.map(e=>(0,N.jsxs)(`button`,{className:`look`,onClick:()=>void fr(e),title:e.line,children:[e.name,(0,N.jsx)(`span`,{className:`tag`,children:e.subject})]},e.name)),e.map(e=>(0,N.jsxs)(`div`,{className:`look-own`,children:[(0,N.jsx)(`button`,{className:`look`,onClick:()=>void dr(e),title:e.subject?`Made on ${e.subject}: opens it.`:`Applies to what is loaded.`,children:e.name}),(0,N.jsx)(`button`,{className:`x`,onClick:()=>_r(e.name),"aria-label":`Delete the look ${e.name}`,title:`Delete`,children:`×`})]},e.name)),t?(0,N.jsxs)(`form`,{className:`look-name`,onSubmit:e=>{e.preventDefault(),a()},children:[(0,N.jsx)(`input`,{autoFocus:!0,value:r,maxLength:80,placeholder:`name this look`,"aria-label":`Name of the look`,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(n(!1),i(``))}}),(0,N.jsx)(`button`,{type:`submit`,disabled:!r.trim(),children:`keep`})]}):(0,N.jsx)(`button`,{className:`add`,onClick:()=>n(!0),children:`+ keep this look`})]})}function Lr(){return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`h2`,{children:`Subject`}),(0,N.jsx)(Pr,{}),(0,N.jsx)(`h2`,{children:`Looks`}),(0,N.jsx)(Ir,{}),(0,N.jsx)(`h2`,{children:`Seeing`}),(0,N.jsx)(Fr,{})]})}function Rr(){return(0,N.jsxs)(`aside`,{className:`rail ui`,"aria-label":`Library`,children:[(0,N.jsxs)(`header`,{className:`rail-head`,children:[(0,N.jsx)(`h1`,{children:`V4D`}),(0,N.jsx)(`p`,{children:`Atelier`}),(0,N.jsxs)(`button`,{className:`back`,onClick:()=>window.dispatchEvent(new CustomEvent(`v4d:studio`)),title:`Back to the work (S)`,children:[`← the work`,(0,N.jsx)(`kbd`,{children:`S`})]})]}),(0,N.jsx)(`div`,{className:`rail-body`,children:(0,N.jsx)(Lr,{})}),(0,N.jsxs)(`footer`,{className:`rail-foot`,children:[`© 2026 Mehran Ahmadi · v`,`0.6.0`]})]})}var zr=[`box`,`decay`,`comb`,`saddle`],Br={box:`slice`,decay:`trail`,comb:`strobe`,saddle:`soft`},Vr=[`identity`,`shear`,`swapXT`,`tilt`],Hr={identity:`as it was`,shear:`into space`,swapXT:`slit`,tilt:`tilted`};function Ur(){let e=w(e=>e.lens),t=w(e=>e.loaded),{setWindow:n,setMapping:r,setAge:i,setLens:a}=w.getState(),o=e.window,s=e.mapping,c=e.age,l=t?t.block.header.time.end-t.block.header.time.start:10;return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsxs)(I,{title:`Time held`,children:[(0,N.jsx)(L,{label:`shape`,value:o.profile,options:zr,names:Br,onChange:e=>n({profile:e})}),(0,N.jsx)(F,{label:`how long`,value:o.thickness,min:1e-4,max:l+.05,log:!0,unit:` s`,onChange:e=>n({thickness:e>=l+.04?1/0:e})}),o.profile===`decay`&&(0,N.jsx)(F,{label:`fades over`,value:o.tau,min:.02,max:10,log:!0,unit:` s`,onChange:e=>n({tau:e})}),o.profile===`comb`&&(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(F,{label:`every`,value:o.period,min:.03,max:3,log:!0,unit:` s`,onChange:e=>n({period:e})}),(0,N.jsx)(F,{label:`flash`,value:o.pulse,min:.001,max:1,log:!0,unit:` s`,onChange:e=>n({pulse:e})}),(0,N.jsx)(L,{label:`fixed to`,value:o.combPhase,options:[`block`,`now`],names:{block:`the place`,now:`the present`},onChange:e=>n({combPhase:e})})]}),o.profile===`saddle`&&(0,N.jsx)(F,{label:`held flat`,value:o.plateau,min:0,max:1,onChange:e=>n({plateau:e})}),(0,N.jsx)(`p`,{className:`meta`,children:`Slice: one stretch, evenly. Trail: the past, fading. Strobe: instants at intervals. Soft: both sides, eased.`})]}),(0,N.jsxs)(I,{title:`Time into space`,children:[(0,N.jsx)(L,{label:`laid`,value:s.kind,options:Vr,names:Hr,onChange:e=>r({kind:e})}),s.kind===`shear`&&(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(F,{label:`speed`,value:s.shear.k,min:-2,max:2,unit:` m/s`,onChange:e=>r({shear:{...s.shear,k:e}})}),(0,N.jsx)(F,{label:`across`,value:s.shear.dir[0],min:-2,max:2,step:.01,onChange:e=>r({shear:{...s.shear,dir:[e,s.shear.dir[1],s.shear.dir[2]]}})}),(0,N.jsx)(F,{label:`up`,value:s.shear.dir[1],min:-2,max:2,step:.01,onChange:e=>r({shear:{...s.shear,dir:[s.shear.dir[0],e,s.shear.dir[2]]}})}),(0,N.jsx)(F,{label:`toward`,value:s.shear.dir[2],min:-2,max:2,step:.01,onChange:e=>r({shear:{...s.shear,dir:[s.shear.dir[0],s.shear.dir[1],e]}})}),(0,N.jsx)(`p`,{className:`meta`,children:`Each second of age moves a point by speed × direction: a walk laid into depth, or taken out so the body stays in place.`})]}),s.kind===`swapXT`&&(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(F,{label:`speed`,value:s.swap.k,min:.05,max:3,log:!0,unit:` m/s`,onChange:e=>r({swap:{...s.swap,k:e}})}),(0,N.jsx)(F,{label:`slit at`,value:s.swap.slit,min:-3,max:3,unit:` m`,onChange:e=>r({swap:{...s.swap,slit:e}})}),(0,N.jsx)(`p`,{className:`meta`,children:`A photo-finish: one thin slab of space, all of its time laid side by side.`})]}),s.kind===`tilt`&&(0,N.jsx)(F,{label:`slope`,value:s.tilt.slope[0],min:-3,max:3,unit:` s/m`,onChange:e=>r({tilt:{...s.tilt,slope:[e,0,0]}})})]}),(0,N.jsxs)(I,{title:`What age does`,children:[(0,N.jsx)(F,{label:`memory`,value:c.fadePast,min:.05,max:100,log:!0,unit:` s`,onChange:e=>i({fadePast:e>=99?1/0:e})}),(0,N.jsx)(F,{label:`anticipation`,value:c.fadeFuture,min:.05,max:100,log:!0,unit:` s`,onChange:e=>i({fadeFuture:e>=99?1/0:e})}),(0,N.jsx)(F,{label:`drift`,value:c.drift[0],min:-1,max:1,unit:` m/s`,onChange:e=>i({drift:[e,c.drift[1],c.drift[2]]})}),(0,N.jsx)(F,{label:`rise`,value:c.drift[1],min:-1,max:1,unit:` m/s`,onChange:e=>i({drift:[c.drift[0],e,c.drift[2]]})}),(0,N.jsx)(F,{label:`scatter`,value:c.turbulence,min:0,max:1.5,unit:` m/s`,onChange:e=>i({turbulence:e})}),(0,N.jsx)(F,{label:`shrink`,value:c.shrink,min:0,max:2,onChange:e=>i({shrink:e})})]}),(0,N.jsxs)(I,{title:`Identity`,closed:!0,children:[(0,N.jsx)(L,{label:`points`,value:e.identity,options:[`tracked`,`kalam`],names:{tracked:`persist`,kalam:`made anew`},onChange:e=>a({identity:e})}),(0,N.jsx)(`p`,{className:`meta`,children:`Persist: a point slides to where it is next. Made anew (kalām): each instant is held, then replaced.`})]}),(0,N.jsx)(Cn,{}),(0,N.jsx)(wn,{})]})}var Wr={source:`captured`,tint:`one colour`,age:`by age`,time:`by moment`,identity:`by point`,motion:`by motion`};function Gr({label:e,value:t,onChange:n}){return(0,N.jsx)(`label`,{className:`swatch custom`,title:e,style:{background:d(t)},children:(0,N.jsx)(`input`,{type:`color`,"aria-label":e,value:d(t),onChange:e=>n(g(e.target.value))})})}function Kr(){let e=w(e=>e.look),t=w(e=>e.style),n=w(e=>e.darkroom),{setLook:r,setStyle:i,setDarkroom:a}=w.getState(),o=(e,t)=>!e||!t?!e&&!t:e.every((e,n)=>Math.abs(e-t[n])<.001),s=t.blend===`additive`;return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsxs)(I,{title:`Colour`,children:[(0,N.jsx)(L,{label:`colour`,value:t.lookOverride?.color??e.color,options:ie,names:Wr,onChange:e=>r({color:e})}),(0,N.jsx)(`div`,{className:`opts palettes`,role:`group`,"aria-label":`Palette`,children:Object.entries(O).map(([t,n])=>(0,N.jsx)(`button`,{className:`swatch${o(n.a,e.a)&&o(n.b,e.b)&&o(n.m,e.m)?` on`:``}`,title:t,"aria-label":`${t} palette`,style:{background:n.m?`linear-gradient(135deg, ${d(n.a)} 0 33%, ${d(n.m)} 33% 66%, ${d(n.b)} 66% 100%)`:`linear-gradient(135deg, ${d(n.a)} 0 50%, ${d(n.b)} 50% 100%)`},onClick:()=>r({a:n.a,b:n.b,m:n.m??null,color:e.color===`source`?`time`:e.color})},t))}),(0,N.jsxs)(`div`,{className:`opts palettes`,role:`group`,"aria-label":`Your own colours`,children:[(0,N.jsx)(`span`,{className:`lbl`,children:`own`}),(0,N.jsx)(Gr,{label:`First colour`,value:e.a,onChange:e=>r({a:e})}),e.m&&(0,N.jsx)(Gr,{label:`Middle colour`,value:e.m,onChange:e=>r({m:e})}),(0,N.jsx)(Gr,{label:`Last colour`,value:e.b,onChange:e=>r({b:e})}),(0,N.jsx)(`button`,{className:`link`,onClick:()=>r({m:e.m?null:e.a.map((t,n)=>(t+e.b[n])/2)}),children:e.m?`two colours`:`add a middle`})]}),(0,N.jsx)(L,{label:`ground`,value:t.background===A?`white`:`black`,options:[`black`,`white`],names:{black:`dark`,white:`paper`},onChange:e=>i({background:e===`white`?A:ue})})]}),(0,N.jsxs)(I,{title:`Points`,children:[(0,N.jsx)(L,{label:`drawn as`,value:t.blend,options:[`additive`,`opaque`],names:{additive:`light`,opaque:`ink`},onChange:e=>i({blend:e})}),(0,N.jsx)(F,{label:`fineness`,value:e.grain,min:.15,max:2,log:!0,onChange:e=>r({grain:e})}),(0,N.jsx)(F,{label:`size`,value:t.pointSize*1e3,min:1,max:60,log:!0,unit:` mm`,onChange:e=>i({pointSize:e/1e3})}),s&&(0,N.jsx)(F,{label:`each adds`,value:t.gain,min:.005,max:2,log:!0,onChange:e=>i({gain:e})}),(0,N.jsx)(`p`,{className:`meta`,children:`Light adds up in the dark, like a long exposure. Ink covers, like a print; on paper it stays untoned.`})]}),(0,N.jsxs)(I,{title:`Exposure`,children:[(0,N.jsx)(L,{label:`exposure`,value:n.auto?`auto`:`manual`,options:[`auto`,`manual`],onChange:e=>a({auto:e===`auto`})}),(0,N.jsx)(F,{label:n.auto?`lean`:`stops`,value:n.ev,min:-4,max:4,step:.05,unit:` EV`,onChange:e=>a({ev:e})})]}),(0,N.jsxs)(I,{title:`Glow`,children:[(0,N.jsx)(F,{label:`glow`,value:n.glow,min:0,max:1.5,step:.01,onChange:e=>a({glow:e})}),(0,N.jsx)(F,{label:`reach`,value:n.glowSpread,min:0,max:1,step:.01,onChange:e=>a({glowSpread:e})}),(0,N.jsx)(F,{label:`warmth`,value:n.halation,min:0,max:1,step:.01,onChange:e=>a({halation:e})}),(0,N.jsx)(`p`,{className:`meta`,children:s?`Light spilling around itself, as in a lens. Warmth turns it red, as film does (halation).`:`Glow belongs to light: draw the points as light to see it.`})]}),(0,N.jsxs)(I,{title:`Lens`,children:[(0,N.jsx)(F,{label:`opening`,value:n.aperture,min:0,max:1.5,step:.005,unit:` m`,onChange:e=>a({aperture:e})}),(0,N.jsx)(F,{label:`focus`,value:n.focus,min:-4,max:4,step:.01,unit:` m`,onChange:e=>a({focus:e})}),(0,N.jsx)(F,{label:`vignette`,value:n.vignette,min:0,max:1,step:.01,onChange:e=>a({vignette:e})}),(0,N.jsx)(`p`,{className:`meta`,children:`A wider opening makes a shallower focus. Focus 0 is on the point the camera turns around; + is beyond it. With time laid into depth, the past goes out of focus.`})]}),(0,N.jsxs)(I,{title:`Developing`,closed:!0,children:[(0,N.jsx)(F,{label:`shutter`,value:n.shutter,min:0,max:1,step:.005,unit:` s`,onChange:e=>a({shutter:e})}),(0,N.jsx)(F,{label:`time focus`,value:n.timeFocus,min:0,max:.3,step:.002,unit:` m/s`,onChange:e=>a({timeFocus:e})}),(0,N.jsx)(F,{label:`carving`,value:n.shade,min:0,max:1,step:.01,onChange:e=>a({shade:e})}),(0,N.jsx)(F,{label:`film grain`,value:n.grain,min:0,max:.12,step:.001,onChange:e=>a({grain:e})}),(0,N.jsx)(F,{label:`passes`,value:n.passes,min:8,max:256,step:1,onChange:e=>a({passes:Math.round(e)})}),(0,N.jsx)(`p`,{className:`meta`,children:`A still image (paused) develops over the passes: edges smooth, see-through becomes true, the shutter blurs motion, time focus softens the past. Carving shades solid forms (ink).`})]})]})}var qr={still:`none`,turn:`turn`,push:`push`,ab:`A → B`},Jr=e=>e*180/Math.PI;function Yr(){let e=w(e=>e.orbit),t=w(e=>e.frame),n=w(e=>e.move),r=w(e=>e.filmSeconds),i=w(e=>!!e.movePreview),{setOrbit:a,setFrame:o,setMove:s}=w.getState();return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsxs)(I,{title:`Frame`,children:[(0,N.jsx)(L,{value:t,options:Tn,onChange:o}),(0,N.jsx)(`p`,{className:`meta`,children:`The picture's proportions. The image takes this shape, and a still, a print and a film keep it.`})]}),(0,N.jsxs)(I,{title:`View`,children:[(0,N.jsx)(F,{label:`lens`,value:Jr(e.fovY),min:8,max:100,step:1,unit:`°`,onChange:t=>a({...e,fovY:t*Math.PI/180})}),(0,N.jsx)(F,{label:`distance`,value:e.distance,min:.3,max:40,log:!0,unit:` m`,onChange:t=>a({...e,distance:t})}),(0,N.jsx)(F,{label:`around`,value:Jr(e.yaw),min:-180,max:180,step:1,unit:`°`,onChange:t=>a({...e,yaw:t*Math.PI/180})}),(0,N.jsx)(F,{label:`above`,value:Jr(e.pitch),min:-85,max:85,step:1,unit:`°`,onChange:t=>a({...e,pitch:t*Math.PI/180})}),(0,N.jsxs)(`p`,{className:`meta`,children:[`Drag the image to turn, shift-drag to slide, scroll to come closer. A narrow lens flattens; a wide one deepens. `,(0,N.jsx)(`button`,{className:`link`,onClick:()=>a(b()),children:`reset`})]})]}),(0,N.jsxs)(I,{title:`Move`,children:[(0,N.jsx)(L,{value:n.kind,options:ce,names:qr,onChange:e=>s({kind:e})}),n.kind===`turn`&&(0,N.jsx)(F,{label:`by`,value:n.degrees,min:-360,max:360,step:5,unit:`°`,onChange:e=>s({degrees:e})}),n.kind===`push`&&(0,N.jsx)(F,{label:`ends at`,value:n.push,min:.3,max:2,step:.01,unit:` ×`,onChange:e=>s({push:e})}),n.kind===`ab`&&(0,N.jsxs)(`div`,{className:`opts`,children:[(0,N.jsx)(`button`,{className:n.a?`on`:``,onClick:()=>s({a:{...e}}),children:`set A here`}),(0,N.jsx)(`button`,{className:n.b?`on`:``,onClick:()=>s({b:{...e}}),children:`set B here`}),n.a&&(0,N.jsx)(`button`,{onClick:()=>a({...n.a}),children:`see A`}),n.b&&(0,N.jsx)(`button`,{onClick:()=>a({...n.b}),children:`see B`})]}),n.kind!==`still`&&(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(L,{label:`pace`,value:n.ease,options:[`soft`,`linear`],names:{soft:`gentle`,linear:`steady`},onChange:e=>s({ease:e})}),(0,N.jsxs)(`p`,{className:`meta`,children:[n.kind===`turn`&&`The camera goes around the subject from where it stands. 360° at a steady pace makes a film that loops.`,n.kind===`push`&&`The camera comes closer (below 1) or pulls away (above 1), from where it stands.`,n.kind===`ab`&&(n.a&&n.b?`The camera travels from view A to view B.`:`Frame a view and set it as A; frame another and set it as B.`),` `,`A film takes the move over its whole length (`,r,` s). `,(0,N.jsx)(`button`,{className:`link`,onClick:()=>w.setState({movePreview:i?null:{start:performance.now(),seconds:r}}),children:i?`stop`:`preview`})]})]})]})]})}var Xr=[`1`,`2`,`3`],Zr=[`32`,`64`,`128`],Qr=[`2400`,`4800`,`8000`],$r=[`32`,`64`,`128`,`256`],ei=[`5`,`10`,`20`],ti=[`1280`,`1920`,`3840`],ni=[`4`,`16`,`32`];function ri(){let e=w(e=>e.printing),t=w(e=>e.filmSeconds),n=w(e=>e.move.kind),r=w(e=>e.looks.length);w(e=>e.frame);let[i,a]=(0,j.useState)(`2`),[o,s]=(0,j.useState)(`64`),[c,l]=(0,j.useState)(`4800`),[u,d]=(0,j.useState)(`128`),[f,p]=(0,j.useState)(`1920`),[m,h]=(0,j.useState)(`16`),g=Zt.aspect(),[_,v]=Qt(Math.round(Zt.pixels()*Number(i)),g),[y,b]=Qt(Number(c),g),[x,S]=zt(Number(f),g),C=e!==null,T=(0,N.jsxs)(N.Fragment,{children:[`Working… `,Math.round((e??0)*100),` %`]});return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsxs)(I,{title:`Still`,children:[(0,N.jsx)(L,{label:`size`,value:i,options:Xr,names:{1:`screen`,2:`2 ×`,3:`3 ×`},onChange:a}),(0,N.jsx)(L,{label:`passes`,value:o,options:Zr,onChange:s}),(0,N.jsx)(`p`,{className:`meta`,children:C?T:(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`button`,{className:`link act`,onClick:()=>void Xt(Number(i),Number(o)),children:`Save a still`}),(0,N.jsx)(`kbd`,{children:`E`}),` `,_,` × `,v,` px: what is on screen, developed.`]})})]}),(0,N.jsxs)(I,{title:`Print`,children:[(0,N.jsx)(L,{label:`long side`,value:c,options:Qr,names:{2400:`2400`,4800:`4800`,8e3:`8000 px`},onChange:l}),(0,N.jsx)(L,{label:`passes`,value:u,options:$r,onChange:d}),(0,N.jsx)(`p`,{className:`meta`,children:C?T:(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`button`,{className:`link act`,onClick:()=>void en({long:Number(c),passes:Number(u)}),children:`Print`}),` `,y,` × `,b,` px, 16-bit PNG, with how it was made written inside.`]})})]}),(0,N.jsxs)(I,{title:`Film`,children:[(0,N.jsx)(L,{label:`length`,value:String(t),options:ei,names:{5:`5 s`,10:`10 s`,20:`20 s`},onChange:e=>w.setState({filmSeconds:Number(e)})}),(0,N.jsx)(L,{label:`long side`,value:f,options:ti,names:{1280:`1280`,1920:`1920`,3840:`3840 px`},onChange:p}),(0,N.jsx)(L,{label:`passes`,value:m,options:ni,names:{4:`4`,16:`16`,32:`32 a frame`},onChange:h}),(0,N.jsx)(`p`,{className:`meta`,children:C?T:(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`button`,{className:`link act`,onClick:()=>void Ut({seconds:t,fps:24,long:Number(f),passes:Number(m),fromOpening:!1}),children:`Film`}),` `,x,` × `,S,`, 24 fps, H.264 MP4, every frame developed`,n===`still`?`; the camera holds still (set a move under Camera).`:`; the camera makes its move.`]})})]}),(0,N.jsxs)(I,{title:`Share`,children:[(0,N.jsxs)(`p`,{className:`meta`,children:[(0,N.jsx)(`button`,{className:`link act`,onClick:()=>void Sr(),children:`Copy a link`}),` that reopens this look, this view and this moment. The look travels inside the link itself; nothing is uploaded.`]}),(0,N.jsxs)(`p`,{className:`meta`,children:[`Looks kept here: `,r,`.`,` `,r>0&&(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`button`,{className:`link`,onClick:yr,children:`save them as a file`}),` · `]}),(0,N.jsxs)(`label`,{className:`link file`,children:[`read looks from a file`,(0,N.jsx)(`input`,{type:`file`,accept:`.json,application/json`,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&br(t)}})]})]})]})]})}var ii={everywhere:`all`,"edges only":`edges`};function ai(){let e=w(e=>e.importSettings),t=w(e=>e.imported),n=w(e=>e.loaded),r=w(e=>e.job),i=w.getState().setImportSettings,a=!!t&&t.label===n?.label&&!r,o=a&&t.maxPointsPerFrame{if(l.current){l.current=!1;return}if(!a)return;let t=setTimeout(()=>{c(!0),pn(e).finally(()=>c(!1))},200);return()=>clearTimeout(t)},[e]);let u=Object.keys(ii).find(t=>ii[t]===e.spill)??`everywhere`;return(0,N.jsxs)(I,{title:`Video import`,children:[(0,N.jsx)(F,{label:`height`,value:e.heightM,min:.5,max:2.5,step:.01,unit:` m`,onChange:e=>i({heightM:e})}),(0,N.jsx)(F,{label:`field of view`,value:e.hfov,min:15,max:110,step:1,unit:`°`,onChange:e=>i({hfov:Math.round(e)})}),(0,N.jsx)(F,{label:`depth relief`,value:e.relief,min:0,max:1.5,step:.01,unit:` m`,onChange:e=>i({relief:e})}),(0,N.jsx)(F,{label:`points / frame`,value:e.pointsPerFrame,min:1e3,max:4e4,log:!0,onChange:e=>i({pointsPerFrame:Math.round(e/500)*500||500})}),(0,N.jsx)(It,{label:`green spill`,value:u,options:Object.keys(ii),onChange:e=>i({spill:ii[e]})}),(0,N.jsxs)(`p`,{className:`meta`,children:[a?o?(0,N.jsxs)(N.Fragment,{children:[`This clip was sampled at `,t.maxPointsPerFrame.toLocaleString(),` points per frame. `,(0,N.jsx)(`button`,{className:`link`,onClick:()=>void mn(),children:`Re-import`}),` for more.`]}):s?`Rebuilding…`:`Changes rebuild this clip at once.`:`Used for the next green-screen video you open (drop it on the window).`,` `,(0,N.jsx)(`button`,{className:`link`,onClick:()=>i({..._}),children:`defaults`})]}),(0,N.jsx)(`p`,{className:`meta`,children:`Spill everywhere turns a green suit khaki; edges only keeps its colour and cleans the outline.`})]})}function oi(){let e=w(e=>e.loaded),t=w(e=>e.stats),n=e?.block.header,r=typeof n?.meta?.origin==`string`?n.meta.origin:null;return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsxs)(I,{title:`Subject`,children:[n?(0,N.jsxs)(`p`,{className:`meta`,children:[e.label,`: `,n.meta?.source===`live`?(0,N.jsxs)(N.Fragment,{children:[`a live ring of `,n.pointCount.toLocaleString(),` points`]}):(0,N.jsxs)(N.Fragment,{children:[n.pointCount.toLocaleString(),` points, `,n.frameCount,` frames at `,Math.round(n.fps*100)/100,` a second, `,(n.time.end-n.time.start).toFixed(1),` s`]}),e.next?`, with tracks`:`, without tracks`,e.block.observed?`, and what the camera saw`:``,`.`]}):(0,N.jsx)(`p`,{className:`meta`,children:`Nothing loaded.`}),r&&(0,N.jsxs)(`p`,{className:`meta`,children:[r,`.`]}),(0,N.jsxs)(`p`,{className:`meta live`,children:[t.fps.toFixed(0),` frames a second · `,t.drawn.toLocaleString(),` points drawn`]})]}),(0,N.jsx)(nn,{}),(0,N.jsx)(ai,{})]})}var H={library:`Library`,time:`Time`,light:`Light`,camera:`Camera`,output:`Output`,source:`Source`};function si(){let e=`(max-width: 900px)`,[t,n]=(0,j.useState)(()=>typeof matchMedia==`function`&&matchMedia(e).matches);return(0,j.useEffect)(()=>{let t=matchMedia(e),r=()=>n(t.matches);return t.addEventListener(`change`,r),()=>t.removeEventListener(`change`,r)},[]),t}function ci(){let e=w(e=>e.lensOpen),t=w(e=>e.tab),n=si(),r=se.filter(e=>n||e!==`library`),i=r.includes(t)?t:`time`;return e?(0,N.jsxs)(`aside`,{className:`inspector ui`,"aria-label":`Inspector`,children:[(0,N.jsx)(`nav`,{className:`tabs`,role:`tablist`,children:r.map(e=>(0,N.jsx)(`button`,{role:`tab`,"aria-selected":e===i,className:e===i?`on`:``,onClick:()=>w.getState().setTab(e),children:H[e]},e))}),(0,N.jsxs)(`div`,{className:`panel panel-${i}`,role:`tabpanel`,"aria-label":H[i],children:[i===`library`&&(0,N.jsx)(`div`,{className:`lib`,children:(0,N.jsx)(Lr,{})}),i===`time`&&(0,N.jsx)(Ur,{}),i===`light`&&(0,N.jsx)(Kr,{}),i===`camera`&&(0,N.jsx)(Yr,{}),i===`output`&&(0,N.jsx)(ri,{}),i===`source`&&(0,N.jsx)(oi,{})]})]}):null}var li=[.1,.25,.5,1,2];function ui(){let e=w(e=>e.preset),t=w(e=>e.idea),n=w(e=>e.status),r=w(e=>e.statusLevel);return(0,j.useEffect)(()=>{if(!n||r!==`info`||n.endsWith(`…`))return;let e=setTimeout(()=>{w.getState().status===n&&w.getState().setStatus(``)},5e3);return()=>clearTimeout(e)},[n,r]),(0,N.jsxs)(`div`,{className:`present ui`,"aria-live":`polite`,children:[e&&(0,N.jsx)(`div`,{className:`preset-name`,children:e}),e&&t&&(0,N.jsx)(`div`,{className:`idea`,children:t}),n&&r===`info`&&(0,N.jsx)(`div`,{className:`status`,children:n}),(0,N.jsx)(et,{})]})}function di(){let e=w(e=>e.loaded),t=w(e=>e.lens.window.t0),n=w(e=>e.playing),r=w(e=>e.speed),i=w(e=>e.history),a=w(e=>e.lensOpen),{setPlaying:o,setSpeed:s,setLensOpen:c,setBare:l}=w.getState(),u=e?.block.header.time.end??0,d=xt(e?.block),[f,p]=(0,j.useState)(!1);return(0,j.useEffect)(()=>{let e=()=>p(!!document.fullscreenElement);return document.addEventListener(`fullscreenchange`,e),()=>document.removeEventListener(`fullscreenchange`,e)},[]),(0,N.jsxs)(`div`,{className:`bar ui`,children:[(0,N.jsxs)(`button`,{className:`act play`,onClick:()=>o(!n),"aria-label":n?`Pause`:`Play`,title:`Space`,children:[(0,N.jsx)(`span`,{className:`glyph`,"aria-hidden":`true`,children:n?`❚❚`:`▶`}),n?`pause`:`play`]}),(0,N.jsx)(`div`,{className:`opts speeds`,role:`group`,"aria-label":`Playback speed`,children:li.map(e=>(0,N.jsxs)(`button`,{className:e===r?`on`:``,"aria-pressed":e===r,onClick:()=>s(e),children:[e,`×`]},e))}),(0,N.jsx)(`div`,{className:`bar-time`,children:(0,N.jsx)(Pt,{})}),(0,N.jsx)(`div`,{className:`clock`,children:d?(0,N.jsxs)(N.Fragment,{children:[`live`,(0,N.jsxs)(`span`,{children:[` · the last `,u.toFixed(0),` s`]})]}):(0,N.jsxs)(N.Fragment,{children:[t.toFixed(2),(0,N.jsxs)(`span`,{children:[` / `,u.toFixed(2),` s`]})]})}),(0,N.jsxs)(`div`,{className:`bar-end`,children:[(0,N.jsx)(`button`,{className:`only-narrow`,onClick:()=>window.dispatchEvent(new CustomEvent(`v4d:studio`)),title:`Back to the work (S)`,children:`← work`}),(0,N.jsx)(`button`,{disabled:!i.undo,onClick:()=>void jr(),title:`Undo (Ctrl+Z)`,children:`undo`}),(0,N.jsx)(`button`,{className:`wide`,disabled:!i.redo,onClick:()=>void Mr(),title:`Redo (Ctrl+Shift+Z)`,children:`redo`}),(0,N.jsx)(`button`,{className:a?`on`:``,"aria-pressed":a,onClick:()=>c(!a),title:`The inspector (L)`,children:`panels`}),(0,N.jsx)(`button`,{className:`wide`,onClick:()=>l(!0),title:`Hide everything but the image (H)`,children:`hide`}),(0,N.jsx)(`button`,{className:`icon`,onClick:tt,"aria-label":f?`Leave fullscreen`:`Fullscreen`,title:`${f?`Leave fullscreen`:`Fullscreen`} (F)`,children:(0,N.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`14`,height:`14`,"aria-hidden":`true`,children:(0,N.jsx)(`path`,{d:f?`M6 1v5H1M10 1v5h5M6 15v-5H1M10 15v-5h5`:`M1 6V1h5M15 6V1h-5M1 10v5h5M15 10v5h-5`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`})})})]})]})}function fi(){return(0,j.useEffect)(()=>(hr(),window.__v4d&&(window.__v4d.share=xr),kr()),[]),(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(Rr,{}),(0,N.jsx)(ui,{}),(0,N.jsx)(ci,{}),(0,N.jsx)(di,{})]})}function pi(){return w(e=>e.bare)?(0,N.jsxs)(`button`,{className:`reveal`,onClick:()=>w.getState().setBare(!1),title:`Show the controls (H)`,children:[`show`,(0,N.jsx)(`kbd`,{children:`H`})]}):null}function mi(){let e=w(e=>e.job);return e?(0,N.jsxs)(`div`,{className:`import`,role:`status`,children:[(0,N.jsxs)(`div`,{className:`import-head`,children:[(0,N.jsxs)(`span`,{children:[`Importing `,e.label]}),(0,N.jsx)(`button`,{onClick:dn,children:`Cancel`})]}),(0,N.jsx)(`div`,{className:`bar`,children:(0,N.jsx)(`div`,{style:{width:`${Math.round(e.fraction*100)}%`}})}),(0,N.jsx)(`div`,{className:`import-stage`,children:e.stage})]}):null}function hi(){let[e,t]=(0,j.useState)(!1);return(0,j.useEffect)(()=>{let e=0,n=e=>e.dataTransfer?.types.includes(`Files`)??!1,r=r=>{n(r)&&(e++,t(!0))},i=()=>{e=Math.max(0,e-1),e||t(!1)},a=e=>{n(e)&&e.preventDefault()},o=n=>{n.preventDefault(),e=0,t(!1);let r=n.dataTransfer?.files[0];r&&Pn(r)};return window.addEventListener(`dragenter`,r),window.addEventListener(`dragleave`,i),window.addEventListener(`dragover`,a),window.addEventListener(`drop`,o),()=>{window.removeEventListener(`dragenter`,r),window.removeEventListener(`dragleave`,i),window.removeEventListener(`dragover`,a),window.removeEventListener(`drop`,o)}},[]),e?(0,N.jsx)(`div`,{className:`dropzone`,children:(0,N.jsx)(`p`,{children:`Drop a green-screen video or a .v4d block`})}):null}function gi(){let e=w(e=>e.status),t=w(e=>e.statusLevel);return!e||t===`info`?null:(0,N.jsxs)(`div`,{className:`alert ${t}`,role:`alert`,children:[(0,N.jsx)(`span`,{children:e}),(0,N.jsx)(`button`,{onClick:()=>w.getState().setStatus(``),"aria-label":`Dismiss`,children:`×`})]})}var _i=`// Auto-exposure's light meter (darkroom/darkroom.ts autoExposure): for each cell of a 64 × 40\r +// grid over the scene (linear light, before exposure), the brightest of 6 × 6 samples in it.\r +\r +@group(0) @binding(0) var scene: texture_2d;\r +@group(0) @binding(1) var cells: array;\r +\r +const GX: u32 = 64u;\r +const GY: u32 = 40u;\r +const S: u32 = 6u;\r +\r +@compute @workgroup_size(8, 8)\r +fn measure(@builtin(global_invocation_id) id: vec3) {\r + if (id.x >= GX || id.y >= GY) { return; }\r + let size = vec2(textureDimensions(scene));\r + let last = vec2(size) - vec2(1);\r + var m = 0.0;\r + for (var j = 0u; j < S; j++) {\r + for (var i = 0u; i < S; i++) {\r + let uv = (vec2(f32(id.x * S + i), f32(id.y * S + j)) + 0.5) / vec2(f32(GX * S), f32(GY * S));\r + let px = clamp(vec2(uv * size), vec2(0), last);\r + let c = textureLoad(scene, px, 0).rgb;\r + m = max(m, dot(c, vec3(0.2126, 0.7152, 0.0722)));\r + }\r + }\r + cells[id.y * GX + id.x] = m;\r +}\r +`,vi=`// Glow (darkroom/darkroom.ts: glowLevels, glowWeight, glowNorm). The picture's light is +// halved again and again into a chain of smaller pictures, each a wider blur, and the chain is +// added back up: level 0 ends as Σ weight^k · blur_k. present (post.wgsl) adds it to the +// picture before the film curve, so bright light spills into its surroundings as it does in a +// lens and in film, and nothing is clipped first. +// +// first: the accumulated light (÷ passes) at half size, a 2 × 2 box. +// down: one level to the next, half the size (dual filter, 5 taps). +// up: one level added into the one above it, × weight (dual filter, 8 taps). + +struct G { + // 1 / passes, weight of each wider level, _, _ + a: vec4, +}; + +@group(0) @binding(0) var g: G; +@group(0) @binding(1) var accTex: texture_2d; // first: unfilterable (rgba32float) +@group(0) @binding(2) var levelTex: texture_2d; // down, up +@group(0) @binding(3) var samp: sampler; + +struct V { @builtin(position) pos: vec4 }; + +@vertex +fn full(@builtin(vertex_index) i: u32) -> V { + var xy = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0)); + var o: V; + o.pos = vec4(xy[i], 0.0, 1.0); + return o; +} + +// Half-float targets hold up to 65504: keep the brightest light finite. +const CEIL: f32 = 60000.0; + +@fragment +fn first(v: V) -> @location(0) vec4 { + let size = vec2(textureDimensions(accTex)); + let p = vec2(v.pos.xy) * 2; + var c = vec3(0.0); + for (var y = 0; y < 2; y++) { + for (var x = 0; x < 2; x++) { + c += textureLoad(accTex, clamp(p + vec2(x, y), vec2(0), size - vec2(1)), 0).rgb; + } + } + return vec4(clamp(c * 0.25 * g.a.x, vec3(0.0), vec3(CEIL)), 1.0); +} + +@fragment +fn down(v: V) -> @location(0) vec4 { + let src = vec2(textureDimensions(levelTex)); + let uv = v.pos.xy * 2.0 / src; + let h = 1.0 / src; + var c = textureSampleLevel(levelTex, samp, uv, 0.0).rgb * 4.0; + c += textureSampleLevel(levelTex, samp, uv + vec2(-h.x, -h.y), 0.0).rgb; + c += textureSampleLevel(levelTex, samp, uv + vec2(h.x, -h.y), 0.0).rgb; + c += textureSampleLevel(levelTex, samp, uv + vec2(-h.x, h.y), 0.0).rgb; + c += textureSampleLevel(levelTex, samp, uv + vec2(h.x, h.y), 0.0).rgb; + return vec4(c / 8.0, 1.0); +} + +@fragment +fn up(v: V) -> @location(0) vec4 { + let src = vec2(textureDimensions(levelTex)); + let uv = v.pos.xy * 0.5 / src; + let h = 0.5 / src; + var c = textureSampleLevel(levelTex, samp, uv + vec2(-2.0 * h.x, 0.0), 0.0).rgb; + c += textureSampleLevel(levelTex, samp, uv + vec2(2.0 * h.x, 0.0), 0.0).rgb; + c += textureSampleLevel(levelTex, samp, uv + vec2(0.0, -2.0 * h.y), 0.0).rgb; + c += textureSampleLevel(levelTex, samp, uv + vec2(0.0, 2.0 * h.y), 0.0).rgb; + c += textureSampleLevel(levelTex, samp, uv + vec2(-h.x, h.y), 0.0).rgb * 2.0; + c += textureSampleLevel(levelTex, samp, uv + vec2(h.x, h.y), 0.0).rgb * 2.0; + c += textureSampleLevel(levelTex, samp, uv + vec2(-h.x, -h.y), 0.0).rgb * 2.0; + c += textureSampleLevel(levelTex, samp, uv + vec2(h.x, -h.y), 0.0).rgb * 2.0; + // Added into the level above (blend one + one). + return vec4(c / 12.0 * g.a.y, 1.0); +} +`,yi=`// The Darkroom's two full-screen passes (darkroom/darkroom.ts mirrors the curves). +// accumulate: acc = prev·keep + scene · eye-dome shade (solid forms only). +// present: acc / n → glow (glow.wgsl) → vignette → exposure → tone (ACES for light, none for +// ink on paper) → grain → out. + +struct P { + // keep (0 or 1), shade strength, opaque (1 = solid points, eye-dome applies), passes n + a: vec4, + // exposure multiplier, tone mode (0 none, 1 ACES), grain strength, grain seed + b: vec4, + // encode sRGB in the shader (1 for a float target; 0 when an sRGB view encodes), near, far, _ + c: vec4, + // this tile's pixel offset in the whole print (x, y), so grain never repeats across tiles; + // the whole picture's size in pixels (w, h), so glow and vignette span the tiles + d: vec4, + // glow strength (already divided by the levels' total weight), halation (the glow's warmth, + // 0..1), vignette (0..1), _ + e: vec4, +}; + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var sceneTex: texture_2d; +@group(0) @binding(2) var depthTex: texture_depth_2d; +@group(0) @binding(3) var prevTex: texture_2d; +// present only: the glow of the whole picture (glow.wgsl), read with a linear sampler. +@group(0) @binding(4) var glowTex: texture_2d; +@group(0) @binding(5) var glowSamp: sampler; + +struct V { @builtin(position) pos: vec4 }; + +@vertex +fn full(@builtin(vertex_index) i: u32) -> V { + // One triangle that covers the screen. + var xy = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0)); + var o: V; + o.pos = vec4(xy[i], 0.0, 1.0); + return o; +} + +/** Distance from the eye of a depth-buffer value (camera.ts: perspective, WebGPU z in [0, 1]). */ +fn linearDepth(z: f32) -> f32 { + let near = p.c.y; + let far = p.c.z; + let m10 = far / (near - far); + let m14 = near * far / (near - far); + return m14 / (z + m10); +} + +/** Eye-dome lighting (as in Potree): darker where a neighbour is nearer, so forms read as carved. */ +fn eyeDome(px: vec2, size: vec2) -> f32 { + let z = textureLoad(depthTex, px, 0); + if (z >= 1.0) { return 1.0; } + let d = log2(linearDepth(z)); + var res = 0.0; + var offs = array, 8>(vec2(1, 0), vec2(-1, 0), vec2(0, 1), vec2(0, -1), vec2(2, 2), vec2(-2, 2), vec2(2, -2), vec2(-2, -2)); + for (var k = 0; k < 8; k++) { + let q = clamp(px + offs[k], vec2(0), size - vec2(1)); + let zn = textureLoad(depthTex, q, 0); + if (zn >= 1.0) { continue; } + res += max(0.0, d - log2(linearDepth(zn))); + } + return exp(-res / 8.0 * 300.0 * p.a.y); +} + +@fragment +fn accumulate(v: V) -> @location(0) vec4 { + let px = vec2(v.pos.xy); + let size = vec2(textureDimensions(sceneTex)); + var c = textureLoad(sceneTex, px, 0).rgb; + if (p.a.z > 0.5 && p.a.y > 0.0) { c *= eyeDome(px, size); } + // The first pass of a picture starts the sum: no need to read the old one. + if (p.a.x < 0.5) { return vec4(c, 1.0); } + return vec4(textureLoad(prevTex, px, 0).rgb + c, 1.0); +} + +fn pcg(v: u32) -> u32 { + let state = v * 747796405u + 2891336453u; + let word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u; + return (word >> 22u) ^ word; +} + +fn aces(x: vec3) -> vec3 { + let v = max(x, vec3(0.0)); + return clamp((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14), vec3(0.0), vec3(1.0)); +} + +fn encodeSrgb(c: vec3) -> vec3 { + let v = clamp(c, vec3(0.0), vec3(1.0)); + return select(1.055 * pow(v, vec3(1.0 / 2.4)) - 0.055, 12.92 * v, v <= vec3(0.0031308)); +} + +fn decodeSrgb(c: vec3) -> vec3 { + return select(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, c <= vec3(0.04045)); +} + +@fragment +fn present(v: V) -> @location(0) vec4 { + let px = vec2(v.pos.xy); + // In this pass binding 1 holds the accumulated light. + var c = textureLoad(sceneTex, px, 0).rgb / max(p.a.w, 1.0); + // Where this pixel is in the whole picture, 0..1 (a print's tiles share one picture). + let uv = (vec2(px) + vec2(0.5) + p.d.xy) / max(p.d.zw, vec2(1.0)); + // Glow: light spilling around itself, as in a lens and in film (halation is its warm part). + if (p.b.y > 0.5 && p.e.x > 0.0) { + let g = textureSampleLevel(glowTex, glowSamp, uv, 0.0).rgb; + c += g * p.e.x * mix(vec3(1.0), vec3(1.0, 0.42, 0.2), p.e.y); + } + // darkroom.ts: vignette. The corners fall off, as through a real lens. + if (p.e.z > 0.0) { + let q = (uv - vec2(0.5)) * vec2(min(1.0, p.d.z / max(p.d.w, 1.0)), min(1.0, p.d.w / max(p.d.z, 1.0))) * 2.0; + c *= 1.0 - p.e.z * smoothstep(0.45, 1.5, length(q)); + } + if (p.b.y > 0.5) { c = aces(c * p.b.x); } + // Grain in display tone: strongest in the middle tones, as in film. + var d = encodeSrgb(c); + if (p.b.z > 0.0) { + let g = px + vec2(p.d.xy); + let h = pcg(u32(g.x) * 1973u + u32(g.y) * 9277u + u32(p.b.w) * 26699u); + let n = f32(h) / 4294967295.0 - 0.5; + let lum = dot(d, vec3(0.2126, 0.7152, 0.0722)); + d = clamp(d + n * p.b.z * (0.35 + 2.6 * lum * (1.0 - lum)), vec3(0.0), vec3(1.0)); + } + if (p.c.x > 0.5) { return vec4(d, 1.0); } + return vec4(decodeSrgb(d), 1.0); +} +`,bi=`// Point renderer + Temporal Lens. Mirrors apps/viewer/src/lens/*.ts line for line; +// change both together (the TS functions carry the unit tests). + +struct U { + viewProj: mat4x4, + boundsMin: vec4, // xyz + boundsSize: vec4, // xyz + timing: vec4, // tStart, tSpan, dt, t0 + win: vec4, // thickness, tau, period, pulse + win2: vec4, // plateau, profile, combPhase, mappingKind + shear: vec4, // dir.xyz, k + swap: vec4, // axis, k, slit, _ + tiltSlope: vec4, + tiltOrigin: vec4, + drift: vec4, // xyz, turbulence + age: vec4, // fadePast, fadeFuture, noiseScale, shrink + render: vec4, // pointSize (m), minPx, viewportW, viewportH + proj: vec4, // P[0][0], P[1][1], gain, mark fraction + flags: vec4, // tracked identity, hasNext, hasTrack, opaque + mark: vec4, // mark colour rgb, _ + look: vec4, // colour mode (look.ts), age span (s), live span (s, 0 = not live), motion reference (m/s) + colA: vec4, // palette A rgb (sRGB) + colB: vec4, // palette B rgb (sRGB) + dark: vec4, // darkroom: time focus (m per s of age), pass index, frame of the present, _ + thread: vec4, // lens/thread.ts: share of tracks drawn, half-width (m), kind (0 path, 1 repair), _ + wit: vec4, // witness/: show (0 all, 1 seen, 2 unseen), before (0 repaired .. 1 raw lift), doubt (m per s unseen), unseen light + wit2: vec4, // has gap, has raw position, unseen as rings, has motion + optics: vec4, // darkroom.ts lens: focus distance from the eye (m), aperture (m, 0 = everything sharp), largest blur radius (px), _ + colM: vec4, // look.ts: the ramp's middle colour rgb (sRGB), 1 when the ramp has three stops +}; + +@group(0) @binding(0) var u: U; +@group(0) @binding(1) var posBuf: array; +@group(0) @binding(2) var timeBuf: array; +@group(0) @binding(3) var colBuf: array; +@group(0) @binding(4) var trackBuf: array; +@group(0) @binding(5) var nextBuf: array; +@group(0) @binding(6) var auxBuf: array; // lens/motion.ts buildAux: u16 per sample, gap | motion << 8 +@group(0) @binding(7) var rawBuf: array; // format 1.1 rawPosition: u16 ×3, same bounds + +const OFF: f32 = 1e29; // "Infinity" for fades and thickness +const BLUR_BUDGET: f32 = 80.0; // darkroom.ts: pixels a blurred point may cover before it is thinned +const THREAD_BUDGET: f32 = 6.0; // half-width in pixels a blurred thread may have before it is thinned +const PI: f32 = 3.14159265358979; + +fn u16At(i: u32) -> u32 { let w = posBuf[i >> 1u]; return (w >> ((i & 1u) * 16u)) & 0xffffu; } +fn t16At(i: u32) -> u32 { let w = timeBuf[i >> 1u]; return (w >> ((i & 1u) * 16u)) & 0xffffu; } +fn u8At(i: u32) -> u32 { let w = colBuf[i >> 2u]; return (w >> ((i & 3u) * 8u)) & 0xffu; } +fn auxAt(i: u32) -> u32 { let w = auxBuf[i >> 1u]; return (w >> ((i & 1u) * 16u)) & 0xffffu; } +fn r16At(i: u32) -> u32 { let w = rawBuf[i >> 1u]; return (w >> ((i & 1u) * 16u)) & 0xffffu; } + +fn decodePos(i: u32) -> vec3 { + let q = vec3(f32(u16At(3u * i)), f32(u16At(3u * i + 1u)), f32(u16At(3u * i + 2u))); + return u.boundsMin.xyz + q / 65535.0 * u.boundsSize.xyz; +} +fn decodeRaw(i: u32) -> vec3 { + let q = vec3(f32(r16At(3u * i)), f32(r16At(3u * i + 1u)), f32(r16At(3u * i + 2u))); + return u.boundsMin.xyz + q / 65535.0 * u.boundsSize.xyz; +} + +const SRC_LENS: u32 = 0u; // the position the witness's "before" asks for +const SRC_RAW: u32 = 1u; // the raw lift +const SRC_REPAIRED: u32 = 2u; // the repaired position + +/** A point's position: the repaired one, the raw lift, or between (WITNESS "before"). */ +fn posAt(i: u32, src: u32) -> vec3 { + let p = decodePos(i); + if (u.wit2.y == 0u || src == SRC_REPAIRED) { return p; } + if (src == SRC_RAW) { return decodeRaw(i); } + if (u.wit.y <= 0.0) { return p; } + return mix(p, decodeRaw(i), u.wit.y); +} + +fn pcg(v: u32) -> u32 { + let state = v * 747796405u + 2891336453u; + let word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u; + return (word >> 22u) ^ word; +} +fn hash01(v: u32) -> f32 { return f32(pcg(v)) / 4294967295.0; } +fn hash3(seed: u32) -> vec3 { + return vec3(hash01(seed * 3u), hash01(seed * 3u + 1u), hash01(seed * 3u + 2u)) * 2.0 - 1.0; +} + +fn wrapf(x: f32, m: f32) -> f32 { return x - m * floor(x / m); } + +// window.ts: windowWeight +fn windowWeight(t: f32) -> f32 { + let d = t - u.timing.w; + let T = u.win.x; + let half = T * 0.5; + let profile = u32(u.win2.y); + if (profile == 0u) { // box + return select(0.0, 1.0, d >= -half && d < half); + } + if (profile == 1u) { // decay + let a = -d; + if (a < 0.0 || a > T) { return 0.0; } + if (u.win.y > 0.0) { return exp(-a / u.win.y); } + return select(0.0, 1.0, a == 0.0); + } + if (profile == 2u) { // comb + if (!(d >= -half && d < half) || u.win.z <= 0.0) { return 0.0; } + let r = select(t, d, u.win2.z > 0.5); + let ph = wrapf(r + u.win.w * 0.5, u.win.z); + return select(0.0, 1.0, ph < u.win.w); + } + // saddle + let ad = abs(d); + if (ad > half) { return 0.0; } + let flat = half * clamp(u.win2.x, 0.0, 1.0); + if (ad <= flat) { return 1.0; } + let x = (ad - flat) / (half - flat); + return 0.5 * (1.0 + cos(PI * x)); +} + +struct Mapped { p: vec3, t: f32 }; + +// mapping.ts: mapPoint +fn mapPoint(p: vec3, t: f32) -> Mapped { + let t0 = u.timing.w; + let kind = u32(u.win2.w); + if (kind == 1u) { // shear + return Mapped(p + u.shear.xyz * (u.shear.w * (t - t0)), t); + } + if (kind == 2u) { // swapXT + let axis = u32(u.swap.x); + let k = u.swap.y; + let slit = u.swap.z; + var q = p; + q[axis] = slit - k * (t - t0); + var tt = t; + if (k != 0.0) { tt = t0 - (p[axis] - slit) / k; } + return Mapped(q, tt); + } + if (kind == 3u) { // tilt + return Mapped(p, t - dot(u.tiltSlope.xyz, p - u.tiltOrigin.xyz)); + } + return Mapped(p, t); +} + +/** sRGB transfer function, decoded: colours are stored as sRGB, light is added linearly. */ +fn srgbToLinear(c: vec3) -> vec3 { + return select(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, c <= vec3(0.04045)); +} + +struct VOut { + @builtin(position) pos: vec4, + @location(0) uv: vec2, + @location(1) color: vec4, + @location(2) @interpolate(flat) seed: u32, + @location(3) @interpolate(flat) ring: f32, +}; + +fn hidden() -> VOut { + var o: VOut; + o.pos = vec4(2.0, 2.0, 2.0, 1.0); + o.uv = vec2(0.0); + o.color = vec4(0.0); + o.seed = 0u; + o.ring = 0.0; + return o; +} + +/** One sample through the lens: where it goes, its light (0 outside the window), size and colour. */ +struct LP { + p: vec3, + alpha: f32, + size: f32, + rgb: vec3, + seed: u32, + ok: bool, // false: not there at all (an empty live slot, or filtered out by the witness) + ring: f32, // 1: drawn as a ring (unseen by the camera) +}; + +fn nothing() -> LP { + return LP(vec3(0.0), 0.0, 0.0, vec3(0.0), 0u, false, 0.0); +} + +/** + * The full chain for one sample (lens.ts: evaluateLens; thread.ts: evaluateEnd). + * lerpTracked: slide toward the next frame of the track (points); threads use the samples as they are. + */ +fn lensEval(ii: u32, lerpTracked: bool, src: u32) -> LP { + let t0 = u.timing.w; + let dt = u.timing.z; + var p = posAt(ii, src); + let tq = t16At(ii); + var t = u.timing.x + f32(tq) / 65535.0 * u.timing.y; + // live/ring.ts: a live ring stores time modulo its span (unwrapTime); 65535 is an empty point. + let liveSpan = u.look.z; + if (liveSpan > 0.0) { + if (tq == 65535u) { return nothing(); } + t = t0 - wrapf(t0 - t, liveSpan); + } + + // witness/gap.ts: frames since (or until) the camera saw this track; 0 = seen now. + var gap = 0u; + if (u.wit2.x == 1u) { + gap = auxAt(ii) & 0xffu; + let show = u32(u.wit.x); + if ((show == 1u && gap > 0u) || (show == 2u && gap == 0u)) { return nothing(); } + } + + // lens.ts: segmentTime + tracked interpolation + var ts = t; + var a = 0.0; + if (lerpTracked && dt > 0.0) { + let off = min(max(t0 - t, 0.0), dt * 0.9999); + ts = t + off; + a = off / dt; + } + let tracked = u.flags.x == 1u; + if (lerpTracked && tracked && u.flags.y == 1u && a > 0.0) { + let n = nextBuf[ii]; + if (n >= 0) { p = mix(p, posAt(u32(n), src), a); } + } + + var seed = ii; + if (tracked && u.flags.z == 1u) { + let tid = trackBuf[ii]; + if (tid != 0xffffffffu) { seed = tid; } + } + + let m = mapPoint(p, ts); + var alpha = windowWeight(m.t); + + // age.ts: ageForces + let age = t0 - ts; + let aa = abs(age); + if (age > 0.0 && u.age.x < OFF) { alpha *= select(0.0, exp(-age / u.age.x), u.age.x > 0.0); } + if (age < 0.0 && u.age.y < OFF) { alpha *= select(0.0, exp(age / u.age.y), u.age.y > 0.0); } + let s = u.age.z; + let swirl = vec3(sin(m.p.y * s + 1.7), sin(m.p.z * s + 4.1), sin(m.p.x * s + 2.3)); + let n3 = 0.65 * hash3(seed) + 0.35 * swirl; + var pa = m.p + (u.drift.xyz + u.drift.w * n3) * aa; + // darkroom.ts: time focus. Each pass moves a point by a new random offset whose size + // grows with its age, so as passes accumulate the past goes soft and the present stays sharp. + if (u.dark.x > 0.0) { + let k = pcg(seed ^ (u32(u.dark.y) * 0x2c1b3c6du + 0x85ebca6bu)); + let dir = hash3(k); + pa += dir * (u.dark.x * aa) * sqrt(hash01(k ^ 0x68e31da4u)); + } + var size = exp(-aa * u.age.w); + + var ring = 0.0; + if (gap > 0u) { + // Doubt: the longer a track goes unseen, the wider the cloud it may be in. A new offset + // each frame of the present while it plays, and each pass while it develops. + if (u.wit.z > 0.0 && dt > 0.0) { + let k = pcg(seed ^ (u32(u.dark.y) * 0x632be5abu) ^ (u32(u.dark.z) * 0x85157af5u) ^ 0x1b873593u); + // A track never seen (gap 255) doubts no more than one unseen for 1.5 s. + let unseen = min(f32(gap) * dt, 1.5); + pa += hash3(k) * (u.wit.z * unseen) * sqrt(hash01(k ^ 0x5bd1e995u)); + } + alpha *= u.wit.w; + if (u.wit2.z == 1u) { ring = 1.0; size *= 1.6; } + } + + var rgb = vec3(f32(u8At(3u * ii)), f32(u8At(3u * ii + 1u)), f32(u8At(3u * ii + 2u))) / 255.0; + // look.ts: palette colouring, shaded by the captured brightness so the form still reads. + let mode = u32(u.look.x); + if (mode != 0u) { + let lum = dot(rgb, vec3(0.299, 0.587, 0.114)); + let shade = 0.3 + 0.7 * clamp(lum * 1.6, 0.0, 1.0); + var g = 0.0; + if (mode == 2u) { g = clamp(aa / max(u.look.y, 1e-3), 0.0, 1.0); } + if (mode == 3u) { g = clamp((t - u.timing.x) / max(u.timing.y, 1e-6), 0.0, 1.0); } + if (mode == 4u) { g = hash01(seed ^ 0x51ed270bu); } + if (mode == 5u) { + // lens/motion.ts: speed relative to the body's own motion (decodeMotion), or, for a + // block without it (a live ring), plain speed (thread.ts: speedOf). motionFraction: rest + // is colour A, motion at the reference speed B. + var speed = 0.0; + if (u.wit2.w == 1u) { + let f = f32(auxAt(ii) >> 8u) / 255.0; + speed = f * f * 4.0; + } else if (u.flags.y == 1u && dt > 0.0) { + let n = nextBuf[ii]; + if (n >= 0) { speed = length(decodePos(u32(n)) - decodePos(ii)) / dt; } + } + g = sqrt(clamp(speed / max(u.look.w, 1e-3), 0.0, 1.0)); + } + // look.ts: rampColor. Two stops, or three with a middle colour at g = 0.5. + var ramp = mix(u.colA.rgb, u.colB.rgb, g); + if (u.colM.w > 0.5) { + if (g < 0.5) { ramp = mix(u.colA.rgb, u.colM.rgb, g * 2.0); } + else { ramp = mix(u.colM.rgb, u.colB.rgb, g * 2.0 - 1.0); } + } + rgb = ramp * shade; + } + if (u.proj.w > 0.0 && hash01(seed ^ 0x9e3779b9u) < u.proj.w) { rgb = u.mark.rgb; } + // Light adds in linear space; the render target is an sRGB view that encodes it for display. + return LP(pa, alpha, size, srgbToLinear(rgb), seed, true, ring); +} + +/** + * darkroom.ts: cocRadius. The lens: a point at distance d from the eye, with the focus at f and + * an opening A, is drawn as a disc of radius A/2 · |d − f| / f (metres, at the point's own + * distance). Light that adds up needs no sorting, so for light this is a true thin lens. + */ +fn cocRadius(d: f32) -> f32 { + if (u.optics.y <= 0.0) { return 0.0; } + return 0.5 * u.optics.y * abs(d - u.optics.x) / max(u.optics.x, 1e-3); +} + +@vertex +fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut { + let L = lensEval(ii, true, SRC_LENS); + if (!L.ok || L.alpha < 0.002) { return hidden(); } // below a 1/255 step: skip the quad + var alpha = L.alpha; + + var clip = u.viewProj * vec4(L.p, 1.0); + var corners = array, 6>( + vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(-1.0, 1.0), + vec2(-1.0, 1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), + ); + let corner = corners[vi]; + let r = u.render.x * L.size; + // Out of focus, the point is a disc as wide as the lens's circle of confusion. + let coc = cocRadius(clip.w); + let rb = sqrt(r * r + coc * coc); + let perPx = vec2(2.0 / u.render.z, 2.0 / u.render.w) * clip.w; + let minClip = u.render.y * perPx; + var rad = max(vec2(rb * u.proj.x, rb * u.proj.y), minClip); + if (coc > 0.0) { + rad = min(rad, max(u.optics.z * perPx, minClip)); + // darkroom.ts: blurKeep. A wide disc holds little light per pixel and costs many pixels: + // only some are drawn, each with the light of those left out, so the sum stays the same. + // A new choice each pass, so a developed image converges on every disc. + let keep = min(1.0, BLUR_BUDGET / (PI * (rad.x / perPx.x) * (rad.y / perPx.y))); + if (keep < 1.0) { + if (hash01(pcg(ii ^ 0x7f4a7c15u) ^ (u32(u.dark.y) * 0x9e3779b9u)) > keep) { return hidden(); } + alpha /= keep; + } + } + clip = vec4(clip.xy + corner * rad, clip.zw); + // look.ts: footprintCoverage. A point drawn larger than its true size (the minimum + // pixel size, or a disc out of focus) gives only the light, or the coverage, its true size + // holds, so brightness does not depend on screen size, distance or focus. + let cover = clamp((r * u.proj.x) / max(rad.x, 1e-12), 0.0, 1.0); + alpha *= cover * cover; + + var o: VOut; + o.pos = clip; + o.uv = corner; + o.color = vec4(L.rgb, alpha); + o.seed = ii; + o.ring = L.ring; + return o; +} + +const THREAD_SALT: u32 = 0x3c6ef372u; // thread.ts: threadKept + +/** + * TRACE (lens/thread.ts): a sample drawn as a thread to the same track one frame later, so + * every point leaves its path. Kind 1 (WITNESS): the thread runs from the raw lift to the + * repaired position, the repair itself made visible. Both ends go through the same lens. + */ +@vertex +fn vsThread(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut { + var key = ii; + if (u.flags.z == 1u) { + let tid = trackBuf[ii]; + if (tid != 0xffffffffu) { key = tid; } + } + if (hash01(key ^ THREAD_SALT) >= u.thread.x) { return hidden(); } + var A: LP; + var B: LP; + if (u.thread.z < 0.5) { + if (u.flags.y == 0u) { return hidden(); } + let n = nextBuf[ii]; + if (n < 0) { return hidden(); } + A = lensEval(ii, false, SRC_LENS); + B = lensEval(u32(n), false, SRC_LENS); + } else { + if (u.wit2.y == 0u) { return hidden(); } + A = lensEval(ii, false, SRC_RAW); + B = lensEval(ii, false, SRC_REPAIRED); + } + if (!A.ok || !B.ok || max(A.alpha, B.alpha) < 0.002) { return hidden(); } + + let ca = u.viewProj * vec4(A.p, 1.0); + let cb = u.viewProj * vec4(B.p, 1.0); + if (ca.w <= 0.05 || cb.w <= 0.05) { return hidden(); } // behind the camera + // corner.x: 0 at A, 1 at B; corner.y: −1..1 across the thread. + var corners = array, 6>( + vec2(0.0, -1.0), vec2(1.0, -1.0), vec2(0.0, 1.0), + vec2(0.0, 1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), + ); + let corner = corners[vi]; + let res = u.render.zw; + let d = (cb.xy / cb.w - ca.xy / ca.w) * res; + let len = length(d); + let dir = select(vec2(1.0, 0.0), d / len, len > 1e-6); + let nrm = vec2(-dir.y, dir.x); + let atB = corner.x > 0.5; + var clip = select(ca, cb, atB); + var L = A; + if (atB) { L = B; } + // Half-width in pixels at this end: its true width, or the minimum, which keeps only + // the light its true width holds (thread.ts: lineCoverage). + let truePx = u.thread.y * L.size * u.proj.x / clip.w * res.x * 0.5; + // Out of focus, the thread widens by the lens's circle of confusion (cocRadius). + let cocPx = cocRadius(clip.w) * u.proj.x / clip.w * res.x * 0.5; + var px = max(sqrt(truePx * truePx + cocPx * cocPx), u.render.y); + var thin = 1.0; + if (cocPx > 0.0) { + px = min(px, max(u.optics.z, u.render.y)); + // As for points (blurKeep): a thread blurred wide is drawn less often, with more light. + thin = min(1.0, THREAD_BUDGET / px); + if (thin < 1.0 && hash01(pcg(ii ^ 0x7f4a7c15u) ^ (u32(u.dark.y) * 0x9e3779b9u)) > thin) { return hidden(); } + } + clip = vec4(clip.xy + nrm * corner.y * px * 2.0 / res * clip.w, clip.zw); + let cover = clamp(truePx / max(px, 1e-6), 0.0, 1.0); + + var o: VOut; + o.pos = clip; + o.uv = vec2(corner.y, 0.0); + o.color = vec4(L.rgb, L.alpha * cover / thin); + o.seed = ii; + o.ring = 0.0; + return o; +} + +@fragment +fn fsAdd(i: VOut) -> @location(0) vec4 { + let r2 = dot(i.uv, i.uv); + if (r2 > 1.0) { discard; } + var soft = 1.0 - r2 * r2; + // An unseen point is light around a hole: present as an absence. + if (i.ring > 0.5) { soft *= smoothstep(0.3, 0.6, r2); } + let a = i.color.a * u.proj.z * soft; + return vec4(i.color.rgb * a, a); +} + +@fragment +fn fsOpaque(i: VOut) -> @location(0) vec4 { + let r2 = dot(i.uv, i.uv); + if (r2 > 1.0) { discard; } + // An unseen point is ink around a hole (ReLift's own drawing: a ring is filled in). + if (i.ring > 0.5 && r2 < 0.45) { discard; } + // Stochastic transparency: order-independent, so no depth sort is needed. + let px = vec2(i.pos.xy); + // The pass index makes each pass draw a new pattern, so accumulated passes converge on true transparency. + if (i.color.a < 1.0 && hash01(px.x * 1973u + px.y * 9277u + i.seed * 26699u + u32(u.dark.y) * 0x9e3779b9u) > i.color.a) { discard; } + return vec4(i.color.rgb, 1.0); +} +`,xi={box:0,decay:1,comb:2,saddle:3},Si={identity:0,shear:1,swapXT:2,tilt:3},Ci=1e30,wi=e=>Number.isFinite(e)?e:Ci,Ti=448,Ei={all:0,seen:1,unseen:2},Di=80,Oi=2048,ki=24,Ai=.05,ji=200,Mi=2048,Ni=class extends Error{};function Pi(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(t.byteLength%4==0&&t.byteLength>0)return t;let n=new Uint8Array(Math.max(4,Math.ceil(t.byteLength/4)*4));return n.set(t),n}function Fi(e){let t=e&32768?-1:1,n=e>>10&31,r=e&1023;return n===0?t*r*2**-24:n===31?r?NaN:t*(1/0):t*(1+r/1024)*2**(n-15)}var Ii=class e{device;context;format;canvas;uniform;postAcc;postPresent;glowBuf;glowFirstPipe;glowDownPipe;glowUpPipe;glowFirstLayout;glowLevelLayout;linear;uniformData=new ArrayBuffer(Ti);pipelines;threadPipelines;accumulatePipe;presentPipe;presentFloatPipe;accLayout;presentLayout;bindGroup=null;buffers=[];display=null;target=null;block=null;hasNext=!1;hasGap=!1;hasMotion=!1;hasRaw=!1;adapter=null;cur=0;constructor(e,t,n,r){this.device=e,this.context=t,this.format=n,this.canvas=r,this.view=Li(n),this.uniform=e.createBuffer({size:Ti,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.postAcc=e.createBuffer({size:Di,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.postPresent=e.createBuffer({size:Di,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.glowBuf=e.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.linear=e.createSampler({magFilter:`linear`,minFilter:`linear`,addressModeU:`clamp-to-edge`,addressModeV:`clamp-to-edge`});let i=e.createShaderModule({code:bi}),a=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:`uniform`}},...[1,2,3,4,5,6,7].map(e=>({binding:e,visibility:GPUShaderStage.VERTEX,buffer:{type:`read-only-storage`}}))]});this.layout=a;let o=e.createPipelineLayout({bindGroupLayouts:[a]}),s=(t,n=`vs`)=>e.createRenderPipeline({layout:o,vertex:{module:i,entryPoint:n},fragment:{module:i,entryPoint:t===`additive`?`fsAdd`:`fsOpaque`,targets:[{format:`rgba16float`,...t===`additive`?{blend:{color:{srcFactor:`one`,dstFactor:`one`,operation:`add`},alpha:{srcFactor:`one`,dstFactor:`one`,operation:`add`}}}:{}}]},primitive:{topology:`triangle-list`},depthStencil:{format:`depth24plus`,depthWriteEnabled:t===`opaque`,depthCompare:t===`opaque`?`less`:`always`}});this.pipelines={additive:s(`additive`),opaque:s(`opaque`)},this.threadPipelines={additive:s(`additive`,`vsThread`),opaque:s(`opaque`,`vsThread`)};let c=e.createShaderModule({code:yi}),l=e=>({binding:e,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:`unfilterable-float`}}),u={binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:`uniform`}};this.accLayout=e.createBindGroupLayout({entries:[u,l(1),{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:`depth`}},l(3)]}),this.presentLayout=e.createBindGroupLayout({entries:[u,l(1),{binding:4,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:`float`}},{binding:5,visibility:GPUShaderStage.FRAGMENT,sampler:{type:`filtering`}}]});let d=e.createShaderModule({code:vi});this.glowFirstLayout=e.createBindGroupLayout({entries:[u,l(1)]}),this.glowLevelLayout=e.createBindGroupLayout({entries:[u,{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:`float`}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{type:`filtering`}}]});let f=(t,n,r)=>e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[t]}),vertex:{module:d,entryPoint:`full`},fragment:{module:d,entryPoint:n,targets:[{format:`rgba16float`,...r?{blend:{color:{srcFactor:`one`,dstFactor:`one`,operation:`add`},alpha:{srcFactor:`zero`,dstFactor:`one`,operation:`add`}}}:{}}]},primitive:{topology:`triangle-list`}});this.glowFirstPipe=f(this.glowFirstLayout,`first`,!1),this.glowDownPipe=f(this.glowLevelLayout,`down`,!1),this.glowUpPipe=f(this.glowLevelLayout,`up`,!0);let p=(t,n,r)=>e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[t]}),vertex:{module:c,entryPoint:`full`},fragment:{module:c,entryPoint:n,targets:[{format:r}]},primitive:{topology:`triangle-list`}});this.accumulatePipe=p(this.accLayout,`accumulate`,`rgba32float`),this.measureLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`unfilterable-float`}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}}]}),this.measurePipe=e.createComputePipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this.measureLayout]}),compute:{module:e.createShaderModule({code:_i}),entryPoint:`measure`}});let m=de[0]*de[1]*4;this.cellBuf=e.createBuffer({size:m,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this.cellRead=e.createBuffer({size:m,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this.presentPipe=p(this.presentLayout,`present`,this.view),this.presentFloatPipe=p(this.presentLayout,`present`,`rgba16float`)}layout;measureLayout;measurePipe;cellBuf;cellRead;metering=!1;measureBinds=new WeakMap;presented=null;view;static async create(t,n=!1){if(!(`gpu`in navigator))throw new Ni(`This browser has no WebGPU.`);let r=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!r)throw new Ni(`No WebGPU adapter was found.`);let i=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),a=n?null:t.getContext(`webgpu`);if(!n&&!a)throw new Ni(`Could not get a WebGPU canvas context.`);i.addEventListener(`uncapturederror`,e=>console.error(`WebGPU:`,e.error.message));let o=n?`rgba8unorm`:navigator.gpu.getPreferredCanvasFormat(),s=new e(i,a,o,t);return s.adapter=r,s}attach(){this.context?.configure({device:this.device,format:this.format,alphaMode:`opaque`,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,viewFormats:[this.view]})}setBlock(e,t,n=null){for(let e of this.buffers)e.destroy();if(this.buffers=[],!(e.position instanceof Uint16Array)||!(e.time instanceof Uint16Array))throw Error(`The viewer reads u16 position and time sections (the format's default).`);let r=e=>{let t=Pi(e),n=this.device.createBuffer({size:t.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});return this.device.queue.writeBuffer(n,0,t),this.buffers.push(n),n},i=r(e.position),a=r(e.time),o=r(e.color),s=r(e.trackId??new Uint32Array(1)),c=r(t??new Int32Array(1)),l=r(n?.data??new Uint16Array(2)),u=r(e.rawPosition??new Uint16Array(2));this.bindGroup=this.device.createBindGroup({layout:this.layout,entries:[this.uniform,i,a,o,s,c,l,u].map((e,t)=>({binding:t,resource:{buffer:e}}))}),this.block=e,this.hasNext=t!==null,this.hasGap=!!n?.gap,this.hasMotion=!!n?.motion,this.hasRaw=!!e.rawPosition}updateRange(e,t,n){if(e!==this.block||this.buffers.length<3)return;let[r,i,a]=this.buffers,o=e.position,s=e.time,c=e.color,l=this.device.queue;l.writeBuffer(r,t*6,o.buffer,o.byteOffset+t*6,n*6),l.writeBuffer(i,t*2,s.buffer,s.byteOffset+t*2,n*2),l.writeBuffer(a,t*3,c.buffer,c.byteOffset+t*3,n*3)}makeTargets(e,t){let n=this.device,r=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,i=n.createTexture({size:[e,t],format:`rgba16float`,usage:r}),a=n.createTexture({size:[e,t],format:`depth24plus`,usage:r}),o=[0,1].map(()=>n.createTexture({size:[e,t],format:`rgba32float`,usage:r})),s=[0,1].map(e=>n.createBindGroup({layout:this.accLayout,entries:[{binding:0,resource:{buffer:this.postAcc}},{binding:1,resource:i.createView()},{binding:2,resource:a.createView()},{binding:3,resource:o[e].createView()}]})),c=fe(Math.min(e,t)),l=[];for(let i=0,a=e,o=t;i>1),o=Math.max(1,o>>1),l.push(n.createTexture({size:[a,o],format:`rgba16float`,usage:r}));let u=l.map(e=>e.createView()),d={binding:0,resource:{buffer:this.glowBuf}},f={w:e,h:t,scene:i,depth:a,acc:o,accBind:s,presentBind:null,glow:{tex:l,views:u,first:[0,1].map(e=>n.createBindGroup({layout:this.glowFirstLayout,entries:[d,{binding:1,resource:o[e].createView()}]})),read:u.map(e=>n.createBindGroup({layout:this.glowLevelLayout,entries:[d,{binding:2,resource:e},{binding:3,resource:this.linear}]}))}};return f.presentBind=this.presentBinds(f,u[0]),f}presentBinds(e,t){return[0,1].map(n=>this.device.createBindGroup({layout:this.presentLayout,entries:[{binding:0,resource:{buffer:this.postPresent}},{binding:1,resource:e.acc[n].createView()},{binding:4,resource:t},{binding:5,resource:this.linear}]}))}presentUniforms(e,t,n,r,i,a,o,s){let c=n&&t.glow>0?t.glow*he(t.glowSpread,s):0;return new Float32Array([0,0,0,e,2**t.ev,+!!n,t.grain,r,+!!i,Ai,ji,0,a[0],a[1],o[0],o[1],c,t.halation,t.vignette,0])}glowChain(e,t,n,r,i){let{glow:a}=t;this.device.queue.writeBuffer(this.glowBuf,0,new Float32Array([1/Math.max(1,r),T(i.glowSpread),0,0]));let o=(t,n,r,i)=>{let a=e.beginRenderPass({colorAttachments:[{view:t,clearValue:{r:0,g:0,b:0,a:1},loadOp:i?`load`:`clear`,storeOp:`store`}]});a.setPipeline(n),a.setBindGroup(0,r),a.draw(3),a.end()};o(a.views[0],this.glowFirstPipe,a.first[n],!1);for(let e=0;e+1=0;e--)o(a.views[e],this.glowUpPipe,a.read[e+1],!0)}static dropTargets(e){if(e){e.scene.destroy(),e.depth.destroy(),e.acc[0].destroy(),e.acc[1].destroy();for(let t of e.glow.tex)t.destroy()}}pass(e,t,n,r,i,a,o,s,c,l,u,d){let{device:f}=this;this.writeUniforms(i,a,o,e.w,e.h,l,u);let p=l.darkroom,m=o.blend===`additive`,h=1-t,g=l.pass+1;f.queue.writeBuffer(this.postAcc,0,new Float32Array([+(l.pass>0),p.shade,+!m,g,0,0,0,0,0,Ai,ji,0,0,0,0,0]));let _=u?u.tx*e.w:0,v=u?u.ty*e.h:0,y=u?[u.nx*e.w,u.ny*e.h]:[e.w,e.h];f.queue.writeBuffer(this.postPresent,0,this.presentUniforms(g,p,m,l.grainSeed??0,r,[_,v],y,d?.levels??e.glow.views.length));let b=f.createCommandEncoder(),[x,S,C]=o.background.map(Ri),w=b.beginRenderPass({colorAttachments:[{view:e.scene.createView(),clearValue:{r:x,g:S,b:C,a:1},loadOp:`clear`,storeOp:`store`}],depthStencilAttachment:{view:e.depth.createView(),depthClearValue:1,depthLoadOp:`clear`,depthStoreOp:`store`}});this.bindGroup&&c>0&&(w.setBindGroup(0,this.bindGroup),(!o.thread||o.thread.points)&&(w.setPipeline(this.pipelines[o.blend]),w.draw(6,c,0,s)),o.thread&&(w.setPipeline(this.threadPipelines[o.blend]),w.draw(6,c,0,s))),w.end();let T=l.measure&&!this.metering?l.measure:null;if(T){let t=this.measureBinds.get(e.scene);t||(t=f.createBindGroup({layout:this.measureLayout,entries:[{binding:0,resource:e.scene.createView()},{binding:1,resource:{buffer:this.cellBuf}}]}),this.measureBinds.set(e.scene,t));let n=b.beginComputePass();n.setPipeline(this.measurePipe),n.setBindGroup(0,t),n.dispatchWorkgroups(Math.ceil(de[0]/8),Math.ceil(de[1]/8)),n.end(),b.copyBufferToBuffer(this.cellBuf,0,this.cellRead,0,this.cellRead.size)}let E=b.beginRenderPass({colorAttachments:[{view:e.acc[h].createView(),clearValue:{r:0,g:0,b:0,a:1},loadOp:`clear`,storeOp:`store`}]});if(E.setPipeline(this.accumulatePipe),E.setBindGroup(0,e.accBind[t]),E.draw(3),E.end(),m&&p.glow>0&&!d&&this.glowChain(b,e,h,g,p),n){let t=b.beginRenderPass({colorAttachments:[{view:n,clearValue:{r:0,g:0,b:0,a:1},loadOp:`clear`,storeOp:`store`}]});t.setPipeline(r?this.presentFloatPipe:this.presentPipe),t.setBindGroup(0,(d?.bind??e.presentBind)[h]),t.draw(3),t.end()}return f.queue.submit([b.finish()]),T&&(this.metering=!0,this.cellRead.mapAsync(GPUMapMode.READ).then(()=>{let e=new Float32Array(this.cellRead.getMappedRange().slice(0));this.cellRead.unmap(),this.metering=!1,T(e)},()=>{this.metering=!1})),!r&&n&&(this.presented={n:g,additive:m}),h}represent(e,t=1){let n=this.display,r=this.presented;if(!n||!r)return;let{device:i}=this;i.queue.writeBuffer(this.postPresent,0,this.presentUniforms(r.n,e,r.additive,t,!1,[0,0],[n.w,n.h],n.glow.views.length));let a=i.createCommandEncoder(),o=this.currentTexture().createView({format:this.view}),s=a.beginRenderPass({colorAttachments:[{view:o,clearValue:{r:0,g:0,b:0,a:1},loadOp:`clear`,storeOp:`store`}]});s.setPipeline(this.presentPipe),s.setBindGroup(0,n.presentBind[this.cur]),s.draw(3),s.end(),i.queue.submit([a.finish()])}meter(e,t,n,r,i,a){return new Promise(o=>{let s=()=>{if(this.metering)return void setTimeout(s,10);this.draw(e,t,n,r,i,{pass:0,darkroom:a,measure:o})};s()})}draw(t,n,r,i,a,o={pass:0,darkroom:ne()}){let{canvas:s,device:c}=this,l=s.width,u=s.height;(!this.display||this.display.w!==l||this.display.h!==u)&&(e.dropTargets(this.display),this.display=this.makeTargets(l,u),this.cur=0),!this.context&&(!this.target||this.target.width!==l||this.target.height!==u)&&(this.target?.destroy(),this.target=c.createTexture({size:[l,u],format:this.format,viewFormats:[this.view],usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}));let d=this.currentTexture().createView({format:this.view});this.cur=this.pass(this.display,this.cur,d,!1,t,n,r,i,a,o)}async capture(e,t,n,r,i,a=1,o=ne(),s){for(let c=0;c1&&o.blend===`additive`&&l.glow>0){let e=Math.min(1,Oi/Math.max(m*g,h*_));T=this.makeTargets(Math.max(2,Math.round(m*g*e)),Math.max(2,Math.round(h*_*e)));let t=0,n=Math.min(r,ki);for(let e=0;e=n)break;for(let e=0;e=t)break;let a=r*S/2+e*4,o=(i*t+n)*3;for(let e=0;e<3;e++)C[o+e]=Math.round(Math.min(1,Math.max(0,Fi(T[a+e])))*65535)}}x.unmap()}}finally{e.dropTargets(T),f||this.releaseHeld()}return C}held=null;releaseHeld(){let t=this.held;this.held=null,t&&(t.read.destroy(),t.out.destroy(),e.dropTargets(t.t))}get offscreen(){return this.context===null}currentTexture(){return this.context?this.context.getCurrentTexture():this.target}writeUniforms(e,t,n,r,i,o,s){let c=new Float32Array(this.uniformData),l=new Uint32Array(this.uniformData),{viewProj:u,proj:d}=S(t,s?s.fullAspect:r/i),f=s?a(s.tx,s.ty,s.nx,s.ny):{sx:1,sy:1,ox:0,oy:0},[p,m]=me(o.pass),h=f.ox+2*p/r,g=f.oy-2*m/i,_=Float32Array.from(u);for(let e=0;e<4;e++)_[e*4]=u[e*4]*f.sx+h*u[e*4+3],_[e*4+1]=u[e*4+1]*f.sy+g*u[e*4+3];c.set(_,0);let v=this.block?.header,y=v?.bounds.min??[0,0,0],b=v?.bounds.max??[0,0,0],x=v?.fps??0,w=e.window,T=e.mapping,E=e.age,D=(e,t,n,r,i)=>c.set([t,n,r,i],16+e*4);D(0,y[0],y[1],y[2],0),D(1,b[0]-y[0],b[1]-y[1],b[2]-y[2],0),D(2,v?.time.start??0,(v?.time.end??0)-(v?.time.start??0),x>0?1/x:0,w.t0),D(3,wi(w.thickness),w.tau,w.period,w.pulse),D(4,w.plateau,xi[w.profile],+(w.combPhase===`now`),Si[T.kind]),D(5,...T.shear.dir,T.shear.k),D(6,T.swap.axis,T.swap.k,T.swap.slit,0),D(7,...T.tilt.slope,0),D(8,...T.tilt.origin,0),D(9,...E.drift,E.turbulence),D(10,wi(E.fadePast),wi(E.fadeFuture),E.noiseScale,E.shrink),D(11,n.pointSize/2,n.minPx,r,i),D(12,d[0]*f.sx,d[5]*f.sy,n.gain,n.mark),l.set([+(e.identity===`tracked`),+!!this.hasNext,+!!this.block?.trackId,+(n.blend===`opaque`)],68),D(14,...n.markColor,0);let te=n.palette,ne=typeof v?.meta?.liveSpan==`number`?v.meta.liveSpan:0;D(15,te?.mode??0,te?.ageSpan??1,ne,te?.motionRef??1.5),D(16,...te?.a??[1,1,1],0),D(23,...te?.m??[1,1,1],+!!te?.m),D(22,C(t.distance,o.darkroom),o.darkroom.aperture,ee*(s?i*s.ny:i),0),D(17,...te?.b??[1,1,1],0),D(18,o.pass>0?o.darkroom.timeFocus:0,o.pass,x>0?Math.floor(w.t0*x):0,0);let re=n.thread,O=n.witness;D(19,re?.share??0,(re?.width??0)/2,+(re?.kind===`repair`),0),D(20,Ei[O?.show??`all`],O?.before??0,O?.doubt??0,O?.unseenLight??1),l.set([+!!this.hasGap,+!!this.hasRaw,+!!O?.rings,+!!this.hasMotion],100),this.device.queue.writeBuffer(this.uniform,0,this.uniformData)}destroy(){this.releaseHeld(),this.cellBuf.destroy(),this.cellRead.destroy();for(let e of this.buffers)e.destroy();this.uniform.destroy(),this.postAcc.destroy(),this.postPresent.destroy(),this.glowBuf.destroy(),e.dropTargets(this.display),this.target?.destroy(),this.device.destroy()}};function Li(e){return e===`bgra8unorm`?`bgra8unorm-srgb`:e===`rgba8unorm`?`rgba8unorm-srgb`:e}function Ri(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function zi(e){return e.profile===`decay`?[e.t0-e.thickness,e.t0]:[e.t0-e.thickness/2,e.t0+e.thickness/2]}function Bi(e,t,n=0){let r=e.mapping.kind;if(r===`swapXT`||r===`tilt`)return t;let[i,a]=zi(e.window);return[Math.max(t[0],i-n),Math.min(t[1],a)]}function Vi(e){return e.coarsePointer||e.deviceMemory!==void 0&&e.deviceMemory<=4?`walker-2m`:`walker`}function Hi(){return{deviceMemory:navigator.deviceMemory,coarsePointer:matchMedia?.(`(pointer: coarse)`).matches??!1}}function Ui(){return typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}function Wi(e,t){try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}function Gi(e){let{header:t,frameStart:n,position:r}=e,{min:i,max:a}=t.bounds;if(!n||t.frameCount<1||!(r instanceof Uint16Array))return Float32Array.from([...i,...a]);let o=new Float32Array(t.frameCount*6),s=[(a[0]-i[0])/65535,(a[1]-i[1])/65535,(a[2]-i[2])/65535];for(let e=0;el[t]&&(l[t]=n)}a<=t&&(c.fill(0),l.fill(65535));for(let t=0;t<3;t++)o[e*6+t]=i[t]+c[t]*s[t],o[e*6+3+t]=i[t]+l[t]*s[t]}return o}function U(e,t,n,r,i){let a=e.length/6,o=0,s=a-1;a>1&&n>0&&(o=Math.max(0,Math.min(a-1,Math.floor((r-t.start)*n+1e-6))),s=Math.max(o,Math.min(a-1,Math.floor((i-t.start)*n+1e-6))));let c=[1/0,1/0,1/0],l=[-1/0,-1/0,-1/0];for(let t=o;t<=s;t++)for(let n=0;n<3;n++)c[n]=Math.min(c[n],e[t*6+n]),l[n]=Math.max(l[n],e[t*6+3+n]);return{min:c,max:l}}var W=e=>Number.isFinite(e)?4*e:1/0;function Ki(e,t){let{window:n,mapping:r,age:i}=e;if(r.kind!==`identity`)return{ta:t.start,tb:t.end,spread:0};let[a,o]=zi(n),s=n.t0;n.profile===`decay`&&(a=Math.max(a,s-W(n.tau))),a=Math.max(a,s-W(i.fadePast)),o=Math.min(o,s+W(i.fadeFuture)),a=Math.max(t.start,a),o=Math.min(t.end,o),o=e.hold):Yi((t-e.hold)/e.seconds)}function Zi(e,t,n){if(t>=1||!Number.isFinite(e.thickness)||e.thickness<=n)return e;let r=Math.min(1,Math.max(0,t)),i=n*(e.thickness/n)**r;return{...e,thickness:i,tau:e.tau*(i/e.thickness)}}function Qi(e){let t=!e.studio&&e.viewerLens?z[e.viewerLens]:null;return t?Dn[t.material].background:e.style.background}function $i(e,t){let n=e.loaded?.block.header,i=n?n.time.end-n.time.start:10,a=!e.studio&&e.viewerLens?z[e.viewerLens]:null,o=a?e.work?.colour===`source`&&e.loaded?.block===e.work.block?{...Dn[a.material].look,color:`source`}:Dn[a.material].look:{...e.look,...e.style.lookOverride},s={...e.style,background:Qi(e)},{color:l,a:u,b:d}=o;return{...c(s,o),palette:{mode:r[l],a:u,b:d,m:o.m??null,ageSpan:p(t.window,i),motionRef:e.style.motionRef??1.5}}}function ea(e,t){let n=e.loaded;if(!n)return[0,0];if(xt(n.block))return[0,n.block.header.pointCount];let{time:r,fps:i}=n.block.header,a=i>0?1/i:0,[o,s]=Bi(t,[r.start,r.end],a),[c,l]=o<=s?Pe(n.block,o,s):[0,0];return[c,l-c]}function ta(e,t,n){return t.shutter<=0||n===0?e:{...e,window:{...e.window,t0:e.window.t0-t.shutter*v(n)}}}var na=new WeakMap,ra=1,ia=e=>na.get(e)??(na.set(e,ra++),ra-1),aa=new URLSearchParams(location.search),oa=aa.has(`offscreen`),sa=aa.has(`reveal`)?Number(aa.get(`reveal`)):null,ca=aa.has(`develop`)?Math.max(1,Number(aa.get(`develop`))):1;function la(e,t,n,r,i,a,o,s){let{time:c,fps:l}=n.header,u=n.header.bounds,d=0;if(r&&i===`present`){let e=Ki(t,c);u=U(r,c,l,e.ta,e.tb),d=Math.min(e.spread,1.5)}u={min:[u.min[0]-d,u.min[1],u.min[2]-d],max:[u.max[0]+d,u.max[1]+d*.5,u.max[2]+d]};let f=qi(u,a.yaw,a.pitch,a.fovY,o);return!e||!Number.isFinite(s)?{target:[...f.target],distance:f.distance}:{target:[0,1,2].map(t=>Ji(e.target[t],f.target[t],2.2,s)),distance:Ji(e.distance,f.distance,1.6,s)}}function ua(e,t,n=0){let r=b();return{...t,yaw:t.yaw+n,target:[e.target[0]+t.target[0]-r.target[0],e.target[1]+t.target[1]-r.target[1],e.target[2]+t.target[2]-r.target[2]],distance:e.distance*(t.distance/r.distance)}}var da={orbit:null};function fa(){let e=(0,j.useRef)(null),[t,n]=(0,j.useState)(null),r=w(e=>e.loaded),a=w(e=>e.viewerLens),o=(0,j.useRef)(null),s=(0,j.useRef)(null),c=(0,j.useRef)(performance.now()),l=(0,j.useRef)({ev:0,target:null,ready:!1,block:-1,last:0,shown:NaN}),[d,f]=(0,j.useState)(!1);(0,j.useEffect)(()=>{let t=e.current,r=!0,a=null;window.__v4d={framesRendered:0,blockReady:!1,store:w},Ii.create(t,oa).then(e=>{if(!r)return e.destroy();e.attach(),o.current=e,window.__v4d.capture=async()=>{let t=a,n=t?.darkroom,r=w.getState(),i=((!r.studio&&r.viewerLens?z[r.viewerLens]:null)?.darkroom?.auto??r.darkroom.auto)&&t?.style.blend===`additive`;if(t&&n&&i&&Number.isNaN(l.current.shown)){let r=await e.meter(t.lens,t.orbit,t.style,t.first,t.count,n),i=oe(r),a=Array.from(r).filter(e=>e>.004).sort((e,t)=>e-t);window.__v4d.exposure={ev:i,lit:a.length,p50:a[Math.floor(a.length/2)]??0,p90:a[Math.floor(a.length*.9)]??0,max:a[a.length-1]??0},i!==null&&(n={...n,ev:n.ev+i})}let o=t&&n?await e.capture(t.lens,t.orbit,t.style,t.first,t.count,ca,n,e=>ta(t.lens,n,e)):await e.capture(w.getState().lens,w.getState().orbit,w.getState().style,0,0),s=document.createElement(`canvas`);return s.width=o.width,s.height=o.height,s.getContext(`2d`).putImageData(o,0,0),s.toDataURL(`image/png`)},f(!0)},e=>n(e.message));let d=u(t,()=>w.getState().orbit,e=>w.getState().setOrbit(e),()=>c.current=performance.now()),p=!1,m=()=>{let e=w.getState();!e.studio&&e.playing&&(p=!0,e.setPlaying(!1))},h=()=>{p&&(p=!1,w.getState().setPlaying(!0))};t.addEventListener(`pointerdown`,m),window.addEventListener(`pointerup`,h),window.addEventListener(`pointercancel`,h),t.__frame=e=>a=e,vt.write=(e,t)=>{for(let n of t)o.current?.updateRange(e,n.first,n.count)},Zt.aspect=()=>t.clientWidth/Math.max(1,t.clientHeight),Zt.pixels=()=>Math.max(t.width,t.height);let g=null;return Rt.aspect=()=>t.clientWidth/Math.max(1,t.clientHeight),Rt.begin=()=>{let e=w.getState(),t=a;if(!t||!e.loaded)return;let n=!e.studio&&e.viewerLens?z[e.viewerLens]:null;g={lens:{...e.lens,window:{...e.lens.window,t0:x.t}},v:n,user:e.orbit,style:t.style,dk:t.darkroom,cam:null,wasPlaying:e.playing,block:e.loaded.block},e.setPlaying(!1)},Rt.end=()=>{g?.wasPlaying&&w.getState().setPlaying(!0),g=null,o.current?.releaseHeld()},Rt.frame=async(e,t,n,r)=>{let a=o.current,c=g,l=w.getState();if(!a||!c||!l.loaded)throw Error(`nothing on screen to film`);let{time:u,fps:d}=c.block.header,f=d>0?1/d:0,p=i(c.lens.window.t0,e/t.fps,u.start,u.end-u.start+f),m={...c.lens,window:{...c.lens.window,t0:p}};c.v?.reveal&&t.fromOpening?m={...m,window:Zi(m.window,Xi(c.v.reveal,e/t.fps),c.v.reveal.from)}:c.v?.reveal&&(m={...m,window:Zi(m.window,1,c.v.reveal.from)});let h=c.user;c.v?(c.cam=la(c.cam,m,c.block,s.current,c.v.frame,c.user,n/r,e===0?1/0:1/t.fps),h=ua(c.cam,c.user)):h=E(c.user,l.move,ae(e,Bt(t.seconds,t.fps).frames,l.move));let[_,v]=ea(l,m);if(c.dk.shutter>0){let[e,t]=ea(l,{...m,window:{...m.window,t0:p-c.dk.shutter}}),n=Math.max(_+v,e+t);_=Math.min(_,e),v=n-_}let y={...c.dk,passes:t.passes},b=await a.print(n,r,t.passes,e=>ta(m,y,e),h,c.style,_,v,y,void 0,Math.max(n,r),!0,11+e),x=new Uint8ClampedArray(n*r*4);for(let e=0,t=0;e>8,x[t+1]=b[e+1]>>8,x[t+2]=b[e+2]>>8,x[t+3]=255;return x},window.__v4d.film=async(e,t,n,r)=>(await lt(()=>Promise.resolve().then(()=>Lt).then(i=>i.makeFilm({seconds:e,fps:24,long:t,passes:n,fromOpening:r})),void 0))?.name??null,window.__v4d.print=async(e,t,n)=>(await lt(()=>Promise.resolve().then(()=>Yt).then(r=>r.makePrint({long:e,passes:t,tile:n})),void 0))?.name??null,Zt.render=async(e,t,n,r,i)=>{let s=o.current,c=a;if(!s||!c)throw Error(`nothing on screen to print`);let l=w.getState(),u=await s.print(e,t,n,e=>ta(c.lens,c.darkroom,e),c.orbit,c.style,c.first,c.count,c.darkroom,i,r),d=l.loaded?.block.header.meta??{};return{rgb:u,text:{Title:`V4D ${l.studio?l.preset??``:l.viewerLens??``}`.trim(),Author:`Mehran Ahmadi`,Software:`V4D 0.6.0`,Copyright:`(c) Mehran Ahmadi. All rights reserved.`,"V4D block":JSON.stringify({label:l.loaded?.label,source:d.source,generator:d.generator}),"V4D lens":JSON.stringify(c.lens,(e,t)=>t===1/0?`Infinity`:t),"V4D camera":JSON.stringify(c.orbit),"V4D darkroom":JSON.stringify({...c.darkroom,passes:n}),"V4D style":JSON.stringify(c.style)}}},()=>{r=!1,vt.write=null,Zt.render=null,Rt.frame=null,d(),t.removeEventListener(`pointerdown`,m),window.removeEventListener(`pointerup`,h),window.removeEventListener(`pointercancel`,h),o.current?.destroy(),o.current=null}},[]),(0,j.useEffect)(()=>{let e=o.current;e&&r&&(e.setBlock(r.block,r.next,r.aux??null),s.current=Gi(r.block),window.__v4d.blockReady=!0)},[r,d]),(0,j.useEffect)(()=>{if(!d)return;let t=e.current,n=t.__frame,r=Ui(),a=0,u=performance.now(),f=0,p=0,m=u,g=u,_=x.t,v=null,y=``,b=0,S=0,C=l.current,T=0,ee=e=>{a=requestAnimationFrame(ee);let l=Math.min(.1,(e-u)/1e3);u=e;let d=Math.min(2,window.devicePixelRatio||1),ne=Math.max(1,Math.round(t.clientWidth*d)),re=Math.max(1,Math.round(t.clientHeight*d));(t.width!==ne||t.height!==re)&&(t.width=ne,t.height=re);let O=w.getState(),ie=o.current;if(!ie)return;let ae=O.loaded,se=0;if(ae&&window.__v4d?.blockReady){let{time:t,fps:a}=ae.block.header,o=a>0?1/a:0,u=t.end-t.start+o,d=xt(ae.block);d?x.t=bt():O.playing&&(x.t=i(x.t,l*O.speed,t.start,u));let f=!d&&Math.abs(x.t-_)>u/2;_=x.t,(O.playing||d)&&e-g>100&&(O.setT0(x.t),g=e);let m={...O.lens,window:{...O.lens.window,t0:x.t}},ee=!O.studio&&O.viewerLens?z[O.viewerLens]:null;if(ee?.reveal&&(O.revealStart!==null||sa!==null)){let t=sa??(oa?1:Xi(ee.reveal,(e-O.revealStart)/1e3));m={...m,window:Zi(m.window,t,ee.reveal.from)}}let ce=O.orbit;if(ee){if(d){let e=h(O.liveSettings);v={target:[...e.target],distance:e.distance}}else v=la(v,m,ae.block,s.current,ee.frame,O.orbit,ne/re,oa||f?1/0:l);let t=e-c.current>6e3&&!r&&!oa&&O.playing;T=Ji(T,+!!t,t?.35:3,l),ce=ua(v,O.orbit,.16*T*Math.sin(2*Math.PI*e/46e3))}else if(v=null,O.movePreview){let t=(e-O.movePreview.start)/1e3/Math.max(.1,O.movePreview.seconds);t>=1?w.setState({movePreview:null}):ce=E(O.orbit,O.move,t)}da.orbit=ce;let A=ee?{...O.darkroom,...D,...ee.darkroom}:O.darkroom;ee&&O.work?.ev&&ae.block===O.work.block&&(A={...A,ev:A.ev+O.work.ev});let[le,ue]=ea(O,m);if(A.shutter>0){let[e,t]=ea(O,{...m,window:{...m.window,t0:m.window.t0-A.shutter}}),n=Math.max(le+ue,e+t);le=Math.min(le,e),ue=n-le}se=ue;let de=$i(O,m),fe=A.auto&&de.blend===`additive`,pe=ia(ae.block);pe!==C.block&&(C.block=pe,C.ready=!1,C.target=null),C.target!==null&&(C.ev=C.ready?k(C.ev,C.target,l):C.target),C.target!==null&&(C.ready=!0);let me={...A,ev:A.ev+(fe&&C.ready?C.ev:0)},he={lens:m,orbit:ce,style:de,first:le,count:ue,darkroom:{...me,auto:!1}};n(he);let ge=te([m,ce,de,ne,re,pe,{...A,ev:0},O.studio]);ge===y&&!O.playing?b=Math.min(b+1,A.passes):(b=0,y=ge),e-S>100&&O.developed!==b&&(O.setDeveloped(b),S=e);let _e=fe&&e-C.last>150?e=>{let t=oe(e);t!==null&&(C.target=t)}:void 0;!ie.offscreen&&b.01&&(ie.represent(me),C.shown=me.ev)}else ie.offscreen||ie.draw(O.lens,O.orbit,$i(O,O.lens),0,0);window.__v4d.framesRendered++,f+=l,p++,e-m>500&&(O.setStats({fps:p/f,drawn:se}),f=0,p=0,m=e)};return a=requestAnimationFrame(ee),()=>cancelAnimationFrame(a)},[d]);let p=a?`V4D: a body kept in time, seen through the ${z[a].name} lens. Drag to turn it.`:`V4D: a body kept in time.`,m=w(e=>e.studio?En(e.frame):null);return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`div`,{className:`stage${m?` framed`:``}`,style:m?{"--aspect":String(m)}:void 0,children:(0,N.jsx)(`canvas`,{ref:e,className:`viewport`,role:`img`,"aria-label":p})}),t&&(0,N.jsxs)(`div`,{className:`fatal`,children:[(0,N.jsx)(`p`,{className:`fatal-name`,children:`V4D · Virtual Fourth Dimension · by Mehran Ahmadi`}),(0,N.jsx)(`img`,{src:`/v4d-next/still.jpg`,alt:`A walker re-exposed through the Timegraph lens`}),(0,N.jsx)(`p`,{children:`This is a still. The work itself moves, and needs WebGPU: open this page in a current Chrome or Edge on a computer, Safari 26+, or Firefox 141+.`}),(0,N.jsx)(`p`,{className:`fatal-why`,children:t})]})]})}function pa(e){let t=e?.works;if(!Array.isArray(t))return[];let n=e=>typeof e==`string`&&e.trim()?e.trim():void 0;return t.flatMap(e=>{let t=n(e?.file),r=n(e?.title);if(!t||!r||!/\.v4d$/i.test(t))return[];let i=e.colour===`source`?`source`:`material`,a=Number(e.ev);return[{file:t,title:r,line:n(e.line),about:n(e.about),colour:i,...Number.isFinite(a)&&a!==0?{ev:Math.max(-8,Math.min(8,a))}:{}}]})}async function ma(e,t=0){let n=new URL(`works/`,new URL(e,location.href)).href,r=[];try{let e=await fetch(new URL(`works.json`,n),{cache:`no-cache`});if(!e.ok)return null;r=pa(await e.json())}catch{return null}let i=r[Math.min(Math.max(0,t),r.length-1)];if(!i)return null;let a=new URL(i.file,n).href;if(!Wi(a,location.href))return null;let o=await fetch(a);if(!o.ok)throw Error(`could not fetch ${i.file}: ${o.status}`);return{...i,label:i.title,block:Ae(await o.arrayBuffer())}}var ha=typeof location>`u`?null:new URLSearchParams(location.search),ga=Math.max(2,Number(ha?.get(`sitseconds`)??20)||20);function _a(e,t,n=3,r=ga){let i=(t-e)/1e3;return i{if(e!==ya)return;let i=_a(t,performance.now());if(i.phase===`sitting`&&!n&&(n=!0,Ot()),i.phase===`done`)return void Ca();let a=w.getState().sit;(a?.phase!==i.phase||a.left!==i.left)&&w.setState({sit:{phase:i.phase,left:i.left}}),va=window.setTimeout(r,100)};r()}async function Ca(){let e=kt({source:`sitting`});if(Dt(),!e){w.setState({sit:{phase:`intro`,error:`Nothing was seen: was there a person in front of the camera?`}});return}let t=w.getState();w.setState({sitting:{block:e,label:`your sitting`},sit:{phase:`developed`}}),t.setLoaded({block:e,next:null,label:`your sitting`}),t.setT0(e.header.time.end),await Nn(`EXPOSURE`,!0),w.getState().setPlaying(!1)}async function G(){let{makePrint:e}=await lt(async()=>{let{makePrint:e}=await Promise.resolve().then(()=>Yt);return{makePrint:e}},void 0);return e({long:Math.min(2400,Math.round(Math.max(window.innerWidth,window.innerHeight)*Math.min(2,window.devicePixelRatio||1))),passes:96,title:`V4D sitting`})}async function wa(){ya++,window.clearTimeout(va),Dt(),w.setState({sit:null,sitting:null}),w.getState().setPlaying(!0),await In(),await Nn(kn,!0)}var Ta={name:`V4D`,line:`A body, kept in time.`,by:`by Mehran Ahmadi`,hint:`drag to turn · hold to stop time`,about:`about`,lenses:{NOW:`One instant, as a photograph keeps it.`,ECHO:`The present thickens. What has just passed is still here.`,FIREBRAND:`One spark, whirled, draws a line of fire. The line is made by the eye.`,DISSOLVE:`The present holds. Before and after come apart.`,EXPOSURE:`The shutter never closes. All of its time at once.`},sit:{word:`Sit`,intro:`Your own time, kept for twenty seconds. The camera stays on this device: nothing is sent, and nothing is kept unless you save it.`,open:`open the camera`,notNow:`not now`,preparing:`Preparing (the first time, about 50 MB):`,mirror:`A mirror with memory. When you are ready, sit, and hold still for twenty seconds.`,begin:`sit`,close:`close the camera`,settle:`Settle.`,hold:`Hold still.`,developed:`Your twenty seconds, at once. The camera is closed.`,save:`save the image`,saving:`Developing the image…`,again:`sit again`,back:`back to the work`}};function Ea(){let e=w(e=>e.work);return(0,N.jsxs)(`header`,{className:`v-masthead ui`,children:[(0,N.jsx)(`h1`,{children:Ta.name}),(0,N.jsx)(`p`,{className:`v-line`,children:e?.line??Ta.line}),(0,N.jsx)(`p`,{className:`v-by`,children:Ta.by})]})}function Da(){let e=w(e=>e.aboutOpen);return(0,N.jsxs)(`div`,{className:`v-corner ui`,children:[(0,N.jsx)(`button`,{className:e?`on`:``,onClick:()=>w.getState().setAboutOpen(!e),"aria-expanded":e,"aria-controls":`about`,children:Ta.about}),(0,N.jsx)(`button`,{className:`icon`,onClick:tt,"aria-label":`Fullscreen`,title:`Fullscreen (F)`,children:(0,N.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`15`,height:`15`,"aria-hidden":`true`,children:(0,N.jsx)(`path`,{d:`M1 6V1h5M15 6V1h-5M1 10v5h5M15 10v5h-5`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`})})})]})}function Oa(){let e=w(e=>e.viewerLens),t=w(e=>e.sit);return(0,N.jsxs)(`div`,{className:`v-bottom ui`,children:[t?(0,N.jsx)(ka,{}):(0,N.jsx)(`p`,{className:`v-sentence`,"aria-live":`polite`,children:e?Ta.lenses[e]:``}),!t||t.phase===`developed`?(0,N.jsx)(`div`,{className:`v-time`,children:(0,N.jsx)(Pt,{})}):null,(0,N.jsxs)(`nav`,{className:`v-lenses`,"aria-label":`Ways of seeing`,children:[On.map(n=>(0,N.jsx)(`button`,{className:e===n&&(!t||t.phase!==`intro`)?`on`:``,"aria-pressed":e===n,disabled:!!t&&t.phase!==`developed`&&t.phase!==`intro`&&n===`FIREBRAND`,onClick:()=>void(t?.phase===`intro`?wa():Nn(n)),children:z[n].name},n)),(0,N.jsx)(`button`,{className:t?`on sit`:`sit`,"aria-pressed":!!t,onClick:()=>t?void 0:ba(),children:Ta.sit.word})]})]})}function ka(){let e=w(e=>e.sit),t=w(e=>e.live),n=w(e=>e.printing),r=Ta.sit,i=(e,...t)=>(0,N.jsxs)(`div`,{className:`v-sit`,"aria-live":`polite`,children:[(0,N.jsx)(`p`,{className:`v-sentence`,children:e}),t.length>0&&(0,N.jsx)(`p`,{className:`v-sit-actions`,children:t.map(([e,t])=>(0,N.jsx)(`button`,{onClick:()=>void t(),children:e},e))})]});switch(e.phase){case`intro`:return i(e.error??r.intro,[r.open,xa],[r.notNow,wa]);case`loading`:return i(t?.stage?`${r.preparing} ${t.stage.toLowerCase()}`:r.preparing);case`mirror`:return i(r.mirror,[r.begin,Sa],[r.close,wa]);case`countdown`:return i(`${r.settle} ${e.left??``}`);case`sitting`:return i(`${r.hold} ${e.left??``}`);case`developed`:return i(n===null?r.developed:`${r.saving} ${Math.round(n*100)} %`,[r.save,G],[r.again,xa],[r.back,wa])}}function Aa(){return w(e=>e.loaded===null)?(0,N.jsx)(`div`,{className:`v-loading`,role:`status`,"aria-label":`Loading`,children:(0,N.jsx)(`span`,{})}):null}var ja=`v4d.hinted`;function Ma(){let e=w(e=>e.introDone),[t,n]=(0,j.useState)(!1);return(0,j.useEffect)(()=>{if(!e)return;let t=!1;try{t=localStorage.getItem(ja)===`1`,localStorage.setItem(ja,`1`)}catch{}if(t)return;n(!0);let r=setTimeout(()=>n(!1),7e3);return()=>clearTimeout(r)},[e]),(0,N.jsx)(`p`,{className:`v-hint ui${t?` show`:``}`,"aria-hidden":!t,children:Ta.hint})}function Na(){let e=w(e=>e.aboutOpen);(0,j.useEffect)(()=>{let t=document.getElementById(`about`);if(!t)return;t.hidden=!e,e&&t.querySelector(`[data-close]`)?.focus();let n=e=>{let t=e.target;t.closest(`[data-close]`)&&w.getState().setAboutOpen(!1),t.closest(`[data-studio]`)&&(w.getState().setAboutOpen(!1),window.dispatchEvent(new CustomEvent(`v4d:studio`)))};return t.addEventListener(`click`,n),()=>t.removeEventListener(`click`,n)},[e])}function Pa(){let e=new URLSearchParams(location.search),t=w.getState(),n=t=>e.has(t)?Number(e.get(t)):void 0,r=Ui(),i=n(`t`);i!==void 0&&t.setT0(i),(e.get(`play`)===`0`||r)&&t.setPlaying(!1),e.has(`shot`)&&document.body.classList.add(`shot`);let a={...t.orbit};a.yaw=n(`yaw`)??a.yaw,a.pitch=n(`pitch`)??a.pitch,a.distance=n(`dist`)??a.distance,a.target=[n(`tx`)??a.target[0],n(`ty`)??a.target[1],n(`tz`)??a.target[2]],t.setOrbit(a);let o={};for(let[e,t]of[[`height`,`heightM`],[`hfov`,`hfov`],[`relief`,`relief`],[`ppf`,`pointsPerFrame`]]){let r=n(e);r!==void 0&&Number.isFinite(r)&&(o[t]=r)}let s=e.get(`spill`);(s===`all`||s===`edges`)&&(o.spill=s),Object.keys(o).length&&t.setImportSettings(o);let c=[],l=t=>{let n=e.get(t);return n===null||n===`none`||Wi(n,location.href)?n:(c.push(n),null)},u=l(`model`);u!==null&&Ke(u===`none`?null:u);let d=e.get(`color`),f=O[e.get(`palette`)??``],p=n(`grain`);t.setLook({...d&&ie.includes(d)?{color:d}:{},...f?{a:f.a,b:f.b}:{},...p!==void 0&&p>0?{grain:p}:{}}),e.get(`lens`)===`1`&&t.setLensOpen(!0),e.get(`lens`)===`0`&&t.setLensOpen(!1);let m=e.get(`frame`);m&&Tn.includes(m)&&t.setFrame(m);let h=e.get(`tab`);h&&se.includes(h)&&t.setTab(h);let g={};for(let[e,t]of[[`ev`,`ev`],[`shutter`,`shutter`],[`focus`,`timeFocus`],[`shade`,`shade`],[`filmgrain`,`grain`],[`passes`,`passes`],[`glow`,`glow`],[`spread`,`glowSpread`],[`halation`,`halation`],[`aperture`,`aperture`],[`focusat`,`focus`],[`vignette`,`vignette`]]){let r=n(e);r!==void 0&&Number.isFinite(r)&&(g[t]=r)}Object.keys(g).length&&t.setDarkroom(g),e.get(`ae`)===`0`&&t.setDarkroom({auto:!1});let _=l(`file`)??l(`video`),v=e.get(`preset`)?.toUpperCase(),y=e.get(`lens`)?.toUpperCase(),b=e.get(`camera`)===`1`,x=e.get(`matte`);(x===`person`||x===`green`)&&t.setLiveSettings({...t.liveSettings,matte:x});let S=l(`segmenter`),C=or(location.hash)!==null,T=Nr[(n(`builtin`)??0)-1]??null,E=e.has(`studio`)&&e.get(`studio`)!==`0`||!!v||!!_||b||C||!!T;t.setStudio(E);let ee=Vi(Hi()),D=e.get(`block`)??ee;return He(D===`walker`||D===`walker-2m`?D:ee),{block:D,refused:c.length>0,home:!e.has(`block`)&&!_&&e.get(`work`)!==`none`,shared:C,builtin:T,work:Number(e.get(`work`)??0)||0,camera:b,segmenter:S,preset:hn.includes(v)?v:null,viewerLens:y&&On.includes(y)?y:kn,kalam:e.get(`kalam`)===`1`,win:n(`win`),file:_,depth:e.get(`depth`)===`standin`?`standin`:`auto`,plate:e.get(`plate`)!==`0`,snap:e.get(`snap`)!==`0`,intro:e.get(`intro`)!==`0`&&!e.has(`offscreen`)&&!r,reduced:r}}function Fa(){let e=new URLSearchParams(location.search),t=w.getState(),n=t=>e.has(t)?Number(e.get(t)):void 0,r=n(`threads`),i=e.get(`thread`);if(r!==void 0||i){let e=t.style.thread??_n();t.setStyle({thread:{...e,...r===void 0?{}:{share:r},...i===`path`||i===`repair`?{kind:i}:{}}})}let a=n(`before`),o=n(`doubt`),s=e.get(`show`);if(a!==void 0||o!==void 0||s){let e=t.style.witness??vn();t.setStyle({witness:{...e,...a===void 0?{}:{before:a},...o===void 0?{}:{doubt:o},...s===`all`||s===`seen`||s===`unseen`?{show:s}:{}}})}}async function Ia(e,t,n,r){let i=await fetch(e);if(!i.ok)return w.getState().setStatus(`Could not fetch ${e}: ${i.status}`,`error`);let a=decodeURIComponent(new URL(e,location.href).pathname.split(`/`).pop()||`clip`);await Pn(new File([await i.blob()],a,{type:i.headers.get(`content-type`)??``}),{depth:t,plate:n,snap:r})}async function La(e){try{let t=await ma(`/v4d-next/`,e);if(t){w.setState({work:t});let e=document.getElementById(`about-figure`);e&&t.about&&(e.textContent=t.about),Fn(t);return}}catch(e){w.getState().setStatus(`The work could not load: ${e.message}`,`warn`)}await An(Ue())}function Ra(){let e=w.getState();e.studio?((At()||e.loaded?.label===`camera`||Ye(e.loaded?.label))&&(Dt(),In().then(()=>Nn(e.viewerLens??`ECHO`,!0))),e.setOrbit({...b(),yaw:e.orbit.yaw,pitch:e.orbit.pitch}),e.setStudio(!1),Nn(e.viewerLens??`ECHO`,!0)):(da.orbit&&e.setOrbit(da.orbit),e.setStudio(!0))}function za(){(0,j.useEffect)(()=>{let e=Pa();(e.camera?Promise.resolve():e.home?La(e.work):An(e.block)).then(()=>(e.refused&&w.getState().setStatus(`Blocks and models open from this site only.`,`warn`),e.file?Ia(e.file,e.depth,e.plate,e.snap):void 0)).then(()=>e.camera?Ct({depth:e.depth,segmenter:e.segmenter??void 0}).catch(()=>{}):void 0).then(()=>e.preset?Mn(e.preset,e.kalam):e.camera?Mn(`ECHO`):Nn(e.viewerLens,!e.intro)).then(()=>{if(e.win===void 0)return;let{lens:t,preset:n}=w.getState(),r=n===`FIREBRAND`?xn(e.win):{thickness:e.win};w.setState({lens:{...t,window:{...t.window,...r}}})}).then(()=>Fa()).then(()=>e.builtin?fr(e.builtin):void 0).then(async()=>{if(!e.shared)return;let t=await Cr(location.hash);t?await dr(t):w.getState().setStatus(`The look in this link could not be read.`,`warn`)}).finally(()=>{window.__v4d&&(window.__v4d.settled=!0),e.intro?setTimeout(()=>w.setState({introDone:!0}),3e3):w.setState({introDone:!0})})},[]),Na();let e=w(e=>e.bare),t=w(e=>e.studio),n=w(e=>e.introDone),r=w(e=>e.lensOpen),i=w(e=>Qi(e)[0]>.5);return(0,j.useEffect)(()=>{let e=e=>{if((e.ctrlKey||e.metaKey)&&!e.altKey&&w.getState().studio&&!e.target.closest?.(`input:not([type=range]), textarea`)){let t=e.key.toLowerCase();if(t===`z`||t===`y`){e.preventDefault(),t===`y`||e.shiftKey?Mr():jr();return}}if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.shiftKey&&(e.key===`P`||e.key===`M`)){e.preventDefault(),e.key===`P`?lt(()=>Promise.resolve().then(()=>Yt).then(e=>e.makePrint({long:4800,passes:128})),void 0):lt(()=>Promise.resolve().then(()=>Lt).then(e=>e.makeFilm({seconds:20,fps:24,long:1920,passes:16,fromOpening:!0})),void 0);return}let t=e.target;if(t.closest?.(`select, textarea, input:not([type=range]):not([type=color])`))return;let n=w.getState(),r=e.key.toLowerCase();if(r===` `)e.preventDefault(),t.blur?.(),n.setPlaying(!n.playing);else if(r===`escape`)n.setAboutOpen(!1);else if(r===`s`)Ra();else if(r===`f`)tt();else if(r===`h`)n.setBare(!n.bare);else if(r===`l`&&n.studio)n.setLensOpen(!n.lensOpen);else if(r===`k`&&n.studio&&At())Nt();else if(r===`e`&&n.studio)lt(()=>Promise.resolve().then(()=>Yt).then(e=>e.makeStill()),void 0);else if(/^[1-9]$/.test(r)){let e=Number(r)-1;n.studio&&hn[e]?Mn(hn[e]):!n.studio&&On[e]?Nn(On[e]):!n.studio&&e===On.length&&!n.sit&&ba()}},t=()=>Ra();return window.addEventListener(`keydown`,e),window.addEventListener(`v4d:studio`,t),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`v4d:studio`,t)}},[]),(0,N.jsxs)(`div`,{className:`app${e?` bare`:``}${i?` light`:``}${t?` studio`:` viewer`}${n?``:` quiet`}${r?``:` no-panels`}`,children:[(0,N.jsx)(fa,{}),t?(0,N.jsx)(fi,{}):(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(Ea,{}),(0,N.jsx)(Da,{}),(0,N.jsx)(Oa,{}),(0,N.jsx)(Ma,{}),(0,N.jsx)(Aa,{})]}),(0,N.jsx)(rn,{}),(0,N.jsx)(pi,{}),(0,N.jsx)(mi,{}),(0,N.jsx)(gi,{}),(0,N.jsx)(hi,{})]})}(0,Se.createRoot)(document.getElementById(`root`)).render((0,N.jsx)(j.StrictMode,{children:(0,N.jsx)(za,{})})); \ No newline at end of file diff --git a/v4d-next/assets/live.worker-B9vktp9Y.js b/v4d-next/assets/live.worker-B9vktp9Y.js new file mode 100644 index 0000000..d5b2f23 --- /dev/null +++ b/v4d-next/assets/live.worker-B9vktp9Y.js @@ -0,0 +1 @@ +var e=class{name=`silhouette stand-in`;async estimate(e){return{data:t(e.alpha,e.width,e.height),width:e.width,height:e.height}}};function t(e,t,n){let r=new Float32Array(t*n);for(let t=0;t=.5?1e9:0;let i=Math.SQRT2;for(let e=0;e0&&(s=Math.min(s,r[o-1]+1)),e>0&&(s=Math.min(s,r[o-t]+1),a>0&&(s=Math.min(s,r[o-t-1]+i)),a=0;e--)for(let o=t-1;o>=0;o--){let s=e*t+o;if(r[s]===0)continue;let c=r[s];o0&&(c=Math.min(c,r[s+t-1]+i))),r[s]=c,c>a&&(a=c)}if(a>0)for(let e=0;e=.85&&(u[e]=1,d.push(c[e]));let f=new Float32Array(l),p=new Uint8Array(l);if(d.length<20)return{data:f,width:o,height:s,known:p};let m=Math.max(n(d,.9)-n(d,.1),1e-6),h=a(c,u,o,s,m,4);for(let e=0;e0&&Math.abs(c[n-1]-r)>g||tg||e>0&&Math.abs(c[n-o]-r)>g||eg||(p[n]=1,f[n]=r)}for(let e=0;e0&&p[i-1]&&(a+=f[i-1],c++),r0&&p[i-o]&&(a+=f[i-o],c++),n0&&Math.abs(c[r-1]-i)>g||ng||e>0&&Math.abs(c[r-o]-i)>g||eg||(p[r]=1,f[r]=i)}return{data:f,width:o,height:s,known:p}}const s={black:.12,white:.9};function c(e,t,n,r,i=0){let a=(e+t+n)/3,o=1/(a+8);r[i]=(e-a)*o,r[i+1]=(t-a)*o,r[i+2]=(n-a)*o}const l=/* @__PURE__ */ new Float64Array(3);function u(e,t,n){c(e,t,n,l);let r=Math.max(Math.hypot(l[0],l[1],l[2]),.001);return[l[0]/r,l[1]/r,l[2]/r,r]}function d(e,t,n,r,i,a,o){let s=(e+t+n)/3,c=1/(s+8),l=(e-s)*c,u=(t-s)*c,d=(n-s)*c,f=l*r+u*i+d*a,p=Math.max(0,l*l+u*u+d*d-f*f);return 1-f/o+2*Math.sqrt(p)/o}function f(e){if(!e.length)return 0;let t=[...e].sort((e,t)=>e-t),n=t.length>>1;return t.length%2?t[n]:(t[n-1]+t[n])/2}function p(e,t,n){return t>=e&&t>=n?1:n>=e?2:0}function m(e,t,n,r=4){let i=[],a=Math.max(1,Math.floor((t+n)/400)),o=(n,r)=>{let a=4*(r*t+n);i.push([e[a],e[a+1],e[a+2]])};for(let e=0;e>1,t>>1);e++){for(let r=0;rf(i.map(t=>t[e]))),[c,l,m,h]=u(s[0],s[1],s[2]),g=f(i.map(e=>Math.abs(d(e[0],e[1],e[2],c,l,m,h))));return{r:s[0],g:s[1],b:s[2],channel:p(s[0],s[1],s[2]),spread:g}}function h(e,t,n=.1){if(!e||e.channel!==t.channel)return t;let r=(e,t)=>e+(t-e)*n;return{r:r(e.r,t.r),g:r(e.g,t.g),b:r(e.b,t.b),channel:e.channel,spread:r(e.spread,t.spread)}}function g(e,t=s){let n=Math.min(.45,Math.max(t.black,3*e.spread));return[n,Math.max(t.white,n+.2)]}const _=e=>e<=0?0:e>=1?1:e;function v(e,t,n,r,i=s,a=null){let o=new Float32Array(t*n),[l,f,p,m]=u(r.r,r.g,r.b);if(!a){let[a,s]=g(r,i),c=s-a;for(let r=0,i=0;r1.4)&&(u+=1);let v=_((u-.06)/.1),b=_((d(t,n,s,l,f,p,m)-h)/S);o[r]=Math.min(v,b)}return o}function y(e,t,n,r){return r.channel===1?[e,Math.min(t,Math.max(e,n)),n]:r.channel===2?[e,t,Math.min(n,Math.max(e,t))]:[Math.min(e,Math.max(t,n)),t,n]}function b(e,t,n){let r=t*n,i=new Int32Array(r).fill(-1),a=[],o=[];for(let s=0;s=n))for(let n=-1;n<=1;n++){let a=s+n;if(a<0||a>=t)continue;let l=c*t+a;i[l]===-1&&e[l]>=.5&&(i[l]=r,o.push(l))}}}a.push(c)}let s=new Float32Array(r);if(!a.length)return s;let c=Math.max(Math.max(...a)*.015,2e-4*r),l=a.map(e=>e>=c),u=new Uint8Array(r);for(let e=0;e=0&&l[i[e]]&&(u[e]=1);let d=new Uint8Array(r);for(let e=0;e=0;r--)u[e*t+r]&&(n=r),n-r<=3&&(d[e*t+r]=1)}let f=new Uint8Array(r);for(let e=0;e=0;i--)d[i*t+e]&&(r=i),r-i<=3&&(f[i*t+e]=1)}for(let t=0;t=.5?u[t]:f[t])&&(s[t]=n)}return s}function x(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function S(e,t,n,r){let i=[],a=[],o=0;for(let t=0;t>1;a[e]<=n?l=e+1:u=e}let d=i[l];c[e]=d,s[2*e]=d%t+r(),s[2*e+1]=Math.floor(d/t)+r()}return{uv:s,pixel:c,area:o}}function C(e,t,n,r,i,a,o,s){let c=Math.min(Math.max(i/o*n-.5,0),n-1),l=Math.min(Math.max(a/s*r-.5,0),r-1),u=Math.floor(c),d=Math.floor(l),f=Math.min(u+1,n-1),p=Math.min(d+1,r-1),m=c-u,h=l-d,g=0,_=0,v=(n,r)=>{t[n]&&r>0&&(g+=e[n]*r,_+=r)};if(v(d*n+u,(1-m)*(1-h)),v(d*n+f,m*(1-h)),v(p*n+u,(1-m)*h),v(p*n+f,m*h),_>0)return g/_;let y=Math.round(l)*n+Math.round(c);return t[y]?e[y]:NaN}const w=1.5;var T=class{prev=null;prevBody=null;last=NaN;norm=new O;update(e,t,n,r,i,a){let o=n*r,s=[];for(let n=0;n=.9&&s.push(e[n]);if(s.length<8){s=[];for(let n=0;n.3&&s.push(e[n])}let{median:c,spread:l}=this.norm.update(s,i),u=new Float32Array(o),d=new Uint8Array(o),f=this.prev&&this.prev.length===o&&i>this.last,p=f&&a>0?1-Math.exp(-(i-this.last)/a):1;for(let n=0;n.3),u[n]=f&&d[n]&&this.prevBody[n]?this.prev[n]+(r-this.prev[n])*p:r}return this.prev=u.slice(),this.prevBody=d,this.last=i,u}};const E=[.1,.7];var D=class{fast=null;slow=null;stable=null;last=NaN;update(e,t,n,r,i){let a=e.length;if(!this.fast||this.fast.length!==a||!(n>this.last))return this.fast=e.slice(),this.slow=e.slice(),this.stable=new Float32Array(a),this.last=n,e;let o=n-this.last;this.last=n;let s=1-Math.exp(-2*Math.PI*E[1]*o),c=1-Math.exp(-2*Math.PI*E[0]*o),l=1-Math.exp(-o/2),u=new Float32Array(a),d=this.fast,f=this.slow,p=this.stable;for(let n=0;n.3)-p[n])*l;let o=Math.min(1,Math.max(0,(p[n]-.9)/.08)),m=Math.min(i,Math.max(-i,r*(d[n]-f[n])));u[n]=a+(r>0?m*o:0)}return u}},O=class{seconds;median=NaN;spread=NaN;last=NaN;constructor(e=.25){this.seconds=e}update(e,t){if(e.length===0)return{median:this.median,spread:this.spread};let r=n(e,.5),i=Math.max(n(e,.9)-n(e,.1),1e-6);if(!Number.isFinite(this.median)||!(t>this.last))this.median=r,this.spread=i;else{let e=1-Math.exp(-(t-this.last)/this.seconds);this.median+=(r-this.median)*e,this.spread+=(i-this.spread)*e}return this.last=t,{median:this.median,spread:this.spread}}};function k(e,t,n,r,i,a){let o=t.length,s=new Float32Array(3*o),c=n/2/Math.tan(a.hfov/2*Math.PI/180),l=n/2,u=r/2,d=a.mirror?-1:1;for(let n=0;nw?w:r;let o=a.distance-a.relief*r;s[3*n]=d*((e[2*n]-l)/c)*o,s[3*n+1]=1.2-(e[2*n+1]-u)/c*o,s[3*n+2]=a.distance-o}return s}function A(e){let t=Math.min(1,Math.max(0,(e-.35)/.4));return t*t*(3-2*t)}var j=class{name=`green screen key`;key=null;alpha(e,t,n,r){return this.key=h(this.key,m(t,n,r),this.key?.1:1),b(v(t,n,r,this.key),n,r)}};async function M(e,t){let{ImageSegmenter:n}=await import(`./vision_bundle-Ct9A5sJw.js`),r={wasmLoaderPath:t.loader,wasmBinaryPath:t.binary},i=null;for(let t of[`GPU`,`CPU`])try{let i=await n.createFromOptions(r,{baseOptions:{modelAssetPath:e,delegate:t},runningMode:`VIDEO`,outputConfidenceMasks:!0,outputCategoryMask:!1}),a=-1;return{name:`MediaPipe selfie segmenter (${t})`,alpha(e,t,n,r,o){a=Math.max(o,a+1);let s=i.segmentForVideo(e,a),c=s.confidenceMasks??[],l=new Float32Array(n*r),u=c[+(c.length>1)];if(u){let e=u.getAsFloat32Array(),t=u.width,i=u.height;for(let a=0;ai.close()}}catch(e){i=e}throw i instanceof Error?i:Error(String(i))}const N=(e,t=[])=>self.postMessage(e,t);let P=null,F=null,I=null,L=new T,R=new D;const z=x(7);let B=null,V=null;self.onmessage=e=>{let t=e.data;t.type===`start`?H(t).catch(e=>N({type:`error`,message:e?.message??String(e)})):t.type===`settings`?P=t.settings:t.type===`reset`?(L=new T,R=new D):t.type===`frame`&&U(t.bitmap,t.t).catch(e=>{t.bitmap.close(),N({type:`error`,message:e?.message??String(e)})})};async function H(t){P=t.settings;let n=[];if(t.settings.matte===`green`)F=new j;else{N({type:`progress`,stage:`Loading the person matte`});try{F=await M(t.segmenter,t.wasm)}catch(e){F=new j,n.push(`person matte unavailable (${e?.message??e}); using a green screen key`)}}if(t.depth===`standin`)I=new e,n.push(`stand-in depth requested`);else{N({type:`progress`,stage:`Loading the depth model`});try{let{loadDepthModel:e}=await import(`./depthModel-BEeGmccg.js`);I=await e(e=>N({type:`progress`,stage:`Loading the depth model ${Math.round(e*100)}%`}))}catch(t){I=new e,n.push(`depth model unavailable (${t?.message??t}); using a silhouette stand-in`)}}N({type:`ready`,matte:F.name,depth:I.name,notes:n})}async function U(t,n){let i=performance.now(),a=P,s=F,c=I;if(!a||!s||!c){t.close();return}let l=t.width,u=t.height;(!B||B.canvas.width!==l||B.canvas.height!==u)&&(B=new OffscreenCanvas(l,u).getContext(`2d`,{willReadFrequently:!0})),B.drawImage(t,0,0);let d=B.getImageData(0,0,l,u).data,f=s.alpha(t,d,l,u,n*1e3),p=s instanceof j?f:b(f,l,u),m=S(p,l,a.pointsPerFrame,z);if(m.area<.002*l*u){t.close(),N({type:`frame`,t:n,positions:/* @__PURE__ */ new Float32Array,colors:/* @__PURE__ */ new Uint8Array,ms:performance.now()-i});return}let h;if(c instanceof e)h=await c.estimate({rgba:d,width:l,height:u,alpha:p});else{let e=Math.min(1,364/Math.max(l,u)),n=Math.max(14,Math.round(l*e)),r=Math.max(14,Math.round(u*e));(!V||V.canvas.width!==n||V.canvas.height!==r)&&(V=new OffscreenCanvas(n,r).getContext(`2d`,{willReadFrequently:!0})),V.drawImage(t,0,0,n,r),h=await c.estimate({rgba:V.getImageData(0,0,n,r).data,width:n,height:r,alpha:p})}t.close();let g=r(p,l,u,h.width,h.height),_=L.update(h.data,g,h.width,h.height,n,a.calm),v=o({data:R.update(_,g,n,a.breath,.03/Math.max(a.relief,.001)),width:h.width,height:h.height},g),x=m.pixel.length,w=new Float32Array(2*x),T=new Float32Array(x),E=new Uint8Array(3*x),D=s instanceof j&&s.key?{channel:s.key.channel}:null,O=0;for(let e=0;e{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},n=2**32,r=2**32-1,i=131072,a=class e extends ArrayBuffer{constructor(e){super(e),this.fileStart=0,this.usedBytes=0}static fromArrayBuffer(t,n){let r=new e(t.byteLength);return new Uint8Array(r).set(new Uint8Array(t)),r.fileStart=n,r}},o=class e{static{this.ENDIANNESS=new Int8Array(new Int16Array([1]).buffer)[0]>0?2:1}constructor(e,t,n){this._byteLength=0,this.failurePosition=0,this._dynamicSize=1,this._byteOffset=t||0,e instanceof ArrayBuffer?this.buffer=a.fromArrayBuffer(e,0):e instanceof DataView?(this.dataView=e,t&&(this._byteOffset+=t)):this.buffer=new a(e||0),this.position=0,this.endianness=n||1}getPosition(){return this.position}_realloc(e){if(!this._dynamicSize)return;let t=this._byteOffset+this.position+e,n=this._buffer.byteLength;if(t<=n){t>this._byteLength&&(this._byteLength=t);return}for(n<1&&(n=1);t>n;)n*=2;let r=new a(n),i=new Uint8Array(this._buffer);new Uint8Array(r,0,i.length).set(i),this.buffer=r,this._byteLength=t}_trimAlloc(){if(this._byteLength===this._buffer.byteLength)return;let e=new a(this._byteLength),t=new Uint8Array(e),n=new Uint8Array(this._buffer,0,t.length);t.set(n),this.buffer=e}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){return this._trimAlloc(),this._buffer}set buffer(e){this._buffer=e,this._dataView=new DataView(e,this._byteOffset),this._byteLength=e.byteLength}get byteOffset(){return this._byteOffset}set byteOffset(e){this._byteOffset=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get dataView(){return this._dataView}set dataView(e){this._byteOffset=e.byteOffset,this._buffer=a.fromArrayBuffer(e.buffer,0),this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+e.byteLength}seek(e){let t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t}isEof(){return this.position>=this._byteLength}#e(e){return Array.isArray(e)&&e.length===3&&e[0]===`[]`}mapUint8Array(e){this._realloc(e*1);let t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e*1,t}readInt32Array(t,n){t=t===void 0?this.byteLength-this.position/4:t;let r=new Int32Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readInt16Array(t,n){t=t===void 0?this.byteLength-this.position/2:t;let r=new Int16Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readInt8Array(t){t=t===void 0?this.byteLength-this.position:t;let n=new Int8Array(t);return e.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,t*n.BYTES_PER_ELEMENT),this.position+=n.byteLength,n}readUint32Array(t,n){t=t===void 0?this.byteLength-this.position/4:t;let r=new Uint32Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readUint16Array(t,n){t=t===void 0?this.byteLength-this.position/2:t;let r=new Uint16Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readUint8Array(t){t=t===void 0?this.byteLength-this.position:t;let n=new Uint8Array(t);return e.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,t*n.BYTES_PER_ELEMENT),this.position+=n.byteLength,n}readFloat64Array(t,n){t=t===void 0?this.byteLength-this.position/8:t;let r=new Float64Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readFloat32Array(t,n){t=t===void 0?this.byteLength-this.position/4:t;let r=new Float32Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readInt32(e){let t=this._dataView.getInt32(this.position,(e??this.endianness)===2);return this.position+=4,t}readInt16(e){let t=this._dataView.getInt16(this.position,(e??this.endianness)===2);return this.position+=2,t}readInt8(){let e=this._dataView.getInt8(this.position);return this.position+=1,e}readUint32(e){let t=this._dataView.getUint32(this.position,(e??this.endianness)===2);return this.position+=4,t}readUint16(e){let t=this._dataView.getUint16(this.position,(e??this.endianness)===2);return this.position+=2,t}readUint8(){let e=this._dataView.getUint8(this.position);return this.position+=1,e}readFloat32(e){let t=this._dataView.getFloat32(this.position,(e??this.endianness)===2);return this.position+=4,t}readFloat64(e){let t=this._dataView.getFloat64(this.position,(e??this.endianness)===2);return this.position+=8,t}static memcpy(e,t,n,r,i){let a=new Uint8Array(e,t,i),o=new Uint8Array(n,r,i);a.set(o)}static arrayToNative(t,n){return n===e.ENDIANNESS?t:this.flipArrayEndianness(t)}static nativeToEndian(t,n){return n&&e.ENDIANNESS===2?t:this.flipArrayEndianness(t)}static flipArrayEndianness(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);for(let n=0;ni;r--,i++){let e=t[i];t[i]=t[r],t[r]=e}return e}readString(e,t){return t===void 0||t===`ASCII`?s(this.mapUint8Array(e===void 0?this.byteLength-this.position:e)):new TextDecoder(t).decode(this.mapUint8Array(e))}readCString(e){let t=0,n=this.byteLength-this.position,r=new Uint8Array(this._buffer,this._byteOffset+this.position),i=e===void 0?n:Math.min(e,n);for(;t>16),this.writeUint8((e&65280)>>8),this.writeUint8(e&255)}adjustUint32(e,t){let n=this.position;this.seek(e),this.writeUint32(t),this.seek(n)}readStruct(e){let t={},n=this.position;for(let r=0;r=p&&console.debug(`[`+m.getDurationString(new Date().getTime()-c.getTime(),1e3)+`]`,`[`+e+`]`,t)},log(e,t){this.debug(e.msg)},info(e,t){d>=p&&console.info(`[`+m.getDurationString(new Date().getTime()-c.getTime(),1e3)+`]`,`[`+e+`]`,t)},warn(e,t){u>=p&&console.warn(`[`+m.getDurationString(new Date().getTime()-c.getTime(),1e3)+`]`,`[`+e+`]`,t)},error(e,t,n){n?.onError?n.onError(e,t):l>=p&&console.error(`[`+m.getDurationString(new Date().getTime()-c.getTime(),1e3)+`]`,`[`+e+`]`,t)},getDurationString(e,t){let n;function r(e,t){let n=(``+e).split(`.`);for(;n[0].length0){let n=``;for(let r=0;r0&&(n+=`,`),n+=`[`+m.getDurationString(e.start(r))+`,`+m.getDurationString(e.end(r))+`]`;return n}return`(empty)`}};function h(e,t){m.debug(`ArrayBuffer`,`Trying to create a new buffer of size: `+(e.byteLength+t.byteLength));let n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}var g=class extends o{constructor(e){super(new ArrayBuffer,0),this.buffers=[],this.bufferIndex=-1,e&&(this.insertBuffer(e),this.bufferIndex=0)}initialized(){if(this.bufferIndex>-1)return!0;if(this.buffers.length>0){let e=this.buffers[0];return e.fileStart===0?(this.buffer=e,this.bufferIndex=0,m.debug(`MultiBufferStream`,`Stream ready for parsing`),!0):(m.warn(`MultiBufferStream`,`The first buffer should have a fileStart of 0`),this.logBufferLevel(),!1)}return m.warn(`MultiBufferStream`,`No buffer to start parsing from`),this.logBufferLevel(),!1}reduceBuffer(e,t,n){let r=new Uint8Array(n);return r.set(new Uint8Array(e,t,n)),r.buffer.fileStart=e.fileStart+t,r.buffer.usedBytes=0,r.buffer}insertBuffer(e){let t=!0,n=0;for(;nr.byteLength){this.buffers.splice(n,1),n--;continue}m.warn(`MultiBufferStream`,`Buffer (fileStart: `+e.fileStart+` - Length: `+e.byteLength+`) already appended, ignoring`)}else e.fileStart+e.byteLength<=r.fileStart||(e=this.reduceBuffer(e,0,r.fileStart-e.fileStart)),m.debug(`MultiBufferStream`,`Appending new buffer (fileStart: `+e.fileStart+` - Length: `+e.byteLength+`)`),this.buffers.splice(n,0,e),n===0&&(this.buffer=e);t=!1;break}if(e.fileStart0)e=this.reduceBuffer(e,n,i);else{t=!1;break}}}t&&(m.debug(`MultiBufferStream`,`Appending new buffer (fileStart: `+e.fileStart+` - Length: `+e.byteLength+`)`),this.buffers.push(e),n===0&&(this.buffer=e))}logBufferLevel(e){let t=[],n=``,r,i=0,a=0;for(let e=0;e0&&(n+=r.end-1+`]`);let o=e?m.info:m.debug;this.buffers.length===0?o(`MultiBufferStream`,`No more buffer in memory`):o(`MultiBufferStream`,``+this.buffers.length+` stored buffer(s) (`+i+`/`+a+` bytes), continuous ranges: `+n)}cleanBuffers(){for(let e=0;e`+this.buffer.byteLength+`)`),!0}return!1}return!1}findPosition(e,t,n){let r=-1,i=e===!0?0:this.bufferIndex;for(;i=t?(m.debug(`MultiBufferStream`,`Found position in existing buffer #`+r),r):-1}findEndContiguousBuf(e){let t=e===void 0?this.bufferIndex:e,n=this.buffers[t];if(this.buffers.length>t+1)for(let e=t+1;er||this.original_size===1)&&(this.size+=8),this.type===`uuid`&&(this.size+=16),m.debug(`BoxWriter`,`Writing box `+this.type+` of size: `+this.size+` at position `+e.getPosition()+(t||``)),this.original_size===0?e.writeUint32(0):this.size>r||this.original_size===1?e.writeUint32(1):(this.sizePosition=e.getPosition(),e.writeUint32(this.size)),e.writeString(this.type,void 0,4),this.type===`uuid`){let t=new Uint8Array(16);for(let e=0;e<16;e++)t[e]=parseInt(this.uuid.substring(e*2,e*2+2),16);e.writeUint8Array(t)}(this.size>r||this.original_size===1)&&(this.sizePosition=e.getPosition(),e.writeUint64(this.size))}write(e){if(this.type===`mdat`){let t=this;if(t.stream){this.size=t.stream.getAbsoluteEndPosition(),this.writeHeader(e);for(let n of t.stream.buffers){let t=new Uint8Array(n);e.writeUint8Array(t)}}else t.data&&(this.size=t.data.length,this.writeHeader(e),e.writeUint8Array(t.data))}else this.size=this.data?this.data.length:0,this.writeHeader(e),this.data&&e.writeUint8Array(this.data)}printHeader(e){this.size+=8,this.size>r&&(this.size+=8),this.type===`uuid`&&(this.size+=16),e.log(e.indent+`size:`+this.size),e.log(e.indent+`type:`+this.type)}print(e){this.printHeader(e)}parse(e){this.type===`mdat`?this.size===0?e.seek(e.getEndPosition()):e.seek(this.start+this.size):this.data=e.readUint8Array(this.size-this.hdr_size)}parseDataAndRewind(e){this.data=e.readUint8Array(this.size-this.hdr_size),e.seek(this.start+this.hdr_size)}parseLanguage(e){this.language=e.readUint16();let t=[];t[0]=this.language>>10&31,t[1]=this.language>>5&31,t[2]=this.language&31,this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96)}computeSize(e){let t=e||new g;this.write(t)}isEndOfBox(e){return e.getPosition()===this.start+this.size}},v=class extends _{constructor(...e){super(...e),this.flags=0,this.version=0}writeHeader(e){this.size+=4,super.writeHeader(e,` v=`+this.version+` f=`+this.flags),e.writeUint8(this.version),e.writeUint24(this.flags)}printHeader(e){this.size+=4,super.printHeader(e),e.log(e.indent+`version:`+this.version),e.log(e.indent+`flags:`+this.flags)}parseDataAndRewind(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,e.seek(this.start+this.hdr_size)}parseFullHeader(e){this.version=e.readUint8(),this.flags=e.readUint24(),this.hdr_size+=4}parse(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)}},y=class{static{this.registryId=Symbol.for(`SampleGroupEntryIdentifier`)}constructor(e){this.grouping_type=e}write(e){e.writeUint8Array(this.data)}parse(e){m.warn(`BoxParser`,`Unknown sample group type: '${this.grouping_type}'`),this.data=e.readUint8Array(this.description_length)}},b=class extends v{parse(e){this.parseFullHeader(e),this.track_group_id=e.readUint32()}},x=class extends _{constructor(e,t,n,r,i){super(t),this.box_name=n,this.hdr_size=r,this.start=i,this.type=e}parse(e){this.from_item_ID=e.readUint16();let t=e.readUint16();this.references=[];for(let n=0;ne===n))continue;else if(e[n]instanceof _||t[n]instanceof _)continue;else if(e[n]===void 0||t[n]===void 0)continue;else if(typeof e[n]==`function`||typeof t[n]==`function`)continue;else if(`subBoxNames`in e&&e.subBoxNames.indexOf(n.slice(0,4))>-1||`subBoxNames`in t&&t.subBoxNames.indexOf(n.slice(0,4))>-1)continue;else if(n===`data`||n===`start`||n===`size`||n===`creation_time`||n===`modification_time`)continue;else if(T.find(e=>e===n))continue;else if(e[n]!==t[n])return!1;return!0}function ee(e,t){if(!E(e,t))return!1;for(let n=0;n{let t=Symbol.for(`SampleGroupEntryIdentifier`);return D(e)===t},ne=e=>{let t=Symbol.for(`SampleEntryIdentifier`);return D(e)===t},re=e=>{let t=Symbol.for(`BoxIdentifier`);return D(e)===t},O={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};function ie(e){let t={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};for(let[n,r]of Object.entries(e))if(te(r)){let e=`grouping_type`in r?r.grouping_type:void 0;if(!e)throw Error(`SampleGroupEntry class ${n} does not have a valid static grouping_type. Please ensure it is defined correctly.`);if(e in t.sampleGroupEntry)throw Error(`SampleGroupEntry class ${n} has a grouping_type that is already registered. Please ensure it is unique.`);t.sampleGroupEntry[e]=r}else if(ne(r)){let e=`fourcc`in r?r.fourcc:void 0;if(!e)throw Error(`SampleEntry class ${n} does not have a valid static fourcc. Please ensure it is defined correctly.`);if(e in t.sampleEntry)throw Error(`SampleEntry class ${n} has a fourcc that is already registered. Please ensure it is unique.`);t.sampleEntry[e]=r}else if(re(r)){let e=`fourcc`in r?r.fourcc:void 0,i=`uuid`in r?r.uuid:void 0;if(e===`uuid`){if(!i)throw Error(`Box class ${n} has a fourcc of 'uuid' but does not have a valid uuid. Please ensure it is defined correctly.`);if(i in t.uuid)throw Error(`Box class ${n} has a uuid that is already registered. Please ensure it is unique.`);t.uuid[i]=r;continue}t.box[e]=r}else throw Error(`Box class ${n} does not have a valid static fourcc, uuid, or grouping_type. Please ensure it is defined correctly.`);return O.uuid={...t.uuid},O.sampleEntry={...t.sampleEntry},O.sampleGroupEntry={...t.sampleGroupEntry},O.box={...t.box},O}var k={};function ae(e){return Object.entries(e).forEach(([e,t])=>k[e]=t),k}function oe(e){return A(e)}function A(e){let t=``;for(let n=0;n<16;n++){let n=e.readUint8().toString(16);t+=n.length===1?`0`+n:n}return t}function j(e,t,n){let r,i,a=e.getPosition(),o=0,s;if(e.getEndPosition()-a<8)return m.debug(`BoxParser`,`Not enough data in stream to parse the type and size of the box`),{code:0};if(n&&n<8)return m.debug(`BoxParser`,`Not enough bytes left in the parent box to parse a new box`),{code:0};let c=e.readUint32(),l=e.readString(4);if(l.length!==4||!/^[\x20-\x7E]{4}$/.test(l))return m.error(`BoxParser`,`Invalid box type: '${l}'`),{code:-1,start:a,type:l};let u=l;if(m.debug(`BoxParser`,`Found box of type '`+l+`' and size `+c+` at position `+a),o=8,l===`uuid`){if(e.getEndPosition()-e.getPosition()<16||n-o<16)return e.seek(a),m.debug(`BoxParser`,`Not enough bytes left in the parent box to parse a UUID box`),{code:0};s=oe(e),o+=16,u=s}if(c===1){if(e.getEndPosition()-e.getPosition()<8||n&&n-o<8)return e.seek(a),m.warn(`BoxParser`,`Not enough data in stream to parse the extended size of the "`+l+`" box`),{code:0};i=c,c=e.readUint64(),o+=8}else if(c===0){if(n)c=n;else if(l!==`mdat`)return m.error(`BoxParser`,`Unlimited box size not supported for type: '`+l+`'`),r=new _(c),r.type=l,{code:1,box:r,size:r.size};else c=e.getEndPosition()-a}if(c!==0&&cn)return m.error(`BoxParser`,`Box of type '`+l+`' has a size `+c+` greater than its container size `+n),{code:0,type:l,size:c,hdr_size:o,start:a};if(c!==0&&a+c>e.getEndPosition())return e.seek(a),m.info(`BoxParser`,`Not enough data in stream to parse the entire '`+l+`' box`),{code:0,type:l,size:c,hdr_size:o,start:a,original_size:i};if(t)return{code:1,type:l,size:c,hdr_size:o,start:a};l in O.box?r=new O.box[l](c):l===`uuid`?s in O.uuid?r=new O.uuid[s](c):(m.warn(`BoxParser`,`Unknown UUID box type: '${s}'`),r=new _(c),r.type=l,r.uuid=s,r.has_unparsed_data=!0):(m.warn(`BoxParser`,`Unknown box type: '${l}'`),r=new _(c),r.type=l,r.has_unparsed_data=!0),r.original_size=i,r.hdr_size=o,r.start=a,r.write===_.prototype.write&&r.type!==`mdat`&&(m.info(`BoxParser`,`'`+u+`' box writing not yet implemented, keeping unparsed data in memory for later write`),r.parseDataAndRewind(e)),r.parse(e);let d=e.getPosition()-(r.start+r.size);return d<0?(m.warn(`BoxParser`,`Parsing of box '`+u+`' did not read the entire indicated box data size (missing `+-d+` bytes), seeking forward`),e.seek(r.start+r.size)):d>0&&r.size!==0&&(m.error(`BoxParser`,`Parsing of box '`+u+`' read `+d+` more bytes than the indicated box data size, seeking backwards`),e.seek(r.start+r.size)),{code:1,box:r,size:r.size}}var M=class extends _{write(e){if(this.size=0,this.writeHeader(e),this.boxes)for(let t=0;t`;e+=`lengthnalu_data`,e+=``;for(let t=0;t`,e+=``+n.length+``,e+=``,e+=n.data.reduce(function(e,t){return e+t.toString(16).padStart(2,`0`)},`0x`),e+=``}return e+=``,e}},ue=class extends _{constructor(...e){super(...e),this.box_name=`AVCConfigurationBox`}static{this.fourcc=`avcC`}parse(e){this.configurationVersion=e.readUint8(),this.AVCProfileIndication=e.readUint8(),this.profile_compatibility=e.readUint8(),this.AVCLevelIndication=e.readUint8(),this.lengthSizeMinusOne=e.readUint8()&3,this.nb_SPS_nalus=e.readUint8()&31;let t=this.size-this.hdr_size-6;this.SPS=new le;for(let n=0;n0&&(this.ext=e.readUint8Array(t))}write(e){this.size=7;for(let e=0;e>24,this.minor_version>>16&255,this.minor_version>>8&255,this.minor_version&255);n.match(`[a-zA-Z0-9]{4}`)&&(this.minor_version=n),t-=8,this.compatible_brands=[];let r=0;for(;t>=4;)this.compatible_brands[r]=e.readString(4),t-=4,r++}write(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,void 0,4),typeof this.minor_version==`number`?e.writeUint32(this.minor_version):e.writeString(this.minor_version,void 0,4);for(let t=0;t1&&(m.info(`BoxParser`,`Warning: hdlr name is not null-terminated, possibly length-prefixed string. Trimming first byte.`),this.name=this.name.slice(1))}}write(e){this.size=20+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(e),e.writeUint32(0),e.writeString(this.handler,void 0,4),e.writeUint32Array([0,0,0]),e.writeCString(this.name)}},Xe=class extends _{constructor(...e){super(...e),this.box_name=`HEVCConfigurationBox`}static{this.fourcc=`hvcC`}parse(e){this.configurationVersion=e.readUint8();let t=e.readUint8();this.general_profile_space=t>>6,this.general_tier_flag=(t&32)>>5,this.general_profile_idc=t&31,this.general_profile_compatibility=e.readUint32(),this.general_constraint_indicator=e.readUint8Array(6),this.general_level_idc=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,this.chroma_format_idc=e.readUint8()&3,this.bit_depth_luma_minus8=e.readUint8()&7,this.bit_depth_chroma_minus8=e.readUint8()&7,this.avgFrameRate=e.readUint16(),t=e.readUint8(),this.constantFrameRate=t>>6,this.numTemporalLayers=(t&13)>>3,this.temporalIdNested=(t&4)>>2,this.lengthSizeMinusOne=t&3,this.nalu_arrays=[];let n=e.readUint8();for(let r=0;r>7,n.nalu_type=t&63;let r=e.readUint16();for(let t=0;tr||this.creation_time>r||this.duration>r||this.version===1;this.version=+!!t,this.size=20,this.size+=t?12:0,this.flags=0,this.writeHeader(e),t?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.timescale),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration)),e.writeUint16(this.language),e.writeUint16(0)}},Qe=class extends v{constructor(...e){super(...e),this.box_name=`MovieExtendsHeaderBox`}static{this.fourcc=`mehd`}parse(e){this.parseFullHeader(e),this.flags&1&&(m.warn(`BoxParser`,`mehd box incorrectly uses flags set to 1, converting version to 1`),this.version=1),this.fragment_duration=this.version===1?e.readUint64():e.readUint32()}write(e){let t=this.fragment_duration>r||this.version===1;this.version=+!!t,this.size=4,this.size+=t?4:0,this.flags=0,this.writeHeader(e),t?e.writeUint64(this.fragment_duration):e.writeUint32(this.fragment_duration)}},$e=class extends v{constructor(...e){super(...e),this.box_name=`ItemInfoEntry`}static{this.fourcc=`infe`}parse(e){this.parseFullHeader(e),(this.version===0||this.version===1)&&(this.item_ID=e.readUint16(),this.item_protection_index=e.readUint16(),this.item_name=e.readCString(),this.content_type=e.readCString(),this.isEndOfBox(e)||(this.content_encoding=e.readCString())),this.version===1?(this.extension_type=e.readString(4),m.warn(`BoxParser`,`Cannot parse extension type`),e.seek(this.start+this.size)):this.version>=2&&(this.version===2?this.item_ID=e.readUint16():this.version===3&&(this.item_ID=e.readUint32()),this.item_protection_index=e.readUint16(),this.item_type=e.readString(4),this.item_name=e.readCString(),this.item_type===`mime`?(this.content_type=e.readCString(),this.content_encoding=e.readCString()):this.item_type===`uri `&&(this.item_uri_type=e.readCString()))}},et=class extends v{constructor(...e){super(...e),this.box_name=`ItemInfoBox`}static{this.fourcc=`iinf`}parse(e){this.parseFullHeader(e),this.entry_count=this.version===0?e.readUint16():e.readUint32(),this.item_infos=[];for(let t=0;t>4&15,this.length_size=t&15,t=e.readUint8(),this.base_offset_size=t>>4&15,this.index_size=this.version===1||this.version===2?t&15:0,this.items=[];let n=0;if(this.version<2)n=e.readUint16();else if(this.version===2)n=e.readUint32();else throw Error(`version of iloc box not supported`);for(let t=0;t8){switch(e.readUint32(),e.readString(4)){case`hdlr`:case`mhdr`:case`keys`:case`ilst`:case`ctry`:case`lang`:this.isQT=!0}e.seek(t)}this.isQT||this.parseFullHeader(e),M.prototype.parse.call(this,e)}},ot=class extends v{constructor(...e){super(...e),this.box_name=`MovieFragmentHeaderBox`}static{this.fourcc=`mfhd`}parse(e){this.parseFullHeader(e),this.sequence_number=e.readUint32()}write(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.sequence_number)}},st=class extends v{constructor(...e){super(...e),this.box_name=`MovieHeaderBox`}static{this.fourcc=`mvhd`}parse(e){this.parseFullHeader(e),this.version===1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.rate=e.readUint32(),this.volume=e.readUint16()>>8,e.readUint16(),e.readUint32Array(2),this.matrix=e.readInt32Array(9),e.readUint32Array(6),this.next_track_id=e.readUint32()}write(e){let t=this.modification_time>r||this.creation_time>r||this.duration>r||this.version===1;this.version=+!!t,this.size=96,this.size+=t?12:0,this.flags=0,this.writeHeader(e),t?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.timescale),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration)),e.writeUint32(this.rate),e.writeUint16(this.volume<<8),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeInt32Array(this.matrix),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(this.next_track_id)}print(e){super.printHeader(e),e.log(e.indent+`creation_time: `+this.creation_time),e.log(e.indent+`modification_time: `+this.modification_time),e.log(e.indent+`timescale: `+this.timescale),e.log(e.indent+`duration: `+this.duration),e.log(e.indent+`rate: `+this.rate),e.log(e.indent+`volume: `+(this.volume>>8)),e.log(e.indent+`matrix: `+this.matrix.join(`, `)),e.log(e.indent+`next_track_id: `+this.next_track_id)}},ct=class extends P{static{this.fourcc=`mett`}parse(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}},lt=class extends P{static{this.fourcc=`metx`}parse(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.parseFooter(e)}},ut=class extends _{constructor(...e){super(...e),this.box_name=`AV1CodecConfigurationBox`}static{this.fourcc=`av1C`}parse(e){let t=e.readUint8();if((t>>7&1)!=1){m.error(`BoxParser`,`av1C marker problem`,e.isofile);return}if(this.version=t&127,this.version!==1){m.error(`BoxParser`,`av1C version `+this.version+` not supported`,e.isofile);return}if(t=e.readUint8(),this.seq_profile=t>>5&7,this.seq_level_idx_0=t&31,t=e.readUint8(),this.seq_tier_0=t>>7&1,this.high_bitdepth=t>>6&1,this.twelve_bit=t>>5&1,this.monochrome=t>>4&1,this.chroma_subsampling_x=t>>3&1,this.chroma_subsampling_y=t>>2&1,this.chroma_sample_position=t&3,t=e.readUint8(),this.reserved_1=t>>5&7,this.reserved_1!==0){m.error(`BoxParser`,`av1C reserved_1 parsing problem`,e.isofile);return}if(this.initial_presentation_delay_present=t>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=t&15;else if(this.reserved_2=t&15,this.reserved_2!==0){m.error(`BoxParser`,`av1C reserved_2 parsing problem`,e.isofile);return}let n=this.size-this.hdr_size-4;this.configOBUs=e.readUint8Array(n)}},dt=class extends v{constructor(...e){super(...e),this.box_name=`ElementaryStreamDescriptorBox`}static{this.fourcc=`esds`}parse(e){this.parseFullHeader(e);let t=e.readUint8Array(this.size-this.hdr_size);if(`MPEG4DescriptorParser`in k){let e=new k.MPEG4DescriptorParser;this.esd=e.parseOneDescriptor(new o(t.buffer,0))}}},ft=class extends M{constructor(...e){super(...e),this.box_name=`siDecompressionParamBox`}static{this.fourcc=`wave`}},pt=class extends _{constructor(...e){super(...e),this.box_name=`LCEVCConfigurationBox`}static{this.fourcc=`lvcC`}parse(e){if(this.configurationVersion=e.readUint8(),this.configurationVersion!==1){m.error(`BoxParser`,`lvcC version `+this.configurationVersion+` not supported`,e.isofile);return}this.LCEVCProfileIndication=e.readUint8(),this.LCEVCLevelIndication=e.readUint8();let t=e.readUint8();this.chroma_format_idc=t>>6&3,this.bit_depth_luma_minus8=t>>3&7,this.bit_depth_chroma_minus8=t&7,t=e.readUint8(),this.lengthSizeMinusOne=t>>6&3;let n=t&63;if(n!==63||(this.pic_width_in_luma_samples=e.readUint32(),this.pic_height_in_luma_samples=e.readUint32(),t=e.readUint8(),this.sc_in_stream=t>>7&1,this.gc_in_stream=t>>6&1,this.ai_in_stream=t>>5&1,n=t&31,n!==31)){m.error(`BoxParser`,`lvcC reserved parsing problem`,e.isofile);return}this.nalu_arrays=[];let r=e.readUint8();for(let i=0;i>6&3,n!==0){m.error(`BoxParser`,`lvcC reserved parsing problem`,e.isofile);return}r.nalu_type=t&63;let i=e.readUint16();for(let t=0;t>4,this.chromaSubsampling=t>>1&7,this.videoFullRangeFlag=t&1,this.colourPrimaries=e.readUint8(),this.transferCharacteristics=e.readUint8(),this.matrixCoefficients=e.readUint8(),this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)}else{this.profile=e.readUint8(),this.level=e.readUint8();let t=e.readUint8();this.bitDepth=t>>4&15,this.colorSpace=t&15,t=e.readUint8(),this.chromaSubsampling=t>>4&15,this.transferFunction=t>>1&7,this.videoFullRangeFlag=t&1,this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)}}},ht=class extends v{constructor(...e){super(...e),this.box_name=`VvcConfigurationBox`}static{this.fourcc=`vvcC`}parse(e){this.parseFullHeader(e);let t={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(e){this.held_bits=e.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(e){this.held_bits=e.readUint16(),this.num_held_bits=16},extract_bits:function(e){let t=this.held_bits>>this.num_held_bits-e&(1<1){t.stream_read_1_bytes(e),this.ptl_sublayer_present_mask=0;for(let e=this.num_sublayers-2;e>=0;--e){let n=t.extract_bits(1);this.ptl_sublayer_present_mask|=n<1;++e)t.extract_bits(1);this.sublayer_level_idc=[];for(let t=this.num_sublayers-2;t>=0;--t)this.ptl_sublayer_present_mask&1<>7}else(this.colour_type===`rICC`||this.colour_type===`prof`)&&(this.ICC_profile=e.readUint8Array(this.size-4))}};function H(e,t){let n=Number(e).toString(16);for(t=t===void 0?2:t;n.length>=1;e+=H(n,0),e+=`.`,this.hvcC.general_tier_flag===0?e+=`L`:e+=`H`,e+=this.hvcC.general_level_idc;let r=!1,i=``;for(let e=5;e>=0;e--)(this.hvcC.general_constraint_indicator[e]||r)&&(i=`.`+H(this.hvcC.general_constraint_indicator[e],0)+i,r=!0);e+=i}return e}},Ct=class extends W{constructor(...e){super(...e),this.box_name=`HEVCSampleEntry`}static{this.fourcc=`hvc1`}},wt=class extends W{static{this.fourcc=`hvc2`}},Tt=class extends W{constructor(...e){super(...e),this.box_name=`HEVCSampleEntry`,this.colrs=[],this.subBoxNames=[`colr`]}static{this.fourcc=`hev1`}},Et=class extends W{static{this.fourcc=`hev2`}},Dt=class extends I{constructor(...e){super(...e),this.box_name=`HEVCTileSampleSampleEntry`}static{this.fourcc=`hvt1`}},Ot=class extends I{constructor(...e){super(...e),this.box_name=`LHEVCSampleEntry`}static{this.fourcc=`lhe1`}},kt=class extends I{constructor(...e){super(...e),this.box_name=`LHEVCSampleEntry`}static{this.fourcc=`lhv1`}},At=class extends I{constructor(...e){super(...e),this.box_name=`LCEVCSampleEntry`}static{this.fourcc=`lvc1`}getCodec(){let e=super.getCodec();return this.lvcC&&(e+=`.`,e+=`vprf`,e+=this.lvcC.LCEVCProfileIndication,e+=`.`,e+=`vlev`,e+=this.lvcC.LCEVCLevelIndication),e}},jt=class extends I{static{this.fourcc=`dvh1`}},Mt=class extends I{static{this.fourcc=`dvhe`}},Nt=class extends I{getCodec(){let e=super.getCodec();if(this.vvcC){e+=`.`+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?e+=`.H`:e+=`.L`,e+=this.vvcC.general_level_idc;let t=``;if(this.vvcC.general_constraint_info){let e=[],n=0;n|=this.vvcC.ptl_frame_only_constraint_flag<<7,n|=this.vvcC.ptl_multilayer_enabled_flag<<6;let r;for(let t=0;t>2&63,e.push(n),n&&(r=t),n=this.vvcC.general_constraint_info[t]>>2&3;if(r===void 0)t=`.CA`;else{t=`.C`;let n=`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`,i=0,a=0;for(let o=0;o<=r;++o)for(i=i<<8|e[o],a+=8;a>=5;){let e=i>>a-5&31;t+=n[e],a-=5,i&=(1<>6,this.sample_depends_on[n]=t>>4&3,this.sample_is_depended_on[n]=t>>2&3,this.sample_has_redundancy[n]=t&3}}},bn=class extends v{constructor(...e){super(...e),this.box_name=`SampleGroupDescriptionBox`}static{this.fourcc=`sgpd`}parse(e){this.parseFullHeader(e),this.grouping_type=e.readString(4),m.debug(`BoxParser`,`Found Sample Groups of type `+this.grouping_type),this.default_length=this.version===1?e.readUint32():0,this.version>=2&&(this.default_group_description_index=e.readUint32()),this.entries=[];let t=e.readUint32();for(let n=0;n=2&&e.writeUint32(this.default_sample_description_index),e.writeUint32(this.entries.length);for(let t=0;t>31&1,referenced_size:t&2147483647,subsegment_duration:n,starts_with_SAP:r>>31&1,SAP_type:r>>28&7,SAP_delta_time:r&268435455})}}write(e){let t=this.earliest_presentation_time>r||this.first_offset>r||this.version===1;this.version=+!!t,this.size=12+12*this.references.length,this.size+=t?16:8,this.flags=0,this.writeHeader(e),e.writeUint32(this.reference_ID),e.writeUint32(this.timescale),t?(e.writeUint64(this.earliest_presentation_time),e.writeUint64(this.first_offset)):(e.writeUint32(this.earliest_presentation_time),e.writeUint32(this.first_offset)),e.writeUint16(0),e.writeUint16(this.references.length);for(let t=0;t0&&this.sample_size===0&&(t=!1),this.size=8,t||(this.size+=4*this.sample_sizes.length),this.writeHeader(e),e.writeUint32(this.sample_size),e.writeUint32(this.sample_sizes.length),t||e.writeUint32Array(this.sample_sizes)}unpack(e){for(let t=0;tr||this.version===1;this.version=+!!t,this.size=4,this.size+=t?4:0,this.flags=0,this.writeHeader(e),t?e.writeUint64(this.baseMediaDecodeTime):e.writeUint32(this.baseMediaDecodeTime)}},An=class extends v{constructor(...e){super(...e),this.box_name=`TrackFragmentHeaderBox`}static{this.fourcc=`tfhd`}parse(e){this.parseFullHeader(e);let t=0;this.track_id=e.readUint32(),this.size-this.hdr_size>t&&this.flags&1?(this.base_data_offset=e.readUint64(),t+=8):this.base_data_offset=0,this.size-this.hdr_size>t&&this.flags&2?(this.default_sample_description_index=e.readUint32(),t+=4):this.default_sample_description_index=0,this.size-this.hdr_size>t&&this.flags&8?(this.default_sample_duration=e.readUint32(),t+=4):this.default_sample_duration=0,this.size-this.hdr_size>t&&this.flags&16?(this.default_sample_size=e.readUint32(),t+=4):this.default_sample_size=0,this.size-this.hdr_size>t&&this.flags&32?(this.default_sample_flags=e.readUint32(),t+=4):this.default_sample_flags=0}write(e){this.version=0,this.size=4,this.flags&1&&(this.size+=8),this.flags&2&&(this.size+=4),this.flags&8&&(this.size+=4),this.flags&16&&(this.size+=4),this.flags&32&&(this.size+=4),this.writeHeader(e),e.writeUint32(this.track_id),this.flags&1&&e.writeUint64(this.base_data_offset),this.flags&2&&e.writeUint32(this.default_sample_description_index),this.flags&8&&e.writeUint32(this.default_sample_duration),this.flags&16&&e.writeUint32(this.default_sample_size),this.flags&32&&e.writeUint32(this.default_sample_flags)}},jn=class extends v{constructor(...e){super(...e),this.box_name=`TrackHeaderBox`,this.layer=0,this.alternate_group=0}static{this.fourcc=`tkhd`}parse(e){this.parseFullHeader(e),this.version===1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint32()),e.readUint32Array(2),this.layer=e.readInt16(),this.alternate_group=e.readInt16(),this.volume=e.readInt16()>>8,e.readUint16(),this.matrix=e.readInt32Array(9),this.width=e.readUint32(),this.height=e.readUint32()}write(e){let t=this.modification_time>r||this.creation_time>r||this.duration>r||this.version===1;this.version=+!!t,this.size=80,this.size+=t?12:0,this.flags=this.flags??3,this.writeHeader(e),t?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint32(this.duration)),e.writeUint32Array([0,0]),e.writeInt16(this.layer),e.writeInt16(this.alternate_group),e.writeInt16(this.volume<<8),e.writeInt16(0),e.writeInt32Array(this.matrix),e.writeUint32(this.width),e.writeUint32(this.height)}print(e){super.printHeader(e),e.log(e.indent+`creation_time: `+this.creation_time),e.log(e.indent+`modification_time: `+this.modification_time),e.log(e.indent+`track_id: `+this.track_id),e.log(e.indent+`duration: `+this.duration),e.log(e.indent+`volume: `+(this.volume>>8)),e.log(e.indent+`matrix: `+this.matrix.join(`, `)),e.log(e.indent+`layer: `+this.layer),e.log(e.indent+`alternate_group: `+this.alternate_group),e.log(e.indent+`width: `+this.width),e.log(e.indent+`height: `+this.height)}},G=class extends v{constructor(...e){super(...e),this.box_name=`TrackExtendsBox`}static{this.fourcc=`trex`}parse(e){this.parseFullHeader(e),this.track_id=e.readUint32(),this.default_sample_description_index=e.readUint32(),this.default_sample_duration=e.readUint32(),this.default_sample_size=e.readUint32(),this.default_sample_flags=e.readUint32()}write(e){this.version=0,this.flags=0,this.size=20,this.writeHeader(e),e.writeUint32(this.track_id),e.writeUint32(this.default_sample_description_index),e.writeUint32(this.default_sample_duration),e.writeUint32(this.default_sample_size),e.writeUint32(this.default_sample_flags)}},Mn=class extends v{constructor(...e){super(...e),this.box_name=`TrackRunBox`,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[]}static{this.fourcc=`trun`}parse(e){this.parseFullHeader(e);let t=0;if(this.sample_count=e.readUint32(),t+=4,this.size-this.hdr_size>t&&this.flags&1?(this.data_offset=e.readInt32(),t+=4):this.data_offset=0,this.size-this.hdr_size>t&&this.flags&4?(this.first_sample_flags=e.readUint32(),t+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>t)for(let t=0;te.nb_samples!==o)){m.error(`ISOFile`,`Cannot set segment options for track ${e}: nbSamples (${o}) does not match existing tracks`);return}let c=this.getTrackById(e);if(c){let n={id:e,user:t,trak:c,segmentStream:void 0,nb_samples:o,nb_samples_per_fragment:s,size_per_segment:r,rapAlignement:i,normalizeAudioSampleEntriesForMSE:a,state:{lastFragmentSampleNumber:0,lastSegmentSampleNumber:0,accumulatedSize:0}};this.fragmentedTracks.push(n),c.nextSample=0}this.discardMdatData&&m.warn(`ISOFile`,`Segmentation options set but discardMdatData is true, samples will not be segmented`)}unsetSegmentOptions(e){let t=-1;for(let n=0;n-1&&this.fragmentedTracks.splice(t,1)}setExtractionOptions(e,t,{nbSamples:n=1e3}={}){let r=this.getTrackById(e);r&&(this.extractedTracks.push({id:e,user:t,trak:r,nb_samples:n,samples:[]}),r.nextSample=0),this.discardMdatData&&m.warn(`ISOFile`,`Extraction options set but discardMdatData is true, samples will not be extracted`)}unsetExtractionOptions(e){let t=-1;for(let n=0;n-1&&this.extractedTracks.splice(t,1)}parse(){if(!this.restoreParsePosition||this.restoreParsePosition())for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else{this.saveParsePosition&&this.saveParsePosition();let e=j(this.stream,!1);if(e.code===0){if(this.processIncompleteBox){if(this.processIncompleteBox(e))continue;return}return}if(e.code===1){let t=e.box;if(this.boxes.push(t),t.type===`uuid`)this[t.uuid]!==void 0&&m.warn(`ISOFile`,`Duplicate Box of uuid: `+t.uuid+`, overriding previous occurrence`),this[t.uuid]=t;else switch(t.type){case`mdat`:this.mdats.push(t),this.transferMdatData(t);break;case`moof`:this.moofs.push(t);break;case`free`:case`skip`:break;case`moov`:this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[t.type]===void 0?(this[t.type]=t,Array.isArray(this[t.type+`s`])&&this[t.type+`s`].push(t)):Array.isArray(this[t.type+`s`])?(m.info(`ISOFile`,`Found multiple boxes of type ${t.type} in ISOFile, adding to array`),this[t.type+`s`].push(t)):(m.warn(`ISOFile`,`Found multiple boxes of type ${t.type} but no array exists. Creating array dynamically.`),this[t.type+`s`]=[this[t.type],t])}this.updateUsedBytes&&this.updateUsedBytes(t,e)}else if(e.code===-1){m.error(`ISOFile`,`Invalid data found while parsing box of type '${e.type}' at position ${e.start}. Aborting parsing.`,this);break}}}checkBuffer(e){if(!e)throw Error(`Buffer must be defined and non empty`);return e.byteLength===0?(m.warn(`ISOFile`,`Ignoring empty buffer (fileStart: `+e.fileStart+`)`),this.stream.logBufferLevel(),!1):(m.info(`ISOFile`,`Processing buffer (fileStart: `+e.fileStart+`)`),e.usedBytes=0,this.stream.insertBuffer(e),this.stream.logBufferLevel(),this.stream.initialized()?!0:(m.warn(`ISOFile`,`Not ready to start parsing`),!1))}appendBuffer(e,t){let n;if(this.checkBuffer(e))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||=(this.buildSampleLists(),!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(t),this.nextSeekPosition?(n=this.nextSeekPosition,this.nextSeekPosition=void 0):n=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(n=this.stream.getEndFilePositionAfter(n))):n=this.nextParsePosition?this.nextParsePosition:0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(m.info(`ISOFile`,`Done processing buffer (fileStart: `+e.fileStart+`) - next buffer to fetch should have a fileStart position of `+n),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),m.info(`ISOFile`,`Sample data size in memory: `+this.getAllocatedSampleDataSize())),n}getFragmentDuration(){let e=this.getBox(`mvex`);if(!e)return;if(e.mehd)return{num:e.mehd.fragment_duration,den:this.moov.mvhd.timescale};let t=this.getBoxes(`trak`,!1),n={num:0,den:1};for(let e of t){let t=e.samples_duration,r=e.mdia.mdhd.timescale;t&&r&&t/r>n.num/n.den&&(n={num:t,den:r})}return n}getInfo(){if(!this.moov)return{hasMoov:!1,mime:``};let e=new Date(`1904-01-01T00:00:00Z`).getTime(),t=this.getBox(`mvex`)!==void 0,n={hasMoov:!0,duration:this.moov.mvhd.duration,timescale:this.moov.mvhd.timescale,isFragmented:t,fragment_duration:this.getFragmentDuration(),isProgressive:this.isProgressive,hasIOD:this.moov.iods!==void 0,brands:[this.ftyp.major_brand].concat(this.ftyp.compatible_brands),created:new Date(e+this.moov.mvhd.creation_time*1e3),modified:new Date(e+this.moov.mvhd.modification_time*1e3),tracks:[],audioTracks:[],videoTracks:[],subtitleTracks:[],metadataTracks:[],hintTracks:[],otherTracks:[],mime:``};for(let t=0;t0?n.mime+=`video/mp4; codecs="`:n.audioTracks&&n.audioTracks.length>0?n.mime+=`audio/mp4; codecs="`:n.mime+=`application/mp4; codecs="`;for(let e=0;ee.trak.nextSamplen.nb_samples_per_fragment,s=a-n.state.lastSegmentSampleNumber>n.nb_samples,c=o||a%n.nb_samples_per_fragment===0,l=s||a%n.nb_samples===0,u=n.state.accumulatedSize>=n.size_per_segment,d=!n.rapAlignement||i.is_sync,f=e||r.nextSample+1>=r.samples.length;if(f&&!d&&m.warn(`ISOFile`,`Flushing track #`+n.id+` at sample #`+r.nextSample+` which is not a RAP, this may lead to playback issues`),c&&=d,l&&=d,u&&=d,c||u||f){o?m.warn(`ISOFile`,`Fragment on track #`+n.id+` is overdue, creating it with samples [`+n.state.lastFragmentSampleNumber+`, `+r.nextSample+`]`):m.debug(`ISOFile`,`Creating media fragment on track #`+n.id+` for samples [`+n.state.lastFragmentSampleNumber+`, `+r.nextSample+`]`);let e=this.createFragment(n.id,n.state.lastFragmentSampleNumber,r.nextSample,n.segmentStream);if(e)n.segmentStream=e,n.state.lastFragmentSampleNumber=r.nextSample+1;else{t.add(n.id);continue}}(l||u||f)&&(s?m.warn(`ISOFile`,`Segment on track #`+n.id+` is overdue, sending it with samples [`+Math.max(0,r.nextSample-n.nb_samples)+`, `+(r.nextSample-1)+`]`):m.info(`ISOFile`,`Sending fragmented data on track #`+n.id+` for samples [`+Math.max(0,r.nextSample-n.nb_samples)+`, `+(r.nextSample-1)+`]`),m.info(`ISOFile`,`Sample data size in memory: `+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(n.id,n.user,n.segmentStream.buffer,r.nextSample+1,e||r.nextSample+1>=r.samples.length),n.segmentStream=void 0,n.state.accumulatedSize=0,n.state.lastSegmentSampleNumber=r.nextSample+1),r.nextSample++}}}if(this.onSamples!==void 0)for(let e=0;e=n.samples.length)&&(m.debug(`ISOFile`,`Sending samples on track #`+t.id+` for sample `+n.nextSample),this.onSamples&&this.onSamples(t.id,t.user,t.samples),t.samples=[],t!==this.extractedTracks[e]))break}}}}getBox(e){let t=this.getBoxes(e,!0);return t.length?t[0]:void 0}getBoxes(e,t){let n=[],r=i=>{i instanceof _&&i.type&&i.type===e&&n.push(i);let a=[];i.boxes&&a.push(...i.boxes),i.entries&&a.push(...i.entries),i.item_infos&&a.push(...i.item_infos),i.references&&a.push(...i.references);for(let e of a){if(n.length&&t)return;r(e)}};return r(this),n}getTrackSamplesInfo(e){let t=this.getTrackById(e);if(t)return t.samples}getTrackSample(e,t){let n=this.getTrackById(e);return this.getSample(n,t)}releaseUsedSamples(e,t){let n=0,r=this.getTrackById(e);r.lastValidSample||=0;for(let e=r.lastValidSample;ee*s.timescale){i=o-1;break}t&&s.is_sync&&(r=o)}for(t&&(i=r),e=n.samples[i].cts,n.nextSample=i,this.resetFragmentedTrackStateAfterSeek(n,i),this.resetExtractedTrackStateAfterSeek(n);n.samples[i].alreadyRead===n.samples[i].size&&n.samples[i+1];)i++;let o=n.samples[i].offset+n.samples[i].alreadyRead;return m.info(`ISOFile`,`Seeking to `+(t?`RAP`:``)+` sample #`+n.nextSample+` on track `+n.tkhd.track_id+`, time `+m.getDurationString(e,a)+` and offset: `+o),{offset:o,time:e/a}}resetFragmentedTrackStateAfterSeek(e,t){let n=this.fragmentedTracks.find(t=>t.trak===e);n&&(n.state.lastFragmentSampleNumber=t,n.state.lastSegmentSampleNumber=t,n.state.accumulatedSize=0,n.segmentStream=void 0)}resetExtractedTrackStateAfterSeek(e){let t=this.extractedTracks.find(t=>t.trak===e);t&&(t.samples=[])}getTrackDuration(e){if(!e.samples)return 1/0;let t=e.samples[e.samples.length-1];return(t.cts+t.duration)/t.timescale}seek(e,t){let n=this.moov,r={offset:1/0,time:1/0};if(this.moov){for(let i=0;ithis.getTrackDuration(a))continue;let o=this.seekTrack(e,t,a);o.offset=0;e--)s[e]()}return a.buffer}save(e){let t=new o;return t.isofile=this,this.write(t),t.save(e)}getBuffer(){let e=new o;return e.isofile=this,this.write(e),e}static normalizeAudioSampleEntriesForMSEFragmentedInit(e,t){let n=[];for(let r of e)if(t?.has(r.tkhd.track_id))for(let e of r.mdia.minf.stbl.stsd?.entries??[]){if(!(e instanceof qt))continue;let t=e.wave?.esds;if(e.esds||!t)continue;let r=e.esds,i=e.wave,a=e.boxes;n.push(()=>{e.esds=r,e.wave=i,e.boxes=a});let o=Array.isArray(e.boxes)?e.boxes.filter(e=>e?.type!==`wave`&&e?.type!==`esds`):[];e.esds=t,e.boxes=[...o,t],e.wave=void 0}return n}initializeSegmentation(t){if(this.onSegment||m.warn(`MP4Box`,`No segmentation callback set!`),t!==void 0&&t!==`combined`&&t!==`per-track`)throw Error(`Invalid segmentation mode: ${t}`);this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.resetTables());let n=[];for(let e of this.fragmentedTracks){let t=this.getTrackById(e.id);t?n.push({id:e.id,user:e.user,trak:t}):m.warn(`ISOFile`,`Track with id ${e.id} not found, skipping fragmentation initialization`)}let r=this.moov?.mvex?.mehd?.fragment_duration,i=new Set(this.fragmentedTracks.filter(e=>e.normalizeAudioSampleEntriesForMSE!==!1).map(e=>e.id));if(t===`per-track`)return n.map(({id:t,user:n,trak:a})=>{let o=new B;return o.addBox(this.moov.mvhd),o.addBox(a),{id:t,user:n,buffer:e.writeInitializationSegment(this.ftyp,o,r,i)}});let a=new B;a.addBox(this.moov.mvhd);for(let e of n)a.addBox(e.trak);return{tracks:n.map(({id:e,user:t})=>({id:e,user:t})),buffer:e.writeInitializationSegment(this.ftyp,a,r,i)}}resetTables(){this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0;for(let e=0;e=2){let n=r[t].grouping_type+`/0`,i=new Fn(r[t].grouping_type,0);e.sample_groups_info[n]||(e.sample_groups_info[n]=i)}}else if(i){for(let e=0;e=2){let n=i[e].grouping_type+`/0`,r=new Fn(i[e].grouping_type,0);r.is_fragment=!0,t.sample_groups_info[n]||(t.sample_groups_info[n]=r)}}}static setSampleGroupProperties(e,t,n,r){t.sample_groups=[];for(let e in r)if(t.sample_groups[e]={grouping_type:r[e].grouping_type,grouping_type_parameter:r[e].grouping_type_parameter},n>=r[e].last_sample_in_run&&(r[e].last_sample_in_run<0&&(r[e].last_sample_in_run=0),r[e].entry_index++,r[e].entry_index<=r[e].sbgp.entries.length-1&&(r[e].last_sample_in_run+=r[e].sbgp.entries[r[e].entry_index].sample_count)),r[e].entry_index<=r[e].sbgp.entries.length-1?t.sample_groups[e].group_description_index=r[e].sbgp.entries[r[e].entry_index].group_description_index:t.sample_groups[e].group_description_index=-1,t.sample_groups[e].group_description_index!==0){let n;if(n=r[e].fragment_description?r[e].fragment_description:r[e].description,t.sample_groups[e].group_description_index>0){let r;r=t.sample_groups[e].group_description_index>65535?(t.sample_groups[e].group_description_index>>16)-1:t.sample_groups[e].group_description_index-1,n&&r>=0&&(t.sample_groups[e].description=n.entries[r])}else n&&n.version>=2&&n.default_group_description_index>0&&(t.sample_groups[e].description=n.entries[n.default_group_description_index-1])}}static process_sdtp(e,t,n){t&&(e?(t.is_leading=e.is_leading[n],t.depends_on=e.sample_depends_on[n],t.is_depended_on=e.sample_is_depended_on[n],t.has_redundancy=e.sample_has_redundancy[n]):(t.is_leading=0,t.depends_on=0,t.is_depended_on=0,t.has_redundancy=0))}buildSampleLists(){for(let e=0;ey&&(b++,y<0&&(y=0),y+=d.sample_counts[b]),n>0?(t.samples[n-1].duration=d.sample_deltas[b],t.samples_duration+=t.samples[n-1].duration,E.dts=t.samples[n-1].dts+t.samples[n-1].duration):E.dts=0,f?(n>=x&&(S++,x<0&&(x=0),x+=f.sample_counts[S]),E.cts=t.samples[n].dts+f.sample_offsets[S]):E.cts=E.dts,p?(n===p.sample_numbers[C]-1?(E.is_sync=!0,C++):(E.is_sync=!1,E.degradation_priority=0),h&&h.entries[w].sample_delta+T===n+1&&(E.subsamples=h.entries[w].subsamples,T+=h.entries[w].sample_delta,w++)):E.is_sync=!0,e.process_sdtp(t.mdia.minf.stbl.sdtp,E,E.number),E.degradation_priority=g?g.priority[n]:0,h&&h.entries[w].sample_delta+T===n&&(E.subsamples=h.entries[w].subsamples,T+=h.entries[w].sample_delta),(_.length>0||v.length>0)&&e.setSampleGroupProperties(t,E,n,t.sample_groups_info)}n>0&&(t.samples[n-1].duration=Math.max(t.mdia.mdhd.duration-t.samples[n-1].dts,0),t.samples_duration+=t.samples[n-1].duration)}}updateSampleLists(){let t,n,r,i,a;if(this.moov!==void 0)for(;this.lastMoofIndex0&&e.initSampleGroups(l,c,c.sbgps,l.mdia.minf.stbl.sgpds,c.sgpds);for(let o=0;o0?g=l.samples[l.samples.length-1].dts+l.samples[l.samples.length-1].duration:(g=c.tfdt?c.tfdt.baseMediaDecodeTime:0,l.first_traf_merged=!0);let _=g;u.flags&2048&&(_=g+u.sample_composition_time_offset[d]);let v=!!(c.tfhd.flags&1),y=!!(c.tfhd.flags&131072),b=!!(u.flags&1),x=0;x=v?c.tfhd.base_data_offset:y||o===0?s.start:a;let S;S=o===0&&d===0?b?x+u.data_offset:x:a,a=S+m;let C=c.sample_number;c.sample_number++;let w={cts:_,description_index:f,description:l.mdia.minf.stbl.stsd.entries[f],dts:g,duration:h,moof_number:this.lastMoofIndex,number_in_traf:C,number:l.samples.length,offset:S,size:m,timescale:l.mdia.mdhd.timescale,track_id:l.tkhd.track_id,is_sync:!(p>>16&1),is_leading:p>>26&3,depends_on:p>>24&3,is_depended_on:p>>22&3,has_redundancy:p>>20&3,degradation_priority:p&65535};c.first_sample_index=l.samples.length,l.samples.push(w),(c.sbgps.length>0||c.sgpds.length>0||l.mdia.minf.stbl.sbgps.length>0||l.mdia.minf.stbl.sgpds.length>0)&&e.setSampleGroupProperties(l,w,w.number_in_traf,c.sample_groups_info)}}if(c.subs){l.has_fragment_subsamples=!0;let e=c.first_sample_index;for(let t=0;t-1)i=e.buffers[r],a=i.fileStart;else for(let t of this.mdats)if(!t.stream)m.debug(`ISOFile`,`mdat stream not yet fully read for #`+this.mdats.indexOf(t)+` mdat`);else if(r=t.stream.findPosition(!0,n.offset+n.alreadyRead-t.start-t.hdr_size,!1),r>-1){e=t.stream,i=t.stream.buffers[r],a=t.start+t.hdr_size+i.fileStart;break}if(i){let r=i.byteLength-(n.offset+n.alreadyRead-a);if(n.size-n.alreadyRead<=r)return m.debug(`ISOFile`,`Getting sample #`+t+` data (alreadyRead: `+n.alreadyRead+` offset: `+(n.offset+n.alreadyRead-a)+` read size: `+(n.size-n.alreadyRead)+` full size: `+n.size+`)`),o.memcpy(n.data.buffer,n.alreadyRead,i,n.offset+n.alreadyRead-a,n.size-n.alreadyRead),i.usedBytes+=n.size-n.alreadyRead,e.logBufferLevel(),n.alreadyRead=n.size,n;if(r===0)return;m.debug(`ISOFile`,`Getting sample #`+t+` partial data (alreadyRead: `+n.alreadyRead+` offset: `+(n.offset+n.alreadyRead-a)+` read size: `+r+` full size: `+n.size+`)`),o.memcpy(n.data.buffer,n.alreadyRead,i,n.offset+n.alreadyRead-a,r),n.alreadyRead+=r,i.usedBytes+=r,e.logBufferLevel()}else return}}}releaseSample(e,t){let n=e.samples[t];return n.data?(this.samplesDataSize-=n.size,n.data=void 0,n.alreadyRead=0,n.size):0}getAllocatedSampleDataSize(){return this.samplesDataSize}getCodecs(){let e=``;for(let t=0;t0&&(e+=`,`),e+=n.mdia.minf.stbl.stsd.entries[0].getCodec()}return e}getTrexById(e){if(this.moov&&this.moov.mvex)for(let t=0;t0?n.ipro.protections[n.iinf.item_infos[t].item_protection_index-1]:void 0}}if(n.grpl)for(let e=0;e0&&t.property_index-1-1){let a=this.stream.buffers[i],s=a.byteLength-(r.offset+r.alreadyRead-a.fileStart);if(r.length-r.alreadyRead<=s)m.debug(`ISOFile`,`Getting item #`+e+` extent #`+n+` data (alreadyRead: `+r.alreadyRead+` offset: `+(r.offset+r.alreadyRead-a.fileStart)+` read size: `+(r.length-r.alreadyRead)+` full extent size: `+r.length+` full item size: `+t.size+`)`),o.memcpy(t.data.buffer,t.alreadyRead,a,r.offset+r.alreadyRead-a.fileStart,r.length-r.alreadyRead),(!this.parsingMdat||this.discardMdatData)&&(a.usedBytes+=r.length-r.alreadyRead),this.stream.logBufferLevel(),t.alreadyRead+=r.length-r.alreadyRead,r.alreadyRead=r.length;else{m.debug(`ISOFile`,`Getting item #`+e+` extent #`+n+` partial data (alreadyRead: `+r.alreadyRead+` offset: `+(r.offset+r.alreadyRead-a.fileStart)+` read size: `+s+` full extent size: `+r.length+` full item size: `+t.size+`)`),o.memcpy(t.data.buffer,t.alreadyRead,a,r.offset+r.alreadyRead-a.fileStart,s),r.alreadyRead+=s,t.alreadyRead+=s,(!this.parsingMdat||this.discardMdatData)&&(a.usedBytes+=s),this.stream.logBufferLevel();return}}else return}}if(t.alreadyRead===t.size)return t}releaseItem(e){let t=this.items[e];if(t.data){this.itemsDataSize-=t.size,t.data=void 0,t.alreadyRead=0;for(let e=0;es){m.debug(`ISOFile`,`Transferring 'mdat' data from buffer #`+e+` (`+s+` to `+c+`)`);let n=c-s,r=new a(n),l=t.stream.getAbsoluteEndPosition();o.memcpy(r,0,i,s,n),r.fileStart=l,t.stream.insertBuffer(r),i.usedBytes+=n}}}}processIncompleteMdat(){let e=this.parsingMdat;return this.stream.seek(e.start+e.size,!1,this.discardMdatData)?(m.debug(`ISOFile`,`Found 'mdat' end in buffered data`),this.transferMdatData(),this.parsingMdat=void 0,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)}restoreParsePosition(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)}saveParsePosition(){this.lastBoxStartPosition=this.stream.getPosition()}updateUsedBytes(e,t){this.stream.addUsedBytes&&(e.type===`mdat`?(this.stream.addUsedBytes(e.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(e.size-e.hdr_size)):this.stream.addUsedBytes(e.size))}addBox(e){return _.prototype.addBox.call(this,e)}init(e={}){let t=this.addBox(new Je);t.major_brand=e.brands&&e.brands[0]||`iso4`,t.minor_version=0,t.compatible_brands=e.brands||[`iso4`];let n=this.addBox(new B);n.addBox(new V);let r=n.addBox(new st);return r.timescale=e.timescale||600,r.rate=e.rate||65536,r.creation_time=0,r.modification_time=0,r.duration=e.duration||0,r.volume=e.width?0:256,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.next_track_id=1,this}addTrack(e={}){this.moov||this.init(e);let t=e||{};t.width=t.width||320,t.height=t.height||320,t.id=t.id||this.moov.mvhd.next_track_id,t.type=t.type||`avc1`;let n=this.moov.addBox(new be);this.moov.mvhd.next_track_id=t.id+1;let r=n.addBox(new jn);r.flags=7,r.creation_time=0,r.modification_time=0,r.track_id=t.id,r.duration=t.duration||0,r.layer=t.layer||0,r.alternate_group=0,r.volume=1,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.width=t.width<<16,r.height=t.height<<16;let i=n.addBox(new Se),a=i.addBox(new Ze);a.creation_time=0,a.modification_time=0,a.timescale=t.timescale||1,a.duration=t.media_duration||0,a.language=t.language||`und`;let s=i.addBox(new Ye);s.handler=t.hdlr||`vide`,s.name=t.name||`Track created with MP4Box.js`;let c=i.addBox(new qe);c.extended_language=t.language||`fr-FR`;let l=i.addBox(new Ce),u=O.sampleEntry[t.type];if(!u)return;let d=new u;if(d.data_reference_index=1,d instanceof I){let e=d,n=l.addBox(new Pn);n.graphicsmode=0,n.opcolor=[0,0,0],e.width=t.width,e.height=t.height,e.horizresolution=72<<16,e.vertresolution=72<<16,e.frame_count=1,e.compressorname=t.type+` Compressor`,e.depth=24,t.avcDecoderConfigRecord?e.addBox(new ue(t.avcDecoderConfigRecord.byteLength)).parse(new o(t.avcDecoderConfigRecord)):t.hevcDecoderConfigRecord&&e.addBox(new Xe(t.hevcDecoderConfigRecord.byteLength)).parse(new o(t.hevcDecoderConfigRecord))}else if(d instanceof L){let e=d,n=l.addBox(new Sn);n.balance=t.balance||0,e.channel_count=t.channel_count||2,e.samplesize=t.samplesize||16,e.samplerate=t.samplerate||65536}else d instanceof se?l.addBox(new me):d instanceof F?(l.addBox(new wn),d instanceof mn&&(d.namespace=t.namespace||`nonamespace`,d.schema_location=t.schema_location||``,d.auxiliary_mime_types=t.auxiliary_mime_types||``)):(d instanceof P||d instanceof R,l.addBox(new he));t.description&&d.addBox.call(d,t.description),t.description_boxes&&t.description_boxes.forEach(function(e){d.addBox.call(d,e)});let f=l.addBox(new we).addBox(new Ke),p=new Nn;p.flags=1,f.addEntry(p);let m=l.addBox(new Te);m.addBox(new En).addEntry(d);let h=m.addBox(new On);h.sample_counts=[],h.sample_deltas=[];let g=m.addBox(new Tn);g.first_chunk=[],g.samples_per_chunk=[],g.sample_description_index=[];let _=m.addBox(new Cn);_.chunk_offsets=[];let v=m.addBox(new Dn);v.sample_sizes=[];let y=this.moov.mvex.addBox(new G);return y.track_id=t.id,y.default_sample_description_index=t.default_sample_description_index||1,y.default_sample_duration=t.default_sample_duration||0,y.default_sample_size=t.default_sample_size||0,y.default_sample_flags=t.default_sample_flags||0,this.buildTrakSampleLists(n),t.id}addSample(e,t,{sample_description_index:n,duration:r=1,cts:i=0,dts:a=0,is_sync:o=!1,is_leading:s=0,depends_on:c=0,is_depended_on:l=0,has_redundancy:u=0,degradation_priority:d=0,subsamples:f,offset:p=0}={}){let m=this.getTrackById(e);if(m===void 0)return;let h=n?n-1:0,g={number:m.samples.length,track_id:m.tkhd.track_id,timescale:m.mdia.mdhd.timescale,description_index:h,description:m.mdia.minf.stbl.stsd.entries[h],data:t,size:t.byteLength,alreadyRead:t.byteLength,duration:r,cts:i,dts:a,is_sync:o,is_leading:s,depends_on:c,is_depended_on:l,has_redundancy:u,degradation_priority:d,offset:p,subsamples:f};m.samples.push(g),m.samples_size+=g.size,m.samples_duration+=g.duration,m.first_dts===void 0&&(m.first_dts=a),this.processSamples();let _=this.addBox(this.createMoof([g]));_.computeSize(),_.trafs[0].truns[0].data_offset=_.size+8;let v=this.addBox(new z);return v.data=new Uint8Array(t),g}createMoof(e){if(e.length===0)return;if(e.some(t=>t.track_id!==e[0].track_id))throw Error(`Cannot create moof for samples from different tracks: `+e.map(e=>e.track_id).join(`, `));let t=e[0].track_id,n=this.getTrackById(t);if(!n)throw Error(`Cannot create moof for non-existing track: `+t);let r=new Ee,a=r.addBox(new ot);a.sequence_number=++this.nextMoofNumber;let o=r.addBox(new De),s=o.addBox(new An);s.track_id=t,s.flags=i;let c=o.addBox(new kn);c.baseMediaDecodeTime=e[0].dts-(n.first_dts||0);let l=o.addBox(new Mn);l.flags=3841,l.data_offset=0,l.first_sample_flags=0,l.sample_count=e.length;for(let t of e){let e=0;e=t.is_sync?1<<25:65536,l.sample_duration.push(t.duration),l.sample_size.push(t.size),l.sample_flags.push(e),l.sample_composition_time_offset.push(t.cts-t.dts)}return r}print(e){e.indent=``;for(let t=0;t=4;)this.compatible_brands[n]=e.readString(4),t-=4,n++}write(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,void 0,4),e.writeUint32(this.minor_version);for(let t=0;tq,ES_Descriptor:()=>Gn,MPEG4DescriptorParser:()=>qn}),Hn=3,K=4,Un=5,Wn=6,q=class e{constructor(e,t){this.tag=e,this.size=t,this.descs=[]}parse(e){this.data=e.readUint8Array(this.size)}findDescriptor(e){for(let t=0;t>3;return e===31&&t.data.length>=2&&(e=32+((t.data[0]&7)<<3)+((t.data[1]&224)>>5)),e}}},Kn={Descriptor:q,ES_Descriptor:Gn,DecoderConfigDescriptor:class extends q{constructor(e){super(K,e)}parse(e){this.oti=e.readUint8(),this.streamType=e.readUint8(),this.upStream=!!(this.streamType>>1&1),this.streamType>>>=2,this.bufferSize=e.readUint24(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32(),this.size-=13,this.parseRemainingDescriptors(e)}},DecoderSpecificInfo:class extends q{constructor(e){super(Un,e)}},SLConfigDescriptor:class extends q{constructor(e){super(Wn,e)}}},J={[Hn]:`ES_Descriptor`,[K]:`DecoderConfigDescriptor`,[Un]:`DecoderSpecificInfo`,[Wn]:`SLConfigDescriptor`},qn=class{constructor(){this.parseOneDescriptor=q.prototype.parseOneDescriptor}getDescriptorName(e){return J[e]}},Jn=class extends _{constructor(...e){super(...e),this.box_name=`AV1LayeredImageIndexingProperty`}static{this.fourcc=`a1lx`}parse(e){let t=((e.readUint8()&1)+1)*16;this.layer_size=[];for(let n=0;n<3;n++)t===16?this.layer_size[n]=e.readUint16():this.layer_size[n]=e.readUint32()}},Yn=class extends _{constructor(...e){super(...e),this.box_name=`OperatingPointSelectorProperty`}static{this.fourcc=`a1op`}parse(e){this.op_index=e.readUint8()}},Xn=class extends v{constructor(...e){super(...e),this.box_name=`AuxiliaryTypeProperty`}static{this.fourcc=`auxC`}parse(e){this.parseFullHeader(e),this.aux_type=e.readCString();let t=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=e.readUint8Array(t)}},Zn=class extends _{constructor(...e){super(...e),this.box_name=`BitRateBox`}static{this.fourcc=`btrt`}parse(e){this.bufferSizeDB=e.readUint32(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32()}},Qn=class extends v{constructor(...e){super(...e),this.box_name=`CodingConstraintsBox`}static{this.fourcc=`ccst`}parse(e){this.parseFullHeader(e);let t=e.readUint8();this.all_ref_pics_intra=(t&128)==128,this.intra_pred_used=(t&64)==64,this.max_ref_per_pic=(t&63)>>2,e.readUint24()}},$n=class extends _{constructor(...e){super(...e),this.box_name=`ComponentDefinitionBox`}static{this.fourcc=`cdef`}parse(e){this.channel_count=e.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[];for(let t=0;t=32768&&this.component_type_urls.push(e.readCString())}}},or=class extends v{constructor(...e){super(...e),this.box_name=`ChunkLargeOffsetBox`}static{this.fourcc=`co64`}parse(e){this.parseFullHeader(e);let t=e.readUint32();if(this.chunk_offsets=[],this.version===0)for(let n=0;n>5),this.coverage_regions=[];for(let n=0;n>6),t.sphere_region=this.parseSphereRegion(e,!0,!0),this.coverage_regions.push(t)}}parseSphereRegion(e,t,n){let r=new cr;return r.centre_azimuth=e.readInt32(),r.centre_elevation=e.readInt32(),r.centre_tilt=e.readInt32(),r.range_included_flag=t,t&&(r.azimuth_range=e.readUint32(),r.elevation_range=e.readUint32()),r.interpolate_included_flag=n,n&&(r.interpolate=(e.readUint8()&128)==128),r}},dr=class extends v{constructor(...e){super(...e),this.box_name=`CopyrightBox`}static{this.fourcc=`cprt`}parse(e){this.parseFullHeader(e),this.parseLanguage(e),this.notice=e.readCString()}},fr=class extends v{constructor(...e){super(...e),this.box_name=`CompatibleSchemeTypeBox`}static{this.fourcc=`csch`}parse(e){this.parseFullHeader(e),this.scheme_type=e.readString(4),this.scheme_version=e.readUint32(),this.flags&1&&(this.scheme_uri=e.readCString())}},Y=2147483647,pr=class extends v{constructor(...e){super(...e),this.box_name=`CompositionToDecodeBox`}static{this.fourcc=`cslg`}parse(e){this.parseFullHeader(e),this.version===0?(this.compositionToDTSShift=e.readInt32(),this.leastDecodeToDisplayDelta=e.readInt32(),this.greatestDecodeToDisplayDelta=e.readInt32(),this.compositionStartTime=e.readInt32(),this.compositionEndTime=e.readInt32()):this.version===1&&(this.compositionToDTSShift=e.readInt64(),this.leastDecodeToDisplayDelta=e.readInt64(),this.greatestDecodeToDisplayDelta=e.readInt64(),this.compositionStartTime=e.readInt64(),this.compositionEndTime=e.readInt64())}write(e){this.version=0,(this.compositionToDTSShift>Y||this.leastDecodeToDisplayDelta>Y||this.greatestDecodeToDisplayDelta>Y||this.compositionStartTime>Y||this.compositionEndTime>Y)&&(this.version=1),this.flags=0,this.version===0?(this.size=20,this.writeHeader(e),e.writeInt32(this.compositionToDTSShift),e.writeInt32(this.leastDecodeToDisplayDelta),e.writeInt32(this.greatestDecodeToDisplayDelta),e.writeInt32(this.compositionStartTime),e.writeInt32(this.compositionEndTime)):this.version===1&&(this.size=40,this.writeHeader(e),e.writeInt64(this.compositionToDTSShift),e.writeInt64(this.leastDecodeToDisplayDelta),e.writeInt64(this.greatestDecodeToDisplayDelta),e.writeInt64(this.compositionStartTime),e.writeInt64(this.compositionEndTime))}},mr=class extends v{constructor(...e){super(...e),this.box_name=`CompositionOffsetBox`}static{this.fourcc=`ctts`}parse(e){this.parseFullHeader(e);let t=e.readUint32();if(this.sample_counts=[],this.sample_offsets=[],this.version===0)for(let n=0;ne<0),this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length);for(let t=0;t>6,this.bsid=t>>1&31,this.bsmod=(t&1)<<2|n>>6&3,this.acmod=n>>3&7,this.lfeon=n>>2&1,this.bit_rate_code=n&3|r>>5&7}},gr=class extends _{constructor(...e){super(...e),this.box_name=`EC3SpecificBox`}static{this.fourcc=`dec3`}parse(e){let t=e.readUint16();this.data_rate=t>>3,this.num_ind_sub=t&7,this.ind_subs=[];for(let t=0;t>6,bsid:t>>1&31,bsmod:(t&1)<<4|n>>4&15,acmod:n>>1&7,lfeon:n&1,num_dep_sub:r>>1&15};this.ind_subs.push(i),i.num_dep_sub>0&&(i.chan_loc=(r&1)<<8|e.readUint8())}}},_r=class extends v{constructor(...e){super(...e),this.box_name=`FLACSpecificBox`}static{this.fourcc=`dfLa`}parse(e){this.parseFullHeader(e);let t=[],n=[`STREAMINFO`,`PADDING`,`APPLICATION`,`SEEKTABLE`,`VORBIS_COMMENT`,`CUESHEET`,`PICTURE`,`RESERVED`],r;do{r=e.readUint8();let i=Math.min(r&127,n.length-1);i?e.readUint8Array(e.readUint24()):(e.readUint8Array(13),this.samplerate=e.readUint32()>>12,e.readUint8Array(20)),t.push(n[i])}while(r&128);this.numMetadataBlocks=t.length+` (`+t.join(`, `)+`)`}},vr=class extends _{constructor(...e){super(...e),this.box_name=`hintimmediateBytesSent`}static{this.fourcc=`dimm`}parse(e){this.bytessent=e.readUint64()}},yr=class extends _{constructor(...e){super(...e),this.box_name=`hintlongestpacket`}static{this.fourcc=`dmax`}parse(e){this.time=e.readUint32()}},br=class extends _{constructor(...e){super(...e),this.box_name=`hintmediaBytesSent`}static{this.fourcc=`dmed`}parse(e){this.bytessent=e.readUint64()}},xr=class extends _{constructor(...e){super(...e),this.box_name=`OpusSpecificBox`}static{this.fourcc=`dOps`}parse(e){if(this.Version=e.readUint8(),this.OutputChannelCount=e.readUint8(),this.PreSkip=e.readUint16(),this.InputSampleRate=e.readUint32(),this.OutputGain=e.readInt16(),this.ChannelMappingFamily=e.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=e.readUint8(),this.CoupledCount=e.readUint8(),this.ChannelMapping=[];for(let t=0;te.segment_duration>r||e.media_time>r)||this.version===1;this.version=+!!t,this.size=4+12*this.entries.length,this.size+=t?8*this.entries.length:0,this.writeHeader(e),e.writeUint32(this.entries.length);for(let n=0;n>7,this.axis=t&1}},Wr=class extends v{constructor(...e){super(...e),this.box_name=`ItemPropertyAssociationBox`}static{this.fourcc=`ipma`}parse(e){this.parseFullHeader(e);let t=e.readUint32();this.associations=[];for(let n=0;n>7==1,property_index:this.flags&1?(t&127)<<8|e.readUint8():t&127})}this.associations.push({id:t,props:n})}}},Gr=class extends _{constructor(...e){super(...e),this.box_name=`ImageRotation`}static{this.fourcc=`irot`}parse(e){this.angle=e.readUint8()&3}},Kr=class extends v{constructor(...e){super(...e),this.box_name=`ImageSpatialExtentsProperty`}static{this.fourcc=`ispe`}parse(e){this.parseFullHeader(e),this.image_width=e.readUint32(),this.image_height=e.readUint32()}},qr=class extends v{constructor(...e){super(...e),this.box_name=`TAITimestampBox`}static{this.fourcc=`itai`}parse(e){this.TAI_timestamp=e.readUint64();let t=e.readUint8();this.sychronization_state=t>>7&1,this.timestamp_generation_failure=t>>6&1,this.timestamp_is_modified=t>>5&1}},Jr=class extends v{constructor(...e){super(...e),this.box_name=`KindBox`}static{this.fourcc=`kind`}parse(e){this.parseFullHeader(e),this.schemeURI=e.readCString(),this.isEndOfBox(e)||(this.value=e.readCString())}write(e){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value?this.value.length+1:0),this.writeHeader(e),e.writeCString(this.schemeURI),this.value&&e.writeCString(this.value)}},Yr=class extends v{constructor(...e){super(...e),this.box_name=`LevelAssignmentBox`}static{this.fourcc=`leva`}parse(e){this.parseFullHeader(e);let t=e.readUint8();this.levels=[];for(let n=0;n>7,t.assignment_type=r&127,t.assignment_type){case 0:t.grouping_type=e.readString(4);break;case 1:t.grouping_type=e.readString(4),t.grouping_type_parameter=e.readUint32();break;case 2:break;case 3:break;case 4:t.sub_track_id=e.readUint32();break;default:m.warn(`BoxParser`,`Unknown level assignment type: ${t.assignment_type}`)}}}},Xr=class extends _{constructor(...e){super(...e),this.box_name=`LHEVCConfigurationBox`}static{this.fourcc=`lhvC`}parse(e){this.configurationVersion=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3;let t=e.readUint8();this.numTemporalLayers=(t&13)>>3,this.temporalIdNested=(t&4)>>2,this.lengthSizeMinusOne=t&3,this.nalu_arrays=[];let n=e.readUint8();for(let r=0;r>7,n.nalu_type=t&63;let r=e.readUint16();for(let t=0;t>4,r=t&7;this.padbits.push(new ii(n,r))}}},oi=class extends _{constructor(...e){super(...e),this.box_name=`PixelAspectRatioBox`}static{this.fourcc=`pasp`}parse(e){this.hSpacing=e.readUint32(),this.vSpacing=e.readUint32()}},si=class extends _{constructor(...e){super(...e),this.box_name=`CuePayloadBox`}static{this.fourcc=`payl`}parse(e){this.text=e.readString(this.size-this.hdr_size)}},ci=class extends _{constructor(...e){super(...e),this.box_name=`hintpayloadID`}static{this.fourcc=`payt`}parse(e){this.payloadID=e.readUint32();let t=e.readUint8();this.rtpmap_string=e.readString(t)}},li=class extends v{constructor(...e){super(...e),this.box_name=`ProgressiveDownloadInfoBox`,this.rate=[],this.initial_delay=[]}static{this.fourcc=`pdin`}parse(e){this.parseFullHeader(e);let t=(this.size-this.hdr_size)/8;for(let n=0;n0){let t=e.readUint32();for(let n=0;n0&&(this.protection_data=e.readUint8Array(t))}},gi=class extends v{constructor(...e){super(...e),this.box_name=`TrackCleanApertureDimensionsBox`}static{this.fourcc=`clef`}parse(e){this.parseFullHeader(e),this.width=e.readUint32(),this.height=e.readUint32()}};function _i(e,t){if(e===Q.Types.UTF8)return new TextDecoder(`utf-8`).decode(t);let n=new DataView(t.buffer);if(e===Q.Types.BE_UNSIGNED_INT){if(t.length===1)return n.getUint8(0);if(t.length===2)return n.getUint16(0,!1);if(t.length===4)return n.getUint32(0,!1);if(t.length===8)return n.getBigUint64(0,!1);throw Error(`Unsupported ITIF_TYPE_BE_UNSIGNED_INT length `+t.length)}if(e===Q.Types.BE_SIGNED_INT){if(t.length===1)return n.getInt8(0);if(t.length===2)return n.getInt16(0,!1);if(t.length===4)return n.getInt32(0,!1);if(t.length===8)return n.getBigInt64(0,!1);throw Error(`Unsupported ITIF_TYPE_BE_SIGNED_INT length `+t.length)}if(e===Q.Types.BE_FLOAT32)return n.getFloat32(0,!1);m.warn(`DataBox`,`Unsupported or unimplemented itif data type: `+e)}var Q=class extends _{constructor(...e){super(...e),this.box_name=`DataBox`}static{this.fourcc=`data`}static{this.Types={RESERVED:0,UTF8:1,UTF16:2,SJIS:3,UTF8_SORT:4,UTF16_SORT:5,JPEG:13,PNG:14,BE_SIGNED_INT:21,BE_UNSIGNED_INT:22,BE_FLOAT32:23,BE_FLOAT64:24,BMP:27,QT_ATOM:28,BE_SIGNED_INT8:65,BE_SIGNED_INT16:66,BE_SIGNED_INT32:67,BE_FLOAT32_POINT:70,BE_FLOAT32_DIMENSIONS:71,BE_FLOAT32_RECT:72,BE_SIGNED_INT64:74,BE_UNSIGNED_INT8:75,BE_UNSIGNED_INT16:76,BE_UNSIGNED_INT32:77,BE_UNSIGNED_INT64:78,BE_FLOAT64_AFFINE_TRANSFORM:79}}parse(e){this.valueType=e.readUint32(),this.country=e.readUint16(),this.country>255&&(e.seek(e.getPosition()-2),this.countryString=e.readString(2)),this.language=e.readUint16(),this.language>255&&(e.seek(e.getPosition()-2),this.parseLanguage(e)),this.raw=e.readUint8Array(this.size-this.hdr_size-8),this.value=_i(this.valueType,this.raw)}},vi=class extends v{constructor(...e){super(...e),this.box_name=`TrackEncodedPixelsDimensionsBox`}static{this.fourcc=`enof`}parse(e){this.parseFullHeader(e),this.width=e.readUint32(),this.height=e.readUint32()}},yi=class extends _{constructor(...e){super(...e),this.box_name=`IlstBox`}static{this.fourcc=`ilst`}parse(e){this.list={};let t=this.size-this.hdr_size;for(;t>0;){let n=e.readUint32(),r=e.readUint32(),i=j(e,!1,n-8);i.code===1&&(this.list[r]=i.box),t-=n}}},bi=class extends v{constructor(...e){super(...e),this.box_name=`KeysBox`}static{this.fourcc=`keys`}parse(e){this.parseFullHeader(e),this.count=e.readUint32(),this.keys={};for(let t=0;t>4&15,this.sample_sizes[n+1]=t&15}else if(this.field_size===8)for(let n=0;n0)for(let r=0;r>6}},Hi=class extends v{constructor(...e){super(...e),this.box_name=`TrackEncryptionBox`}static{this.fourcc=`tenc`}parse(e){if(this.parseFullHeader(e),e.readUint8(),this.version===0)e.readUint8();else{let t=e.readUint8();this.default_crypt_byte_block=t>>4&15,this.default_skip_byte_block=t&15}this.default_isProtected=e.readUint8(),this.default_Per_Sample_IV_Size=e.readUint8(),this.default_KID=A(e),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=e.readUint8(),this.default_constant_IV=e.readUint8Array(this.default_constant_IV_size))}},Ui=class{},Wi=class extends v{constructor(...e){super(...e),this.box_name=`TrackFragmentRandomAccessBox`}static{this.fourcc=`tfra`}parse(e){this.parseFullHeader(e),this.track_ID=e.readUint32(),e.readUint24();let t=e.readUint8();this.length_size_of_traf_num=t>>4&3,this.length_size_of_trun_num=t>>2&3,this.length_size_of_sample_num=t&3,this.entries=[];let n=e.readUint32();for(let t=0;t>7&1,this.block_pad_lsb=t>>6&1,this.block_little_endian=t>>5&1,this.block_reversed=t>>4&1,this.pad_unknown=t>>3&1,this.pixel_size=e.readUint32(),this.row_align_size=e.readUint32(),this.tile_align_size=e.readUint32(),this.num_tile_cols_minus_one=e.readUint32(),this.num_tile_rows_minus_one=e.readUint32()}}},aa=class extends v{constructor(...e){super(...e),this.box_name=`DataEntryUrnBox`}static{this.fourcc=`urn `}parse(e){this.parseFullHeader(e),this.name=e.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=e.readCString())}write(e){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(e),e.writeCString(this.name),this.location&&e.writeCString(this.location)}},oa=class extends _{constructor(...e){super(...e),this.box_name=`WebVTTConfigurationBox`}static{this.fourcc=`vttC`}parse(e){this.text=e.readString(this.size-this.hdr_size)}},sa=class extends v{constructor(...e){super(...e),this.box_name=`VvcNALUConfigBox`}static{this.fourcc=`vvnC`}parse(e){this.parseFullHeader(e);let t=e.readUint8();this.lengthSizeMinusOne=t&3}},ca=class extends y{static{this.grouping_type=`alst`}parse(e){let t=e.readUint16();this.first_output_sample=e.readUint16(),this.sample_offset=[];for(let n=0;n>7,this.avgRateFlag=t>>6&1,this.durationFlag&&(this.duration=e.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()),this.dependency=[];let n=e.readUint8();for(let t=0;t>7,this.num_leading_samples=t&127}},ha=class extends y{static{this.grouping_type=`rash`}parse(e){if(this.operation_point_count=e.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)m.warn(`BoxParser`,`Mismatch in `+this.grouping_type+` sample group length`),this.data=e.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=e.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(let t=0;t>4,this.skip_byte_block=t&15,this.isProtected=e.readUint8(),this.Per_Sample_IV_Size=e.readUint8(),this.KID=A(e),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=e.readUint8(),this.constant_IV=e.readUint8Array(this.constant_IV_size))}},ba=class extends y{static{this.grouping_type=`stsa`}parse(e){m.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}},xa=class extends y{static{this.grouping_type=`sync`}parse(e){let t=e.readUint8();this.NAL_unit_type=t&63}},Sa=class extends y{static{this.grouping_type=`tele`}parse(e){let t=e.readUint8();this.level_independently_decodable=t>>7}},Ca=class extends y{static{this.grouping_type=`tsas`}parse(e){m.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}},wa=class extends y{static{this.grouping_type=`tscl`}parse(e){m.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}},Ta=class extends y{static{this.grouping_type=`vipr`}parse(e){m.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}},Ea=class extends _{static{this.fourcc=`uuid`}},$=class extends v{static{this.fourcc=`uuid`}},Da=class extends ${constructor(...e){super(...e),this.box_name=`LiveServerManifestBox`}static{this.uuid=`a5d40b30e81411ddba2f0800200c9a66`}parse(e){this.parseFullHeader(e),this.LiveServerManifest=e.readString(this.size-this.hdr_size).replace(/&/g,`&`).replace(//g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}},Oa=class extends ${constructor(...e){super(...e),this.box_name=`PiffProtectionSystemSpecificHeaderBox`}static{this.uuid=`d08a4f1810f34a82b6c832d8aba183d3`}parse(e){this.parseFullHeader(e),this.system_id=A(e);let t=e.readUint32();t>0&&(this.data=e.readUint8Array(t))}},ka=class extends ${constructor(...e){super(...e),this.box_name=`PiffSampleEncryptionBox`}static{this.uuid=`a2394f525a9b4f14a2446c427c648df4`}},Aa=class extends ${constructor(...e){super(...e),this.box_name=`PiffTrackEncryptionBox`}static{this.uuid=`8974dbce7be74c5184f97148f9882554`}parse(e){this.parseFullHeader(e),this.default_AlgorithmID=e.readUint24(),this.default_IV_size=e.readUint8(),this.default_KID=A(e)}},ja=class extends ${constructor(...e){super(...e),this.box_name=`TfrfBox`}static{this.uuid=`d4807ef2ca3946958e5426cb9e46a79f`}parse(e){this.parseFullHeader(e),this.fragment_count=e.readUint8(),this.entries=[];for(let t=0;tsr,ItemComponentContentIDPropertyBox:()=>Pa,ItemContentIDPropertyBox:()=>Na,OpusSampleEntry:()=>Qt,SmDmBox:()=>ji,a1lxBox:()=>Jn,a1opBox:()=>Yn,ac_3SampleEntry:()=>Yt,ac_4SampleEntry:()=>Xt,aebrBox:()=>wr,afbrBox:()=>Tr,albcBox:()=>Er,alstSampleGroupEntry:()=>ca,altrBox:()=>Dr,auxCBox:()=>Xn,av01SampleEntry:()=>xt,av1CBox:()=>ut,avc1SampleEntry:()=>_t,avc2SampleEntry:()=>vt,avc3SampleEntry:()=>yt,avc4SampleEntry:()=>bt,avcCBox:()=>ue,avllSampleGroupEntry:()=>la,avs3SampleEntry:()=>Vt,avssSampleGroupEntry:()=>ua,brstBox:()=>Or,btrtBox:()=>Zn,bxmlBox:()=>ve,ccstBox:()=>Qn,cdefBox:()=>$n,clapBox:()=>er,clefBox:()=>gi,clliBox:()=>tr,cmexBox:()=>nr,cminBox:()=>rr,cmpCBox:()=>ir,cmpdBox:()=>ar,co64Box:()=>or,colrBox:()=>gt,coviBox:()=>ur,cprtBox:()=>dr,cschBox:()=>fr,cslgBox:()=>pr,cttsBox:()=>mr,dOpsBox:()=>xr,dac3Box:()=>hr,dataBox:()=>Q,dav1SampleEntry:()=>St,dec3Box:()=>gr,dfLaBox:()=>_r,dimmBox:()=>vr,dinfBox:()=>we,dmax:()=>yr,dmedBox:()=>br,dobrBox:()=>kr,drefBox:()=>Ke,drepBox:()=>Sr,dtrtSampleGroupEntry:()=>da,dvh1SampleEntry:()=>jt,dvheSampleEntry:()=>Mt,ec_3SampleEntry:()=>Zt,edtsBox:()=>xe,elngBox:()=>qe,elstBox:()=>Cr,emsgBox:()=>Rn,encaSampleEntry:()=>on,encmSampleEntry:()=>dn,encsSampleEntry:()=>cn,enctSampleEntry:()=>un,encuSampleEntry:()=>sn,encvSampleEntry:()=>an,enofBox:()=>vi,eqivBox:()=>Ar,esdsBox:()=>dt,etypBox:()=>We,fLaCSampleEntry:()=>rn,favcBox:()=>jr,fielBox:()=>Vr,fobrBox:()=>Mr,freeBox:()=>fe,frmaBox:()=>Hr,ftypBox:()=>Je,grplBox:()=>He,hdlrBox:()=>Ye,hev1SampleEntry:()=>Tt,hev2SampleEntry:()=>Et,hinfBox:()=>Me,hmhdBox:()=>me,hntiBox:()=>je,hvc1SampleEntry:()=>Ct,hvc2SampleEntry:()=>wt,hvcCBox:()=>Xe,hvt1SampleEntry:()=>Dt,iaugBox:()=>Nr,idatBox:()=>de,iinfBox:()=>et,ilocBox:()=>tt,ilstBox:()=>yi,imirBox:()=>Ur,infeBox:()=>$e,iodsBox:()=>ge,ipcoBox:()=>Ve,ipmaBox:()=>Wr,iproBox:()=>ye,iprpBox:()=>Be,irefBox:()=>rt,irotBox:()=>Gr,ispeBox:()=>Kr,itaiBox:()=>qr,j2kHBox:()=>Ue,j2kiSampleEntry:()=>Ht,keysBox:()=>bi,kindBox:()=>Jr,levaBox:()=>Yr,lhe1SampleEntry:()=>Ot,lhv1SampleEntry:()=>kt,lhvCBox:()=>Xr,lselBox:()=>Zr,lvc1SampleEntry:()=>At,lvcCBox:()=>pt,m4aeSampleEntry:()=>Jt,maxrBox:()=>Qr,mdatBox:()=>z,mdcvBox:()=>$r,mdhdBox:()=>Ze,mdiaBox:()=>Se,mecoBox:()=>Ae,mehdBox:()=>Qe,metaBox:()=>at,mettSampleEntry:()=>ct,metxSampleEntry:()=>lt,mfhdBox:()=>ot,mfraBox:()=>ke,mfroBox:()=>ei,mha1SampleEntry:()=>$t,mha2SampleEntry:()=>en,mhm1SampleEntry:()=>tn,mhm2SampleEntry:()=>nn,minfBox:()=>Ce,mjp2SampleEntry:()=>Ut,mjpgSampleEntry:()=>Wt,moofBox:()=>Ee,moovBox:()=>B,mp4aSampleEntry:()=>qt,mp4sSampleEntry:()=>ln,mp4vSampleEntry:()=>Kt,mskCBox:()=>ti,msrcTrackGroupTypeBox:()=>Xi,mvexBox:()=>V,mvhdBox:()=>st,mvifSampleGroupEntry:()=>fa,nmhdBox:()=>he,npckBox:()=>ni,numpBox:()=>ri,padbBox:()=>ai,panoBox:()=>Pr,paspBox:()=>oi,paylBox:()=>si,paytBox:()=>ci,pdinBox:()=>li,piffLsmBox:()=>Da,piffPsshBox:()=>Oa,piffSencBox:()=>ka,piffTencBox:()=>Aa,piffTfrfBox:()=>ja,piffTfxdBox:()=>Ma,pitmBox:()=>it,pixiBox:()=>ui,pmaxBox:()=>di,povdBox:()=>Ge,prdiBox:()=>fi,prfrBox:()=>pi,prftBox:()=>mi,prgrBox:()=>zr,profBox:()=>xi,prolSampleGroupEntry:()=>pa,psshBox:()=>hi,pymdBox:()=>Br,rapSampleGroupEntry:()=>ma,rashSampleGroupEntry:()=>ha,resvSampleEntry:()=>fn,rinfBox:()=>Ie,rollSampleGroupEntry:()=>ga,rtp_Box:()=>Ci,saioBox:()=>wi,saizBox:()=>Ti,sbgpBox:()=>vn,sbpmBox:()=>Di,sbttSampleEntry:()=>pn,schiBox:()=>Le,schmBox:()=>Oi,scifSampleGroupEntry:()=>_a,scnmSampleGroupEntry:()=>va,sdp_Box:()=>ki,sdtpBox:()=>yn,seigSampleGroupEntry:()=>ya,sencBox:()=>Ai,sgpdBox:()=>bn,sidxBox:()=>xn,sinfBox:()=>Fe,skipBox:()=>pe,slidBox:()=>Fr,smhdBox:()=>Sn,sratBox:()=>Mi,ssixBox:()=>zn,stblBox:()=>Te,stcoBox:()=>Cn,stdpBox:()=>Ni,sterBox:()=>Ir,sthdBox:()=>wn,stppSampleEntry:()=>mn,strdBox:()=>Pe,striBox:()=>Pi,strkBox:()=>Ne,stsaSampleGroupEntry:()=>ba,stscBox:()=>Tn,stsdBox:()=>En,stsgBox:()=>Fi,stshBox:()=>Ii,stssBox:()=>Li,stszBox:()=>Dn,sttsBox:()=>On,stviBox:()=>Ri,stxtSampleEntry:()=>hn,stypBox:()=>Bn,stz2Box:()=>zi,subsBox:()=>Bi,syncSampleGroupEntry:()=>xa,taicBox:()=>Vi,taptBox:()=>Si,teleSampleGroupEntry:()=>Sa,tencBox:()=>Hi,tfdtBox:()=>kn,tfhdBox:()=>An,tfraBox:()=>Wi,tkhdBox:()=>jn,tmaxBox:()=>Gi,tminBox:()=>Ki,totlBox:()=>qi,tpayBox:()=>Ji,tpylBox:()=>Yi,trafBox:()=>De,trakBox:()=>be,trefBox:()=>Zi,trepBox:()=>Qi,trexBox:()=>G,trgrBox:()=>Re,trpyBox:()=>$i,trunBox:()=>Mn,tsasSampleGroupEntry:()=>Ca,tsclSampleGroupEntry:()=>wa,tselBox:()=>ea,tsynBox:()=>Lr,tx3gSampleEntry:()=>gn,txtcBox:()=>ta,tycoBox:()=>na,udesBox:()=>ra,udtaBox:()=>ze,uncCBox:()=>ia,uncvSampleEntry:()=>Gt,urlBox:()=>Nn,urnBox:()=>aa,viprSampleGroupEntry:()=>Ta,vmhdBox:()=>Pn,vp08SampleEntry:()=>zt,vp09SampleEntry:()=>Bt,vpcCBox:()=>mt,vttCBox:()=>oa,vttcBox:()=>Oe,vvc1SampleEntry:()=>Pt,vvcCBox:()=>ht,vvcNSampleEntry:()=>Lt,vvi1SampleEntry:()=>Ft,vvnCBox:()=>sa,vvs1SampleEntry:()=>It,waveBox:()=>ft,wbbrBox:()=>Rr,wvttSampleEntry:()=>_n,xmlBox:()=>_e})),ae(Vn);export{Ln as createFile}; \ No newline at end of file diff --git a/v4d-next/assets/ort-wasm-simd-threaded.asyncify-CxOG5pUO.wasm b/v4d-next/assets/ort-wasm-simd-threaded.asyncify-CxOG5pUO.wasm new file mode 100644 index 0000000..6eea0a7 Binary files /dev/null and b/v4d-next/assets/ort-wasm-simd-threaded.asyncify-CxOG5pUO.wasm differ diff --git a/v4d-next/assets/rolldown-runtime-XKyaHtl9.js b/v4d-next/assets/rolldown-runtime-XKyaHtl9.js new file mode 100644 index 0000000..6758219 --- /dev/null +++ b/v4d-next/assets/rolldown-runtime-XKyaHtl9.js @@ -0,0 +1 @@ +var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));export{s as n,l as r,o as t}; \ No newline at end of file diff --git a/v4d-next/assets/store-BW4Lw9fM.js b/v4d-next/assets/store-BW4Lw9fM.js new file mode 100644 index 0000000..8169193 --- /dev/null +++ b/v4d-next/assets/store-BW4Lw9fM.js @@ -0,0 +1 @@ +import{r as e,t}from"./rolldown-runtime-XKyaHtl9.js";var n=t((e=>{var t=Symbol.for(`react.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.provider`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.iterator;function p(e){return typeof e!=`object`||!e?null:(e=f&&e[f]||e[`@@iterator`],typeof e==`function`?e:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},h=Object.assign,g={};function _(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||m}_.prototype.isReactComponent={},_.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`setState(...): takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},_.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function v(){}v.prototype=_.prototype;function y(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||m}var b=y.prototype=new v;b.constructor=y,h(b,_.prototype),b.isPureReactComponent=!0;var x=Array.isArray,S=Object.prototype.hasOwnProperty,C={current:null},w={key:!0,ref:!0,__self:!0,__source:!0};function T(e,n,r){var i,a={},o=null,s=null;if(n!=null)for(i in n.ref!==void 0&&(s=n.ref),n.key!==void 0&&(o=``+n.key),n)S.call(n,i)&&!w.hasOwnProperty(i)&&(a[i]=n[i]);var c=arguments.length-2;if(c===1)a.children=r;else if(1{t.exports=n()})),i=e(r(),1),a=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},o=(e=>e?a(e):a),s=e=>e;function c(e,t=s){let n=i.useSyncExternalStore(e.subscribe,i.useCallback(()=>t(e.getState()),[e,t]),i.useCallback(()=>t(e.getInitialState()),[e,t]));return i.useDebugValue(n),n}var l=e=>{let t=o(e),n=e=>c(t,e);return Object.assign(n,t),n},u=(e=>e?l(e):l);function d(){return{target:[0,.95,0],distance:6.5,yaw:0,pitch:.12,fovY:40*Math.PI/180}}function f(e,t,n,r){let i=1/Math.tan(e/2),a=new Float32Array(16);return a[0]=i/t,a[5]=i,a[10]=r/(n-r),a[11]=-1,a[14]=n*r/(n-r),a}function p(e,t,n){let r=(e,t)=>[e[0]-t[0],e[1]-t[1],e[2]-t[2]],i=e=>{let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]},a=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],o=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],s=i(r(e,t)),c=i(a(n,s)),l=a(s,c);return Float32Array.from([c[0],l[0],s[0],0,c[1],l[1],s[1],0,c[2],l[2],s[2],0,-o(c,e),-o(l,e),-o(s,e),1])}function m(e,t){let n=new Float32Array(16);for(let r=0;r<4;r++)for(let i=0;i<4;i++){let a=0;for(let n=0;n<4;n++)a+=e[n*4+i]*t[r*4+n];n[r*4+i]=a}return n}function h(e){let t=Math.cos(e.pitch);return[e.target[0]+e.distance*t*Math.sin(e.yaw),e.target[1]+e.distance*Math.sin(e.pitch),e.target[2]+e.distance*t*Math.cos(e.yaw)]}function g(e,t){let n=f(e.fovY,t,.05,200);return{viewProj:m(n,p(h(e),e.target,[0,1,0])),proj:n}}function _(e,t,n,r){let i=Math.hypot(t.x-e.x,t.y-e.y),a=Math.hypot(r.x-n.x,r.y-n.y);return{scale:i>0&&a>0?i/a:1,dx:(n.x+r.x-e.x-t.x)/2,dy:(n.y+r.y-e.y-t.y)/2}}var v=e=>Math.max(.3,Math.min(80,e));function y(e,t,n,r){let i=null,a=new Map,o=(e,t,n)=>{let r=e.distance*.0016,i=[Math.cos(e.yaw),0,-Math.sin(e.yaw)];return{...e,target:[e.target[0]-i[0]*t*r,e.target[1]+n*r,e.target[2]-i[2]*t*r]}},s=t=>{e.setPointerCapture(t.pointerId),a.set(t.pointerId,{x:t.clientX,y:t.clientY}),i=a.size===1?{x:t.clientX,y:t.clientY,pan:t.button===2||t.shiftKey}:null,r?.()},c=e=>{let s=a.get(e.pointerId);if(!s)return;let c={x:e.clientX,y:e.clientY};if(a.size===2){let[i,l]=[...a.keys()],u=i===e.pointerId?l:i,d=a.get(u),f=_(s,d,c,d),p=o(t(),f.dx,f.dy);n({...p,distance:v(p.distance*f.scale)}),a.set(e.pointerId,c),r?.();return}if(a.set(e.pointerId,c),!i)return;let l=e.clientX-i.x,u=e.clientY-i.y,d=t();i.pan?n(o(d,l,u)):n({...d,yaw:d.yaw-l*.006,pitch:Math.max(-1.5,Math.min(1.5,d.pitch+u*.006))}),i={...i,x:e.clientX,y:e.clientY},r?.()},l=e=>{a.delete(e.pointerId),i=null},u=e=>{e.preventDefault();let i=t();n({...i,distance:v(i.distance*Math.exp(e.deltaY*.001))}),r?.()},d=e=>e.preventDefault();return e.addEventListener(`pointerdown`,s),e.addEventListener(`pointermove`,c),e.addEventListener(`pointerup`,l),e.addEventListener(`pointercancel`,l),e.addEventListener(`wheel`,u,{passive:!1}),e.addEventListener(`contextmenu`,d),()=>{e.removeEventListener(`pointerdown`,s),e.removeEventListener(`pointermove`,c),e.removeEventListener(`pointerup`,l),e.removeEventListener(`pointercancel`,l),e.removeEventListener(`wheel`,u),e.removeEventListener(`contextmenu`,d)}}var b={t:0};function x(e,t,n,r){return r<=0?n:n+((e-n+t)%r+r)%r}var S={heightM:1.75,hfov:66,relief:.3,pointsPerFrame:2e4,spill:`all`},C=6e6;function w(){return{window:{t0:0,thickness:1e-4,profile:`box`,tau:.8,period:.5,pulse:1/30,combPhase:`block`,plateau:.3},mapping:{kind:`identity`,shear:{dir:[0,0,1],k:.3},swap:{axis:0,k:.55,slit:0},tilt:{slope:[.5,0,0],origin:[0,0,0]}},age:{fadePast:1/0,fadeFuture:1/0,drift:[0,0,0],turbulence:0,noiseScale:3,shrink:0},identity:`tracked`}}var T=[`source`,`tint`,`age`,`time`,`identity`,`motion`],E={bone:{a:[.96,.92,.86],b:[.42,.29,.2]},ember:{a:[1,.86,.6],b:[.75,.12,.04]},ice:{a:[.92,.97,1],b:[.12,.33,.78]},firuzeh:{a:[.62,1,.9],b:[.04,.32,.38]},saffron:{a:[1,.78,.18],b:[.55,.08,.26]},violet:{a:[.86,.8,1],b:[.36,.16,.7]},ink:{a:[.06,.06,.07],b:[.55,.55,.6]},dusk:{a:[1,.93,.82],m:[.93,.42,.34],b:[.16,.2,.55]},kiln:{a:[1,.96,.84],m:[1,.52,.12],b:[.3,.03,.05]},lagoon:{a:[.94,1,.96],m:[.2,.78,.74],b:[.05,.12,.42]},rosewater:{a:[1,.95,.93],m:[.94,.56,.62],b:[.3,.3,.52]},verdigris:{a:[.98,.9,.68],m:[.3,.66,.52],b:[.05,.2,.26]}};function D(){return{color:`source`,...E.bone,grain:.6}}var O={source:0,tint:1,age:2,time:3,identity:4,motion:5};function k(e,t){let n=Number.isFinite(e.thickness)?e.thickness:t,r=e.profile===`decay`?n:n/2;return Math.max(.001,Math.min(r,Math.max(t,.001)))}function A(e,t){let n=Math.max(.05,t.grain);return{...e,pointSize:e.pointSize*n,minPx:Math.max(.35,e.minPx*Math.min(1,n)),gain:e.blend===`additive`?e.gain/n:e.gain}}function j(e){return`#`+e.map(e=>Math.round(Math.max(0,Math.min(1,e))*255).toString(16).padStart(2,`0`)).join(``)}function M(e){let t=/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);return t?[parseInt(t[1],16)/255,parseInt(t[2],16)/255,parseInt(t[3],16)/255]:[1,1,1]}var N={distance:.9,hfov:70,relief:.4,pointsPerFrame:12e3,seconds:20,mirror:!0,matte:`person`,calm:.25,breath:0},P={min:[-2,-1,-2],max:[2,3.5,2]};function F(e){return{target:[0,1.15,0],distance:Math.max(1.2,e.distance*2.2),yaw:0,pitch:.04,fovY:40*Math.PI/180}}var I=`v4d.liveSettings.2`;function L(){try{let e=JSON.parse(localStorage.getItem(I)??`{}`),t={...N};typeof matchMedia==`function`&&matchMedia(`(pointer: coarse)`).matches&&(t.pointsPerFrame=4e3);for(let n of[`distance`,`hfov`,`relief`,`pointsPerFrame`,`seconds`,`calm`,`breath`])typeof e[n]==`number`&&Number.isFinite(e[n])&&(t[n]=e[n]);return typeof e.mirror==`boolean`&&(t.mirror=e.mirror),(e.matte===`person`||e.matte===`green`)&&(t.matte=e.matte),t}catch{return{...N}}}function ee(e){try{localStorage.setItem(I,JSON.stringify(e))}catch{}}function R(){return{ev:0,auto:!0,shutter:0,timeFocus:0,shade:.35,grain:.035,passes:128,glow:0,glowSpread:.5,halation:0,aperture:0,focus:0,vignette:0}}var te={glow:0,halation:0,aperture:0,focus:0,vignette:0};function ne(e,t){return Math.max(.05,e+t.focus)}var z=.05;function re(e){return Math.max(1,Math.min(8,Math.floor(Math.log2(Math.max(1,e)/12))))}function B(e){return .45+.65*Math.min(1,Math.max(0,e))}function ie(e,t){let n=B(e),r=0;for(let e=0;e0;i=Math.floor(i/t))n/=t,r+=i%t*n;return r}function ae(e){return e===0?[0,0]:[V(e,2)-.5,V(e,3)-.5]}function oe(e){return e===0?0:V(e,5)}function se(e,t,n,r){return{sx:n,sy:r,ox:n-1-2*e,oy:-(r-1-2*t)}}function H(e,t,n){let r=Math.ceil(e/n),i=Math.ceil(t/n);return{nx:r,ny:i,tw:Math.ceil(e/r),th:Math.ceil(t/i)}}function U(e){return JSON.stringify(e,(e,t)=>typeof t==`number`?Math.round(t*1e5)/1e5:t)}var W=[64,40],G={percentile:.9,target:.9,floor:.004,minCells:12,min:-7,max:2};function ce(e,t=G){let n=[];for(let r=0;rt.floor&&n.push(i)}if(n.lengthe-t);let r=n[Math.min(n.length-1,Math.floor(t.percentile*(n.length-1)))];return Math.min(t.max,Math.max(t.min,Math.log2(t.target/r)))}function le(e,t,n){let r=te+(t-e)*n;function fe(e,t,n){let r=de(t.ease,n);switch(t.kind){case`turn`:return{...e,yaw:e.yaw+t.degrees*Math.PI/180*r};case`push`:return{...e,distance:e.distance*q(1,t.push,r)};case`ab`:{let n=t.a??e,i=t.b??e;return{yaw:q(n.yaw,i.yaw,r),pitch:q(n.pitch,i.pitch,r),distance:n.distance*(i.distance/n.distance)**r,fovY:q(n.fovY,i.fovY,r),target:[q(n.target[0],i.target[0],r),q(n.target[1],i.target[1],r),q(n.target[2],i.target[2],r)]}}default:return e}}function pe(e,t,n){return t<=1?0:e/(n.kind===`turn`&&n.ease===`linear`&&n.degrees!==0&&Math.abs(n.degrees)%360==0?t:t-1)}var me=[`library`,`time`,`light`,`camera`,`output`,`source`],J=[0,0,0],he=[.96,.95,.93],ge=[1,.59,.24];function Y(){return{pointSize:.012,minPx:.75,blend:`opaque`,background:J,gain:1,mark:0,markColor:ge}}var X=`v4d.importSettings`,Z=`v4d.look`;function Q(){let e=D();try{let t=JSON.parse(localStorage.getItem(Z)??`{}`),n=e=>Array.isArray(e)&&e.length===3&&e.every(e=>typeof e==`number`&&e>=0&&e<=1);return{color:T.includes(t.color)?t.color:e.color,a:n(t.a)?t.a:e.a,b:n(t.b)?t.b:e.b,m:n(t.m)?t.m:null,grain:typeof t.grain==`number`&&t.grain>0&&t.grain<=3?t.grain:e.grain}}catch{return e}}function _e(e){try{localStorage.setItem(Z,JSON.stringify(e))}catch{}}function ve(){try{let e=localStorage.getItem(X),t=e?JSON.parse(e):{},n={...S};for(let e of[`heightM`,`hfov`,`relief`,`pointsPerFrame`])typeof t[e]==`number`&&Number.isFinite(t[e])&&(n[e]=t[e]);return(t.spill===`all`||t.spill===`edges`)&&(n.spill=t.spill),n}catch{return{...S}}}function ye(e){try{localStorage.setItem(X,JSON.stringify(e))}catch{}}function $(e,t){return t||!e.preset?{}:{preset:e.preset.endsWith(`*`)?e.preset:`${e.preset}*`}}var be=u(e=>({loaded:null,status:``,statusLevel:`info`,job:null,imported:null,importSettings:ve(),lensOpen:!0,bare:!1,look:Q(),lens:w(),style:Y(),orbit:d(),preset:null,idea:``,kalam:!1,playing:!0,speed:1,stats:{fps:0,drawn:0},studio:!1,viewerLens:null,revealStart:null,aboutOpen:!1,introDone:!1,live:null,liveSettings:L(),kept:[],darkroom:R(),developed:0,printing:null,work:null,sit:null,sitting:null,frame:`free`,move:K(),movePreview:null,filmSeconds:10,tab:`time`,looks:[],history:{undo:0,redo:0},fetching:null,setLoaded:t=>e({loaded:t}),setStatus:(t,n=`info`)=>e({status:t,statusLevel:n}),setJob:t=>e({job:t}),setImported:t=>e({imported:t}),setImportSettings:t=>e(e=>{let n={...e.importSettings,...t};return ye(n),{importSettings:n}}),setWindow:t=>e(e=>({lens:{...e.lens,window:{...e.lens.window,...t}},...$(e,`t0`in t&&Object.keys(t).length===1)})),setMapping:t=>e(e=>({lens:{...e.lens,mapping:{...e.lens.mapping,...t}},...$(e,!1)})),setAge:t=>e(e=>({lens:{...e.lens,age:{...e.lens.age,...t}},...$(e,!1)})),setLens:t=>e(e=>({lens:{...e.lens,...t}})),setStyle:t=>e(e=>({style:{...e.style,...t}})),setLensOpen:t=>e({lensOpen:t}),setBare:t=>e({bare:t}),setLook:t=>e(e=>{let n={...e.look,...t};_e(n);let r={...e.style};return delete r.lookOverride,{look:n,style:r}}),setOrbit:t=>e({orbit:t}),setT0:t=>{b.t=t,e(e=>({lens:{...e.lens,window:{...e.lens.window,t0:t}}}))},setPlaying:t=>e({playing:t}),setSpeed:t=>e({speed:t}),setPreset:(t,n=``)=>e({preset:t,idea:n}),setKalam:t=>e({kalam:t}),setStats:t=>e({stats:t}),setStudio:t=>e({studio:t}),setAboutOpen:t=>e({aboutOpen:t}),setLive:t=>e({live:t}),setLiveSettings:t=>e({liveSettings:t}),addKept:t=>e(e=>({kept:[...e.kept,t]})),setDarkroom:t=>e(e=>({darkroom:{...e.darkroom,...t}})),setDeveloped:t=>e({developed:t}),setPrinting:t=>e({printing:t}),setFrame:t=>e({frame:t}),setMove:t=>e(e=>({move:{...e.move,...t}})),setTab:t=>e({tab:t})}));export{O as A,x as B,se as C,N as D,P as E,A as F,r as G,y as H,j as I,w as L,k as M,D as N,F as O,M as P,S as R,oe as S,ee as T,d as U,b as V,g as W,ne as _,be as a,B as b,fe as c,z as d,te as f,U as g,R as h,Y as i,E as j,T as k,pe as l,ce as m,me as n,ue as o,le as p,he as r,K as s,J as t,W as u,re as v,H as w,ae as x,ie as y,C as z}; \ No newline at end of file diff --git a/v4d-next/assets/synth.worker-D-Qhg7ac.js b/v4d-next/assets/synth.worker-D-Qhg7ac.js new file mode 100644 index 0000000..5f25bde --- /dev/null +++ b/v4d-next/assets/synth.worker-D-Qhg7ac.js @@ -0,0 +1,7 @@ +var e=class extends Error{};function t(e,t,n,r){if(n===t)return 0;let i=Math.floor((e-t)/(n-t)*r+.5);return i<0?0:i>r?r:i}function n(n){let r=n.times.length;if(n.positions.length!==3*r||n.colors.length!==3*r)throw new e(`positions and colors must have 3 values per point`);if(n.trackIds&&n.trackIds.length!==r)throw new e(`trackIds must have 1 value per point`);if(n.observed&&n.observed.length!==r)throw new e(`observed must have 1 value per point`);if(n.rawPositions&&n.rawPositions.length!==3*r)throw new e(`rawPositions must have 3 values per point`);let i=1/0,a=-1/0;for(let e=0;ea&&(a=t)}let o=n.time??{start:r?i:0,end:r?a:0},s=n.bounds;if(!s){let e=[1/0,1/0,1/0],t=[-1/0,-1/0,-1/0];for(let i of n.rawPositions?[n.positions,n.rawPositions]:[n.positions])for(let n=0;nt[r]&&(t[r]=a)}s=r?{min:e,max:t}:{min:[0,0,0],max:[0,0,0]}}let c=null;for(let e=1;et);e.sort((e,t)=>n.times[e]-n.times[t]||e-t),c=Uint32Array.from(e);break}let l=e=>c?c[e]:e,u=new Uint16Array(3*r),d=new Uint16Array(r),f=new Uint8Array(3*r),p=n.trackIds?new Uint32Array(r):void 0,m=n.observed?new Uint8Array(r):void 0,h=n.rawPositions?new Uint16Array(3*r):void 0;for(let e=0;e0?n.fps:0,_=0,v;if(g>0&&r>0){let e=e=>Math.round((n.times[l(e)]-o.start)*g);_=e(r-1)+1,v=new Uint32Array(_+1);let t=0;for(let n=0;n>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function i(e,t,n,r,i){return{header:{pointCount:e,frameCount:t,fps:n,time:{start:0,end:t>1?(t-1)/n:0},bounds:r,space:{units:`m`,up:`+y`,handedness:`right`},sections:[],meta:{generator:`v4d-synth 0.1.0`,...i}},position:new Uint16Array(e*3),time:new Uint16Array(e),color:new Uint8Array(e*3),trackId:new Uint32Array(e),frameStart:new Uint32Array(t+1)}}function a(e,n,r,i,a,o,s,c,l,u){let{min:d,max:f}=e.header.bounds;e.position[3*n]=t(r,d[0],f[0],65535),e.position[3*n+1]=t(i,d[1],f[1],65535),e.position[3*n+2]=t(a,d[2],f[2],65535),e.time[n]=t(o,e.header.time.start,e.header.time.end,65535),e.color[3*n]=s,e.color[3*n+1]=c,e.color[3*n+2]=l,e.trackId[n]=u}function o(e,t){let n={header:e.header,position:e.position,time:e.time,color:e.color,frameStart:e.frameStart,extra:{}};return t&&(n.trackId=e.trackId),n}const s={pelvis:0,neck:1,head:2,shL:3,elL:4,haL:5,shR:6,elR:7,haR:8,hipL:9,knL:10,anL:11,hipR:12,knR:13,anR:14,toeL:15,toeR:16},c=[214,178,152],l=[206,204,196],u=[62,66,78],d=[40,34,30],f=[{name:`head`,a:s.head,b:null,rz:.105,rx:.105,color:c},{name:`torso`,a:s.pelvis,b:s.neck,rz:.17,rx:.11,color:l},{name:`upperArmL`,a:s.shL,b:s.elL,rz:.045,rx:.045,color:l},{name:`foreArmL`,a:s.elL,b:s.haL,rz:.038,rx:.038,color:c},{name:`upperArmR`,a:s.shR,b:s.elR,rz:.045,rx:.045,color:l},{name:`foreArmR`,a:s.elR,b:s.haR,rz:.038,rx:.038,color:c},{name:`thighL`,a:s.hipL,b:s.knL,rz:.075,rx:.075,color:u},{name:`shinL`,a:s.knL,b:s.anL,rz:.055,rx:.055,color:u},{name:`footL`,a:s.anL,b:s.toeL,rz:.04,rx:.035,color:d},{name:`thighR`,a:s.hipR,b:s.knR,rz:.075,rx:.075,color:u},{name:`shinR`,a:s.knR,b:s.anR,rz:.055,rx:.055,color:u},{name:`footR`,a:s.anR,b:s.toeR,rz:.04,rx:.035,color:d}],p=.46,m=.45,h=.3,g=.28,_=.2;function v(e,t,n){let r=t/(2*Math.max(.3,.75*Math.sqrt(t))),i=2*Math.PI*r*e,a=-t*n/2+t*e,o=.02*Math.cos(2*i),c=[a,.95+o,0],l=.06,u=[a+l,1.48+o,0],d=[a+l+.02,1.64+o,0],f=Array(17);f[s.pelvis]=c,f[s.neck]=u,f[s.head]=d;let v=Math.min(.55,.25+.25*t),y=(e,t)=>{let n=[a,.92+o,.1*e],r=v*Math.sin(t),i=.15+.55*Math.max(0,Math.sin(t+1.2))**2,s=[n[0]+p*Math.sin(r),n[1]-p*Math.cos(r),n[2]],c=r-i,l=[s[0]+m*Math.sin(c),s[1]-m*Math.cos(c),n[2]],u=c+Math.PI/2-.1;return{hip:n,kn:s,an:l,toe:[l[0]+_*Math.sin(u),l[1]-_*Math.cos(u),n[2]]}},b=(e,t)=>{let n=[a+l*.9,1.42+o,.2*e],r=.6*v*Math.sin(t),i=[n[0]+h*Math.sin(r),n[1]-h*Math.cos(r),n[2]],s=r+.25+.2*Math.max(0,Math.sin(t));return{sh:n,el:i,ha:[i[0]+g*Math.sin(s),i[1]-g*Math.cos(s),n[2]]}},x=y(1,i),S=y(-1,i+Math.PI),C=b(1,i+Math.PI),w=b(-1,i);f[s.hipL]=x.hip,f[s.knL]=x.kn,f[s.anL]=x.an,f[s.toeL]=x.toe,f[s.hipR]=S.hip,f[s.knR]=S.kn,f[s.anR]=S.an,f[s.toeR]=S.toe,f[s.shL]=C.sh,f[s.elL]=C.el,f[s.haL]=C.ha,f[s.shR]=w.sh,f[s.elR]=w.el,f[s.haR]=w.ha;let T=Math.min(x.toe[1],x.an[1],S.toe[1],S.an[1])-.035;for(let e of f)e[1]-=T;return f}const y=(()=>{let e=[.4,.8,.45],t=Math.hypot(...e);return[e[0]/t,e[1]/t,e[2]/t]})();function b(e){if(e.b===null)return 4*Math.PI*e.rz*e.rz;let t={torso:.53,upperArmL:h,upperArmR:h,foreArmL:g,foreArmR:g,thighL:p,thighR:p,shinL:m,shinR:m,footL:_,footR:_};return 2*Math.PI*((e.rz+e.rx)/2)*(t[e.name]??.3)}function x(e,t){let n=f.map(b),r=n.reduce((e,t)=>e+t,0),i=[];n.reduce((e,t,n)=>i[n]=e+t/r,0);let a=Array(e);for(let n=0;ne<=t);r<0&&(r=f.length-1),a[n]={part:r,s:t(),a:t()*2*Math.PI,u:t()*2-1}}return a}function S(e,t,n){let r=f[e.part],i=t[r.a],a,o,s,c,l,u;if(r.b===null){let t=Math.sqrt(1-e.u*e.u);a=t*Math.cos(e.a),o=e.u,s=t*Math.sin(e.a),c=i[0]+r.rx*a,l=i[1]+r.rz*o,u=i[2]+r.rz*s}else{let n=t[r.b],d=n[0]-i[0],f=n[1]-i[1],p=Math.hypot(d,f)||1,m=-f/p,h=d/p,g=Math.cos(e.a),_=Math.sin(e.a);a=m*g,o=h*g,s=_,c=i[0]+d*e.s+m*r.rx*g,l=i[1]+f*e.s+h*r.rx*g,u=i[2]+r.rz*_}n[0]=c,n[1]=l,n[2]=u,n[3]=.45+.55*Math.max(0,a*y[0]+o*y[1]+s*y[2])}function C(e={}){let t=e.pointsPerFrame??2e4,n=e.seconds??10,s=e.fps??30,c=e.speed??.55,l=e.resample??!1,u=r(e.seed??1),d=Math.round(n*s),p=c*n/2+.6,m=i(t*d,d,s,{min:[-p,0,-.45],max:[p,2,.45]},{source:`synth:walker`,pointsPerFrame:t,speed:c,resample:l}),h=x(t,u),g=/* @__PURE__ */ new Float64Array(4),_=0;for(let e=0;e0&&(h=x(t,u));for(let e=0;e=128?0:255;if(!t)return r;for(let e=0;e=0&&r[n]!==0&&(r[n]=Math.min(r[n],Math.min(255,r[e]+1)))}let i=Uint8Array.from(r),a=new Uint8Array(n);for(let t=0;t=128?0:255;for(let e=n-1;e>=0;e--){let n=t[e];n>=0&&a[e]!==0&&(a[e]=Math.min(a[e],Math.min(255,a[n]+1))),a[e](c[e]-s[e])/65535),u=n.fps,d=r?Array.from({length:n.frameCount},(e,t)=>[r[t],r[t+1]]):[[0,a]],f=/* @__PURE__ */ new Float32Array(3);for(let[e,n]of d){let r=/* @__PURE__ */ new Float64Array(3),a=0;for(let o=e;o0)for(let e=0;e<3;e++)r[e]=r[e]/a;for(let a=e;a=0&&t[n]<0&&(o[n]=o[e])}return o}function ne(e,t){let n=e.observed?T(e.observed,t):null,r=t?te(e,t):null;if(!n&&!r)return null;let i=e.header.pointCount,a=new Uint16Array(i+(i&1));for(let e=0;eo&&(o=n)}let s=o<1<<24?new Int32Array(o+1):null,c=s?null:/* @__PURE__ */ new Map;for(let e=0;e+1>8&255]+O[e>>16&255]+O[e>>24&255]+`-`+O[t&255]+O[t>>8&255]+`-`+O[t>>16&15|64]+O[t>>24&255]+`-`+O[n&63|128]+O[n>>8&255]+`-`+O[n>>16&255]+O[n>>24&255]+O[r&255]+O[r>>8&255]+O[r>>16&255]+O[r>>24&255]).toLowerCase()}function A(e,t,n){return Math.max(t,Math.min(n,e))}function je(e,t){return(e%t+t)%t}function Me(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function Ne(e,t,n){return e===t?0:(n-e)/(t-e)}function Pe(e,t,n){return(1-n)*e+n*t}function Fe(e,t,n,r){return Pe(e,t,1-Math.exp(-n*r))}function Ie(e,t=1){return t-Math.abs(je(e,t*2)-t)}function Le(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function Re(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function ze(e,t){return e+Math.floor(Math.random()*(t-e+1))}function Be(e,t){return e+Math.random()*(t-e)}function Ve(e){return e*(.5-Math.random())}function He(e){e!==void 0&&(Oe=e);let t=Oe+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Ue(e){return e*ke}function We(e){return e*Ae}function Ge(e){return!(e&e-1)&&e!==0}function Ke(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function qe(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function Je(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),f=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*f,s*l);break;case`YZY`:e.set(c*f,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*f,s*u,s*l);break;case`XZX`:e.set(s*u,c*m,c*p,s*l);break;case`YXY`:e.set(c*p,s*u,c*m,s*l);break;case`ZYZ`:e.set(c*m,c*p,s*u,s*l);break;default:console.warn(`THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function j(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`Invalid component type.`)}}function M(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`Invalid component type.`)}}const Ye={DEG2RAD:ke,RAD2DEG:Ae,generateUUID:k,clamp:A,euclideanModulo:je,mapLinear:Me,inverseLerp:Ne,lerp:Pe,damp:Fe,pingpong:Ie,smoothstep:Le,smootherstep:Re,randInt:ze,randFloat:Be,randFloatSpread:Ve,seededRandom:He,degToRad:Ue,radToDeg:We,isPowerOfTwo:Ge,ceilPowerOfTwo:Ke,floorPowerOfTwo:qe,setQuaternionFromProperEuler:Je,normalize:M,denormalize:j};var N=class e{constructor(t=0,n=0){e.prototype.isVector2=!0,this.x=t,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=A(this.x,e.x,t.x),this.y=A(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=A(this.x,e,t),this.y=A(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(A(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(A(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},P=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(o===0)e[t+0]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u;else if(o===1)e[t+0]=d,e[t+1]=f,e[t+2]=p,e[t+3]=m;else{if(u!==m||s!==d||c!==f||l!==p){let e=1-o,t=s*d+c*f+l*p+u*m,n=t>=0?1:-1,r=1-t*t;if(r>2**-52){let i=Math.sqrt(r),a=Math.atan2(i,t*n);e=Math.sin(e*a)/i,o=Math.sin(o*a)/i}let i=o*n;if(s=s*e+d*i,c=c*e+f*i,l=l*e+p*i,u=u*e+m*i,e===1-o){let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:console.warn(`THREE.Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(A(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);let n=this._x,r=this._y,i=this._z,a=this._w,o=a*e._w+n*e._x+r*e._y+i*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=n,this._y=r,this._z=i,this;let s=1-o*o;if(s<=2**-52){let e=1-t;return this._w=e*a+t*this._w,this._x=e*n+t*this._x,this._y=e*r+t*this._y,this._z=e*i+t*this._z,this.normalize(),this}let c=Math.sqrt(s),l=Math.atan2(c,o),u=Math.sin((1-t)*l)/c,d=Math.sin(t*l)/c;return this._w=a*u+this._w*d,this._x=n*u+this._x*d,this._y=r*u+this._y*d,this._z=i*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},F=class e{constructor(t=0,n=0,r=0){e.prototype.isVector3=!0,this.x=t,this.y=n,this.z=r}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Ze.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ze.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=A(this.x,e.x,t.x),this.y=A(this.y,e.y,t.y),this.z=A(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=A(this.x,e,t),this.y=A(this.y,e,t),this.z=A(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(A(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Xe.copy(this).projectOnVector(e),this.sub(Xe)}reflect(e){return this.sub(Xe.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(A(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};const Xe=/*@__PURE__*/ new F,Ze=/*@__PURE__*/ new P;var Qe=class e{constructor(t,n,r,i,a,o,s,c,l){e.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply($e.makeScale(e,t)),this}rotate(e){return this.premultiply($e.makeRotation(-e)),this}translate(e,t){return this.premultiply($e.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}};const $e=/*@__PURE__*/ new Qe;function et(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function tt(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}const nt={};function rt(e){e in nt||(nt[e]=!0,console.warn(e))}const it=/*@__PURE__*/ new Qe().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),at=/*@__PURE__*/ new Qe().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function ot(){let e={enabled:!0,workingColorSpace:Se,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n||(this.spaces[t].transfer===`srgb`&&(e.r=st(e.r),e.g=st(e.g),e.b=st(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=ct(e.r),e.g=ct(e.g),e.b=ct(e.b))),e},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Ce:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return rt(`THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return rt(`THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[Se]:{primaries:t,whitePoint:r,transfer:Ce,toXYZ:it,fromXYZ:at,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:D},outputColorSpaceConfig:{drawingBufferColorSpace:D}},[D]:{primaries:t,whitePoint:r,transfer:`srgb`,toXYZ:it,fromXYZ:at,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:D}}}),e}const I=/*@__PURE__*/ ot();function st(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function ct(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}let lt;var ut=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{lt===void 0&&(lt=tt(`canvas`)),lt.width=e.width,lt.height=e.height;let t=lt.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=lt}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=tt(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e1),this.pmremVersion=0}get width(){return this.source.getSize(ht).x}get height(){return this.source.getSize(ht).y}get depth(){return this.source.getSize(ht).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];r===void 0?console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`):r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ie:e.x-=Math.floor(e.x);break;case E:e.x=e.x<0?0:1;break;case ae:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case ie:e.y-=Math.floor(e.y);break;case E:e.y=e.y<0?0:1;break;case ae:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};gt.DEFAULT_IMAGE=null,gt.DEFAULT_MAPPING=300,gt.DEFAULT_ANISOTROPY=1;var L=class e{constructor(t=0,n=0,r=0,i=1){e.prototype.isVector4=!0,this.x=t,this.y=n,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)s&&e>_?e_?s=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,R),R.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Et),Dt.subVectors(this.max,Et),bt.subVectors(e.a,Et),xt.subVectors(e.b,Et),St.subVectors(e.c,Et),Ct.subVectors(xt,bt),wt.subVectors(St,xt),Tt.subVectors(bt,St);let t=[0,-Ct.z,Ct.y,0,-wt.z,wt.y,0,-Tt.z,Tt.y,Ct.z,0,-Ct.x,wt.z,0,-wt.x,Tt.z,0,-Tt.x,-Ct.y,Ct.x,0,-wt.y,wt.x,0,-Tt.y,Tt.x,0];return!At(t,bt,xt,St,Dt)||(t=[1,0,0,0,1,0,0,0,1],!At(t,bt,xt,St,Dt))?!1:(Ot.crossVectors(Ct,wt),t=[Ot.x,Ot.y,Ot.z],At(t,bt,xt,St,Dt))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,R).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(R).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(vt[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),vt[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),vt[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),vt[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),vt[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),vt[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),vt[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),vt[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(vt)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}};const vt=[/*@__PURE__*/ new F,/*@__PURE__*/ new F,/*@__PURE__*/ new F,/*@__PURE__*/ new F,/*@__PURE__*/ new F,/*@__PURE__*/ new F,/*@__PURE__*/ new F,/*@__PURE__*/ new F],R=/*@__PURE__*/ new F,yt=/*@__PURE__*/ new _t,bt=/*@__PURE__*/ new F,xt=/*@__PURE__*/ new F,St=/*@__PURE__*/ new F,Ct=/*@__PURE__*/ new F,wt=/*@__PURE__*/ new F,Tt=/*@__PURE__*/ new F,Et=/*@__PURE__*/ new F,Dt=/*@__PURE__*/ new F,Ot=/*@__PURE__*/ new F,kt=/*@__PURE__*/ new F;function At(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){kt.fromArray(e,a);let o=i.x*Math.abs(kt.x)+i.y*Math.abs(kt.y)+i.z*Math.abs(kt.z),s=t.dot(kt),c=n.dot(kt),l=r.dot(kt);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}const jt=/*@__PURE__*/ new _t,Mt=/*@__PURE__*/ new F,Nt=/*@__PURE__*/ new F;var z=class{constructor(e=new F,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t===void 0?jt.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;tthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Mt.subVectors(e,this.center);let t=Mt.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(Mt,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Nt.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Mt.copy(e.center).add(Nt)),this.expandByPoint(Mt.copy(e.center).sub(Nt))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}};const Pt=/*@__PURE__*/ new F,Ft=/*@__PURE__*/ new F,It=/*@__PURE__*/ new F,Lt=/*@__PURE__*/ new F,Rt=/*@__PURE__*/ new F,zt=/*@__PURE__*/ new F,Bt=/*@__PURE__*/ new F;var Vt=class{constructor(e=new F,t=new F(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Pt)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=Pt.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Pt.copy(this.origin).addScaledVector(this.direction,t),Pt.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){Ft.copy(e).add(t).multiplyScalar(.5),It.copy(t).sub(e).normalize(),Lt.copy(this.origin).sub(Ft);let i=e.distanceTo(t)*.5,a=-this.direction.dot(It),o=Lt.dot(this.direction),s=-Lt.dot(It),c=Lt.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0){if(u=a*s-o,d=a*o-s,p=i*l,u>=0){if(d>=-p){if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c)}else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(Ft).addScaledVector(It,d),f}intersectSphere(e,t){Pt.subVectors(e.center,this.origin);let n=Pt.dot(this.direction),r=Pt.dot(Pt)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,Pt)!==null}intersectTriangle(e,t,n,r,i){Rt.subVectors(t,e),zt.subVectors(n,e),Bt.crossVectors(Rt,zt);let a=this.direction.dot(Bt),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Lt.subVectors(this.origin,e);let s=o*this.direction.dot(zt.crossVectors(Lt,zt));if(s<0)return null;let c=o*this.direction.dot(Rt.cross(Lt));if(c<0||s+c>a)return null;let l=-o*Lt.dot(Bt);return l<0?null:this.at(l/a,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},B=class e{constructor(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){e.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){let t=this.elements,n=e.elements,r=1/Ht.setFromMatrixColumn(e,0).length(),i=1/Ht.setFromMatrixColumn(e,1).length(),a=1/Ht.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Ut,e,Wt)}lookAt(e,t,n){let r=this.elements;return H.subVectors(e,t),H.lengthSq()===0&&(H.z=1),H.normalize(),Gt.crossVectors(n,H),Gt.lengthSq()===0&&(Math.abs(n.z)===1?H.x+=1e-4:H.z+=1e-4,H.normalize(),Gt.crossVectors(n,H)),Gt.normalize(),Kt.crossVectors(H,Gt),r[0]=Gt.x,r[4]=Kt.x,r[8]=H.x,r[1]=Gt.y,r[5]=Kt.y,r[9]=H.y,r[2]=Gt.z,r[6]=Kt.z,r[10]=H.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],ee=r[5],te=r[9],ne=r[13],re=r[2],ie=r[6],E=r[10],ae=r[14],oe=r[3],se=r[7],ce=r[11],le=r[15];return i[0]=a*x+o*T+s*re+c*oe,i[4]=a*S+o*ee+s*ie+c*se,i[8]=a*C+o*te+s*E+c*ce,i[12]=a*w+o*ne+s*ae+c*le,i[1]=l*x+u*T+d*re+f*oe,i[5]=l*S+u*ee+d*ie+f*se,i[9]=l*C+u*te+d*E+f*ce,i[13]=l*w+u*ne+d*ae+f*le,i[2]=p*x+m*T+h*re+g*oe,i[6]=p*S+m*ee+h*ie+g*se,i[10]=p*C+m*te+h*E+g*ce,i[14]=p*w+m*ne+h*ae+g*le,i[3]=_*x+v*T+y*re+b*oe,i[7]=_*S+v*ee+y*ie+b*se,i[11]=_*C+v*te+y*E+b*ce,i[15]=_*w+v*ne+y*ae+b*le,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15];return p*(+i*s*u-r*c*u-i*o*d+n*c*d+r*o*f-n*s*f)+m*(+t*s*f-t*c*d+i*a*d-r*a*f+r*c*l-i*s*l)+h*(+t*c*u-t*o*f-i*a*u+n*a*f+i*o*l-n*c*l)+g*(-r*o*l-t*s*u+t*o*d+r*a*u-n*a*d+n*s*l)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=u*h*c-m*d*c+m*s*f-o*h*f-u*s*g+o*d*g,v=p*d*c-l*h*c-p*s*f+a*h*f+l*s*g-a*d*g,y=l*m*c-p*u*c+p*o*f-a*m*f-l*o*g+a*u*g,b=p*u*s-l*m*s-p*o*d+a*m*d+l*o*h-a*u*h,x=t*_+n*v+r*y+i*b;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let S=1/x;return e[0]=_*S,e[1]=(m*d*i-u*h*i-m*r*f+n*h*f+u*r*g-n*d*g)*S,e[2]=(o*h*i-m*s*i+m*r*c-n*h*c-o*r*g+n*s*g)*S,e[3]=(u*s*i-o*d*i-u*r*c+n*d*c+o*r*f-n*s*f)*S,e[4]=v*S,e[5]=(l*h*i-p*d*i+p*r*f-t*h*f-l*r*g+t*d*g)*S,e[6]=(p*s*i-a*h*i-p*r*c+t*h*c+a*r*g-t*s*g)*S,e[7]=(a*d*i-l*s*i+l*r*c-t*d*c-a*r*f+t*s*f)*S,e[8]=y*S,e[9]=(p*u*i-l*m*i-p*n*f+t*m*f+l*n*g-t*u*g)*S,e[10]=(a*m*i-p*o*i+p*n*c-t*m*c-a*n*g+t*o*g)*S,e[11]=(l*o*i-a*u*i-l*n*c+t*u*c+a*n*f-t*o*f)*S,e[12]=b*S,e[13]=(l*m*r-p*u*r+p*n*d-t*m*d-l*n*h+t*u*h)*S,e[14]=(p*o*r-a*m*r-p*n*s+t*m*s+a*n*h-t*o*h)*S,e[15]=(a*u*r-l*o*r+l*n*s-t*u*s-a*n*d+t*o*d)*S,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements,i=Ht.set(r[0],r[1],r[2]).length(),a=Ht.set(r[4],r[5],r[6]).length(),o=Ht.set(r[8],r[9],r[10]).length();this.determinant()<0&&(i=-i),e.x=r[12],e.y=r[13],e.z=r[14],V.copy(this);let s=1/i,c=1/a,l=1/o;return V.elements[0]*=s,V.elements[1]*=s,V.elements[2]*=s,V.elements[4]*=c,V.elements[5]*=c,V.elements[6]*=c,V.elements[8]*=l,V.elements[9]*=l,V.elements[10]*=l,t.setFromRotationMatrix(V),n.x=i,n.y=a,n.z=o,this}makePerspective(e,t,n,r,i,a,o=Ee,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=Ee,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}};const Ht=/*@__PURE__*/ new F,V=/*@__PURE__*/ new B,Ut=/*@__PURE__*/ new F(0,0,0),Wt=/*@__PURE__*/ new F(1,1,1),Gt=/*@__PURE__*/ new F,Kt=/*@__PURE__*/ new F,H=/*@__PURE__*/ new F,qt=/*@__PURE__*/ new B,Jt=/*@__PURE__*/ new P;var Yt=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin(A(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-A(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin(A(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-A(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin(A(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-A(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:console.warn(`THREE.Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return qt.makeRotationFromQuaternion(e),this.setFromRotationMatrix(qt,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Jt.setFromEuler(this),this.setFromQuaternion(Jt,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};Yt.DEFAULT_ORDER=`XYZ`;var Xt=class{constructor(){this.mask=1}set(e){this.mask=1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t0){r.children=[];for(let t=0;t0){r.animations=[];for(let t=0;t0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){W.subVectors(r,t),pn.subVectors(n,t),mn.subVectors(e,t);let a=W.dot(W),o=W.dot(pn),s=W.dot(mn),c=pn.dot(pn),l=pn.dot(mn),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,hn)!==null&&hn.x>=0&&hn.y>=0&&hn.x+hn.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,hn)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,hn.x),s.addScaledVector(a,hn.y),s.addScaledVector(o,hn.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return Sn.setScalar(0),Cn.setScalar(0),wn.setScalar(0),Sn.fromBufferAttribute(e,t),Cn.fromBufferAttribute(e,n),wn.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(Sn,i.x),a.addScaledVector(Cn,i.y),a.addScaledVector(wn,i.z),a}static isFrontFacing(e,t,n,r){return W.subVectors(n,t),pn.subVectors(e,t),W.cross(pn).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return W.subVectors(this.c,this.b),pn.subVectors(this.a,this.b),W.cross(pn).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;gn.subVectors(r,n),_n.subVectors(i,n),yn.subVectors(e,n);let s=gn.dot(yn),c=_n.dot(yn);if(s<=0&&c<=0)return t.copy(n);bn.subVectors(e,r);let l=gn.dot(bn),u=_n.dot(bn);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(gn,a);xn.subVectors(e,i);let f=gn.dot(xn),p=_n.dot(xn);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(_n,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return vn.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(vn,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(gn,a).addScaledVector(_n,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}};const En={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Dn={h:0,s:0,l:0},On={h:0,s:0,l:0};function kn(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var G=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=D){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,I.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=I.workingColorSpace){return this.r=e,this.g=t,this.b=n,I.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=I.workingColorSpace){if(e=je(e,1),t=A(t,0,1),n=A(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=kn(i,r,e+1/3),this.g=kn(i,r,e),this.b=kn(i,r,e-1/3)}return I.colorSpaceToWorking(this,r),this}setStyle(e,t=D){function n(t){t!==void 0&&parseFloat(t)<1&&console.warn(`THREE.Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:console.warn(`THREE.Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);console.warn(`THREE.Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=D){let n=En[e.toLowerCase()];return n===void 0?console.warn(`THREE.Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=st(e.r),this.g=st(e.g),this.b=st(e.b),this}copyLinearToSRGB(e){return this.r=ct(e.r),this.g=ct(e.g),this.b=ct(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=D){return I.workingToColorSpace(K.copy(this),e),Math.round(A(K.r*255,0,255))*65536+Math.round(A(K.g*255,0,255))*256+Math.round(A(K.b*255,0,255))}getHexString(e=D){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=I.workingColorSpace){I.workingToColorSpace(K.copy(this),t);let n=K.r,r=K.g,i=K.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];r===void 0?console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`):r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,this.name!==``&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},Mn=class extends jn{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new G(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yt,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}};const q=/*@__PURE__*/ new F,Nn=/*@__PURE__*/ new N;let Pn=0;var Fn=class{constructor(e,t,n=!1){if(Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Pn++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Te,this.updateRanges=[],this.gpuType=pe,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;rt.count&&console.warn(`THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new _t);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)console.error(`THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new F(-1/0,-1/0,-1/0),new F(1/0,1/0,1/0));else{if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e0&&(e.userData=this.userData),this.parameters!==void 0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2))&&(Wn.copy(i).invert(),Gn.copy(e.ray).applyMatrix4(Wn),(n.boundingBox===null||Gn.intersectsBox(n.boundingBox)!==!1)&&this._computeIntersections(e,t,Gn)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null){if(Array.isArray(a))for(let i=0,s=d.length;in.far?null:{distance:l,point:er.clone(),object:e}}function rr(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,Jn),e.getVertexPosition(c,Yn),e.getVertexPosition(l,Xn);let u=nr(e,t,n,r,Jn,Yn,Xn,$n);if(u){let e=new F;Tn.getBarycoord($n,Jn,Yn,Xn,e),i&&(u.uv=Tn.getInterpolatedAttribute(i,s,c,l,e,new N)),a&&(u.uv1=Tn.getInterpolatedAttribute(a,s,c,l,e,new N)),o&&(u.normal=Tn.getInterpolatedAttribute(o,s,c,l,e,new F),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new F,materialIndex:0};Tn.getNormal(Jn,Yn,Xn,t.normal),u.face=t,u.barycoord=e}return u}var ir=class extends U{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new B,this.projectionMatrix=new B,this.projectionMatrixInverse=new B,this.coordinateSystem=Ee,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}};const ar=/*@__PURE__*/ new F,or=/*@__PURE__*/ new N,sr=/*@__PURE__*/ new N;var cr=class extends ir{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=Ae*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(ke*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Ae*2*Math.atan(Math.tan(ke*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){ar.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ar.x,ar.y).multiplyScalar(-e/ar.z),ar.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(ar.x,ar.y).multiplyScalar(-e/ar.z)}getViewSize(e,t){return this.getViewBounds(e,or,sr),t.subVectors(sr,or)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(ke*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},lr=class extends U{constructor(){super(),this.isGroup=!0,this.type=`Group`}},ur=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e===void 0?0:e.length/t,this.usage=Te,this.updateRanges=[],this.version=0,this.uuid=k()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let r=0,i=this.stride;r1?null:t.copy(e.start).addScaledVector(n,i)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||Rr.getNormalMatrix(e),r=this.coplanarPoint(Ir).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}};const Br=/*@__PURE__*/ new z,Vr=/*@__PURE__*/ new N(.5,.5),Hr=/*@__PURE__*/ new F;var Ur=class{constructor(e=new zr,t=new zr,n=new zr,r=new zr,i=new zr,a=new zr){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Ee,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Br.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Br.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Br)}intersectsSprite(e){Br.center.set(0,0,0);let t=Vr.distanceTo(e.center);return Br.radius=.7071067811865476+t,Br.applyMatrix4(e.matrixWorld),this.intersectsSphere(Br)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,Hr.y=r.normal.y>0?e.max.y:e.min.y,Hr.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Hr)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Wr=class extends jn{constructor(e){super(),this.isLineBasicMaterial=!0,this.type=`LineBasicMaterial`,this.color=new G(16777215),this.map=null,this.linewidth=1,this.linecap=`round`,this.linejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}};const Gr=/*@__PURE__*/ new F,Kr=/*@__PURE__*/ new F,qr=/*@__PURE__*/ new B,Jr=/*@__PURE__*/ new Vt,Yr=/*@__PURE__*/ new z,Xr=/*@__PURE__*/ new F,Zr=/*@__PURE__*/ new F;var Qr=class extends U{constructor(e=new Un,t=new Wr){super(),this.isLine=!0,this.type=`Line`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let e=1,r=t.count;e0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;er)return;Xr.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(Xr);if(!(ct.far))return{distance:c,point:Zr.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}const ei=/*@__PURE__*/ new F,ti=/*@__PURE__*/ new F;var ni=class extends Qr{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type=`LineSegments`}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let e=0,r=t.count;e0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;ei.far)return;a.push({distance:c,distanceToRay:Math.sqrt(s),point:n,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}var di=class extends jn{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type=`MeshStandardMaterial`,this.defines={STANDARD:``},this.color=new G(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new G(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new N(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yt,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:``},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},fi=class extends di{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:``,PHYSICAL:``},this.type=`MeshPhysicalMaterial`,this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new N(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return A(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new G(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new G(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new G(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:``,PHYSICAL:``},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}};function pi(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function mi(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function hi(e){function t(t,n){return e[t]-e[n]}let n=e.length,r=Array(n);for(let e=0;e!==n;++e)r[e]=e;return r.sort(t),r}function gi(e,t,n){let r=e.length,i=new e.constructor(r);for(let a=0,o=0;o!==r;++a){let r=n[a]*t;for(let n=0;n!==t;++n)i[o++]=e[r+n]}return i}function _i(e,t,n,r){let i=1,a=e[0];for(;a!==void 0&&a[r]===void 0;)a=e[i++];if(a===void 0)return;let o=a[r];if(o!==void 0){if(Array.isArray(o))do o=a[r],o!==void 0&&(t.push(a.time),n.push(...o)),a=e[i++];while(a!==void 0);else if(o.toArray!==void 0)do o=a[r],o!==void 0&&(t.push(a.time),o.toArray(n,n.length)),a=e[i++];while(a!==void 0);else do o=a[r],o!==void 0&&(t.push(a.time),n.push(o)),a=e[i++];while(a!==void 0)}}var vi=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e=i)){let o=t[1];e=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n>>1;et;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(console.error(`THREE.KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(console.error(`THREE.KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){console.error(`THREE.KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){console.error(`THREE.KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&mi(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){console.error(`THREE.KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===_e,i=e.length-1,a=1;for(let o=1;o0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};Q.prototype.ValueTypeName=``,Q.prototype.TimeBufferType=Float32Array,Q.prototype.ValueBufferType=Float32Array,Q.prototype.DefaultInterpolation=ge;var Si=class extends Q{constructor(e,t,n){super(e,t,n)}};Si.prototype.ValueTypeName=`bool`,Si.prototype.ValueBufferType=Array,Si.prototype.DefaultInterpolation=he,Si.prototype.InterpolantFactoryMethodLinear=void 0,Si.prototype.InterpolantFactoryMethodSmooth=void 0;var Ci=class extends Q{constructor(e,t,n,r){super(e,t,n,r)}};Ci.prototype.ValueTypeName=`color`;var wi=class extends Q{constructor(e,t,n,r){super(e,t,n,r)}};wi.prototype.ValueTypeName=`number`;var Ti=class extends vi{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)P.slerpFlat(i,0,a,c-o,a,c,s);return i}},Ei=class extends Q{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new Ti(this.times,this.values,this.getValueSize(),e)}};Ei.prototype.ValueTypeName=`quaternion`,Ei.prototype.InterpolantFactoryMethodSmooth=void 0;var Di=class extends Q{constructor(e,t,n){super(e,t,n)}};Di.prototype.ValueTypeName=`string`,Di.prototype.ValueBufferType=Array,Di.prototype.DefaultInterpolation=he,Di.prototype.InterpolantFactoryMethodLinear=void 0,Di.prototype.InterpolantFactoryMethodSmooth=void 0;var Oi=class extends Q{constructor(e,t,n,r){super(e,t,n,r)}};Oi.prototype.ValueTypeName=`vector`;var ki=class{constructor(e=``,t=-1,n=[],r=xe){this.name=e,this.tracks=n,this.duration=t,this.blendMode=r,this.uuid=k(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,r=1/(e.fps||1);for(let e=0,i=n.length;e!==i;++e)t.push(ji(n[e]).scale(r));let i=new this(e.name,e.duration,t,e.blendMode);return i.uuid=e.uuid,i.userData=JSON.parse(e.userData||`{}`),i}static toJSON(e){let t=[],n=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let e=0,r=n.length;e!==r;++e)t.push(Q.toJSON(n[e]));return r}static CreateFromMorphTargetSequence(e,t,n,r){let i=t.length,a=[];for(let e=0;e1){let e=a[1],t=r[e];t||(r[e]=t=[]),t.push(n)}}let a=[];for(let e in r)a.push(this.CreateFromMorphTargetSequence(e,r[e],t,n));return a}static parseAnimation(e,t){if(console.warn(`THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185`),!e)return console.error(`THREE.AnimationClip: No animation in JSONLoader data.`),null;let n=function(e,t,n,r,i){if(n.length!==0){let a=[],o=[];_i(n,a,o,r),a.length!==0&&i.push(new e(t,a,o))}},r=[],i=e.name||`default`,a=e.fps||30,o=e.blendMode,s=e.length||-1,c=e.hierarchy||[];for(let e=0;e{t&&t(i),this.manager.itemEnd(e)},0),i;if(Fi[e]!==void 0){Fi[e].push({onLoad:t,onProgress:n,onError:r});return}Fi[e]=[],Fi[e].push({onLoad:t,onProgress:n,onError:r});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?`include`:`same-origin`,signal:typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,s=this.responseType;fetch(a).then(t=>{if(t.status===200||t.status===0){if(t.status===0&&console.warn(`THREE.FileLoader: HTTP Status 0 received.`),typeof ReadableStream>`u`||t.body===void 0||t.body.getReader===void 0)return t;let n=Fi[e],r=t.body.getReader(),i=t.headers.get(`X-File-Size`)||t.headers.get(`Content-Length`),a=i?parseInt(i):0,o=a!==0,s=0,c=new ReadableStream({start(e){t();function t(){r.read().then(({done:r,value:i})=>{if(r)e.close();else{s+=i.byteLength;let r=new ProgressEvent(`progress`,{lengthComputable:o,loaded:s,total:a});for(let e=0,t=n.length;e{e.error(t)})}}});return new Response(c)}throw new Ii(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)}).then(e=>{switch(s){case`arraybuffer`:return e.arrayBuffer();case`blob`:return e.blob();case`document`:return e.text().then(e=>new DOMParser().parseFromString(e,o));case`json`:return e.json();default:if(o===``)return e.text();{let t=/charset="?([^;"\s]*)"?/i.exec(o),n=t&&t[1]?t[1].toLowerCase():void 0,r=new TextDecoder(n);return e.arrayBuffer().then(e=>r.decode(e))}}}).then(t=>{Mi.add(`file:${e}`,t);let n=Fi[e];delete Fi[e];for(let e=0,r=n.length;e{let n=Fi[e];if(n===void 0)throw this.manager.itemError(e),t;delete Fi[e];for(let e=0,r=n.length;e{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}};const Ri=/* @__PURE__ */ new WeakMap;var zi=class extends Pi{constructor(e){super(e)}load(e,t,n,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=Mi.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)i.manager.itemStart(e),setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);else{let e=Ri.get(a);e===void 0&&(e=[],Ri.set(a,e)),e.push({onLoad:t,onError:r})}return a}let o=tt(`img`);function s(){l(),t&&t(this);let n=Ri.get(this)||[];for(let e=0;e`u`&&console.warn(`THREE.ImageBitmapLoader: createImageBitmap() not supported.`),typeof fetch>`u`&&console.warn(`THREE.ImageBitmapLoader: fetch() not supported.`),this.options={premultiplyAlpha:`none`},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=Mi.get(`image-bitmap:${e}`);if(a!==void 0){if(i.manager.itemStart(e),a.then){a.then(n=>{if(ra.has(a)===!0)r&&r(ra.get(a)),i.manager.itemError(e),i.manager.itemEnd(e);else return t&&t(n),i.manager.itemEnd(e),n});return}return setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0),a}let o={};o.credentials=this.crossOrigin===`anonymous`?`same-origin`:`include`,o.headers=this.requestHeader,o.signal=typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let s=fetch(e,o).then(function(e){return e.blob()}).then(function(e){return createImageBitmap(e,Object.assign(i.options,{colorSpaceConversion:`none`}))}).then(function(n){return Mi.add(`image-bitmap:${e}`,n),t&&t(n),i.manager.itemEnd(e),n}).catch(function(t){r&&r(t),ra.set(s,t),Mi.remove(`image-bitmap:${e}`),i.manager.itemError(e),i.manager.itemEnd(e)});Mi.add(`image-bitmap:${e}`,s),i.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},aa=class{constructor(e,t,n){this.binding=e,this.valueSize=n;let r,i,a;switch(t){case`quaternion`:r=this._slerp,i=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case`string`:case`bool`:r=this._select,i=this._select,a=this._setAdditiveIdentityOther,this.buffer=Array(n*5);break;default:r=this._lerp,i=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=r,this._mixBufferRegionAdditive=i,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let n=this.buffer,r=this.valueSize,i=e*r+r,a=this.cumulativeWeight;if(a===0){for(let e=0;e!==r;++e)n[i+e]=n[e];a=t}else{a+=t;let e=t/a;this._mixBufferRegion(n,i,0,e,r)}this.cumulativeWeight=a}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,r=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,r,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,r=e*t+t,i=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,i<1){let e=t*this._origIndex;this._mixBufferRegion(n,r,e,1-i,t)}a>0&&this._mixBufferRegionAdditive(n,r,this._addIndex*t,1,t);for(let e=t,i=t+t;e!==i;++e)if(n[e]!==n[e+t]){o.setValue(n,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,r=n*this._origIndex;e.getValue(t,r);for(let e=n,i=r;e!==i;++e)t[e]=t[r+e%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n=.5)for(let r=0;r!==i;++r)e[t+r]=e[n+r]}_slerp(e,t,n,r){P.slerpFlat(e,t,e,t,e,n,r)}_slerpAdditive(e,t,n,r,i){let a=this._workIndex*i;P.multiplyQuaternionsFlat(e,a,e,t,e,n),P.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,n,r,i){let a=1-r;for(let o=0;o!==i;++o){let i=t+o;e[i]=e[i]*a+e[n+o]*r}}_lerpAdditive(e,t,n,r,i){for(let a=0;a!==i;++a){let i=t+a;e[i]=e[i]+e[n+a]*r}}};const oa=/* @__PURE__ */ RegExp(`[\\[\\]\\.:\\/]`,`g`),sa=/* @__PURE__ */ RegExp(`^((?:[^\\[\\]\\.:\\/]+[\\/:])*)([^\\[\\]:\\/]+)?(?:\\.([^\\[\\]\\.:\\/]+)(?:\\[(.+)\\])?)?\\.([^\\[\\]\\.:\\/]+)(?:\\[(.+)\\])?$`),ca=[`material`,`materials`,`bones`,`map`];var la=class{constructor(e,t,n){let r=n||$.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},$=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(oa,``)}static parseTrackName(e){let t=sa.exec(e);if(t===null)throw Error(`PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);ca.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r0){let e=this._interpolants,t=this._propertyBindings;switch(this.blendMode){case 2501:for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(a),t[n].accumulateAdditive(o);break;case xe:default:for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(a),t[n].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,r=this.time+e,i=this._loopCount,a=n===2202;if(e===0)return i===-1?r:a&&(i&1)==1?t-r:r;if(n===2200){i===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));handle_stop:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break handle_stop}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e<0?-1:1})}}else{if(i===-1&&(e>=0?(i=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let n=Math.floor(r/t);r-=t*n,i+=Math.abs(n);let o=this.repetitions-i;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e>0?1:-1});else{if(o===1){let t=e<0;this._setEndings(t,!t,a)}else this._setEndings(!1,!1,a);this._loopCount=i,this.time=r,this._mixer.dispatchEvent({type:`loop`,action:this,loopDelta:n})}}else this.time=r;if(a&&(i&1)==1)return t-r}return r}_setEndings(e,t,n){let r=this._interpolantSettings;n?(r.endingStart=ye,r.endingEnd=ye):(r.endingStart=e?this.zeroSlopeAtStart?ye:ve:be,r.endingEnd=t?this.zeroSlopeAtEnd?ye:ve:be)}_scheduleFading(e,t,n){let r=this._mixer,i=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,s=a.sampleValues;return o[0]=i,s[0]=t,o[1]=i+e,s[1]=n,this}};const da=/* @__PURE__ */ new Float32Array(1);var fa=class extends De{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){let n=e._localRoot||this._root,r=e._clip.tracks,i=r.length,a=e._propertyBindings,o=e._interpolants,s=n.uuid,c=this._bindingsByRootAndName,l=c[s];l===void 0&&(l={},c[s]=l);for(let e=0;e!==i;++e){let i=r[e],c=i.name,u=l[c];if(u!==void 0)++u.referenceCount,a[e]=u;else{if(u=a[e],u!==void 0){u._cacheIndex===null&&(++u.referenceCount,this._addInactiveBinding(u,s,c));continue}let r=t&&t._propertyBindings[e].binding.parsedPath;u=new aa($.create(n,c,r),i.ValueTypeName,i.getValueSize()),++u.referenceCount,this._addInactiveBinding(u,s,c),a[e]=u}o[e].resultBuffer=u.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let t=(e._localRoot||this._root).uuid,n=e._clip.uuid,r=this._actionsByClip[n];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,n,t)}let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];n.useCount++===0&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.useCount===0&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,r=this.time+=e,i=Math.sign(e),a=this._accuIndex^=1;for(let o=0;o!==n;++o)t[o]._update(r,e,i,a);let o=this._bindings,s=this._nActiveBindings;for(let e=0;e!==s;++e)o[e].apply(a);return this}setTime(e){this.time=0;for(let e=0;e>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function ma(e,t=`walk`){let n=t.toLowerCase();return e.find(e=>e.name.toLowerCase()===n)??e.find(e=>e.name.toLowerCase().includes(n))??e[0]??null}function ha(e){let t=e?.image;return!t?.data||!t.width||!t.height||t.data.length<4*t.width*t.height?null:t}function ga(e){let t=[];e.updateMatrixWorld(!0);let n=new F,r=new F,i=new F;return e.traverse(e=>{let a=e;if(!a.isMesh||!a.geometry.getAttribute(`position`))return;let o=a.geometry,s=o.getAttribute(`position`).count,c=o.index?Uint32Array.from(o.index.array):Uint32Array.from({length:s-s%3},(e,t)=>t),l=new Float64Array(c.length/3),u=0;for(let e=0;e0&&t.push({mesh:a,tri:c,cum:l,color:g,tex:m})}),t}function _a(e,t,n,r){let i=e.color;if(!e.tex)return[i.r,i.g,i.b];let{pixels:a,uv:o}=e.tex,s=e.tri[3*t],c=e.tri[3*t+1],l=e.tri[3*t+2],u=1-n-r,d=o.getX(s)*u+o.getX(c)*n+o.getX(l)*r,f=o.getY(s)*u+o.getY(c)*n+o.getY(l)*r,p=Math.min(a.width-1,Math.floor((d-Math.floor(d))*a.width)),m=4*(Math.min(a.height-1,Math.floor((f-Math.floor(f))*a.height))*a.width+p);return[i.r*a.data[m]/255,i.g*a.data[m+1]/255,i.b*a.data[m+2]/255]}function va(e,t,n){let r=e.reduce((e,t)=>e+t.cum[t.cum.length-1],0),i=[];for(let a=0;a>1;o[e]1&&(l=1-l,u=1-u);let[d,f,p]=_a(e[a],s,l,u);i.push({part:a,tri:s,u:l,v:u,r:d,g:f,b:p})}return i}const ya=new F(.35,.85,.4).normalize();function ba(e,t,r){let i=ga(e);if(!i.length)throw Error(`the model has no meshes`);let a=ma(t,r.clip??`walk`),o=new fa(e);a&&o.clipAction(a).play();let s=pa(r.seed??7),c=Math.max(1,Math.round(r.seconds*r.fps)),l=r.pointsPerFrame,u=va(i,l,s),d=i.map(e=>new Float32Array(3*e.mesh.geometry.getAttribute(`position`).count)),f=i.map(e=>new Uint8Array(e.mesh.geometry.getAttribute(`position`).count)),p=new F,m=(e,t,n)=>(f[e][t]||(i[e].mesh.getVertexPosition(t,p).applyMatrix4(i[e].mesh.matrixWorld),d[e][3*t]=p.x,d[e][3*t+1]=p.y,d[e][3*t+2]=p.z,f[e][t]=1),n.set(d[e][3*t],d[e][3*t+1],d[e][3*t+2])),h=t=>{a&&o.setTime(t),e.updateMatrixWorld(!0);for(let e=0;e{let e=0,t=0;for(let n of u)m(n.part,i[n.part].tri[3*n.tri],g),e+=g.x,t+=g.z;return[e/l,t/l]},S=a&&a.duration>0?a.duration:0,C=0,w=0;if(S){h(0);let[e,t]=x();h(S*.9999);let[n,r]=x();C=n-e,w=r-t}let T=new Float32Array(3*l*c),ee=new Uint8Array(3*l*c),te=new Float32Array(l*c),ne=r.resample?void 0:new Uint32Array(l*c);for(let e=0;e0&&(u=va(i,l,s));for(let r=0;r{let t=0,n=0;for(let r=0;re.name),carried:ue}}}function xa(e){let t=Math.imul(e>>>0,747796405)+2891336453>>>0,n=Math.imul((t>>>(t>>>28)+4^t)>>>0,277803737)>>>0;return(n>>>22^n)>>>0}function Sa(e){return xa(e)/4294967295}function Ca(){return{eye:[0,1.35,8],target:[0,.95,0],hfov:78*Math.PI/180,cells:400,tolerance:.05,jitter:.006,drift:.02,seed:7}}function wa(e,t){let n=[t[0]-e[0],t[1]-e[1],t[2]-e[2]],r=Math.hypot(...n)||1;n[0]/=r,n[1]/=r,n[2]/=r;let i=[-n[2],0,n[0]],a=Math.hypot(...i)||1;return i[0]/=a,i[2]/=a,[i,[i[1]*n[2]-i[2]*n[1],i[2]*n[0]-i[0]*n[2],i[0]*n[1]-i[1]*n[0]],n]}function Ta(e){let t=Math.max(1e-9,Sa(xa(e))),n=Sa(xa(e^2654435769));return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*n)}function Ea(e,n=Ca()){let{header:r,frameStart:i,trackId:a}=e,o=e.position;if(!(o instanceof Uint16Array))throw Error(`simulateWitness reads u16 positions`);let s=r.pointCount,{min:c,max:l}=r.bounds,u=[0,1,2].map(e=>(l[e]-c[e])/65535),d=i&&r.frameCount>0?Array.from({length:r.frameCount},(e,t)=>[i[t],i[t+1]]):[[0,s]],f=r.fps>0?r.fps:30,[p,m,h]=wa(n.eye,n.target),g=Math.max(8,Math.round(n.cells)),_=Math.round(g*2/3),v=g/2/Math.tan(n.hfov/2),y=new Float32Array(g*_),b=new Int32Array(s),x=new Float32Array(s),S=new Uint8Array(s),C=new Uint16Array(3*s),w=0,T=[0,0,0];return d.forEach(([e,r],i)=>{y.fill(1/0);for(let t=e;t=g||a>=_)continue;let s=a*g+i;b[t]=s,x[t]=0){let t=y[e],a=f<=t+n.tolerance;a&&(S[d]=255,w++);let o=a?f:t,c=2*Math.PI*Sa((r^n.seed)>>>0),l=n.jitter*Ta(r*977+i*7919+n.seed>>>0)+n.drift*Math.sin(2*Math.PI*s/2.7+c);f=o*Math.exp(l)}let p=x[d]>0?f/x[d]:1;for(let e=0;e<3;e++){let r=n.eye[e]+(T[e]-n.eye[e])*p;C[3*d+e]=t(r,c[e],l[e],65535)}}}),{observed:S,rawPosition:C,seen:s?w/s:1}}function Da(e,t,n={}){return{...e,header:{...e.header,meta:{...e.header.meta,witness:{simulated:!0,seen:Math.round(t.seen*1e3)/1e3,...n}}},observed:t.observed,rawPosition:t.rawPosition}}function Oa(e){e.traverse(e=>{let t=e.isMesh?[e.material].flat():[];for(let e of t){let t=e.map?.image;if(!e.map||typeof ImageBitmap>`u`||!(t instanceof ImageBitmap))continue;let n=new OffscreenCanvas(t.width,t.height).getContext(`2d`);n.drawImage(t,0,0),e.map.image=n.getImageData(0,0,t.width,t.height)}})}async function ka(e,t,n){let r=await fetch(e).catch(()=>null);if(!r?.ok)return null;let i=await r.arrayBuffer();if(i.byteLength<12||new TextDecoder().decode(new Uint8Array(i,0,4))!==`glTF`)return null;let{GLTFLoader:a}=await import(`./GLTFLoader-DXt_9DaB.js`),o=await new a().parseAsync(i,``);Oa(o.scene);let{block:s,info:c}=ba(o.scene,o.animations,{pointsPerFrame:t,seconds:10,fps:30,heightM:1.75,resample:n});return{block:s,note:`walker from ${decodeURIComponent(e.split(`/`).pop()??e)}, clip “${c.clip}”${c.carried?`, carried across at 1.3 m/s`:``}`}}self.onmessage=async e=>{try{let{kind:t,model:n}=e.data,r=t.startsWith(`walker-2m`)||t===`witness-2m`?6667:2e4,i=t.endsWith(`kalam`),a=``,o;if(t===`firebrand`)o=w();else{let e=n?await ka(n,r,i):null;e?{block:o,note:a}=e:o=C({pointsPerFrame:r,resample:i})}if(t.startsWith(`witness`)){let e=Ea(o);o=Da(o,e),a=`${a?a+`; `:``}simulated witness: one camera saw ${Math.round(e.seen*100)} % of the samples; the model's own positions stand in for the repair`}let s=re(o),c=ne(o,s),l=[o.position.buffer,o.time.buffer,o.color.buffer];c&&l.push(c.data.buffer),o.observed&&l.push(o.observed.buffer),o.rawPosition&&l.push(o.rawPosition.buffer),o.trackId&&l.push(o.trackId.buffer),o.frameStart&&l.push(o.frameStart.buffer),s&&l.push(s.buffer),self.postMessage({block:o,next:s,aux:c,note:a},l)}catch(e){self.postMessage({error:String(e?.message??e)})}};export{Er as $,jn as A,se as B,ni as C,Se as D,ue as E,fi as F,Qi as G,U as H,di as I,$ as J,li as K,ae as L,B as M,tr as N,Pi as O,Mn as P,D as Q,oe as R,ri as S,de as T,$i as U,wi as V,cr as W,Ei as X,P as Y,ie as Z,vi as _,Un as a,N as at,Qr as b,I as c,lr as d,xr as et,ia as f,dr as g,ur as h,Fn as i,Bi as it,Ye as j,na as k,ta as l,Fr as m,Sr as n,qi as nt,E as o,F as ot,Dr as p,ii as q,_t as r,gt as rt,G as s,Oi as st,ki as t,z as tt,Li as u,he as v,le as w,Wr as x,ge as y,ce as z}; \ No newline at end of file diff --git a/v4d-next/assets/transformers.web--pOIPjDQ.js b/v4d-next/assets/transformers.web--pOIPjDQ.js new file mode 100644 index 0000000..3a20c16 --- /dev/null +++ b/v4d-next/assets/transformers.web--pOIPjDQ.js @@ -0,0 +1,49 @@ +var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},n=/* @__PURE__ */ (e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")}),r=/* @__PURE__ */ t({InferenceSession:()=>Ae,TRACE:()=>D,TRACE_EVENT_BEGIN:()=>Te,TRACE_EVENT_END:()=>Ee,TRACE_FUNC_BEGIN:()=>Ce,TRACE_FUNC_END:()=>we,Tensor:()=>be,default:()=>or,env:()=>C,registerBackend:()=>h}),i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,c=(e=>typeof n<`u`?n:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof n<`u`?n:e)[t]}):e)(function(e){ +/*! +* ONNX Runtime Web v1.31.0-dev.20260914-8d85527a0 +* Copyright (c) Microsoft Corporation. All rights reserved. +* Licensed under the MIT License. +*/ +if(typeof n<`u`)return n.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),l=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},u=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of o(t))!s.call(e,c)&&c!==n&&i(e,c,{get:()=>t[c],enumerable:!(r=a(t,c))||r.enumerable});return e},f=e=>d(i({},`__esModule`,{value:!0}),e),p,m,h,g,_,v=l(()=>{p=/* @__PURE__ */ new Map,m=[],h=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=p.get(e);if(r===void 0)p.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=m.indexOf(e);t!==-1&&m.splice(t,1);for(let t=0;t{let t=p.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},_=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?m:n,i,a=[],o=/* @__PURE__ */ new Set;for(let e of r){let t=await g(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),y=l(()=>{v()}),b,x=l(()=>{b=`1.31.0-dev.20260911-2a43ec07e`}),ee,S,te=l(()=>{x(),ee=`warning`,S={wasm:{},webgl:{},webgpu:{},versions:{common:b},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);ee=e}},get logLevel(){return ee}},Object.defineProperty(S,"logLevel",{enumerable:!0})}),C,w=l(()=>{te(),C=S}),ne,re,T=l(()=>{ne=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t{ye(),E=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,E(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(E(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return E(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},ae=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new ve({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},oe=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new ve({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},se=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new ve({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},ce=(e,t,n)=>new ve({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),ue,de,fe,pe,me=l(()=>{ue=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),de=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),fe=!1,pe=()=>{if(!fe){fe=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(ue.set(`int64`,BigInt64Array),de.set(BigInt64Array,`int64`)),t&&(ue.set(`uint64`,BigUint64Array),de.set(BigUint64Array,`uint64`)),r?(ue.set(`float16`,n),de.set(n,`float16`)):ue.set(`float16`,Uint16Array)}}}),he,ge,_e=l(()=>{ye(),he=e=>{let t=1;for(let n=0;n{switch(e.location){case`cpu`:return new ve(e.type,e.data,t);case`cpu-pinned`:return new ve({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new ve({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new ve({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new ve({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),ve,ye=l(()=>{T(),le(),me(),_e(),ve=class{constructor(e,t,n){pe();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=ue.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=ue.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=de.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=he(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return ie(e,t)}static fromTexture(e,t){return ae(e,t)}static fromGpuBuffer(e,t){return oe(e,t)}static fromMLTensor(e,t){return se(e,t)}static fromPinnedBuffer(e,t,n){return ce(e,t,n)}toDataURL(e){return ne(this,e)}toImageData(e){return re(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return ge(this,e)}}}),be,xe=l(()=>{ye(),be=ve}),D,Se,Ce,we,Te,Ee,De=l(()=>{te(),D=(e,t)=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||console.timeStamp(`${e}::ORT::${t}`)},Se=(e,t)=>{let n=(/* @__PURE__ */ Error()).stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||Se(`BEGIN`,e)},we=e=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||Se(`END`,e)},Te=e=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||console.time(`ORT::${e}`)},Ee=e=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||console.timeEnd(`ORT::${e}`)}}),Oe,ke=l(()=>{v(),xe(),De(),Oe=class e{constructor(e){this.handler=e}async run(e,t,n){Ce(),Te(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof be||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof be)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof be)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];s[e]=t instanceof be?t:new be(t.type,t.data,t.dims)}return Ee(`InferenceSession.run`),we(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){Ce(),Te(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await _(o),l=await s.createInferenceSessionHandler(a,c);return Ee(`InferenceSession.create`),we(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ae,je=l(()=>{ke(),Ae=Oe}),Me=l(()=>{}),Ne=l(()=>{}),Pe=l(()=>{}),Fe=l(()=>{}),Ie={};u(Ie,{InferenceSession:()=>Ae,TRACE:()=>D,TRACE_EVENT_BEGIN:()=>Te,TRACE_EVENT_END:()=>Ee,TRACE_FUNC_BEGIN:()=>Ce,TRACE_FUNC_END:()=>we,Tensor:()=>be,env:()=>C,registerBackend:()=>h});var Le=l(()=>{y(),w(),je(),xe(),Me(),Ne(),De(),Pe(),Fe()}),Re=l(()=>{}),ze={};u(ze,{default:()=>He});var Be,Ve,He,Ue=l(()=>{An(),vt(),lt(),Be=`ort-wasm-proxy-worker`,Ve=globalThis.self?.name===Be,Ve&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:_t(n.wasm).then(()=>{vn(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;yn(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=Cn(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;wn(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:Tn(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;Dn(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},kn([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:On(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),He=Ve?null:e=>new Worker(e??Qe,{type:`module`,name:Be})}),We={};u(We,{default:()=>Ke});async function Ge(e={}){var t=e,n=!!globalThis.window,r=!!globalThis.WorkerGlobalScope,i=r&&self.name?.startsWith(`em-pthread`);t.mountExternalData=(e,n)=>{e.startsWith(`./`)&&(e=e.substring(2)),(t.ed||=/* @__PURE__ */ new Map).set(e,n)},t.unmountExternalData=()=>{delete t.ed,delete t.Te,delete t.Se,delete t.Ue},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let e=e=>(...t)=>{let n=un;return t=e(...t),un==n?t:new Promise((e,t)=>{_n={resolve:e,reject:t}})};(()=>{for(let n of[`_OrtAppendExecutionProvider`,`_OrtCreateSession`,`_OrtRun`,`_OrtRunWithBinding`,`_OrtBindInput`])t[n]=e(t[n])})(),typeof jsepRunAsync<`u`&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,s,c=(e,t)=>{throw t},l=import.meta.url,u=``;if(n||r){try{u=new URL(`.`,l).href}catch{}r&&(s=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),o=async e=>{if(ee(e))return new Promise((t,n)=>{var r=new XMLHttpRequest;r.open(`GET`,e,!0),r.responseType=`arraybuffer`,r.onload=()=>{r.status==200||r.status==0&&r.response?t(r.response):n(r.status)},r.onerror=n,r.send(null)});var t=await fetch(e,{credentials:`same-origin`});if(t.ok)return t.arrayBuffer();throw Error(t.status+` : `+t.url)}}var d,f,p,m,h,g,_=console.log.bind(console),v=console.error.bind(console),y=_,b=v,x=!1,ee=e=>e.startsWith(`file://`);function S(){Ne.buffer!=C.buffer&&ue()}if(i){let e=function(n){try{var r=n.data,i=r.$c;if(i===`load`){let n=[];self.onmessage=e=>n.push(e),g=()=>{postMessage({$c:`loaded`});for(let t of n)e(t);self.onmessage=e};for(let e of r.ue)t[e]&&!t[e].proxy||(t[e]=(...t)=>{postMessage({$c:`callHandler`,te:e,args:t})},e==`print`&&(y=t[e]),e==`printErr`&&(b=t[e]));Ne=r.Me,ue(),f=r.Ne,me(),ss()}else if(i===`run`){(function(e){var t=(S(),E)[e+52>>>2>>>0];e=(S(),E)[e+56>>>2>>>0],Ca(t,t-e),F(t)})(r.Xc),ma(r.Xc,0,0,1,0,0),Ae(),Qt(r.Xc),te||=(Wi(),!0);try{Pe(r.ze,r.kd)}catch(e){if(e!=`unwind`)throw e}}else r.target!==`setimmediate`&&(i===`checkMailbox`?te&&$t():i&&(b(`worker: received unknown command ${i}`),b(r)))}catch(e){throw ha(),e}};var te=!1;self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=e}var C,w,ne,re,T,E,ie,ae,oe,se,ce,le=!1;function ue(){var e=Ne.buffer;t.HEAP8=C=new Int8Array(e),ne=new Int16Array(e),t.HEAPU8=w=new Uint8Array(e),re=new Uint16Array(e),t.HEAP32=T=new Int32Array(e),t.HEAPU32=E=new Uint32Array(e),ie=new Float32Array(e),ae=new Float64Array(e),oe=new BigInt64Array(e),se=new BigUint64Array(e)}function de(){le=!0,i?g():yo.hc()}function fe(e){throw b(e=`Aborted(`+e+`)`),x=!0,e=new WebAssembly.RuntimeError(e+`. Build with -sASSERTIONS for more info.`),h?.(e),e}function pe(){return{a:{qa:So,f:Re,K:Be,k:Ge,p:Ke,l:qe,fa:Je,b:Ye,da:Xe,gc:Qe,q:$e,ea:it,Ua:at,cc:ot,ec:st,Va:ct,Sa:lt,La:ut,Ra:dt,oa:ft,dc:pt,ac:mt,Ta:ht,bc:gt,_a:_t,Ba:Ct,Xb:wt,Vb:Mt,Aa:Pt,O:Ft,J:It,Wb:zt,ka:qt,Yb:Jt,Oa:Yt,_b:en,Ea:nn,Tb:rn,Ca:an,Na:Qt,Xa:on,U:bn,n:Dn,c:Dt,qb:On,w:kn,N:An,A:jn,j:Mn,o:Nn,rb:Pn,H:Fn,T:In,g:Ln,u:Rn,m:zn,i:Bn,Ia:Vn,Ja:Gn,Ka:Kn,Ga:qn,Ha:Jn,Ub:Zn,ab:Qn,Za:tr,Z:ir,pb:ar,Da:or,Ya:$n,X:sr,Wa:cr,$b:lr,G:Xn,db:ur,_:dr,pa:_r,Zb:vr,cb:gr,bb:yr,lb:Kr,z:qr,sa:Jr,ra:Yr,nb:Xr,Y:Zr,v:Qr,kb:$r,jb:M,ib:ei,mb:ti,gb:ni,fb:ri,eb:ii,Pa:ci,Qa:li,fc:we,W:ui,Fa:di,ma:N,Ma:fi,la:mi,Fb:as,va:$o,Gb:is,wa:Qo,E:zo,e:Eo,r:wo,x:Co,C:Fo,Ib:Yo,ca:Jo,D:ko,xa:Xo,aa:es,ha:qo,Jb:Ko,Kb:Go,za:Vo,Lb:Uo,ya:Wo,Mb:Ho,ua:rs,ba:Zo,d:To,B:Oo,s:Do,Eb:os,t:Ao,y:Lo,F:L,I:jo,L:Ro,Nb:Bo,R:ts,ia:Po,$:ns,Pb:No,Rb:Mo,Ob:Io,h:hi,a:Ne,$a:Se,Hb:gi,V:_i,M:vi,na:yi,Db:bi,ja:xi,S:Si,Ab:Ci,Bb:wi,vb:Ti,wb:Ei,P:Di,xb:Oi,yb:ki,ta:Ai,Sb:ji,ob:Mi,Q:Ni,hb:Pi,Cb:Fi,sb:Ii,tb:Ri,ub:zi,ga:Bi,zb:Vi,Qb:Hi}}}async function me(){function e(e,n){var r=yo=e.exports;e={};for(let[t,n]of Object.entries(r))typeof n==`function`?(r=cn(n),e[t]=r):e[t]=n;return yo=e,yo=(function(){var e=yo,t=e=>t=>e(t)>>>0,n=e=>()=>e()>>>0;return(e=Object.assign({},e)).ic=t(e.ic),e.Nc=n(e.Nc),e.Pc=t(e.Pc),e.Bd=(e=>(t,n)=>e(t,n)>>>0)(e.Bd),e.Gd=t(e.Gd),e.Hd=n(e.Hd),e.Ld=t(e.Ld),e})(),De.push(yo.sd),Ui=(e=yo).ic,Wi=e.jc,t._OrtInit=e.kc,t._OrtGetLastError=e.lc,t._OrtCreateSessionOptions=e.mc,t._OrtAppendExecutionProvider=e.nc,t._OrtAddFreeDimensionOverride=e.oc,t._OrtAddSessionConfigEntry=e.pc,t._OrtReleaseSessionOptions=e.qc,t._OrtCreateSession=e.rc,t._OrtReleaseSession=e.sc,t._OrtGetInputOutputCount=e.tc,t._OrtGetInputOutputMetadata=e.uc,t._OrtFree=e.vc,t._OrtCreateTensor=e.wc,t._OrtGetTensorData=e.xc,t._OrtReleaseTensor=e.yc,t._OrtCreateRunOptions=e.zc,t._OrtAddRunConfigEntry=e.Ac,t._OrtReleaseRunOptions=e.Bc,t._OrtCreateBinding=e.Cc,t._OrtBindInput=e.Dc,t._OrtBindOutput=e.Ec,t._OrtClearBoundOutputs=e.Fc,t._OrtReleaseBinding=e.Gc,t._OrtRunWithBinding=e.Hc,t._OrtRun=e.Ic,t._OrtEndProfiling=e.Jc,Gi=t._OrtCreateWebGpuInstance=e.Kc,t._wgpuCreateInstance=e.Lc,Ki=t._OrtGetWebGpuDevice=e.Mc,qi=e.Nc,Ji=t._free=e.Oc,Yi=t._malloc=e.Pc,Xi=t._wgpuBufferRelease=e.Qc,Zi=e.Rc,Qi=e.Sc,$i=e.Tc,ea=e.Uc,ta=e.Vc,na=e.Yc,ra=e.Zc,ia=e.hd,aa=e.id,oa=e.jd,sa=e.ld,ca=e.md,la=e.nd,ua=e.od,da=e.pd,fa=e.qd,pa=e.rd,ma=e.ud,ha=e.vd,ga=e.wd,_a=e.xd,va=e.yd,ya=e.zd,ba=e.Ad,xa=e.Bd,P=e.Cd,Sa=e.Dd,Ca=e.Ed,F=e.Fd,wa=e.Gd,I=e.Hd,Ta=e.Id,Ea=e.Jd,Da=e.Kd,Oa=e.Ld,ka=e.Md,Aa=e.Nd,ja=e.Od,Ma=e.Pd,Na=e.Qd,Pa=e.Rd,Fa=e.Sd,Ia=e.Td,La=e.Ud,Ra=e.Vd,za=e.Wd,Ba=e.Xd,Va=e.Yd,Ha=e.Zd,Ua=e._d,Wa=e.$d,Ga=e.ae,Ka=e.be,qa=e.ce,Ja=e.de,Ya=e.fe,Xa=e.ge,Za=e.he,Qa=e.ie,$a=e.je,eo=e.ke,to=e.le,no=e.me,ro=e.Ae,io=e.Be,ao=e.Ce,oo=e.De,so=e.Ee,co=e.Fe,lo=e.Ge,uo=e.He,fo=e.Ie,po=e.Je,mo=e.Ke,ho=e.nf,go=e.of,_o=e.pf,vo=e.qf,f=n,yo}var n,r=pe();return t.instantiateWasm?new Promise(n=>{t.instantiateWasm(r,(t,r)=>{n(e(t,r))})}):i?e(new WebAssembly.Instance(f,pe()),f):(ce??=t.locateFile?t.locateFile?t.locateFile(`ort-wasm-simd-threaded.asyncify.wasm`,u):u+`ort-wasm-simd-threaded.asyncify.wasm`:new URL(`/v4d-next/assets/ort-wasm-simd-threaded.asyncify-CxOG5pUO.wasm`,``+import.meta.url).href,n=await(async function(e){var t=ce;if(!d&&!ee(t))try{var n=fetch(t,{credentials:`same-origin`});return await WebAssembly.instantiateStreaming(n,e)}catch(e){b(`wasm streaming compile failed: ${e}`),b(`falling back to ArrayBuffer instantiation`)}return(async function(e,t){try{var n=await(async function(e){if(!d)try{var t=await o(e);return new Uint8Array(t)}catch{}if(e==ce&&d)e=new Uint8Array(d);else{if(!s)throw`both async and sync fetching of the wasm failed`;e=s(e)}return e})(e);return await WebAssembly.instantiate(n,t)}catch(e){b(`failed to asynchronously prepare wasm: ${e}`),fe(e)}})(t,e)})(r),e(n.instance,n.module))}class he{name=`ExitStatus`;constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var ge=e=>{e.terminate(),e.onmessage=()=>{}},_e=[],ve=0,ye=null,be=e=>{Te.length==0&&(Me(),je(Te[0]));var t=Te.pop();if(!t)return 6;Ee.push(t),Oe[e.Xc]=t,t.Xc=e.Xc;var n={$c:`run`,ze:e.ye,kd:e.kd,Xc:e.Xc};return t.postMessage(n,e.oe),0},xe=0,D=(e,t,...n)=>{var r,i=16*n.length,a=I(),o=wa(i),s=o>>>3;for(r of n)typeof r==`bigint`?((S(),oe)[s++>>>0]=1n,(S(),oe)[s++>>>0]=r):((S(),oe)[s++>>>0]=0n,(S(),ae)[s++>>>0]=r);return e=ga(e,0,i,o,t),F(a),e};function Se(e){if(i)return D(0,1,e);if(p=e,!(0{if(p=e,i)throw Ce(e),`unwind`;Se(e)},Te=[],Ee=[],De=[],Oe={},ke=e=>{var t=e.Xc;delete Oe[t],Te.push(e),Ee.splice(Ee.indexOf(e),1),e.Xc=0,_a(t)};function Ae(){De.forEach(e=>e())}var je=e=>new Promise(n=>{e.onmessage=r=>{var i=r.data;if(r=i.$c,i.gd&&i.gd!=qi()){var a=Oe[i.gd];a?a.postMessage(i,i.oe):b(`Internal error! Worker sent a message "${r}" to target pthread ${i.gd}, but that thread no longer exists!`)}else r===`checkMailbox`?$t():r===`spawnThread`?be(i):r===`cleanupThread`?Xt(()=>{ke(Oe[i.Le])}):r===`loaded`?(e.loaded=!0,n(e)):i.target===`setimmediate`?e.postMessage(i):r===`uncaughtException`?e.onerror(i.error):r===`callHandler`?t[i.te](...i.args):r&&b(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw b(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var r,i=[];for(r of[])t.propertyIsEnumerable(r)&&i.push(r);e.postMessage({$c:`load`,ue:i,Me:Ne,Ne:f})});function Me(){var e=new Worker((()=>{let e=URL;return import.meta.url>`file:`&&import.meta.url<`file;`?new e(`ort.webgpu.bundle.min.mjs`,import.meta.url):new URL(import.meta.url)})(),{type:`module`,workerData:`em-pthread`,name:`em-pthread`});Te.push(e)}var Ne,Pe=(e,t)=>{xe=0,e=Aa(e,t),0-9007199254740992>e||9007199254740992>>=0);return(S(),C)[t.ad+12>>>0]==0&&(Ve(t,!0),Ie--),He(t,!1),Fe.push(t),Oa(e)}var ze=0,Be=()=>{P(0,0);var e=Fe.pop();Ta(e.td),ze=0};function Ve(e,t){t=+!!t,(S(),C)[e.ad+12>>>0]=t}function He(e,t){t=+!!t,(S(),C)[e.ad+13>>>0]=t}class Ue{constructor(e){this.td=e,this.ad=e-24}}var We=e=>{var t=ze;if(!t)return Sa(0),0;var n=new Ue(t);(S(),E)[n.ad+16>>>2>>>0]=t;var r=(S(),E)[n.ad+4>>>2>>>0];if(!r)return Sa(0),t;for(var i of e){if(i===0||i===r)break;if(Da(i,r,n.ad+16))return Sa(i),t}return Sa(r),t};function Ge(){return We([])}function Ke(e){return We([e>>>0])}function qe(e,t,n,r){return We([e>>>0,t>>>0,n>>>0,r>>>0])}var Je=()=>{var e=Fe.pop();e||fe(`no exception to throw`);var t=e.td;throw(S(),C)[e.ad+13>>>0]==0&&(Fe.push(e),He(e,!0),Ve(e,!1),Ie++),Ea(t),ze=t};function Ye(e,t,n){var r=new Ue(e>>>=0);throw t>>>=0,n>>>=0,(S(),E)[r.ad+16>>>2>>>0]=0,(S(),E)[r.ad+4>>>2>>>0]=t,(S(),E)[r.ad+8>>>2>>>0]=n,Ea(e),Ie++,ze=e}var Xe=()=>Ie;function Ze(e,t,n,r){return i?D(2,1,e,t,n,r):Qe(e,t,n,r)}function Qe(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,!globalThis.SharedArrayBuffer)return 6;var a=[];return i&&a.length===0?Ze(e,t,n,r):(e={ye:n,Xc:e,kd:r,oe:a},i?(e.$c=`spawnThread`,postMessage(e,a),0):be(e))}function $e(e){throw ze||=e>>>0,ze}var et=globalThis.TextDecoder&&new TextDecoder,tt=(e,t,n,r)=>{if(n=t+n,r)return n;for(;e[t]&&!(t>=n);)++t;return t},nt=(e,t=0,n,r)=>{if(16<(n=tt(e,t>>>=0,n,r))-t&&e.buffer&&et)return et.decode(e.buffer instanceof ArrayBuffer?e.subarray(t,n):e.slice(t,n));for(r=``;t(i=(240&i)==224?(15&i)<<12|a<<6|o:(7&i)<<18|a<<12|o<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r},rt=(e,t,n)=>(e>>>=0)?nt((S(),w),e,t,n):``;function it(e,t,n){return i?D(3,1,e,t,n):0}function at(e,t){if(i)return D(4,1,e,t)}function ot(e,t){if(i)return D(5,1,e,t)}function st(e,t,n){if(i)return D(6,1,e,t,n)}function ct(e,t,n){return i?D(7,1,e,t,n):0}function lt(e,t){if(i)return D(8,1,e,t)}function ut(e,t,n){if(i)return D(9,1,e,t,n)}function dt(e,t,n,r){if(i)return D(10,1,e,t,n,r)}function ft(e,t,n,r){if(i)return D(11,1,e,t,n,r)}function pt(e,t,n,r){if(i)return D(12,1,e,t,n,r)}function mt(e){if(i)return D(13,1,e)}function ht(e,t){if(i)return D(14,1,e,t)}function gt(e,t,n){if(i)return D(15,1,e,t,n)}var _t=()=>fe(``),O=e=>{e>>>=0;for(var t=``;;){var n=(S(),w)[e++>>>0];if(!n)return t;t+=String.fromCharCode(n)}},vt={},yt={},bt={},k=class extends Error{constructor(e){super(e),this.name=`BindingError`}};function xt(e,t,n={}){return(function(e,t,n={}){var r=t.name;if(!e)throw new k(`type "${r}" must have a positive integer typeid pointer`);if(yt.hasOwnProperty(e)){if(n.ve)return;throw new k(`Cannot register type '${r}' twice`)}yt[e]=t,delete bt[e],vt.hasOwnProperty(e)&&(t=vt[e],delete vt[e],t.forEach(e=>e()))})(e,t,n)}var St=(e,t,n)=>{switch(t){case 1:return n?e=>(S(),C)[e>>>0]:e=>(S(),w)[e>>>0];case 2:return n?e=>(S(),ne)[e>>>1>>>0]:e=>(S(),re)[e>>>1>>>0];case 4:return n?e=>(S(),T)[e>>>2>>>0]:e=>(S(),E)[e>>>2>>>0];case 8:return n?e=>(S(),oe)[e>>>3>>>0]:e=>(S(),se)[e>>>3>>>0];default:throw TypeError(`invalid integer width (${t}): ${e}`)}};function Ct(e,t,n,r,i){e>>>=0,n>>>=0,t=O(t>>>0);let a=e=>e;if(r=r===0n){let e=8*n;a=t=>BigInt.asUintN(e,t),i=a(i)}xt(e,{name:t,Wc:a,cd:(e,t)=>(typeof t==`number`&&(t=BigInt(t)),t),bd:St(t,n,!r),dd:null})}function wt(e,t,n,r){xt(e>>>=0,{name:t=O(t>>>0),Wc:function(e){return!!e},cd:function(e,t){return t?n:r},bd:function(e){return this.Wc((S(),w)[e>>>0])},dd:null})}var Tt=[],Et=[0,1,,1,null,1,!0,1,!1,1];function Dt(e){9<(e>>>=0)&&--Et[e+1]===0&&(Et[e]=void 0,Tt.push(e))}var Ot=e=>{if(!e)throw new k(`Cannot use deleted val. handle = ${e}`);return Et[e]},kt=e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let t=Tt.pop()||Et.length;return Et[t]=e,Et[t+1]=1,t}};function At(e){return this.Wc((S(),E)[e>>>2>>>0])}var jt={name:`emscripten::val`,Wc:e=>{var t=Ot(e);return Dt(e),t},cd:(e,t)=>kt(t),bd:At,dd:null};function Mt(e){return xt(e>>>0,jt)}var Nt=(e,t)=>{switch(t){case 4:return function(e){return this.Wc((S(),ie)[e>>>2>>>0])};case 8:return function(e){return this.Wc((S(),ae)[e>>>3>>>0])};default:throw TypeError(`invalid float width (${t}): ${e}`)}};function Pt(e,t,n){n>>>=0,xt(e>>>=0,{name:t=O(t>>>0),Wc:e=>e,cd:(e,t)=>t,bd:Nt(t,n),dd:null})}function Ft(e,t,n,r,i){e>>>=0,n>>>=0,t=O(t>>>0);let a=e=>e;if(r===0){var o=32-8*n;a=e=>e<>>o,i=a(i)}xt(e,{name:t,Wc:a,cd:(e,t)=>t,bd:St(t,n,r!==0),dd:null})}function It(e,t,n){function r(e){var t=(S(),E)[e>>>2>>>0];return e=(S(),E)[e+4>>>2>>>0],new i((S(),C).buffer,e,t)}var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][t];xt(e>>>=0,{name:n=O(n>>>0),Wc:r,bd:r},{ve:!0})}var Lt=(e,t,n)=>{var r=(S(),w);if(t>>>=0,0=o){if(t>=n)break;r[t++>>>0]=o}else if(2047>=o){if(t+1>=n)break;r[t++>>>0]=192|o>>6,r[t++>>>0]=128|63&o}else if(65535>=o){if(t+2>=n)break;r[t++>>>0]=224|o>>12,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o}else{if(t+3>=n)break;r[t++>>>0]=240|o>>18,r[t++>>>0]=128|o>>12&63,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o,a++}}r[t>>>0]=0,e=t-i}else e=0;return e},Rt=e=>{for(var t=0,n=0;n=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t};function zt(e,t){xt(e>>>=0,{name:t=O(t>>>0),Wc(e){var t=(S(),E)[e>>>2>>>0];return t=rt(e+4,t,!0),Ji(e),t},cd(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var n=typeof t==`string`;if(!(n||ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT==1))throw new k(`Cannot pass non-string to std::string`);var r=n?Rt(t):t.length,i=Yi(4+r+1),a=i+4;return(S(),E)[i>>>2>>>0]=r,n?Lt(t,a,r+1):(S(),w).set(t,a>>>0),e!==null&&e.push(Ji,i),i},bd:At,dd(e){Ji(e)}})}var Bt=globalThis.TextDecoder?new TextDecoder(`utf-16le`):void 0,Vt=(e,t,n)=>{if(e>>>=1,16<(t=tt((S(),re),e,t/2,n))-e&&Bt)return Bt.decode((S(),re).slice(e,t));for(n=``;e>>0];n+=String.fromCharCode(r)}return n},Ht=(e,t,n)=>{if(n??=2147483647,2>n)return 0;var r=t;n=(n-=2)<2*e.length?n/2:e.length;for(var i=0;i>>1>>>0]=a,t+=2}return(S(),ne)[t>>>1>>>0]=0,t-r},Ut=e=>2*e.length,Wt=(e,t,n)=>{var r=``;e>>>=2;for(var i=0;!(i>=t/4);i++){var a=(S(),E)[e+i>>>0];if(!a&&!n)break;r+=String.fromCodePoint(a)}return r},Gt=(e,t,n)=>{if(t>>>=0,n??=2147483647,4>n)return 0;var r=t;n=r+n-4;for(var i=0;i>>2>>>0]=a,(t+=4)+4>n)break}return(S(),T)[t>>>2>>>0]=0,t-r},Kt=e=>{for(var t=0,n=0;n>>=0,t>>>=0,n=O(n>>>=0),t===2)var r=Vt,i=Ht,a=Ut;else r=Wt,i=Gt,a=Kt;xt(e,{name:n,Wc:e=>{var n=(S(),E)[e>>>2>>>0];return n=r(e+4,n*t,!0),Ji(e),n},cd:(e,r)=>{if(typeof r!=`string`)throw new k(`Cannot pass non-string to C++ string type ${n}`);var o=a(r),s=Yi(4+o+t);return(S(),E)[s>>>2>>>0]=o/t,i(r,s+4,o+t),e!==null&&e.push(Ji,s),s},bd:At,dd(e){Ji(e)}})}function Jt(e,t){xt(e>>>=0,{we:!0,name:t=O(t>>>0),Wc:()=>{},cd:()=>{}})}function Yt(e){ma(e>>>0,!r,1,!n,131072,!1),Ae()}var Xt=e=>{if(!x)try{if(e(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Qt(e){e>>>=0,Zt||(Atomics.waitAsync((S(),T),e>>>2,e).value.then($t),e+=128,Atomics.store((S(),T),e>>>2,1))}var $t=()=>Xt(()=>{var e=qi();e&&(Qt(e),ba())});function en(e,t){(e>>>=0)==t>>>0?setTimeout($t):i?postMessage({gd:e,$c:`checkMailbox`}):(e=Oe[e])&&e.postMessage({$c:`checkMailbox`})}var tn=[];function nn(e,t,n,r,i){for(t>>>=0,i>>>=0,tn.length=0,n=i>>>3,r=i+r>>>3;n>>0]?(S(),oe)[n++>>>0]:(S(),ae)[n++>>>0];tn.push(a)}return(t?xo[t]:bo[e])(...tn)}var rn=()=>{xe=0};function an(e){e>>>=0,i?postMessage({$c:`cleanupThread`,Le:e}):ke(Oe[e])}function on(e){}var sn=e=>{try{e()}catch(e){fe(e)}};function cn(e){var t=(...t)=>{fn.push(e);try{return e(...t)}finally{x||(fn.pop(),un&&ln===1&&fn.length===0&&(ln=0,xe+=1,sn(go),typeof Fibers<`u`&&Fibers.We()))}};return hn.set(e,t),t}var ln=0,un=null,dn=0,fn=[],pn=/* @__PURE__ */ new Map,mn=/* @__PURE__ */ new Map,hn=/* @__PURE__ */ new Map,gn=0,_n=null,vn=[],yn=e=>(function(e){if(!x){if(ln===0){var t=!1,n=!1;e((e=0)=>{if(!x&&(dn=e,t=!0,n)){ln=2,sn(()=>_o(un)),typeof MainLoop<`u`&&MainLoop.se&&MainLoop.resume(),e=!1;try{var r=(function(){var e=(S(),T)[un+8>>>2>>>0];return e=mn.get(e),e=hn.get(e),--xe,e()})()}catch(t){r=t,e=!0}var i=!1;if(!un){var a=_n;a&&(_n=null,(e?a.reject:a.resolve)(r),i=!0)}if(e&&!i)throw r}}),n=!0,t||(ln=1,un=(function(){var e=Yi(65548),t=e+12;if((S(),E)[e>>>2>>>0]=t,(S(),E)[e+4>>>2>>>0]=t+65536,t=fn[0],!pn.has(t)){var n=gn++;pn.set(t,n),mn.set(n,t)}return t=pn.get(t),(S(),T)[e+8>>>2>>>0]=t,e})(),typeof MainLoop<`u`&&MainLoop.se&&MainLoop.pause(),sn(()=>ho(un)))}else ln===2?(ln=0,sn(vo),Ji(un),un=null,vn.forEach(Xt)):fe(`invalid state: ${ln}`);return dn}})(t=>{e().then(t)});function bn(e){return e>>>=0,yn(async()=>kt(await Ot(e)))}var xn=[],Sn=e=>{var t=xn.length;return xn.push(e),t},Cn=(e,t)=>{for(var n=Array(e),r=0;r>>2>>>0],o=yt[a];if(o===void 0)throw e=`parameter ${r}`,a=Ui(a),t=O(a),Ji(a),new k(`${e} has unknown type ${t}`);n[i]=o}return n},wn=(e,t,n)=>{var r=[];return e=e(r,n),r.length&&((S(),E)[t>>>2>>>0]=kt(r)),e},Tn={},En=e=>{var t=Tn[e];return t===void 0?O(e):t};function Dn(e,t,n){var[r,...i]=Cn(e,t>>>0);t=r.cd.bind(r);var a=i.map(e=>e.bd.bind(e));e--;var o={toValue:Ot};switch(e=a.map((e,t)=>{var n=`argFromPtr${t}`;return o[n]=e,`${n}(args${t?`+`+8*t:``})`}),n){case 0:var s=`toValue(handle)`;break;case 2:s=`new (toValue(handle))`;break;case 3:s=``;break;case 1:o.getStringOrSymbol=En,s=`toValue(handle)[getStringOrSymbol(methodName)]`}return s+=`(${e})`,r.we||(o.toReturnWire=t,o.emval_returnValue=wn,s=`return emval_returnValue(toReturnWire, destructorsRef, ${s})`),s=`return function (handle, methodName, destructorsRef, args) { + ${s} + }`,n=Function(Object.keys(o),s)(...Object.values(o)),s=`methodCaller<(${i.map(e=>e.name)}) => ${r.name}>`,Sn(Object.defineProperty(n,"name",{value:s}))}function On(e,t){return t>>>=0,(e=Ot(e>>>0))==Ot(t)}function kn(e){return(e>>>=0)?(e=En(e),kt(globalThis[e])):kt(globalThis)}function An(e){return e=En(e>>>0),kt(t[e])}function jn(e,t){return t>>>=0,e=Ot(e>>>0),t=Ot(t),kt(e[t])}function Mn(e){9<(e>>>=0)&&(Et[e+1]+=1)}function Nn(e,t,n,r,i){return xn[e>>>0](t>>>0,n>>>0,r>>>0,i>>>0)}function Pn(e,t,n,r,i){return Nn(e>>>0,t>>>0,n>>>0,r>>>0,i>>>0)}function Fn(){return kt([])}function In(e){e=Ot(e>>>0);for(var t=Array(e.length),n=0;n>>0))}function Rn(){return kt({})}function zn(e){for(var t=Ot(e>>>=0);t.length;){var n=t.pop();t.pop()(n)}Dt(e)}function Bn(e,t,n){t>>>=0,n>>>=0,e=Ot(e>>>0),t=Ot(t),n=Ot(n),e[t]=n}function Vn(e,t){e=Le(e),t>>>=0,e=/* @__PURE__ */ new Date(1e3*e),(S(),T)[t>>>2>>>0]=e.getUTCSeconds(),(S(),T)[t+4>>>2>>>0]=e.getUTCMinutes(),(S(),T)[t+8>>>2>>>0]=e.getUTCHours(),(S(),T)[t+12>>>2>>>0]=e.getUTCDate(),(S(),T)[t+16>>>2>>>0]=e.getUTCMonth(),(S(),T)[t+20>>>2>>>0]=e.getUTCFullYear()-1900,(S(),T)[t+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(S(),T)[t+28>>>2>>>0]=e}var Hn=e=>e%4==0&&(e%100!=0||e%400==0),Un=[0,31,60,91,121,152,182,213,244,274,305,335],Wn=[0,31,59,90,120,151,181,212,243,273,304,334];function Gn(e,t){e=Le(e),t>>>=0,e=/* @__PURE__ */ new Date(1e3*e),(S(),T)[t>>>2>>>0]=e.getSeconds(),(S(),T)[t+4>>>2>>>0]=e.getMinutes(),(S(),T)[t+8>>>2>>>0]=e.getHours(),(S(),T)[t+12>>>2>>>0]=e.getDate(),(S(),T)[t+16>>>2>>>0]=e.getMonth(),(S(),T)[t+20>>>2>>>0]=e.getFullYear()-1900,(S(),T)[t+24>>>2>>>0]=e.getDay();var n=(Hn(e.getFullYear())?Un:Wn)[e.getMonth()]+e.getDate()-1|0;(S(),T)[t+28>>>2>>>0]=n,(S(),T)[t+36>>>2>>>0]=-60*e.getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();var r=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=0|(n!=r&&e.getTimezoneOffset()==Math.min(r,n)),(S(),T)[t+32>>>2>>>0]=e}function Kn(e){e>>>=0;var t=new Date((S(),T)[e+20>>>2>>>0]+1900,(S(),T)[e+16>>>2>>>0],(S(),T)[e+12>>>2>>>0],(S(),T)[e+8>>>2>>>0],(S(),T)[e+4>>>2>>>0],(S(),T)[e>>>2>>>0],0),n=(S(),T)[e+32>>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=new Date(t.getFullYear(),0,1).getTimezoneOffset(),o=Math.min(a,i);return 0>n?(S(),T)[e+32>>>2>>>0]=+(i!=a&&o==r):0>>2>>>0]=t.getDay(),n=(Hn(t.getFullYear())?Un:Wn)[t.getMonth()]+t.getDate()-1|0,(S(),T)[e+28>>>2>>>0]=n,(S(),T)[e>>>2>>>0]=t.getSeconds(),(S(),T)[e+4>>>2>>>0]=t.getMinutes(),(S(),T)[e+8>>>2>>>0]=t.getHours(),(S(),T)[e+12>>>2>>>0]=t.getDate(),(S(),T)[e+16>>>2>>>0]=t.getMonth(),(S(),T)[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),BigInt(isNaN(e)?-1:e/1e3)}function qn(e,t,n,r,a,o,s){return i?D(16,1,e,t,n,r,a,o,s):-52}function Jn(e,t,n,r,a,o){if(i)return D(17,1,e,t,n,r,a,o)}var Yn={},Xn=()=>performance.timeOrigin+performance.now();function Zn(e,t){return i?D(18,1,e,t):(Yn[e]&&(clearTimeout(Yn[e].id),delete Yn[e]),t&&(Yn[e]={id:setTimeout(()=>{delete Yn[e],Xt(()=>ya(e,performance.timeOrigin+performance.now()))},t),Ve:t}),0)}function Qn(e,t,n,r){e>>>=0,t>>>=0,n>>>=0,r>>>=0;var i=(/* @__PURE__ */ new Date()).getFullYear(),a=new Date(i,0,1).getTimezoneOffset();i=new Date(i,6,1).getTimezoneOffset();var o=Math.max(a,i);(S(),E)[e>>>2>>>0]=60*o,(S(),T)[t>>>2>>>0]=+(a!=i),e=(t=e=>{var t=Math.abs(e);return`UTC${0<=e?`-`:`+`}${String(Math.floor(t/60)).padStart(2,`0`)}${String(t%60).padStart(2,`0`)}`})(a),t=t(i),iDate.now(),er=1;function tr(e,t,n){if(n>>>=0,!(0<=e&&3>=e))return 28;if(e===0)e=Date.now();else{if(!er)return 52;e=performance.timeOrigin+performance.now()}return e=Math.round(1e6*e),(S(),oe)[n>>>3>>>0]=BigInt(e),0}var nr=[],rr=(e,t)=>{nr.length=0;for(var n;n=(S(),w)[e++>>>0];){var r=n!=105;t+=(r&=n!=112)&&t%8?4:0,nr.push(n==112?(S(),E)[t>>>2>>>0]:n==106?(S(),oe)[t>>>3>>>0]:n==105?(S(),T)[t>>>2>>>0]:(S(),ae)[t>>>3>>>0]),t+=r?8:4}return nr};function ir(e,t,n){return e>>>=0,t=rr(t>>>0,n>>>0),xo[e](...t)}function ar(e,t,n){return e>>>=0,t=rr(t>>>0,n>>>0),xo[e](...t)}var or=()=>{};function sr(e,t){return b(rt(e>>>0,t>>>0))}var cr=()=>{throw xe+=1,`unwind`};function lr(){return 4294901760}var ur=()=>1,dr=()=>navigator.hardwareConcurrency,fr={},pr=e=>{var t=Rt(e)+1,n=Yi(t);return n&&Lt(e,n,t),n},mr=e=>{var t;return(t=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(e))?+t[1]:(t=/:(\d+):\d+(?:\)|$)/.exec(e))?2147483648|t[1]:0},hr=e=>{for(var t of e)(e=mr(t))&&(fr[e]=t)};function gr(){var e=Error().stack.toString().split(` +`);return e[0]==`Error`&&e.shift(),hr(e),fr.ee=mr(e[3]),fr.xe=e,fr.ee}function _r(e){if(!(e=fr[e>>>0]))return 0;var t;if(t=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(e))e=t[1];else if(t=/^\s+at (.*) \(.*\)$/.exec(e))e=t[1];else{if(!(t=/^(.+?)@/.exec(e)))return 0;e=t[1]}return Ji(_r.ne??0),_r.ne=pr(e),_r.ne}function vr(e){e>>>=0;var t=(S(),w).length;if(e<=t||4294901760=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);e:{r=(Math.min(4294901760,65536*Math.ceil(Math.max(e,r)/65536))-Ne.buffer.byteLength+65535)/65536|0;try{Ne.grow(r),ue();var i=1;break e}catch{}i=void 0}if(i)return!0}return!1}function yr(e,t,n){if(e>>>=0,t>>>=0,fr.ee==e)var r=fr.xe;else(r=Error().stack.toString().split(` +`))[0]==`Error`&&r.shift(),hr(r);for(var i=3;r[i]&&mr(r[i])!=e;)++i;for(e=0;e>>2>>>0]=mr(r[e+i]);return e}var br=e=>{var t=Rt(e)+1,n=wa(t);return Lt(e,n,t),n},xr=e=>(S(),E)[e>>>2>>>0]+4294967296*(S(),T)[e+4>>>2>>>0],Sr=[],Cr=(e,t)=>{Sr[e>>>0]=t},wr=[],Tr=[],Er=(e,t)=>{Tr[e]=new Promise(n=>t.finally(()=>n(e)))},A=e=>{if(e)return Sr[e>>>0]},Dr=(e,t)=>{for(e=(S(),E)[e>>>2>>>0];e;e=(S(),E)[e>>>2>>>0])t[(S(),T)[e+4>>>2>>>0]](e)},Or=(e,t,n)=>{(S(),E)[e>>>2>>>0]=t,(S(),E)[e+4>>>2>>>0]=n},kr=e=>{var t=(S(),E)[e>>>2>>>0];return e=(S(),E)[e+4>>>2>>>0],rt(t,e)},Ar=e=>{var t=(S(),E)[e>>>2>>>0];return e=(S(),E)[e+4>>>2>>>0],t?rt(t,e):e===0?``:void 0},jr=e=>{var t=Ar(e+4),n=(n=(S(),E)[e+12>>>2>>>0])?A(n):`auto`;if(e+=16){var r=A((S(),E)[e+4>>>2>>>0]),i=(S(),E)[e+16>>>2>>>0],a=(S(),E)[e+20>>>2>>>0];if(i){for(var o={},s=0;s>>3>>>0]}i=o}else i=void 0;e={module:r,constants:i,entryPoint:Ar(e+8)}}else e=void 0;return{label:t,layout:n,compute:e}},Mr=(e,t)=>{function n(t,n,r,i=0){t=e[t]??i,(S(),E)[n+r>>>2>>>0]=t}function r(t,n,r,i=0){n+=r,t=e[t]??i,(S(),E)[n>>>2>>>0]=t,i=(S(),E)[n>>>2>>>0],(S(),E)[n+4>>>2>>>0]=(t-i)/4294967296}var i=(S(),E)[t>>>2>>>0];n(`maxTextureDimension1D`,t,4),n(`maxTextureDimension2D`,t,8),n(`maxTextureDimension3D`,t,12),n(`maxTextureArrayLayers`,t,16),n(`maxBindGroups`,t,20),n(`maxBindGroupsPlusVertexBuffers`,t,24),n(`maxBindingsPerBindGroup`,t,28),n(`maxDynamicUniformBuffersPerPipelineLayout`,t,32),n(`maxDynamicStorageBuffersPerPipelineLayout`,t,36),n(`maxSampledTexturesPerShaderStage`,t,40),n(`maxSamplersPerShaderStage`,t,44),n(`maxStorageBuffersPerShaderStage`,t,48),n(`maxStorageTexturesPerShaderStage`,t,52),n(`maxUniformBuffersPerShaderStage`,t,56),n(`minUniformBufferOffsetAlignment`,t,80),n(`minStorageBufferOffsetAlignment`,t,84),r(`maxUniformBufferBindingSize`,t,64),r(`maxStorageBufferBindingSize`,t,72),n(`maxVertexBuffers`,t,88),r(`maxBufferSize`,t,96),n(`maxVertexAttributes`,t,104),n(`maxVertexBufferArrayStride`,t,108),n(`maxInterStageShaderVariables`,t,112),n(`maxColorAttachments`,t,116),n(`maxColorAttachmentBytesPerSample`,t,120),n(`maxComputeWorkgroupStorageSize`,t,124),n(`maxComputeInvocationsPerWorkgroup`,t,128),n(`maxComputeWorkgroupSizeX`,t,132),n(`maxComputeWorkgroupSizeY`,t,136),n(`maxComputeWorkgroupSizeZ`,t,140),n(`maxComputeWorkgroupsPerDimension`,t,144),n(`maxImmediateSize`,t,148),i!==0&&(S(),n(`maxStorageBuffersInVertexStage`,i,8,e.maxStorageBuffersPerShaderStage),n(`maxStorageBuffersInFragmentStage`,i,16,e.maxStorageBuffersPerShaderStage),n(`maxStorageTexturesInVertexStage`,i,12,e.maxStorageTexturesPerShaderStage),n(`maxStorageTexturesInFragmentStage`,i,20,e.maxStorageTexturesPerShaderStage))},Nr=(e,t)=>{(S(),E)[t+52>>>2>>>0]=e.subgroupMinSize,(S(),E)[t+56>>>2>>>0]=e.subgroupMaxSize;var n=pr(e.vendor+e.architecture+e.device+e.description),r=Rt(e.vendor);Or(t+4,n,r),n+=r,r=Rt(e.architecture),Or(t+12,n,r),n+=r,r=Rt(e.device),Or(t+20,n,r),n+=r,r=Rt(e.description),Or(t+28,n,r),n+=r,(S(),T)[t+36>>>2>>>0]=2,n=e.isFallbackAdapter?3:4,(S(),T)[t+40>>>2>>>0]=n,(S(),E)[t+44>>>2>>>0]=0,(S(),E)[t+48>>>2>>>0]=0,Dr(t,{327739:t=>{let n=0,r=0;if(e.subgroupMatrixConfigs){n=e.subgroupMatrixConfigs.length,r=Yi(20*n);for(let[t,n]of e.subgroupMatrixConfigs.entries()){let e=r+20*t,i=Hr.indexOf(n.componentType),a=Hr.indexOf(n.resultComponentType);(S(),T)[e>>>2>>>0]=i,(S(),T)[e+4>>>2>>>0]=a,(S(),E)[e+8>>>2>>>0]=n.M,(S(),E)[e+12>>>2>>>0]=n.N,(S(),E)[e+16>>>2>>>0]=n.K}}(S(),E)[t+12>>>2>>>0]=r,(S(),E)[t+8>>>2>>>0]=n}})},Pr=[,,`uniform`,`storage`,`read-only-storage`],Fr=[,`validation`,`out-of-memory`,`internal`],Ir=[,`compatibility`,`core`],Lr={1:`core-features-and-limits`,2:`depth-clip-control`,3:`depth32float-stencil8`,4:`texture-compression-bc`,5:`texture-compression-bc-sliced-3d`,6:`texture-compression-etc2`,7:`texture-compression-astc`,8:`texture-compression-astc-sliced-3d`,9:`timestamp-query`,10:`indirect-first-instance`,11:`shader-f16`,12:`rg11b10ufloat-renderable`,13:`bgra8unorm-storage`,14:`float32-filterable`,15:`float32-blendable`,16:`clip-distances`,17:`dual-source-blending`,18:`subgroups`,19:`texture-formats-tier1`,20:`texture-formats-tier2`,21:`primitive-index`,22:`texture-component-swizzle`,23:`subgroup-size-control`,327692:`chromium-experimental-unorm16-texture-formats`,327729:`chromium-experimental-multi-draw-indirect`,327732:`chromium-experimental-subgroup-matrix`},Rr=[,`low-power`,`high-performance`],zr=[,`occlusion`,`timestamp`],Br=[,,`filtering`,`non-filtering`,`comparison`],Vr=[,,`write-only`,`read-only`,`read-write`],Hr=[,`f32`,`f16`,`u32`,`i32`,`u8`,`i8`],Ur=[,`r8unorm`,`r8snorm`,`r8uint`,`r8sint`,`r16unorm`,`r16snorm`,`r16uint`,`r16sint`,`r16float`,`rg8unorm`,`rg8snorm`,`rg8uint`,`rg8sint`,`r32float`,`r32uint`,`r32sint`,`rg16unorm`,`rg16snorm`,`rg16uint`,`rg16sint`,`rg16float`,`rgba8unorm`,`rgba8unorm-srgb`,`rgba8snorm`,`rgba8uint`,`rgba8sint`,`bgra8unorm`,`bgra8unorm-srgb`,`rgb10a2uint`,`rgb10a2unorm`,`rg11b10ufloat`,`rgb9e5ufloat`,`rg32float`,`rg32uint`,`rg32sint`,`rgba16unorm`,`rgba16snorm`,`rgba16uint`,`rgba16sint`,`rgba16float`,`rgba32float`,`rgba32uint`,`rgba32sint`,`stencil8`,`depth16unorm`,`depth24plus`,`depth24plus-stencil8`,`depth32float`,`depth32float-stencil8`,`bc1-rgba-unorm`,`bc1-rgba-unorm-srgb`,`bc2-rgba-unorm`,`bc2-rgba-unorm-srgb`,`bc3-rgba-unorm`,`bc3-rgba-unorm-srgb`,`bc4-r-unorm`,`bc4-r-snorm`,`bc5-rg-unorm`,`bc5-rg-snorm`,`bc6h-rgb-ufloat`,`bc6h-rgb-float`,`bc7-rgba-unorm`,`bc7-rgba-unorm-srgb`,`etc2-rgb8unorm`,`etc2-rgb8unorm-srgb`,`etc2-rgb8a1unorm`,`etc2-rgb8a1unorm-srgb`,`etc2-rgba8unorm`,`etc2-rgba8unorm-srgb`,`eac-r11unorm`,`eac-r11snorm`,`eac-rg11unorm`,`eac-rg11snorm`,`astc-4x4-unorm`,`astc-4x4-unorm-srgb`,`astc-5x4-unorm`,`astc-5x4-unorm-srgb`,`astc-5x5-unorm`,`astc-5x5-unorm-srgb`,`astc-6x5-unorm`,`astc-6x5-unorm-srgb`,`astc-6x6-unorm`,`astc-6x6-unorm-srgb`,`astc-8x5-unorm`,`astc-8x5-unorm-srgb`,`astc-8x6-unorm`,`astc-8x6-unorm-srgb`,`astc-8x8-unorm`,`astc-8x8-unorm-srgb`,`astc-10x5-unorm`,`astc-10x5-unorm-srgb`,`astc-10x6-unorm`,`astc-10x6-unorm-srgb`,`astc-10x8-unorm`,`astc-10x8-unorm-srgb`,`astc-10x10-unorm`,`astc-10x10-unorm-srgb`,`astc-12x10-unorm`,`astc-12x10-unorm-srgb`,`astc-12x12-unorm`,`astc-12x12-unorm-srgb`],Wr=[,,`float`,`unfilterable-float`,`depth`,`sint`,`uint`],Gr=[,`1d`,`2d`,`2d-array`,`cube`,`cube-array`,`3d`],j={undefined:1,unknown:1,destroyed:2};function Kr(e,t,n,r,i,a){t=Le(t),n=Le(n),r>>>=0,i>>>=0,a>>>=0;var o=A(e>>>0);if(e={},a){var s=(S(),E)[a+12>>>2>>>0];if(s){var c=(S(),E)[a+16>>>2>>>0];e.requiredFeatures=Array.from((S(),E).subarray(c>>>2>>>0,c+4*s>>>2>>>0),e=>Lr[e])}if(s=(S(),E)[a+20>>>2>>>0]){let t=function(e,t,n,r=!1){t+=n,(t=(S(),E)[t>>>2>>>0])==4294967295||r&&t==0||(l[e]=t)},n=function(e,t,n){t+=n,n=(S(),E)[t>>>2>>>0];var r=(S(),E)[t+4>>>2>>>0];n==4294967295&&r==4294967295||(l[e]=xr(t))};c=(S(),E)[s>>>2>>>0];var l={};t(`maxTextureDimension1D`,s,4),t(`maxTextureDimension2D`,s,8),t(`maxTextureDimension3D`,s,12),t(`maxTextureArrayLayers`,s,16),t(`maxBindGroups`,s,20),t(`maxBindGroupsPlusVertexBuffers`,s,24),t(`maxBindingsPerBindGroup`,s,28),t(`maxDynamicUniformBuffersPerPipelineLayout`,s,32),t(`maxDynamicStorageBuffersPerPipelineLayout`,s,36),t(`maxSampledTexturesPerShaderStage`,s,40),t(`maxSamplersPerShaderStage`,s,44),t(`maxStorageBuffersPerShaderStage`,s,48),t(`maxStorageTexturesPerShaderStage`,s,52),t(`maxUniformBuffersPerShaderStage`,s,56),t(`minUniformBufferOffsetAlignment`,s,80),t(`minStorageBufferOffsetAlignment`,s,84),n(`maxUniformBufferBindingSize`,s,64),n(`maxStorageBufferBindingSize`,s,72),t(`maxVertexBuffers`,s,88),n(`maxBufferSize`,s,96),t(`maxVertexAttributes`,s,104),t(`maxVertexBufferArrayStride`,s,108),t(`maxInterStageShaderVariables`,s,112),t(`maxColorAttachments`,s,116),t(`maxColorAttachmentBytesPerSample`,s,120),t(`maxComputeWorkgroupStorageSize`,s,124),t(`maxComputeInvocationsPerWorkgroup`,s,128),t(`maxComputeWorkgroupSizeX`,s,132),t(`maxComputeWorkgroupSizeY`,s,136),t(`maxComputeWorkgroupSizeZ`,s,140),t(`maxComputeWorkgroupsPerDimension`,s,144),t(`maxImmediateSize`,s,148,!0),c!==0&&(S(),`maxStorageBuffersInVertexStage`in GPUSupportedLimits.prototype&&(t(`maxStorageBuffersInVertexStage`,c,8),t(`maxStorageTexturesInVertexStage`,c,12),t(`maxStorageBuffersInFragmentStage`,c,16),t(`maxStorageTexturesInFragmentStage`,c,20))),e.requiredLimits=l}(s=(S(),E)[a+24>>>2>>>0])&&(s={label:Ar(s+4)},e.defaultQueue=s),e.label=Ar(a+4)}xe+=1,Er(t,o.requestDevice(e).then(e=>{--xe,Xt(()=>{Sr[i>>>0]=e.queue,Sr[r>>>0]=e,xe+=1,Er(n,e.lost.then(t=>{Xt(()=>{e.onuncapturederror=()=>{};var r=I(),i=br(t.message);ca(n,j[t.reason],i),F(r)}),--xe})),e.onuncapturederror=e=>{var t=5;e.error instanceof GPUValidationError?t=2:e.error instanceof GPUOutOfMemoryError?t=3:e.error instanceof GPUInternalError&&(t=4);var n=I();e=br(e.error.message),pa(r,t,e),F(n)},`adapterInfo`in e||(e.adapterInfo=o.info),fa(t,1,r,0)})},e=>{--xe,Xt(()=>{var i=I(),a=br(e.message);fa(t,3,r,a),n&&ca(n,4,a),F(i)})}))}function qr(e){var t=A(e>>>=0),n=wr[e];if(n){for(var r=0;r>>=0;var r=A(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=xa(16,i.byteLength);return(S(),w).set(new Uint8Array(i),a>>>0),wr[e].push(()=>Ji(a)),a}function Yr(e,t,n){n>>>=0;var r=A(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=xa(16,i.byteLength);return(S(),w).fill(0,a,i.byteLength),wr[e].push(()=>{new Uint8Array(i).set((S(),w).subarray(a>>>0,a+i.byteLength>>>0)),Ji(a)}),a}function Xr(e,t,n,r,i){e>>>=0,t=Le(t),n=Le(n),i>>>=0;var a=A(e);wr[e]=[],i==4294967295&&(i=void 0),xe+=1,Er(t,a.mapAsync(n,r>>>0,i).then(()=>{--xe,Xt(()=>{la(t,1,0)})},n=>{--xe,Xt(()=>{I();var r=br(n.message);la(t,n.name===`AbortError`?4:n.name===`OperationError`?3:0,r),delete wr[e]})}))}function Zr(e){var t=A(e>>>=0),n=wr[e];if(n){for(var r=0;r>>0]}function $r(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=!!(S(),E)[t+32>>>2>>>0];t={label:Ar(t+4),usage:(S(),E)[t+16>>>2>>>0],size:xr(t+24),mappedAtCreation:r},e=A(e);try{var i=e.createBuffer(t)}catch{return!1}return Sr[n>>>0]=i,r&&(wr[n]=[]),!0}function M(e,t,n,r){e>>>=0,t=Le(t),r>>>=0,n=jr(n>>>0),e=A(e),xe+=1,Er(t,e.createComputePipelineAsync(n).then(e=>{--xe,Xt(()=>{Sr[r>>>0]=e,sa(t,1,r,0)})},e=>{--xe,Xt(()=>{var n=I(),i=br(e.message);sa(t,e.reason===`validation`?3:e.reason===`internal`?4:0,r,i),F(n)})}))}function ei(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=(S(),E)[t>>>2>>>0],i=(S(),T)[r+4>>>2>>>0];t={label:Ar(t+4),code:``},i===2&&(t.code=kr(r+8)),e=A(e).createShaderModule(t),Sr[n>>>0]=e}var ti=e=>{(e=A(e)).onuncapturederror=null,e.destroy()};function ni(e,t){t=Le(t),e=A(e>>>0),xe+=1,Er(t,e.popErrorScope().then(e=>{--xe,Xt(()=>{var n=5;e?e instanceof GPUValidationError?n=2:e instanceof GPUOutOfMemoryError?n=3:e instanceof GPUInternalError&&(n=4):n=1;var r=I(),i=e?br(e.message):0;ua(t,1,n,i),F(r)})},e=>{--xe,Xt(()=>{var n=I(),r=br(e.message);ua(t,1,5,r),F(n)})}))}function ri(e,t,n,r){if(t=Le(t),r>>>=0,n>>>=0){var i={featureLevel:Ir[(S(),T)[n+4>>>2>>>0]],powerPreference:Rr[(S(),T)[n+8>>>2>>>0]],forceFallbackAdapter:!!(S(),E)[n+12>>>2>>>0]};(e=(S(),E)[n>>>2>>>0])!==0&&(S(),i.Ye=!!(S(),E)[e+8>>>2>>>0])}`gpu`in navigator?(xe+=1,Er(t,navigator.gpu.requestAdapter(i).then(e=>{--xe,Xt(()=>{if(e)Sr[r>>>0]=e,da(t,1,r,0);else{var n=I(),i=br(`WebGPU not available on this browser (requestAdapter returned null)`);da(t,3,r,i),F(n)}})},e=>{--xe,Xt(()=>{var n=I(),i=br(e.message);da(t,4,r,i),F(n)})}))):(i=I(),e=br(`WebGPU not available on this browser (navigator.gpu is not available)`),da(t,3,r,e),F(i))}function ii(e,t,n){return e>>>=0,t>>>=0,n>>>=0,yn(async()=>{var r=[];if(n){var i=(S(),T)[n>>>2>>>0];r.length=t+1,r[t]=new Promise(e=>setTimeout(e,i,0))}else r.length=t;for(var a=0;a{if(!ai){var e,t={USER:`web_user`,LOGNAME:`web_user`,PATH:`/`,PWD:`/`,HOME:`/home/web_user`,LANG:(globalThis.navigator?.language??`C`).replace(`-`,`_`)+`.UTF-8`,_:`./this.program`};for(e in oi)oi[e]===void 0?delete t[e]:t[e]=oi[e];var n=[];for(e in t)n.push(`${e}=${t[e]}`);ai=n}return ai};function ci(e,t){if(i)return D(19,1,e,t);e>>>=0,t>>>=0;var n,r=0,a=0;for(n of si()){var o=t+r;(S(),E)[e+a>>>2>>>0]=o,r+=Lt(n,o,1/0)+1,a+=4}return 0}function li(e,t){if(i)return D(20,1,e,t);e>>>=0,t>>>=0;var n=si();for(var r of((S(),E)[e>>>2>>>0]=n.length,e=0,n))e+=Rt(r)+1;return(S(),E)[t>>>2>>>0]=e,0}function ui(e){return i?D(21,1,e):52}function di(e,t,n,r,a){return i?D(22,1,e,t,n,r,a):52}function N(e,t,n,r){return i?D(23,1,e,t,n,r):52}function fi(e,t,n,r){return i?D(24,1,e,t,n,r):70}var pi=[null,[],[]];function mi(e,t,n,r){if(i)return D(25,1,e,t,n,r);t>>>=0,n>>>=0,r>>>=0;for(var a=0,o=0;o>>2>>>0],c=(S(),E)[t+4>>>2>>>0];t+=8;for(var l=0;l>>0],f=pi[u];d===0||d===10?((u===1?y:b)(nt(f)),f.length=0):f.push(d)}a+=c}return(S(),E)[r>>>2>>>0]=a,0}function hi(e){return e>>>0}function gi(e,t){return Mr(A(e>>>0).limits,t>>>0),1}function _i(e,t){return A(e>>>0).features.has(Lr[t])}function vi(e){return BigInt(A(e>>>0).size)}function yi(e){return BigInt(A(e>>>0).usage)}function bi(e,t){if(e>>>=0,t>>>=0){var n=Ar(t+4);n={label:n,timestampWrites:t=(t=(S(),E)[t+12>>>2>>>0])===0?void 0:{querySet:A((S(),E)[t+4>>>2>>>0]),beginningOfPassWriteIndex:(S(),E)[t+8>>>2>>>0],endOfPassWriteIndex:(S(),E)[t+12>>>2>>>0]}}}return t=A(e),e=ta(0),n=t.beginComputePass(n),Sr[e>>>0]=n,e}function xi(e,t,n,r){n=Le(n),(r=Le(r))==-1&&(r=void 0),(e=A(e>>>0)).clearBuffer(A(t>>>0),n,r)}function Si(e,t,n,r,i,a){n=Le(n),i=Le(i),a=Le(a),A(e>>>0).copyBufferToBuffer(A(t>>>0),n,A(r>>>0),i,a)}function Ci(e){var t=A(e>>>0);return e=$i(0),t=t.finish(),Sr[e>>>0]=t,e}function wi(e,t,n,r,i,a){a=Le(a),A(e>>>0).resolveQuerySet(A(t>>>0),n,r,A(i>>>0),a)}function Ti(e,t,n,r){A(e>>>0).dispatchWorkgroups(t,n,r)}function Ei(e,t,n){n=Le(n),A(e>>>0).dispatchWorkgroupsIndirect(A(t>>>0),n)}function Di(e){A(e>>>0).end()}function Oi(e,t,n,r,i){r>>>=0,i>>>=0,e=A(e>>>0),n=A(n>>>0),r==0?e.setBindGroup(t,n):e.setBindGroup(t,n,(S(),E),i>>>2,r)}function ki(e,t){A(e>>>0).setPipeline(A(t>>>0))}function Ai(e,t,n){A(e>>>0).Xe(A(t>>>0),n)}function ji(e,t){function n(e){var t=(S(),E)[e+8>>>2>>>0],n=(S(),E)[e+32>>>2>>>0],r=(S(),E)[e+36>>>2>>>0],i=0;return Dr(e,{14:e=>{i=(S(),E)[e+8>>>2>>>0]}}),t?((n=xr(e+24))==-1&&(n=void 0),t={buffer:A(t),offset:xr(e+16),size:n}):t=A(n||r||i),{binding:(S(),E)[e+4>>>2>>>0],resource:t}}e>>>=0,t={label:Ar((t>>>=0)+4),layout:A((S(),E)[t+12>>>2>>>0]),entries:(function(e,t){for(var r=[],i=0;i>>2>>>0],(S(),E)[t+20>>>2>>>0])},e=A(e);var r=Zi(0);return Cr(r,e.createBindGroup(t)),r}function Mi(e,t){function n(e){var t=(S(),E)[e+4>>>2>>>0];if(t)return{type:Pr[t],hasDynamicOffset:!!(S(),E)[e+8>>>2>>>0],minBindingSize:xr(e+16)}}function r(e){if(e=(S(),E)[e+4>>>2>>>0])return{type:Br[e]}}function i(e){var t=(S(),E)[e+4>>>2>>>0];if(t)return{sampleType:Wr[t],viewDimension:Gr[(S(),T)[e+8>>>2>>>0]],multisampled:!!(S(),E)[e+12>>>2>>>0]}}function a(e){var t=(S(),E)[e+4>>>2>>>0];if(t)return{access:Vr[t],format:Ur[(S(),T)[e+8>>>2>>>0]],viewDimension:Gr[(S(),T)[e+12>>>2>>>0]]}}function o(e){var t={binding:(S(),E)[e+4>>>2>>>0],visibility:(S(),E)[e+8>>>2>>>0],buffer:n(e+24),sampler:r(e+48),texture:i(e+56),storageTexture:a(e+72)};return Dr(e,{13:()=>{t.externalTexture={}}}),t}e>>>=0,t={label:Ar((t>>>=0)+4),entries:(function(e,t){for(var n=[],r=0;r>>2>>>0],(S(),E)[t+16>>>2>>>0])},e=A(e);var s=Qi(0);return Cr(s,e.createBindGroupLayout(t)),s}function Ni(e,t){var n;return e>>>=0,(t>>>=0)&&(n={label:Ar(t+4)}),t=A(e),e=ea(0),n=t.createCommandEncoder(n),Sr[e>>>0]=n,e}function Pi(e,t){e>>>=0,t>>>=0;for(var n=(S(),E)[t+12>>>2>>>0],r=(S(),E)[t+16>>>2>>>0],i=[],a=0;a>>2>>>0]));return t={label:Ar(t+4),bindGroupLayouts:i,immediateSize:(S(),E)[t+20>>>2>>>0]},n=A(e),e=na(0),t=n.createPipelineLayout(t),Sr[e>>>0]=t,e}function Fi(e,t){e>>>=0,t>>>=0,t={type:zr[(S(),T)[t+12>>>2>>>0]],count:(S(),E)[t+16>>>2>>>0]};var n=A(e);return e=ra(0),t=n.createQuerySet(t),Sr[e>>>0]=t,e}function Ii(e,t){return Nr(A(e>>>0).adapterInfo,t>>>0),1}var Li={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"subgroup-size-control":23,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729,"chromium-experimental-subgroup-matrix":327732};function Ri(e,t){t>>>=0;var n=A(e>>>0);e=Yi(4*n.features.size);var r=0,i=0;for(let t of n.features)0<=(n=Li[t])&&((S(),T)[e+r>>>2>>>0]=n,r+=4,i++);(S(),E)[t+4>>>2>>>0]=e,(S(),E)[t>>>2>>>0]=i}function zi(e,t){return Mr(A(e>>>0).limits,t>>>0),1}function Bi(e,t){A(e>>>0).pushErrorScope(Fr[t])}function Vi(e,t,n){t>>>=0,n>>>=0,e=A(e>>>0),t=Array.from((S(),T).subarray(n>>>2>>>0,n+4*t>>>2>>>0),e=>A(e)),e.submit(t)}function Hi(e,t,n,r,i){n=Le(n),r>>>=0,i>>>=0,e=A(e>>>0),t=A(t>>>0),r=(S(),w).subarray(r>>>0,r+i>>>0),e.writeBuffer(t,n,r,0,i)}i||(function(){for(var e=t.numThreads-1;e--;)Me();_e.push(async()=>{var e=(async function(){if(!i)return Promise.all(Te.map(je))})();ve++,await e,--ve==0&&ye&&(e=ye,ye=null,e())})})(),i||(Ne=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),ue()),t.wasmBinary&&(d=t.wasmBinary),t.stackSave=()=>I(),t.stackRestore=e=>F(e),t.stackAlloc=e=>wa(e),t.setValue=function(e,t,n=`i8`){switch(n.endsWith(`*`)&&(n=`*`),n){case`i1`:case`i8`:(S(),C)[e>>>0]=t;break;case`i16`:(S(),ne)[e>>>1>>>0]=t;break;case`i32`:(S(),T)[e>>>2>>>0]=t;break;case`i64`:(S(),oe)[e>>>3>>>0]=BigInt(t);break;case`float`:(S(),ie)[e>>>2>>>0]=t;break;case`double`:(S(),ae)[e>>>3>>>0]=t;break;case`*`:(S(),E)[e>>>2>>>0]=t;break;default:fe(`invalid type for setValue: ${n}`)}},t.getValue=function(e,t=`i8`){switch(t.endsWith(`*`)&&(t=`*`),t){case`i1`:case`i8`:return(S(),C)[e>>>0];case`i16`:return(S(),ne)[e>>>1>>>0];case`i32`:return(S(),T)[e>>>2>>>0];case`i64`:return(S(),oe)[e>>>3>>>0];case`float`:return(S(),ie)[e>>>2>>>0];case`double`:return(S(),ae)[e>>>3>>>0];case`*`:return(S(),E)[e>>>2>>>0];default:fe(`invalid type for getValue: ${t}`)}},t.UTF8ToString=rt,t.stringToUTF8=Lt,t.lengthBytesUTF8=Rt;var Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra,ia,aa,oa,sa,ca,la,ua,da,fa,pa,ma,ha,ga,_a,va,ya,ba,xa,P,Sa,Ca,F,wa,I,Ta,Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra,za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa,Ja,Ya,Xa,Za,Qa,$a,eo,to,no,ro,io,ao,oo,so,co,lo,uo,fo,po,mo,ho,go,_o,vo,yo,bo=[Se,Ce,Ze,it,at,ot,st,ct,lt,ut,dt,ft,pt,mt,ht,gt,qn,Jn,Zn,ci,li,ui,di,N,fi,mi],xo={1280444:(e,n,r,i,a)=>{if(t===void 0||!t.ed)return 1;if((e=rt(Number(e>>>0))).startsWith(`./`)&&(e=e.substring(2)),!(e=t.ed.get(e)))return 2;if(n=Number(n>>>0),r=Number(r>>>0),i=Number(i>>>0),n+r>e.byteLength)return 3;try{let o=e.subarray(n,n+r);switch(a){case 0:(S(),w).set(o,i>>>0);break;case 1:t.pe?t.pe(i,o):t.Re(i,o);break;default:return 4}return 0}catch{return 4}},1281268:(e,n,r)=>{t.re(e,(S(),w).subarray(n>>>0,n+r>>>0))},1281332:()=>t.Pe(),1281374:e=>{t.qe(e)},1281411:()=>typeof wasmOffsetConverter<`u`};function So(){return typeof wasmOffsetConverter<`u`}function Co(e,t,n,r){var i=I();try{return Ra(e,t,n,r)}catch(e){if(F(i),e!==e+0)throw e;P(1,0)}}function wo(e,t,n){var r=I();try{return Fa(e,t,n)}catch(e){if(F(r),e!==e+0)throw e;P(1,0)}}function To(e){var t=I();try{ja(e)}catch(e){if(F(t),e!==e+0)throw e;P(1,0)}}function Eo(e,t){var n=I();try{return Aa(e,t)}catch(e){if(F(n),e!==e+0)throw e;P(1,0)}}function Do(e,t,n){var r=I();try{ka(e,t,n)}catch(e){if(F(r),e!==e+0)throw e;P(1,0)}}function Oo(e,t){var n=I();try{za(e,t)}catch(e){if(F(n),e!==e+0)throw e;P(1,0)}}function ko(e,t,n,r,i,a,o){var s=I();try{return Pa(e,t,n,r,i,a,o)}catch(e){if(F(s),e!==e+0)throw e;P(1,0)}}function L(e,t,n,r,i,a){var o=I();try{Ma(e,t,n,r,i,a)}catch(e){if(F(o),e!==e+0)throw e;P(1,0)}}function Ao(e,t,n,r){var i=I();try{La(e,t,n,r)}catch(e){if(F(i),e!==e+0)throw e;P(1,0)}}function jo(e,t,n,r,i,a,o){var s=I();try{Va(e,t,n,r,i,a,o)}catch(e){if(F(s),e!==e+0)throw e;P(1,0)}}function Mo(e,t,n,r,i,a,o){var s=I();try{Ha(e,t,n,r,i,a,o)}catch(e){if(F(s),e!==e+0)throw e;P(1,0)}}function No(e,t,n,r,i,a,o,s){var c=I();try{Qa(e,t,n,r,i,a,o,s)}catch(e){if(F(c),e!==e+0)throw e;P(1,0)}}function Po(e,t,n,r,i,a,o,s,c,l,u,d){var f=I();try{Ua(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(F(f),e!==e+0)throw e;P(1,0)}}function Fo(e,t,n,r,i){var a=I();try{return Ba(e,t,n,r,i)}catch(e){if(F(a),e!==e+0)throw e;P(1,0)}}function Io(e,t,n,r,i,a){var o=I();try{$a(e,t,n,r,i,a)}catch(e){if(F(o),e!==e+0)throw e;P(1,0)}}function Lo(e,t,n,r,i){var a=I();try{Na(e,t,n,r,i)}catch(e){if(F(a),e!==e+0)throw e;P(1,0)}}function Ro(e,t,n,r,i,a,o,s){var c=I();try{Ia(e,t,n,r,i,a,o,s)}catch(e){if(F(c),e!==e+0)throw e;P(1,0)}}function zo(e){var t=I();try{return eo(e)}catch(e){if(F(t),e!==e+0)throw e;P(1,0)}}function Bo(e,t,n,r,i,a,o,s,c){var l=I();try{Ga(e,t,n,r,i,a,o,s,c)}catch(e){if(F(l),e!==e+0)throw e;P(1,0)}}function Vo(e,t,n){var r=I();try{return to(e,t,n)}catch(e){if(F(r),e!==e+0)throw e;P(1,0)}}function Ho(e,t){var n=I();try{return mo(e,t)}catch(e){if(F(n),e!==e+0)throw e;return P(1,0),0n}}function Uo(e,t,n,r){var i=I();try{return no(e,t,n,r)}catch(e){if(F(i),e!==e+0)throw e;P(1,0)}}function Wo(e){var t=I();try{return Wa(e)}catch(e){if(F(t),e!==e+0)throw e;return P(1,0),0n}}function Go(e,t,n,r){var i=I();try{return ro(e,t,n,r)}catch(e){if(F(i),e!==e+0)throw e;P(1,0)}}function Ko(e,t,n,r,i){var a=I();try{return io(e,t,n,r,i)}catch(e){if(F(a),e!==e+0)throw e;P(1,0)}}function qo(e,t,n,r,i,a){var o=I();try{return ao(e,t,n,r,i,a)}catch(e){if(F(o),e!==e+0)throw e;P(1,0)}}function Jo(e,t,n,r,i,a){var o=I();try{return Xa(e,t,n,r,i,a)}catch(e){if(F(o),e!==e+0)throw e;P(1,0)}}function Yo(e,t,n,r,i,a){var o=I();try{return oo(e,t,n,r,i,a)}catch(e){if(F(o),e!==e+0)throw e;P(1,0)}}function Xo(e,t,n,r,i,a,o,s){var c=I();try{return Za(e,t,n,r,i,a,o,s)}catch(e){if(F(c),e!==e+0)throw e;P(1,0)}}function Zo(e,t,n,r,i){var a=I();try{return so(e,t,n,r,i)}catch(e){if(F(a),e!==e+0)throw e;return P(1,0),0n}}function Qo(e,t,n,r){var i=I();try{return co(e,t,n,r)}catch(e){if(F(i),e!==e+0)throw e;P(1,0)}}function $o(e,t,n,r){var i=I();try{return lo(e,t,n,r)}catch(e){if(F(i),e!==e+0)throw e;P(1,0)}}function es(e,t,n,r,i,a,o,s,c,l,u,d){var f=I();try{return uo(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(F(f),e!==e+0)throw e;P(1,0)}}function ts(e,t,n,r,i,a,o,s,c,l,u){var d=I();try{fo(e,t,n,r,i,a,o,s,c,l,u)}catch(e){if(F(d),e!==e+0)throw e;P(1,0)}}function ns(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){var g=I();try{po(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}catch(e){if(F(g),e!==e+0)throw e;P(1,0)}}function rs(e,t,n){var r=I();try{return qa(e,t,n)}catch(e){if(F(r),e!==e+0)throw e;return P(1,0),0n}}function is(e,t,n){var r=I();try{return Ka(e,t,n)}catch(e){if(F(r),e!==e+0)throw e;P(1,0)}}function as(e,t,n){var r=I();try{return Ja(e,t,n)}catch(e){if(F(r),e!==e+0)throw e;P(1,0)}}function os(e,t,n,r){var i=I();try{Ya(e,t,n,r)}catch(e){if(F(i),e!==e+0)throw e;P(1,0)}}function ss(){if(0{let n=/* @__PURE__ */ new WeakMap,r,i,a=1;t.webgpuRegisterDevice=e=>{if(i!==void 0)throw Error(`another WebGPU EP inference session is being created.`);if(e){var t=n.get(e);if(!t){let r=((e,t=0)=>{var n=oa(t);return t=aa(t,n),Sr[n>>>0]=e.queue,Sr[t>>>0]=e,t})(e,t=Gi());t=[a++,t,r],n.set(e,t)}return r=e,i=t[0],t}r=void 0,i=0};let o=/* @__PURE__ */ new Map;t.webgpuOnCreateSession=t=>{if(i!==void 0){var n=i;if(i=void 0,t){let i=Ki(n);o.set(t,i),n===0&&e(r??A(i))}r=void 0}},t.webgpuOnReleaseSession=e=>{o.delete(e)};let s=Symbol(`gpuBufferMetadata`);t.webgpuRegisterBuffer=(e,t,n)=>{if(n)return e[s]=[n,NaN],n;if(n=e[s])return n[1]++,n[0];if((t=o.get(t))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);return t=((e,t=0)=>(e.mapState===`unmapped`||fe(),t=ia(t),Sr[t>>>0]=e,t))(e,t),e[s]=[t,1],t},t.webgpuUnregisterBuffer=e=>{let t=e[s];if(!t)throw Error(`Buffer is not registered`);t[1]--,t[1]===0&&(Xi(t[0]),delete e[s])},t.webgpuGetBuffer=e=>A(e),t.webgpuCreateDownloader=(e,t,n)=>{if((n=o.get(n))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);let r=A(n),i=16*Math.ceil(Number(t)/16);return async()=>{let n=r.createBuffer({size:i,usage:9});try{let a=r.createCommandEncoder();return a.copyBufferToBuffer(e,0,n,0,i),r.queue.submit([a.finish()]),await n.mapAsync(GPUMapMode.READ),n.getMappedRange().slice(0,t)}finally{n.destroy()}}},t.pe=(e,t)=>{var n=t.buffer;let a=t.byteOffset,o=t.byteLength;if(t=16*Math.ceil(Number(o)/16),e=A(e),!r){var s=Ki(i);r=A(s)}let c=(s=r.createBuffer({mappedAtCreation:!0,size:t,usage:6})).getMappedRange();new Uint8Array(c).set(new Uint8Array(n,a,o)),s.unmap(),(n=r.createCommandEncoder()).copyBufferToBuffer(s,0,e,0,t),r.queue.submit([n.finish()]),s.destroy()}},t.webnnInit=e=>{let n=e[0];[t.Pe,t.qe,t.webnnEnsureTensor,t.re,t.webnnDownloadTensor,t.Oe,t.webnnEnableTraceEvent]=e.slice(1),t.webnnReleaseTensorId=t.qe,t.webnnUploadTensor=t.re,t.webnnRegisterMLContext=t.Oe,t.webnnOnRunStart=e=>n.onRunStart(e),t.webnnOnRunEnd=n.onRunEnd.bind(n),t.webnnOnReleaseSession=e=>{n.onReleaseSession(e)},t.webnnCreateMLTensorDownloader=(e,t)=>n.createMLTensorDownloader(e,t),t.webnnRegisterMLTensor=(e,t,r,i)=>n.registerMLTensor(e,t,r,i),t.webnnCreateMLContext=e=>n.createMLContext(e),t.webnnRegisterGraphInput=n.registerGraphInput.bind(n),t.webnnIsGraphInput=n.isGraphInput.bind(n),t.webnnRegisterGraphOutput=n.registerGraphOutput.bind(n),t.webnnIsGraphOutput=n.isGraphOutput.bind(n),t.webnnCreateTemporaryTensor=n.createTemporaryTensor.bind(n),t.webnnIsGraphInputOutputTypeSupported=n.isGraphInputOutputTypeSupported.bind(n)},le?t:new Promise((e,t)=>{m=e,h=t})}var Ke,qe,Je=l(()=>{Ke=Ge,qe=globalThis.self?.name?.startsWith(`em-pthread`),qe&&Ge()}),Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,at,ot,st,ct,lt=l(()=>{Re(),Ye=typeof location>`u`?void 0:location.origin,Xe=import.meta.url>`file:`&&import.meta.url<`file;`,Ze=()=>Xe?new URL(new URL(`ort.webgpu.bundle.min.mjs`,import.meta.url).href,Ye).href:import.meta.url,Qe=Ze(),$e=()=>{if(Qe&&!Qe.startsWith(`blob:`))return Qe.substring(0,Qe.lastIndexOf(`/`)+1)},et=(e,t)=>{try{let n=t??Qe;return(n?new URL(e,n):new URL(e)).origin===Ye}catch{return!1}},tt=(e,t)=>{let n=t??Qe;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},nt=(e,t)=>`${t??`./`}${e}`,rt=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},it=async e=>(await import( +/*webpackIgnore:true*/ +/*@vite-ignore*/ +e)).default,at=(Ue(),f(ze)).default,ot=async()=>{if(!Qe)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(et(Qe))return[void 0,at()];let e=await rt(Qe);return[e,at(e)]},st=(Je(),f(We)).default,ct=async(e,t,n,r)=>{let i=st&&!(e||t);if(i){if(Qe)i=et(Qe)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`)}if(i)return[void 0,st];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??tt(r,t),a=n&&i&&!et(i,t),o=a?await rt(i):i??nt(r,t);return[a?o:void 0,await it(o)]}}}),ut,dt,ft,pt,mt,ht,gt,_t,O,vt=l(()=>{lt(),dt=!1,ft=!1,pt=!1,mt=()=>{if(typeof SharedArrayBuffer>`u`)return!1;try{return typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},ht=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},gt=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},_t=async e=>{if(dt)return Promise.resolve();if(ft)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(pt)throw Error(`previous call to 'initializeWebAssembly()' failed.`);ft=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!gt())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!ht())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=mt();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await ct(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=$e();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{ft=!1,dt=!0,ut=t,e(),d&&URL.revokeObjectURL(d)},e=>{ft=!1,pt=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},O=()=>{if(dt&&ut)return ut;throw Error(`WebAssembly is not initialized yet.`)}}),yt,bt,k,xt=l(()=>{vt(),yt=(e,t)=>{let n=O(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},bt=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)bt(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},k=e=>{let t=O(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),St,Ct=l(()=>{vt(),xt(),St=e=>{let t=O(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=yt(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&k(`Can't create run options.`),e?.extra!==void 0&&bt(e.extra,``,/* @__PURE__ */ new WeakSet,(e,i)=>{let a=yt(e,r),o=yt(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&k(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),wt,Tt,Et,Dt,Ot,kt,At,jt=l(()=>{vt(),xt(),wt=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},Tt=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},Et=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},Dt=(e,t,n,r)=>{let i=yt(t,r),a=yt(n,r);O()._OrtAddSessionConfigEntry(e,i,a)!==0&&k(`Can't set a session config entry: ${t} - ${n}.`)},Ot=(e,t,n,r)=>{let i=yt(t,r),a=yt(n,r);e.push([i,a])},kt=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[];switch(r){case`webnn`:if(r=`WEBNN`,Dt(e,`session.disable_quant_qdq`,`1`,n),Dt(e,`session.disable_qdq_constant_folding`,`1`,n),typeof i!=`string`){let t=i?.deviceType;t&&Dt(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e;if(typeof i!=`string`){let r=i;if(r.device){if(typeof GPUDevice<`u`&&r.device instanceof GPUDevice)e=r.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`)}let{enableGraphCapture:o}=t;if(typeof o==`boolean`&&o&&Ot(a,`enableGraphCapture`,`1`,n),typeof r.preferredLayout==`string`&&Ot(a,`preferredLayout`,r.preferredLayout,n),r.forceCpuNodeNames){let e=Array.isArray(r.forceCpuNodeNames)?r.forceCpuNodeNames:[r.forceCpuNodeNames];Ot(a,`forceCpuNodeNames`,e.join(` +`),n)}r.validationMode&&Ot(a,`validationMode`,r.validationMode,n),typeof r.enableMatmulFp32Accumulation==`boolean`&&Ot(a,`enableMatmulFp32Accumulation`,r.enableMatmulFp32Accumulation?`1`:`0`,n);for(let e of[`storageBufferCacheMode`,`uniformBufferCacheMode`,`queryResolveBufferCacheMode`,`defaultBufferCacheMode`]){let t=r[e];if(t){if(t!==`disabled`&&t!==`lazyRelease`&&t!==`simple`&&t!==`bucket`)throw Error(`${e} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${t}`);Ot(a,e,t,n)}}}let o=O().webgpuRegisterDevice(e);if(o){let[e,t,r]=o;Ot(a,`deviceId`,e.toString(),n),Ot(a,`webgpuInstance`,t.toString(),n),Ot(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let o=yt(r,n),s=a.length,c=0,l=0;if(s>0){c=O()._malloc(s*O().PTR_SIZE),n.push(c),l=O()._malloc(s*O().PTR_SIZE),n.push(l);for(let e=0;e{let t=O(),n=0,r=[],i=e||{};Et(i);try{let e=wt(i.graphOptimizationLevel??`all`),a=Tt(i.executionMode??`sequential`),o=typeof i.logId==`string`?yt(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?yt(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&k(`Can't create session options.`),i.executionProviders&&await kt(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);Dt(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=yt(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&k(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&bt(i.extra,``,/* @__PURE__ */ new WeakSet,(e,t)=>{Dt(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&k(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),Mt,Nt,Pt,Ft,It,Lt,Rt,zt,Bt=l(()=>{Mt=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},Nt=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},Pt=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},Ft=e=>{switch(e){case`float16`:return typeof Float16Array<`u`?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},It=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},Lt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Rt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,zt=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Vt,Ht=l(()=>{Re(),Vt=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Ut,Wt=l(()=>{Bt(),Ut=(e,t)=>new(Ft(t))(e)}),Gt,Kt,qt,Jt,Yt,Xt,Zt,Qt=l(()=>{Bt(),Gt=[`V`,`I`,`W`,`E`,`F`],Kt=(e,t)=>{console.log(`[${Gt[e]},${(/* @__PURE__ */ new Date()).toISOString()}]${t}`)},Yt=(e,t)=>{qt=e,Jt=t},Xt=(e,t)=>{let n=It(e);n>=It(qt)&&Kt(n,typeof t==`function`?t():t)},Zt=(...e)=>{Jt&&Xt(...e)}}),$t,en,tn,nn,rn,an,on,sn,cn,ln,un,dn=l(()=>{Bt(),Qt(),$t=/* @__PURE__ */ new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),en=(e,t)=>{if(t===`int32`)return e;let n=$t.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(Ft(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>2147483647))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},tn=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},nn=1,rn=()=>nn++,an=/* @__PURE__ */ new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),on=(e,t)=>{let n=$t.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},sn=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return on(this.dataType,this.tensorShape)}destroy(){Zt(`verbose`,()=>`[WebNN] TensorWrapper.destroy`),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=tn(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}return new Uint8Array(n).buffer}return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},cn=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=an.get(t),!o||!a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);Zt(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==on(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType){if(this.wrapper.fallbackType===`int32`)t=en(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`)}if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}Zt(`verbose`,()=>`Data size does not match tensor size. Releasing tensor.`),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?tn(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},ln=class{constructor(e){this.backend=e,this.tensorTrackersById=/* @__PURE__ */ new Map,this.freeTensors=[],this.externalTensors=/* @__PURE__ */ new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=rn();return this.tensorTrackersById.set(e,new cn(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r,i){Zt(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){Zt(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,r){let i=this.getMLContext(e),a=rn(),o=new sn({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new cn(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){Zt(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}Zt(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new sn({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},un=(...e)=>new ln(...e)}),fn={};u(fn,{WebNNBackend:()=>hn});var pn,mn,hn,gn=l(()=>{Bt(),vt(),Wt(),dn(),Qt(),pn=/* @__PURE__ */ new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),mn=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},hn=class{constructor(e){this.tensorManager=un(this),this.mlContextBySessionId=/* @__PURE__ */ new Map,this.sessionIdsByMLContext=/* @__PURE__ */ new Map,this.mlContextCache=[],this.sessionGraphInputs=/* @__PURE__ */ new Map,this.sessionGraphOutputs=/* @__PURE__ */ new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=/* @__PURE__ */ new Map,this.mlOpSupportLimitsBySessionId=/* @__PURE__ */ new Map,Yt(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){Zt(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Zt(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)Zt(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>mn(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=/* @__PURE__ */ new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Zt(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=pn.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){Zt(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=pn.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!O().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);Zt(`verbose`,()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return Ut(n,t)}}registerMLTensor(e,t,n,r){let i=pn.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return Zt(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=pn.get(Mt(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),_n,vn,yn,bn,xn,Sn,Cn,wn,Tn,En,Dn,On,kn,An=l(()=>{Le(),Ct(),jt(),Bt(),vt(),xt(),Ht(),_n=(e,t)=>{O()._OrtInit(e,t)!==0&&k(`Can't initialize onnxruntime.`)},vn=async e=>{_n(e.wasm.numThreads,It(e.logLevel))},yn=async(e,t)=>{O().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&O().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new(gn(),f(fn)).WebNNBackend(e);O().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},bn=/* @__PURE__ */ new Map,xn=e=>{let t=O(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&k(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},Sn=(e,t)=>{let n=O(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&k(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e{let t=O(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},wn=async(e,t)=>{let n,r,i=O();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=Cn(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await At(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path,r=typeof n==`string`?n:n.data;e.push(Vt(r).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;i.currentContext=n||(r?await i.webnnCreateMLContext(r):await i.webnnCreateMLContext({deviceType:a,powerPreference:o}))}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&k(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=xn(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;te===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&k(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>zt(e))}),bn.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&k(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&k(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&k(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},Tn=e=>{let t=O(),n=bn.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&k(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&k(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&k(`Can't release session.`),bn.delete(e)},En=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=O(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=Pt(Mt(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=Pt(Mt(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,Mt(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;es.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(Mt(l),p,m,g,u.length,zt(f));e===0&&k(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},Dn=async(e,t,n,r,i,a)=>{let o=O(),s=o.PTR_SIZE,c=bn.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],ee=[],S=o.stackSave(),te=o.stackAlloc(h*s),C=o.stackAlloc(h*s),w=o.stackAlloc(g*s),ne=o.stackAlloc(g*s);try{[_,v]=St(a),Te(`wasm prepareInputOutputTensor`);for(let r=0;re*t,1);u=Nt(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t0){let t=o.webgpuGetBuffer;if(!t)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let r=t(d),i=Pt(a,g);if(i===void 0||!Lt(u))throw Error(`Unsupported data type: ${u}`);l=!0;{o.webgpuRegisterBuffer(r,e,d);let t=o.webgpuCreateDownloader(r,i,e);S.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(Ft(u))(e)},dispose:()=>{o._OrtReleaseTensor(n)!==0&&k(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(Pt(a,g)===void 0||!Rt(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,S.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=S.length;l=!0,re.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),S.push([u,h,[],`cpu`])}else{let e=new(Ft(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),S.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&k(`Can't clear bound outputs.`),bn.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(re))S[e][2]=t;return Ee(`wasm ProcessOutputTensor`),S}finally{o.webnnOnRunEnd?.(l),o.stackRestore(S),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},On=e=>{let t=O(),n=bn.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&k(`Can't get an profile file name.`),t._OrtFree(i)},kn=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn=l(()=>{Le(),An(),vt(),lt(),jn=()=>!!C.wasm.proxy&&typeof document<`u`,Nn=!1,Pn=!1,Fn=!1,Rn=/* @__PURE__ */ new Map,zn=(e,t)=>{let n=Rn.get(e);n?n.push(t):Rn.set(e,[t])},Bn=()=>{if(Nn||!Pn||Fn||!Mn)throw Error(`worker not ready`)},Vn=e=>{switch(e.data.type){case`init-wasm`:Nn=!1,e.data.err?(Fn=!0,Ln[1](e.data.err)):(Pn=!0,Ln[0]()),In&&=(URL.revokeObjectURL(In),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Rn.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Hn=async()=>{if(!Pn){if(Nn)throw Error(`multiple calls to 'initWasm()' detected.`);if(Fn)throw Error(`previous call to 'initWasm()' failed.`);if(Nn=!0,jn())return new Promise((e,t)=>{Mn?.terminate(),ot().then(([n,r])=>{try{Mn=r,Mn.onerror=e=>t(e),Mn.onmessage=Vn,Ln=[e,t];let i={type:`init-wasm`,in:C};!i.in.wasm.wasmPaths&&(n||Xe)&&(i.in.wasm.wasmPaths={wasm:new URL(`/v4d-next/assets/ort-wasm-simd-threaded.asyncify-CxOG5pUO.wasm`,``+import.meta.url).href}),Mn.postMessage(i),In=n}catch(e){t(e)}},t)});try{await _t(C.wasm),await vn(C),Pn=!0}catch(e){throw Fn=!0,e}finally{Nn=!1}}},Un=async e=>{if(jn())return Bn(),new Promise((t,n)=>{zn(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:C}};Mn.postMessage(r)});await yn(C,e)},Wn=async e=>jn()?(Bn(),new Promise((t,n)=>{zn(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};Mn.postMessage(r,[e.buffer])})):Cn(e),Gn=async(e,t)=>{if(jn()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return Bn(),new Promise((n,r)=>{zn(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Mn.postMessage(i,a)})}return wn(e,t)},Kn=async e=>{if(jn())return Bn(),new Promise((t,n)=>{zn(`release`,[t,n]);let r={type:`release`,in:e};Mn.postMessage(r)});Tn(e)},qn=async(e,t,n,r,i,a)=>{if(jn()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return Bn(),new Promise((i,o)=>{zn(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};Mn.postMessage(c,kn(s))})}return Dn(e,t,n,r,i,a)},Jn=async e=>{if(jn())return Bn(),new Promise((t,n)=>{zn(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};Mn.postMessage(r)});On(e)}}),Xn,Zn,Qn,$n=l(()=>{Le(),Yn(),Bt(),Re(),Ht(),Xn=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},Zn=e=>{switch(e[3]){case`cpu`:return new be(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!Lt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return be.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!Rt(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return be.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},Qn=class{async fetchModelAndCopyToWasmMemory(e){return Wn(await Vt(e))}async loadModel(e,t){Ce();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Gn(n,t),we()}async dispose(){return Kn(this.sessionId)}async run(e,t,n){Ce();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>Xn(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?Xn(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await qn(this.sessionId,i,s,o,c,n),u={};for(let e=0;enr,initializeFlags:()=>tr,wasmBackend:()=>rr});var tr,nr,rr,ir=l(()=>{Le(),Yn(),$n(),tr=()=>{(typeof C.wasm.initTimeout!=`number`||C.wasm.initTimeout<0)&&(C.wasm.initTimeout=0);let e=C.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),C.wasm.simd=!1),typeof C.wasm.proxy!=`boolean`&&(C.wasm.proxy=!1),typeof C.wasm.trace!=`boolean`&&(C.wasm.trace=!1),typeof C.wasm.numThreads!=`number`||!Number.isInteger(C.wasm.numThreads)||C.wasm.numThreads<=0){if(typeof self<`u`&&!self.crossOriginIsolated)C.wasm.numThreads=1;else{let e=typeof navigator>`u`?c(`node:os`).cpus().length:navigator.hardwareConcurrency;C.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}}},nr=class{async init(e){tr(),await Hn(),await Un(e)}async createInferenceSessionHandler(e,t){let n=new Qn;return await n.loadModel(e,t),n}},rr=new nr});Le(),Le(),Le();var ar=`1.31.0-dev.20260914-8d85527a0`,or=Ie;{let e=(ir(),f(er)).wasmBackend;h(`webgpu`,e,5),h(`webnn`,e,5),h(`cpu`,e,10),h(`wasm`,e,10)}Object.defineProperty(C.versions,"web",{value:ar,enumerable:!0});let sr=`warning`;Object.defineProperty({wasm:{},webgl:{},webgpu:{},versions:{common:`1.30.0`},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);sr=e}},get logLevel(){return sr}},"logLevel",{enumerable:!0});const cr=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t===void 0||t.format===void 0?`RGB`:t.format,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat===void 0||t.tensorFormat===void 0?`RGB`:t.tensorFormat,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,ur(o,s)}throw Error(`Can not access image data`)}else if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(ur(e.data,s))}});else throw Error(`Input data provided is not supported - aborted tensor creation`);if(o!==void 0)return ur(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},fr=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new Sr({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},pr=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Sr({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},mr=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Sr({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},hr=(e,t,n)=>new Sr({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]}),gr=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),_r=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]);let vr=!1;const yr=()=>{if(!vr){vr=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=n!==void 0&&n.from;e&&(gr.set(`int64`,BigInt64Array),_r.set(BigInt64Array,`int64`)),t&&(gr.set(`uint64`,BigUint64Array),_r.set(BigUint64Array,`uint64`)),r?(gr.set(`float16`,n),_r.set(n,`float16`)):gr.set(`float16`,Uint16Array)}},br=e=>{let t=1;for(let n=0;n{switch(e.location){case`cpu`:return new Sr(e.type,e.data,t);case`cpu-pinned`:return new Sr({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new Sr({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new Sr({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new Sr({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}};var Sr=class{constructor(e,t,n){yr();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=gr.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=gr.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=_r.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=br(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return dr(e,t)}static fromTexture(e,t){return fr(e,t)}static fromGpuBuffer(e,t){return pr(e,t)}static fromMLTensor(e,t){return mr(e,t)}static fromPinnedBuffer(e,t,n){return hr(e,t,n)}toDataURL(e){return cr(this,e)}toImageData(e){return lr(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return xr(this,e)}};const Cr=Sr;var wr=Object.defineProperty,Tr=(e,t)=>{for(var n in t)wr(e,n,{get:t[n],enumerable:!0})},Er={},A={},Dr={},Or=`4.3.0`,kr=typeof self<`u`,Ar=!ei(Er),jr=!ei(A),Mr=kr&&`caches`in self,Nr=globalThis.Deno!==void 0;globalThis.Bun;var Pr=Nr&&Mr&&!Ar,Fr=typeof process<`u`,Ir=Fr&&process?.release?.name===`node`&&!Pr,Lr=typeof window<`u`&&window.document!==void 0,Rr=kr&&[`DedicatedWorkerGlobalScope`,`ServiceWorkerGlobalScope`,`SharedWorkerGlobalScope`].includes(self.constructor?.name),zr=Lr||Rr||Pr,Br=Ir||typeof navigator<`u`&&`gpu`in navigator,Vr=typeof navigator<`u`&&`ml`in navigator,Hr=typeof crypto<`u`&&typeof crypto.getRandomValues==`function`,Ur=typeof chrome<`u`&&chrome.runtime!==void 0&&typeof chrome.runtime.id==`string`,Wr=typeof ServiceWorkerGlobalScope<`u`&&kr&&self instanceof ServiceWorkerGlobalScope,Gr=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent;if(!((navigator.vendor||``).indexOf(`Apple`)>-1&&!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes(`Chrome`)&&!e.includes(`Android`)))return!1;let t=e.match(/Version\/(\d+)/);return t?parseInt(t[1],10)<26:!1})(),j=Object.freeze({IS_BROWSER_ENV:Lr,IS_WEBWORKER_ENV:Rr,IS_WEB_ENV:zr,IS_SERVICE_WORKER_ENV:Wr,IS_DENO_WEB_RUNTIME:Pr,IS_WEB_CACHE_AVAILABLE:Mr,IS_WEBGPU_AVAILABLE:Br,IS_WEBNN_AVAILABLE:Vr,IS_SAFARI_BELOW_26:Gr,IS_PROCESS_AVAILABLE:Fr,IS_NODE_ENV:Ir,IS_FS_AVAILABLE:Ar,IS_PATH_AVAILABLE:jr,IS_CRYPTO_AVAILABLE:Hr,IS_CHROME_AVAILABLE:Ur}),Kr=Ar&&jr,qr=`./`;if(Kr){let e=import.meta.url;e?qr=A.dirname(A.dirname(Dr.fileURLToPath(e))):typeof __dirname<`u`&&(qr=A.dirname(__dirname))}var Jr=Kr?A.join(qr,`/.cache/`):null,Yr=`/models/`,Xr=Kr?A.join(qr,Yr):Yr,Zr=typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0,Qr=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),$r=Qr.WARNING,M={version:Or,backends:{onnx:{}},get logLevel(){return $r},set logLevel(e){$r=e,M.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:`https://huggingface.co/`,remotePathTemplate:`{model}/resolve/{revision}/`,allowLocalModels:!(Lr||Rr||Pr),localModelPath:Xr,useFS:Ar,useBrowserCache:Mr,useFSCache:Ar,cacheDir:Jr,useCustomCache:!1,customCache:null,useWasmCache:Mr||Ar,cacheKey:`transformers-cache`,experimental_useCrossOriginStorage:!1,fetch:Zr};function ei(e){return Object.keys(e).length===0}var ti=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error(`Must implement _call method in subclass`)}};function ni(e,t){e&&e(t)}var ri=class extends ti{constructor(e,t){super(),this.callback=e,this.files_loading=t,this.loads=/* @__PURE__ */ new Map}_call(e){if(e.status===`progress`){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((e,t)=>e+t.loaded,0),n=Object.values(this.files_loading).reduce((e,t)=>e+t.total,0),r=n>0?t/n*100:0;this.callback({status:`progress_total`,name:e.name,progress:r,loaded:t,total:n,files:structuredClone(this.files_loading)})}this.callback(e)}};function ii(e){return Number.isInteger(e)||typeof e==`bigint`}function ai(e){return e==null||e===-1}function oi(e){let t=[],n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function si(...e){return Array.prototype.concat.apply([],e)}function ci(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))}function li(e,t){return Math.abs((e+t)%(2*t)-t)}function ui(e,t){return Object.assign({},...t.map(t=>{if(e[t]!==void 0)return{[t]:e[t]}}))}function di(e,t){let n=0;for(let r of e)r===t&&++n;return n}var N={error(...e){M.logLevel<=Qr.ERROR&&console.error(...e)},warn(...e){M.logLevel<=Qr.WARNING&&console.warn(...e)},info(...e){M.logLevel<=Qr.INFO&&console.log(...e)},debug(...e){M.logLevel<=Qr.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},fi=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=/* @__PURE__ */ Object.create(null);for(let n of e){let e=t;for(let t=0;tr&&t.push(e.slice(r,i)),t.push(o),i+=o.length,r=i):++i}return r{try{return new RegExp(e,t)}catch(n){if(!(n instanceof SyntaxError))throw n;let r=/* @__PURE__ */ new Map,i=e.replace(/(\\[pP])\{([^}=]+)\}/g,(t,n,i,a)=>{let o=0;for(let t=a-1;t>=0&&e[t]===`\\`;--t)++o;if(o%2==1)return t;let s=r.get(i);if(s===void 0){try{RegExp(`\\p{${i}}`,`u`),s=i}catch{s=`Script=${i}`}r.set(i,s)}return`${n}{${s}}`});if(i===e)throw n;try{return new RegExp(i,t)}catch{throw n}}},hi=e=>e.replace(/ \./g,`.`).replace(/ \?/g,`?`).replace(/ \!/g,`!`).replace(/ ,/g,`,`).replace(/ \' /g,`'`).replace(/ n't/g,`n't`).replace(/ 'm/g,`'m`).replace(/ 's/g,`'s`).replace(/ 've/g,`'ve`).replace(/ 're/g,`'re`),gi=(e,t=!0)=>{if(e.Regex!==void 0)return mi(ea(Hi(e.Regex)),`gu`);if(e.String!==void 0){let n=ta(e.String);return new RegExp(t?n:`(${n})`,`gu`)}return console.warn(`Unknown pattern type:`,e),null},_i=`\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}`,vi=`${_i}\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE`,yi=`[${vi}]`,bi=`[^${vi}]`,xi=`(?:(?|[:=!>])/,Ni=/^\\([pPxu])\{([^}]*)\}/,Pi=/^\{(\d+(?:,\d*)?|,\d+)\}/,Fi=/^\[:(\^?)(\p{Alphabetic}+):\]/u,Ii=/^\[:\^:\]/,Li=/^\[(?:\.[^\]]*\.\]|=[^\]]*=\])/,Ri=/^(?:\\x[0-9A-Fa-f]{2}|\\u[0-9A-Fa-f]{4}|\\c[A-Za-z])/,zi=e=>e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`,Bi=(e,t)=>String.fromCodePoint(e.codePointAt(t)),Vi=e=>{if(!/^[0-9A-Fa-f]{1,8}$/.test(e))return null;let t=Number.parseInt(e,16);if(t>127)return null;let n=String.fromCharCode(t);return zi(n)?`[${n.toLowerCase()}${n.toUpperCase()}]`:null},Hi=e=>e.replace(/\[\^\(\\s\|\[([^\]]+)\]\)\]/g,`[^()|\\s$1]`),Ui=`[\\s\\S]`,Wi=256,Gi=()=>({fragment:``,alternatives:[],tail:null,contains_complex_set:!1}),Ki=e=>{throw SyntaxError(`Unsupported range with a set-valued character-class operand at index ${e}`)},qi=(e,t,n,r=!0)=>{e.tail===`range`&&Ki(n),e.alternatives.push(t),e.tail=`set`,e.contains_complex_set=e.contains_complex_set||r},Ji=(e,t,n=!1,r=-1)=>{n&&e.tail===`range`&&Ki(r),e.tail===`range`?(e.fragment+=t,e.tail=`complete_range`):(e.fragment+=t,e.tail=n?`set`:`scalar`,e.contains_complex_set=e.contains_complex_set||n)},Yi=(e,t,n)=>{let r=Ni.exec(e.slice(t));if(r){let[e,i,a]=r;return i===`P`&&a===`Word`?qi(n,`[^${_i}]`,t):Ji(n,i===`x`?`\\u{${a}}`:i===`p`&&a===`Word`?_i:e,i===`p`||i===`P`,t),t+e.length}let i=Ri.exec(e.slice(t));if(i)return Ji(n,i[0]),t+i[0].length;if(t+1>=e.length)throw SyntaxError(`Unterminated escape in character class at index ${t}`);let a=Bi(e,t+1),o=t+1+a.length,s=ki.get(a);if(s!==void 0)return Ji(n,s),o;let c=Oi.get(a);if(c!==void 0)return qi(n,c,t),o;let l=Di.get(a),u,d=!1;return l===void 0?u=/[A-Za-z0-9]/.test(a)||ji.includes(a)||a===`-`?`\\${a}`:a:(u=l,d=a!==`a`&&a!==`e`),Ji(n,u,d,t),o},Xi=e=>e.length===1?e[0]:`(?:(?=(?:${e.join(`|`)}))${Ui})`,Zi=e=>Xi(e.fragment.length===0?e.alternatives:[`[${e.fragment}]`,...e.alternatives]),Qi=e=>{let t=mi(`^(?:${e})$`,`u`),n=``;for(let e=0;e<26;++e){let r=String.fromCharCode(65+e),i=String.fromCharCode(97+e),a=t.test(r);a!==t.test(i)&&(n+=a?i:r)}return n},$i=(e,t,n,r=!0,i=1)=>{if(i>Wi)throw SyntaxError(`Maximum character-class nesting depth of ${Wi} exceeded at index ${t}`);let a=t+1,o=e[a]===`^`;o&&++a;let s=a,c=[Gi()],l=c[0],u=!1;for(;a1?SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`):SyntaxError(`Empty character class at index ${t}`);let e=c.some(e=>e.contains_complex_set);if(o&&c.length>1&&u)throw SyntaxError(`Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${t}`);let i=Zi(c[0]),d=i;if(c.length>1){let e=``;for(let t=1;t0&&(f?(p+=e,d=`[${p}]`):d=Xi([d,`[${e}]`]))}return{atom:o?f?`[^${p}]`:`(?:(?!${d})${Ui})`:d,end:a+1,negated:o,contains_complex_set:e,contains_nested_negated_complex_set:u}}if(e.startsWith(`&&`,a)){if(l.tail===null)throw SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`);l=Gi(),c.push(l),a+=2}else if(d===`[`){let t=e.slice(a);if(Ii.test(t))throw SyntaxError(`Malformed empty negated POSIX character class at index ${a}`);let r=Fi.exec(t);if(r){let[,e,t]=r,i=Ai.get(t);if(i===void 0)throw SyntaxError(`Unsupported POSIX character class "${t}" at index ${a}`);if(n&&e&&(t===`lower`||t===`upper`))throw SyntaxError(`Unsupported negated POSIX ${t} class inside an inline case-insensitive group`);e?qi(l,`[^${i}]`,a):Ji(l,i,!0,a),a+=r[0].length;continue}if(Li.test(t))throw SyntaxError(`Unsupported POSIX collating or equivalence bracket expression at index ${a}`);let o=$i(e,a,n,!1,i+1);qi(l,o.atom,a,o.contains_complex_set),u||=o.contains_nested_negated_complex_set||o.negated&&o.contains_complex_set,a=o.end}else if(d===`-`){let t=e[a+1]===`]`||e.startsWith(`&&`,a+1);l.tail===`set`&&!t&&Ki(a),l.tail===null||l.tail===`range`||l.tail===`complete_range`||t?Ji(l,`\\-`):(l.fragment+=`-`,l.tail=`range`),++a}else Ji(l,d===`^`&&l.fragment.length===0?`\\^`:d),a+=d.length}}throw SyntaxError(`${c.length>1?`Unterminated character-class intersection`:`Unterminated character class`} at index ${t}`)},ea=e=>{let t=``,n=-1,r=!1,i=!1,a=[],o=e=>{n=t.length,t+=e,r=!1};for(let s=0;s=e.length){t+=c;break}let a=Bi(e,s+1);if(s+=1+a.length,a===`G`)continue;let l=ki.get(a);if(l!==void 0){o(l);continue}let u=Ei.get(a),d;d=u===void 0?/[A-Za-z0-9]/.test(a)||ji.includes(a)?`\\${a}`:a:u,o(d)}else switch(c){case`[`:{let t=$i(e,s,i);o(t.atom),s=t.end;continue}case`]`:o(`\\]`),++s;continue;case`.`:o(`[^\\n]`),++s;continue;case`^`:o(Ci),++s;continue;case`$`:o(wi),++s;continue;case`(`:{let n=e.startsWith(`(?i:`,s),o=n?`(?i:`:Mi.exec(e.slice(s))?.[0]??`(`,c=n||o===`(?>`?`(?:`:o;a.push([t.length,i]),n&&(i=!0),t+=c,r=!1,s+=o.length;continue}case`)`:t+=c,[n,i]=a.pop()??[-1,!1],r=!1,++s;continue;case`|`:t+=c,n=-1,r=!1,++s;continue;case`{`:{let i=Pi.exec(e.slice(s));if(!i||n<0){o(`\\{`),++s;continue}let a=i[1].startsWith(`,`)?`0${i[1]}`:i[1];s+=i[0].length;let c=e[s];c===`+`||c===`*`?(t=`${t.slice(0,n)}(?:${t.slice(n)}{${a}})${c}`,++s):t+=`{${a}}`,r=!0;continue}case`}`:o(`\\}`),++s;continue;case`+`:if(r){++s;continue}t+=c,r=!0,++s;continue;case`*`:case`?`:t+=c,r=!0,++s;continue;default:o(i&&zi(c)?`[${c.toLowerCase()}${c.toUpperCase()}]`:c),s+=c.length;continue}}return t},ta=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),na=(e,t,n)=>{let r=[],i=0;for(;ie>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,ia=e=>Number.isInteger(e)||typeof e==`bigint`,aa=e=>{let t=0;for(let n of e)++t;return t},oa=e=>ua(e.toLowerCase()),sa=(...e)=>Array.prototype.concat.apply([],e),ca=e=>new Map(Object.entries(e)),la=(e,t)=>{let n=[],r=0;for(let i of e.matchAll(t)){let t=i[0];r0&&n.push(t),r=i.index+t.length}return re.replace(/\p{M}/gu,``),da=(e,t,n=[])=>{if(!e||Array.isArray(e)||typeof e!=`object`)return`${t} must be a valid object`;for(let r of n)if(!(r in e))return`${t} must contain a "${r}" property`;return null},fa=e=>e.match(/\S+/g)||[],pa=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},ma=class extends pa{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},ha=class extends ma{tokenize_chinese_chars(e){let t=[];for(let n=0;ne.normalize(`NFKC`)).join(`~`):e.normalize(`NFKC`),e}},_a=class extends ma{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(e=>Ea(e))}normalize(e){return this.normalizers.reduce((e,t)=>t?t.normalize(e):e,e)}},va=class extends ma{constructor(e){super(e),this.pattern=gi(this.config.pattern??{})}normalize(e){return this.pattern===null?e:e.replaceAll(this.pattern,this.config.content??``)}},ya=class extends ma{constructor(){super(...arguments),this.form=`NFC`}normalize(e){return e=e.normalize(this.form),e}},ba=class extends ya{constructor(){super(...arguments),this.form=`NFC`}},xa=class extends ya{constructor(){super(...arguments),this.form=`NFD`}},P=class extends ya{constructor(){super(...arguments),this.form=`NFKC`}},Sa=class extends ya{constructor(){super(...arguments),this.form=`NFKD`}},Ca=class extends ma{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},F=class extends ma{normalize(e){return ua(e)}},wa=class extends ma{normalize(e){return e.toLowerCase()}},I=class extends ma{normalize(e){return e=this.config.prepend+e,e}};function Ta(e){if(e===null)return null;switch(e.type){case`BertNormalizer`:return new ha(e);case`Precompiled`:return new ga(e);case`Sequence`:return new _a(e);case`Replace`:return new va(e);case`NFC`:return new ba(e);case`NFD`:return new xa(e);case`NFKC`:return new P(e);case`NFKD`:return new Sa(e);case`Strip`:return new Ca(e);case`StripAccents`:return new F(e);case`Lowercase`:return new wa(e);case`Prepend`:return new I(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}var Ea=Ta,Da=class extends pa{pre_tokenize(e,t){return(Array.isArray(e)?e.map(e=>this.pre_tokenize_text(e,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},Oa=(()=>{let e=[...Array.from({length:94},(e,t)=>t+33),...Array.from({length:12},(e,t)=>t+161),...Array.from({length:82},(e,t)=>t+174)],t=e.slice(),n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);let r=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,r[t]]))})(),ka=(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])))(Oa),Aa=`\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E`,ja=class extends Da{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=Oa,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(` `)&&(e=` `+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(e=>Array.from(this.text_encoder.encode(e),e=>this.byte_encoder[e]).join(``))}},Ma=class extends Da{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},Na=class extends Da{constructor(e){super(),this.replacement=e.replacement??`▁`,this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??`always`}pre_tokenize_text(e,t){let{section_index:n=void 0}=t??{},r=e.replaceAll(` `,this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme===`always`||this.prepend_scheme===`first`&&n===0)&&(r=this.str_rep+r),[r]}},Pa=class extends Da{constructor(e){super(),this.config=e,this.pattern=gi(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?(e.match(this.pattern)||[]).filter(e=>e):this.config.behavior?.toLowerCase()===`removed`?e.split(this.pattern).filter(e=>e):la(e,this.pattern)}},Fa=class extends Da{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${Aa}]+|[${Aa}]+`,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},Ia=class extends Da{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?``:`+`}`;this.pattern=new RegExp(t,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},La=class extends Da{constructor(){super(),this.pattern=RegExp(`[^\\s${Aa}]+|[${Aa}]`,`gu`)}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},Ra=class extends Da{constructor(e){super(),this.config=e,this.pattern=gi(this.config.pattern??{}),this.content=this.config.content??``}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??``)]}},za=class extends Da{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(e=>Ua(e))}pre_tokenize_text(e,t){return this.tokenizers.reduce((e,n)=>n?n.pre_tokenize(e,t):e,[e])}},Ba=class extends Da{pre_tokenize_text(e){return fa(e)}},Va=class extends Da{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let n=0;nthis.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,i=0,a=[];for(;i0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(n===null){r=!0;break}a.push(n),i=t}r?t.push(this.unk_token):t.push(...a)}return t}},Ka=class e{constructor(e,t){this.is_leaf=e,this.children=t}static default(){return new e(!1,/* @__PURE__ */ new Map)}},qa=class{constructor(){this.root=Ka.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let n of e){let e=t.children.get(n);e===void 0&&(e=Ka.default(),t.children.set(n,e)),t=e}t.is_leaf=!0}*common_prefix_search(e,t=0){let n=this.root;if(n===void 0)return;let r=``;for(let i=t;i[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new Ja(this.bos_token_id??0,0,0,0,0),i=new Ja(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(i.clone()),this.begin_nodes[this.len].push(i),this.end_nodes[0].push(r)}insert(e,t,n,r){let i=this.nodes.length,a=new Ja(r,i,e,t,n);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let e of this.begin_nodes[t]){e.prev=null;let n=0,r=null;for(let i of this.end_nodes[t]){let t=i.backtrace_score+e.score;(r===null||t>n)&&(r=i.clone(),n=t)}if(r!==null)e.prev=r,e.backtrace_score=n;else return[]}++t}let n=[],r=this.begin_nodes[e][0].prev;if(r===null)return[];let i=r.clone();for(;i.prev!==null;)n.push(i.clone()),i=i.clone().prev.clone();return n.reverse(),n}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join(``)}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}};function Xa(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r[e,t])),this.bos_token=` `,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=Xa(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new qa,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,n=0;for(;ne>t,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},eo=class extends Wa{constructor(e){super(e),this.tokens_to_ids=ca(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(e=>e.split(` `,2)),this.bpe_ranks=new Map(this.merges.map((e,t)=>[JSON.stringify(e),t])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new $a(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];let t=this.cache.get(e);if(t!==void 0)return t;let n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let e=new Qa((e,t)=>e.score`<0x${e.toString(16).toUpperCase().padStart(2,`0`)}>`);e.every(e=>this.tokens_to_ids.has(e))?t.push(...e):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},to=class extends Wa{constructor(e,t){super(e);let n=e.vocab;this.tokens_to_ids=ca(t.target_lang?n[t.target_lang]:n),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}};function no(e,t){switch(e.type){case`WordPiece`:return new Ga(e);case`Unigram`:return new Za(e,t.eos_token);case`BPE`:return new eo(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Za(e,t.eos_token):Object.hasOwn(e,`continuing_subword_prefix`)&&Object.hasOwn(e,`unk_token`)?Object.hasOwn(e,`merges`)?new eo(e):new Ga(e):new to(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw Error(`Unknown TokenizerModel type: ${e?.type}`)}}var ro=no,io=class extends pa{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},ao=class extends io{post_process(e,t=null,n=!0){let r=t===null?this.config.single:this.config.pair,i=[],a=[];for(let o of r)`SpecialToken`in o?n&&(i.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):`Sequence`in o&&(o.Sequence.id===`A`?(i=sa(i,e),a=sa(a,Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id===`B`&&(i=sa(i,t),a=sa(a,Array(t.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:a}}},oo=class extends io{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},so=class extends io{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,n=!0){n&&(e=sa([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=[],a=n?[this.sep[0]]:[];e=sa(e,i,t,a),r=sa(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},co=class extends io{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,n=!0){n&&(e=sa([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=n?[this.sep[0]]:[],a=n?[this.sep[0]]:[];e=sa(e,i,t,a),r=sa(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},lo=class extends io{constructor(e){super(e),this.processors=(e.processors??[]).map(e=>fo(e))}post_process(e,t=null,n=!0){let r={tokens:e,tokens_pair:t};for(let e of this.processors)r=e.post_process(r.tokens,r.tokens_pair,n);return r}};function uo(e){if(e===null)return null;switch(e.type){case`TemplateProcessing`:return new ao(e);case`ByteLevel`:return new oo(e);case`BertProcessing`:return new so(e);case`RobertaProcessing`:return new co(e);case`Sequence`:return new lo(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}var fo=uo,po=class extends pa{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=`trim_offsets`in e&&e.trim_offsets}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join(``)}},mo=class extends po{constructor(e){super(e),this.byte_decoder=ka,this.text_decoder=new TextDecoder(`utf-8`,{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(``),n=new Uint8Array([...t].map(e=>this.byte_decoder[e]));return this.text_decoder.decode(n)}decode_chain(e){let t=[],n=[];for(let r of e)this.added_tokens.find(e=>e.content===r)===void 0?n.push(r):(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r));return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}},ho=class extends po{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((e,t)=>{if(t!==0){let t=this.config.prefix;e=t&&e.startsWith(t)?e.replace(t,``):` `+e}return this.cleanup&&(e=hi(e)),e})}},go=class extends po{constructor(e){super(e),this.replacement=e.replacement??`▁`}decode_chain(e){let t=[];for(let n=0;nt.replaceAll(this.suffix,n===e.length-1?``:` `))}},vo=class extends po{constructor(e){super(e),this.pad_token=e.pad_token??``,this.word_delimiter_token=e.word_delimiter_token??``,this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return``;let t=[e[0]];for(let n=1;ne!==this.pad_token).join(``);return this.cleanup&&(n=hi(n).replaceAll(this.word_delimiter_token,` `).trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},yo=class extends po{constructor(e){super(e),this.decoders=(e.decoders??[]).map(e=>To(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}},bo=class extends po{constructor(e){super(e),this.pattern=gi(this.config.pattern)}decode_chain(e){let t=this.config.content??``,n=this.pattern;return n===null?e:e.map(e=>e.replaceAll(n,t))}},xo=class extends po{decode_chain(e){return[e.join(``)]}},So=class extends po{constructor(e){super(e),this.content=e.content??``,this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(e=>{let t=0;for(let n=0;n`)){let t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(e!==null)n.push(e);else{if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}};function wo(e){if(e===null)return null;switch(e.type){case`ByteLevel`:return new mo(e);case`WordPiece`:return new ho(e);case`Metaspace`:return new go(e);case`BPEDecoder`:return new _o(e);case`CTC`:return new vo(e);case`Sequence`:return new yo(e);case`Replace`:return new bo(e);case`Fuse`:return new xo(e);case`Strip`:return new So(e);case`ByteFallback`:return new Co(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}var To=wo,Eo=class{constructor(e,t){let n=da(e,`Tokenizer`,[`model`,`decoder`,`post_processor`,`pre_tokenizer`,`normalizer`]);if(n)throw Error(n);let r=da(t,`Config`);if(r)throw Error(r);this.tokenizer=e,this.config=t,this.normalizer=Ea(this.tokenizer.normalizer),this.pre_tokenizer=Ua(this.tokenizer.pre_tokenizer),this.model=ro(this.tokenizer.model,this.config),this.post_processor=fo(this.tokenizer.post_processor),this.decoder=To(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let i=[],a=[];this.added_tokens_map=/* @__PURE__ */ new Map;for(let e of this.tokenizer.added_tokens){let t=new pi(e);if(this.added_tokens.push(t),this.model.tokens_to_ids.set(t.content,t.id),this.model.vocab[t.id]=t.content,t.special&&(this.special_tokens.push(t.content),this.all_special_ids.push(t.id)),this.added_tokens_map.set(t.content,t),t.normalized&&this.normalizer!==null){let e=this.normalizer(t.content);a.push(e),this.added_tokens_map.set(e,t)}else i.push(t.content)}(this.config.additional_special_tokens??[]).forEach(e=>{this.special_tokens.includes(e)||this.special_tokens.push(e)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new fi(i),this.splitter_normalized=new fi(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:i,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}),o=i.map(e=>this.added_tokens_map.get(e)?.id??this.model.tokens_to_ids.get(e)??this.model.unk_token_id),s={ids:o,tokens:i,attention_mask:Array(o.length).fill(1)};return r&&a&&(s.token_type_ids=a),s}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!ia(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);let n=e.map(e=>this.model.vocab[Number(e)]??this.model.unk_token);t.skip_special_tokens&&(n=n.filter(e=>!this.special_tokens.includes(e)));let r=this.decoder?this.decoder(n):n.join(` `);return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix,` `),t.skip_special_tokens&&(r=r.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=hi(r)),r}tokenize(e,{text_pair:t=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((e,n)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),r.rstrip&&n{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];if(this.remove_space===!0&&(e=e.trim().split(/\s+/).join(` `)),this.do_lowercase_and_remove_accent&&(e=oa(e)),this.normalizer!==null&&(e=this.normalizer(e)),e.length===0)return[];let n=this.splitter_normalized.split(e);return n.forEach((e,t)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&t>0&&(n[t-1]=n[t-1].trimEnd()),r.rstrip&&t{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];let n=this.pre_tokenizer===null?[e]:this.pre_tokenizer(e,{section_index:t});return this.model(n)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:n=!0}){let r=this.encode_text(e),i=this.encode_text(t||null);return this.post_processor?this.post_processor(r,i,n):{tokens:sa(r??[],i??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=/* @__PURE__ */ new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=/* @__PURE__ */ new Map;for(let n=0;nt in e?Do(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ko=(e,t,n)=>(Oo(e,typeof t==`symbol`?t:t+``,n),n),L=Object.freeze({Text:`Text`,NumericLiteral:`NumericLiteral`,StringLiteral:`StringLiteral`,Identifier:`Identifier`,Equals:`Equals`,OpenParen:`OpenParen`,CloseParen:`CloseParen`,OpenStatement:`OpenStatement`,CloseStatement:`CloseStatement`,OpenExpression:`OpenExpression`,CloseExpression:`CloseExpression`,OpenSquareBracket:`OpenSquareBracket`,CloseSquareBracket:`CloseSquareBracket`,OpenCurlyBracket:`OpenCurlyBracket`,CloseCurlyBracket:`CloseCurlyBracket`,Comma:`Comma`,Dot:`Dot`,Colon:`Colon`,Pipe:`Pipe`,CallOperator:`CallOperator`,AdditiveBinaryOperator:`AdditiveBinaryOperator`,MultiplicativeBinaryOperator:`MultiplicativeBinaryOperator`,ExponentiationBinaryOperator:`ExponentiationBinaryOperator`,ComparisonBinaryOperator:`ComparisonBinaryOperator`,UnaryOperator:`UnaryOperator`,Comment:`Comment`}),Ao=class{constructor(e,t){this.value=e,this.type=t}};function jo(e){return/\w/.test(e)}function Mo(e){return/[0-9]/.test(e)}function No(e){return/\s/.test(e)}var Po=[[`{%`,L.OpenStatement],[`%}`,L.CloseStatement],[`{{`,L.OpenExpression],[`}}`,L.CloseExpression],[`(`,L.OpenParen],[`)`,L.CloseParen],[`{`,L.OpenCurlyBracket],[`}`,L.CloseCurlyBracket],[`[`,L.OpenSquareBracket],[`]`,L.CloseSquareBracket],[`,`,L.Comma],[`.`,L.Dot],[`:`,L.Colon],[`|`,L.Pipe],[`<=`,L.ComparisonBinaryOperator],[`>=`,L.ComparisonBinaryOperator],[`==`,L.ComparisonBinaryOperator],[`!=`,L.ComparisonBinaryOperator],[`<`,L.ComparisonBinaryOperator],[`>`,L.ComparisonBinaryOperator],[`+`,L.AdditiveBinaryOperator],[`-`,L.AdditiveBinaryOperator],[`~`,L.AdditiveBinaryOperator],[`**`,L.ExponentiationBinaryOperator],[`*`,L.MultiplicativeBinaryOperator],[`//`,L.MultiplicativeBinaryOperator],[`/`,L.MultiplicativeBinaryOperator],[`%`,L.MultiplicativeBinaryOperator],[`=`,L.Equals]],Fo=/* @__PURE__ */ new Map([[`n`,` +`],[`t`,` `],[`r`,`\r`],[`b`,`\b`],[`f`,`\f`],[`v`,`\v`],[`'`,`'`],[`"`,`"`],[`\\`,`\\`]]);function Io(e,t={}){return e.endsWith(` +`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,`$1`)),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,`$1`)),e.replace(/(\s*){%(-?)\s*(?:end)?generation\s*(-?)%}(\s*)/gs,(e,t,n,r,i)=>(n?``:t)+(r?``:i))}function Lo(e,t={}){let n=[],r=Io(e,t),i=0,a=0,o=e=>{let t=``;for(;e(r[i]);)if(r[i]===`\\`){if(++i,i>=r.length)throw SyntaxError(`Unexpected end of input`);let e=r[i++],n=Fo.get(e);if(n===void 0)throw SyntaxError(`Unexpected escaped character: ${e}`);t+=n}else if(t+=r[i++],i>=r.length)throw SyntaxError(`Unexpected end of input`);return t},s=()=>{let e=n.at(-1);e&&e.type===L.Text&&(e.value=e.value.trimEnd(),e.value===``&&n.pop())},c=()=>{for(;i0){n.push(new Ao(e,L.Text));continue}}if(r[i]===`{`&&r[i+1]===`#`){i+=2;let e=r[i]===`-`;e&&++i;let t=``;for(;r[i]!==`#`||r[i+1]!==`}`;){if(i+2>=r.length)throw SyntaxError(`Missing end of comment tag`);t+=r[i++]}let a=t.endsWith(`-`);a&&(t=t.slice(0,-1)),e&&s(),n.push(new Ao(t,L.Comment)),i+=2,a&&c();continue}if(r.slice(i,i+3)===`{%-`){s(),n.push(new Ao(`{%`,L.OpenStatement)),i+=3;continue}if(r.slice(i,i+3)===`{{-`){s(),n.push(new Ao(`{{`,L.OpenExpression)),a=0,i+=3;continue}if(o(No),r.slice(i,i+3)===`-%}`){n.push(new Ao(`%}`,L.CloseStatement)),i+=3,c();continue}if(r.slice(i,i+3)===`-}}`){n.push(new Ao(`}}`,L.CloseExpression)),i+=3,c();continue}let t=r[i];if(t===`-`||t===`+`){let e=n.at(-1)?.type;if(e===L.Text||e===void 0)throw SyntaxError(`Unexpected character: ${t}`);switch(e){case L.Identifier:case L.NumericLiteral:case L.StringLiteral:case L.CloseParen:case L.CloseSquareBracket:break;default:{++i;let e=o(Mo);if(e.length>0&&r[i]===`.`&&Mo(r[i+1])){++i;let t=o(Mo);e=`${e}.${t}`}n.push(new Ao(`${t}${e}`,e.length>0?L.NumericLiteral:L.UnaryOperator));continue}}}for(let[e,t]of Po)if(!(e===`}}`&&a>0)&&r.slice(i,i+e.length)===e){n.push(new Ao(e,t)),t===L.OpenExpression?a=0:t===L.OpenCurlyBracket?++a:t===L.CloseCurlyBracket&&--a,i+=e.length;continue main}if(t===`'`||t===`"`){++i;let e=o(e=>e!==t);n.push(new Ao(e,L.StringLiteral)),++i}else if(Mo(t)){let e=o(Mo);if(n.at(-1)?.type!==L.Dot&&r[i]===`.`&&Mo(r[i+1])){++i;let t=o(Mo);e=`${e}.${t}`}n.push(new Ao(e,L.NumericLiteral))}else if(jo(t)){let e=o(jo);n.push(new Ao(e,L.Identifier))}else throw SyntaxError(`Unexpected character: ${t}`)}return n}var Ro=class{type=`Statement`},zo=class extends Ro{constructor(e){super(),this.body=e}type=`Program`},Bo=class extends Ro{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type=`If`},Vo=class extends Ro{constructor(e,t,n,r){super(),this.loopvar=e,this.iterable=t,this.body=n,this.defaultBlock=r}type=`For`},Ho=class extends Ro{type=`Break`},Uo=class extends Ro{type=`Continue`},Wo=class extends Ro{constructor(e,t,n){super(),this.assignee=e,this.value=t,this.body=n}type=`Set`},Go=class extends Ro{constructor(e,t,n){super(),this.name=e,this.args=t,this.body=n}type=`Macro`},Ko=class extends Ro{constructor(e){super(),this.value=e}type=`Comment`},qo=class extends Ro{type=`Expression`},Jo=class extends qo{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type=`MemberExpression`},Yo=class extends qo{constructor(e,t){super(),this.callee=e,this.args=t}type=`CallExpression`},Xo=class extends qo{constructor(e){super(),this.value=e}type=`Identifier`},Zo=class extends qo{constructor(e){super(),this.value=e}type=`Literal`},Qo=class extends Zo{type=`IntegerLiteral`},$o=class extends Zo{type=`FloatLiteral`},es=class extends Zo{type=`StringLiteral`},ts=class extends Zo{type=`ArrayLiteral`},ns=class extends Zo{type=`TupleLiteral`},rs=class extends Zo{type=`ObjectLiteral`},is=class extends qo{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type=`BinaryExpression`},as=class extends qo{constructor(e,t){super(),this.operand=e,this.filter=t}type=`FilterExpression`},os=class extends Ro{constructor(e,t){super(),this.filter=e,this.body=t}type=`FilterStatement`},ss=class extends qo{constructor(e,t){super(),this.lhs=e,this.test=t}type=`SelectExpression`},cs=class extends qo{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type=`TestExpression`},ls=class extends qo{constructor(e,t){super(),this.operator=e,this.argument=t}type=`UnaryExpression`},us=class extends qo{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type=`SliceExpression`},ds=class extends qo{constructor(e,t){super(),this.key=e,this.value=t}type=`KeywordArgumentExpression`},fs=class extends qo{constructor(e){super(),this.argument=e}type=`SpreadExpression`},ps=class extends qo{constructor(e){super(),this.argument=e}type=`KeywordSpreadExpression`},ms=class extends Ro{constructor(e,t,n){super(),this.call=e,this.callerArgs=t,this.body=n}type=`CallStatement`},hs=class extends qo{constructor(e,t,n){super(),this.condition=e,this.trueExpr=t,this.falseExpr=n}type=`Ternary`};function gs(e){let t=new zo([]),n=0;function r(t,r){let i=e[n++];if(!i||i.type!==t)throw Error(`Parser Error: ${r}. ${i.type} !== ${t}.`);return i}function i(e){if(!c(e))throw SyntaxError(`Expected ${e}`);++n}function a(){switch(e[n].type){case L.Comment:return new Ko(e[n++].value);case L.Text:return l();case L.OpenStatement:return u();case L.OpenExpression:return d();default:throw SyntaxError(`Unexpected token type: ${e[n].type}`)}}function o(...t){return n+t.length<=e.length&&t.every((t,r)=>t===e[n+r].type)}function s(...t){return e[n]?.type===L.OpenStatement&&e[n+1]?.type===L.Identifier&&t.includes(e[n+1]?.value)}function c(...t){return n+t.length<=e.length&&t.every((t,r)=>e[n+r].type===`Identifier`&&t===e[n+r].value)}function l(){return new es(r(L.Text,`Expected text token`).value)}function u(){if(r(L.OpenStatement,`Expected opening statement token`),e[n].type!==L.Identifier)throw SyntaxError(`Unknown statement, got ${e[n].type}`);let t=e[n].value,c;switch(t){case`set`:++n,c=f();break;case`if`:++n,c=p(),r(L.OpenStatement,`Expected {% token`),i(`endif`),r(L.CloseStatement,`Expected %} token`);break;case`macro`:++n,c=m(),r(L.OpenStatement,`Expected {% token`),i(`endmacro`),r(L.CloseStatement,`Expected %} token`);break;case`for`:++n,c=g(),r(L.OpenStatement,`Expected {% token`),i(`endfor`),r(L.CloseStatement,`Expected %} token`);break;case`call`:{++n;let e=null;o(L.OpenParen)&&(e=w(`parameters`));let t=ce();if(t.type!==`Identifier`)throw SyntaxError(`Expected identifier following call statement`);let l=w(`call`);r(L.CloseStatement,`Expected closing statement token`);let u=[];for(;!s(`endcall`);)u.push(a());r(L.OpenStatement,`Expected '{%'`),i(`endcall`),r(L.CloseStatement,`Expected closing statement token`),c=new ms(new Yo(t,l),e,u);break}case`break`:++n,r(L.CloseStatement,`Expected closing statement token`),c=new Ho;break;case`continue`:++n,r(L.CloseStatement,`Expected closing statement token`),c=new Uo;break;case`filter`:{++n;let e=ce();e instanceof Xo&&o(L.OpenParen)&&(e=C(e)),r(L.CloseStatement,`Expected closing statement token`);let t=[];for(;!s(`endfilter`);)t.push(a());r(L.OpenStatement,`Expected '{%'`),i(`endfilter`),r(L.CloseStatement,`Expected '%}'`),c=new os(e,t);break}default:throw SyntaxError(`Unknown statement type: ${t}`)}return c}function d(){r(L.OpenExpression,`Expected opening expression token`);let e=_();return r(L.CloseExpression,`Expected closing expression token`),e}function f(){let e=h(),t=null,c=[];if(o(L.Equals))++n,t=h();else{for(r(L.CloseStatement,`Expected %} token`);!s(`endset`);)c.push(a());r(L.OpenStatement,`Expected {% token`),i(`endset`)}return r(L.CloseStatement,`Expected closing statement token`),new Wo(e,t,c)}function p(){let e=_();r(L.CloseStatement,`Expected closing statement token`);let t=[],i=[];for(;!s(`elif`,`else`,`endif`);)t.push(a());if(s(`elif`)){++n,++n;let e=p();i.push(e)}else if(s(`else`))for(++n,++n,r(L.CloseStatement,`Expected closing statement token`);!s(`endif`);)i.push(a());return new Bo(e,t,i)}function m(){let e=ce();if(e.type!==`Identifier`)throw SyntaxError(`Expected identifier following macro statement`);let t=w(`parameters`);r(L.CloseStatement,`Expected closing statement token`);let n=[];for(;!s(`endmacro`);)n.push(a());return new Go(e,t,n)}function h(e=!1){let t=e?ce:_,r=[t()],i=o(L.Comma);for(;i&&(++n,r.push(t()),o(L.Comma)););return i?new ns(r):r[0]}function g(){let e=h(!0);if(!(e instanceof Xo||e instanceof ns))throw SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);if(!c(`in`))throw SyntaxError("Expected `in` keyword following loop variable");++n;let t=_();r(L.CloseStatement,`Expected closing statement token`);let i=[];for(;!s(`endfor`,`else`);)i.push(a());let o=[];if(s(`else`))for(++n,++n,r(L.CloseStatement,`Expected closing statement token`);!s(`endfor`);)o.push(a());return new Vo(e,t,i,o)}function _(){return v()}function v(){let e=y();if(c(`if`)){++n;let t=y();return c(`else`)?(++n,new hs(t,e,v())):new ss(e,t)}return e}function y(){let t=b();for(;c(`or`);){let r=e[n];++n;let i=b();t=new is(r,t,i)}return t}function b(){let t=x();for(;c(`and`);){let r=e[n];++n;let i=x();t=new is(r,t,i)}return t}function x(){let t;for(;c(`not`);){let r=e[n];++n,t=new ls(r,x())}return t??ee()}function ee(){let t=S();for(;;){let r;if(c(`not`,`in`))r=new Ao(`not in`,L.Identifier),n+=2;else if(c(`in`))r=e[n++];else if(o(L.ComparisonBinaryOperator))r=e[n++];else break;let i=S();t=new is(r,t,i)}return t}function S(){let t=E();for(;o(L.AdditiveBinaryOperator);){let r=e[n];++n;let i=E();t=new is(r,t,i)}return t}function te(){let e=T(ce());return o(L.OpenParen)?C(e):e}function C(e){let t=new Yo(e,w(`call`));return t=T(t),o(L.OpenParen)&&(t=C(t)),t}function w(e){r(L.OpenParen,`Expected opening parenthesis for arguments list`);let t=ne(e);return r(L.CloseParen,`Expected closing parenthesis for arguments list`),t}function ne(t){let r=[],i=/* @__PURE__ */ new Set,a=!1,s=!1;for(;!o(L.CloseParen);){let c=o(L.ExponentiationBinaryOperator),l=o(L.MultiplicativeBinaryOperator)&&e[n].value===`*`;if(t===`parameters`&&(c||l))throw SyntaxError(`Argument unpacking is not allowed in parameter declarations`);if(c){if(++n,r.push(new ps(_())),o(L.Comma)&&++n,!o(L.CloseParen))throw SyntaxError("Expected closing parenthesis: `**` must be applied to the final argument");break}let u;if(l){if(s)throw SyntaxError("Only one `*` argument unpacking is allowed");s=!0,++n,u=new fs(_())}else{if(u=_(),o(L.Equals)){if(++n,!(u instanceof Xo))throw SyntaxError(t===`parameters`?`Expected identifier for parameter declaration`:`Expected identifier for keyword argument`);let e=_();u=new ds(u,e)}if(t===`parameters`){if(!(u instanceof Xo||u instanceof ds))throw SyntaxError(`Expected identifier for parameter declaration`);let e=u instanceof Xo?u.value:u.key.value;if(i.has(e))throw SyntaxError(`Duplicate parameter name: ${e}`);i.add(e)}if(u instanceof ds)a=!0;else if(a)throw SyntaxError(t===`call`?`Positional arguments must come before keyword arguments`:`Non-default argument follows default argument`);else if(s)throw SyntaxError("Positional arguments must not follow `*` argument unpacking")}r.push(u),o(L.Comma)&&++n}return r}function re(){let e=[],t=!1;for(;!o(L.CloseSquareBracket);)o(L.Colon)?(e.push(void 0),++n,t=!0):(e.push(_()),o(L.Colon)&&(++n,t=!0));if(e.length===0)throw SyntaxError(`Expected at least one argument for member/slice expression`);if(t){if(e.length>3)throw SyntaxError(`Expected 0-3 arguments for slice expression`);return new us(...e)}return e[0]}function T(t){for(;o(L.Dot)||o(L.OpenSquareBracket);){let i=e[n];++n;let a,o=i.type===L.OpenSquareBracket;if(o)a=re(),r(L.CloseSquareBracket,`Expected closing square bracket`);else if(a=ce(),a.type!==`Identifier`&&a.type!==`IntegerLiteral`)throw SyntaxError(`Expected identifier or integer following dot operator`);t=new Jo(t,a,o)}return t}function E(){let t=ie();for(;o(L.MultiplicativeBinaryOperator);){let r=e[n++],i=ie();t=new is(r,t,i)}return t}function ie(){let t=ae();for(;o(L.ExponentiationBinaryOperator);){let r=e[n++],i=ae();t=new is(r,t,i)}return t}function ae(){let e=oe();for(;c(`is`);){++n;let t=c(`not`);t&&++n;let r=ce();if(!(r instanceof Xo))throw SyntaxError(`Expected identifier for the test`);e=new cs(e,t,r)}return e}function oe(){let e=se();for(;o(L.Pipe);){++n;let t=ce();if(!(t instanceof Xo))throw SyntaxError(`Expected identifier for the filter`);o(L.OpenParen)&&(t=C(t)),e=new as(e,t)}return e}function se(){let t=e[n];if(t&&(t.type===L.UnaryOperator||t.type===L.AdditiveBinaryOperator)&&(t.value===`-`||t.value===`+`)){let t=e[n++];return new ls(t,se())}return te()}function ce(){let t=e[n++];switch(t.type){case L.NumericLiteral:{let e=t.value;return e.includes(`.`)?new $o(Number(e)):new Qo(Number(e))}case L.StringLiteral:{let r=t.value;for(;o(L.StringLiteral);)r+=e[n++].value;return new es(r)}case L.Identifier:return new Xo(t.value);case L.OpenParen:{let e=h();return r(L.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),e}case L.OpenSquareBracket:{let e=[];for(;!o(L.CloseSquareBracket);)e.push(_()),o(L.Comma)&&++n;return++n,new ts(e)}case L.OpenCurlyBracket:{let e=/* @__PURE__ */ new Map;for(;!o(L.CloseCurlyBracket);){let t=_();r(L.Colon,`Expected colon between key and value in object literal`);let i=_();e.set(t,i),o(L.Comma)&&++n}return++n,new rs(e)}default:throw SyntaxError(`Unexpected token: ${t.type}`)}}for(;n0)for(let i=e;it;i+=n)r.push(i);return r}function vs(e,t,n,r=1){let i=Math.sign(r);i>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));let a=[];for(let o=t;i*oe.toUpperCase())}function bs(e){return xs(/* @__PURE__ */ new Date,e)}function xs(e,t){let n=new Intl.DateTimeFormat(void 0,{month:`long`}),r=new Intl.DateTimeFormat(void 0,{month:`short`}),i=e=>e<10?`0`+e:e.toString();return t.replace(/%[YmdbBHM%]/g,t=>{switch(t){case`%Y`:return e.getFullYear().toString();case`%m`:return i(e.getMonth()+1);case`%d`:return i(e.getDate());case`%b`:return r.format(e);case`%B`:return n.format(e);case`%H`:return i(e.getHours());case`%M`:return i(e.getMinutes());case`%%`:return`%`;default:return t}})}function Ss(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Cs(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?/* @__PURE__ */ RegExp(`(?=)`,`gu`):new RegExp(Ss(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var ws=class extends Error{},Ts=class extends Error{},Es=/* @__PURE__ */ new Map,Ds=class{type=`RuntimeValue`;value;get builtins(){return Es}constructor(e=void 0){this.value=e}__bool__(){return new V(!!this.value)}toString(){return String(this.value)}},R=class extends Ds{type=`IntegerValue`},z=class extends Ds{type=`FloatValue`;toString(){return Object.is(this.value,-0)?`-0.0`:this.value%1==0?this.value.toFixed(1):this.value.toString()}},B=class extends Ds{type=`StringValue`;_builtins;get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`upper`,new Fs(()=>new B(this.value.toUpperCase()))],[`lower`,new Fs(()=>new B(this.value.toLowerCase()))],[`strip`,new Fs(()=>new B(this.value.trim()))],[`title`,new Fs(()=>new B(ys(this.value)))],[`capitalize`,new Fs(()=>new B(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new R(this.value.length)],[`rstrip`,new Fs(()=>new B(this.value.trimEnd()))],[`lstrip`,new Fs(()=>new B(this.value.trimStart()))],[`startswith`,new Fs(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof B)return new V(this.value.startsWith(t.value));if(t instanceof H){for(let e of t.value){if(!(e instanceof B))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new V(!0)}return new V(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new Fs(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof B)return new V(this.value.endsWith(t.value));if(t instanceof H){for(let e of t.value){if(!(e instanceof B))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new V(!0)}return new V(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new Fs(e=>{let t=e[0]??new Is;if(!(t instanceof B||t instanceof Is))throw Error(`sep argument must be a string or null`);let n=e[1]??new R(-1);if(!(n instanceof R))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof Is){let e=this.value.trimStart();for(let{0:t,index:i}of e.matchAll(/\S+/g)){if(n.value!==-1&&r.length>=n.value&&i!==void 0){r.push(t+e.slice(i+t.length));break}r.push(t)}}else{if(t.value===``)throw Error(`empty separator`);r=this.value.split(t.value),n.value!==-1&&r.length>n.value&&r.push(r.splice(n.value).join(t.value))}return new H(r.map(e=>new B(e)))})],[`replace`,new Fs(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof B&&n instanceof B))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new Is:e[2]:new Is,!(r instanceof R||r instanceof Is))throw Error(`replace() count argument must be a number or null`);return new B(Cs(this.value,t.value,n.value,r.value))})]])}},V=class extends Ds{type=`BooleanValue`},Os=/[\x7f-\uffff]/g;function ks(e){return e.replace(Os,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function As(e,t={},n=0,r=!0){let{indent:i=null,ensureAscii:a=!1,separators:o=null,sortKeys:s=!1}=t,c,l;switch(o?[c,l]=o:i?(c=`,`,l=`: `):(c=`, `,l=`: `),e.type){case`NullValue`:return`null`;case`UndefinedValue`:return r?`null`:`undefined`;case`IntegerValue`:case`FloatValue`:case`BooleanValue`:return JSON.stringify(e.value);case`StringValue`:{let t=JSON.stringify(e.value);return a&&(t=ks(t)),t}case`ArrayValue`:case`NamespaceValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=` +`+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>As(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}{let o=Array.from(e.value.entries());s&&(o=o.sort(([e],[t])=>e.localeCompare(t)));let f=o.map(([e,o])=>{let s=JSON.stringify(e);a&&(s=ks(s));let c=`${s}${l}${As(o,t,n+1,r)}`;return i?`${d}${c}`:c});return i?`{${f.join(c)}${u}}`:`{${f.join(c)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var js=class extends Ds{type=`ObjectValue`;_builtins;__bool__(){return new V(this.value.size>0)}get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`get`,new Fs(([e,t])=>{if(!(e instanceof B))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new Is})],[`items`,new Fs(()=>this.items())],[`keys`,new Fs(()=>this.keys())],[`values`,new Fs(()=>this.values())],[`dictsort`,new Fs(e=>{let t=/* @__PURE__ */ new Map,n=e.filter(e=>e instanceof Ms?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new V(!1);if(!(r instanceof V))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new B(`key`);if(!(i instanceof B))throw Error(`by must be a string`);if(![`key`,`value`].includes(i.value))throw Error(`by must be either 'key' or 'value'`);let a=n.at(2)??t.get(`reverse`)??new V(!1);if(!(a instanceof V))throw Error(`reverse must be a boolean`);return new H(Array.from(this.value.entries()).map(([e,t])=>new H([new B(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=e.value[n],s=t.value[n],c=Ks(o,s,r.value);return a.value?-c:c}))})]])}items(){return new H(Array.from(this.value.entries()).map(([e,t])=>new H([new B(e),t])))}keys(){return new H(Array.from(this.value.keys()).map(e=>new B(e)))}values(){return new H(Array.from(this.value.values()))}toString(){return As(this,{},0,!1)}},Ms=class extends js{type=`KeywordArgumentsValue`},Ns=class extends Ds{type=`NamespaceValue`;toString(){return As(this,{},0,!1)}},H=class extends Ds{type=`ArrayValue`;_builtins;get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`length`,new R(this.value.length)]])}__bool__(){return new V(this.value.length>0)}toString(){return As(this,{},0,!1)}},Ps=class extends H{type=`TupleValue`},Fs=class extends Ds{type=`FunctionValue`},Is=class extends Ds{type=`NullValue`},Ls=class extends Ds{type=`UndefinedValue`};function Rs(e){let t;if(e instanceof H?t=e.value:e instanceof B&&(t=Array.from(e.value,e=>new B(e))),!t||t.length!==2)throw Error(`namespace expected an object or an iterable of [key, value] pairs`);let[n,r]=t;if(!(n instanceof B))throw Error(`namespace keys must be strings`);return[n,r]}var zs=class{constructor(e){this.parent=e}variables=/* @__PURE__ */ new Map([[`namespace`,new Fs(e=>{let t=e.slice(),n;if(t.at(-1)instanceof Ms&&(n=t.pop()),t.length>1)throw Error(`namespace expected at most 1 argument, got ${t.length}`);let r=/* @__PURE__ */ new Map;if(t.length===1){let e=t[0];if(e instanceof js)for(let[t,n]of e.value)r.set(t,n);else if(e instanceof H)for(let t of e.value){let[e,n]=Rs(t);r.set(e.value,n)}else throw Error(`'${e.type}' object is not iterable`)}if(n)for(let[e,t]of n.value)r.set(e,t);return new Ns(r)})]]);tests=zs.TESTS;set(e,t){return this.declareVariable(e,Zs(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new Ls}catch{return new Ls}}},Bs=zs;ko(Bs,`TESTS`,/* @__PURE__ */ new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof Fs],[`odd`,e=>{if(!(e instanceof R))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof R))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],[`false`,e=>e.type===`BooleanValue`&&!e.value],[`true`,e=>e.type===`BooleanValue`&&e.value],[`none`,e=>e.type===`NullValue`],[`string`,e=>e.type===`StringValue`],[`number`,e=>e instanceof R||e instanceof z],[`integer`,e=>e instanceof R],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof js],[`sequence`,e=>e instanceof H||e instanceof js||e instanceof B],[`lower`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toLowerCase()}],[`upper`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toUpperCase()}],[`none`,e=>e.type===`NullValue`],[`defined`,e=>e.type!==`UndefinedValue`],[`undefined`,e=>e.type===`UndefinedValue`],[`equalto`,(e,t)=>e.value===t.value],[`eq`,(e,t)=>e.value===t.value]]));function Vs(e){e.set(`false`,!1),e.set(`true`,!0),e.set(`none`,null),e.set(`raise_exception`,e=>{throw Error(e)}),e.set(`range`,_s),e.set(`strftime_now`,bs),e.set(`True`,!0),e.set(`False`,!1),e.set(`None`,null)}function Hs(e){return e instanceof js||e instanceof Ns}function Us(e){return e instanceof R||e instanceof z||e instanceof V}function Ws(e){return e instanceof V?Number(e.value):e.value}function Gs(e,t){let n=t.split(`.`),r=e;for(let e of n)if(Hs(r))r=r.value.get(e)??new Ls;else if(r instanceof H){let t=parseInt(e,10);if(!isNaN(t)&&t>=0&&tr)}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case`StringValue`:{let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),ri)}default:throw Error(`Cannot compare type: ${e.type}`)}}function qs(e){if(e.type===`Identifier`)return{name:e.value};let t=e;return{name:t.key.value,defaultValue:t.value}}function Js(e){return e===`kwargs`||e===`varargs`}function Ys(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=e=>{Js(e)&&n.add(e)},a=e=>{if(e.type===`Identifier`)i(e.value);else if(e.type===`TupleLiteral`)for(let t of e.value)a(t)},o=e=>{i(qs(e).name)},s=e=>{for(let t of e){let e=qs(t);e.defaultValue&&l(e.defaultValue)}},c=e=>{e.type===`CallExpression`&&l(e.args)},l=e=>{if(Array.isArray(e))for(let t of e)l(t);else if(e instanceof Map)for(let[t,n]of e)l(t),l(n);else if(e instanceof Ro)switch(e.type){case`For`:{let t=e;if(a(t.loopvar),t.iterable.type===`SelectExpression`){let e=t.iterable;l(e.lhs),l(t.body),l(t.defaultBlock),l(e.test);return}l(t.iterable),l(t.body),l(t.defaultBlock);return}case`Set`:{let t=e;a(t.assignee),l(t.value),l(t.body);return}case`Macro`:{let t=e;for(let e of t.args)o(e);s(t.args),l(t.body);return}case`CallStatement`:{let t=e;l(t.call);for(let e of t.callerArgs??[])o(e);s(t.callerArgs??[]),l(t.body);return}case`FilterStatement`:{let t=e;l(t.body),c(t.filter);return}case`Identifier`:{let t=e.value;Js(t)&&!n.has(t)&&r.add(t);return}case`MemberExpression`:{let t=e;l(t.object),t.computed&&l(t.property);return}case`FilterExpression`:{let t=e;l(t.operand),c(t.filter);return}case`TestExpression`:l(e.operand);return;case`SelectExpression`:{let t=e;l(t.test),l(t.lhs);return}case`KeywordArgumentExpression`:l(e.value);return;default:for(let t of Object.values(e))l(t)}};for(let t of e)o(t);return l(t),r}var Xs=class{global;constructor(e){this.global=e??new Bs}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let n=this.evaluate(e.left,t);switch(e.operator.value){case`and`:return n.__bool__().value?this.evaluate(e.right,t):n;case`or`:return n.__bool__().value?n:this.evaluate(e.right,t)}let r=this.evaluate(e.right,t);switch(e.operator.value){case`==`:return new V(n.value==r.value);case`!=`:return new V(n.value!=r.value)}if(n instanceof Ls||r instanceof Ls){if(r instanceof Ls&&[`in`,`not in`].includes(e.operator.value))return new V(e.operator.value===`not in`);throw Error(`Cannot perform operation ${e.operator.value} on undefined values`)}if(n instanceof Is||r instanceof Is)throw Error(`Cannot perform operation on null values`);if(e.operator.value===`~`)return new B(n.value.toString()+r.value.toString());if(e.operator.value===`**`&&Us(n)&&Us(r)){let e=Ws(n),t=Ws(r);if(e===0&&t<0)throw Error(`0.0 cannot be raised to a negative power`);let i=e**t;if(!Number.isFinite(i))throw Error(`Exponentiation result is not a finite real number`);return n instanceof z||r instanceof z||t<0?new z(i):new R(i)}if((n instanceof R||n instanceof z)&&(r instanceof R||r instanceof z)){let t=n.value,i=r.value;switch(e.operator.value){case`+`:case`-`:case`*`:{let a=e.operator.value===`+`?t+i:e.operator.value===`-`?t-i:t*i;return n instanceof z||r instanceof z?new z(a):new R(a)}case`/`:return new z(t/i);case`//`:{let e=Math.floor(t/i);return n instanceof z||r instanceof z?new z(e):new R(e)}case`%`:{let e=t%i;return n instanceof z||r instanceof z?new z(e):new R(e)}case`<`:return new V(t`:return new V(t>i);case`>=`:return new V(t>=i);case`<=`:return new V(t<=i)}}else if(n instanceof H&&r instanceof H)switch(e.operator.value){case`+`:return new H(n.value.concat(r.value))}else if(r instanceof H){let t=r.value.find(e=>e.value===n.value)!==void 0;switch(e.operator.value){case`in`:return new V(t);case`not in`:return new V(!t)}}if(n instanceof B||r instanceof B)switch(e.operator.value){case`+`:return new B(n.value.toString()+r.value.toString())}if(n instanceof B&&r instanceof B)switch(e.operator.value){case`in`:return new V(r.value.includes(n.value));case`not in`:return new V(!r.value.includes(n.value))}if(n instanceof B&&r instanceof js)switch(e.operator.value){case`in`:return new V(r.value.has(n.value));case`not in`:return new V(!r.value.has(n.value))}throw SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(e,t){let n=[],r=/* @__PURE__ */ new Map,i=(e,t)=>{if(r.has(e))throw Error(`Got multiple values for keyword argument '${e}'`);r.set(e,t)};for(let r of e)if(r.type===`SpreadExpression`){let e=r,i=this.evaluate(e.argument,t);if(!(i instanceof H))throw Error(`Cannot unpack non-iterable type: ${i.type}`);for(let e of i.value)n.push(e)}else r.type!==`KeywordArgumentExpression`&&r.type!==`KeywordSpreadExpression`&&n.push(this.evaluate(r,t));for(let n of e)if(n.type===`KeywordArgumentExpression`){let e=n;i(e.key.value,this.evaluate(e.value,t))}else if(n.type===`KeywordSpreadExpression`){let e=n,r=this.evaluate(e.argument,t);if(!(r instanceof js))throw Error(`Argument after ** must be a mapping, not ${r.type}`);for(let[e,t]of r.value)i(e,t)}return[n,r]}applyFilter(e,t,n){if(t.type===`Identifier`){let r=t;if(r.value===`safe`)return e;if(r.value===`tojson`)return new B(As(e,{}));if(e instanceof H)switch(r.value){case`list`:return e;case`first`:return e.value[0];case`last`:return e.value[e.value.length-1];case`length`:return new R(e.value.length);case`reverse`:return new H(e.value.slice().reverse());case`sort`:return new H(e.value.slice().sort((e,t)=>Ks(e,t,!1)));case`join`:return new B(e.value.map(e=>e.value).join(``));case`string`:return new B(As(e,{},0,!1));case`unique`:{let t=/* @__PURE__ */ new Set,n=[];for(let r of e.value)t.has(r.value)||(t.add(r.value),n.push(r));return new H(n)}default:throw Error(`Unknown ArrayValue filter: ${r.value}`)}else if(e instanceof B)switch(r.value){case`length`:case`upper`:case`lower`:case`title`:case`capitalize`:{let t=e.builtins.get(r.value);if(t instanceof Fs)return t.value([],n);if(t instanceof R)return t;throw Error(`Unknown StringValue filter: ${r.value}`)}case`trim`:return new B(e.value.trim());case`indent`:return new B(e.value.split(` +`).map((e,t)=>t===0||e.length===0?e:` `+e).join(` +`));case`join`:case`string`:return e;case`int`:{let t=parseInt(e.value,10);return new R(isNaN(t)?0:t)}case`float`:{let t=parseFloat(e.value);return new z(isNaN(t)?0:t)}default:throw Error(`Unknown StringValue filter: ${r.value}`)}else if(e instanceof R||e instanceof z)switch(r.value){case`abs`:return e instanceof R?new R(Math.abs(e.value)):new z(Math.abs(e.value));case`int`:return new R(Math.floor(e.value));case`float`:return new z(e.value);case`string`:return new B(e.toString());default:throw Error(`Unknown NumericValue filter: ${r.value}`)}else if(e instanceof js)switch(r.value){case`items`:return new H(Array.from(e.value.entries()).map(([e,t])=>new H([new B(e),t])));case`length`:return new R(e.value.size);default:{let t=e.builtins.get(r.value);if(t)return t instanceof Fs?t.value([],n):t;throw Error(`Unknown ObjectValue filter: ${r.value}`)}}else if(e instanceof V)switch(r.value){case`bool`:return new V(e.value);case`int`:return new R(+!!e.value);case`float`:return new z(+!!e.value);case`string`:return new B(e.value?`true`:`false`);default:throw Error(`Unknown BooleanValue filter: ${r.value}`)}throw Error(`Cannot apply filter "${r.value}" to type: ${e.type}`)}if(t.type===`CallExpression`){let r=t;if(r.callee.type!==`Identifier`)throw Error(`Unknown filter: ${r.callee.type}`);let i=r.callee.value;if(i===`tojson`){let[,t]=this.evaluateArguments(r.args,n),i=t.get(`indent`)??new Is;if(!(i instanceof R||i instanceof Is))throw Error(`If set, indent must be a number`);let a=t.get(`ensure_ascii`)??new V(!1);if(!(a instanceof V))throw Error(`If set, ensure_ascii must be a boolean`);let o=t.get(`sort_keys`)??new V(!1);if(!(o instanceof V))throw Error(`If set, sort_keys must be a boolean`);let s=t.get(`separators`)??new Is,c=null;if(s instanceof H||s instanceof Ps){if(s.value.length!==2)throw Error(`separators must be a tuple of two strings`);let[e,t]=s.value;if(!(e instanceof B)||!(t instanceof B))throw Error(`separators must be a tuple of two strings`);c=[e.value,t.value]}else if(!(s instanceof Is))throw Error(`If set, separators must be a tuple of two strings`);return new B(As(e,{indent:i.value,ensureAscii:a.value,sortKeys:o.value,separators:c}))}if(i===`join`){let t;if(e instanceof B)t=Array.from(e.value);else if(e instanceof H)t=e.value.map(e=>e.value);else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`);let[a,o]=this.evaluateArguments(r.args,n),s=a.at(0)??o.get(`separator`)??new B(``);if(!(s instanceof B))throw Error(`separator must be a string`);return new B(t.join(s.value))}if(i===`int`||i===`float`){let[t,a]=this.evaluateArguments(r.args,n),o=t.at(0)??a.get(`default`)??(i===`int`?new R(0):new z(0));if(e instanceof B){let t=i===`int`?parseInt(e.value,10):parseFloat(e.value);return isNaN(t)?o:i===`int`?new R(t):new z(t)}if(e instanceof R||e instanceof z)return e;if(e instanceof V)return i===`int`?new R(+!!e.value):new z(+!!e.value);throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}if(i==="default"){let[t,i]=this.evaluateArguments(r.args,n),a=t[0]??new B(``),o=t[1]??i.get(`boolean`)??new V(!1);if(!(o instanceof V))throw Error("`default` filter flag must be a boolean");return e instanceof Ls||o.value&&!e.__bool__().value?a:e}if(e instanceof H){switch(i){case`sort`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`reverse`)??new V(!1);if(!(a instanceof V))throw Error(`reverse must be a boolean`);let o=t.at(1)??i.get(`case_sensitive`)??new V(!1);if(!(o instanceof V))throw Error(`case_sensitive must be a boolean`);let s=t.at(2)??i.get(`attribute`)??new Is;if(!(s instanceof B||s instanceof R||s instanceof Is))throw Error(`attribute must be a string, integer, or null`);let c=e=>s instanceof Is?e:Gs(e,s instanceof R?String(s.value):s.value);return new H(e.value.slice().sort((e,t)=>{let n=Ks(c(e),c(t),o.value);return a.value?-n:n}))}case`selectattr`:case`rejectattr`:{let t=i===`selectattr`;if(e.value.some(e=>!Hs(e)))throw Error(`\`${i}\` can only be applied to array of objects`);if(r.args.some(e=>e.type!==`StringLiteral`))throw Error(`arguments of \`${i}\` must be strings`);let[a,o,s]=r.args.map(e=>this.evaluate(e,n)),c;if(o){let e=n.tests.get(o.value);if(!e)throw Error(`Unknown test: ${o.value}`);c=e}else c=(...e)=>e[0].__bool__().value;return new H(e.value.filter(e=>{let n=e.value.get(a.value),r=n?c(n,s):!1;return t?r:!r}))}case`map`:{let[,t]=this.evaluateArguments(r.args,n);if(t.has(`attribute`)){let n=t.get(`attribute`);if(!(n instanceof B))throw Error(`attribute must be a string`);let r=t.get(`default`);return new H(e.value.map(e=>{if(!Hs(e))throw Error(`items in map must be an object`);let t=Gs(e,n.value);return t instanceof Ls?r??new Ls:t}))}throw Error("`map` expressions without `attribute` set are not currently supported.")}}throw Error(`Unknown ArrayValue filter: ${i}`)}if(e instanceof B){switch(i){case`indent`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`width`)??new R(4);if(!(a instanceof R))throw Error(`width must be a number`);let o=t.at(1)??i.get(`first`)??new V(!1),s=t.at(2)??i.get(`blank`)??new V(!1),c=e.value.split(` +`),l=` `.repeat(a.value);return new B(c.map((e,t)=>!o.value&&t===0||!s.value&&e.length===0?e:l+e).join(` +`))}case`replace`:{let t=e.builtins.get(`replace`);if(!(t instanceof Fs))throw Error(`replace filter not available`);let[i,a]=this.evaluateArguments(r.args,n);return t.value([...i,new Ms(a)],n)}}throw Error(`Unknown StringValue filter: ${i}`)}if(e instanceof js){let t=e.builtins.get(i);if(t&&t instanceof Fs){let[e,i]=this.evaluateArguments(r.args,n);return i.size>0&&e.push(new Ms(i)),t.value(e,n)}throw Error(`Unknown ObjectValue filter: ${i}`)}throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}throw Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let n=this.evaluate(e.operand,t);return this.applyFilter(n,e.filter,t)}evaluateTestExpression(e,t){let n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw Error(`Unknown test: ${e.test.value}`);let i=r(n);return new V(e.negate?!i:i)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new Ls}evaluateUnaryExpression(e,t){let n=this.evaluate(e.argument,t);switch(e.operator.value){case`not`:return new V(!n.value);case`+`:case`-`:{let t=e.operator.value===`-`?-1:1;if(n instanceof R||n instanceof z||n instanceof V){let e=t*(n instanceof V?+!!n.value:n.value);return n instanceof z?new z(e):new R(e)}throw SyntaxError(`Unknown operator "${e.operator.value}" for ${n.type}`)}default:throw SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n=``;for(let r of e){let e=this.evaluate(r,t);e.type!==`NullValue`&&e.type!==`UndefinedValue`&&(n+=e.toString())}return new B(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[n,r]=this.evaluateArguments(e.args,t);r.size>0&&n.push(new Ms(r));let i=this.evaluate(e.callee,t);if(i.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof H||e instanceof B))throw Error(`Slice object must be an array or string`);let r=this.evaluate(t.start,n),i=this.evaluate(t.stop,n),a=this.evaluate(t.step,n);if(!(r instanceof R||r instanceof Ls))throw Error(`Slice start must be numeric or undefined`);if(!(i instanceof R||i instanceof Ls))throw Error(`Slice stop must be numeric or undefined`);if(!(a instanceof R||a instanceof Ls))throw Error(`Slice step must be numeric or undefined`);return e instanceof H?new H(vs(e.value,r.value,i.value,a.value)):new B(vs(Array.from(e.value),r.value,i.value,a.value).join(``))}evaluateMemberExpression(e,t){let n=this.evaluate(e.object,t),r;if(e.computed){if(e.property.type===`SliceExpression`)return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=e.property.type===`IntegerLiteral`?new R(e.property.value):new B(e.property.value);let i;if(Hs(n)){if(!(r instanceof B))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??(n instanceof js?n.builtins.get(r.value):void 0)}else if(n instanceof H||n instanceof B){if(r instanceof R)i=n.value.at(r.value),n instanceof B&&(i=new B(n.value.at(r.value)));else if(r instanceof B)i=n.builtins.get(r.value);else throw Error(`Cannot access property with non-string/non-number: got ${r.type}`)}else{if(!(r instanceof B))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof Ds?i:new Ls}evaluateSet(e,t){let n=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type===`Identifier`){let r=e.assignee.value;t.setVariable(r,n)}else if(e.assignee.type===`TupleLiteral`){let r=e.assignee;if(!(n instanceof H))throw Error(`Cannot unpack non-iterable type in set: ${n.type}`);let i=n.value;if(i.length!==r.value.length)throw Error(`Too ${r.value.length>i.length?`few`:`many`} items to unpack in set`);for(let e=0;et.setVariable(e.loopvar.value,c);else if(e.loopvar.type===`TupleLiteral`){let t=e.loopvar;if(c.type!==`ArrayValue`)throw Error(`Cannot unpack non-iterable type: ${c.type}`);let n=c;if(t.value.length!==n.value.length)throw Error(`Too ${t.value.length>n.value.length?`few`:`many`} items to unpack`);l=e=>{for(let r=0;r0?a[t-1]:new Ls],[`nextitem`,t0)throw Error(`macro ${e} takes no keyword argument '${o.keys().next().value}'`);if(n.has(`varargs`))i.setVariable(`varargs`,new H(a.slice(t.length)));else if(a.length>t.length)throw Error(`macro ${e} takes not more than ${t.length} argument(s)`);for(let[e,t]of s)i.setVariable(e,this.evaluate(t,i))}evaluateMacro(e,t){let n=Ys(e.args,e.body);return t.setVariable(e.name.value,new Fs((t,r)=>{let i=new Bs(r);return this.bindMacroArguments(`'${e.name.value}'`,e.args,n,t,i),this.evaluateBlock(e.body,i)})),new Is}evaluateCallStatement(e,t){let n=e.callerArgs??[],r=Ys(n,e.body),i=new Fs(i=>{let a=new Bs(t);return this.bindMacroArguments(`None`,n,r,i,a),this.evaluateBlock(e.body,a)}),[a,o]=this.evaluateArguments(e.call.args,t);a.push(new Ms(o));let s=this.evaluate(e.call.callee,t);if(s.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${s.type}`);let c=new Bs(t);return c.setVariable(`caller`,i),s.value(a,c)}evaluateFilterStatement(e,t){let n=this.evaluateBlock(e.body,t);return this.applyFilter(n,e.filter,t)}evaluate(e,t){if(!e)return new Ls;switch(e.type){case`Program`:return this.evalProgram(e,t);case`Set`:return this.evaluateSet(e,t);case`If`:return this.evaluateIf(e,t);case`For`:return this.evaluateFor(e,t);case`Macro`:return this.evaluateMacro(e,t);case`CallStatement`:return this.evaluateCallStatement(e,t);case`Break`:throw new ws;case`Continue`:throw new Ts;case`IntegerLiteral`:return new R(e.value);case`FloatLiteral`:return new z(e.value);case`StringLiteral`:return new B(e.value);case`ArrayLiteral`:return new H(e.value.map(e=>this.evaluate(e,t)));case`TupleLiteral`:return new Ps(e.value.map(e=>this.evaluate(e,t)));case`ObjectLiteral`:{let n=/* @__PURE__ */ new Map;for(let[r,i]of e.value){let e=this.evaluate(r,t);if(!(e instanceof B))throw Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(i,t))}return new js(n)}case`Identifier`:return this.evaluateIdentifier(e,t);case`CallExpression`:return this.evaluateCallExpression(e,t);case`MemberExpression`:return this.evaluateMemberExpression(e,t);case`UnaryExpression`:return this.evaluateUnaryExpression(e,t);case`BinaryExpression`:return this.evaluateBinaryExpression(e,t);case`FilterExpression`:return this.evaluateFilterExpression(e,t);case`FilterStatement`:return this.evaluateFilterStatement(e,t);case`TestExpression`:return this.evaluateTestExpression(e,t);case`SelectExpression`:return this.evaluateSelectExpression(e,t);case`Ternary`:return this.evaluateTernaryExpression(e,t);case`Comment`:return new Is;default:throw SyntaxError(`Unknown node type: ${e.type}`)}}};function Zs(e){switch(typeof e){case`number`:return Number.isInteger(e)?new R(e):new z(e);case`string`:return new B(e);case`boolean`:return new V(e);case`undefined`:return new Ls;case`object`:return e===null?new Is:Array.isArray(e)?new H(e.map(Zs)):new js(new Map(Object.entries(e).map(([e,t])=>[e,Zs(t)])));case`function`:return new Fs((t,n)=>Zs(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}var Qs=` +`,$s=`{%- `,ec=` -%}`,tc=Object.freeze({CONDITIONAL:0,LOGICAL_OR:1,LOGICAL_AND:2,LOGICAL_NOT:3,COMPARISON:4,ADDITIVE:5,MULTIPLICATIVE:6,EXPONENTIATION:7,TEST:8,FILTER:9,UNARY_SIGN:10,ATOM:11});function nc(e){switch(e.operator.type){case`ExponentiationBinaryOperator`:return tc.EXPONENTIATION;case`MultiplicativeBinaryOperator`:return tc.MULTIPLICATIVE;case`AdditiveBinaryOperator`:return tc.ADDITIVE;case`ComparisonBinaryOperator`:return tc.COMPARISON;case`Identifier`:return e.operator.value===`and`?tc.LOGICAL_AND:e.operator.value===`in`||e.operator.value===`not in`?tc.COMPARISON:tc.LOGICAL_OR}return tc.LOGICAL_OR}function rc(e){switch(e.type){case`SelectExpression`:case`Ternary`:return tc.CONDITIONAL;case`BinaryExpression`:return nc(e);case`UnaryExpression`:return e.operator.value===`not`?tc.LOGICAL_NOT:tc.UNARY_SIGN;case`TestExpression`:return tc.TEST;case`FilterExpression`:return tc.FILTER;default:return tc.ATOM}}function ic(e,t){let n=gc(e);return rc(e)lc(e,t,n)).join(Qs)}function cc(e){return e.map(e=>gc(e)).join(`, `)}function lc(e,t,n){let r=n.repeat(t);switch(e.type){case`Program`:return sc(e.body,t,n);case`If`:return uc(e,t,n);case`For`:return dc(e,t,n);case`Set`:return fc(e,t,n);case`Macro`:return pc(e,t,n);case`Break`:return r+oc(`break`);case`Continue`:return r+oc(`continue`);case`CallStatement`:return mc(e,t,n);case`FilterStatement`:return hc(e,t,n);case`Comment`:return r+`{# `+e.value+` #}`;default:return r+`{{- `+gc(e)+` -}}`}}function uc(e,t,n){let r=n.repeat(t),i=[],a=e;for(;a&&(i.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type===`If`);)a=a.alternate[0];let o=r+oc(`if`,gc(i[0].test))+Qs+sc(i[0].body,t+1,n);for(let e=1;e0&&(o+=Qs+r+oc(`else`)+Qs+sc(a.alternate,t+1,n)),o+=Qs+r+oc(`endif`),o}function dc(e,t,n){let r=n.repeat(t),i=``;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=`${gc(t.lhs)} if ${gc(t.test)}`}else i=gc(e.iterable);let a=r+oc(`for`,gc(e.loopvar),`in`,i)+Qs+sc(e.body,t+1,n);return e.defaultBlock.length>0&&(a+=Qs+r+oc(`else`)+Qs+sc(e.defaultBlock,t+1,n)),a+=Qs+r+oc(`endfor`),a}function fc(e,t,n){let r=n.repeat(t),i=gc(e.assignee),a=e.value?gc(e.value):``,o=r+oc(`set`,`${i}${e.value?` = `+a:``}`);return e.body.length===0?o:o+Qs+sc(e.body,t+1,n)+Qs+r+oc(`endset`)}function pc(e,t,n){let r=n.repeat(t),i=cc(e.args);return r+oc(`macro`,`${e.name.value}(${i})`)+Qs+sc(e.body,t+1,n)+Qs+r+oc(`endmacro`)}function mc(e,t,n){let r=n.repeat(t),i=e.callerArgs&&e.callerArgs.length>0?`(${cc(e.callerArgs)})`:``,a=gc(e.call),o=r+oc(`call${i}`,a)+Qs;return o+=sc(e.body,t+1,n)+Qs,o+=r+oc(`endcall`),o}function hc(e,t,n){let r=n.repeat(t),i=r+oc(`filter`,e.filter.type===`Identifier`?e.filter.value:gc(e.filter))+Qs;return i+=sc(e.body,t+1,n)+Qs,i+=r+oc(`endfilter`),i}function gc(e){switch(e.type){case`SpreadExpression`:return`*${gc(e.argument)}`;case`KeywordSpreadExpression`:return`**${gc(e.argument)}`;case`Identifier`:return e.value;case`IntegerLiteral`:return`${e.value}`;case`FloatLiteral`:{let t=e.value;return Object.is(t,-0)?`-0.0`:t%1==0?t.toFixed(1):t.toString()}case`StringLiteral`:return JSON.stringify(e.value);case`BinaryExpression`:{let t=e,n=nc(t),r=ic(t.left,n),i=ic(t.right,n+1);return`${r} ${t.operator.value} ${i}`}case`UnaryExpression`:{let t=e,n=t.argument.type===`UnaryExpression`?rc(t):tc.ATOM;return t.operator.value+(t.operator.value===`not`?` `:``)+ic(t.argument,n)}case`CallExpression`:{let t=e,n=cc(t.args);return`${gc(t.callee)}(${n})`}case`MemberExpression`:{let t=e,n=ic(t.object,tc.ATOM),r=gc(t.property);return!t.computed&&t.property.type!==`Identifier`&&t.property.type!==`IntegerLiteral`&&(r=`(${r})`),t.computed?`${n}[${r}]`:`${n}.${r}`}case`FilterExpression`:{let t=e,n=ic(t.operand,tc.FILTER);return t.filter.type===`CallExpression`?`${n} | ${gc(t.filter)}`:`${n} | ${t.filter.value}`}case`SelectExpression`:{let t=e;return`${ic(t.lhs,tc.LOGICAL_OR)} if ${ic(t.test,tc.LOGICAL_OR)}`}case`TestExpression`:{let t=e;return`${ic(t.operand,tc.TEST)} is${t.negate?` not`:``} ${t.test.value}`}case`ArrayLiteral`:case`TupleLiteral`:{let t=cc(e.value),n=e.type===`ArrayLiteral`?`[]`:`()`;return`${n[0]}${t}${n[1]}`}case`ObjectLiteral`:return`{${Array.from(e.value.entries()).map(([e,t])=>`${gc(e)}: ${gc(t)}`).join(`, `)}}`;case`SliceExpression`:{let t=e;return`${t.start?gc(t.start):``}:${t.stop?gc(t.stop):``}${t.step?`:${gc(t.step)}`:``}`}case`KeywordArgumentExpression`:{let t=e;return`${t.key.value}=${gc(t.value)}`}case`Ternary`:{let t=e;return`${ic(t.trueExpr,tc.LOGICAL_OR)} if ${ic(t.condition,tc.LOGICAL_OR)} else ${ic(t.falseExpr,tc.CONDITIONAL)}`}default:throw Error(`Unknown expression type: ${e.type}`)}}var _c=class{parsed;constructor(e){let t=Lo(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=gs(t)}render(e){let t=new Bs;if(Vs(t),e)for(let[n,r]of Object.entries(e))t.set(n,r);return new Xs(t).run(this.parsed).value}format(e){return ac(this.parsed,e?.indent||` `)}},vc={txt:`text/plain`,html:`text/html`,css:`text/css`,js:`text/javascript`,json:`application/json`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`},yc=class e{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=Er.existsSync(e),this.exists){this.status=200,this.statusText=`OK`;let t=Er.statSync(e);this.headers.set(`content-length`,t.size.toString()),this.updateContentType();let n=Er.createReadStream(e);this.body=new ReadableStream({start(e){n.on(`data`,t=>e.enqueue(t)),n.on(`end`,()=>e.close()),n.on(`error`,t=>e.error(t))},cancel(){n.destroy()}})}else this.status=404,this.statusText=`Not Found`,this.body=null}updateContentType(){let e=this.filePath.toString().split(`.`).pop().toLowerCase();this.headers.set(`content-type`,vc[e]??`application/octet-stream`)}clone(){let t=new e(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await Er.promises.readFile(this.filePath)).buffer}async blob(){let e=await Er.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get(`content-type`)})}async text(){return await Er.promises.readFile(this.filePath,`utf8`)}async json(){return JSON.parse(await this.text())}},bc=class{constructor(e){this._mt=/* @__PURE__ */ new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null){if(j.IS_CRYPTO_AVAILABLE){let t=/* @__PURE__ */ new Uint32Array(1);crypto.getRandomValues(t),e=t[0]}else e=Date.now()>>>0}let t=this._mt,n=(e,t)=>Math.imul(e,t)>>>0,r=[];for(let t=e||0;t>0;t=Math.floor(t/4294967296))r.push(t|0);r.length||r.push(0),t[0]=19650218;for(let e=1;e<624;++e)t[e]=n(1812433253,t[e-1]^t[e-1]>>>30)+e>>>0;let i=1,a=0;for(let e=Math.max(624,r.length);e>0;--e,++i,++a)i>=624&&(t[0]=t[623],i=1),a>=r.length&&(a=0),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1664525))+r[a]+a>>>0;for(let e=623;e>0;--e,++i)i>=624&&(t[0]=t[623],i=1),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1566083941))-i>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let t=0;t<624;++t){let n=e[t]&2147483648|e[(t+1)%624]&2147483647;e[t]=(e[(t+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let n=this._gauss_next;if(this._gauss_next=null,n===null){let e=this.random()*2*Math.PI,t=Math.sqrt(-2*Math.log(1-this.random()));n=Math.cos(e)*t,this._gauss_next=Math.sin(e)*t}return e+n*t}shuffle(e){for(let t=e.length-1;t>0;--t){let n=32-Math.clz32(t+1),r=this._int32()>>>32-n;for(;r>t;)r=this._int32()>>>32-n;let i=e[t];e[t]=e[r],e[r]=i}}choices(e,t){return e[xc(this._random_fn,t)]}};function xc(e,t){let n=0;for(let e=0;exc(Cc.random,e),Tc=new bc,Ec=class{constructor(e){this.path=e}async match(e){let t=new yc(A.join(this.path,e));if(t.exists)return t}async put(e,t,n=void 0){let r=A.join(this.path,e),i=r+`.tmp.${j.IS_PROCESS_AVAILABLE?process.pid:Date.now()}.${Tc._int32().toString(36)}`;try{let e=t.headers.get(`Content-Length`),a=parseInt(e??`0`),o=0;await Er.promises.mkdir(A.dirname(r),{recursive:!0});let s=Er.createWriteStream(i),c=t.body.getReader();for(;;){let{done:e,value:t}=await c.read();if(e)break;await new Promise((e,n)=>{s.write(t,t=>{t?n(t):e()})}),o+=t.length;let r=a?o/a*100:0;n?.({progress:r,loaded:o,total:a})}await new Promise((e,t)=>{s.close(n=>n?t(n):e())}),await Er.promises.rename(i,r)}catch(e){try{await Er.promises.unlink(i)}catch{}throw e}}async delete(e){let t=A.join(this.path,e);try{return await Er.promises.unlink(t),!0}catch{return!1}}},Dc={400:`Bad request error occurred while trying to load file`,401:`Unauthorized access to file`,403:`Forbidden access to file`,404:`Could not locate file`,408:`Request timeout error occurred while trying to load file`,500:`Internal server error error occurred while trying to load file`,502:`Bad gateway error occurred while trying to load file`,503:`Service unavailable error occurred while trying to load file`,504:`Gateway timeout error occurred while trying to load file`},Oc=100,kc=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Ac(...e){return e=e.map((t,n)=>(n&&(t=t.replace(/* @__PURE__ */ RegExp(`^/`),``)),n!==e.length-1&&(t=t.replace(/* @__PURE__ */ RegExp(`/$`),``)),t)),e.join(`/`)}function jc(e,t=null,n=null){let r;try{r=new URL(e)}catch{return!1}return!(t&&!t.includes(r.protocol)||n&&!n.includes(r.hostname))}function Mc(e){return!(!kc.test(e)||e.includes(`..`)||e.includes(`--`)||e.endsWith(`.git`)||e.endsWith(`.ipynb`))}function Nc(e,t={},...n){return JSON.stringify([e,t.revision??`main`,t.cache_dir??null,t.local_files_only??!1,...n])}var Pc=class extends Error{constructor(e,{status:t=null}={}){super(e),this.name=`ModelFileNotFoundError`,this.status=t}},Fc=/* @__PURE__ */ new Set([401,403,404]);function Ic(e,t,n){if(!n)return null;let r=`${Dc[e]??`Error (${e}) occurred while trying to load file`}: "${t}".`;throw Fc.has(e)?new Pc(r,{status:e}):Error(r)}async function Lc(e,t,n){let r=e.headers.get(`Content-Length`),i=r?parseInt(r,10):n??0;r===null&&!n&&N.warn(`Unable to determine content-length from response headers. Will expand buffer when needed.`);let a=new Uint8Array(i),o=0,s=e.body.getReader();async function c(){let{done:e,value:n}=await s.read();if(e)return;let r=o+n.length;if(r>i){i=r;let e=new Uint8Array(i);e.set(a),a=e}return a.set(n,o),o=r,t({progress:o/i*100,loaded:o,total:i}),c()}return await c(),a}function Rc(e){return jc(e,[`blob:`])}function zc(e,{allowUnresolved:t=!1}={}){let n;if(typeof location<`u`&&location.href)n=location.href;else if(import.meta.url)n=import.meta.url;else return e;try{return new URL(e,n).href}catch(n){if(!t)throw n;return e}}var Bc=`SHA-256`,Vc=`experimental_transformers-hash-cache`,Hc=e=>({algorithm:Bc,value:e}),Uc=class{#e=null;_getHashCache=()=>(this.#e??=caches.open(Vc),this.#e);static isAvailable=()=>typeof navigator<`u`&&`crossOriginStorage`in navigator;match=async e=>{let t=await this._getFileHash(e);if(t)try{let e=await(await navigator.crossOriginStorage.requestFileHandle(Hc(t))).getFile();return new Response(e,{headers:{"Content-Length":String(e.size)}})}catch{return}};put=async(e,t)=>{let n=await this._getFileHash(e);if(n){let e=await t.blob();await this._storeBlobInCOS(e,n)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{let n=await(await navigator.crossOriginStorage.requestFileHandle(Hc(t),{create:!0,origins:`*`})).createWritable();await n.write(e),await n.close()};_processAndStore=async(e,t)=>{try{let n=[];for await(let e of t)n.push(e);let r=new Blob(n),i=await this._getBlobHash(r);await this._storeBlobInCOS(r,i);try{await(await this._getHashCache()).put(e,new Response(i))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let t=await this._getHashCache(),n=await t.match(e);if(n)return n.text();let r=await this._getLfsFileHash(e);return r?(await t.put(e,new Response(r)),r):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes(`/resolve/`))return null;let t=e.replace(`/resolve/`,`/raw/`);try{let e=(await fetch(t).then(e=>e.text())).match(/^oid sha256:([0-9a-f]+)$/m);return e?e[1]:null}catch{return null}};_getBlobHash=async e=>{let t=await e.arrayBuffer(),n=await crypto.subtle.digest(Bc,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}};async function Wc(e=null){let t=null;if(M.useCustomCache){if(!M.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!M.customCache.match||!M.customCache.put)throw Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=M.customCache}if(!t&&M.experimental_useCrossOriginStorage&&Uc.isAvailable()&&(t=new Uc),!t&&M.useBrowserCache){if(typeof caches>`u`)throw Error(`Browser cache is not available in this environment.`);try{t=await caches.open(M.cacheKey)}catch(e){N.warn(`An error occurred while opening the browser cache:`,e)}}if(!t&&M.useFSCache){if(!j.IS_FS_AVAILABLE)throw Error(`File System Cache is not available in this environment.`);t=new Ec(e??M.cacheDir)}return t}async function Gc(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch{continue}}var Kc=new class{#e;#t;constructor(e){this.#e=e,this.#t=/* @__PURE__ */ new Map}get(e){if(!this.#t.has(e))return;let t=this.#t.get(e);return this.#t.delete(e),this.#t.set(e,t),t}put(e,t){this.#t.has(e)&&this.#t.delete(e),this.#t.set(e,t),this.#t.size>this.#e&&this.#t.delete(this.#t.keys().next().value)}delete(e){return this.#t.delete(e)}clear(){this.#t.clear()}}(100);function qc(e,t){let n=Kc.get(e);if(n!==void 0)return n;let r=t().then(e=>e,t=>(Kc.delete(e),Promise.reject(t)));return Kc.put(e,r),r}async function Jc(e){if(!jc(e,[`http:`,`https:`]))return null;let t=Qc(e);return t.set(`Range`,`bytes=0-0`),M.fetch(e,{method:`GET`,headers:t,cache:`no-store`})}function Yc(e,t,n={}){return qc(Nc(e,n,t),()=>Xc(e,t,n))}async function Xc(e,t,n){let r=await Wc(n?.cache_dir),{localPath:i,remoteURL:a,proposedCacheKey:o,validModelId:s}=$c(e,t,n,r),c=await el(r,i,o);if(c!==void 0&&typeof c!=`string`){let e=c.headers.get(`content-length`),t=c.headers.get(`content-type`);return{exists:!0,size:e?parseInt(e,10):void 0,contentType:t||void 0,fromCache:!0}}if(M.allowLocalModels&&!jc(i,[`http:`,`https:`]))try{let e=await Zc(i);if(typeof e!=`string`&&e.status!==404){let t=e.headers.get(`content-length`),n=e.headers.get(`content-type`);return{exists:!0,size:t?parseInt(t,10):void 0,contentType:n||void 0,fromCache:!1}}}catch{}if(M.allowRemoteModels&&!n.local_files_only&&s){let e=await Jc(a);if(e&&e.status>=200&&e.status<300){let t,n=e.headers.get(`content-type`);if(e.status===206){let n=e.headers.get(`content-range`);if(n){let e=n.match(/bytes \d+-\d+\/(\d+)/);e&&(t=parseInt(e[1],10))}}else if(e.status===200)try{await e.body?.cancel()}catch{}if(t===void 0){let n=e.headers.get(`content-length`);t=n?parseInt(n,10):void 0}return{exists:!0,size:t,contentType:n||void 0,fromCache:!1}}e&&e.status!==404&&e.status!==416&&Ic(e.status,a,!0)}return{exists:!1,fromCache:!1}}async function Zc(e){return M.useFS&&!jc(e,[`http:`,`https:`,`blob:`])?new yc(e instanceof URL?e.protocol===`file:`?e.pathname:e.toString():e):M.fetch(e,{headers:Qc(e)})}function Qc(e){let t=typeof process<`u`&&process?.release?.name===`node`,n=new Headers;if(t){let t=!!{}.TESTING_REMOTELY,r=M.version;if(n.set(`User-Agent`,`transformers.js/${r}; is_ci/${t};`),jc(e,[`http:`,`https:`],[`huggingface.co`,`hf.co`])){let e={}.HF_TOKEN??{}.HF_ACCESS_TOKEN;e&&n.set(`Authorization`,`Bearer ${e}`)}}return n}function $c(e,t,n={},r=null){let i=n.revision??`main`,a=Ac(e,t),o=Mc(e),s=o?Ac(M.localModelPath,a):a,c=Ac(M.remoteHost,M.remotePathTemplate.replaceAll(`{model}`,e).replaceAll(`{revision}`,encodeURIComponent(i)),t);return{requestURL:a,localPath:s,remoteURL:c,proposedCacheKey:r instanceof Ec?i===`main`?a:Ac(e,i,t):c,validModelId:o}}async function el(e,t,n){if(e)return await Gc(e,t,n)}async function tl(e,t,n,r,i,a,o={}){if(await n.match(r)===void 0&&!(typeof Cache<`u`&&n instanceof Cache&&!jc(zc(r,{allowUnresolved:!0}),[`http:`,`https:`]))){if(!a){let a=o.progress_callback?n=>ni(o.progress_callback,{status:`progress`,name:e,file:t,...n}):void 0;await n.put(r,i,a)}else if(typeof i!=`string`){let e=new Headers(i.headers);e.set(`content-length`,a.byteLength.toString()),await n.put(r,new Response(a,{headers:e})).catch(e=>{N.warn(`Unable to add response to browser cache: ${e}.`)})}}}async function nl(e,t,n=!0,r={},i=!1,a=null){let{requestURL:o,localPath:s,remoteURL:c,proposedCacheKey:l,validModelId:u}=$c(e,t,r,a),d,f=!1,p;p=await el(a,s,l);let m=p!==void 0;if(m)d=l;else{if(M.allowLocalModels){if(!jc(o,[`http:`,`https:`]))try{p=await Zc(s),d=s}catch(e){N.warn(`Unable to load from local path "${s}": "${e}"`)}else if(r.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);else if(!M.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}if(p===void 0||typeof p!=`string`&&p.status===404){if(r.local_files_only||!M.allowRemoteModels){if(n)throw new Pc(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${s}".`);return null}if(!u)throw new Pc(`Local file missing at "${s}" and download aborted due to invalid model ID "${e}".`);if(p=await Zc(c),p.status!==200)return Ic(p.status,c,n);d=l}f=a&&typeof Response<`u`&&p instanceof Response&&p.status===200}ni(r.progress_callback,{status:`download`,name:e,file:t});let h;if(!(j.IS_NODE_ENV&&i)){let n;if(typeof p!=`string`){if(!r.progress_callback)n=new Uint8Array(await p.arrayBuffer());else if(m&&typeof navigator<`u`&&/firefox/i.test(navigator.userAgent))n=new Uint8Array(await p.arrayBuffer()),ni(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n.length,total:n.length});else{let i,a=p.headers.get(`content-length`);if(a)i=parseInt(a,10);else try{let n=await Yc(e,t,r);n.size&&(i=n.size)}catch{}n=await Lc(p,n=>{ni(r.progress_callback,{status:`progress`,name:e,file:t,...n})},i)}}h=n}if(f&&d&&typeof p!=`string`&&await tl(e,t,a,d,p,h,r),j.IS_NODE_ENV&&i&&r.progress_callback&&typeof p!=`string`){let n=parseInt(p.headers.get(`content-length`),10)||0;ni(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n,total:n})}if(ni(r.progress_callback,{status:`done`,name:e,file:t}),h){if(!j.IS_NODE_ENV&&i)throw Error(`Cannot return path in a browser environment.`);return h}if(p instanceof yc)return p.filePath;let g=await a?.match(d);if(g instanceof yc)return g.filePath;if(g instanceof Response)return new Uint8Array(await g.arrayBuffer());if(typeof g==`string`)return g;throw Error(`Unable to get model file path or buffer.`)}var rl=/* @__PURE__ */ new Map;async function il(e,t,n=!0,r={},i=!1){if(!M.allowLocalModels){if(r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!M.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}let a=Nc(e,r,t,n,i),{progress_callback:o}=r,s=o instanceof ri?o.loads:rl,c=s.get(a);return c||(ni(o,{status:`initiate`,name:e,file:t}),c=Wc(r.cache_dir).then(a=>nl(e,t,n,r,i,a)),s===rl&&(c=c.finally(()=>rl.delete(a))),s.set(a,c)),await c}async function al(e,t,n=!0,r={}){let i=await il(e,t,n,r,!1);return i===null?null:new TextDecoder(`utf-8`).decode(i)}async function ol(e,t,n=!0,r={}){let i=await al(e,t,n,r);return i===null?{}:JSON.parse(i)}function sl(e,[t,n,r],[i,a],o=`bilinear`,s=!1){let c=a/r,l=i/n,u=new e.constructor(i*a*t),d=n*r,f=i*a;for(let o=0;o=0;--e)i[e]=a,r[e]=t[n[e]],a*=r[e];let a=n.map((e,t)=>i[n.indexOf(t)]),o=new e.constructor(e.length);for(let n=0;n=0;--e)r+=i%t[e]*a[e],i=Math.floor(i/t[e]);o[r]=e[n]}return[o,r]}function ll(e){let t=fl(e)[0],n=e.map(e=>Math.exp(e-t)),r=n.reduce((e,t)=>e+t,0);return n.map(e=>e/r)}function ul(e){let t=fl(e)[0],n=0;for(let r=0;re-t-r)}function dl(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;rt&&(t=e[r],n=r);return[t,n]}function pl(e){return e>0&&!(e&e-1)}var ml=class{constructor(e){if(this.size=e|0,this.size<=1||!pl(this.size))throw Error(`FFT size must be a power of two larger than 1`);this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let e=0;ee;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<>>t&3)<>>1);for(let t=0;t>>1]=e[t];return n}toComplexArray(e,t){let n=t||this.createComplexArray();for(let t=0;t>>1],n[t+1]=0;return n}transform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,-1);for(let t=0;t>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>2;for(o=0;o>>1,i>>>1)}else for(o=0,s=0;o>>1,i>>>1,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>1,s=t>>>1,c=s>>>1;for(o=0;o>>1;for(let t=2;t>1;++t){let n=(t+1-e)**2/2,r=Math.sqrt(s**2+c**2)**n,o=n*Math.atan2(c,s),l=2*t;i[l]=r*Math.cos(o),i[l+1]=r*Math.sin(o),a[l]=i[l],a[l+1]=-i[l+1]}this._slicedChirpBuffer=i.subarray(t,n),this._f=new ml(r>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,n){let r=this._buffer1,i=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,s=this._chirpBuffer,c=this._slicedChirpBuffer,l=this._a;if(n)for(let e=0;e>1];r[e]=i*c[e],r[n]=i*c[n]}else for(let e=0;e=e.length&&(i=2*(e.length-1)-i),r[a++]=e[i]}r.sort(),n[t]=r[i]}return n}function vl(e,t){let n=10**t;return Math.round(e*n)/n}function yl(e){let t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function bl(e){let t=e.length,n=e[0].length,r=[t+1,n+1],i=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));i[0][0]=0;let a=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let t=1;t0||s>0;)switch(c.push(o-1),l.push(s-1),a[o][s]){case 0:--o,--s;break;case 1:--o;break;case 2:--s;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${s}]. Please file a bug report.`)}return c.reverse(),l.reverse(),[c,l]}var xl=/* @__PURE__ */ (function(){let e=null;return function(t){if(!e){e=/* @__PURE__ */ new Float32Array(65536);let t=/* @__PURE__ */ new ArrayBuffer(4),n=new Uint32Array(t),r=new Float32Array(t);for(let t=0;t>10,s=t&1023;if(o===31)i=a|2139095040|s<<13;else if(o===0){if(s===0)i=a;else{let e=113;for(;!(s&1024);)s<<=1,--e;s&=-1025,i=a|e<<23|s<<13}}else i=a|o+112<<23|s<<13;n[0]=i,e[t]=r[0]}}let n=t.length,r=e,i=new Float32Array(n);for(let e=0;e[`webgpu`,`cuda`,`dml`,`webnn-gpu`].includes(e))}if(kl.includes(e))return[El[e]??e];throw Error(`Unsupported device: "${e}". Should be one of: ${kl.join(`, `)}.`)}var Fl=Promise.resolve(),Il=null;async function Ll(){if(Il)return Il;if(!(M.useWasmCache&&typeof Hl?.wasm?.wasmPaths==`object`&&Hl?.wasm?.wasmPaths?.wasm&&Hl?.wasm?.wasmPaths?.mjs)){if(j.IS_DENO_WEB_RUNTIME)throw Error(`env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.`);return Il=Promise.resolve(),Il}return Il=(async()=>{let e=Hl.wasm.wasmPaths,t=!1;await Promise.all([e.wasm&&!Rc(e.wasm)?(async()=>{try{let n=await wl(zc(e.wasm));n&&(Hl.wasm.wasmBinary=n,t=!0)}catch(e){N.warn(`Failed to pre-load WASM binary:`,e)}})():Promise.resolve(),e.mjs&&!Rc(e.mjs)?(async()=>{try{let t=await Tl(zc(e.mjs));t&&(Hl.wasm.wasmPaths.mjs=t)}catch(e){N.warn(`Failed to pre-load WASM factory:`,e)}})():Promise.resolve()]),t||(Hl.wasm.wasmPaths.mjs=e.mjs)})(),Il}async function Rl(e,t,n){await Ll();let r=Dl(M.logLevel??Qr.WARNING),i=()=>Nl.create(e,{logSeverityLevel:r,...t}),a=await(j.IS_WEB_ENV?Fl=Fl.then(i):i());return a.config=n,a}var zl=Promise.resolve();async function Bl(e,t){let n=()=>e.run(t);return j.IS_WEB_ENV?zl=zl.then(n):n()}function Vl(e){return e instanceof jl.Tensor}var Hl=jl?.env;function Ul(){return Hl?.wasm?.proxy}if(Hl){let e=function(e){Hl.logLevel=Ol[Dl(e)]};if(Hl.wasm){if(!(typeof ServiceWorkerGlobalScope<`u`&&self instanceof ServiceWorkerGlobalScope)&&Hl.versions?.web&&!Hl.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Hl.versions.web}/dist/`,t=`.asyncify`;j.IS_SAFARI_BELOW_26&&!j.IS_WEBGPU_AVAILABLE&&(t=``),Hl.wasm.wasmPaths={mjs:`${e}ort-wasm-simd-threaded${t}.mjs`,wasm:`${e}ort-wasm-simd-threaded${t}.wasm`}}Hl.wasm.proxy=!1}Hl.webgpu&&(Hl.webgpu.powerPreference=`high-performance`),e(M.logLevel??Qr.WARNING),M.backends.onnx={...Hl,setLogLevel:e}}var Wl=async(e,t,n)=>{let r=await Rl(new Uint8Array(e),t);return(async e=>{let t=Ul(),i=Object.fromEntries(Object.entries(e).map(([e,n])=>[e,(t?n.clone():n).ort_tensor])),a=await Bl(r,i);return Array.isArray(n)?n.map(e=>new U(a[e])):new U(a[n])})},Gl=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||=Wl([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,`y`),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||=Wl([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,`y`),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||=Wl([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,`y`),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||=Wl([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,`c`),this._matmul}static get stft(){return this._stft||=Wl([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,`o`),this._stft}static get rfft(){return this._rfft||=Wl([8,9,58,93,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,19,10,1,120,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,1,90,11,10,1,97,18,6,10,4,8,7,18,0,98,19,10,1,121,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,2,66,2,16,20],this.session_options,`y`),this._rfft}static get top_k(){return this._top_k||=Wl([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,[`v`,`i`]),this._top_k}static get slice(){return this._slice||=Wl([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,`y`),this._slice}},Kl=Object.freeze({auto:`auto`,gpu:`gpu`,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:`webnn`,"webnn-npu":`webnn-npu`,"webnn-gpu":`webnn-gpu`,"webnn-cpu":`webnn-cpu`}),ql=j.IS_NODE_ENV?`cpu`:`wasm`;function Jl(e,t,{warn:n}={}){return e?typeof e==`string`?e:e.hasOwnProperty(t)?e[t]:(n&&n(`device not specified for "${t}". Using the default device (${ql}).`),ql):ql}var Yl=/* @__PURE__ */ (function(){let e;return async function(){if(e===void 0){if(!j.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has(`shader-f16`)}catch{e=!1}}return e}})(),Xl=Object.freeze({auto:`auto`,fp32:`fp32`,fp16:`fp16`,q8:`q8`,int8:`int8`,uint8:`uint8`,q4:`q4`,bnb4:`bnb4`,q4f16:`q4f16`,q2:`q2`,q2f16:`q2f16`,q1:`q1`,q1f16:`q1f16`}),Zl=Xl.fp32,Ql=Object.freeze({[Kl.wasm]:Xl.q8}),$l=Object.freeze({[Xl.fp32]:``,[Xl.fp16]:`_fp16`,[Xl.int8]:`_int8`,[Xl.uint8]:`_uint8`,[Xl.q8]:`_quantized`,[Xl.q4]:`_q4`,[Xl.q2]:`_q2`,[Xl.q1]:`_q1`,[Xl.q4f16]:`_q4f16`,[Xl.q2f16]:`_q2f16`,[Xl.q1f16]:`_q1f16`,[Xl.bnb4]:`_bnb4`});function eu(e,t,n,{configDtype:r=null,warn:i}={}){let a,o=!1;e&&typeof e!=`string`?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let s;if(a===Xl.auto){if(r){let e=typeof r==`string`?r:r?.[t];if(e&&e!==Xl.auto&&Xl.hasOwnProperty(e))return e}s=Ql[n]??Zl}else s=a&&Xl.hasOwnProperty(a)?a:Ql[n]??Zl;return o&&i&&i(`dtype not specified for "${t}". Using the default dtype (${s}) for this device (${n}).`),s}var tu=Object.freeze({float32:Float32Array,float16:typeof Float16Array<`u`?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array}),U=class e{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return this.ort_tensor=Vl(e[0])?e[0]:new Cr(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if(typeof t==`string`){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let n=t.reduce((e,t)=>e*t);for(let r=0;r0){let e=r.reduce((e,t)=>e*t);return this._subarray(t,e,r)}return new e(this.type,[this.data[t]],r)}_subarray(t,n,r){let i=t*n,a=(t+1)*n,o=`subarray`in this.data?this.data.subarray(i,a):this.data.slice(i,a);return new e(this.type,o,r)}item(){let e=this.data;if(e.length!==1)throw Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return nu(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let t=0;t0||r>0&&n<0?r+n:r}return this}clone(){return new e(this.type,this.data.slice(),this.dims.slice())}slice(...t){let n=[],r=[];for(let e=0;ea)throw Error(`Invalid slice: ${i}`);let o=[Math.max(t,0),Math.min(a,this.dims[e])];r.push(o),n.push(o[1]-o[0])}else throw Error(`Invalid slice: ${i}`)}let i=r.map(([e,t])=>t-e),a=i.reduce((e,t)=>e*t),o=this.data,s=new o.constructor(a),c=this.stride(),l=!0;for(let e=1;e=0;--n){let e=i[n];t+=(a%e+r[n][0])*c[n],a=Math.floor(a/e)}s[e]=o[t]}return new e(this.type,s,n)}permute(...e){return ru(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(t=`fro`,n=null,r=!1){if(t===`fro`)t=2;else if(typeof t==`string`)throw Error(`Unsupported norm: ${t}`);let i=this.data,a=i instanceof BigInt64Array||i instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,s;if(a?(o=(e,t)=>e+t,s=0n):(o=(e,n)=>e+n**t,s=0),n===null){let n=i.reduce(o,s);return t!==1&&(n**=1/t),new e(this.type,[n],[])}let[c,l,u]=gu(o,this,n,r);if(t!==1)for(let e=0;e=0;--r){let e=this.dims[r];if(r!==t){let t=i%e;n+=t*a,a*=this.dims[r]}i=Math.floor(i/e)}r[e]/=i[n]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return yu(this.dims)}squeeze(t=null){return new e(this.type,this.data,du(this.dims,t))}squeeze_(e=null){return this.dims=du(this.dims,e),this}unsqueeze(t){return new e(this.type,this.data,fu(this.dims,t))}unsqueeze_(e){return this.dims=fu(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),i=this.dims.slice(t+1);return this.dims=[...n,r.reduce((e,t)=>e*t,1),...i],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...t){let n=-1;for(let e=0;er===n?e:e*t,1);t[n]=r.length/e}return new e(this.type,r,t)}neg_(){let e=this.data;for(let t=0;tt);return new e(`bool`,n,this.dims)}lt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;eMath.min(e,t),this,t,n,1/0);return new e(r,i,a)}max(t=null,n=!1){if(t===null){let t=fl(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=gu((e,t)=>Math.max(e,t),this,t,n,-1/0);return new e(r,i,a)}argmin(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=dl(this.data)[1];return new e(`int64`,[BigInt(r)],[])}argmax(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=fl(this.data)[1];return new e(`int64`,[BigInt(r)],[])}repeat(...t){if(t.lengthe===1)){if(t.length===this.dims.length)return this.clone();let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims);return new e(this.type,this.data.slice(),r)}let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims),i=r.map((e,n)=>e*t[n]),a=i.reduce((e,t)=>e*t,1),o=this.data,s=new o.constructor(a),c=yu(r),l=yu(i);for(let e=0;eBigInt(Math.floor(e)):BigInt;else if(this.type===`float16`&&t==`float32`&&this.data instanceof Uint16Array)return new e(t,xl(this.data),this.dims);return new e(t,tu[t].from(this.data,n),this.dims)}};function nu(e,t){let n=e.length;if(n!==(t.length===0?1:t.reduce((e,t)=>e*t)))throw Error(`cannot reshape array of size ${n} into shape (${t})`);let r=e;for(let e=t.length-1;e>=0;e--)r=r.reduce((n,r)=>{let i=n[n.length-1];return i.lengthnew U(`int64`,e,[e.length]);async function lu(e,t,n,r,i){return await(await Gl.slice)({x:e,s:cu(t),e:cu(n),a:cu(r),t:cu(i??Array(r.length).fill(1))})}function uu(e,t){let n=e.data,r=t.data,i=[e.dims[0],e.dims[2]],a=new n.constructor(i[0]*i[1]),[o,s,c]=e.dims,l=0;for(let e=0;ee!==1):typeof t==`number`?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,n)=>e!==1||!t.includes(n))),e}function fu(e,t){return t=pu(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function pu(e,t,n=null,r=!0){if(e<-t||e>=t){if(r)throw Error(`IndexError: index ${e} is out of bounds for dimension${n===null?``:` `+n} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function mu(e,t=0){t=pu(t,e[0].dims.length);let n=e[0].dims.slice();n[t]=e.reduce((e,n)=>e+n.dims[t],0);let r=n.reduce((e,t)=>e*t,1),i=new e[0].data.constructor(r),a=e[0].type;if(t===0){let t=0;for(let n of e){let e=n.data;i.set(e,t),t+=e.length}}else{let r=0;for(let a=0;a=0;--i){let e=s[i],l=o%e;i===t&&(l+=r),a+=l*c,c*=n[i],o=Math.floor(o/e)}i[a]=o[e]}r+=s[t]}}return new U(a,i,n)}function hu(e,t=0){return mu(e.map(e=>e.unsqueeze(t)),t)}function gu(e,t,n,r=!1,i=null){let a=t.data,o=t.dims;n=pu(n,o.length);let s=o.slice();s[n]=1;let c=new a.constructor(a.length/o[n]);i!==null&&c.fill(i);for(let t=0;t=0;--e){let t=o[e];if(e!==n){let n=i%t;r+=n*a,a*=s[e]}i=Math.floor(i/t)}c[r]=e(c[r],a[t],t,r)}return r||s.splice(n,1),[t.type,c,s]}function _u(e,t=null,n=1,r=!1){let i=e.data,a=e.dims;if(t===null){let t=i.reduce((e,t)=>e+t,0)/i.length,r=Math.sqrt(i.reduce((e,n)=>e+(n-t)**2,0)/(i.length-n)),a=new U(e.type,[t],[]);return[new U(e.type,[r],[]),a]}t=pu(t,a.length);let o=vu(e,t,r),s=o.data,[c,l,u]=gu((e,t,n,r)=>e+(t-s[r])**2,e,t,r);for(let e=0;ee+t,0);return new U(e.type,[t/i.length],[])}t=pu(t,r.length);let[a,o,s]=gu((e,t)=>e+t,e,t,n);if(r[t]!==1)for(let e=0;e=0;--n)t[n]=r,r*=e[n];return t}function bu(e,t,n,r){return new U(n,new r(e.reduce((e,t)=>e*t,1)).fill(t),e)}function xu(e,t){let n,r;if(typeof t==`number`)n=`float32`,r=Float32Array;else if(typeof t==`bigint`)n=`int64`,r=BigInt64Array;else if(typeof t==`boolean`)n=`bool`,r=Uint8Array;else throw Error(`Unsupported data type: ${typeof t}`);return bu(e,t,n,r)}function Su(e,t){return xu(e.dims,t)}function Cu(e){return bu(e,1n,`int64`,BigInt64Array)}function wu(e){return Cu(e.dims)}function Tu(e){return bu(e,0n,`int64`,BigInt64Array)}function Eu(e){return Tu(e.dims)}function Du(e){let t=e.reduce((e,t)=>e*t,1);return new U(`float32`,Float32Array.from({length:t},()=>Cc.gauss()),e)}function Ou(e,t){if(e.dims.length!==2)throw Error(`The tensor must have 2 dimensions`);if(e.dims.at(-1)%8!=0)throw Error(`The last dimension of the tensor must be a multiple of 8`);if(![`binary`,`ubinary`].includes(t))throw Error(`The precision must be either 'binary' or 'ubinary'`);let n=t===`binary`,r=n?`int8`:`uint8`,i=n?Int8Array:Uint8Array,a=e.data,o=new i(a.length/8);for(let e=0;e0),r=Math.floor(e/8),i=e%8;o[r]|=t<<7-i,n&&i===0&&(o[r]-=128)}return new U(r,o,[e.dims[0],e.dims[1]/8])}async function ku(e){if(!e)throw Error(`modelId is required for get_tokenizer_files`);return(await Yc(e,`tokenizer_config.json`,{})).exists?[`tokenizer.json`,`tokenizer_config.json`]:[]}async function Au(e,t){let n=await ku(e);return await Promise.all(n.map(n=>ol(e,n,!0,t)))}function ju(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var Mu=[`bos_token`,`eos_token`,`unk_token`,`sep_token`,`pad_token`,`cls_token`,`mask_token`];function Nu(e,t,n,r){for(let i of Object.keys(e)){let a=t-e[i].length,o=n(i),s=Array(a).fill(o);e[i]=r===`right`?si(e[i],s):si(s,e[i])}}function Pu(e,t){for(let n of Object.keys(e))e[n].length=t}function Fu(e,...t){for(let n of t){if(!Object.hasOwn(e,n))continue;let t=e[n];if(t){if(typeof t==`object`){if(t.__type===`AddedToken`)return t.content;throw Error(`Unknown token: ${t}`)}return t}}return null}function Iu(e){let t=[];for(let n of e.get_added_tokens_decoder().values())n.special&&t.push(n);return t}var W=class extends ti{return_token_type_ids=!1;padding_side=`right`;constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new Eo(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Fu(t,`mask_token`),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Fu(t,`pad_token`,`eos_token`),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Fu(t,`sep_token`),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Fu(t,`unk_token`),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Fu(t,`bos_token`),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Fu(t,`eos_token`),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){let e=/* @__PURE__ */ Object.create(null);for(let{name:t,template:n}of this.chat_template){if(typeof t!=`string`||typeof n!=`string`)throw Error(`Chat template must be a list of objects with "name" and "template" properties`);e[t]=n}this.chat_template=e}this._compiled_template_cache=/* @__PURE__ */ new Map;let n=Iu(this._tokenizer);this.all_special_ids=n.map(e=>e.id),this.all_special_tokens=n.map(e=>e.content)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let o=await Au(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a});return new this(...o)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e==`string`?this._tokenizer.token_to_id(e):e.map(e=>this._tokenizer.token_to_id(e))}_call(e,t={}){let{text_pair:n=null,add_special_tokens:r=!0,padding:i=!1,return_token_type_ids:a=null}=t,{truncation:o=null,max_length:s=null}=t,c=t.return_tensor??!0,l=Array.isArray(e),u;if(l){if(e.length===0)throw Error(`text array must be non-empty`);if(n!==null){if(!Array.isArray(n))throw Error(`text_pair must also be an array`);if(e.length!==n.length)throw Error(`text and text_pair must have the same length`);u=e.map((e,t)=>this._encode_plus(e,{text_pair:n[t],add_special_tokens:r,return_token_type_ids:a}))}else u=e.map(e=>this._encode_plus(e,{add_special_tokens:r,return_token_type_ids:a}))}else{if(e==null)throw Error(`text may not be null or undefined`);if(Array.isArray(n))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");u=[this._encode_plus(e,{text_pair:n,add_special_tokens:r,return_token_type_ids:a})]}if(s===null?s=this.model_max_length:o===null&&(i===!0?(N.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),s=this.model_max_length):i===!1&&(N.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),i===!0&&(s=Math.min(fl(u.map(e=>e.input_ids.length))[0],s??1/0)),s=Math.min(s,this.model_max_length??1/0),i||o)for(let e=0;es?o&&Pu(u[e],s):i&&Nu(u[e],s,e=>e===`input_ids`?this.pad_token_id:0,this.padding_side);let d={};if(c){if(!(i&&o)&&u.some(e=>{for(let t of Object.keys(e))if(e[t].length!==u[0][t]?.length)return!0;return!1}))throw Error(`Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.`);let e=[u.length,u[0].input_ids.length];for(let t of Object.keys(u[0]))d[t]=new U(`int64`,BigInt64Array.from(u.flatMap(e=>e[t]).map(BigInt)),e)}else{for(let e of Object.keys(u[0]))d[e]=u.map(t=>t[e]);if(!l)for(let e of Object.keys(d))d[e]=d[e][0]}return d}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{ids:i,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r??this.return_token_type_ids});return{input_ids:i,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:n})}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r}).ids}batch_decode(e,t={}){return e instanceof U&&(e=e.tolist()),e.map(e=>this.decode(e,t))}decode(e,t={}){if(e instanceof U&&(e=ju(e)),!Array.isArray(e)||e.length===0||!ii(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:n=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:n})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template==`object`){let n=this.chat_template;if(e!==null&&Object.hasOwn(n,e))e=n[e];else if(e===null){if(t!==null&&`tool_use`in n)e=n.tool_use;else if(`default`in n)e=n.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(n).sort()}.`)}}else if(e===null){if(this.chat_template)e=this.chat_template;else throw Error(`Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating`)}return e}apply_chat_template(e,t={}){let{tools:n=null,documents:r=null,chat_template:i=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:s=!1,truncation:c=!1,max_length:l=null,return_tensor:u=!0,return_dict:d=!0,tokenizer_kwargs:f={},...p}=t;if(i=this.get_chat_template({chat_template:i,tools:n}),typeof i!=`string`)throw Error(`chat_template must be a string, but got ${typeof i}`);let m=this._compiled_template_cache.get(i);m===void 0&&(m=new _c(i),this._compiled_template_cache.set(i,m));let h=/* @__PURE__ */ Object.create(null);for(let e of Mu){let t=Fu(this.config,e);t&&(h[e]=t)}let g=m.render({messages:e,add_generation_prompt:a,tools:n,documents:r,...h,...p});if(o){let e=this._call(g,{add_special_tokens:!1,padding:s,truncation:c,max_length:l,return_tensor:u,...f});return d?e:e.input_ids}return g}};function Lu(e,t,n,r){if(!(`language_codes`in e)||!Array.isArray(e.language_codes))throw Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!(`languageRegex`in e)||!(e.languageRegex instanceof RegExp))throw Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!(`lang_to_token`in e)||typeof e.lang_to_token!=`function`)throw Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let i=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);if(i!==void 0){if(!e.language_codes.includes(i))throw Error(`Source language code "${i}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);let t=e._tokenizer.post_processor?.config;if(t&&`single`in t){for(let n of t.single)if(`SpecialToken`in n&&e.languageRegex.test(n.SpecialToken.id)){n.SpecialToken.id=e.lang_to_token(i);break}}}return r.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,n)}var Ru={};Tr(Ru,{AlbertTokenizer:()=>zu,AutoTokenizer:()=>G,BartTokenizer:()=>Bu,BertTokenizer:()=>Vu,BlenderbotSmallTokenizer:()=>Hu,BlenderbotTokenizer:()=>Uu,BloomTokenizer:()=>Wu,CLIPTokenizer:()=>Ku,CamembertTokenizer:()=>Gu,CodeGenTokenizer:()=>Ju,CodeLlamaTokenizer:()=>qu,CohereAsrTokenizer:()=>Xu,CohereTokenizer:()=>Yu,ConvBertTokenizer:()=>Zu,DebertaTokenizer:()=>$u,DebertaV2Tokenizer:()=>Qu,DistilBertTokenizer:()=>ed,ElectraTokenizer:()=>td,EsmTokenizer:()=>nd,FalconTokenizer:()=>rd,GPT2Tokenizer:()=>od,GPTNeoXTokenizer:()=>ad,GemmaTokenizer:()=>id,HerbertTokenizer:()=>sd,LlamaTokenizer:()=>cd,M2M100Tokenizer:()=>ld,MBart50Tokenizer:()=>fd,MBartTokenizer:()=>dd,MPNetTokenizer:()=>hd,MarianTokenizer:()=>ud,MgpstrTokenizer:()=>pd,MobileBertTokenizer:()=>md,NllbTokenizer:()=>gd,NougatTokenizer:()=>_d,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>vd,RoFormerTokenizer:()=>bd,RobertaTokenizer:()=>yd,SiglipTokenizer:()=>xd,SpeechT5Tokenizer:()=>Sd,SqueezeBertTokenizer:()=>Cd,T5Tokenizer:()=>wd,TokenizersBackend:()=>W,VitsTokenizer:()=>Ed,Wav2Vec2CTCTokenizer:()=>Dd,WhisperTokenizer:()=>Pd,XLMRobertaTokenizer:()=>Fd,XLMTokenizer:()=>Id});var zu=class extends W{return_token_type_ids=!0},Bu=class extends W{},Vu=class extends W{return_token_type_ids=!0},Hu=class extends W{},Uu=class extends W{},Wu=class extends W{},Gu=class extends W{},Ku=class extends W{},qu=class extends W{},Ju=class extends W{},Yu=class extends W{},Xu=class extends W{},Zu=class extends W{return_token_type_ids=!0},Qu=class extends W{return_token_type_ids=!0},$u=class extends W{return_token_type_ids=!0},ed=class extends W{},td=class extends W{return_token_type_ids=!0},nd=class extends W{},rd=class extends W{},id=class extends W{},ad=class extends W{},od=class extends W{},sd=class extends W{return_token_type_ids=!0},cd=class extends W{padding_side=`left`},ld=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e.slice(2,-2)),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return Lu(this,e,t,n)}},ud=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(e=>this.languageRegex.test(e)),N.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[t,...n]=e.trim().split(this.languageRegex);if(n.length===0)return super._encode_text(t);if(n.length===2){let[e,t]=n;return this.supported_language_codes.includes(e)||N.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),si([e],super._encode_text(t))}}},dd=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Lu(this,e,t,n)}},fd=class extends dd{},pd=class extends W{},md=class extends W{return_token_type_ids=!0},hd=class extends W{},gd=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Lu(this,e,t,n)}},_d=class extends W{},vd=class extends W{},yd=class extends W{},bd=class extends W{return_token_type_ids=!0},xd=class extends W{},Sd=class extends W{},Cd=class extends W{return_token_type_ids=!0},wd=class extends W{},Td=class extends po{decode_chain(e){let t=``;for(let n=1;n[t,e]),[`burmese`,`my`],[`valencian`,`ca`],[`flemish`,`nl`],[`haitian`,`ht`],[`letzeburgesch`,`lb`],[`pushto`,`ps`],[`panjabi`,`pa`],[`moldavian`,`ro`],[`moldovan`,`ro`],[`sinhalese`,`si`],[`castilian`,`es`]]);function jd(e){e=e.toLowerCase();let t=Ad.get(e);if(t===void 0){let n=e.match(/^<\|([a-z]{2})\|>$/);if(n&&(e=n[1]),kd.has(e))t=e;else{let t=e.length===2?kd.keys():kd.values();throw Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(t))}`)}}return t}var Md=/* @__PURE__ */ RegExp(`^[\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]+$`,`gu`),Nd=.1,Pd=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id(`<|notimestamps|>`)+1}_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:i=!0}={}){if(r===null)throw Error(`Must specify time_precision`);let a=null,o=t===`word`;function s(){return{language:a,timestamp:[null,null],text:``}}let c=[],l=s(),u=0,d=this.timestamp_begin,f=d+1500,p=[],m=[],h=!1,g=null,_=new Set(this.all_special_ids);for(let n of e){let e=n.tokens,i=o?n.token_timestamps:null,v=null,y=d;if(`stride`in n){let[t,i,a]=n.stride;if(u-=i,g=t-a,i&&(y=i/r+d),a)for(let t=e.length-1;t>=0;--t){let n=Number(e[t]);if(n>=d){if(v!==null&&(n-d)*r=d&&g<=f){let e=vl((g-d)*r+u,2);if(v!==null&&g>=v)h=!0;else if(h||p.length>0&&g0&&l.timestamp[1]!==null))for(let e of l.words)e.timestamp[1]>l.timestamp[1]&&l.timestamp[1]>=e.timestamp[0]&&(e.timestamp[1]=l.timestamp[1]);c.push(l),p=[],b=[],m=[],x=[],l=s()}}else if(b.push(g),o){let e=vl(i[n]+u,2),t;if(n+10?(p.push(b),o&&m.push(x)):p.every(e=>e.length===0)&&(l=s(),p=[],b=[],m=[],x=[])}if(p.length>0){if(i&&t)throw Error(`Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.`);let[e,n]=this.findLongestCommonSequence(p,m),r=this.decode(e);l.text=r,o&&(l.words=this.collateWordTimestamps(e,n,a)),c.push(l)}let v=/* @__PURE__ */ Object.create(null),y=c.map(e=>e.text).join(``);if(t||n){for(let e=0;e0,o=a?[]:null,s=a?t[0]:null;for(let c=1;ce===g[n]&&s[i+n][0]-Nd<=t[c][m+n][0]).length:p.filter((e,t)=>e===g[t]).length;let v=e/1e4,y=_/e+v;_>1&&y>u&&(u=y,d=[i,o,m,h])}let[p,m,h,g]=d,_=Math.floor((m+p)/2),v=Math.floor((g+h)/2);if(a&&u===0&&r>0){let e=s[r-1][0],n=t[c].findIndex(t=>t[0]>=e);v=n===-1?l.length:n}i.push(...n.slice(0,_)),n=l.slice(v),r=n.length,a&&(o.push(...s.slice(0,_)),s=t[c].slice(v))}return i.push(...n),a?(o.push(...s),[i,o]):[i,[]]}collateWordTimestamps(e,t,n){let[r,i,a]=this.combineTokensIntoWords(e,n),o=[];for(let e=0;e=r){let e=((t-r)*n).toFixed(2);i.push(`<|${e}|>`),i.push([])}else i[i.length-1].push(t);return i=i.map(e=>typeof e==`string`?e:super.decode(e,t)),i.join(``)}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],i=[],a=[],o=[],s=0;for(let c=0;c=this._tokenizer.token_to_id(`<|endoftext|>`),d=s.startsWith(` `),f=s.trim(),p=Md.test(f);if(u||d||p||i.length===0)i.push(s),a.push(c),o.push(l);else{let e=i.length-1;i[e]+=s,a[e].push(...c),o[e].push(...l)}}return[i,a,o]}mergePunctuations(e,t,n,r,i){let a=structuredClone(e),o=structuredClone(t),s=structuredClone(n),c=a.length-2,l=a.length-1;for(;c>=0;)a[c].startsWith(` `)&&r.includes(a[c].trim())?(a[l]=a[c]+a[l],o[l]=si(o[c],o[l]),s[l]=si(s[c],s[l]),a[c]=``,o[c]=[],s[c]=[]):l=c,--c;for(c=0,l=1;le),o.filter(e=>e.length>0),s.filter(e=>e.length>0)]}},Fd=class extends W{},Id=class extends W{return_token_type_ids=!0;constructor(e,t){super(e,t),N.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},G=class{static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let[o,s]=await Au(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a}),c=s.tokenizer_class?.replace(/Fast$/,``)??`PreTrainedTokenizer`,l=Ru[c];return l||=(N.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),W),new l(o,s)}},Ld=`https://github.com/huggingface/transformers.js/issues/new/choose`,Rd=`preprocessor_config.json`,zd=`preprocessor_config.json`,Bd=`processor_config.json`,Vd=`chat_template.jinja`,K=class extends ti{static classes=[`image_processor_class`,`tokenizer_class`,`feature_extractor_class`];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,n){super(),this.config=e,this.components=t,this.chat_template=n}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw Error(`Unable to apply chat template without a tokenizer.`);return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.decode(...e)}async _call(e,...t){for(let n of[this.image_processor,this.feature_extractor,this.tokenizer])if(n)return n(e,...t);throw Error(`No image processor, feature extractor, or tokenizer found.`)}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([this.uses_processor_config?ol(e,Bd,!0,t):{},Promise.all(this.classes.filter(e=>e in this).map(async n=>{let r=await this[n].from_pretrained(e,t);return[n.replace(/_class$/,``),r]})).then(Object.fromEntries),this.uses_chat_template_file?al(e,Vd,!0,t):null]);return new this(n,r,i)}},Hd={};Tr(Hd,{ChatterboxProcessor:()=>Lf,CohereAsrProcessor:()=>zf,Florence2Processor:()=>Dm,Gemma3Processor:()=>Om,Gemma3nProcessor:()=>km,Gemma4Processor:()=>Am,Glm46VProcessor:()=>Mm,GraniteSpeechProcessor:()=>Nm,GroundingDinoProcessor:()=>Fm,Idefics3Processor:()=>zm,JinaCLIPProcessor:()=>Vm,Lfm2VlProcessor:()=>Hm,LlavaProcessor:()=>Um,MgpstrProcessor:()=>Gm,MoonshineProcessor:()=>Km,OwlViTProcessor:()=>qm,PaliGemmaProcessor:()=>Xm,Phi3VProcessor:()=>$m,PixtralProcessor:()=>eh,Processor:()=>K,PyAnnoteProcessor:()=>th,Qwen2VLProcessor:()=>jm,Qwen2_5_VLProcessor:()=>nh,Qwen3VLProcessor:()=>rh,Sam2Processor:()=>ah,Sam2VideoProcessor:()=>oh,SamProcessor:()=>ih,SmolVLMProcessor:()=>zm,SpeechT5Processor:()=>sh,UltravoxProcessor:()=>ch,VLChatProcessor:()=>Bm,VoxtralProcessor:()=>ph,VoxtralRealtimeProcessor:()=>yh,Wav2Vec2Processor:()=>bh,Wav2Vec2ProcessorWithLM:()=>xh,WhisperProcessor:()=>Sh});var Ud=class extends ti{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){let n=await ol(e,Rd,!0,t);return new this(n)}};function Wd(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`load_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Gd={};Tr(Gd,{ASTFeatureExtractor:()=>gf,ChatterboxFeatureExtractor:()=>vf,ClapFeatureExtractor:()=>yf,CohereAsrFeatureExtractor:()=>Sf,DacFeatureExtractor:()=>Cf,EncodecFeatureExtractor:()=>_f,FeatureExtractor:()=>Ud,Gemma3nAudioFeatureExtractor:()=>wf,Gemma4AudioFeatureExtractor:()=>Tf,GraniteSpeechFeatureExtractor:()=>Ef,MoonshineFeatureExtractor:()=>Df,ParakeetFeatureExtractor:()=>xf,PyAnnoteFeatureExtractor:()=>Of,SeamlessM4TFeatureExtractor:()=>kf,SnacFeatureExtractor:()=>Af,SpeechT5FeatureExtractor:()=>jf,VoxtralRealtimeFeatureExtractor:()=>Pf,Wav2Vec2FeatureExtractor:()=>Mf,WeSpeakerFeatureExtractor:()=>Nf,WhisperFeatureExtractor:()=>Ff});var Kd={fromWeb:()=>{}};async function qd(e,t){if(j.IS_BROWSER_ENV){if(j.IS_WEBWORKER_ENV)throw Error(`Unable to save a file from a Web Worker.`);let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.click(),r.remove(),URL.revokeObjectURL(n)}else if(j.IS_FS_AVAILABLE){let n=t.stream();Kd.fromWeb(n),Er.createWriteStream(e),await void 0}else throw Error(`Unable to save because filesystem is disabled in this environment.`)}async function Jd(e,t){if(typeof AudioContext>`u`)throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let n=await(await Zc(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});t===void 0&&N.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);let i=await r.decodeAudioData(n),a;if(i.numberOfChannels===2){let e=Math.sqrt(2),t=i.getChannelData(0),n=i.getChannelData(1);a=new Float32Array(t.length);for(let r=0;r2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function ef(e,t=`htk`){let n=$d[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}var tf={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function nf(e,t=`htk`){let n=tf[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}function rf(e,t){let n=Float64Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n]),r=Array.from({length:e.length},()=>Array(t.length));for(let n=0;nArray(e.length));for(let t=0;te+r*n)}function of(e,t,n,r,i,a=null,o=`htk`,s=!1){if(a!==null&&a!==`slaney`)throw Error(`norm must be one of null or "slaney"`);if(e<2)throw Error(`Require num_frequency_bins: ${e} >= 2`);if(n>r)throw Error(`Require min_frequency: ${n} <= max_frequency: ${r}`);let c=af(ef(n,o),ef(r,o),t+2),l=nf(c,o),u;if(s){let t=i/((e-1)*2);u=ef(Float64Array.from({length:e},(e,n)=>n*t),o),l=c}else u=af(0,Math.floor(i/2),e);let d=rf(u,l);if(a!==null&&a===`slaney`)for(let n=0;ni)throw Error(`frame_length (${n}) may not be larger than fft_length (${i})`);if(C!==n)throw Error(`Length of the window (${C}) must equal frame_length (${n})`);if(r<=0)throw Error(`hop_length must be greater than zero`);if(a===null&&d!==null)throw Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!u)throw Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o){let t=Math.floor(n/2);switch(s){case`reflect`:e=sf(e,t,t);break;case`constant`:{let n=new e.constructor(e.length+2*t);n.set(e,t),e=n;break}case`semicausal`:{let n=new e.constructor(e.length+t);n.set(e,t),e=n;break}default:throw Error(`pad_mode="${s}" not implemented yet.`)}}let w=Math.floor(1+Math.floor((e.length-n)/r));y!==null&&ww?x&&(T=b):T=re=b);let E=new gl(i),ie=new Float64Array(i),ae=new Float64Array(E.outputBufferSize),oe=new Float32Array(ne*T);for(let i=0;i=1;--e)ie[e]-=l*ie[e-1];ie[0]*=1-l}for(let e=0;ee**.85);break;default:throw Error(`Unknown window type ${t}.`)}if(n&&(o=o.subarray(0,e)),r===null||e===r)return o;if(e>r)throw Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);let s=new Float64Array(r),c=i?Math.floor((r-e)/2):0;return s.set(o,c),s}function pf(e,t){let n=e.reduce((e,t)=>e+t.length,0),r=/* @__PURE__ */ new ArrayBuffer(44),i=new DataView(r);return mf(i,0,`RIFF`),i.setUint32(4,36+n*4,!0),mf(i,8,`WAVE`),mf(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*4,!0),i.setUint16(32,4,!0),i.setUint16(34,32,!0),mf(i,36,`data`),i.setUint32(40,n*4,!0),new Blob([r,...e.map(e=>e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e.slice())],{type:`audio/wav`})}function mf(e,t,n){for(let r=0;re+t.length,0),t=new Float32Array(e),n=0;for(let e of this.audio)t.set(e,n),n+=e.length;return t}return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),pf(e,this.sampling_rate)}async save(e){return qd(e,this.toBlob())}},gf=class extends Ud{constructor(e){super(e);let t=this.config.sampling_rate,n=of(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=ff(400,`hann`,{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return df(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){Wd(e,`ASTFeatureExtractor`);let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let e=this.std*2,n=t.data;for(let t=0;t0){if(n===`rand_trunc`){let n=Math.floor(Cc.random()*(a+1));e=e.subarray(n,n+t),i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy "${n}" not implemented`)}else{if(a<0){let n=new Float64Array(t);if(n.set(e),r===`repeat`)for(let r=e.length;r=1;--n)e[n]-=t*e[n-1];return await df(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:`log`,mel_floor:-1/0,pad_mode:`constant`,center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Wd(e,`ParakeetFeatureExtractor`);let t=await this._extract_fbank_features(e),n=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),r=t.data;r.fill(0,n*t.dims[1]);let[i,a]=t.dims,o=new Float64Array(a),s=new Float64Array(a);for(let e=0;e1?n-1:1;for(let e=0;e=l){s.push(e.slice(c,l));break}let t=Math.max(c,c+a-o),n=Math.min(c+a,l),i;i=n<=t?c+a:this._find_split_point_energy(e,t,n,r),i=Math.max(c+1,Math.min(i,l)),s.push(e.slice(c,i)),c=i}return s}_find_split_point_energy(e,t,n,r){let i=n-t;if(i<=r)return Math.floor((t+n)/2);let a=1/0,o=t,s=i-r;for(let n=0;n<=s;n+=r){let i=0;for(let a=0;at&&(e=e.slice(0,t)),r&&e.length%i!==0){let t=i-e.length%i,n=new Float64Array(e.length+t);n.set(e),this.config.padding_value!==0&&n.fill(this.config.padding_value,e.length),e=n}let a=await this._extract_fbank_features(e,this.config.max_length),o=xu([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},Tf=class extends wf{async _extract_fbank_features(e,t){let{frame_length:n,hop_length:r,fft_length:i}=this.config,a=Math.floor(n/2),o=Math.floor((e.length+a-(n+1))/r)+1;return df(e,this.window,n,r,{fft_length:i,center:!0,pad_mode:`semicausal`,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:this.config.mel_floor,mel_floor_mode:`add`,remove_dc_offset:!1,transpose:!0,max_num_frames:o})}async _call(e,t={}){Wd(e,`Gemma4AudioFeatureExtractor`);let n=e.length,r=await super._call(e,t),{input_features:i}=r,[,a,o]=i.dims,{frame_length:s,hop_length:c}=this.config,l=Math.floor(s/2),u=s+1,d=new Uint8Array(n+l+(t.pad_to_multiple_of??128));d.fill(1,l,l+n);let f=new Uint8Array(a);for(let e=0;e({id:e,start:t*n,end:r*n,confidence:i/(r-t)})))}return r}},kf=class extends Ud{constructor(e){super(e);let t=this.config.sampling_rate,n=of(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=ff(400,`povey`,{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(e=>e*32768),df(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:i=!0}={}){Wd(e,`SeamlessM4TFeatureExtractor`);let a=await this._extract_fbank_features(e,this.config.max_length);if(r){let[e,t]=a.dims,n=a.data;for(let r=0;r0){let n=new Float32Array(t*(e+s));n.set(r),n.fill(this.config.padding_value,r.length);let c=e+s;a=new U(a.type,n,[c,t]),i&&(o=new U(`int64`,new BigInt64Array(c),[1,c]),o.data.fill(1n,0,e))}}let[s,c]=a.dims,l=this.config.stride;if(s%l!==0)throw Error(`The number of frames (${s}) must be a multiple of the stride (${l}).`);let u=a.view(1,Math.floor(s/l),c*l),d={input_features:u};if(i){let e=u.dims[1],t=new BigInt64Array(e);if(o){let e=o.data;for(let n=1,r=0;ne+t,0)/e.length,n=e.reduce((e,n)=>e+(n-t)**2,0)/e.length;return e.map(e=>(e-t)/Math.sqrt(n+1e-7))}async _call(e){Wd(e,`Wav2Vec2FeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let n=[1,t.length];return{input_values:new U(`float32`,t,n),attention_mask:new U(`int64`,new BigInt64Array(t.length).fill(1n),n)}}},Nf=class extends Ud{constructor(e){super(e);let t=this.config.sampling_rate,n=of(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=ff(400,`hamming`,{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(e=>e*32768),df(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Wd(e,`WeSpeakerFeatureExtractor`);let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let e=t.mean(1).data,n=t.data,[r,i,a]=t.dims;for(let t=0;tr?(e.length>this.config.n_samples&&N.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),n=e.slice(0,r)):(n=new Float32Array(r),n.set(e)),{input_features:(await this._extract_fbank_features(n)).unsqueeze_(0)}}},If=class{static async from_pretrained(e,t={}){let n=await ol(e,Rd,!0,t),r=n.feature_extractor_type,i=Gd[r];if(!i)throw Error(`Unknown feature_extractor_type: '${r}'. Please report this at ${Ld}.`);return new i(n)}},Lf=class extends K{static tokenizer_class=G;static feature_extractor_class=If;async _call(e,t=null){let n=this.tokenizer(e),r=t?await this.feature_extractor(t):{};return{...n,...r}}},Rf=/* @__PURE__ */ new Set([`ja`,`zh`]),zf=class extends K{static tokenizer_class=G;static feature_extractor_class=If;static uses_processor_config=!0;get_decoder_prompt_ids(e=`en`){let t=[`▁`,`<|startofcontext|>`,`<|startoftranscript|>`,`<|emo:undefined|>`,`<|${e}|>`,`<|${e}|>`,`<|pnc|>`,`<|noitn|>`,`<|notimestamp|>`,`<|nodiarize|>`];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t=`en`){let n=e.filter(e=>e&&e.trim());if(n.length===0)return``;let r=Rf.has(t)?``:` `;return[n[0].trimEnd(),...n.slice(1).map(e=>e.trim())].join(r)}async _call(e){return await this.feature_extractor(e)}},Bf={},Vf,Hf,Uf;if(j.IS_WEB_ENV)Vf=(e,t)=>{if(!self.OffscreenCanvas)throw Error(`OffscreenCanvas not supported by this environment.`);return new self.OffscreenCanvas(e,t)},Uf=self.createImageBitmap,Hf=self.ImageData;else if(Bf)Uf=async e=>{let t=(await e.metadata()).channels,{data:n,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),i=new Kf(new Uint8ClampedArray(n),r.width,r.height,r.channels);return t!==void 0&&t!==r.channels&&i.convert(t),i};else throw Error(`Unable to load image processing library.`);var Wf={0:`nearest`,1:`lanczos`,2:`bilinear`,3:`bicubic`,4:`box`,5:`hamming`},Gf=/* @__PURE__ */ new Map([[`png`,`image/png`],[`jpg`,`image/jpeg`],[`jpeg`,`image/jpeg`],[`gif`,`image/gif`]]),Kf=class e{constructor(e,t,n,r){this.data=e,this.width=t,this.height=n,this.channels=r}get size(){return[this.width,this.height]}static async read(t){if(t instanceof e)return t;if(typeof t==`string`||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!j.IS_WEB_ENV)throw Error(`fromCanvas() is only supported in browser environments.`);let n=t.getContext(`2d`).getImageData(0,0,t.width,t.height).data;return new e(n,t.width,t.height,4)}static async fromURL(e){let t=await Zc(e);if(t.status!==200)throw Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);let n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(j.IS_WEB_ENV){let t=await Uf(e),n=Vf(t.width,t.height).getContext(`2d`);return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{let t=Bf(await e.arrayBuffer());return await Uf(t)}}static fromTensor(t,n=`CHW`){if(t.dims.length!==3)throw Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(n===`CHW`)t=t.permute(1,2,0);else if(n!==`HWC`)throw Error(`Unsupported channel format: ${n}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new e(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t=0?c=r:u=-r,i>=0?l=i:d=-i,s.drawImage(o,c,l,t,n,u,d,t,n),new e(s.getImageData(0,0,t,n).data,t,n,4).convert(a)}{let e=this.toSharp();if(r>=0&&i>=0)e=e.extract({left:Math.floor(r),top:Math.floor(i),width:t,height:n});else if(r<=0&&i<=0){let a=Math.floor(-i),o=Math.floor(-r);e=e.extend({top:a,left:o,right:t-this.width-o,bottom:n-this.height-a})}else{let a=[0,0],o=0;i<0?(a[0]=Math.floor(-i),a[1]=n-this.height-a[0]):o=Math.floor(i);let s=[0,0],c=0;r<0?(s[0]=Math.floor(-r),s[1]=t-this.width-s[0]):c=Math.floor(r),e=e.extend({top:a[0],bottom:a[1],left:s[0],right:s[1]}).extract({left:c,top:o,width:t,height:n})}return await Uf(e)}}async toBlob(e=`image/png`,t=1){if(!j.IS_WEB_ENV)throw Error(`toBlob() is only supported in browser environments.`);return await this.toCanvas().convertToBlob({type:e,quality:t})}toTensor(e=`CHW`){let t=new U(`uint8`,new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!==`HWC`){if(e===`CHW`)t=t.permute(2,0,1);else throw Error(`Unsupported channel format: ${e}`)}return t}toCanvas(){if(!j.IS_WEB_ENV)throw Error(`toCanvas() is only supported in browser environments.`);let e=this.clone().rgba(),t=Vf(e.width,e.height),n=new Hf(e.data,e.width,e.height);return t.getContext(`2d`).putImageData(n,0,0),t}split(){let{data:t,width:n,height:r,channels:i}=this,a=t.constructor,o=t.length/i,s=Array.from({length:i},()=>new a(o));for(let e=0;enew e(t,n,r,1))}_update(e,t,n,r=null){return this.data=e,this.width=t,this.height=n,r!==null&&(this.channels=r),this}clone(){return new e(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(j.IS_WEB_ENV){if(j.IS_WEBWORKER_ENV)throw Error(`Unable to save an image from a Web Worker.`);let t=e.split(`.`).pop().toLowerCase(),n=Gf.get(t)??`image/png`;return qd(e,await this.toBlob(n))}if(j.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw Error(`Unable to save the image because filesystem is disabled in this environment.`)}toSharp(){if(j.IS_WEB_ENV)throw Error(`toSharp() is only supported in server-side environments.`);return Bf(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};Kf.read.bind(Kf);function qf(e,t,n=0,r=null){let i=e/t,a=yl(i)*t;return r!==null&&a>r&&(a=Math.floor(i)*t),at&&i.push(e)}else{let e=fl(n.data)[1];if(e===c-1||(a=ll(n.data),a[e]e*o[(t+1)%2])),u.boxes.push(n),u.classes.push(t),u.scores.push(a[t])}}l.push(u)}return l}function Zf(e,t=null){let n=e.logits,r=n.dims[0];if(t!==null&&t.length!==r)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let i=[];for(let e=0;el[n]&&(l[n]=t[n],u[n]=e)}let d=Array(a.dims[0]);for(let e=0;ee!==void 0);i.push({segmentation:c,labels:f})}return i}function Qf(e,t,n,r){let i=[],a=[],o=[];for(let s=0;sn&&(i.push(l),a.push(d),o.push(u))}return[i,a,o]}function $f(e,t,n,r=.5,i=.8){let a=[],o=0,s=0,c=t[n].data;for(let t=0;t=r&&++s;let l=o>0&&s>0;return l&&=o/s>i,[l,a]}function ep(e,t,n,r,i,a=null,o=null){let[s,c]=o??e[0].dims,l=new U(`int32`,new Int32Array(s*c),[s,c]),u=[];if(o!==null)for(let t=0;tf[e]&&(d[e]=n,f[e]=i[e])}let p=0,m=l.data;for(let a=0;a200)throw Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/n)*n,s=Math.round(t/n)*n;if(a*o*s>i){let r=Math.sqrt(a*e*t/i);o=Math.max(n,Math.floor(e/r/n)*n),s=Math.max(n,Math.floor(t/r/n)*n)}else if(a*o*si?c=Math.floor(i*s/r):i>r&&(s=Math.floor(r*c/i)),await e.resize(c,s,{resample:n}))}async crop_margin(e,t=200){let n=e.clone().grayscale(),r=dl(n.data)[0],i=fl(n.data)[0]-r;if(i===0)return e;let a=t/255,o=n.width,s=n.height,c=0,l=0,u=n.data;for(let e=0;ethis.preprocess(e)));return{pixel_values:hu(n.map(e=>e.pixel_values),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}static async from_pretrained(e,t={}){let n=await ol(e,zd,!0,t);return new this(n)}},ip={};Tr(ip,{BeitFeatureExtractor:()=>ap,BitImageProcessor:()=>op,CHMv2ImageProcessor:()=>cp,CLIPFeatureExtractor:()=>up,CLIPImageProcessor:()=>lp,ChineseCLIPFeatureExtractor:()=>sp,ConvNextFeatureExtractor:()=>fp,ConvNextImageProcessor:()=>dp,DINOv3ViTImageProcessor:()=>_p,DPTFeatureExtractor:()=>xp,DPTImageProcessor:()=>bp,DeiTFeatureExtractor:()=>mp,DeiTImageProcessor:()=>pp,DetrFeatureExtractor:()=>gp,DetrImageProcessor:()=>hp,DonutFeatureExtractor:()=>yp,DonutImageProcessor:()=>vp,EfficientNetImageProcessor:()=>Sp,GLPNFeatureExtractor:()=>kp,Gemma3ImageProcessor:()=>Cp,Gemma4ImageProcessor:()=>Ep,Glm46VImageProcessor:()=>Op,GroundingDinoImageProcessor:()=>Ap,Idefics3ImageProcessor:()=>jp,ImageFeatureExtractor:()=>q,ImageProcessor:()=>q,JinaCLIPImageProcessor:()=>Np,Lfm2VlImageProcessor:()=>zp,LlavaOnevisionImageProcessor:()=>Bp,Mask2FormerImageProcessor:()=>Up,MaskFormerFeatureExtractor:()=>Hp,MaskFormerImageProcessor:()=>Vp,MobileNetV1FeatureExtractor:()=>Gp,MobileNetV1ImageProcessor:()=>Wp,MobileNetV2FeatureExtractor:()=>qp,MobileNetV2ImageProcessor:()=>Kp,MobileNetV3FeatureExtractor:()=>Yp,MobileNetV3ImageProcessor:()=>Jp,MobileNetV4FeatureExtractor:()=>Zp,MobileNetV4ImageProcessor:()=>Xp,MobileViTFeatureExtractor:()=>$p,MobileViTImageProcessor:()=>Qp,NougatImageProcessor:()=>em,OwlViTFeatureExtractor:()=>nm,OwlViTImageProcessor:()=>tm,Owlv2ImageProcessor:()=>rm,Phi3VImageProcessor:()=>lm,PixtralImageProcessor:()=>um,PvtImageProcessor:()=>dm,Qwen2VLImageProcessor:()=>Dp,RTDetrImageProcessor:()=>fm,Sam2ImageProcessor:()=>pm,Sam3ImageProcessor:()=>pm,SamImageProcessor:()=>pm,SapiensFeatureExtractor:()=>hm,SapiensImageProcessor:()=>mm,SegformerFeatureExtractor:()=>_m,SegformerImageProcessor:()=>gm,SiglipImageProcessor:()=>vm,SmolVLMImageProcessor:()=>jp,Swin2SRImageProcessor:()=>ym,VLMImageProcessor:()=>Mp,ViTFeatureExtractor:()=>xm,ViTImageProcessor:()=>bm,VitMatteImageProcessor:()=>Sm,VitPoseImageProcessor:()=>Cm,YolosFeatureExtractor:()=>Tm,YolosImageProcessor:()=>wm});var ap=class extends q{},op=class extends q{},sp=class extends q{},cp=class extends q{},lp=class extends q{},up=class extends lp{},dp=class extends q{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let t=this.size?.shortest_edge;if(t===void 0)throw Error(`Size dictionary must contain 'shortest_edge' key.`);if(t<384){let n=Math.floor(t/this.crop_pct),[r,i]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(r,i,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},fp=class extends dp{},pp=class extends q{},mp=class extends pp{},hp=class extends q{async _call(e){let t=await super._call(e),n=xu([t.pixel_values.dims[0],64,64],1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return Xf(...e)}post_process_panoptic_segmentation(...e){return np(...e)}post_process_instance_segmentation(...e){return rp(...e)}},gp=class extends hp{},_p=class extends q{},vp=class extends q{pad_image(e,t,n,r={}){let[i,a,o]=t,s=this.image_mean;Array.isArray(this.image_mean)||(s=Array(o).fill(s));let c=this.image_std;Array.isArray(c)||(c=Array(o).fill(s));let l=s.map((e,t)=>-e/c[t]);return super.pad_image(e,t,n,{center:!0,constant_values:l,...r})}},yp=class extends vp{},bp=class extends q{},xp=class extends bp{},Sp=class extends q{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(e=>e*e))}},Cp=class extends q{};function wp(e,t,n,r,i){let a=r*n**2,o=Math.sqrt(a/(e*t)),s=i*n,c=Math.floor(o*e/s)*s,l=Math.floor(o*t/s)*s;if(c===0&&l===0)throw Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${s}.`);let u=Math.floor(r/i**2)*s;return c===0?(c=s,l=Math.min(Math.floor(t/e)*s,u)):l===0&&(l=s,c=Math.min(Math.floor(e/t)*s,u)),[c,l]}function Tp(e,t,n,r,i,a,o){let s=Math.floor(t/i),c=Math.floor(n/i),l=s*c,u=i*i*r,d=new Float32Array(a*u),f=0;for(let t=0;ta),0));let l=a.dims[0]/o,u=a.dims[1],d=Math.floor(a.dims[2]/c),f=Math.floor(a.dims[3]/c);return{pixel_values:a.view(l,o,u,Math.floor(d/s),s,c,Math.floor(f/s),s,c).permute(0,3,6,4,7,2,1,5,8).view(l*d*f,u*o*c*c),image_grid_thw:new U(`int64`,[l,d,f],[1,3]),original_sizes:r,reshaped_input_sizes:i}}},Op=class extends Dp{get_resize_output_image_size(e,t){let n=this.patch_size*this.merge_size,r=this.config.temporal_patch_size??2;return tp(e.height,e.width,n,this.min_pixels,this.max_pixels,r)}},kp=class extends q{},Ap=class extends q{async _call(e){let t=await super._call(e),n=t.pixel_values.dims,r=Cu([n[0],n[2],n[3]]);return{...t,pixel_mask:r}}},jp=class extends q{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[n,r]=e.dims.slice(-2),i=r/n;return r>=n?(r=Math.ceil(r/t)*t,n=Math.floor(r/i),n=Math.ceil(n/t)*t):(n=Math.ceil(n/t)*t,r=Math.floor(n*i),r=Math.ceil(r/t)*t),{height:n,width:r}}async _call(e,{do_image_splitting:t=null,return_row_col_info:n=!1}={}){let r;if(!Array.isArray(e))r=[[e]];else{if(e.length===0||!e[0])throw Error(`No images provided.`);r=Array.isArray(e[0])?e:[e]}let i=[],a=[],o=[],s=[],c=[];for(let e of r){let n=await Promise.all(e.map(e=>this.preprocess(e)));s.push(...n.map(e=>e.original_size)),c.push(...n.map(e=>e.reshaped_input_size)),n.forEach(e=>e.pixel_values.unsqueeze_(0));let{longest_edge:r}=this.max_image_size,l;if(t??this.do_image_splitting){let e=Array(n.length),t=Array(n.length);l=await Promise.all(n.map(async(n,i)=>{let a=this.get_resize_for_vision_encoder(n.pixel_values,r),o=await au(n.pixel_values,{size:[a.height,a.width]}),{frames:s,num_splits_h:c,num_splits_w:l}=await this.split_image(o,this.max_image_size);return e[i]=c,t[i]=l,mu(s,0)})),a.push(e),o.push(t)}else{let e=[r,r];l=await Promise.all(n.map(t=>au(t.pixel_values,{size:e}))),a.push(Array(n.length).fill(0)),o.push(Array(n.length).fill(0))}i.push(mu(l,0))}let l=i.length,[u,d,f,p]=i[0].dims,m,h;if(l===1)m=i[0].unsqueeze_(0),h=xu([l,u,f,p],!0);else{let e=Math.max(...i.map(e=>e.dims.at(0)));h=xu([l,e,f,p],!0);let t=h.data,n=e*f*p;for(let r=0;rn||o>r){s=Math.ceil(a/n),c=Math.ceil(o/r);let t=Math.ceil(a/s),l=Math.ceil(o/c);for(let n=0;ne*this.rescale_factor)}pad_image(e,t,n,r){return super.pad_image(e,t,n,{constant_values:this.constant_values,center:!0,...r})}},Np=class extends q{constructor(e){let{resize_mode:t,fill_color:n,interpolation:r,size:i,...a}=e,o=t===`squash`?{width:i,height:i}:t===`shortest`?{shortest_edge:i}:{longest_edge:i},s=r===`bicubic`?3:2;super({...a,size:o,resample:s,do_center_crop:!0,crop_size:i,do_normalize:!0})}};function Pp(e,t){return Math.round(e/t)*t}function Fp(e,t,n,r,i){let a=1/0,o=[1,1],s=n*r;for(let n of t){let t=Math.abs(e-n[0]/n[1]);t.5*i*i*n[0]*n[1]&&(o=n)}return o}function Ip(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let i=e;i<=t;++i)for(let a=1;a<=i;++a)for(let o=1;o<=i;++o){let i=a*o;if(i>=e&&i<=t){let e=a<<16|o;r.has(e)||(r.add(e),n.push([a,o]))}}return n.sort((e,t)=>e[0]*e[1]-t[0]*t[1])}function Lp(e,t){let[n,r,i,a]=e.dims,o=Math.floor(i/t),s=Math.floor(a/t),c=t*t*r,l=e.data,u=new Float32Array(n*o*s*c),d=i*a;for(let e=0;ethis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let n=Ip(this.min_tiles,this.max_tiles),[r,i]=Fp(t/e,n,t,e,this.tile_size);return{grid_width:r,grid_height:i,target_width:this.tile_size*r,target_height:this.tile_size*i}}async _call(e,{return_row_col_info:t=null}={}){let n;n=Array.isArray(e)?Array.isArray(e[0])?e:[e]:[[e]];let r=[],i=[],a=[],o=[],s=[],c=[];for(let e of n){let t=await Promise.all(e.map(e=>this.preprocess(e,{do_pad:!1})));for(let{pixel_values:e}of t){let[,t,n]=e.dims,l=e.unsqueeze_(0),u=this.encoder_patch_size*this.downsample_factor,d=u**2,[f,p]=tp(Math.max(u,t),Math.max(u,n),u,this.min_image_tokens*d,this.max_image_tokens*d).map(e=>Math.max(u,e)),m,h=1,g=1,_=this._is_image_too_large(t,n),v=this.do_image_splitting&&(this.min_tiles!==1||this.max_tiles!==1);if(_&&v){let{grid_width:e,grid_height:r,target_width:i,target_height:a}=this._get_grid_layout(t,n);h=r,g=e;let o=await au(l,{size:[a,i]});m=[];for(let t=0;t(e-this.image_mean[t])/this.image_std[t]);return super.pad_image(e,t,{width:s,height:o},{center:!0,constant_values:c,...r})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||cm(t)%1!=0)throw Error(`num_crops must be a square number >= 4`);Array.isArray(e)||(e=[e]);let n=e.length,r=await Promise.all(e.map(e=>this.preprocess(e))),i=r.map(e=>e.original_size),a=r.map(e=>e.reshaped_input_size),o=[];for(let{pixel_values:e}of r){e.unsqueeze_(0);let[n,r]=e.dims.slice(-2),i=await au(e,{size:[im,im],mode:`bicubic`});if(t>0){let a=[],s=cm(t),c=sm(r/s),l=sm(n/s);for(let t=0;te.map(e=>im*om(e/im)));return{pixel_values:s,original_sizes:i,reshaped_input_sizes:a,image_sizes:new U(`int64`,c.flat(),[n,2]),num_img_tokens:c.map(([e,t])=>this.calc_num_image_tokens_from_image_size(t,e))}}},um=class extends q{get_resize_output_image_size(e,t){let{longest_edge:n}=t;if(n===void 0)throw Error(`size must contain 'longest_edge'`);let[r,i]=e.size,a=Math.max(r,i)/n,o=r,s=i;a>1&&(o=Math.floor(r/a),s=Math.floor(i/a));let{patch_size:c,spatial_merge_size:l}=this.config;if(!l)throw Error(`config must contain 'spatial_merge_size'`);let u=c*l,d=Math.floor((o-1)/u)+1,f=Math.floor((s-1)/u)+1;return[d*u,f*u]}},dm=class extends q{},fm=class extends q{post_process_object_detection(...e){return Xf(...e)}},pm=class extends q{reshape_input_points(e,t,n,r=!1){e=structuredClone(e);let i=oi(e);if(i.length===3)r||(i=[1,...i]),e=[e];else if(i.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let r=0;re!==t.dims[n]))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new U(`int64`,e.flat(1/0).map(BigInt),n)}async _call(e,{input_points:t=null,input_labels:n=null,input_boxes:r=null}={}){let i=await super._call(e);if(t&&(i.input_points=this.reshape_input_points(t,i.original_sizes,i.reshaped_input_sizes)),n){if(!i.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");i.input_labels=this.add_input_labels(n,i.input_points)}return r&&(i.input_boxes=this.reshape_input_points(r,i.original_sizes,i.reshaped_input_sizes,!0)),i}async post_process_masks(e,t,n,{mask_threshold:r=0,binarize:i=!0,pad_size:a=null}={}){let o=[];a=a??this.pad_size??this.size;let s=[a.height,a.width];for(let a=0;ar&&(t[n]=1);u=new U(`bool`,t,u.dims)}o.push(u)}return o}generate_crop_boxes(e,t,{crop_n_layers:n=0,overlap_ratio:r=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:a=1}={}){}},mm=class extends q{post_process_semantic_segmentation(...e){return Zf(...e)}},hm=class extends mm{},gm=class extends q{post_process_semantic_segmentation(...e){return Zf(...e)}},_m=class extends gm{},vm=class extends q{},ym=class extends q{pad_image(e,t,n,r={}){let[i,a,o]=t;return super.pad_image(e,t,{width:a+(n-a%n)%n,height:i+(n-i%n)%n},{mode:`symmetric`,center:!1,constant_values:-1,...r})}},bm=class extends q{},xm=class extends bm{},Sm=class extends q{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let n=await Promise.all(e.map(e=>this.preprocess(e))),r=await Promise.all(t.map(e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:hu(n.map((e,t)=>mu([e.pixel_values,r[t].pixel_values],0)),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}},Cm=class extends q{post_process_pose_estimation(e,t,{threshold:n=null}={}){let r=e.tolist(),[i,a,o,s]=e.dims,c=[];for(let e=0;e/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e==`string`&&(e=[e]);let t=[];for(let n of e)if(this.task_prompts_without_inputs.has(n))t.push(this.task_prompts_without_inputs.get(n));else{for(let[e,r]of this.task_prompts_with_input)if(n.includes(e)){t.push(r.replaceAll(`{input}`,n).replaceAll(e,``));break}t.length!==e.length&&t.push(n)}return t}post_process_generation(e,t,n){let r=this.tasks_answer_post_processing_type.get(t)??`pure_text`;e=e.replaceAll(``,``).replaceAll(``,``);let i;switch(r){case`pure_text`:i=e;break;case`description_with_bboxes`:case`bboxes`:case`phrase_grounding`:case`ocr`:let a=r===`ocr`?`quad_boxes`:`bboxes`,o=e.matchAll(this.regexes[a]),s=[],c=[];for(let[e,t,...r]of o)s.push(t?t.trim():s.at(-1)??``),c.push(r.map((e,t)=>(Number(e)+.5)/this.size_per_bin*n[t%2]));i={labels:s,[a]:c};break;default:throw Error(`Task "${t}" (of type "${r}") not yet implemented.`)}return{[t]:i}}async _call(e,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=await this.image_processor(e,n),i=t?this.tokenizer(this.construct_prompts(t),n):{};return{...r,...i}}},Om=class extends K{static tokenizer_class=G;static image_processor_class=Em;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.image_seq_length=this.config.image_seq_length;let{boi_token:r,image_token:i,eoi_token:a}=this.tokenizer.config;this.boi_token=r,this.image_token=i,this.eoi_token=a;let o=i.repeat(this.image_seq_length);this.full_image_sequence=` + +${r}${o}${a} + +`}async _call(e,t=null,n={}){typeof e==`string`&&(e=[e]);let r;return t&&(r=await this.image_processor(t,n),e=e.map(e=>e.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,n),...r}}},km=class extends K{static image_processor_class=Em;static feature_extractor_class=If;static tokenizer_class=G;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:r,boa_token:i,audio_token:a,eoa_token:o,image_token_id:s,boi_token:c,image_token:l,eoi_token:u}=this.tokenizer.config;this.audio_token_id=r,this.boa_token=i,this.audio_token=a;let d=a.repeat(this.audio_seq_length);this.full_audio_sequence=` + +${i}${d}${o} + +`,this.image_token_id=s,this.boi_token=c,this.image_token=l;let f=l.repeat(this.image_seq_length);this.full_image_sequence=` + +${c}${f}${u} + +`}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;n&&(i=await this.feature_extractor(n,r),e=e.map(e=>e.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,r),e=e.map(e=>e.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,r),...a,...i}}},Am=class extends K{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:r,boa_token:i,eoa_token:a,image_token:o,boi_token:s,eoi_token:c}=this.tokenizer.config;this.audio_token=r,this.boa_token=i,this.eoa_token=a,this.image_token=o,this.boi_token=s,this.eoi_token=c}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([ol(e,Bd,!0,t),G.from_pretrained(e,t),al(e,Vd,!1,t)]),a={tokenizer:r};return n.image_processor&&(a.image_processor=new Ep(n.image_processor)),n.feature_extractor&&(a.feature_extractor=new Tf(n.feature_extractor)),new this(n,a,i)}_compute_audio_num_tokens(e,t){let n=Math.round(t*20/1e3),r=Math.round(t*10/1e3),i=Math.floor(n/2),a=Math.floor((e+i-n-1)/r)+1;if(a<=0)return 0;for(let e=0;e<2;++e)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;if(t){i=await this.image_processor(t,r);let n=i.num_soft_tokens_per_image,a=0;e=e.map(e=>e.replaceAll(this.image_token,()=>` + +${this.boi_token}${this.image_token.repeat(n[a++])}${this.eoi_token} + +`))}let a;if(n){let t=Array.isArray(n)?n:[n];a=await this.feature_extractor(t[0],r);let i=this.feature_extractor.config.sampling_rate??16e3,o=0;e=e.map(e=>e.replaceAll(this.audio_token,()=>` + +${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(t[o++].length,i))}${this.eoa_token} + +`))}return{...this.tokenizer(e,r),...i,...a}}},jm=class extends K{static image_processor_class=Em;static tokenizer_class=G;static image_token=`<|image_pad|>`;async _call(e,t=null,...n){Array.isArray(e)||(e=[e]);let r,i;if(t&&(r=await this.image_processor(t),i=r.image_grid_thw),i){let t=this.image_processor.config.merge_size**2,n=0,r=this.constructor.image_token,a=i.tolist();e=e.map(e=>{for(;e.includes(r);){let i=Number(a[n++].reduce((e,t)=>e*t,1n));e=e.replace(r,`<|placeholder|>`.repeat(Math.floor(i/t)))}return e.replaceAll(`<|placeholder|>`,r)})}return{...this.tokenizer(e),...r}}},Mm=class extends jm{static image_token=`<|image|>`},Nm=class extends K{static tokenizer_class=G;static feature_extractor_class=If;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:n,projector_downsample_rate:r}=this.feature_extractor.config,i=Math.floor(n/r),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/n)*i}async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){let{input_features:n}=await this.feature_extractor(t);r.input_features=n;let i=this._get_num_audio_features(t.length);r.input_features_mask=new U(`bool`,new Uint8Array(i).fill(1),[1,i]);let a=this.config.audio_token??`<|audio|>`;if(!e.includes(a))throw Error(`The input text does not contain the audio token ${a}.`);e=e.replaceAll(a,a.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}};function Pm(e,t){let n=e.dims.at(-1)-1,r=e.tolist();r.fill(!1,0,1),r.fill(!1,n);let i=t.tolist();return r.map((e,t)=>e?t:null).filter(e=>e!==null).map(e=>i[e])}var Fm=class extends K{static tokenizer_class=G;static image_processor_class=Em;async _call(e,t,n={}){let r=e?await this.image_processor(e,n):{};return{...t?this.tokenizer(t,n):{},...r}}post_process_grounded_object_detection(e,t,{box_threshold:n=.25,text_threshold:r=.25,target_sizes:i=null}={}){let{logits:a,pred_boxes:o}=e,s=a.dims[0];if(i!==null&&i.length!==s)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let c=a.dims.at(1),l=a.sigmoid(),u=l.max(-1).tolist(),d=o.tolist().map(e=>e.map(e=>Yf(e))),f=[];for(let e=0;ee.map((e,t)=>e*a[(t+1)%2])));let o=u[e],s=[],p=[],m=[];for(let i=0;i`+i.repeat(e);o+=` +`}return o+=` +${r}${a}`+i.repeat(e)+`${r}`,o}function Lm(e,t,n,r){return`${t}${r}`+n.repeat(e)+`${t}`}function Rm(e,t,n,r,i,a){return e===0&&t===0?Lm(n,r,i,a):Im(n,e,t,r,i,a)}var zm=class extends K{static image_processor_class=Em;static tokenizer_class=G;static uses_processor_config=!0;fake_image_token=``;image_token=``;global_img_token=``;async _call(e,t=null,n={}){n.return_row_col_info??=!0;let r;t&&(r=await this.image_processor(t,n)),Array.isArray(e)||(e=[e]);let i=r.rows??[Array(e.length).fill(0)],a=r.cols??[Array(e.length).fill(0)],o=this.config.image_seq_len,s=[],c=[];for(let t=0;tRm(e,l[t],o,this.fake_image_token,this.image_token,this.global_img_token)),d=n.split(this.image_token);if(d.length===0)throw Error(`The image token should be present in the text.`);let f=d[0];for(let e=0;ee.images).flatMap(e=>e.images).map(e=>Kf.read(e)));let r=this.tokenizer,i=r.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:n}),a=e=>r.encode(e,{add_special_tokens:!1}),o=i.split(this.image_tag),s=o.length-1;if(t.length!==s)throw Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${s})`);let[c,l,u]=r.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),d=a(o[0]),f=Array(d.length).fill(!1);for(let e=1;e0){let e=await this.image_processor(t);return e.pixel_values.unsqueeze_(0),{...m,...e}}return m}},Vm=class extends K{static tokenizer_class=G;static image_processor_class=Em;async _call(e=null,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=e?this.tokenizer(e,n):{},i=t?await this.image_processor(t,n):{};return{...r,...i}}},Hm=class extends K{static tokenizer_class=G;static image_processor_class=Em;async _call(e,t=null,n={}){let{image_rows:r,image_cols:i,image_sizes:a,...o}=await this.image_processor(e,{...n,return_row_col_info:!0});if(t){let e=this.config.image_token??``,{tile_size:n=512,downsample_factor:o=2,encoder_patch_size:s=16,use_thumbnail:c=!0}=this.image_processor.config,l=e=>Math.ceil(Math.floor(e/s)/o),u=l(n)**2,d=this.config.image_start_token??`<|image_start|>`,f=this.config.image_end_token??`<|image_end|>`,p=this.config.image_thumbnail??`<|img_thumbnail|>`;Array.isArray(t)||(t=[t]);let m=0;t=t.map(t=>{let n=t.split(e);return n[0]+n.slice(1).map(t=>{let n=m++,[o,s]=a[n],h=r[n],g=i[n],_=l(o)*l(s),v=d;if(h>1||g>1){let t=e.repeat(u);for(let e=0;e`+t;c&&(v+=p+e.repeat(_))}else v+=e.repeat(_);return v+f+t}).join(``)})}return{...o,...t?this.tokenizer(t,n):{}}}},Um=class extends K{static tokenizer_class=G;static image_processor_class=Em;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,patch_size:a,num_additional_image_tokens:o}=this.config,s=Math.floor(e/a)*Math.floor(n/a)+o;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;e0?i.reduce((e,t)=>e*t,1):0;c.push(n),s.push(a)}return[i(c),s]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}batch_decode([e,t,n]){let[r,i]=this._decode_helper(e,`char`),[a,o]=this._decode_helper(t,`bpe`),[s,c]=this._decode_helper(n,`wp`),l=[],u=[];for(let e=0;e`;function Ym(e,t,n,r,i){return`${r.repeat(n*i)}${t}${e} +`}var Xm=class extends K{static tokenizer_class=G;static image_processor_class=Em;static uses_processor_config=!1;async _call(e,t=null,n={}){t||=(N.warn(`You are using PaliGemma without a text prefix. It will perform as a picture-captioning model.`),``),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let r=this.tokenizer.bos_token,i=this.image_processor.config.image_seq_length,a;t.some(e=>e.includes(Jm))?a=t.map(e=>{let t=e.replaceAll(Jm,Jm.repeat(i)),n=t.lastIndexOf(Jm),a=n===-1?0:n+Jm.length;return t.slice(0,a)+r+t.slice(a)+` +`}):(N.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=t.map(t=>Ym(t,r,i,Jm,e.length)));let o=this.tokenizer(a,n);return{...await this.image_processor(e,n),...o}}},Zm=`<|image|>`,Qm=/<\|image_\d+\|>/g,$m=class extends K{static image_processor_class=Em;static tokenizer_class=G;async _call(e,t=null,{padding:n=!0,truncation:r=!0,num_crops:i=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:i});let{num_img_tokens:s}=o,c=e.map((e,t)=>e.split(Qm).join(Zm.repeat(s[t])));a=this.tokenizer(c,{padding:n,truncation:r});let l=this.tokenizer._tokenizer.token_to_id(Zm);a.input_ids.map_(e=>e==l?-e:e)}else a=this.tokenizer(e);return{...a,...o}}},eh=class extends K{static tokenizer_class=G;static image_processor_class=Em;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,image_break_token:a,image_end_token:o,patch_size:s,spatial_merge_size:c}=this.config,l=s*c,u=Math.floor(e/l),d=Math.floor(n/l);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;efh(e,o)),c=s.map(e=>e.length),l=s.flat(),u=(await Promise.all(l.map(e=>this.feature_extractor(e,n)))).map(e=>e.input_features);r.audio_values=u.length>1?mu(u,0):u[0];let d=i[0];for(let e=0;e0){if(l>Oc)throw Error(`The number of external data chunks (${l}) exceeds the maximum allowed value (${Oc}).`);let t=jh(o,l);for(let n of t){let t=`${r.subfolder??``}/${n}`;c.push(new Promise(async(i,a)=>{let o=await il(e,t,!0,r,s);i(o instanceof Uint8Array?{path:n,data:o}:n)}))}}else a.externalData!==void 0&&(c=a.externalData.map(async t=>{if(typeof t.data==`string`){let n=await il(e,t.data,!0,r);return{...t,data:n}}return t}));return Promise.all(c)}async function Ph(e,t,n,r=!1,i=void 0){let a=n.config?.[`transformers.js_config`]??{},o=Jl(n.device??a.device,t,{warn:e=>N.info(e)}),s=Pl(o),c=a.device_config??{};c.hasOwnProperty(o)&&(a={...a,...c[o]});let l=eu(n.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:e=>N.info(e)});if(!$l.hasOwnProperty(l))throw Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys(Xl).join(`, `)}`);if(o===`webgpu`&&!j.IS_NODE_ENV&&l===Xl.fp16&&!await Yl())throw Error(`The device (${o}) does not support fp16.`);let u=$l[l],d={...n.session_options};d.executionProviders??=s;let f=a.free_dimension_overrides;f?d.freeDimensionOverrides??=f:o.startsWith(`webnn`)&&!d.freeDimensionOverrides&&N.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let p=Mh(e,t,n,u),m=await Nh(e,t,u,n,n.use_external_data_format??a.use_external_data_format,d);if(m.length>0&&(!j.IS_NODE_ENV||m.some(e=>typeof e!=`string`))&&(d.externalData=m),r&&o===`webgpu`){let e=Eh(n.config,{prefix:`present`,session_name:i});if(e.size>0&&!Ul()){let t={};for(let n of e)t[n]=`gpu-buffer`;d.preferredOutputLocation=t}}return{buffer_or_path:await p,session_options:d,session_config:{dtype:l,device:o}}}async function Fh(e,t,n,r=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async i=>{let a=r?.[i]??!1,{buffer_or_path:o,session_options:s,session_config:c}=await Ph(e,t[i],n,a,i);return[i,await Rl(o,s,c)]})))}function Ih(e){for(let t in e)Vl(e[t])?e[t]=new U(e[t]):typeof e[t]==`object`&&Ih(e[t]);return e}async function J(e,t){let n=Lh(e,t);try{return Ih(await Bl(e,Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=t.ort_tensor;return j.IS_NODE_ENV&&typeof Float16Array<`u`&&n.cpuData instanceof Float16Array&&(n.cpuData=new Uint16Array(n.cpuData.buffer)),[e,n]}))))}catch(e){let t=Object.fromEntries(Object.entries(n).map(([e,t])=>{let n={type:t.type,dims:t.dims,location:t.location};return n.location!==`gpu-buffer`&&(n.data=t.data),[e,n]}));throw N.error(`An error occurred during model execution: "${e}".`),N.error(`Inputs given to model:`,t),e}}function Lh(e,t){let n=/* @__PURE__ */ Object.create(null),r=[];for(let i of e.inputNames){let e=t[i];e instanceof U?n[i]=Ul()?e.clone():e:r.push(i)}if(r.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(`, `)}.`);let i=Object.keys(t).length,a=e.inputNames.length;if(i>a){let n=Object.keys(t).filter(t=>!e.inputNames.includes(t));N.warn(`WARNING: Too many inputs were provided (${i} > ${a}). The following inputs will be ignored: "${n.join(`, `)}".`)}return n}var Rh=class{},zh=class extends Rh{constructor({last_hidden_state:e,hidden_states:t=null,attentions:n=null}){super(),this.last_hidden_state=e,this.hidden_states=t,this.attentions=n}},Y=class extends Rh{constructor({logits:e,...t}){super(),this.logits=e;let n=Object.values(t);n.length>0&&(this.attentions=n)}},Bh=class extends Rh{constructor({logits:e}){super(),this.logits=e}},Vh=class extends Rh{constructor({logits:e}){super(),this.logits=e}},Hh=class extends Rh{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},Uh=class extends Rh{constructor({logits:e}){super(),this.logits=e}},Wh=class extends Rh{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}},Gh=class extends Rh{constructor({logits:e,past_key_values:t,encoder_outputs:n,decoder_attentions:r=null,cross_attentions:i=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=n,this.decoder_attentions=r,this.cross_attentions=i}},Kh=class extends Rh{constructor({alphas:e}){super(),this.alphas=e}},qh=class extends ti{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Jh=class extends ti{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Yh=class extends ti{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let n=t;for(let t of this.processors)n=t(e,n);return n}[Symbol.iterator](){return this.processors.values()}},Xh=class extends qh{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let n=0;n=1&&i[i.length-1]>=this.timestamp_begin,o=i.length<2||i[i.length-2]>=this.timestamp_begin;if(a&&(o?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e[n].length===this.begin_index&&this.max_initial_timestamp_index!==null){let e=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(e+1).fill(-1/0)}let s=ul(r);Math.log(s.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t))>fl(s.subarray(0,this.timestamp_begin))[0]&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},tg=class extends qh{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,n=[];for(let r=0;r1 to use the classifier-free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);let n=e.length,r=t.slice([0,n],null),i=t.slice([n,t.dims[0]],null);for(let e=0;ee.length>=this.max_length)}},fg=class extends lg{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(e=>{let t=e.at(-1);return this.eos_token_id.some(e=>t==e)})}},pg=class extends ti{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error(`sample should be implemented in subclasses.`)}getLogits(e,t){let n=e.dims.at(-1),r=e.data;if(t===-1)r=r.slice(-n);else{let e=t*n;r=r.slice(e,e+n)}return r}randomSelect(e){return wc(e)}static getSampler(e){if(e.do_sample)return new hg(e);if(e.num_beams>1)return new gg(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new mg(e)}},mg=class extends pg{async sample(e){let t=fl(e.data)[1];return[[BigInt(t),0]]}},hg=class extends pg{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[n,r]=await su(e,t),i=ll(n.data);return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(i);return[r.data[e],Math.log(i[e])]})}},gg=class extends pg{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[n,r]=await su(e,t),i=ll(n.data);return Array.from({length:this.generation_config.num_beams},(e,t)=>[r.data[t],Math.log(i[t])])}},_g=class{constructor(e){if(e)for(let t in e){if(t in this)throw TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);let n=e[t];if(!(n instanceof U))throw TypeError(`Expected a Tensor for key "${t}", got ${typeof n}`);this[t]=n}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let t in e)if(t.startsWith(`past_key_values.`))return e[t].dims.at(-2);throw Error(`Unable to determine sequence length from the cache.`)}update(e){for(let t in e){let n=this[t],r=e[t];n&&n!==r&&n.location===`gpu-buffer`&&n.dispose(),this[t]=r}}async dispose(){let e=[];for(let t of Object.values(this))t.location===`gpu-buffer`&&e.push(t.dispose());await Promise.all(e)}},X={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},vg={[X.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??`model`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??`model`})},[X.Seq2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.Vision2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.Musicgen]:{sessions:()=>({model:`text_encoder`,decoder_model_merged:`decoder_model_merged`,encodec_decode:`encodec_decode`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.EncoderDecoder]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0}},[X.MaskGeneration]:{sessions:()=>({model:`vision_encoder`,prompt_encoder_mask_decoder:`prompt_encoder_mask_decoder`})},[X.ImageTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...vg[X.ImageTextToText].text_only_sessions};return n||(r.vision_encoder=`vision_encoder`),e.is_encoder_decoder&&(r.model=`encoder_model`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.AudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...vg[X.AudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...vg[X.ImageAudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`,r.vision_encoder=`vision_encoder`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.Phi3V]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`model`,vision_encoder:`vision_encoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.MultiModality]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`language_model`,lm_head:`lm_head`,gen_head:`gen_head`,gen_img_embeds:`gen_img_embeds`,image_decode:`image_decode`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.AutoEncoder]:{sessions:()=>({encoder_model:`encoder_model`,decoder_model:`decoder_model`})},[X.Supertonic]:{sessions:()=>({text_encoder:`text_encoder`,latent_denoiser:`latent_denoiser`,voice_decoder:`voice_decoder`})},[X.Chatterbox]:{sessions:()=>({embed_tokens:`embed_tokens`,speech_encoder:`speech_encoder`,model:`language_model`,conditional_decoder:`conditional_decoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.VoxtralRealtime]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...vg[X.VoxtralRealtime].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:`generation_config.json`}},default:{sessions:(e,t)=>({model:t.model_file_name??`model`})}};function yg(e){return vg[e]?.text_only_sessions??null}function bg(e,t,n={}){let r=vg[e]??vg.default;return{sessions:r.sessions(t,n,n.textOnly??!1),cache_sessions:r.cache_sessions,optional_configs:r.optional_configs}}function xg(e,{warn:t=!0}={}){let n=e.architectures||[];for(let e of n){let t=Ag.get(e);if(t!==void 0)return t}if(e.model_type){let t=Ag.get(e.model_type);if(t!==void 0)return t;for(let t of Object.values(wg))if(t.has(e.model_type)){let n=Ag.get(t.get(e.model_type));if(n!==void 0)return n}}if(t){let t=n.length>0?n.join(`, `):`(none)`;N.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${t}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Ld}`)}return X.EncoderOnly}function Sg(e,{config:t=null,cache_dir:n=null,local_files_only:r=!1,revision:i=`main`}={}){return t===null?qc(Nc(e,{cache_dir:n,local_files_only:r,revision:i}),()=>kh.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})):kh.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})}async function Cg(e,{config:t=null,dtype:n=null,device:r=null,model_file_name:i=null}={}){t=await Sg(e,{config:t});let a=[`config.json`],o=t[`transformers.js_config`]??{},s=o.use_external_data_format,c=`onnx`,l=r??o.device,u=n??o.dtype,d=xg(t),f=(e,t=null)=>{t??=e;let n=Jl(l,e),r=$l[eu(u,e,n)]??``,i=`${t}${r}.onnx`,o=`${c}/${i}`;a.push(o);let d=Ah(s,i,e);for(let e of jh(i,d)){let t=`${c}/${e}`;a.push(t)}},{sessions:p,optional_configs:m}=bg(d,t,{model_file_name:i});for(let[e,t]of Object.entries(p))f(e,t);if(m)for(let e of Object.values(m))a.push(e);return a}var wg=null;function Tg(e){wg=e}function Eg(e){if(e instanceof U)return e;if(e.length===0)throw Error(`items must be non-empty`);if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[0].length))throw Error(`Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.`);return new U(`int64`,BigInt64Array.from(e.flat().map(e=>BigInt(e))),[e.length,e[0].length])}return new U(`int64`,BigInt64Array.from(e.map(e=>BigInt(e))),[1,e.length])}function Dg(e){return new U(`bool`,[e],[1])}var Og={[X.DecoderOnly]:{can_generate:!0,forward:Vg,prepare_inputs:qg},[X.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Vg,prepare_inputs:qg},[X.Seq2Seq]:{can_generate:!0,forward:Ng,prepare_inputs:Jg},[X.Vision2Seq]:{can_generate:!0,forward:Ng,prepare_inputs:Jg},[X.Musicgen]:{can_generate:!0,forward:Ng},[X.EncoderDecoder]:{can_generate:!1,forward:Ng},[X.ImageTextToText]:{can_generate:!0,forward:Wg,prepare_inputs:Yg},[X.AudioTextToText]:{can_generate:!0,forward:Ug,prepare_inputs:Yg},[X.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Yg},[X.Phi3V]:{can_generate:!0,prepare_inputs:Yg},[X.MultiModality]:{can_generate:!0},[X.AutoEncoder]:{can_generate:!1,forward:Fg},[X.Chatterbox]:{can_generate:!0,forward:Pg},[X.VoxtralRealtime]:{can_generate:!0,prepare_inputs:qg},default:{can_generate:!1,forward:Pg}};function kg(e,t){let n=Ag.get(e),r=!1,i=t?.architectures?.[0];if(i&&i!==e&&e?.endsWith(`ForCausalLM`)&&i.endsWith(`ForConditionalGeneration`)){let e=Ag.get(i);e!==void 0&&(n=e,r=!0)}let a=Og[n]??Og.default,o=vg[n]??vg.default;return{typeConfig:{...a,...o},textOnly:r,modelType:n}}var Ag=/* @__PURE__ */ new Map,jg=/* @__PURE__ */ new Map,Mg=/* @__PURE__ */ new Map,Z=class extends ti{main_input_name=`input_ids`;forward_params=[`input_ids`,`attention_mask`];_return_dict_in_generate_keys=null;constructor(e,t,n){super(),this.config=e,this.sessions=t,this.configs=n;let{typeConfig:r}=kg(Mg.get(this.constructor),e);this.can_generate=r.can_generate,this._forward=r.forward,this._prepare_inputs_for_generation=r.prepare_inputs,this.can_generate&&this.forward_params.push(`past_key_values`),this.custom_config=this.config[`transformers.js_config`]??{}}async dispose(){let e=[];for(let t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d},p=Mg.get(this);n=f.config=await kh.from_pretrained(e,f);let{typeConfig:m,textOnly:h,modelType:g}=kg(p,n);if(g===void 0){let e=p??n?.model_type;e!==`custom`&&N.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${Ld}.`)}if(t&&!(t instanceof ri)){let r={};try{let t=await Cg(e,{config:n,dtype:l,device:c,model_file_name:o});(await Promise.all(t.map(t=>Yc(e,t,f)))).forEach((e,n)=>{if(e.exists){let i=t[n]===`config.json`;r[t[n]]={loaded:i?e.size??0:0,total:e.size??0}}})}catch(e){N.warn(`Unable to fetch model file metadata for total progress tracking: ${e}`)}Object.keys(r).length>0&&(f.progress_callback=new ri(t,r))}let _=[Fh(e,m.sessions(n,f,h),f,m.cache_sessions)];m.optional_configs&&_.push($g(e,m.optional_configs,f));let v=await Promise.all(_);return new this(n,...v)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,t,n=null){let r=new Yh;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&r.push(new ng(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&r.push(new tg(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&r.push(new ag(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&r.push(new rg(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&r.push(new ig(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&r.push(new Xh(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&r.push(new Zh(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&r.push(new Qh(e.suppress_tokens)),e.begin_suppress_tokens!==null){let n=t>1||e.forced_bos_token_id===null?t:t+1;r.push(new $h(e.begin_suppress_tokens,n))}return e.guidance_scale!==null&&e.guidance_scale>1&&r.push(new og(e.guidance_scale)),e.temperature===0&&e.do_sample&&(N.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&r.push(new sg(e.temperature)),n!==null&&r.extend(n),r}_prepare_generation_config(e,t,n=cg){let r={...this.config};for(let e of[`decoder`,`generator`,`text_config`])e in r&&Object.assign(r,r[e]);let i=new n(r);return Object.assign(i,this.generation_config??{}),e&&Object.assign(i,e),t&&Object.assign(i,ui(t,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(e,t=null){let n=new ug;return e.max_length!==null&&n.push(new dg(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&n.push(new fg(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){let e=[wg.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,wg.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,wg.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,wg.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=Mg.get(this.constructor),n=/* @__PURE__ */ new Set,r=this.config.model_type;for(let t of e){let e=t?.get(r);e&&n.add(e)}let i=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(i+=` Please use the following class instead: ${[...n].join(`, `)}`),Error(i)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw Error(`prepare_inputs_for_generation is not implemented for this model.`);return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:n,is_encoder_decoder:r}){return n.past_key_values=Ig(t,n.past_key_values),n.input_ids=new U(`int64`,e.flat(),[e.length,1]),r?`decoder_attention_mask`in n&&(n.decoder_attention_mask=mu([n.decoder_attention_mask,Cu([n.decoder_attention_mask.dims[0],1])],1)):n.attention_mask=mu([n.attention_mask,Cu([n.attention_mask.dims[0],1])],1),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:n}){let r=ui(n,this.forward_params),i=this.main_input_name;if(i in r){if(e)throw Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else r[i]=e;return{inputs_tensor:r[i],model_inputs:r,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:n,generation_config:r}){if(this.sessions.model.inputNames.includes(`inputs_embeds`)&&!t.inputs_embeds&&`_prepare_inputs_embeds`in this){let{input_ids:e,pixel_values:n,attention_mask:r,...i}=t,a=await this._prepare_inputs_embeds(t);t={...i,...ui(a,[`inputs_embeds`,`attention_mask`])}}let{last_hidden_state:i}=await Pg(this,t);if(r.guidance_scale!==null&&r.guidance_scale>1)i=mu([i,Su(i,0)],0),`attention_mask`in t&&(t.attention_mask=mu([t.attention_mask,Eu(t.attention_mask)],0));else if(t.decoder_input_ids){let e=Eg(t.decoder_input_ids).dims[0];if(e!==i.dims[0]){if(i.dims[0]!==1)throw Error(`The encoder outputs have a different batch size (${i.dims[0]}) than the decoder inputs (${e}).`);i=mu(Array.from({length:e},()=>i),0)}}return t.encoder_outputs=i,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:n,decoder_start_token_id:r,bos_token_id:i,generation_config:a}){let{decoder_input_ids:o,...s}=n;if(!(o instanceof U)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},()=>o));else if(r??=i,this.config.model_type===`musicgen`)o=Array.from({length:e*this.config.decoder.num_codebooks},()=>[r]);else if(Array.isArray(r)){if(r.length!==e)throw Error(`\`decoder_start_token_id\` expected to have length ${e} but got ${r.length}`);o=r}else o=Array.from({length:e},()=>[r]);o=Eg(o)}return s.decoder_attention_mask=wu(o),{input_ids:o,model_inputs:s}}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,streamer:i=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:o,model_inputs:s,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),l=this.config.is_encoder_decoder;l&&(`encoder_outputs`in s||(s=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:s,model_input_name:c,generation_config:t})));let u;l?{input_ids:u,model_inputs:s}=this._prepare_decoder_input_ids_for_generation({batch_size:s[c].dims.at(0),model_input_name:c,model_kwargs:s,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):u=s[c];let d=u.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=d+t.max_new_tokens);let f=this._get_logits_processor(t,d,n),p=this._get_stopping_criteria(t,r),m=s[c].dims.at(0),h=pg.getSampler(t),g=Array(m).fill(0),_=u.tolist();i&&i.put(_);let v,y={},b={};for(;;){if(s=this.prepare_inputs_for_generation(_,s,t),v=await this.forward(s),t.return_dict_in_generate){if(t.output_attentions){let e=Lg(v);for(let t in e)t in y||(y[t]=[]),y[t].push(e[t])}else this._return_dict_in_generate_keys&&Object.assign(b,ui(v,this._return_dict_in_generate_keys))}let e=f(_,v.logits.slice(null,-1,null).to(`float32`)),n=[];for(let t=0;te))break;s=this._update_model_kwargs_for_generation({generated_input_ids:n,outputs:v,model_inputs:s,is_encoder_decoder:l})}i&&i.end();let x=new U(`int64`,_.flat(),[_.length,_[0].length]),ee=Ig(v,s.past_key_values),S=new Set(Object.values(ee));for(let e of Object.values(v))e.location===`gpu-buffer`&&!S.has(e)&&e.dispose();return`past_key_values`in a||t.return_dict_in_generate||await ee.dispose(),t.return_dict_in_generate?{sequences:x,past_key_values:ee,...y,...b}:x}async _encode_input(e,t,n){if(!Object.hasOwn(this.sessions,e))throw Error(`Model does not have a ${e} session.`);let r=this.sessions[e];return(await J(r,ui(t,r.inputNames)))[n]}async encode_image(e){return this._encode_input(`vision_encoder`,e,`image_features`)}async encode_text(e){return this._encode_input(`embed_tokens`,e,`inputs_embeds`)}async encode_audio(e){return this._encode_input(`audio_encoder`,e,`audio_features`)}};async function Ng(e,t){let{encoder_outputs:n,input_ids:r,decoder_input_ids:i,decoder_attention_mask:a,...o}=t;return n||=(await Pg(e,ui(t,e.sessions.model.inputNames))).last_hidden_state,o.input_ids=i,o.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes(`encoder_attention_mask`)&&(o.encoder_attention_mask=t.attention_mask),a&&!o.attention_mask&&(o.attention_mask=a),await Vg(e,o,!0)}async function Pg(e,t){let n=e.sessions.model,r=ui(t,n.inputNames);if(n.inputNames.includes(`inputs_embeds`)&&!r.inputs_embeds){if(!t.input_ids)throw Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(n.inputNames.includes(`token_type_ids`)&&!r.token_type_ids){if(!r.input_ids)throw Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");r.token_type_ids=Eu(r.input_ids)}if(n.inputNames.includes(`pixel_mask`)&&!r.pixel_mask){if(!r.pixel_values)throw Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let e=r.pixel_values.dims;r.pixel_mask=Cu([e[0],e[2],e[3]])}return await J(n,r)}async function Fg(e,t){let n=await e.encode(t);return await e.decode(n)}function Ig(e,t){let n=/* @__PURE__ */ Object.create(null);for(let r in e)if(r.startsWith(`present`)){let i=r.replace(`present_ssm`,`past_ssm`).replace(`present_conv`,`past_conv`).replace(`present_recurrent`,`past_recurrent`).replace(`present_compressor`,`past_compressor`).replace(`present_indexer`,`past_indexer`).replace(`present`,`past_key_values`);n[i]=r.includes(`encoder`)&&t?t[i]:e[r]}return t?(t.update(n),t):new _g(n)}function Lg(e){let t={};for(let n of[`cross_attentions`,`encoder_attentions`,`decoder_attentions`])for(let r in e)r.startsWith(n)&&(n in t||(t[n]=[]),t[n].push(e[r]));return t}function Rg(e,t){return e.map(e=>typeof e==`number`?e:t[e]??0)}function zg(e,t,n){if(n&&Object.keys(n).length>0)return Object.assign(t,n),n;let r=e.sessions.decoder_model_merged??e.sessions.model,i=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=Eh(e.config),o=e.config?.normalized_config?.num_heads,s={batch_size:i};typeof o==`number`&&(s[`batch_size x num_heads`]=i*o);let c=/* @__PURE__ */ Object.create(null);for(let e of r.inputMetadata){if(!a.has(e.name))continue;let n=Rg(e.shape,s),r=n.reduce((e,t)=>e*t,1),i=tu[e.type],o=new U(e.type,new i(r),n);t[e.name]=o,c[e.name]=o}return n?(n.update(c),n):new _g(c)}function Bg(e,t,n){t.num_logits_to_keep||(e.sessions.decoder_model_merged??e.sessions.model)?.inputNames.includes(`num_logits_to_keep`)&&(t.num_logits_to_keep=new U(`int64`,[n],[]))}async function Vg(e,t,n=!1){let r=e.sessions[n?`decoder_model_merged`:`model`],{past_key_values:i,...a}=t;return r.inputNames.includes(`use_cache_branch`)&&(a.use_cache_branch=Dg(i!=null&&Object.keys(i).length>0)),r.inputNames.includes(`position_ids`)&&a.attention_mask&&!a.position_ids&&(a.position_ids=Kg(a,i,+!![`paligemma`,`gemma3_text`,`gemma3`].includes(e.config.model_type))),Bg(e,a,0n),zg(e,a,i),await J(r,ui(a,r.inputNames))}async function Hg(e,{encode_function:t,merge_function:n,modality_input_names:r,modality_output_name:i,input_ids:a=null,attention_mask:o=null,position_ids:s=null,inputs_embeds:c=null,past_key_values:l=null,generation_config:u=null,logits_processor:d=null,num_logits_to_keep:f=null,...p}){if(!c){c=await e.encode_text({input_ids:a,...p});let s=ui(p,r);if(Object.keys(s).length>0){if(a.dims[1]!==1){let e=await t({...s,...p});({inputs_embeds:c,attention_mask:o}=n({[i]:e,inputs_embeds:c,input_ids:a,attention_mask:o}))}else if(l&&a.dims[1]===1){let e=a.dims[1],t=l.get_seq_length();o=mu([Cu([a.dims[0],t]),o.slice(null,[o.dims[1]-e,o.dims[1]])],1)}}}if(!s&&[`qwen2_vl`,`qwen2_vl_text`,`qwen2_5_vl`,`qwen2_5_vl_text`,`qwen3_vl`,`qwen3_vl_text`,`qwen3_vl_moe`,`qwen3_vl_moe_text`,`qwen3_5`,`qwen3_5_text`,`qwen3_5_moe`,`qwen3_5_moe_text`,`glm_ocr`,`glm_ocr_text`].includes(e.config.model_type)){let{image_grid_thw:t,video_grid_thw:n}=p;[s]=e.get_rope_index(a,t,n,o)}return await Vg(e,{inputs_embeds:c,past_key_values:l,attention_mask:o,position_ids:s,generation_config:u,logits_processor:d,num_logits_to_keep:f},!0)}async function Ug(e,t){return await Hg(e,{...t,modality_input_names:[`audio_values`,`input_features`],modality_output_name:`audio_features`,encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function Wg(e,t){return await Hg(e,{...t,modality_input_names:[`pixel_values`],modality_output_name:`image_features`,encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function Gg(e,t=0){let[n,r]=e.dims,i=e.data,a=new BigInt64Array(i.length);for(let e=0;ee.dims[1]||i[e.at(-1)])),Bg(e,n,1n),{...n,decoder_input_ids:Eg(t)}}function Yg(e,...t){return e.config.is_encoder_decoder?Jg(e,...t):qg(e,...t)}function Xg({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i}){let a=r.tolist().map(t=>t.reduce((t,n,r)=>(n==e&&t.push(r),t),[])),o=a.reduce((e,t)=>e+t.length,0),s=n.dims[0];if(o!==s)throw Error(`Number of tokens and features do not match: tokens: ${o}, features ${s}`);let c=0;for(let e=0;e[r,await ol(e,t[r],!1,n)])))}var e_={};Tr(e_,{ASTForAudioClassification:()=>__,ASTModel:()=>g_,ASTPreTrainedModel:()=>h_,AfmoeForCausalLM:()=>d_,AfmoeModel:()=>u_,AfmoePreTrainedModel:()=>l_,AlbertForMaskedLM:()=>a_,AlbertForQuestionAnswering:()=>i_,AlbertForSequenceClassification:()=>r_,AlbertModel:()=>n_,AlbertPreTrainedModel:()=>t_,ApertusForCausalLM:()=>c_,ApertusModel:()=>s_,ApertusPreTrainedModel:()=>o_,ArceeForCausalLM:()=>m_,ArceeModel:()=>p_,ArceePreTrainedModel:()=>f_,BartForConditionalGeneration:()=>b_,BartForSequenceClassification:()=>x_,BartModel:()=>y_,BartPretrainedModel:()=>v_,BaseModelOutput:()=>zh,BeitForImageClassification:()=>w_,BeitModel:()=>C_,BeitPreTrainedModel:()=>S_,BertForMaskedLM:()=>D_,BertForQuestionAnswering:()=>A_,BertForSequenceClassification:()=>O_,BertForTokenClassification:()=>k_,BertModel:()=>E_,BertPreTrainedModel:()=>T_,BlenderbotForConditionalGeneration:()=>N_,BlenderbotModel:()=>M_,BlenderbotPreTrainedModel:()=>j_,BlenderbotSmallForConditionalGeneration:()=>I_,BlenderbotSmallModel:()=>F_,BlenderbotSmallPreTrainedModel:()=>P_,BloomForCausalLM:()=>z_,BloomModel:()=>R_,BloomPreTrainedModel:()=>L_,CHMv2ForDepthEstimation:()=>$_,CHMv2PreTrainedModel:()=>Q_,CLIPModel:()=>av,CLIPPreTrainedModel:()=>iv,CLIPSegForImageSegmentation:()=>fv,CLIPSegModel:()=>dv,CLIPSegPreTrainedModel:()=>uv,CLIPTextModel:()=>ov,CLIPTextModelWithProjection:()=>sv,CLIPVisionModel:()=>cv,CLIPVisionModelWithProjection:()=>lv,CamembertForMaskedLM:()=>H_,CamembertForQuestionAnswering:()=>G_,CamembertForSequenceClassification:()=>U_,CamembertForTokenClassification:()=>W_,CamembertModel:()=>V_,CamembertPreTrainedModel:()=>B_,CausalLMOutput:()=>Uh,CausalLMOutputWithPast:()=>Wh,ChatterboxModel:()=>Y_,ChatterboxPreTrainedModel:()=>J_,ChineseCLIPModel:()=>Z_,ChineseCLIPPreTrainedModel:()=>X_,ClapAudioModelWithProjection:()=>rv,ClapModel:()=>tv,ClapPreTrainedModel:()=>ev,ClapTextModelWithProjection:()=>nv,CodeGenForCausalLM:()=>hv,CodeGenModel:()=>mv,CodeGenPreTrainedModel:()=>pv,Cohere2ForCausalLM:()=>xv,Cohere2Model:()=>bv,Cohere2PreTrainedModel:()=>yv,CohereAsrForConditionalGeneration:()=>wv,CohereAsrModel:()=>Cv,CohereAsrPreTrainedModel:()=>Sv,CohereForCausalLM:()=>vv,CohereModel:()=>_v,CoherePreTrainedModel:()=>gv,ConvBertForMaskedLM:()=>Dv,ConvBertForQuestionAnswering:()=>Av,ConvBertForSequenceClassification:()=>Ov,ConvBertForTokenClassification:()=>kv,ConvBertModel:()=>Ev,ConvBertPreTrainedModel:()=>Tv,ConvNextForImageClassification:()=>Nv,ConvNextModel:()=>Mv,ConvNextPreTrainedModel:()=>jv,ConvNextV2ForImageClassification:()=>Iv,ConvNextV2Model:()=>Fv,ConvNextV2PreTrainedModel:()=>Pv,DFineForObjectDetection:()=>Uv,DFineModel:()=>Hv,DFinePreTrainedModel:()=>Vv,DINOv3ConvNextModel:()=>Iy,DINOv3ConvNextPreTrainedModel:()=>Fy,DINOv3ViTModel:()=>Ry,DINOv3ViTPreTrainedModel:()=>Ly,DPTForDepthEstimation:()=>Yy,DPTModel:()=>Jy,DPTPreTrainedModel:()=>qy,DacDecoderModel:()=>Yv,DacDecoderOutput:()=>Gv,DacEncoderModel:()=>Jv,DacEncoderOutput:()=>Wv,DacModel:()=>qv,DacPreTrainedModel:()=>Kv,DebertaForMaskedLM:()=>Qv,DebertaForQuestionAnswering:()=>ty,DebertaForSequenceClassification:()=>$v,DebertaForTokenClassification:()=>ey,DebertaModel:()=>Zv,DebertaPreTrainedModel:()=>Xv,DebertaV2ForMaskedLM:()=>uy,DebertaV2ForQuestionAnswering:()=>py,DebertaV2ForSequenceClassification:()=>dy,DebertaV2ForTokenClassification:()=>fy,DebertaV2Model:()=>ly,DebertaV2PreTrainedModel:()=>cy,DecisionTransformerModel:()=>hy,DecisionTransformerPreTrainedModel:()=>my,DeepseekV3ForCausalLM:()=>iy,DeepseekV3Model:()=>ry,DeepseekV3PreTrainedModel:()=>ny,DeepseekV4ForCausalLM:()=>sy,DeepseekV4Model:()=>oy,DeepseekV4PreTrainedModel:()=>ay,DeiTForImageClassification:()=>vy,DeiTModel:()=>_y,DeiTPreTrainedModel:()=>gy,DepthAnythingForDepthEstimation:()=>by,DepthAnythingPreTrainedModel:()=>yy,DepthProForDepthEstimation:()=>Sy,DepthProPreTrainedModel:()=>xy,DetrForObjectDetection:()=>Ty,DetrForSegmentation:()=>Ey,DetrModel:()=>wy,DetrObjectDetectionOutput:()=>Dy,DetrPreTrainedModel:()=>Cy,DetrSegmentationOutput:()=>Oy,Dinov2ForImageClassification:()=>jy,Dinov2Model:()=>Ay,Dinov2PreTrainedModel:()=>ky,Dinov2WithRegistersForImageClassification:()=>Py,Dinov2WithRegistersModel:()=>Ny,Dinov2WithRegistersPreTrainedModel:()=>My,DistilBertForMaskedLM:()=>Wy,DistilBertForQuestionAnswering:()=>Uy,DistilBertForSequenceClassification:()=>Vy,DistilBertForTokenClassification:()=>Hy,DistilBertModel:()=>By,DistilBertPreTrainedModel:()=>zy,DonutSwinModel:()=>Ky,DonutSwinPreTrainedModel:()=>Gy,EdgeTamModel:()=>IE,EfficientNetForImageClassification:()=>Qy,EfficientNetModel:()=>Zy,EfficientNetPreTrainedModel:()=>Xy,ElectraForMaskedLM:()=>tb,ElectraForQuestionAnswering:()=>ib,ElectraForSequenceClassification:()=>nb,ElectraForTokenClassification:()=>rb,ElectraModel:()=>eb,ElectraPreTrainedModel:()=>$y,Ernie4_5ForCausalLM:()=>sb,Ernie4_5Model:()=>ob,Ernie4_5PretrainedModel:()=>ab,EsmForMaskedLM:()=>ub,EsmForSequenceClassification:()=>db,EsmForTokenClassification:()=>fb,EsmModel:()=>lb,EsmPreTrainedModel:()=>cb,EuroBertForMaskedLM:()=>hb,EuroBertForSequenceClassification:()=>gb,EuroBertForTokenClassification:()=>_b,EuroBertModel:()=>mb,EuroBertPreTrainedModel:()=>pb,ExaoneForCausalLM:()=>bb,ExaoneModel:()=>yb,ExaonePreTrainedModel:()=>vb,FalconForCausalLM:()=>Cb,FalconH1ForCausalLM:()=>Eb,FalconH1Model:()=>Tb,FalconH1PreTrainedModel:()=>wb,FalconModel:()=>Sb,FalconPreTrainedModel:()=>xb,FastViTForImageClassification:()=>kb,FastViTModel:()=>Ob,FastViTPreTrainedModel:()=>Db,Florence2ForConditionalGeneration:()=>jb,Florence2PreTrainedModel:()=>Ab,GLPNForDepthEstimation:()=>dx,GLPNModel:()=>ux,GLPNPreTrainedModel:()=>lx,GPT2LMHeadModel:()=>Ex,GPT2Model:()=>Tx,GPT2PreTrainedModel:()=>wx,GPTBigCodeForCausalLM:()=>mx,GPTBigCodeModel:()=>px,GPTBigCodePreTrainedModel:()=>fx,GPTJForCausalLM:()=>kx,GPTJModel:()=>Ox,GPTJPreTrainedModel:()=>Dx,GPTNeoForCausalLM:()=>_x,GPTNeoModel:()=>gx,GPTNeoPreTrainedModel:()=>hx,GPTNeoXForCausalLM:()=>bx,GPTNeoXModel:()=>yx,GPTNeoXPreTrainedModel:()=>vx,Gemma2ForCausalLM:()=>Lb,Gemma2Model:()=>Ib,Gemma2PreTrainedModel:()=>Fb,Gemma3ForCausalLM:()=>Gb,Gemma3ForConditionalGeneration:()=>Wb,Gemma3Model:()=>Ub,Gemma3PreTrainedModel:()=>Hb,Gemma3nForCausalLM:()=>Jb,Gemma3nForConditionalGeneration:()=>qb,Gemma3nPreTrainedModel:()=>Kb,Gemma4ForCausalLM:()=>Xb,Gemma4ForConditionalGeneration:()=>Yb,GemmaForCausalLM:()=>Pb,GemmaModel:()=>Nb,GemmaPreTrainedModel:()=>Mb,GlmForCausalLM:()=>$b,GlmModel:()=>Qb,GlmMoeDsaForCausalLM:()=>nx,GlmMoeDsaModel:()=>tx,GlmMoeDsaPreTrainedModel:()=>ex,GlmOcrForConditionalGeneration:()=>cx,GlmPreTrainedModel:()=>Zb,GptOssForCausalLM:()=>Cx,GptOssModel:()=>Sx,GptOssPreTrainedModel:()=>xx,GraniteForCausalLM:()=>Mx,GraniteModel:()=>jx,GraniteMoeHybridForCausalLM:()=>Fx,GraniteMoeHybridModel:()=>Px,GraniteMoeHybridPreTrainedModel:()=>Nx,GranitePreTrainedModel:()=>Ax,GraniteSpeechForConditionalGeneration:()=>Rx,GroundingDinoForObjectDetection:()=>Bx,GroundingDinoPreTrainedModel:()=>zx,GroupViTModel:()=>Hx,GroupViTPreTrainedModel:()=>Vx,HeliumForCausalLM:()=>Gx,HeliumModel:()=>Wx,HeliumPreTrainedModel:()=>Ux,HieraForImageClassification:()=>Jx,HieraModel:()=>qx,HieraPreTrainedModel:()=>Kx,HrmTextForCausalLM:()=>Zx,HrmTextModel:()=>Xx,HrmTextPreTrainedModel:()=>Yx,HubertForCTC:()=>aS,HubertForSequenceClassification:()=>oS,HubertModel:()=>iS,HubertPreTrainedModel:()=>rS,HunYuanDenseV1ForCausalLM:()=>lS,HunYuanDenseV1Model:()=>cS,HunYuanDenseV1PreTrainedModel:()=>sS,IJepaForImageClassification:()=>pS,IJepaModel:()=>fS,IJepaPreTrainedModel:()=>dS,Idefics3ForConditionalGeneration:()=>uS,ImageMattingOutput:()=>Kh,JAISLMHeadModel:()=>gS,JAISModel:()=>hS,JAISPreTrainedModel:()=>mS,JinaCLIPModel:()=>vS,JinaCLIPPreTrainedModel:()=>_S,JinaCLIPTextModel:()=>yS,JinaCLIPVisionModel:()=>bS,Lfm2ForCausalLM:()=>CS,Lfm2Model:()=>SS,Lfm2MoeForCausalLM:()=>DS,Lfm2MoeModel:()=>ES,Lfm2MoePreTrainedModel:()=>TS,Lfm2PreTrainedModel:()=>xS,Lfm2VlForConditionalGeneration:()=>OS,LightOnOcrForConditionalGeneration:()=>wS,LiteWhisperForConditionalGeneration:()=>GO,Llama4ForCausalLM:()=>NS,Llama4PreTrainedModel:()=>MS,LlamaForCausalLM:()=>jS,LlamaModel:()=>AS,LlamaPreTrainedModel:()=>kS,LlavaForConditionalGeneration:()=>zb,LlavaOnevisionForConditionalGeneration:()=>zb,LlavaPreTrainedModel:()=>Rb,LlavaQwen2ForCausalLM:()=>Vb,LongT5ForConditionalGeneration:()=>IS,LongT5Model:()=>FS,LongT5PreTrainedModel:()=>PS,M2M100ForConditionalGeneration:()=>zS,M2M100Model:()=>RS,M2M100PreTrainedModel:()=>LS,MBartForCausalLM:()=>XS,MBartForConditionalGeneration:()=>JS,MBartForSequenceClassification:()=>YS,MBartModel:()=>qS,MBartPreTrainedModel:()=>KS,MPNetForMaskedLM:()=>fw,MPNetForQuestionAnswering:()=>hw,MPNetForSequenceClassification:()=>pw,MPNetForTokenClassification:()=>mw,MPNetModel:()=>dw,MPNetPreTrainedModel:()=>uw,MT5ForConditionalGeneration:()=>xw,MT5Model:()=>bw,MT5PreTrainedModel:()=>yw,MarianMTModel:()=>HS,MarianModel:()=>VS,MarianPreTrainedModel:()=>BS,MaskFormerForInstanceSegmentation:()=>GS,MaskFormerModel:()=>WS,MaskFormerPreTrainedModel:()=>US,MaskedLMOutput:()=>Vh,Metric3DForDepthEstimation:()=>QS,Metric3DPreTrainedModel:()=>ZS,Metric3Dv2ForDepthEstimation:()=>eC,Metric3Dv2PreTrainedModel:()=>$S,MgpstrForSceneTextRecognition:()=>rC,MgpstrModelOutput:()=>tC,MgpstrPreTrainedModel:()=>nC,MimiDecoderModel:()=>lC,MimiDecoderOutput:()=>aC,MimiEncoderModel:()=>cC,MimiEncoderOutput:()=>iC,MimiModel:()=>sC,MimiPreTrainedModel:()=>oC,Ministral3ForCausalLM:()=>hC,Ministral3Model:()=>mC,Ministral3PreTrainedModel:()=>pC,MinistralForCausalLM:()=>fC,MinistralModel:()=>dC,MinistralPreTrainedModel:()=>uC,Mistral3ForConditionalGeneration:()=>yC,Mistral4ForCausalLM:()=>SC,Mistral4Model:()=>xC,Mistral4PreTrainedModel:()=>bC,MistralForCausalLM:()=>vC,MistralModel:()=>_C,MistralPreTrainedModel:()=>gC,MobileBertForMaskedLM:()=>TC,MobileBertForQuestionAnswering:()=>DC,MobileBertForSequenceClassification:()=>EC,MobileBertModel:()=>wC,MobileBertPreTrainedModel:()=>CC,MobileLLMForCausalLM:()=>AC,MobileLLMModel:()=>kC,MobileLLMPreTrainedModel:()=>OC,MobileNetV1ForImageClassification:()=>NC,MobileNetV1ForSemanticSegmentation:()=>PC,MobileNetV1Model:()=>MC,MobileNetV1PreTrainedModel:()=>jC,MobileNetV2ForImageClassification:()=>LC,MobileNetV2ForSemanticSegmentation:()=>RC,MobileNetV2Model:()=>IC,MobileNetV2PreTrainedModel:()=>FC,MobileNetV3ForImageClassification:()=>VC,MobileNetV3ForSemanticSegmentation:()=>HC,MobileNetV3Model:()=>BC,MobileNetV3PreTrainedModel:()=>zC,MobileNetV4ForImageClassification:()=>GC,MobileNetV4ForSemanticSegmentation:()=>KC,MobileNetV4Model:()=>WC,MobileNetV4PreTrainedModel:()=>UC,MobileViTForImageClassification:()=>YC,MobileViTModel:()=>JC,MobileViTPreTrainedModel:()=>qC,MobileViTV2ForImageClassification:()=>QC,MobileViTV2Model:()=>ZC,MobileViTV2PreTrainedModel:()=>XC,ModelOutput:()=>Rh,ModernBertDecoderForCausalLM:()=>ow,ModernBertDecoderModel:()=>aw,ModernBertDecoderPreTrainedModel:()=>iw,ModernBertForMaskedLM:()=>tw,ModernBertForSequenceClassification:()=>nw,ModernBertForTokenClassification:()=>rw,ModernBertModel:()=>ew,ModernBertPreTrainedModel:()=>$C,Moondream1ForConditionalGeneration:()=>Bb,MoonshineForConditionalGeneration:()=>lw,MoonshineModel:()=>cw,MoonshinePreTrainedModel:()=>sw,MptForCausalLM:()=>vw,MptModel:()=>_w,MptPreTrainedModel:()=>gw,MultiModalityCausalLM:()=>Cw,MultiModalityPreTrainedModel:()=>Sw,MusicgenForCausalLM:()=>Ew,MusicgenForConditionalGeneration:()=>Dw,MusicgenModel:()=>Tw,MusicgenPreTrainedModel:()=>ww,NanoChatForCausalLM:()=>Aw,NanoChatModel:()=>kw,NanoChatPreTrainedModel:()=>Ow,NemotronHForCausalLM:()=>Nw,NemotronHModel:()=>Mw,NemotronHPreTrainedModel:()=>jw,NeoBertForMaskedLM:()=>Iw,NeoBertForQuestionAnswering:()=>zw,NeoBertForSequenceClassification:()=>Lw,NeoBertForTokenClassification:()=>Rw,NeoBertModel:()=>Fw,NeoBertPreTrainedModel:()=>Pw,NomicBertModel:()=>Vw,NomicBertPreTrainedModel:()=>Bw,OPTForCausalLM:()=>cT,OPTModel:()=>sT,OPTPreTrainedModel:()=>oT,Olmo2ForCausalLM:()=>qw,Olmo2Model:()=>Kw,Olmo2PreTrainedModel:()=>Gw,Olmo3ForCausalLM:()=>Xw,Olmo3Model:()=>Yw,Olmo3PreTrainedModel:()=>Jw,OlmoForCausalLM:()=>Ww,OlmoHybridForCausalLM:()=>$w,OlmoHybridModel:()=>Qw,OlmoHybridPreTrainedModel:()=>Zw,OlmoModel:()=>Uw,OlmoPreTrainedModel:()=>Hw,OpenAIPrivacyFilterForTokenClassification:()=>nT,OpenAIPrivacyFilterModel:()=>tT,OpenAIPrivacyFilterPreTrainedModel:()=>eT,OpenELMForCausalLM:()=>aT,OpenELMModel:()=>iT,OpenELMPreTrainedModel:()=>rT,OwlViTForObjectDetection:()=>mT,OwlViTModel:()=>pT,OwlViTPreTrainedModel:()=>fT,Owlv2ForObjectDetection:()=>dT,Owlv2Model:()=>uT,Owlv2PreTrainedModel:()=>lT,PaliGemmaForConditionalGeneration:()=>hT,ParakeetForCTC:()=>_T,ParakeetPreTrainedModel:()=>gT,PatchTSMixerForPrediction:()=>bT,PatchTSMixerModel:()=>yT,PatchTSMixerPreTrainedModel:()=>vT,PatchTSTForPrediction:()=>CT,PatchTSTModel:()=>ST,PatchTSTPreTrainedModel:()=>xT,Phi3ForCausalLM:()=>kT,Phi3Model:()=>OT,Phi3PreTrainedModel:()=>DT,Phi3VForCausalLM:()=>jT,Phi3VPreTrainedModel:()=>AT,PhiForCausalLM:()=>ET,PhiModel:()=>TT,PhiPreTrainedModel:()=>wT,PreTrainedModel:()=>Z,PvtForImageClassification:()=>PT,PvtModel:()=>NT,PvtPreTrainedModel:()=>MT,PyAnnoteForAudioFrameClassification:()=>LT,PyAnnoteModel:()=>IT,PyAnnotePreTrainedModel:()=>FT,QuestionAnsweringModelOutput:()=>Hh,Qwen2ForCausalLM:()=>BT,Qwen2Model:()=>zT,Qwen2MoeForCausalLM:()=>UT,Qwen2MoeModel:()=>HT,Qwen2MoePreTrainedModel:()=>VT,Qwen2PreTrainedModel:()=>RT,Qwen2VLForCausalLM:()=>ax,Qwen2VLForConditionalGeneration:()=>ix,Qwen2VLPreTrainedModel:()=>rx,Qwen2_5_VLForCausalLM:()=>sx,Qwen2_5_VLForConditionalGeneration:()=>ox,Qwen3ForCausalLM:()=>KT,Qwen3Model:()=>GT,Qwen3MoeForCausalLM:()=>YT,Qwen3MoeModel:()=>JT,Qwen3MoePreTrainedModel:()=>qT,Qwen3NextForCausalLM:()=>QT,Qwen3NextModel:()=>ZT,Qwen3NextPreTrainedModel:()=>XT,Qwen3PreTrainedModel:()=>WT,Qwen3VLForCausalLM:()=>eE,Qwen3VLForConditionalGeneration:()=>$T,Qwen3VLMoeForCausalLM:()=>nE,Qwen3VLMoeForConditionalGeneration:()=>tE,Qwen3_5ForCausalLM:()=>iE,Qwen3_5ForConditionalGeneration:()=>rE,Qwen3_5MoeForCausalLM:()=>oE,Qwen3_5MoeForConditionalGeneration:()=>aE,RFDetrForObjectDetection:()=>fE,RFDetrModel:()=>dE,RFDetrObjectDetectionOutput:()=>pE,RFDetrPreTrainedModel:()=>uE,RTDetrForObjectDetection:()=>zv,RTDetrModel:()=>Rv,RTDetrObjectDetectionOutput:()=>Bv,RTDetrPreTrainedModel:()=>Lv,RTDetrV2ForObjectDetection:()=>OE,RTDetrV2Model:()=>DE,RTDetrV2ObjectDetectionOutput:()=>kE,RTDetrV2PreTrainedModel:()=>EE,ResNetForImageClassification:()=>lE,ResNetModel:()=>cE,ResNetPreTrainedModel:()=>sE,RoFormerForMaskedLM:()=>SE,RoFormerForQuestionAnswering:()=>TE,RoFormerForSequenceClassification:()=>CE,RoFormerForTokenClassification:()=>wE,RoFormerModel:()=>xE,RoFormerPreTrainedModel:()=>bE,RobertaForMaskedLM:()=>gE,RobertaForQuestionAnswering:()=>yE,RobertaForSequenceClassification:()=>_E,RobertaForTokenClassification:()=>vE,RobertaModel:()=>hE,RobertaPreTrainedModel:()=>mE,Sam2ImageSegmentationOutput:()=>NE,Sam2Model:()=>FE,Sam2PreTrainedModel:()=>PE,Sam3TrackerModel:()=>LE,SamImageSegmentationOutput:()=>AE,SamModel:()=>ME,SamPreTrainedModel:()=>jE,SapiensForDepthEstimation:()=>BE,SapiensForNormalEstimation:()=>VE,SapiensForSemanticSegmentation:()=>zE,SapiensPreTrainedModel:()=>RE,SegformerForImageClassification:()=>WE,SegformerForSemanticSegmentation:()=>GE,SegformerModel:()=>UE,SegformerPreTrainedModel:()=>HE,Seq2SeqLMOutput:()=>Gh,SequenceClassifierOutput:()=>Y,SiglipModel:()=>qE,SiglipPreTrainedModel:()=>KE,SiglipTextModel:()=>JE,SiglipVisionModel:()=>YE,SmolLM3ForCausalLM:()=>QE,SmolLM3Model:()=>ZE,SmolLM3PreTrainedModel:()=>XE,SmolVLMForConditionalGeneration:()=>$E,SnacDecoderModel:()=>rD,SnacEncoderModel:()=>nD,SnacModel:()=>tD,SnacPreTrainedModel:()=>eD,SolarOpenForCausalLM:()=>oD,SolarOpenModel:()=>aD,SolarOpenPreTrainedModel:()=>iD,SpeechT5ForSpeechToText:()=>lD,SpeechT5ForTextToSpeech:()=>uD,SpeechT5HifiGan:()=>dD,SpeechT5Model:()=>cD,SpeechT5PreTrainedModel:()=>sD,SqueezeBertForMaskedLM:()=>mD,SqueezeBertForQuestionAnswering:()=>gD,SqueezeBertForSequenceClassification:()=>hD,SqueezeBertModel:()=>pD,SqueezeBertPreTrainedModel:()=>fD,StableLmForCausalLM:()=>yD,StableLmModel:()=>vD,StableLmPreTrainedModel:()=>_D,Starcoder2ForCausalLM:()=>SD,Starcoder2Model:()=>xD,Starcoder2PreTrainedModel:()=>bD,StyleTextToSpeech2Model:()=>wD,StyleTextToSpeech2PreTrainedModel:()=>CD,SupertonicForConditionalGeneration:()=>ED,SupertonicPreTrainedModel:()=>TD,Swin2SRForImageSuperResolution:()=>ND,Swin2SRModel:()=>MD,Swin2SRPreTrainedModel:()=>jD,SwinForImageClassification:()=>kD,SwinForSemanticSegmentation:()=>AD,SwinModel:()=>OD,SwinPreTrainedModel:()=>DD,T5ForConditionalGeneration:()=>ID,T5Model:()=>FD,T5PreTrainedModel:()=>PD,TableTransformerForObjectDetection:()=>zD,TableTransformerModel:()=>RD,TableTransformerObjectDetectionOutput:()=>BD,TableTransformerPreTrainedModel:()=>LD,TokenClassifierOutput:()=>Bh,TrOCRForCausalLM:()=>HD,TrOCRPreTrainedModel:()=>VD,UltravoxModel:()=>Lx,UltravoxPreTrainedModel:()=>Ix,UniSpeechForCTC:()=>GD,UniSpeechForSequenceClassification:()=>KD,UniSpeechModel:()=>WD,UniSpeechPreTrainedModel:()=>UD,UniSpeechSatForAudioFrameClassification:()=>ZD,UniSpeechSatForCTC:()=>YD,UniSpeechSatForSequenceClassification:()=>XD,UniSpeechSatModel:()=>JD,UniSpeechSatPreTrainedModel:()=>qD,VaultGemmaForCausalLM:()=>eO,VaultGemmaModel:()=>$D,VaultGemmaPreTrainedModel:()=>QD,ViTForImageClassification:()=>iO,ViTMAEModel:()=>oO,ViTMAEPreTrainedModel:()=>aO,ViTMSNForImageClassification:()=>lO,ViTMSNModel:()=>cO,ViTMSNPreTrainedModel:()=>sO,ViTModel:()=>rO,ViTPreTrainedModel:()=>nO,VisionEncoderDecoderModel:()=>tO,VitMatteForImageMatting:()=>dO,VitMattePreTrainedModel:()=>uO,VitPoseForPoseEstimation:()=>pO,VitPosePreTrainedModel:()=>fO,VitsModel:()=>gO,VitsModelOutput:()=>mO,VitsPreTrainedModel:()=>hO,VoxtralForConditionalGeneration:()=>_O,VoxtralRealtimeForConditionalGeneration:()=>DO,VoxtralRealtimePreTrainedModel:()=>EO,Wav2Vec2BertForCTC:()=>AO,Wav2Vec2BertForSequenceClassification:()=>jO,Wav2Vec2BertModel:()=>kO,Wav2Vec2BertPreTrainedModel:()=>OO,Wav2Vec2ForAudioFrameClassification:()=>nS,Wav2Vec2ForCTC:()=>eS,Wav2Vec2ForSequenceClassification:()=>tS,Wav2Vec2Model:()=>$x,Wav2Vec2PreTrainedModel:()=>Qx,WavLMForAudioFrameClassification:()=>RO,WavLMForCTC:()=>FO,WavLMForSequenceClassification:()=>IO,WavLMForXVector:()=>LO,WavLMModel:()=>PO,WavLMPreTrainedModel:()=>NO,WeSpeakerResNetModel:()=>BO,WeSpeakerResNetPreTrainedModel:()=>zO,WhisperForConditionalGeneration:()=>WO,WhisperModel:()=>UO,WhisperPreTrainedModel:()=>HO,XLMForQuestionAnswering:()=>ZO,XLMForSequenceClassification:()=>YO,XLMForTokenClassification:()=>XO,XLMModel:()=>qO,XLMPreTrainedModel:()=>KO,XLMRobertaForMaskedLM:()=>ek,XLMRobertaForQuestionAnswering:()=>rk,XLMRobertaForSequenceClassification:()=>tk,XLMRobertaForTokenClassification:()=>nk,XLMRobertaModel:()=>$O,XLMRobertaPreTrainedModel:()=>QO,XLMWithLMHeadModel:()=>JO,XVectorOutput:()=>MO,YolosForObjectDetection:()=>ok,YolosModel:()=>ak,YolosObjectDetectionOutput:()=>sk,YolosPreTrainedModel:()=>ik,YoutuForCausalLM:()=>uk,YoutuModel:()=>lk,YoutuPreTrainedModel:()=>ck,ZayaForCausalLM:()=>pk,ZayaModel:()=>fk,ZayaPreTrainedModel:()=>dk});var t_=class extends Z{},n_=class extends t_{},r_=class extends t_{async _call(e){return new Y(await super._call(e))}},i_=class extends t_{async _call(e){return new Hh(await super._call(e))}},a_=class extends t_{async _call(e){return new Vh(await super._call(e))}},o_=class extends Z{},s_=class extends o_{},c_=class extends o_{},l_=class extends Z{},u_=class extends l_{},d_=class extends l_{},f_=class extends Z{},p_=class extends f_{},m_=class extends f_{},h_=class extends Z{},g_=class extends h_{},__=class extends h_{},v_=class extends Z{},y_=class extends v_{},b_=class extends v_{},x_=class extends v_{async _call(e){return new Y(await super._call(e))}},S_=class extends Z{},C_=class extends S_{},w_=class extends S_{async _call(e){return new Y(await super._call(e))}},T_=class extends Z{},E_=class extends T_{},D_=class extends T_{async _call(e){return new Vh(await super._call(e))}},O_=class extends T_{async _call(e){return new Y(await super._call(e))}},k_=class extends T_{async _call(e){return new Bh(await super._call(e))}},A_=class extends T_{async _call(e){return new Hh(await super._call(e))}},j_=class extends Z{},M_=class extends j_{},N_=class extends j_{},P_=class extends Z{},F_=class extends P_{},I_=class extends P_{},L_=class extends Z{},R_=class extends L_{},z_=class extends L_{},B_=class extends Z{},V_=class extends B_{},H_=class extends B_{async _call(e){return new Vh(await super._call(e))}},U_=class extends B_{async _call(e){return new Y(await super._call(e))}},W_=class extends B_{async _call(e){return new Bh(await super._call(e))}},G_=class extends B_{async _call(e){return new Hh(await super._call(e))}},K_=4299n,q_=6561n,J_=class extends Z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`audio_values`,`exaggeration`,`audio_features`,`audio_tokens`,`speaker_embeddings`,`speaker_features`,`past_key_values`];main_input_name=`input_ids`;_return_dict_in_generate_keys=[`audio_tokens`,`speaker_embeddings`,`speaker_features`]},Y_=class extends J_{async encode_speech(e){return J(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:n=null,exaggeration:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,num_logits_to_keep:l=null,audio_features:u=null,audio_tokens:d=null,speaker_embeddings:f=null,speaker_features:p=null,...m}){let h;if(!a){let s=this.sessions.embed_tokens.inputNames,c={input_ids:e};if(s.includes(`exaggeration`)){if(!(r instanceof U)){let t=e.dims[0];if(r==null)r=xu([t],.5);else if(typeof r==`number`)r=xu([t],r);else if(Array.isArray(r))r=new U(`float32`,r,[t]);else throw Error("Unsupported type for `exaggeration` input")}c.exaggeration=r}if(s.includes(`position_ids`)&&(c.position_ids=i),{inputs_embeds:a}=await J(this.sessions.embed_tokens,c),u&&d&&f&&p&&(h={audio_features:u,audio_tokens:d,speaker_embeddings:f,speaker_features:p}),h||n)h??=await this.encode_speech(n),a=mu([h.audio_features,a],1),t=Cu([a.dims[0],a.dims[1]]);else{let e=a.dims[1];if(!o||e!==1)throw Error(`Incorrect state encountered during generation.`);let n=o.get_seq_length();t=Cu([a.dims[0],n+e])}}return{...await Vg(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:s,logits_processor:c,num_logits_to_keep:l},!1),...h}}prepare_inputs_for_generation(e,t,n){return!t.position_ids&&this.sessions.embed_tokens.inputNames.includes(`position_ids`)&&(t.position_ids=t.input_ids.dims[1]===1?new U(`int64`,Array.from({length:e.length},(t,n)=>e[n].length-e[n].findLastIndex(e=>e==q_)-1),[e.length,1]):new U(`int64`,t.input_ids.tolist().map(e=>{let t=0;return e.map(e=>e>=q_?0:t++)}).flat(),t.input_ids.dims)),t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),qg(this,e,t,n)}async generate(e){let t=e.past_key_values,{sequences:n,audio_tokens:r,speaker_embeddings:i,speaker_features:a,past_key_values:o}=await super.generate({...e,return_dict_in_generate:!0});try{let t=n.slice(null,[e.input_ids.dims[1],-1]),o=mu([r,t,xu([t.dims[0],3],K_)],1),{waveform:s}=await J(this.sessions.conditional_decoder,{speech_tokens:o,speaker_features:a,speaker_embeddings:i});return s}finally{o!==t&&await o?.dispose()}}},X_=class extends Z{},Z_=class extends X_{},Q_=class extends Z{},$_=class extends Q_{},ev=class extends Z{},tv=class extends ev{},nv=class extends ev{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},rv=class extends ev{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`audio_model`})}},iv=class extends Z{},av=class extends iv{},ov=class extends iv{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},sv=class extends iv{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},cv=class extends iv{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},lv=class extends iv{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},uv=class extends Z{},dv=class extends uv{},fv=class extends uv{},pv=class extends Z{},mv=class extends pv{},hv=class extends pv{},gv=class extends Z{},_v=class extends gv{},vv=class extends gv{},yv=class extends Z{},bv=class extends yv{},xv=class extends yv{},Sv=class extends Z{requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},Cv=class extends Sv{},wv=class extends Sv{},Tv=class extends Z{},Ev=class extends Tv{},Dv=class extends Tv{async _call(e){return new Vh(await super._call(e))}},Ov=class extends Tv{async _call(e){return new Y(await super._call(e))}},kv=class extends Tv{async _call(e){return new Bh(await super._call(e))}},Av=class extends Tv{async _call(e){return new Hh(await super._call(e))}},jv=class extends Z{},Mv=class extends jv{},Nv=class extends jv{async _call(e){return new Y(await super._call(e))}},Pv=class extends Z{},Fv=class extends Pv{},Iv=class extends Pv{async _call(e){return new Y(await super._call(e))}},Lv=class extends Z{},Rv=class extends Lv{},zv=class extends Lv{async _call(e){return new Bv(await super._call(e))}},Bv=class extends Rh{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Vv=class extends Z{},Hv=class extends Vv{},Uv=class extends Vv{async _call(e){return new Bv(await super._call(e))}},Wv=class extends Rh{constructor({audio_codes:e}){super(),this.audio_codes=e}},Gv=class extends Rh{constructor({audio_values:e}){super(),this.audio_values=e}},Kv=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},qv=class extends Kv{async encode(e){return new Wv(await J(this.sessions.encoder_model,e))}async decode(e){return new Gv(await J(this.sessions.decoder_model,e))}},Jv=class extends Kv{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},Yv=class extends Kv{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},Xv=class extends Z{},Zv=class extends Xv{},Qv=class extends Xv{async _call(e){return new Vh(await super._call(e))}},$v=class extends Xv{async _call(e){return new Y(await super._call(e))}},ey=class extends Xv{async _call(e){return new Bh(await super._call(e))}},ty=class extends Xv{async _call(e){return new Hh(await super._call(e))}},ny=class extends Z{},ry=class extends ny{},iy=class extends ny{},ay=class extends Z{},oy=class extends ay{},sy=class extends ay{},cy=class extends Z{},ly=class extends cy{},uy=class extends cy{async _call(e){return new Vh(await super._call(e))}},dy=class extends cy{async _call(e){return new Y(await super._call(e))}},fy=class extends cy{async _call(e){return new Bh(await super._call(e))}},py=class extends cy{async _call(e){return new Hh(await super._call(e))}},my=class extends Z{},hy=class extends my{},gy=class extends Z{},_y=class extends gy{},vy=class extends gy{async _call(e){return new Y(await super._call(e))}},yy=class extends Z{},by=class extends yy{},xy=class extends Z{},Sy=class extends xy{},Cy=class extends Z{},wy=class extends Cy{},Ty=class extends Cy{async _call(e){return new Dy(await super._call(e))}},Ey=class extends Cy{async _call(e){return new Oy(await super._call(e))}},Dy=class extends Rh{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Oy=class extends Rh{constructor({logits:e,pred_boxes:t,pred_masks:n}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=n}},ky=class extends Z{},Ay=class extends ky{},jy=class extends ky{async _call(e){return new Y(await super._call(e))}},My=class extends Z{},Ny=class extends My{},Py=class extends My{async _call(e){return new Y(await super._call(e))}},Fy=class extends Z{},Iy=class extends Fy{},Ly=class extends Z{},Ry=class extends Ly{},zy=class extends Z{},By=class extends zy{},Vy=class extends zy{async _call(e){return new Y(await super._call(e))}},Hy=class extends zy{async _call(e){return new Bh(await super._call(e))}},Uy=class extends zy{async _call(e){return new Hh(await super._call(e))}},Wy=class extends zy{async _call(e){return new Vh(await super._call(e))}},Gy=class extends Z{},Ky=class extends Gy{},qy=class extends Z{},Jy=class extends qy{},Yy=class extends qy{},Xy=class extends Z{},Zy=class extends Xy{},Qy=class extends Xy{async _call(e){return new Y(await super._call(e))}},$y=class extends Z{},eb=class extends $y{},tb=class extends $y{async _call(e){return new Vh(await super._call(e))}},nb=class extends $y{async _call(e){return new Y(await super._call(e))}},rb=class extends $y{async _call(e){return new Bh(await super._call(e))}},ib=class extends $y{async _call(e){return new Hh(await super._call(e))}},ab=class extends Z{},ob=class extends ab{},sb=class extends ab{},cb=class extends Z{},lb=class extends cb{},ub=class extends cb{async _call(e){return new Vh(await super._call(e))}},db=class extends cb{async _call(e){return new Y(await super._call(e))}},fb=class extends cb{async _call(e){return new Bh(await super._call(e))}},pb=class extends Z{},mb=class extends pb{},hb=class extends pb{async _call(e){return new Vh(await super._call(e))}},gb=class extends pb{async _call(e){return new Y(await super._call(e))}},_b=class extends pb{async _call(e){return new Bh(await super._call(e))}},vb=class extends Z{},yb=class extends vb{},bb=class extends vb{},xb=class extends Z{},Sb=class extends xb{},Cb=class extends xb{},wb=class extends Z{},Tb=class extends wb{},Eb=class extends wb{},Db=class extends Z{},Ob=class extends Db{},kb=class extends Db{async _call(e){return new Y(await super._call(e))}},Ab=class extends Z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`pixel_values`,`encoder_outputs`,`decoder_input_ids`,`decoder_inputs_embeds`,`decoder_attention_mask`,`past_key_values`];main_input_name=`inputs_embeds`},jb=class extends Ab{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:n,attention_mask:r}){return{inputs_embeds:mu([t,e],1),attention_mask:mu([Cu(t.dims.slice(0,2)),r],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:n,attention_mask:r}){if(!e&&!t)throw Error("Either `input_ids` or `pixel_values` should be provided.");let i,a;return e&&(i=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),i&&a?{inputs_embeds:n,attention_mask:r}=this._merge_input_ids_with_image_features({inputs_embeds:i,image_features:a,input_ids:e,attention_mask:r}):n=i||a,{inputs_embeds:n,attention_mask:r}}async forward({input_ids:e,pixel_values:t,attention_mask:n,decoder_input_ids:r,decoder_attention_mask:i,encoder_outputs:a,past_key_values:o,inputs_embeds:s,decoder_inputs_embeds:c,num_logits_to_keep:l=null}){if(s||({inputs_embeds:s,attention_mask:n}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:n})),!a){let{last_hidden_state:e}=await Pg(this,{inputs_embeds:s,attention_mask:n});a=e}if(!c){if(!r)throw Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:r})}let u={inputs_embeds:c,attention_mask:i,encoder_attention_mask:n,encoder_hidden_states:a,past_key_values:o,num_logits_to_keep:l};return await Vg(this,u,!0)}},Mb=class extends Z{},Nb=class extends Mb{},Pb=class extends Mb{},Fb=class extends Z{},Ib=class extends Fb{},Lb=class extends Fb{},Rb=class extends Z{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`position_ids`,`past_key_values`]},zb=class extends Rb{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return Zg({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:n})}},Bb=class extends zb{},Vb=class extends zb{},Hb=class extends Z{},Ub=class extends Hb{},Wb=class extends zb{},Gb=class extends Wb{},Kb=class extends Z{forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`input_features`,`input_features_mask`,`past_key_values`]},qb=class extends Kb{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,input_features:r=null,input_features_mask:i=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:s=null,past_key_values:c=null,generation_config:l=null,logits_processor:u=null,num_logits_to_keep:d=null,...f}){if((!o||!s)&&({inputs_embeds:o,per_layer_inputs:s}=await J(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(n){let{image_features:r}=await this._encode_vision({pixel_values:n,...f});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:r,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(r){let{audio_features:n}=await J(this.sessions.audio_encoder,{input_features:r,input_features_mask:i});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:n,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await Vg(this,{inputs_embeds:o,per_layer_inputs:s,past_key_values:c,attention_mask:t,position_ids:a,generation_config:l,logits_processor:u,num_logits_to_keep:d},!0)}_encode_vision(e){return J(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return Zg({image_token_id:this.config.image_token_id,...e,image_features:n})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return Qg({audio_token_id:this.config.audio_token_id,...e,audio_features:n})}},Jb=class extends qb{},Yb=class extends qb{forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`image_position_ids`,`input_features`,`input_features_mask`,`past_key_values`];_encode_vision(e){return J(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},Xb=class extends Yb{},Zb=class extends Z{},Qb=class extends Zb{},$b=class extends Zb{},ex=class extends Z{},tx=class extends ex{},nx=class extends ex{},rx=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`,`pixel_values`,`image_grid_thw`]},ix=class extends rx{image_grid_thw_name=`grid_thw`;_get_text_only_rope_index(e,t){if(t){let{data:e,dims:n}=Gg(t),r=BigInt64Array.from({length:3*e.length},(t,n)=>e[n%e.length]),i=Array.from({length:n[0]},(t,r)=>fl(e.subarray(n[1]*r,n[1]*(r+1)))[0]+1n+BigInt(n[1]));return[new U(`int64`,r,[3,...n]),new U(`int64`,i,[i.length,1])]}{let[t,n]=e.dims;return[new U(`int64`,BigInt64Array.from({length:3*t*n},(e,r)=>BigInt(Math.floor(r%n/t))),[3,...e.dims]),Tu([t,1])]}}_reorder_and_write_positions(e,t,n,r){let i=e.reduce((e,t)=>e+t.length,0),a=Array(i),o=0;for(let t=0;t<3;++t)for(let n of e){let e=n.length/3;for(let r=t*e;r<(t+1)*e;++r)a[o++]=n[r]}let s=0;for(let e=0;e(t==s&&e.push(n),e),[]).map(e=>c[e+1]),u=l.filter(e=>e==a).length,d=l.filter(e=>e==o).length,f=[],p=0,m=u,h=d;for(let e=0;et>p&&e==a),s=c.findIndex((e,t)=>t>p&&e==o),l=m>0&&e!==-1?e:c.length+1,u=h>0&&s!==-1?s:c.length+1,d,g,_,v;l0?fl(f.at(-1))[0]+1:0;f.push(Array.from({length:3*ee},(e,t)=>S+t%ee));let te=ee+S,C=y*b*x,w=Array.from({length:C},(e,t)=>te+Math.floor(t/(b*x))),ne=Array.from({length:C},(e,t)=>te+Math.floor(t/x)%b),re=Array.from({length:C},(e,t)=>te+t%x);f.push([w,ne,re].flat()),p=d+C}if(p0?fl(f.at(-1))[0]+1:0,t=c.length-p;f.push(Array.from({length:3*t},(n,r)=>e+r%t))}return f}get_rope_index(e,t,n,r){let{vision_config:i}=this.config,a=i.spatial_merge_size??2;if(t||n){let i=e.tolist();r||=wu(e);let o=r.tolist(),s=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),c=t?t.tolist():[],l=n?n.tolist():[],u={image_index:0,video_index:0},d=[];for(let e=0;eo[e][n]==1),n=this._get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:c,video_grid_thw_list:l,spatial_merge_size:a,state:u}),r=this._reorder_and_write_positions(n,o[e],s,e);d.push(fl(r)[0]+1-i[e].length)}return[new U(`int64`,s.flat(1/0),[3,e.dims[0],e.dims[1]]),new U(`int64`,d,[d.length,1])]}return this._get_text_only_rope_index(e,r)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await J(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return Zg({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,n){if(Bg(this,t,1n),!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes(`position_ids`))return t;if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;let e=t.past_key_values.get_seq_length();if(en+e);t.position_ids=hu([r,r,r],0)}}return t}},ax=class extends ix{},ox=class extends ix{image_grid_thw_name=`image_grid_thw`},sx=class extends ax{image_grid_thw_name=`image_grid_thw`},cx=class extends ox{get_vision_position_ids(e,t,n,r){let i=Math.floor(t[0]/n),a=Math.floor(t[1]/r),o=Math.floor(t[2]/r),s=a*o*i,c=Array.from({length:s},()=>e),l=Array.from({length:s},(t,n)=>e+Math.floor(n/(o*i))),u=Array.from({length:s},(t,n)=>e+n%o);return[...c,...l,...u]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:n,spatial_merge_size:r,state:i}){let{image_token_id:a}=this.config,o=[],s=0,c=+(e[0]==a);for(let t=1;t<=e.length;++t){let n=tl+n%e)),l+=e}else{let e=t[i.image_index++].map(Number),n=e[0];u.push(this.get_vision_position_ids(l,e,n,r)),l+=Math.max(e[1],e[2])/r}return u}},lx=class extends Z{},ux=class extends lx{},dx=class extends lx{},fx=class extends Z{},px=class extends fx{},mx=class extends fx{},hx=class extends Z{},gx=class extends hx{},_x=class extends hx{},vx=class extends Z{},yx=class extends vx{},bx=class extends vx{},xx=class extends Z{},Sx=class extends xx{},Cx=class extends xx{},wx=class extends Z{},Tx=class extends wx{},Ex=class extends wx{},Dx=class extends Z{},Ox=class extends Dx{},kx=class extends Dx{},Ax=class extends Z{},jx=class extends Ax{},Mx=class extends Ax{},Nx=class extends Z{},Px=class extends Nx{},Fx=class extends Nx{},Ix=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`audio_values`,`past_key_values`]},Lx=class extends Ix{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return Qg({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:n})}},Rx=class extends Lx{forward_params=[`input_ids`,`attention_mask`,`input_features`,`past_key_values`]},zx=class extends Z{},Bx=class extends zx{},Vx=class extends Z{},Hx=class extends Vx{},Ux=class extends Z{},Wx=class extends Ux{},Gx=class extends Ux{},Kx=class extends Z{},qx=class extends Kx{},Jx=class extends Kx{async _call(e){return new Y(await super._call(e))}},Yx=class extends Z{},Xx=class extends Yx{},Zx=class extends Yx{forward_params=[`input_ids`,`attention_mask`,`token_type_ids`,`past_key_values`];prepare_inputs_for_generation(e,t,n){let r=qg(this,e,t,n);return r.token_type_ids=(r.past_key_values?Eu:wu)(r.input_ids),r}},Qx=class extends Z{},$x=class extends Qx{},eS=class extends Qx{async _call(e){return new Uh(await super._call(e))}},tS=class extends Qx{async _call(e){return new Y(await super._call(e))}},nS=class extends Qx{async _call(e){return new Bh(await super._call(e))}},rS=class extends Z{},iS=class extends Qx{},aS=class extends Qx{async _call(e){return new Uh(await super._call(e))}},oS=class extends Qx{async _call(e){return new Y(await super._call(e))}},sS=class extends Z{},cS=class extends sS{},lS=class extends sS{},uS=class extends zb{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`position_ids`,`past_key_values`]},dS=class extends Z{},fS=class extends dS{},pS=class extends dS{async _call(e){return new Y(await super._call(e))}},mS=class extends Z{},hS=class extends mS{},gS=class extends mS{},_S=class extends Z{},vS=class extends _S{async forward(e){let t=!e.input_ids,n=!e.pixel_values;if(t&&n)throw Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=Cu([e.pixel_values.dims[0],1])),n){let{image_size:t}=this.config.vision_config;e.pixel_values=xu([0,3,t,t],0)}let{text_embeddings:r,image_embeddings:i,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),s={};return t||(s.text_embeddings=r,s.l2norm_text_embeddings=a),n||(s.image_embeddings=i,s.l2norm_image_embeddings=o),s}},yS=class extends _S{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},bS=class extends _S{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},xS=class extends Z{},SS=class extends xS{},CS=class extends xS{},wS=class extends zb{},TS=class extends Z{},ES=class extends TS{},DS=class extends TS{},OS=class extends zb{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`spatial_shapes`,`position_ids`,`past_key_values`]},kS=class extends Z{},AS=class extends kS{},jS=class extends kS{},MS=class extends Z{},NS=class extends MS{},PS=class extends Z{},FS=class extends PS{},IS=class extends PS{},LS=class extends Z{},RS=class extends LS{},zS=class extends LS{},BS=class extends Z{},VS=class extends BS{},HS=class extends BS{},US=class extends Z{},WS=class extends US{},GS=class extends US{},KS=class extends Z{},qS=class extends KS{},JS=class extends KS{},YS=class extends KS{async _call(e){return new Y(await super._call(e))}},XS=class extends KS{},ZS=class extends Z{},QS=class extends ZS{},$S=class extends Z{},eC=class extends $S{},tC=class extends Rh{constructor({char_logits:e,bpe_logits:t,wp_logits:n}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=n}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},nC=class extends Z{},rC=class extends nC{async _call(e){return new tC(await super._call(e))}},iC=class extends Rh{constructor({audio_codes:e}){super(),this.audio_codes=e}},aC=class extends Rh{constructor({audio_values:e}){super(),this.audio_values=e}},oC=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},sC=class extends oC{async encode(e){return new iC(await J(this.sessions.encoder_model,e))}async decode(e){return new aC(await J(this.sessions.decoder_model,e))}},cC=class extends oC{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},lC=class extends oC{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},uC=class extends Z{},dC=class extends uC{},fC=class extends uC{},pC=class extends Z{},mC=class extends pC{},hC=class extends pC{},gC=class extends Z{},_C=class extends gC{},vC=class extends gC{},yC=class extends zb{},bC=class extends Z{},xC=class extends bC{},SC=class extends bC{},CC=class extends Z{},wC=class extends CC{},TC=class extends CC{async _call(e){return new Vh(await super._call(e))}},EC=class extends CC{async _call(e){return new Y(await super._call(e))}},DC=class extends CC{async _call(e){return new Hh(await super._call(e))}},OC=class extends Z{},kC=class extends OC{},AC=class extends OC{},jC=class extends Z{},MC=class extends jC{},NC=class extends jC{async _call(e){return new Y(await super._call(e))}},PC=class extends jC{},FC=class extends Z{},IC=class extends FC{},LC=class extends FC{async _call(e){return new Y(await super._call(e))}},RC=class extends FC{},zC=class extends Z{},BC=class extends zC{},VC=class extends zC{async _call(e){return new Y(await super._call(e))}},HC=class extends zC{},UC=class extends Z{},WC=class extends UC{},GC=class extends UC{async _call(e){return new Y(await super._call(e))}},KC=class extends UC{},qC=class extends Z{},JC=class extends qC{},YC=class extends qC{async _call(e){return new Y(await super._call(e))}},XC=class extends Z{},ZC=class extends XC{},QC=class extends XC{async _call(e){return new Y(await super._call(e))}},$C=class extends Z{},ew=class extends $C{},tw=class extends $C{async _call(e){return new Vh(await super._call(e))}},nw=class extends $C{async _call(e){return new Y(await super._call(e))}},rw=class extends $C{async _call(e){return new Bh(await super._call(e))}},iw=class extends Z{},aw=class extends iw{},ow=class extends iw{},sw=class extends Z{requires_attention_mask=!1;main_input_name=`input_values`;forward_params=[`input_values`,`decoder_input_ids`,`past_key_values`]},cw=class extends sw{},lw=class extends sw{},uw=class extends Z{},dw=class extends uw{},fw=class extends uw{async _call(e){return new Vh(await super._call(e))}},pw=class extends uw{async _call(e){return new Y(await super._call(e))}},mw=class extends uw{async _call(e){return new Bh(await super._call(e))}},hw=class extends uw{async _call(e){return new Hh(await super._call(e))}},gw=class extends Z{},_w=class extends gw{},vw=class extends gw{},yw=class extends Z{},bw=class extends yw{},xw=class extends yw{},Sw=class extends Z{},Cw=class extends Sw{forward_params=[`input_ids`,`pixel_values`,`images_seq_mask`,`images_emb_mask`,`attention_mask`,`position_ids`,`past_key_values`];constructor(...e){super(...e),this._generation_mode=`text`}async forward(e){let t=this._generation_mode??`text`,n;if(t===`text`||!e.past_key_values){let t=this.sessions.prepare_inputs_embeds;n=await J(t,ui(e,t.inputNames))}else{let t=this.sessions.gen_img_embeds;n=await J(t,ui({image_ids:e.input_ids},t.inputNames))}let r={...e,...n},i=await Vg(this,r),a=this.sessions[t===`text`?`lm_head`:`gen_head`];if(!a)throw Error(`Unable to find "${a}" generation head`);let o=await J(a,ui(i,a.inputNames));return{...n,...i,...o}}prepare_inputs_for_generation(e,t,n){let r=!!t.past_key_values;return Bg(this,t,1n),n.guidance_scale!==null&&n.guidance_scale>1&&(r?t.input_ids=mu([t.input_ids,t.input_ids],0):(t.input_ids=mu([t.input_ids,Su(t.input_ids,BigInt(n.pad_token_id))],0),t.attention_mask=mu([t.attention_mask,Su(t.attention_mask,0n)],0))),(r||!t.pixel_values)&&(t.pixel_values=xu([0,0,3,384,384],1)),r&&(t.images_seq_mask=new U(`bool`,[,].fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new U(`bool`,[].fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode=`text`,super.generate(e)}async generate_images(e){this._generation_mode=`image`;let t=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[t,null]),r=this.sessions.image_decode,{decoded_image:i}=await J(r,{generated_tokens:n}),a=i.add_(1).mul_(255/2).clamp_(0,255).to(`uint8`),o=[];for(let e of a){let t=Kf.fromTensor(e);o.push(t)}return o}},ww=class extends Z{},Tw=class extends ww{},Ew=class extends ww{},Dw=class extends Z{forward_params=[`input_ids`,`attention_mask`,`encoder_outputs`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`];_apply_and_filter_by_delay_pattern_mask(e){let[t,n]=e.dims,r=this.config.decoder.num_codebooks,i=n-r,a=0;for(let t=0;t0&&o<=i&&(e.data[a++]=e.data[t])}let o=Math.floor(t/r),s=a/(o*r);return new U(e.type,e.data.slice(0,a),[o,r,s])}prepare_inputs_for_generation(e,t,n){let r=BigInt(this.config.decoder.pad_token_id),i=structuredClone(e);for(let e=0;e=t&&(i[e][t]=r);return n.guidance_scale!==null&&n.guidance_scale>1&&(i=i.concat(i)),Jg(this,i,t,n)}async generate(e){let t=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await J(this.sessions.encodec_decode,{audio_codes:n});return r}},Ow=class extends Z{},kw=class extends Ow{},Aw=class extends Ow{},jw=class extends Z{},Mw=class extends jw{},Nw=class extends jw{},Pw=class extends Z{},Fw=class extends Pw{},Iw=class extends Pw{async _call(e){return new Vh(await super._call(e))}},Lw=class extends Pw{async _call(e){return new Y(await super._call(e))}},Rw=class extends Pw{async _call(e){return new Bh(await super._call(e))}},zw=class extends Pw{async _call(e){return new Hh(await super._call(e))}},Bw=class extends Z{},Vw=class extends Bw{},Hw=class extends Z{},Uw=class extends Hw{},Ww=class extends Hw{},Gw=class extends Z{},Kw=class extends Gw{},qw=class extends Gw{},Jw=class extends Z{},Yw=class extends Jw{},Xw=class extends Jw{},Zw=class extends Z{},Qw=class extends Zw{},$w=class extends Zw{},eT=class extends Z{},tT=class extends eT{},nT=class extends eT{async _call(e){return new Y(await super._call(e))}},rT=class extends Z{},iT=class extends rT{},aT=class extends rT{},oT=class extends Z{},sT=class extends oT{},cT=class extends oT{},lT=class extends Z{},uT=class extends lT{},dT=class extends lT{},fT=class extends Z{},pT=class extends fT{},mT=class extends fT{},hT=class extends zb{},gT=class extends Z{},_T=class extends gT{async _call(e){return new Uh(await super._call(e))}},vT=class extends Z{},yT=class extends vT{},bT=class extends vT{},xT=class extends Z{},ST=class extends xT{},CT=class extends xT{},wT=class extends Z{},TT=class extends wT{},ET=class extends wT{},DT=class extends Z{},OT=class extends DT{},kT=class extends DT{},AT=class extends Z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`pixel_values`,`image_sizes`,`past_key_values`]},jT=class extends AT{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,image_sizes:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,num_logits_to_keep:l=null,...u}){if(!a){let t;if(n&&e.dims[1]!==1){if(!r)throw Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:t}=await J(this.sessions.vision_encoder,{pixel_values:n,image_sizes:r}))}else{let e=this.config.normalized_config.hidden_size;t=new U(`float32`,[],[0,e])}({inputs_embeds:a}=await J(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:t}))}return await Vg(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:i,generation_config:s,logits_processor:c,num_logits_to_keep:l},!1)}},MT=class extends Z{},NT=class extends MT{},PT=class extends MT{async _call(e){return new Y(await super._call(e))}},FT=class extends Z{},IT=class extends FT{},LT=class extends FT{async _call(e){return new Bh(await super._call(e))}},RT=class extends Z{},zT=class extends RT{},BT=class extends RT{},VT=class extends Z{},HT=class extends VT{},UT=class extends VT{},WT=class extends Z{},GT=class extends WT{},KT=class extends WT{},qT=class extends Z{},JT=class extends qT{},YT=class extends qT{},XT=class extends Z{},ZT=class extends XT{},QT=class extends XT{},$T=class extends ox{},eE=class extends sx{},tE=class extends $T{},nE=class extends eE{},rE=class extends $T{},iE=class extends rE{},aE=class extends rE{},oE=class extends iE{},sE=class extends Z{},cE=class extends sE{},lE=class extends sE{async _call(e){return new Y(await super._call(e))}},uE=class extends Z{},dE=class extends uE{},fE=class extends uE{async _call(e){return new pE(await super._call(e))}},pE=class extends Bv{},mE=class extends Z{},hE=class extends mE{},gE=class extends mE{async _call(e){return new Vh(await super._call(e))}},_E=class extends mE{async _call(e){return new Y(await super._call(e))}},vE=class extends mE{async _call(e){return new Bh(await super._call(e))}},yE=class extends mE{async _call(e){return new Hh(await super._call(e))}},bE=class extends Z{},xE=class extends bE{},SE=class extends bE{async _call(e){return new Vh(await super._call(e))}},CE=class extends bE{async _call(e){return new Y(await super._call(e))}},wE=class extends bE{async _call(e){return new Bh(await super._call(e))}},TE=class extends bE{async _call(e){return new Hh(await super._call(e))}},EE=class extends Z{},DE=class extends EE{},OE=class extends EE{async _call(e){return new kE(await super._call(e))}},kE=class extends Bv{},AE=class extends Rh{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},jE=class extends Z{},ME=class extends jE{async get_image_embeddings({pixel_values:e}){return await Pg(this,{pixel_values:e})}async forward(e){e=!e.image_embeddings||!e.image_positional_embeddings?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_labels??=Cu(e.input_points.dims.slice(0,-1));let t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await J(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new AE(await super._call(e))}},NE=class extends Rh{constructor({iou_scores:e,pred_masks:t,object_score_logits:n}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=n}},PE=class extends Z{},FE=class extends PE{async get_image_embeddings({pixel_values:e}){return await Pg(this,{pixel_values:e})}async forward(e){let{num_feature_levels:t}=this.config.vision_config;if(e=Array.from({length:t},(e,t)=>`image_embeddings.${t}`).some(t=>!e[t])?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let t=e.input_points.dims;e.input_labels??=Cu(t.slice(0,-1)),e.input_boxes??=xu([t[0],0,4],0)}else if(e.input_boxes){let t=e.input_boxes.dims;e.input_labels=xu([t[0],t[1],0],-1n),e.input_points=xu([t[0],1,0,2],0)}else throw Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder;return await J(n,ui(e,n.inputNames))}async _call(e){return new NE(await super._call(e))}},IE=class extends FE{},LE=class extends FE{},RE=class extends Z{},zE=class extends RE{},BE=class extends RE{},VE=class extends RE{},HE=class extends Z{},UE=class extends HE{},WE=class extends HE{},GE=class extends HE{},KE=class extends Z{},qE=class extends KE{},JE=class extends KE{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},YE=class extends iv{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},XE=class extends Z{},ZE=class extends XE{},QE=class extends XE{},$E=class extends uS{},eD=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},tD=class extends eD{async encode(e){return await J(this.sessions.encoder_model,e)}async decode(e){return await J(this.sessions.decoder_model,e)}},nD=class extends eD{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},rD=class extends eD{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},iD=class extends Z{},aD=class extends iD{},oD=class extends iD{},sD=class extends Z{},cD=class extends sD{},lD=class extends sD{},uD=class extends sD{async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:i=20,vocoder:a=null}={}){let o={input_ids:e},{encoder_outputs:s,encoder_attention_mask:c}=await Pg(this,o),l=s.dims[1]/this.config.reduction_factor,u=Math.floor(l*i),d=Math.floor(l*r),f=this.config.num_mel_bins,p=[],m=null,h=null,g=0;for(;;){++g;let e=Dg(!!h),r;r=h?h.output_sequence_out:new U(`float32`,new Float32Array(f),[1,1,f]);let i={use_cache_branch:e,output_sequence:r,encoder_attention_mask:c,speaker_embeddings:t,encoder_hidden_states:s};zg(this,i,m),h=await J(this.sessions.decoder_model_merged,i),m=Ig(h,m);let{prob:a,spectrum:o}=h;if(p.push(o),g>=d&&(Array.from(a.data).filter(e=>e>=n).length>0||g>=u))break}let _=mu(p),{waveform:v}=await J(a.sessions.model,{spectrogram:_});return{spectrogram:_,waveform:v}}},dD=class extends Z{main_input_name=`spectrogram`},fD=class extends Z{},pD=class extends fD{},mD=class extends fD{async _call(e){return new Vh(await super._call(e))}},hD=class extends fD{async _call(e){return new Y(await super._call(e))}},gD=class extends fD{async _call(e){return new Hh(await super._call(e))}},_D=class extends Z{},vD=class extends _D{},yD=class extends _D{},bD=class extends Z{},xD=class extends bD{},SD=class extends bD{},CD=class extends Z{},wD=class extends CD{},TD=class extends Z{},ED=class extends TD{async generate_speech({input_ids:e,attention_mask:t,style:n,num_inference_steps:r=5,speed:i=1.05}){let{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:s,latent_dim:c}=this.config,{last_hidden_state:l,durations:u}=await J(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:n}),d=u.div(i).mul_(a),f=s*o,p=d.data,m=Int32Array.from(p,e=>Math.ceil(e/f)),h=Math.max(...m),g=e.dims[0],_=new BigInt64Array(g*h);for(let e=0;ee*t,1),r=tu[e.type];c[e.name]=new U(e.type,new r(n),t)}let f=tu[d],p=new U(d,new f(s*vO),[1,s,vO]),m=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!m)throw Error(`input_features must be iterable or async iterable`);return{encoder_session:i,enc_kv_cache:c,enc_padding_cache:p,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:m,text_hidden_size:n.hidden_size}}async function SO(e,t){let n=t.dims[2],r=Math.floor((yO+n-3)/2)+1,i=new U(`int64`,BigInt64Array.from({length:r},(t,n)=>BigInt(e.enc_past_seq_len+n)),[1,r]),a=e.enc_past_seq_len+r,o=Cu([1,a]),{audio_embeds:s,present_padding_cache:c,...l}=await J(e.encoder_session,{input_features:t,attention_mask:o,position_ids:i,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location===`gpu-buffer`&&e.enc_padding_cache.dispose(),e.enc_padding_cache=c;for(let t in l)if(t.startsWith(`present.`)){let n=t.replace(`present`,`past_key_values`),r=e.enc_kv_cache[n];r?.location===`gpu-buffer`&&r.dispose(),e.enc_kv_cache[n]=l[t]}return e.enc_past_seq_len=a,s}async function CO(e,t){for(;e.audio_embed_total_tokens0&&e.audio_embed_queue.length>0;){let t=e.audio_embed_queue[0],n=t.tokens-e.audio_queue_offset,o=Math.min(a,n),s=e.audio_queue_offset*e.text_hidden_size;for(let n=0;n=t.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=n-a}var TO=class extends lg{constructor(e){super(),this._s=e}_call(e){let t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},EO=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`]},DO=class extends EO{async forward({input_ids:e,past_key_values:t,...n}){let r=e.dims[1],i=bO.get(this);i&&await CO(i,i.audio_consumed+r);let{inputs_embeds:a}=await J(this.sessions.embed_tokens,{input_ids:e});i&&wO(i,a,r);let o={inputs_embeds:a,...n};zg(this,o,t);let s=this.sessions.decoder_model_merged;return await J(s,ui(o,s.inputNames))}async generate({input_features:e,stopping_criteria:t,...n}){if(!e)throw Error(`input_features (generator/iterable) must be provided`);let r=xO(this,e);bO.set(this,r);let i=new ug;i.push(new TO(r)),t&&i.extend(t);try{return await super.generate({...n,stopping_criteria:i})}finally{r.enc_kv_cache.dispose(),bO.delete(this)}}},OO=class extends Z{},kO=class extends OO{},AO=class extends OO{async _call(e){return new Uh(await super._call(e))}},jO=class extends OO{async _call(e){return new Y(await super._call(e))}},MO=class extends Rh{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},NO=class extends Z{},PO=class extends NO{},FO=class extends NO{async _call(e){return new Uh(await super._call(e))}},IO=class extends NO{async _call(e){return new Y(await super._call(e))}},LO=class extends NO{async _call(e){return new MO(await super._call(e))}},RO=class extends NO{async _call(e){return new Bh(await super._call(e))}},zO=class extends Z{},BO=class extends zO{},VO=class extends cg{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1},HO=class extends Z{requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`attention_mask`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},UO=class extends HO{},WO=class extends HO{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,VO)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],n=e.language,r=e.task;if(e.is_multilingual){n||=(N.warn(`No language specified - defaulting to English (en).`),`en`);let i=`<|${jd(n)}|>`;t.push(e.lang_to_id[i]),t.push(e.task_to_id[r??`transcribe`])}else if(n||r)throw Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(N.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(e=>e!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,...i}){t=this._prepare_generation_config(t,i);let a=i.decoder_input_ids instanceof U?ju(i.decoder_input_ids):i.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(n??=new Yh,n.push(new eg(t,a))),t.begin_suppress_tokens&&(n??=new Yh,n.push(new $h(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");t.task===`translate`&&N.warn(`Token-level timestamps may not be reliable for task 'translate'.`),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!i.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:a,kwargs:i});let o=await super.generate({inputs:e,generation_config:t,logits_processor:n,decoder_input_ids:a,...i});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,.02,a.length)),o}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:r,kwargs:i}){let a=t.no_timestamps_token_id+1,o=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,s=t.return_token_timestamps,c=e,l=c.dims[2],u=2*this.config.max_source_positions,d=0,f=[],p=[];for(;de+n)}if(v.length>0&&v.at(-1)===o&&v.pop(),v.length===0)break;let b=v.map(e=>e>=a),x=v.length>=2&&b[v.length-1]&&!b[v.length-2],ee=[];for(let e=0;e0){if(x)S=e-d;else{let e=ee.at(-1);S=(v[e-1]-a)*2,te=e}}else S=e-d;let C=Math.floor(d/2),w=a+1500;for(let e=0;e=a&&(v[e]=Math.min(v[e]+C,w));f.push(...v.slice(0,te)),y&&p.push(...y.slice(0,te)),d+=S}f.push(o);let m=[...r,...f];if(s){let e=new U(`int64`,m.map(BigInt),[1,m.length]),t=[...Array(r.length).fill(0),...p,0];return{sequences:e,token_timestamps:new U(`float32`,new Float32Array(t),[1,t.length])}}return new U(`int64`,m.map(BigInt),[1,m.length])}_extract_token_timestamps(e,t,n=null,r=.02,i=0){if(!e.cross_attentions)throw Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");n??N.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(N.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let o=e.cross_attentions,s=Array.from({length:this.config.decoder_layers},(e,t)=>mu(o.map(e=>e[t]),2)),c=hu(t.map(([e,t])=>{if(e>=s.length)throw Error(`Layer index ${e} is out of bounds for cross attentions (length ${s.length}).`);return n?s[e].slice(null,t,null,[0,n]):s[e].slice(null,t)})).permute(1,0,2,3),[l,u]=_u(c,-2,0,!0),d=c.clone();for(let e=0;e0?d.slice(null,null,[i,d.dims[2]],null):d,1)],p=e.sequences.dims,m=new U(`float32`,new Float32Array(p[0]*p[1]),p);for(let e=0;et[n+1]-t[n])).map(e=>!!e),o=[];for(let e=0;e0&&s.push(o.at(-1)),m[e].data.set(s)}return m}},GO=class extends WO{},KO=class extends Z{},qO=class extends KO{},JO=class extends KO{async _call(e){return new Vh(await super._call(e))}},YO=class extends KO{async _call(e){return new Y(await super._call(e))}},XO=class extends KO{async _call(e){return new Bh(await super._call(e))}},ZO=class extends KO{async _call(e){return new Hh(await super._call(e))}},QO=class extends Z{},$O=class extends QO{},ek=class extends QO{async _call(e){return new Vh(await super._call(e))}},tk=class extends QO{async _call(e){return new Y(await super._call(e))}},nk=class extends QO{async _call(e){return new Bh(await super._call(e))}},rk=class extends QO{async _call(e){return new Hh(await super._call(e))}},ik=class extends Z{},ak=class extends ik{},ok=class extends ik{async _call(e){return new sk(await super._call(e))}},sk=class extends Rh{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},ck=class extends Z{},lk=class extends ck{},uk=class extends ck{},dk=class extends Z{},fk=class extends dk{},pk=class extends dk{},mk=/* @__PURE__ */ new Map([[`bert`,`BertModel`],[`eurobert`,`EuroBertModel`],[`neobert`,`NeoBertModel`],[`modernbert`,`ModernBertModel`],[`nomic_bert`,`NomicBertModel`],[`roformer`,`RoFormerModel`],[`electra`,`ElectraModel`],[`esm`,`EsmModel`],[`convbert`,`ConvBertModel`],[`camembert`,`CamembertModel`],[`deberta`,`DebertaModel`],[`deberta-v2`,`DebertaV2Model`],[`mpnet`,`MPNetModel`],[`albert`,`AlbertModel`],[`distilbert`,`DistilBertModel`],[`roberta`,`RobertaModel`],[`xlm`,`XLMModel`],[`xlm-roberta`,`XLMRobertaModel`],[`clap`,`ClapModel`],[`clip`,`CLIPModel`],[`clipseg`,`CLIPSegModel`],[`chinese_clip`,`ChineseCLIPModel`],[`siglip`,`SiglipModel`],[`jina_clip`,`JinaCLIPModel`],[`mobilebert`,`MobileBertModel`],[`squeezebert`,`SqueezeBertModel`],[`wav2vec2`,`Wav2Vec2Model`],[`wav2vec2-bert`,`Wav2Vec2BertModel`],[`unispeech`,`UniSpeechModel`],[`unispeech-sat`,`UniSpeechSatModel`],[`hubert`,`HubertModel`],[`wavlm`,`WavLMModel`],[`audio-spectrogram-transformer`,`ASTModel`],[`vits`,`VitsModel`],[`pyannote`,`PyAnnoteModel`],[`wespeaker-resnet`,`WeSpeakerResNetModel`],[`detr`,`DetrModel`],[`rt_detr`,`RTDetrModel`],[`rt_detr_v2`,`RTDetrV2Model`],[`rf_detr`,`RFDetrModel`],[`d_fine`,`DFineModel`],[`table-transformer`,`TableTransformerModel`],[`vit`,`ViTModel`],[`ijepa`,`IJepaModel`],[`pvt`,`PvtModel`],[`vit_msn`,`ViTMSNModel`],[`vit_mae`,`ViTMAEModel`],[`groupvit`,`GroupViTModel`],[`fastvit`,`FastViTModel`],[`mobilevit`,`MobileViTModel`],[`mobilevitv2`,`MobileViTV2Model`],[`owlvit`,`OwlViTModel`],[`owlv2`,`Owlv2Model`],[`beit`,`BeitModel`],[`deit`,`DeiTModel`],[`hiera`,`HieraModel`],[`convnext`,`ConvNextModel`],[`convnextv2`,`ConvNextV2Model`],[`dinov2`,`Dinov2Model`],[`dinov2_with_registers`,`Dinov2WithRegistersModel`],[`dinov3_vit`,`DINOv3ViTModel`],[`dinov3_convnext`,`DINOv3ConvNextModel`],[`resnet`,`ResNetModel`],[`swin`,`SwinModel`],[`swin2sr`,`Swin2SRModel`],[`donut-swin`,`DonutSwinModel`],[`yolos`,`YolosModel`],[`dpt`,`DPTModel`],[`glpn`,`GLPNModel`],[`hifigan`,`SpeechT5HifiGan`],[`efficientnet`,`EfficientNetModel`],[`decision_transformer`,`DecisionTransformerModel`],[`patchtst`,`PatchTSTModel`],[`patchtsmixer`,`PatchTSMixerModel`],[`mobilenet_v1`,`MobileNetV1Model`],[`mobilenet_v2`,`MobileNetV2Model`],[`mobilenet_v3`,`MobileNetV3Model`],[`mobilenet_v4`,`MobileNetV4Model`],[`maskformer`,`MaskFormerModel`],[`mgp-str`,`MgpstrForSceneTextRecognition`],[`style_text_to_speech_2`,`StyleTextToSpeech2Model`],[`openai_privacy_filter`,`OpenAIPrivacyFilterModel`]]),hk=/* @__PURE__ */ new Map([[`t5`,`T5Model`],[`longt5`,`LongT5Model`],[`mt5`,`MT5Model`],[`bart`,`BartModel`],[`mbart`,`MBartModel`],[`marian`,`MarianModel`],[`whisper`,`WhisperModel`],[`cohere_asr`,`CohereAsrModel`],[`m2m_100`,`M2M100Model`],[`blenderbot`,`BlenderbotModel`],[`blenderbot-small`,`BlenderbotSmallModel`]]),gk=/* @__PURE__ */ new Map([[`mimi`,`MimiModel`],[`dac`,`DacModel`],[`snac`,`SnacModel`]]),_k=/* @__PURE__ */ new Map([[`bloom`,`BloomModel`],[`jais`,`JAISModel`],[`gpt2`,`GPT2Model`],[`gpt_oss`,`GptOssModel`],[`gptj`,`GPTJModel`],[`gpt_bigcode`,`GPTBigCodeModel`],[`gpt_neo`,`GPTNeoModel`],[`gpt_neox`,`GPTNeoXModel`],[`codegen`,`CodeGenModel`],[`llama`,`LlamaModel`],[`apertus`,`ApertusModel`],[`nanochat`,`NanoChatModel`],[`arcee`,`ArceeModel`],[`afmoe`,`AfmoeModel`],[`lfm2`,`Lfm2Model`],[`lfm2_moe`,`Lfm2MoeModel`],[`smollm3`,`SmolLM3Model`],[`exaone`,`ExaoneModel`],[`olmo`,`OlmoModel`],[`olmo2`,`Olmo2Model`],[`olmo3`,`Olmo3Model`],[`olmo_hybrid`,`OlmoHybridModel`],[`mobilellm`,`MobileLLMModel`],[`granite`,`GraniteModel`],[`granitemoehybrid`,`GraniteMoeHybridModel`],[`cohere`,`CohereModel`],[`cohere2`,`Cohere2Model`],[`gemma`,`GemmaModel`],[`gemma2`,`Gemma2Model`],[`vaultgemma`,`VaultGemmaModel`],[`gemma3_text`,`Gemma3Model`],[`helium`,`HeliumModel`],[`glm`,`GlmModel`],[`glm_moe_dsa`,`GlmMoeDsaModel`],[`openelm`,`OpenELMModel`],[`qwen2`,`Qwen2Model`],[`qwen2_moe`,`Qwen2MoeModel`],[`qwen3`,`Qwen3Model`],[`qwen3_moe`,`Qwen3MoeModel`],[`qwen3_next`,`Qwen3NextModel`],[`phi`,`PhiModel`],[`phi3`,`Phi3Model`],[`mpt`,`MptModel`],[`opt`,`OPTModel`],[`mistral`,`MistralModel`],[`mistral4`,`Mistral4Model`],[`ministral`,`MinistralModel`],[`ministral3`,`Ministral3Model`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2Model`],[`deepseek_v3`,`DeepseekV3Model`],[`deepseek_v4`,`DeepseekV4Model`],[`falcon`,`FalconModel`],[`falcon_h1`,`FalconH1Model`],[`nemotron_h`,`NemotronHModel`],[`solar_open`,`SolarOpenModel`],[`stablelm`,`StableLmModel`],[`modernbert-decoder`,`ModernBertDecoderModel`],[`hunyuan_v1_dense`,`HunYuanDenseV1Model`],[`youtu`,`YoutuModel`],[`zaya`,`ZayaModel`],[`hrm_text`,`HrmTextModel`]]),vk=/* @__PURE__ */ new Map([[`speecht5`,`SpeechT5ForSpeechToText`],[`whisper`,`WhisperForConditionalGeneration`],[`lite-whisper`,`LiteWhisperForConditionalGeneration`],[`moonshine`,`MoonshineForConditionalGeneration`],[`cohere_asr`,`CohereAsrForConditionalGeneration`]]),yk=/* @__PURE__ */ new Map([[`speecht5`,`SpeechT5ForTextToSpeech`]]),bk=/* @__PURE__ */ new Map([[`vits`,`VitsModel`],[`musicgen`,`MusicgenForConditionalGeneration`],[`supertonic`,`SupertonicForConditionalGeneration`]]),xk=/* @__PURE__ */ new Map([[`bert`,`BertForSequenceClassification`],[`eurobert`,`EuroBertForSequenceClassification`],[`neobert`,`NeoBertForSequenceClassification`],[`modernbert`,`ModernBertForSequenceClassification`],[`roformer`,`RoFormerForSequenceClassification`],[`electra`,`ElectraForSequenceClassification`],[`esm`,`EsmForSequenceClassification`],[`convbert`,`ConvBertForSequenceClassification`],[`camembert`,`CamembertForSequenceClassification`],[`deberta`,`DebertaForSequenceClassification`],[`deberta-v2`,`DebertaV2ForSequenceClassification`],[`mpnet`,`MPNetForSequenceClassification`],[`albert`,`AlbertForSequenceClassification`],[`distilbert`,`DistilBertForSequenceClassification`],[`roberta`,`RobertaForSequenceClassification`],[`xlm`,`XLMForSequenceClassification`],[`xlm-roberta`,`XLMRobertaForSequenceClassification`],[`bart`,`BartForSequenceClassification`],[`mbart`,`MBartForSequenceClassification`],[`mobilebert`,`MobileBertForSequenceClassification`],[`squeezebert`,`SqueezeBertForSequenceClassification`]]),Sk=/* @__PURE__ */ new Map([[`bert`,`BertForTokenClassification`],[`eurobert`,`EuroBertForTokenClassification`],[`neobert`,`NeoBertForTokenClassification`],[`modernbert`,`ModernBertForTokenClassification`],[`roformer`,`RoFormerForTokenClassification`],[`electra`,`ElectraForTokenClassification`],[`esm`,`EsmForTokenClassification`],[`convbert`,`ConvBertForTokenClassification`],[`camembert`,`CamembertForTokenClassification`],[`deberta`,`DebertaForTokenClassification`],[`deberta-v2`,`DebertaV2ForTokenClassification`],[`mpnet`,`MPNetForTokenClassification`],[`distilbert`,`DistilBertForTokenClassification`],[`roberta`,`RobertaForTokenClassification`],[`xlm`,`XLMForTokenClassification`],[`xlm-roberta`,`XLMRobertaForTokenClassification`],[`openai_privacy_filter`,`OpenAIPrivacyFilterForTokenClassification`]]),Ck=/* @__PURE__ */ new Map([[`t5`,`T5ForConditionalGeneration`],[`longt5`,`LongT5ForConditionalGeneration`],[`mt5`,`MT5ForConditionalGeneration`],[`bart`,`BartForConditionalGeneration`],[`mbart`,`MBartForConditionalGeneration`],[`marian`,`MarianMTModel`],[`m2m_100`,`M2M100ForConditionalGeneration`],[`blenderbot`,`BlenderbotForConditionalGeneration`],[`blenderbot-small`,`BlenderbotSmallForConditionalGeneration`]]),wk=/* @__PURE__ */ new Map([[`bloom`,`BloomForCausalLM`],[`gpt2`,`GPT2LMHeadModel`],[`gpt_oss`,`GptOssForCausalLM`],[`jais`,`JAISLMHeadModel`],[`gptj`,`GPTJForCausalLM`],[`gpt_bigcode`,`GPTBigCodeForCausalLM`],[`gpt_neo`,`GPTNeoForCausalLM`],[`gpt_neox`,`GPTNeoXForCausalLM`],[`codegen`,`CodeGenForCausalLM`],[`llama`,`LlamaForCausalLM`],[`nanochat`,`NanoChatForCausalLM`],[`apertus`,`ApertusForCausalLM`],[`llama4_text`,`Llama4ForCausalLM`],[`arcee`,`ArceeForCausalLM`],[`afmoe`,`AfmoeForCausalLM`],[`lfm2`,`Lfm2ForCausalLM`],[`lfm2_moe`,`Lfm2MoeForCausalLM`],[`smollm3`,`SmolLM3ForCausalLM`],[`exaone`,`ExaoneForCausalLM`],[`olmo`,`OlmoForCausalLM`],[`olmo2`,`Olmo2ForCausalLM`],[`olmo3`,`Olmo3ForCausalLM`],[`olmo_hybrid`,`OlmoHybridForCausalLM`],[`mobilellm`,`MobileLLMForCausalLM`],[`granite`,`GraniteForCausalLM`],[`granitemoehybrid`,`GraniteMoeHybridForCausalLM`],[`cohere`,`CohereForCausalLM`],[`cohere2`,`Cohere2ForCausalLM`],[`gemma`,`GemmaForCausalLM`],[`gemma2`,`Gemma2ForCausalLM`],[`vaultgemma`,`VaultGemmaForCausalLM`],[`gemma3_text`,`Gemma3ForCausalLM`],[`gemma3`,`Gemma3ForCausalLM`],[`helium`,`HeliumForCausalLM`],[`glm`,`GlmForCausalLM`],[`glm_moe_dsa`,`GlmMoeDsaForCausalLM`],[`openelm`,`OpenELMForCausalLM`],[`qwen2`,`Qwen2ForCausalLM`],[`qwen2_moe`,`Qwen2MoeForCausalLM`],[`qwen3`,`Qwen3ForCausalLM`],[`qwen3_moe`,`Qwen3MoeForCausalLM`],[`qwen3_next`,`Qwen3NextForCausalLM`],[`qwen2_vl`,`Qwen2VLForCausalLM`],[`qwen2_5_vl`,`Qwen2_5_VLForCausalLM`],[`qwen3_vl`,`Qwen3VLForCausalLM`],[`qwen3_vl_moe`,`Qwen3VLMoeForCausalLM`],[`qwen3_5`,`Qwen3_5ForCausalLM`],[`qwen3_5_text`,`Qwen3_5ForCausalLM`],[`qwen3_5_moe`,`Qwen3_5MoeForCausalLM`],[`gemma3n`,`Gemma3nForCausalLM`],[`gemma4`,`Gemma4ForCausalLM`],[`phi`,`PhiForCausalLM`],[`phi3`,`Phi3ForCausalLM`],[`mpt`,`MptForCausalLM`],[`opt`,`OPTForCausalLM`],[`mbart`,`MBartForCausalLM`],[`mistral`,`MistralForCausalLM`],[`mistral4`,`Mistral4ForCausalLM`],[`ministral`,`MinistralForCausalLM`],[`ministral3`,`Ministral3ForCausalLM`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2ForCausalLM`],[`deepseek_v3`,`DeepseekV3ForCausalLM`],[`deepseek_v4`,`DeepseekV4ForCausalLM`],[`falcon`,`FalconForCausalLM`],[`falcon_h1`,`FalconH1ForCausalLM`],[`nemotron_h`,`NemotronHForCausalLM`],[`trocr`,`TrOCRForCausalLM`],[`solar_open`,`SolarOpenForCausalLM`],[`stablelm`,`StableLmForCausalLM`],[`modernbert-decoder`,`ModernBertDecoderForCausalLM`],[`hunyuan_v1_dense`,`HunYuanDenseV1ForCausalLM`],[`youtu`,`YoutuForCausalLM`],[`zaya`,`ZayaForCausalLM`],[`hrm_text`,`HrmTextForCausalLM`],[`phi3_v`,`Phi3VForCausalLM`]]),Tk=/* @__PURE__ */ new Map([[`multi_modality`,`MultiModalityCausalLM`]]),Ek=/* @__PURE__ */ new Map([[`bert`,`BertForMaskedLM`],[`eurobert`,`EuroBertForMaskedLM`],[`neobert`,`NeoBertForMaskedLM`],[`modernbert`,`ModernBertForMaskedLM`],[`roformer`,`RoFormerForMaskedLM`],[`electra`,`ElectraForMaskedLM`],[`esm`,`EsmForMaskedLM`],[`convbert`,`ConvBertForMaskedLM`],[`camembert`,`CamembertForMaskedLM`],[`deberta`,`DebertaForMaskedLM`],[`deberta-v2`,`DebertaV2ForMaskedLM`],[`mpnet`,`MPNetForMaskedLM`],[`albert`,`AlbertForMaskedLM`],[`distilbert`,`DistilBertForMaskedLM`],[`roberta`,`RobertaForMaskedLM`],[`xlm`,`XLMWithLMHeadModel`],[`xlm-roberta`,`XLMRobertaForMaskedLM`],[`mobilebert`,`MobileBertForMaskedLM`],[`squeezebert`,`SqueezeBertForMaskedLM`]]),Dk=/* @__PURE__ */ new Map([[`bert`,`BertForQuestionAnswering`],[`neobert`,`NeoBertForQuestionAnswering`],[`roformer`,`RoFormerForQuestionAnswering`],[`electra`,`ElectraForQuestionAnswering`],[`convbert`,`ConvBertForQuestionAnswering`],[`camembert`,`CamembertForQuestionAnswering`],[`deberta`,`DebertaForQuestionAnswering`],[`deberta-v2`,`DebertaV2ForQuestionAnswering`],[`mpnet`,`MPNetForQuestionAnswering`],[`albert`,`AlbertForQuestionAnswering`],[`distilbert`,`DistilBertForQuestionAnswering`],[`roberta`,`RobertaForQuestionAnswering`],[`xlm`,`XLMForQuestionAnswering`],[`xlm-roberta`,`XLMRobertaForQuestionAnswering`],[`mobilebert`,`MobileBertForQuestionAnswering`],[`squeezebert`,`SqueezeBertForQuestionAnswering`]]),Ok=/* @__PURE__ */ new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`]]),kk=/* @__PURE__ */ new Map([[`llava`,`LlavaForConditionalGeneration`],[`llava_onevision`,`LlavaOnevisionForConditionalGeneration`],[`moondream1`,`Moondream1ForConditionalGeneration`],[`florence2`,`Florence2ForConditionalGeneration`],[`qwen2_vl`,`Qwen2VLForConditionalGeneration`],[`qwen2_5_vl`,`Qwen2_5_VLForConditionalGeneration`],[`qwen3_vl`,`Qwen3VLForConditionalGeneration`],[`qwen3_vl_moe`,`Qwen3VLMoeForConditionalGeneration`],[`qwen3_5`,`Qwen3_5ForConditionalGeneration`],[`qwen3_5_moe`,`Qwen3_5MoeForConditionalGeneration`],[`lfm2_vl`,`Lfm2VlForConditionalGeneration`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`],[`paligemma`,`PaliGemmaForConditionalGeneration`],[`llava_qwen2`,`LlavaQwen2ForCausalLM`],[`gemma3`,`Gemma3ForConditionalGeneration`],[`gemma3n`,`Gemma3nForConditionalGeneration`],[`gemma4`,`Gemma4ForConditionalGeneration`],[`mistral3`,`Mistral3ForConditionalGeneration`],[`lighton_ocr`,`LightOnOcrForConditionalGeneration`],[`glm_ocr`,`GlmOcrForConditionalGeneration`]]),Ak=/* @__PURE__ */ new Map([[`granite_speech`,`GraniteSpeechForConditionalGeneration`],[`ultravox`,`UltravoxModel`],[`voxtral`,`VoxtralForConditionalGeneration`],[`voxtral_realtime`,`VoxtralRealtimeForConditionalGeneration`]]),jk=/* @__PURE__ */ new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`]]),Mk=/* @__PURE__ */ new Map([[`vit`,`ViTForImageClassification`],[`ijepa`,`IJepaForImageClassification`],[`pvt`,`PvtForImageClassification`],[`vit_msn`,`ViTMSNForImageClassification`],[`fastvit`,`FastViTForImageClassification`],[`mobilevit`,`MobileViTForImageClassification`],[`mobilevitv2`,`MobileViTV2ForImageClassification`],[`beit`,`BeitForImageClassification`],[`deit`,`DeiTForImageClassification`],[`hiera`,`HieraForImageClassification`],[`convnext`,`ConvNextForImageClassification`],[`convnextv2`,`ConvNextV2ForImageClassification`],[`dinov2`,`Dinov2ForImageClassification`],[`dinov2_with_registers`,`Dinov2WithRegistersForImageClassification`],[`resnet`,`ResNetForImageClassification`],[`swin`,`SwinForImageClassification`],[`segformer`,`SegformerForImageClassification`],[`efficientnet`,`EfficientNetForImageClassification`],[`mobilenet_v1`,`MobileNetV1ForImageClassification`],[`mobilenet_v2`,`MobileNetV2ForImageClassification`],[`mobilenet_v3`,`MobileNetV3ForImageClassification`],[`mobilenet_v4`,`MobileNetV4ForImageClassification`]]),Nk=/* @__PURE__ */ new Map([[`detr`,`DetrForObjectDetection`],[`rt_detr`,`RTDetrForObjectDetection`],[`rt_detr_v2`,`RTDetrV2ForObjectDetection`],[`rf_detr`,`RFDetrForObjectDetection`],[`d_fine`,`DFineForObjectDetection`],[`table-transformer`,`TableTransformerForObjectDetection`],[`yolos`,`YolosForObjectDetection`]]),Pk=/* @__PURE__ */ new Map([[`owlvit`,`OwlViTForObjectDetection`],[`owlv2`,`Owlv2ForObjectDetection`],[`grounding-dino`,`GroundingDinoForObjectDetection`]]),Fk=/* @__PURE__ */ new Map([[`detr`,`DetrForSegmentation`],[`clipseg`,`CLIPSegForImageSegmentation`]]),Ik=/* @__PURE__ */ new Map([[`segformer`,`SegformerForSemanticSegmentation`],[`sapiens`,`SapiensForSemanticSegmentation`],[`swin`,`SwinForSemanticSegmentation`],[`mobilenet_v1`,`MobileNetV1ForSemanticSegmentation`],[`mobilenet_v2`,`MobileNetV2ForSemanticSegmentation`],[`mobilenet_v3`,`MobileNetV3ForSemanticSegmentation`],[`mobilenet_v4`,`MobileNetV4ForSemanticSegmentation`]]),Lk=/* @__PURE__ */ new Map([[`detr`,`DetrForSegmentation`],[`maskformer`,`MaskFormerForInstanceSegmentation`]]),Rk=/* @__PURE__ */ new Map([[`sam`,`SamModel`],[`sam2`,`Sam2Model`],[`edgetam`,`EdgeTamModel`],[`sam3_tracker`,`Sam3TrackerModel`]]),zk=/* @__PURE__ */ new Map([[`wav2vec2`,`Wav2Vec2ForCTC`],[`wav2vec2-bert`,`Wav2Vec2BertForCTC`],[`unispeech`,`UniSpeechForCTC`],[`unispeech-sat`,`UniSpeechSatForCTC`],[`wavlm`,`WavLMForCTC`],[`hubert`,`HubertForCTC`],[`parakeet_ctc`,`ParakeetForCTC`]]),Bk=/* @__PURE__ */ new Map([[`wav2vec2`,`Wav2Vec2ForSequenceClassification`],[`wav2vec2-bert`,`Wav2Vec2BertForSequenceClassification`],[`unispeech`,`UniSpeechForSequenceClassification`],[`unispeech-sat`,`UniSpeechSatForSequenceClassification`],[`wavlm`,`WavLMForSequenceClassification`],[`hubert`,`HubertForSequenceClassification`],[`audio-spectrogram-transformer`,`ASTForAudioClassification`]]),Vk=/* @__PURE__ */ new Map([[`wavlm`,`WavLMForXVector`]]),Hk=/* @__PURE__ */ new Map([[`unispeech-sat`,`UniSpeechSatForAudioFrameClassification`],[`wavlm`,`WavLMForAudioFrameClassification`],[`wav2vec2`,`Wav2Vec2ForAudioFrameClassification`],[`pyannote`,`PyAnnoteForAudioFrameClassification`]]),Uk=/* @__PURE__ */ new Map([[`vitmatte`,`VitMatteForImageMatting`]]),Wk=/* @__PURE__ */ new Map([[`patchtst`,`PatchTSTForPrediction`],[`patchtsmixer`,`PatchTSMixerForPrediction`]]),Gk=/* @__PURE__ */ new Map([[`swin2sr`,`Swin2SRForImageSuperResolution`]]),Kk=/* @__PURE__ */ new Map([[`chmv2`,`CHMv2ForDepthEstimation`],[`dpt`,`DPTForDepthEstimation`],[`depth_anything`,`DepthAnythingForDepthEstimation`],[`glpn`,`GLPNForDepthEstimation`],[`sapiens`,`SapiensForDepthEstimation`],[`depth_pro`,`DepthProForDepthEstimation`],[`metric3d`,`Metric3DForDepthEstimation`],[`metric3dv2`,`Metric3Dv2ForDepthEstimation`]]),qk=/* @__PURE__ */ new Map([[`sapiens`,`SapiensForNormalEstimation`]]),Jk=/* @__PURE__ */ new Map([[`vitpose`,`VitPoseForPoseEstimation`]]),Yk=/* @__PURE__ */ new Map([[`clip`,`CLIPVisionModelWithProjection`],[`siglip`,`SiglipVisionModel`],[`jina_clip`,`JinaCLIPVisionModel`]]),Xk=[[mk,X.EncoderOnly],[hk,X.EncoderDecoder],[_k,X.DecoderOnlyWithoutHead],[gk,X.AutoEncoder],[xk,X.EncoderOnly],[Sk,X.EncoderOnly],[Ck,X.Seq2Seq],[vk,X.Seq2Seq],[wk,X.DecoderOnly],[Tk,X.MultiModality],[Ek,X.EncoderOnly],[Dk,X.EncoderOnly],[Ok,X.Vision2Seq],[kk,X.ImageTextToText],[Ak,X.AudioTextToText],[Mk,X.EncoderOnly],[Fk,X.EncoderOnly],[Lk,X.EncoderOnly],[Ik,X.EncoderOnly],[Uk,X.EncoderOnly],[Wk,X.EncoderOnly],[Gk,X.EncoderOnly],[Kk,X.EncoderOnly],[qk,X.EncoderOnly],[Jk,X.EncoderOnly],[Nk,X.EncoderOnly],[Pk,X.EncoderOnly],[Rk,X.MaskGeneration],[zk,X.EncoderOnly],[Bk,X.EncoderOnly],[yk,X.Seq2Seq],[bk,X.EncoderOnly],[Vk,X.EncoderOnly],[Hk,X.EncoderOnly],[Yk,X.EncoderOnly]];for(let[e,t]of Xk)for(let n of e.values()){Ag.set(n,t);let e=e_[n];Mg.set(e,n),jg.set(n,e)}var Zk=[[`MusicgenForConditionalGeneration`,Dw,X.Musicgen],[`Phi3VForCausalLM`,jT,X.Phi3V],[`CLIPTextModelWithProjection`,sv,X.EncoderOnly],[`SiglipTextModel`,JE,X.EncoderOnly],[`JinaCLIPTextModel`,yS,X.EncoderOnly],[`ClapTextModelWithProjection`,nv,X.EncoderOnly],[`ClapAudioModelWithProjection`,rv,X.EncoderOnly],[`DacEncoderModel`,Jv,X.EncoderOnly],[`DacDecoderModel`,Yv,X.EncoderOnly],[`MimiEncoderModel`,cC,X.EncoderOnly],[`MimiDecoderModel`,lC,X.EncoderOnly],[`SnacEncoderModel`,nD,X.EncoderOnly],[`SnacDecoderModel`,rD,X.EncoderOnly],[`Gemma3nForConditionalGeneration`,qb,X.ImageAudioTextToText],[`Gemma4ForConditionalGeneration`,Yb,X.ImageAudioTextToText],[`SupertonicForConditionalGeneration`,ED,X.Supertonic],[`ChatterboxModel`,Y_,X.Chatterbox],[`VoxtralRealtimeForConditionalGeneration`,DO,X.VoxtralRealtime]];for(let[e,t,n]of Zk)Ag.set(e,n),Mg.set(t,e),jg.set(e,t);var Qk=/* @__PURE__ */ new Map([[`modnet`,Fk],[`birefnet`,Fk],[`isnet`,Fk],[`ben`,Fk]]);for(let[e,t]of Qk.entries())t.set(e,`PreTrainedModel`),Ag.set(e,X.EncoderOnly),jg.set(e,Z);var $k=new Set(Qk.keys());Ag.set(`PreTrainedModel`,X.EncoderOnly),Mg.set(Z,`PreTrainedModel`);var Q={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:xk,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:Sk,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:yk,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:bk,MODEL_FOR_MASKED_LM_MAPPING_NAMES:Ek,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:Dk,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:Mk,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Fk,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:Ik,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:Lk,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:Nk,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:Pk,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:Rk,MODEL_FOR_CTC_MAPPING_NAMES:zk,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:Bk,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:Vk,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:Hk,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:jk,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:Uk,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:Gk,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:Kk,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:qk,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:Jk,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:Yk,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:kk,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:Ak,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:Ck,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:vk,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:wk,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:Ok};Tg(Q);var $=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d};if(f.config=await kh.from_pretrained(e,f),!this.MODEL_CLASS_MAPPINGS)throw Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:p}=f.config;for(let t of this.MODEL_CLASS_MAPPINGS){let n=t.get(p);if(!n){for(let e of t.values())if(e[0]===p){n=e;break}if(!n)continue}return await e_[n].from_pretrained(e,f)}if(this.BASE_IF_FAIL)return $k.has(p)||N.warn(`Unknown model class "${p}", attempting to construct from base class.`),await Z.from_pretrained(e,f);throw Error(`Unsupported model type: ${p}`)}},eA=class extends ${static MODEL_CLASS_MAPPINGS=Xk.map(e=>e[0]);static BASE_IF_FAIL=!0},tA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},nA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},rA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},iA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},aA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},oA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},sA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},cA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},lA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},uA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},dA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},fA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},pA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},mA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},hA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},gA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});var _A=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_CTC_MAPPING_NAMES]},vA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]}),class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]};var yA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});var bA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},xA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]}),class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]};var SA=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]}),class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function CA(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>Kf.read(e)))}async function wA(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>typeof e==`string`||e instanceof URL?Yd(e,t):e instanceof Float64Array?new Float32Array(e):e))}function TA(e,t){t&&(e=e.map(e=>e|0));let[n,r,i,a]=e;return{xmin:n,ymin:r,xmax:i,ymax:a}}var EA=class extends ti{constructor({task:e,model:t,tokenizer:n=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=r}async dispose(){await this.model.dispose()}},DA=class extends EA{async _call(e,{top_k:t=1}={}){let n=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(n),{problem_type:i,id2label:a}=this.model.config,o=i===`multi_label_classification`?e=>e.sigmoid():e=>new U(`float32`,ll(e.data),e.dims),s=[];for(let e of r.logits){let n=await su(o(e),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));t===1?s.push(...i):s.push(i)}return Array.isArray(e)||t===1?s:s[0]}},OA=class extends EA{async _call(e,{ignore_labels:t=[`O`],aggregation_strategy:n=`none`}={}){if(n!==`none`&&n!==`simple`)throw Error(`Invalid aggregation_strategy: "${n}". Must be one of "none" or "simple".`);let r=Array.isArray(e),i=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),a=(await this.model(i)).logits,o=this.model.config.id2label,s=[];for(let e=0;e{let o=0,s=[];for(let n=i;ne==u),i=a[e].tolist(),f=o[e].tolist();for(let n=1;ne==t[n])!==-1)&&(i[n]=-1/0,f[n]=-1/0);let p=ll(i).map((e,t)=>[e,t]),m=ll(f).map((e,t)=>[e,t]);p[0][0]=0,m[0][0]=0;let h=ci(p,m).filter(e=>e[0][1]<=e[1][1]).map(e=>[e[0][1],e[1][1],e[0][0]*e[1][0]]).sort((e,t)=>t[2]-e[2]),g=[];for(let e=0;ee==n);if(c===-1)throw Error(`Mask token (${r}) not found in text.`);let l=a[e][c],u=await su(new U(`float32`,ll(l.data),l.dims),t),d=u[0].tolist(),f=u[1].tolist();o.push(f.map((e,t)=>{let n=i.slice();return n[c]=e,{score:d[t],token:Number(e),token_str:this.tokenizer.decode([e]),sequence:this.tokenizer.decode(n,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},NA=class extends EA{_default_generation_config={max_new_tokens:256};_key=`generated_text`;async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(e=>this.model.config.prefix+e));let n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(e=e.map(e=>n[this.task].prefix+e));let r=this.tokenizer,i={padding:!0,truncation:!0},a;a=this.task===`translation`&&`_build_translation_inputs`in r?r._build_translation_inputs(e,i,t):r(e,i);let o=await this.model.generate({...a,...this._default_generation_config,...t});return r.batch_decode(o,{skip_special_tokens:!0}).map(e=>({[this._key]:e}))}},PA=class extends NA{_key=`summary_text`},FA=class extends NA{_key=`translation_text`};function IA(e){return Array.isArray(e)&&e.every(e=>`role`in e&&`content`in e)}var LA=class extends EA{_default_generation_config={max_new_tokens:256};async _call(e,t={}){let{add_special_tokens:n,return_full_text:r,tools:i,documents:a,chat_template:o,tokenizer_encode_kwargs:s,...c}=t,l=!1,u=!1,d=n??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,f=s,p;if(typeof e==`string`)p=e=[e];else if(Array.isArray(e)&&e.every(e=>typeof e==`string`))l=!0,p=e;else{if(IA(e))e=[e];else if(Array.isArray(e)&&e.every(IA))l=!0;else throw Error(`Input must be a string, an array of strings, a Chat, or an array of Chats`);u=!0;let t={tokenize:!1,add_generation_prompt:!0,...ui({tools:i,documents:a,chat_template:o},[`tools`,`documents`,`chat_template`]),...f};p=e.map(e=>this.tokenizer.apply_chat_template(e,t)),d=!1,f=void 0}let m=u?!1:r??!0;this.tokenizer.padding_side=`left`;let h=this.tokenizer(p,{add_special_tokens:d,padding:!0,truncation:!0,...f}),g=await this.model.generate({...h,...this._default_generation_config,...c}),_=this.tokenizer.batch_decode(g,{skip_special_tokens:!0}),v;!m&&h.input_ids.dims.at(-1)>0&&(v=this.tokenizer.batch_decode(h.input_ids,{skip_special_tokens:!0}).map(e=>e.length));let y=Array.from({length:e.length},e=>[]);for(let t=0;t<_.length;++t){let n=Math.floor(t/g.dims[0]*e.length);v&&(_[t]=_[t].slice(v[n])),y[n].push({generated_text:u?[...e[n],{role:`assistant`,content:_[t]}]:_[t]})}return!l&&y.length===1?y[0]:y}},RA=class extends EA{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([e,t])=>[e.toLowerCase(),t])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(N.warn(`Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.`),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(N.warn(`Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.`),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n=`This example is {}.`,multi_label:r=!1}={}){let i=Array.isArray(e);i||(e=[e]),Array.isArray(t)||(t=[t]);let a=t.map(e=>n.replace(`{}`,e)),o=r||t.length===1,s=[];for(let n of e){let e=[];for(let t of a){let r=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),i=await this.model(r);o?e.push([i.logits.data[this.contradiction_id],i.logits.data[this.entailment_id]]):e.push(i.logits.data[this.entailment_id])}let r=(o?e.map(e=>ll(e)[1]):ll(e)).map((e,t)=>[e,t]).sort((e,t)=>t[0]-e[0]);s.push({sequence:n,labels:r.map(e=>t[e[1]]),scores:r.map(e=>e[0])})}return i?s:s[0]}},zA=class extends EA{async _call(e,{top_k:t=5}={}){let n=this.processor.feature_extractor.config.sampling_rate,r=await wA(e,n),i=this.model.config.id2label,a=[];for(let e of r){let n=await this.processor(e),r=(await this.model(n)).logits[0],o=await su(new U(`float32`,ll(r.data),r.dims),t),s=o[0].tolist(),c=o[1].tolist().map((e,t)=>({label:i?i[e]:`LABEL_${e}`,score:s[t]}));a.push(c)}return Array.isArray(e)?a:a[0]}},BA=class extends EA{async _call(e,t,{hypothesis_template:n=`This is a sound of {}.`}={}){let r=!Array.isArray(e);r&&(e=[e]);let i=t.map(e=>n.replace(`{}`,e)),a=this.tokenizer(i,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,s=await wA(e,o),c=[];for(let e of s){let n=await this.processor(e),r=ll((await this.model({...a,...n})).logits_per_audio.data);c.push([...r].map((e,n)=>({score:e,label:t[n]})))}return r?c[0]:c}},VA=class extends EA{_default_generation_config={};async _call(e,t={}){switch(t={...this._default_generation_config,...t},this.model.config.model_type){case`whisper`:case`lite-whisper`:return this._call_whisper(e,t);case`wav2vec2`:case`wav2vec2-bert`:case`unispeech`:case`unispeech-sat`:case`hubert`:case`parakeet_ctc`:return this._call_wav2vec2(e,t);case`moonshine`:return this._call_moonshine(e,t);case`cohere_asr`:return this._call_cohere_asr(e,t);default:throw Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&N.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&N.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await wA(r,i),o=[];for(let e of a){let t=await this.processor(e),n=(await this.model(t)).logits[0],r=[];for(let e of n)r.push(fl(e.data)[1]);let i=this.tokenizer.decode(r,{skip_special_tokens:!0}).trim();o.push({text:i})}return n?o[0]:o}async _call_whisper(e,t){let n=t.return_timestamps??!1,r=t.chunk_length_s??0,i=t.force_full_sequences??!1,a=t.stride_length_s??null,o={...t};n===`word`&&(o.return_token_timestamps=!0,o.return_timestamps=!0);let s=!Array.isArray(e),c=s?[e]:e,l=this.processor.feature_extractor.config,u=l.chunk_length/this.model.config.max_source_positions,d=l.hop_length,f=l.sampling_rate,p=await wA(c,f),m=[];for(let e of p){let t=[];if(r>0){if(a===null)a=r/6;else if(r<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let n=f*r,i=f*a,o=n-2*i,s=0;for(;;){let r=s+n,a=e.subarray(s,r),c=await this.processor(a),l=s===0,u=r>=e.length;if(t.push({stride:[a.length,l?0:i,u?0:i],input_features:c.input_features,is_last:u}),u)break;s+=o}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(let e of t){o.num_frames=Math.floor(e.stride[0]/d);let t=await this.model.generate({inputs:e.input_features,...o});if(n===`word`){let n=t.sequences.tolist()[0],r=t.token_timestamps.tolist()[0],i=this.tokenizer.timestamp_begin,a=Math.max(n.findIndex(e=>Number(e)>=i),0);e.tokens=n.slice(a),e.token_timestamps=r.slice(a).map(e=>vl(e,2))}else e.tokens=t[0].tolist();e.stride=e.stride.map(e=>e/f)}let[s,c]=this.tokenizer._decode_asr(t,{time_precision:u,return_timestamps:n,force_full_sequences:i});m.push({text:s,...c})}return s?m[0]:m}async _call_moonshine(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await wA(r,i),o=[];for(let e of a){let n=await this.processor(e),r=Math.floor(e.length/i)*6,a=await this.model.generate({max_new_tokens:r,...t,...n}),s=this.tokenizer.batch_decode(a,{skip_special_tokens:!0})[0];o.push({text:s})}return n?o[0]:o}async _call_cohere_asr(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor,a=i.config.sampling_rate,o=await wA(r,a),s=t.language??`en`,c=this.processor.get_decoder_prompt_ids(s),l=[];for(let e of o){let n=i.split_audio(e),r=[];for(let e of n){let n=await this.processor(e),i=await this.model.generate({...n,decoder_input_ids:c,...t}),a=this.tokenizer.decode(i[0].tolist(),{skip_special_tokens:!0}).trim();r.push(a)}let a=this.processor.constructor.join_chunks(r,s);l.push({text:a})}return n?l[0]:l}},HA=class extends EA{DEFAULT_VOCODER_ID=`Xenova/speecht5_hifigan`;constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if((typeof e==`string`||e instanceof URL)&&(e=new Float32Array(await(await M.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new U(`float32`,e,[e.length]);else if(!(e instanceof U))throw Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,n,r=null){let i=t.data,[a,o]=t.dims,s=r?r.data:null,c=[];for(let e=0;e({generated_text:e.trim()}));a.push(r)}return n?a:a[0]}},WA=class extends EA{async _call(e,{top_k:t=5}={}){let n=await CA(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),{id2label:a}=this.model.config,o=[];for(let e of i.logits){let n=await su(new U(`float32`,ll(e.data),e.dims),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));o.push(i)}return Array.isArray(e)?o:o[0]}},GA={panoptic:`post_process_panoptic_segmentation`,instance:`post_process_instance_segmentation`,semantic:`post_process_semantic_segmentation`},KA=class extends EA{async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:i=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error(`Image segmentation pipeline currently only supports a batch size of 1.`);let s=await CA(e),c=s.map(e=>[e.height,e.width]),l=await this.processor(s),{inputNames:u,outputNames:d}=this.model.sessions.model;if(!u.includes(`pixel_values`)){if(u.length!==1)throw Error(`Expected a single input name, but got ${u.length} inputs: ${u}.`);let e=u[0];if(e in l)throw Error(`Input name ${e} already exists in the inputs.`);l[e]=l.pixel_values}let f=await this.model(l),p=null;if(o!==null)p=GA[o];else if(this.processor.image_processor){for(let[e,t]of Object.entries(GA))if(t in this.processor.image_processor){p=this.processor.image_processor[t].bind(this.processor.image_processor),o=e;break}}let m=this.model.config.id2label,h=[];if(!o){let e=f[d[0]];for(let t=0;te<-1e-5||e>1.00001)&&r.sigmoid_();let i=await Kf.fromTensor(r.mul_(255).to(`uint8`)).resize(n[1],n[0]);h.push({label:null,score:null,mask:i})}}else if(o===`panoptic`||o===`instance`){let e=p(f,t,n,r,i,a??c)[0],o=e.segmentation;for(let t of e.segments_info){let e=new Uint8ClampedArray(o.data.length);for(let n=0;n{let n=e.clone();return n.putAlpha(r[t].mask),n});return Array.isArray(e)?i:i[0]}},model:[fA,pA,mA],default:{model:`Xenova/modnet`},type:`image`},"zero-shot-image-classification":{pipeline:class extends EA{async _call(e,t,{hypothesis_template:n=`This is a photo of {}`}={}){let r=Array.isArray(e),i=await CA(e),a=t.map(e=>n.replace(`{}`,e)),o=this.tokenizer(a,{padding:this.model.config.model_type!==`siglip`||`max_length`,truncation:!0}),{pixel_values:s}=await this.processor(i),c=await this.model({...o,pixel_values:s}),l=this.model.config.model_type===`siglip`?e=>e.sigmoid().data:e=>ll(e.data),u=[];for(let e of c.logits_per_image){let n=[...l(e)].map((e,n)=>({score:e,label:t[n]}));n.sort((e,t)=>t.score-e.score),u.push(n)}return r?u:u[0]}},model:eA,default:{model:`Xenova/clip-vit-base-patch32`},type:`multimodal`},"object-detection":{pipeline:class extends EA{async _call(e,{threshold:t=.9,percentage:n=!1}={}){let r=Array.isArray(e);if(r&&e.length!==1)throw Error(`Object detection pipeline currently only supports a batch size of 1.`);let i=await CA(e),a=n?null:i.map(e=>[e.height,e.width]),{pixel_values:o,pixel_mask:s}=await this.processor(i),c=await this.model({pixel_values:o,pixel_mask:s}),l=this.processor.image_processor.post_process_object_detection(c,t,a),{id2label:u}=this.model.config,d=l.map(e=>e.boxes.map((t,r)=>({score:e.scores[r],label:u[e.classes[r]],box:TA(t,!n)})));return r?d:d[0]}},model:hA,default:{model:`Xenova/detr-resnet-50`},type:`multimodal`},"zero-shot-object-detection":{pipeline:class extends EA{async _call(e,t,{threshold:n=.1,top_k:r=null,percentage:i=!1}={}){let a=Array.isArray(e),o=await CA(e),s=this.tokenizer(t,{padding:!0,truncation:!0}),c=await this.processor(o),l=[];for(let e=0;e({score:e.scores[n],label:e.labels[n],box:TA(t,!i)}))}else{let e=this.processor.image_processor.post_process_object_detection(f,n,u,!0)[0];p=e.boxes.map((n,r)=>({score:e.scores[r],label:t[e.classes[r]],box:TA(n,!i)}))}p.sort((e,t)=>t.score-e.score),r!==null&&(p=p.slice(0,r)),l.push(p)}return a?l:l[0]}},model:gA,default:{model:`Xenova/owlvit-base-patch32`},type:`multimodal`},"document-question-answering":{pipeline:class extends EA{_default_generation_config={max_new_tokens:256};async _call(e,t,n={}){if(Array.isArray(e)){if(e.length!==1)throw Error(`Document Question Answering pipeline currently only supports a batch size of 1.`);e=e[0]}let r=(await CA(e))[0],{pixel_values:i}=await this.processor(r),a=`${t}`,o=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,s=await this.model.generate({inputs:i,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...this._default_generation_config,...n}),c=this.tokenizer.batch_decode(s)[0].match(/(.*?)<\/s_answer>/),l=null;return c&&c.length>=2&&(l=c[1].trim()),[{answer:l}]}},model:yA,default:{model:`Xenova/donut-base-finetuned-docvqa`},type:`multimodal`},"image-to-image":{pipeline:class extends EA{async _call(e){let t=await CA(e),n=await this.processor(t),r=await this.model(n),i=[];for(let e of r.reconstruction){let t=e.squeeze().clamp_(0,1).mul_(255).round_().to(`uint8`);i.push(Kf.fromTensor(t))}return Array.isArray(e)?i:i[0]}},model:bA,default:{model:`Xenova/swin2SR-classical-sr-x2-64`},type:`image`},"depth-estimation":{pipeline:class extends EA{async _call(e){let t=await CA(e),n=await this.processor(t),{predicted_depth:r}=await this.model(n),i=[];for(let e=0;e`onnx/${e}`);return s.filter(e=>!e.startsWith(`onnx/`)||t.some(t=>e.startsWith(t)))}}return s}async function QA(e,t=null,{progress_callback:n=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:o=`main`,device:s=null,dtype:c=null,subfolder:l=`onnx`,use_external_data_format:u=null,model_file_name:d=null,session_options:f={}}={}){e=JA[e]??e;let p=qA[e.split(`_`,1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(qA)}]`);t||(t=p.default.model,N.info(`No model specified. Using default model: "${t}".`),!c&&p.default.dtype&&(c=p.default.dtype));let m=await ZA(e,t,{device:s,dtype:c}),h={};if(n)try{(await Promise.all(m.map(async e=>Yc(t,e)))).forEach((e,t)=>{e.exists&&(h[m[t]]={loaded:0,total:e.size??0})})}catch(e){N.warn(`Unable to fetch model file metadata for total progress tracking: ${e}`)}let g={progress_callback:n?new ri(n,h):void 0,config:r,cache_dir:i,local_files_only:a,revision:o,device:s,dtype:c,subfolder:l,use_external_data_format:u,model_file_name:d,session_options:f},_=m.includes(`tokenizer.json`),v=m.includes(`preprocessor_config.json`),y=p.model,b;if(Array.isArray(y)){let n=r??await kh.from_pretrained(t,g),{model_type:i}=n,a=y.find(e=>e.supports(i));if(!a)throw Error(`Unsupported model type "${i}" for task "${e}". None of the candidate model classes support this type.`);b=a.from_pretrained(t,{...g,config:n})}else b=y.from_pretrained(t,g);let[x,ee,S]=await Promise.all([_?G.from_pretrained(t,g):null,v?Ch.from_pretrained(t,g):null,b]),te={task:e,model:S};x&&(te.tokenizer=x),ee&&(te.processor=ee),ni(n,{status:`ready`,task:e,model:t});let C=p.pipeline;return new C(te)}j.IS_PROCESS_AVAILABLE,Object.keys($l);export{Kf as RawImage,QA as pipeline}; \ No newline at end of file diff --git a/v4d-next/assets/video.worker-DUP1KR4N.js b/v4d-next/assets/video.worker-DUP1KR4N.js new file mode 100644 index 0000000..cf9ccdd --- /dev/null +++ b/v4d-next/assets/video.worker-DUP1KR4N.js @@ -0,0 +1 @@ +const e={black:.12,white:.9};function t(e,t,n,r,i=0){let a=(e+t+n)/3,o=1/(a+8);r[i]=(e-a)*o,r[i+1]=(t-a)*o,r[i+2]=(n-a)*o}const n=/* @__PURE__ */ new Float64Array(3);function r(e,r,i){t(e,r,i,n);let a=Math.max(Math.hypot(n[0],n[1],n[2]),.001);return[n[0]/a,n[1]/a,n[2]/a,a]}function i(e,t,n,r,i,a,o){let s=(e+t+n)/3,c=1/(s+8),l=(e-s)*c,u=(t-s)*c,d=(n-s)*c,f=l*r+u*i+d*a,p=Math.max(0,l*l+u*u+d*d-f*f);return 1-f/o+2*Math.sqrt(p)/o}function a(e){if(!e.length)return 0;let t=[...e].sort((e,t)=>e-t),n=t.length>>1;return t.length%2?t[n]:(t[n-1]+t[n])/2}function o(e,t,n){return t>=e&&t>=n?1:n>=e?2:0}function s(e,t,n,s=4){let c=[],l=Math.max(1,Math.floor((t+n)/400)),u=(n,r)=>{let i=4*(r*t+n);c.push([e[i],e[i+1],e[i+2]])};for(let e=0;e>1,t>>1);e++){for(let r=0;ra(c.map(t=>t[e]))),[f,p,m,h]=r(d[0],d[1],d[2]),g=a(c.map(e=>Math.abs(i(e[0],e[1],e[2],f,p,m,h))));return{r:d[0],g:d[1],b:d[2],channel:o(d[0],d[1],d[2]),spread:g}}function c(e,t,n=.1){if(!e||e.channel!==t.channel)return t;let r=(e,t)=>e+(t-e)*n;return{r:r(e.r,t.r),g:r(e.g,t.g),b:r(e.b,t.b),channel:e.channel,spread:r(e.spread,t.spread)}}function l(t,n=e){let r=Math.min(.45,Math.max(n.black,3*t.spread));return[r,Math.max(n.white,r+.2)]}const u=e=>e<=0?0:e>=1?1:e;function d(e,t){for(let n=1;n=0&&e[r]>t;)e[r+1]=e[r],r--;e[r+1]=t}return e[t-1>>1]}function f(t,n,o,s,c=e){let u=t.length;if(u<8)return null;let[f,p]=l(s,c),m=f+.5*(p-f),[h,g,_,v]=r(s.r,s.g,s.b),y=new Uint8Array(3*n*o),b=new Uint8Array(n*o),x=new Float32Array(4*n*o),S=[new Uint8Array(u),new Uint8Array(u),new Uint8Array(u)],C=[new Uint8Array(u),new Uint8Array(u),new Uint8Array(u)],w=new Uint16Array(u),T=[],E=Math.max(1,Math.floor(n*o/4e3));for(let e=0;e=Math.min(3,u)?S:C,o=a===S?n:u;a===C&&(b[e]=1);let s=d(a[0],o),c=d(a[1],o),l=d(a[2],o);y[3*e]=s,y[3*e+1]=c,y[3*e+2]=l;let f=r(s,c,l);if(x[4*e]=f[0],x[4*e+1]=f[1],x[4*e+2]=f[2],x[4*e+3]=Math.max(f[3],.5*v),!b[e]&&e%E===0)for(let r=0;re-t);let D=T.length?T[Math.floor(.995*(T.length-1))]:0;return{width:n,height:o,rgb:y,still:b,chroma:x,spread:Math.max(a(T),D/3),key:s}}function p(n,a,o,s,c=e,d=null){let f=new Float32Array(a*o),[p,m,h,g]=r(s.r,s.g,s.b);if(!d){let[e,t]=l(s,c),r=t-e;for(let t=0,s=0;t1.4)&&(c+=1);let v=u((c-.06)/.1),b=u((i(a,o,s,p,m,h,g)-_)/S);f[e]=Math.min(v,b)}return f}function m(e,t,n,r){return r.channel===1?[e,Math.min(t,Math.max(e,n)),n]:r.channel===2?[e,t,Math.min(n,Math.max(e,t))]:[Math.min(e,Math.max(t,n)),t,n]}function h(e,t,n,r,i,a,o){if(r>=1)return[e,t,n];let s=Math.max(r,.3),c=(e,t)=>{let n=(e-(1-s)*t)/s;return n<=0?0:n>=255?255:Math.round(n)};return[c(e,i),c(t,a),c(n,o)]}function g(e,t,n){let r=t*n,i=new Int32Array(r).fill(-1),a=[],o=[];for(let s=0;s=n))for(let n=-1;n<=1;n++){let a=s+n;if(a<0||a>=t)continue;let l=c*t+a;i[l]===-1&&e[l]>=.5&&(i[l]=r,o.push(l))}}}a.push(c)}let s=new Float32Array(r);if(!a.length)return s;let c=Math.max(Math.max(...a)*.015,2e-4*r),l=a.map(e=>e>=c),u=new Uint8Array(r);for(let e=0;e=0&&l[i[e]]&&(u[e]=1);let d=new Uint8Array(r);for(let e=0;e=0;r--)u[e*t+r]&&(n=r),n-r<=3&&(d[e*t+r]=1)}let f=new Uint8Array(r);for(let e=0;e=0;i--)d[i*t+e]&&(r=i),r-i<=3&&(f[i*t+e]=1)}for(let t=0;t=.5?u[t]:f[t])&&(s[t]=n)}return s}var _=class extends Error{};function v(e,t,n,r){if(n===t)return 0;let i=Math.floor((e-t)/(n-t)*r+.5);return i<0?0:i>r?r:i}function y(e){let t=e.times.length;if(e.positions.length!==3*t||e.colors.length!==3*t)throw new _(`positions and colors must have 3 values per point`);if(e.trackIds&&e.trackIds.length!==t)throw new _(`trackIds must have 1 value per point`);if(e.observed&&e.observed.length!==t)throw new _(`observed must have 1 value per point`);if(e.rawPositions&&e.rawPositions.length!==3*t)throw new _(`rawPositions must have 3 values per point`);let n=1/0,r=-1/0;for(let i=0;ir&&(r=t)}let i=e.time??{start:t?n:0,end:t?r:0},a=e.bounds;if(!a){let n=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];for(let i of e.rawPositions?[e.positions,e.rawPositions]:[e.positions])for(let e=0;er[t]&&(r[t]=a)}a=t?{min:n,max:r}:{min:[0,0,0],max:[0,0,0]}}let o=null;for(let n=1;nt);n.sort((t,n)=>e.times[t]-e.times[n]||t-n),o=Uint32Array.from(n);break}let s=e=>o?o[e]:e,c=new Uint16Array(3*t),l=new Uint16Array(t),u=new Uint8Array(3*t),d=e.trackIds?new Uint32Array(t):void 0,f=e.observed?new Uint8Array(t):void 0,p=e.rawPositions?new Uint16Array(3*t):void 0;for(let n=0;n0?e.fps:0,h=0,g;if(m>0&&t>0){let n=t=>Math.round((e.times[s(t)]-i.start)*m);h=n(t-1)+1,g=new Uint32Array(h+1);let r=0;for(let e=0;e=.5?1e9:0;let i=Math.SQRT2;for(let e=0;e0&&(s=Math.min(s,r[o-1]+1)),e>0&&(s=Math.min(s,r[o-t]+1),a>0&&(s=Math.min(s,r[o-t-1]+i)),a=0;e--)for(let o=t-1;o>=0;o--){let s=e*t+o;if(r[s]===0)continue;let c=r[s];o0&&(c=Math.min(c,r[s+t-1]+i))),r[s]=c,c>a&&(a=c)}if(a>0)for(let e=0;e=.85&&(s[e]=1,c.push(a[e]));let l=new Float32Array(o),u=new Uint8Array(o);if(c.length<20)return{data:l,width:r,height:i,known:u};let d=Math.max(S(c,.9)-S(c,.1),1e-6),f=E(a,s,r,i,d,4);for(let e=0;e0&&Math.abs(a[n-1]-o)>p||tp||e>0&&Math.abs(a[n-r]-o)>p||ep||(u[n]=1,l[n]=o)}for(let e=0;e0&&u[o-1]&&(s+=l[o-1],c++),a0&&u[o-r]&&(s+=l[o-r],c++),n0&&Math.abs(a[o-1]-s)>p||np||e>0&&Math.abs(a[o-r]-s)>p||ep||(u[o]=1,l[o]=s)}return{data:l,width:r,height:i,known:u}}const ee={heightM:1.75,hfov:66,relief:.3,pointsPerFrame:2e4,spill:`all`},te=1.5;var ne=class{o;u;v;d;rgb;alpha;back;n=0;frames;constructor(e){this.o=e;let t=e.frameCount*e.pointsPerFrame;this.u=new Float32Array(t),this.v=new Float32Array(t),this.d=new Float32Array(t),this.rgb=new Uint8Array(3*t),this.alpha=new Uint8Array(t),this.back=new Uint8Array(3*t),this.frames=Array(e.frameCount).fill(null)}get pointCount(){return this.n}addFrame(e,t){if(e<0||e>=this.o.frameCount||this.frames[e])return;let n=Math.min(t.depth.length,this.o.pointsPerFrame);if(n===0)return;let r=this.n;for(let e=0;e!!e);if(!n.length)throw Error(`no subject found: the key removed every pixel`);let r=Math.max(1,Math.min(t.pointsPerFrame,Math.round(e.pointsPerFrame))),i=S(n.map(e=>e.area),.75),a=(t.smoothSeconds??.12)*t.fps,o=C(this.frames.map(e=>e?.median??NaN),a),s=C(this.frames.map(e=>e?.spread??NaN),a),c=n.filter(e=>e.area>=.6*i),l=S((c.length?c:n).map(e=>e.heightPx),.5),u=t.width/2/Math.tan(e.hfov/2*Math.PI/180),d=e.heightM*u/Math.max(l,1),f=0,p=this.frames.map(e=>{let t=e?Math.max(1,Math.round(Math.min(e.count,r)*Math.min(1,e.area/i))):0;return f+=t,t}),g=new Float32Array(3*f),_=new Float32Array(f),v=new Uint8Array(3*f),b=t.width/2,x=t.height/2,w=[],T=[],E={channel:t.channel},D=0;this.frames.forEach((n,r)=>{if(!n)return;let i=r/t.fps,a=o[r],c=s[r],l=0;for(let t=n.start;tte?te:n;let r=d-e.relief*n;g[3*D]=(this.u[t]-b)/u*r,g[3*D+1]=-(this.v[t]-x)/u*r,g[3*D+2]=-r,l+=g[3*D],_[D]=i;let o=this.rgb[3*t],s=this.rgb[3*t+1],f=this.rgb[3*t+2],p=e.spill===`edges`?h(o,s,f,this.alpha[t]/255,this.back[3*t],this.back[3*t+1],this.back[3*t+2]):m(o,s,f,E);v[3*D]=p[0],v[3*D+1]=p[1],v[3*D+2]=p[2]}w.push(l/p[r]),T.push(i)});let ne=Math.max(1,Math.floor(f/2e5)),O=e=>Array.from({length:Math.ceil(f/ne)},(t,n)=>g[3*n*ne+e]),ae=[S(O(0),.5),S(O(1),.005),S(O(2),.5)];for(let e=0;ee+t,0)/n,i=t.reduce((e,t)=>e+t,0)/n,a=0,o=0;for(let s=0;s0?a/o:0}const ie=e=>Math.round(e*1e3)/1e3;var O=Object.defineProperty,ae=(e,t)=>{let n={};for(var r in e)O(n,r,{get:e[r],enumerable:!0});return t||O(n,Symbol.toStringTag,{value:`Module`}),n};const oe=2**32,k=2**32-1;var A=class e extends ArrayBuffer{constructor(e){super(e),this.fileStart=0,this.usedBytes=0}static fromArrayBuffer(t,n){let r=new e(t.byteLength);return new Uint8Array(r).set(new Uint8Array(t)),r.fileStart=n,r}};let se=/* @__PURE__ */ function(e){return e[e.BIG_ENDIAN=1]=`BIG_ENDIAN`,e[e.LITTLE_ENDIAN=2]=`LITTLE_ENDIAN`,e}({});var j=class e{static{this.ENDIANNESS=new Int8Array(new Int16Array([1]).buffer)[0]>0?2:1}constructor(e,t,n){this._byteLength=0,this.failurePosition=0,this._dynamicSize=1,this._byteOffset=t||0,e instanceof ArrayBuffer?this.buffer=A.fromArrayBuffer(e,0):e instanceof DataView?(this.dataView=e,t&&(this._byteOffset+=t)):this.buffer=new A(e||0),this.position=0,this.endianness=n||1}getPosition(){return this.position}_realloc(e){if(!this._dynamicSize)return;let t=this._byteOffset+this.position+e,n=this._buffer.byteLength;if(t<=n){t>this._byteLength&&(this._byteLength=t);return}for(n<1&&(n=1);t>n;)n*=2;let r=new A(n),i=new Uint8Array(this._buffer);new Uint8Array(r,0,i.length).set(i),this.buffer=r,this._byteLength=t}_trimAlloc(){if(this._byteLength===this._buffer.byteLength)return;let e=new A(this._byteLength),t=new Uint8Array(e),n=new Uint8Array(this._buffer,0,t.length);t.set(n),this.buffer=e}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){return this._trimAlloc(),this._buffer}set buffer(e){this._buffer=e,this._dataView=new DataView(e,this._byteOffset),this._byteLength=e.byteLength}get byteOffset(){return this._byteOffset}set byteOffset(e){this._byteOffset=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get dataView(){return this._dataView}set dataView(e){this._byteOffset=e.byteOffset,this._buffer=A.fromArrayBuffer(e.buffer,0),this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+e.byteLength}seek(e){let t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t}isEof(){return this.position>=this._byteLength}#e(e){return Array.isArray(e)&&e.length===3&&e[0]===`[]`}mapUint8Array(e){this._realloc(e*1);let t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e*1,t}readInt32Array(t,n){t=t===void 0?this.byteLength-this.position/4:t;let r=new Int32Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readInt16Array(t,n){t=t===void 0?this.byteLength-this.position/2:t;let r=new Int16Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readInt8Array(t){t=t===void 0?this.byteLength-this.position:t;let n=new Int8Array(t);return e.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,t*n.BYTES_PER_ELEMENT),this.position+=n.byteLength,n}readUint32Array(t,n){t=t===void 0?this.byteLength-this.position/4:t;let r=new Uint32Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readUint16Array(t,n){t=t===void 0?this.byteLength-this.position/2:t;let r=new Uint16Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readUint8Array(t){t=t===void 0?this.byteLength-this.position:t;let n=new Uint8Array(t);return e.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,t*n.BYTES_PER_ELEMENT),this.position+=n.byteLength,n}readFloat64Array(t,n){t=t===void 0?this.byteLength-this.position/8:t;let r=new Float64Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readFloat32Array(t,n){t=t===void 0?this.byteLength-this.position/4:t;let r=new Float32Array(t);return e.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),e.arrayToNative(r,n??this.endianness),this.position+=r.byteLength,r}readInt32(e){let t=this._dataView.getInt32(this.position,(e??this.endianness)===2);return this.position+=4,t}readInt16(e){let t=this._dataView.getInt16(this.position,(e??this.endianness)===2);return this.position+=2,t}readInt8(){let e=this._dataView.getInt8(this.position);return this.position+=1,e}readUint32(e){let t=this._dataView.getUint32(this.position,(e??this.endianness)===2);return this.position+=4,t}readUint16(e){let t=this._dataView.getUint16(this.position,(e??this.endianness)===2);return this.position+=2,t}readUint8(){let e=this._dataView.getUint8(this.position);return this.position+=1,e}readFloat32(e){let t=this._dataView.getFloat32(this.position,(e??this.endianness)===2);return this.position+=4,t}readFloat64(e){let t=this._dataView.getFloat64(this.position,(e??this.endianness)===2);return this.position+=8,t}static memcpy(e,t,n,r,i){let a=new Uint8Array(e,t,i),o=new Uint8Array(n,r,i);a.set(o)}static arrayToNative(t,n){return n===e.ENDIANNESS?t:this.flipArrayEndianness(t)}static nativeToEndian(t,n){return n&&e.ENDIANNESS===2?t:this.flipArrayEndianness(t)}static flipArrayEndianness(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);for(let n=0;ni;r--,i++){let e=t[i];t[i]=t[r],t[r]=e}return e}readString(e,t){return t===void 0||t===`ASCII`?ce(this.mapUint8Array(e===void 0?this.byteLength-this.position:e)):new TextDecoder(t).decode(this.mapUint8Array(e))}readCString(e){let t=0,n=this.byteLength-this.position,r=new Uint8Array(this._buffer,this._byteOffset+this.position),i=e===void 0?n:Math.min(e,n);for(;t>16),this.writeUint8((e&65280)>>8),this.writeUint8(e&255)}adjustUint32(e,t){let n=this.position;this.seek(e),this.writeUint32(t),this.seek(n)}readStruct(e){let t={},n=this.position;for(let r=0;r=M&&console.debug(`[`+N.getDurationString((/* @__PURE__ */ new Date()).getTime()-le.getTime(),1e3)+`]`,`[`+e+`]`,t)},log(e,t){this.debug(e.msg)},info(e,t){2>=M&&console.info(`[`+N.getDurationString((/* @__PURE__ */ new Date()).getTime()-le.getTime(),1e3)+`]`,`[`+e+`]`,t)},warn(e,t){3>=M&&console.warn(`[`+N.getDurationString((/* @__PURE__ */ new Date()).getTime()-le.getTime(),1e3)+`]`,`[`+e+`]`,t)},error(e,t,n){n?.onError?n.onError(e,t):4>=M&&console.error(`[`+N.getDurationString((/* @__PURE__ */ new Date()).getTime()-le.getTime(),1e3)+`]`,`[`+e+`]`,t)},getDurationString(e,t){let n;function r(e,t){let n=(``+e).split(`.`);for(;n[0].length0){let n=``;for(let r=0;r0&&(n+=`,`),n+=`[`+N.getDurationString(e.start(r))+`,`+N.getDurationString(e.end(r))+`]`;return n}return`(empty)`}};function ue(e,t){N.debug(`ArrayBuffer`,`Trying to create a new buffer of size: `+(e.byteLength+t.byteLength));let n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}var de=class extends j{constructor(e){super(/* @__PURE__ */ new ArrayBuffer,0),this.buffers=[],this.bufferIndex=-1,e&&(this.insertBuffer(e),this.bufferIndex=0)}initialized(){if(this.bufferIndex>-1)return!0;if(this.buffers.length>0){let e=this.buffers[0];return e.fileStart===0?(this.buffer=e,this.bufferIndex=0,N.debug(`MultiBufferStream`,`Stream ready for parsing`),!0):(N.warn(`MultiBufferStream`,`The first buffer should have a fileStart of 0`),this.logBufferLevel(),!1)}return N.warn(`MultiBufferStream`,`No buffer to start parsing from`),this.logBufferLevel(),!1}reduceBuffer(e,t,n){let r=new Uint8Array(n);return r.set(new Uint8Array(e,t,n)),r.buffer.fileStart=e.fileStart+t,r.buffer.usedBytes=0,r.buffer}insertBuffer(e){let t=!0,n=0;for(;nr.byteLength){this.buffers.splice(n,1),n--;continue}N.warn(`MultiBufferStream`,`Buffer (fileStart: `+e.fileStart+` - Length: `+e.byteLength+`) already appended, ignoring`)}else e.fileStart+e.byteLength<=r.fileStart||(e=this.reduceBuffer(e,0,r.fileStart-e.fileStart)),N.debug(`MultiBufferStream`,`Appending new buffer (fileStart: `+e.fileStart+` - Length: `+e.byteLength+`)`),this.buffers.splice(n,0,e),n===0&&(this.buffer=e);t=!1;break}if(e.fileStart0)e=this.reduceBuffer(e,n,i);else{t=!1;break}}}t&&(N.debug(`MultiBufferStream`,`Appending new buffer (fileStart: `+e.fileStart+` - Length: `+e.byteLength+`)`),this.buffers.push(e),n===0&&(this.buffer=e))}logBufferLevel(e){let t=[],n=``,r,i=0,a=0;for(let e=0;e0&&(n+=r.end-1+`]`);let o=e?N.info:N.debug;this.buffers.length===0?o(`MultiBufferStream`,`No more buffer in memory`):o(`MultiBufferStream`,``+this.buffers.length+` stored buffer(s) (`+i+`/`+a+` bytes), continuous ranges: `+n)}cleanBuffers(){for(let e=0;e`+this.buffer.byteLength+`)`),!0}return!1}return!1}findPosition(e,t,n){let r=-1,i=e===!0?0:this.bufferIndex;for(;i=t?(N.debug(`MultiBufferStream`,`Found position in existing buffer #`+r),r):-1}findEndContiguousBuf(e){let t=e===void 0?this.bufferIndex:e,n=this.buffers[t];if(this.buffers.length>t+1)for(let e=t+1;ek||this.original_size===1)&&(this.size+=8),this.type===`uuid`&&(this.size+=16),N.debug(`BoxWriter`,`Writing box `+this.type+` of size: `+this.size+` at position `+e.getPosition()+(t||``)),this.original_size===0?e.writeUint32(0):this.size>k||this.original_size===1?e.writeUint32(1):(this.sizePosition=e.getPosition(),e.writeUint32(this.size)),e.writeString(this.type,void 0,4),this.type===`uuid`){let t=/* @__PURE__ */ new Uint8Array(16);for(let e=0;e<16;e++)t[e]=parseInt(this.uuid.substring(e*2,e*2+2),16);e.writeUint8Array(t)}(this.size>k||this.original_size===1)&&(this.sizePosition=e.getPosition(),e.writeUint64(this.size))}write(e){if(this.type===`mdat`){let t=this;if(t.stream){this.size=t.stream.getAbsoluteEndPosition(),this.writeHeader(e);for(let n of t.stream.buffers){let t=new Uint8Array(n);e.writeUint8Array(t)}}else t.data&&(this.size=t.data.length,this.writeHeader(e),e.writeUint8Array(t.data))}else this.size=this.data?this.data.length:0,this.writeHeader(e),this.data&&e.writeUint8Array(this.data)}printHeader(e){this.size+=8,this.size>k&&(this.size+=8),this.type===`uuid`&&(this.size+=16),e.log(e.indent+`size:`+this.size),e.log(e.indent+`type:`+this.type)}print(e){this.printHeader(e)}parse(e){this.type===`mdat`?this.size===0?e.seek(e.getEndPosition()):e.seek(this.start+this.size):this.data=e.readUint8Array(this.size-this.hdr_size)}parseDataAndRewind(e){this.data=e.readUint8Array(this.size-this.hdr_size),e.seek(this.start+this.hdr_size)}parseLanguage(e){this.language=e.readUint16();let t=[];t[0]=this.language>>10&31,t[1]=this.language>>5&31,t[2]=this.language&31,this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96)}computeSize(e){let t=e||new de;this.write(t)}isEndOfBox(e){return e.getPosition()===this.start+this.size}},F=class extends P{constructor(...e){super(...e),this.flags=0,this.version=0}writeHeader(e){this.size+=4,super.writeHeader(e,` v=`+this.version+` f=`+this.flags),e.writeUint8(this.version),e.writeUint24(this.flags)}printHeader(e){this.size+=4,super.printHeader(e),e.log(e.indent+`version:`+this.version),e.log(e.indent+`flags:`+this.flags)}parseDataAndRewind(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,e.seek(this.start+this.hdr_size)}parseFullHeader(e){this.version=e.readUint8(),this.flags=e.readUint24(),this.hdr_size+=4}parse(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)}},I=class{static{this.registryId=Symbol.for(`SampleGroupEntryIdentifier`)}constructor(e){this.grouping_type=e}write(e){e.writeUint8Array(this.data)}parse(e){N.warn(`BoxParser`,`Unknown sample group type: '${this.grouping_type}'`),this.data=e.readUint8Array(this.description_length)}},fe=class extends F{parse(e){this.parseFullHeader(e),this.track_group_id=e.readUint32()}},pe=class extends P{constructor(e,t,n,r,i){super(t),this.box_name=n,this.hdr_size=r,this.start=i,this.type=e}parse(e){this.from_item_ID=e.readUint16();let t=e.readUint16();this.references=[];for(let n=0;ne===n))continue;else if(e[n]instanceof P||t[n]instanceof P)continue;else if(e[n]===void 0||t[n]===void 0)continue;else if(typeof e[n]==`function`||typeof t[n]==`function`)continue;else if(`subBoxNames`in e&&e.subBoxNames.indexOf(n.slice(0,4))>-1||`subBoxNames`in t&&t.subBoxNames.indexOf(n.slice(0,4))>-1)continue;else if(n===`data`||n===`start`||n===`size`||n===`creation_time`||n===`modification_time`)continue;else if(_e.find(e=>e===n))continue;else if(e[n]!==t[n])return!1;return!0}function ye(e,t){if(!ve(e,t))return!1;for(let n=0;n{let t=Symbol.for(`SampleGroupEntryIdentifier`);return be(e)===t},Se=e=>{let t=Symbol.for(`SampleEntryIdentifier`);return be(e)===t},Ce=e=>{let t=Symbol.for(`BoxIdentifier`);return be(e)===t},L={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};function we(e){let t={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};for(let[n,r]of Object.entries(e))if(xe(r)){let e=`grouping_type`in r?r.grouping_type:void 0;if(!e)throw Error(`SampleGroupEntry class ${n} does not have a valid static grouping_type. Please ensure it is defined correctly.`);if(e in t.sampleGroupEntry)throw Error(`SampleGroupEntry class ${n} has a grouping_type that is already registered. Please ensure it is unique.`);t.sampleGroupEntry[e]=r}else if(Se(r)){let e=`fourcc`in r?r.fourcc:void 0;if(!e)throw Error(`SampleEntry class ${n} does not have a valid static fourcc. Please ensure it is defined correctly.`);if(e in t.sampleEntry)throw Error(`SampleEntry class ${n} has a fourcc that is already registered. Please ensure it is unique.`);t.sampleEntry[e]=r}else if(Ce(r)){let e=`fourcc`in r?r.fourcc:void 0,i=`uuid`in r?r.uuid:void 0;if(e===`uuid`){if(!i)throw Error(`Box class ${n} has a fourcc of 'uuid' but does not have a valid uuid. Please ensure it is defined correctly.`);if(i in t.uuid)throw Error(`Box class ${n} has a uuid that is already registered. Please ensure it is unique.`);t.uuid[i]=r;continue}t.box[e]=r}else throw Error(`Box class ${n} does not have a valid static fourcc, uuid, or grouping_type. Please ensure it is defined correctly.`);return L.uuid={...t.uuid},L.sampleEntry={...t.sampleEntry},L.sampleGroupEntry={...t.sampleGroupEntry},L.box={...t.box},L}const Te={};function Ee(e){return Object.entries(e).forEach(([e,t])=>Te[e]=t),Te}function De(e){return R(e)}function R(e){let t=``;for(let n=0;n<16;n++){let n=e.readUint8().toString(16);t+=n.length===1?`0`+n:n}return t}function z(e,t,n){let r,i,a=e.getPosition(),o=0,s;if(e.getEndPosition()-a<8)return N.debug(`BoxParser`,`Not enough data in stream to parse the type and size of the box`),{code:0};if(n&&n<8)return N.debug(`BoxParser`,`Not enough bytes left in the parent box to parse a new box`),{code:0};let c=e.readUint32(),l=e.readString(4);if(l.length!==4||!/^[\x20-\x7E]{4}$/.test(l))return N.error(`BoxParser`,`Invalid box type: '${l}'`),{code:-1,start:a,type:l};let u=l;if(N.debug(`BoxParser`,`Found box of type '`+l+`' and size `+c+` at position `+a),o=8,l===`uuid`){if(e.getEndPosition()-e.getPosition()<16||n-o<16)return e.seek(a),N.debug(`BoxParser`,`Not enough bytes left in the parent box to parse a UUID box`),{code:0};s=De(e),o+=16,u=s}if(c===1){if(e.getEndPosition()-e.getPosition()<8||n&&n-o<8)return e.seek(a),N.warn(`BoxParser`,`Not enough data in stream to parse the extended size of the "`+l+`" box`),{code:0};i=c,c=e.readUint64(),o+=8}else if(c===0){if(n)c=n;else if(l!==`mdat`)return N.error(`BoxParser`,`Unlimited box size not supported for type: '`+l+`'`),r=new P(c),r.type=l,{code:1,box:r,size:r.size};else c=e.getEndPosition()-a}if(c!==0&&cn)return N.error(`BoxParser`,`Box of type '`+l+`' has a size `+c+` greater than its container size `+n),{code:0,type:l,size:c,hdr_size:o,start:a};if(c!==0&&a+c>e.getEndPosition())return e.seek(a),N.info(`BoxParser`,`Not enough data in stream to parse the entire '`+l+`' box`),{code:0,type:l,size:c,hdr_size:o,start:a,original_size:i};if(t)return{code:1,type:l,size:c,hdr_size:o,start:a};l in L.box?r=new L.box[l](c):l===`uuid`?s in L.uuid?r=new L.uuid[s](c):(N.warn(`BoxParser`,`Unknown UUID box type: '${s}'`),r=new P(c),r.type=l,r.uuid=s,r.has_unparsed_data=!0):(N.warn(`BoxParser`,`Unknown box type: '${l}'`),r=new P(c),r.type=l,r.has_unparsed_data=!0),r.original_size=i,r.hdr_size=o,r.start=a,r.write===P.prototype.write&&r.type!==`mdat`&&(N.info(`BoxParser`,`'`+u+`' box writing not yet implemented, keeping unparsed data in memory for later write`),r.parseDataAndRewind(e)),r.parse(e);let d=e.getPosition()-(r.start+r.size);return d<0?(N.warn(`BoxParser`,`Parsing of box '`+u+`' did not read the entire indicated box data size (missing `+-d+` bytes), seeking forward`),e.seek(r.start+r.size)):d>0&&r.size!==0&&(N.error(`BoxParser`,`Parsing of box '`+u+`' read `+d+` more bytes than the indicated box data size, seeking backwards`),e.seek(r.start+r.size)),{code:1,box:r,size:r.size}}var B=class extends P{write(e){if(this.size=0,this.writeHeader(e),this.boxes)for(let t=0;t`;e+=`lengthnalu_data`,e+=``;for(let t=0;t`,e+=``+n.length+``,e+=``,e+=n.data.reduce(function(e,t){return e+t.toString(16).padStart(2,`0`)},`0x`),e+=``}return e+=``,e}},Me=class extends P{constructor(...e){super(...e),this.box_name=`AVCConfigurationBox`}static{this.fourcc=`avcC`}parse(e){this.configurationVersion=e.readUint8(),this.AVCProfileIndication=e.readUint8(),this.profile_compatibility=e.readUint8(),this.AVCLevelIndication=e.readUint8(),this.lengthSizeMinusOne=e.readUint8()&3,this.nb_SPS_nalus=e.readUint8()&31;let t=this.size-this.hdr_size-6;this.SPS=new je;for(let n=0;n0&&(this.ext=e.readUint8Array(t))}write(e){this.size=7;for(let e=0;e>24,this.minor_version>>16&255,this.minor_version>>8&255,this.minor_version&255);n.match(`[a-zA-Z0-9]{4}`)&&(this.minor_version=n),t-=8,this.compatible_brands=[];let r=0;for(;t>=4;)this.compatible_brands[r]=e.readString(4),t-=4,r++}write(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,void 0,4),typeof this.minor_version==`number`?e.writeUint32(this.minor_version):e.writeString(this.minor_version,void 0,4);for(let t=0;t1&&(N.info(`BoxParser`,`Warning: hdlr name is not null-terminated, possibly length-prefixed string. Trimming first byte.`),this.name=this.name.slice(1))}}write(e){this.size=20+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(e),e.writeUint32(0),e.writeString(this.handler,void 0,4),e.writeUint32Array([0,0,0]),e.writeCString(this.name)}},xt=class extends P{constructor(...e){super(...e),this.box_name=`HEVCConfigurationBox`}static{this.fourcc=`hvcC`}parse(e){this.configurationVersion=e.readUint8();let t=e.readUint8();this.general_profile_space=t>>6,this.general_tier_flag=(t&32)>>5,this.general_profile_idc=t&31,this.general_profile_compatibility=e.readUint32(),this.general_constraint_indicator=e.readUint8Array(6),this.general_level_idc=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,this.chroma_format_idc=e.readUint8()&3,this.bit_depth_luma_minus8=e.readUint8()&7,this.bit_depth_chroma_minus8=e.readUint8()&7,this.avgFrameRate=e.readUint16(),t=e.readUint8(),this.constantFrameRate=t>>6,this.numTemporalLayers=(t&13)>>3,this.temporalIdNested=(t&4)>>2,this.lengthSizeMinusOne=t&3,this.nalu_arrays=[];let n=e.readUint8();for(let r=0;r>7,n.nalu_type=t&63;let r=e.readUint16();for(let t=0;tk||this.creation_time>k||this.duration>k||this.version===1;this.version=+!!t,this.size=20,this.size+=t?12:0,this.flags=0,this.writeHeader(e),t?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.timescale),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration)),e.writeUint16(this.language),e.writeUint16(0)}},Ct=class extends F{constructor(...e){super(...e),this.box_name=`MovieExtendsHeaderBox`}static{this.fourcc=`mehd`}parse(e){this.parseFullHeader(e),this.flags&1&&(N.warn(`BoxParser`,`mehd box incorrectly uses flags set to 1, converting version to 1`),this.version=1),this.fragment_duration=this.version===1?e.readUint64():e.readUint32()}write(e){let t=this.fragment_duration>k||this.version===1;this.version=+!!t,this.size=4,this.size+=t?4:0,this.flags=0,this.writeHeader(e),t?e.writeUint64(this.fragment_duration):e.writeUint32(this.fragment_duration)}},wt=class extends F{constructor(...e){super(...e),this.box_name=`ItemInfoEntry`}static{this.fourcc=`infe`}parse(e){this.parseFullHeader(e),(this.version===0||this.version===1)&&(this.item_ID=e.readUint16(),this.item_protection_index=e.readUint16(),this.item_name=e.readCString(),this.content_type=e.readCString(),this.isEndOfBox(e)||(this.content_encoding=e.readCString())),this.version===1?(this.extension_type=e.readString(4),N.warn(`BoxParser`,`Cannot parse extension type`),e.seek(this.start+this.size)):this.version>=2&&(this.version===2?this.item_ID=e.readUint16():this.version===3&&(this.item_ID=e.readUint32()),this.item_protection_index=e.readUint16(),this.item_type=e.readString(4),this.item_name=e.readCString(),this.item_type===`mime`?(this.content_type=e.readCString(),this.content_encoding=e.readCString()):this.item_type===`uri `&&(this.item_uri_type=e.readCString()))}},Tt=class extends F{constructor(...e){super(...e),this.box_name=`ItemInfoBox`}static{this.fourcc=`iinf`}parse(e){this.parseFullHeader(e),this.entry_count=this.version===0?e.readUint16():e.readUint32(),this.item_infos=[];for(let t=0;t>4&15,this.length_size=t&15,t=e.readUint8(),this.base_offset_size=t>>4&15,this.index_size=this.version===1||this.version===2?t&15:0,this.items=[];let n=0;if(this.version<2)n=e.readUint16();else if(this.version===2)n=e.readUint32();else throw Error(`version of iloc box not supported`);for(let t=0;t8){switch(e.readUint32(),e.readString(4)){case`hdlr`:case`mhdr`:case`keys`:case`ilst`:case`ctry`:case`lang`:this.isQT=!0}e.seek(t)}this.isQT||this.parseFullHeader(e),B.prototype.parse.call(this,e)}},jt=class extends F{constructor(...e){super(...e),this.box_name=`MovieFragmentHeaderBox`}static{this.fourcc=`mfhd`}parse(e){this.parseFullHeader(e),this.sequence_number=e.readUint32()}write(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.sequence_number)}},Mt=class extends F{constructor(...e){super(...e),this.box_name=`MovieHeaderBox`}static{this.fourcc=`mvhd`}parse(e){this.parseFullHeader(e),this.version===1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.rate=e.readUint32(),this.volume=e.readUint16()>>8,e.readUint16(),e.readUint32Array(2),this.matrix=e.readInt32Array(9),e.readUint32Array(6),this.next_track_id=e.readUint32()}write(e){let t=this.modification_time>k||this.creation_time>k||this.duration>k||this.version===1;this.version=+!!t,this.size=96,this.size+=t?12:0,this.flags=0,this.writeHeader(e),t?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.timescale),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration)),e.writeUint32(this.rate),e.writeUint16(this.volume<<8),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeInt32Array(this.matrix),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(this.next_track_id)}print(e){super.printHeader(e),e.log(e.indent+`creation_time: `+this.creation_time),e.log(e.indent+`modification_time: `+this.modification_time),e.log(e.indent+`timescale: `+this.timescale),e.log(e.indent+`duration: `+this.duration),e.log(e.indent+`rate: `+this.rate),e.log(e.indent+`volume: `+(this.volume>>8)),e.log(e.indent+`matrix: `+this.matrix.join(`, `)),e.log(e.indent+`next_track_id: `+this.next_track_id)}},Nt=class extends H{static{this.fourcc=`mett`}parse(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}},Pt=class extends H{static{this.fourcc=`metx`}parse(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.parseFooter(e)}},Ft=class extends P{constructor(...e){super(...e),this.box_name=`AV1CodecConfigurationBox`}static{this.fourcc=`av1C`}parse(e){let t=e.readUint8();if((t>>7&1)!=1){N.error(`BoxParser`,`av1C marker problem`,e.isofile);return}if(this.version=t&127,this.version!==1){N.error(`BoxParser`,`av1C version `+this.version+` not supported`,e.isofile);return}if(t=e.readUint8(),this.seq_profile=t>>5&7,this.seq_level_idx_0=t&31,t=e.readUint8(),this.seq_tier_0=t>>7&1,this.high_bitdepth=t>>6&1,this.twelve_bit=t>>5&1,this.monochrome=t>>4&1,this.chroma_subsampling_x=t>>3&1,this.chroma_subsampling_y=t>>2&1,this.chroma_sample_position=t&3,t=e.readUint8(),this.reserved_1=t>>5&7,this.reserved_1!==0){N.error(`BoxParser`,`av1C reserved_1 parsing problem`,e.isofile);return}if(this.initial_presentation_delay_present=t>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=t&15;else if(this.reserved_2=t&15,this.reserved_2!==0){N.error(`BoxParser`,`av1C reserved_2 parsing problem`,e.isofile);return}let n=this.size-this.hdr_size-4;this.configOBUs=e.readUint8Array(n)}},It=class extends F{constructor(...e){super(...e),this.box_name=`ElementaryStreamDescriptorBox`}static{this.fourcc=`esds`}parse(e){this.parseFullHeader(e);let t=e.readUint8Array(this.size-this.hdr_size);if(`MPEG4DescriptorParser`in Te){let e=new Te.MPEG4DescriptorParser;this.esd=e.parseOneDescriptor(new j(t.buffer,0))}}},Lt=class extends B{constructor(...e){super(...e),this.box_name=`siDecompressionParamBox`}static{this.fourcc=`wave`}},Rt=class extends P{constructor(...e){super(...e),this.box_name=`LCEVCConfigurationBox`}static{this.fourcc=`lvcC`}parse(e){if(this.configurationVersion=e.readUint8(),this.configurationVersion!==1){N.error(`BoxParser`,`lvcC version `+this.configurationVersion+` not supported`,e.isofile);return}this.LCEVCProfileIndication=e.readUint8(),this.LCEVCLevelIndication=e.readUint8();let t=e.readUint8();this.chroma_format_idc=t>>6&3,this.bit_depth_luma_minus8=t>>3&7,this.bit_depth_chroma_minus8=t&7,t=e.readUint8(),this.lengthSizeMinusOne=t>>6&3;let n=t&63;if(n!==63||(this.pic_width_in_luma_samples=e.readUint32(),this.pic_height_in_luma_samples=e.readUint32(),t=e.readUint8(),this.sc_in_stream=t>>7&1,this.gc_in_stream=t>>6&1,this.ai_in_stream=t>>5&1,n=t&31,n!==31)){N.error(`BoxParser`,`lvcC reserved parsing problem`,e.isofile);return}this.nalu_arrays=[];let r=e.readUint8();for(let i=0;i>6&3,n!==0){N.error(`BoxParser`,`lvcC reserved parsing problem`,e.isofile);return}r.nalu_type=t&63;let i=e.readUint16();for(let t=0;t>4,this.chromaSubsampling=t>>1&7,this.videoFullRangeFlag=t&1,this.colourPrimaries=e.readUint8(),this.transferCharacteristics=e.readUint8(),this.matrixCoefficients=e.readUint8(),this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)}else{this.profile=e.readUint8(),this.level=e.readUint8();let t=e.readUint8();this.bitDepth=t>>4&15,this.colorSpace=t&15,t=e.readUint8(),this.chromaSubsampling=t>>4&15,this.transferFunction=t>>1&7,this.videoFullRangeFlag=t&1,this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)}}},Bt=class extends F{constructor(...e){super(...e),this.box_name=`VvcConfigurationBox`}static{this.fourcc=`vvcC`}parse(e){this.parseFullHeader(e);let t={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(e){this.held_bits=e.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(e){this.held_bits=e.readUint16(),this.num_held_bits=16},extract_bits:function(e){let t=this.held_bits>>this.num_held_bits-e&(1<1){t.stream_read_1_bytes(e),this.ptl_sublayer_present_mask=0;for(let e=this.num_sublayers-2;e>=0;--e){let n=t.extract_bits(1);this.ptl_sublayer_present_mask|=n<1;++e)t.extract_bits(1);this.sublayer_level_idc=[];for(let t=this.num_sublayers-2;t>=0;--t)this.ptl_sublayer_present_mask&1<>7}else(this.colour_type===`rICC`||this.colour_type===`prof`)&&(this.ICC_profile=e.readUint8Array(this.size-4))}};function K(e,t){let n=Number(e).toString(16);for(t=t===void 0?2:t;n.length>=1;e+=K(n,0),e+=`.`,this.hvcC.general_tier_flag===0?e+=`L`:e+=`H`,e+=this.hvcC.general_level_idc;let r=!1,i=``;for(let e=5;e>=0;e--)(this.hvcC.general_constraint_indicator[e]||r)&&(i=`.`+K(this.hvcC.general_constraint_indicator[e],0)+i,r=!0);e+=i}return e}},Xt=class extends Yt{constructor(...e){super(...e),this.box_name=`HEVCSampleEntry`}static{this.fourcc=`hvc1`}},Zt=class extends Yt{static{this.fourcc=`hvc2`}},Qt=class extends Yt{constructor(...e){super(...e),this.box_name=`HEVCSampleEntry`,this.colrs=[],this.subBoxNames=[`colr`]}static{this.fourcc=`hev1`}},$t=class extends Yt{static{this.fourcc=`hev2`}},en=class extends W{constructor(...e){super(...e),this.box_name=`HEVCTileSampleSampleEntry`}static{this.fourcc=`hvt1`}},tn=class extends W{constructor(...e){super(...e),this.box_name=`LHEVCSampleEntry`}static{this.fourcc=`lhe1`}},nn=class extends W{constructor(...e){super(...e),this.box_name=`LHEVCSampleEntry`}static{this.fourcc=`lhv1`}},rn=class extends W{constructor(...e){super(...e),this.box_name=`LCEVCSampleEntry`}static{this.fourcc=`lvc1`}getCodec(){let e=super.getCodec();return this.lvcC&&(e+=`.`,e+=`vprf`,e+=this.lvcC.LCEVCProfileIndication,e+=`.`,e+=`vlev`,e+=this.lvcC.LCEVCLevelIndication),e}},an=class extends W{static{this.fourcc=`dvh1`}},on=class extends W{static{this.fourcc=`dvhe`}},sn=class extends W{getCodec(){let e=super.getCodec();if(this.vvcC){e+=`.`+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?e+=`.H`:e+=`.L`,e+=this.vvcC.general_level_idc;let t=``;if(this.vvcC.general_constraint_info){let e=[],n=0;n|=this.vvcC.ptl_frame_only_constraint_flag<<7,n|=this.vvcC.ptl_multilayer_enabled_flag<<6;let r;for(let t=0;t>2&63,e.push(n),n&&(r=t),n=this.vvcC.general_constraint_info[t]>>2&3;if(r===void 0)t=`.CA`;else{t=`.C`;let n=`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`,i=0,a=0;for(let o=0;o<=r;++o)for(i=i<<8|e[o],a+=8;a>=5;){let e=i>>a-5&31;t+=n[e],a-=5,i&=(1<>6,this.sample_depends_on[n]=t>>4&3,this.sample_is_depended_on[n]=t>>2&3,this.sample_has_redundancy[n]=t&3}}},qn=class extends F{constructor(...e){super(...e),this.box_name=`SampleGroupDescriptionBox`}static{this.fourcc=`sgpd`}parse(e){this.parseFullHeader(e),this.grouping_type=e.readString(4),N.debug(`BoxParser`,`Found Sample Groups of type `+this.grouping_type),this.default_length=this.version===1?e.readUint32():0,this.version>=2&&(this.default_group_description_index=e.readUint32()),this.entries=[];let t=e.readUint32();for(let n=0;n=2&&e.writeUint32(this.default_sample_description_index),e.writeUint32(this.entries.length);for(let t=0;t>31&1,referenced_size:t&2147483647,subsegment_duration:n,starts_with_SAP:r>>31&1,SAP_type:r>>28&7,SAP_delta_time:r&268435455})}}write(e){let t=this.earliest_presentation_time>k||this.first_offset>k||this.version===1;this.version=+!!t,this.size=12+12*this.references.length,this.size+=t?16:8,this.flags=0,this.writeHeader(e),e.writeUint32(this.reference_ID),e.writeUint32(this.timescale),t?(e.writeUint64(this.earliest_presentation_time),e.writeUint64(this.first_offset)):(e.writeUint32(this.earliest_presentation_time),e.writeUint32(this.first_offset)),e.writeUint16(0),e.writeUint16(this.references.length);for(let t=0;t0&&this.sample_size===0&&(t=!1),this.size=8,t||(this.size+=4*this.sample_sizes.length),this.writeHeader(e),e.writeUint32(this.sample_size),e.writeUint32(this.sample_sizes.length),t||e.writeUint32Array(this.sample_sizes)}unpack(e){for(let t=0;tk||this.version===1;this.version=+!!t,this.size=4,this.size+=t?4:0,this.flags=0,this.writeHeader(e),t?e.writeUint64(this.baseMediaDecodeTime):e.writeUint32(this.baseMediaDecodeTime)}},rr=class extends F{constructor(...e){super(...e),this.box_name=`TrackFragmentHeaderBox`}static{this.fourcc=`tfhd`}parse(e){this.parseFullHeader(e);let t=0;this.track_id=e.readUint32(),this.size-this.hdr_size>t&&this.flags&1?(this.base_data_offset=e.readUint64(),t+=8):this.base_data_offset=0,this.size-this.hdr_size>t&&this.flags&2?(this.default_sample_description_index=e.readUint32(),t+=4):this.default_sample_description_index=0,this.size-this.hdr_size>t&&this.flags&8?(this.default_sample_duration=e.readUint32(),t+=4):this.default_sample_duration=0,this.size-this.hdr_size>t&&this.flags&16?(this.default_sample_size=e.readUint32(),t+=4):this.default_sample_size=0,this.size-this.hdr_size>t&&this.flags&32?(this.default_sample_flags=e.readUint32(),t+=4):this.default_sample_flags=0}write(e){this.version=0,this.size=4,this.flags&1&&(this.size+=8),this.flags&2&&(this.size+=4),this.flags&8&&(this.size+=4),this.flags&16&&(this.size+=4),this.flags&32&&(this.size+=4),this.writeHeader(e),e.writeUint32(this.track_id),this.flags&1&&e.writeUint64(this.base_data_offset),this.flags&2&&e.writeUint32(this.default_sample_description_index),this.flags&8&&e.writeUint32(this.default_sample_duration),this.flags&16&&e.writeUint32(this.default_sample_size),this.flags&32&&e.writeUint32(this.default_sample_flags)}},ir=class extends F{constructor(...e){super(...e),this.box_name=`TrackHeaderBox`,this.layer=0,this.alternate_group=0}static{this.fourcc=`tkhd`}parse(e){this.parseFullHeader(e),this.version===1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint32()),e.readUint32Array(2),this.layer=e.readInt16(),this.alternate_group=e.readInt16(),this.volume=e.readInt16()>>8,e.readUint16(),this.matrix=e.readInt32Array(9),this.width=e.readUint32(),this.height=e.readUint32()}write(e){let t=this.modification_time>k||this.creation_time>k||this.duration>k||this.version===1;this.version=+!!t,this.size=80,this.size+=t?12:0,this.flags=this.flags??3,this.writeHeader(e),t?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint32(this.duration)),e.writeUint32Array([0,0]),e.writeInt16(this.layer),e.writeInt16(this.alternate_group),e.writeInt16(this.volume<<8),e.writeInt16(0),e.writeInt32Array(this.matrix),e.writeUint32(this.width),e.writeUint32(this.height)}print(e){super.printHeader(e),e.log(e.indent+`creation_time: `+this.creation_time),e.log(e.indent+`modification_time: `+this.modification_time),e.log(e.indent+`track_id: `+this.track_id),e.log(e.indent+`duration: `+this.duration),e.log(e.indent+`volume: `+(this.volume>>8)),e.log(e.indent+`matrix: `+this.matrix.join(`, `)),e.log(e.indent+`layer: `+this.layer),e.log(e.indent+`alternate_group: `+this.alternate_group),e.log(e.indent+`width: `+this.width),e.log(e.indent+`height: `+this.height)}},ar=class extends F{constructor(...e){super(...e),this.box_name=`TrackExtendsBox`}static{this.fourcc=`trex`}parse(e){this.parseFullHeader(e),this.track_id=e.readUint32(),this.default_sample_description_index=e.readUint32(),this.default_sample_duration=e.readUint32(),this.default_sample_size=e.readUint32(),this.default_sample_flags=e.readUint32()}write(e){this.version=0,this.flags=0,this.size=20,this.writeHeader(e),e.writeUint32(this.track_id),e.writeUint32(this.default_sample_description_index),e.writeUint32(this.default_sample_duration),e.writeUint32(this.default_sample_size),e.writeUint32(this.default_sample_flags)}},or=class extends F{constructor(...e){super(...e),this.box_name=`TrackRunBox`,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[]}static{this.fourcc=`trun`}parse(e){this.parseFullHeader(e);let t=0;if(this.sample_count=e.readUint32(),t+=4,this.size-this.hdr_size>t&&this.flags&1?(this.data_offset=e.readInt32(),t+=4):this.data_offset=0,this.size-this.hdr_size>t&&this.flags&4?(this.first_sample_flags=e.readUint32(),t+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>t)for(let t=0;te.nb_samples!==o)){N.error(`ISOFile`,`Cannot set segment options for track ${e}: nbSamples (${o}) does not match existing tracks`);return}let c=this.getTrackById(e);if(c){let n={id:e,user:t,trak:c,segmentStream:void 0,nb_samples:o,nb_samples_per_fragment:s,size_per_segment:r,rapAlignement:i,normalizeAudioSampleEntriesForMSE:a,state:{lastFragmentSampleNumber:0,lastSegmentSampleNumber:0,accumulatedSize:0}};this.fragmentedTracks.push(n),c.nextSample=0}this.discardMdatData&&N.warn(`ISOFile`,`Segmentation options set but discardMdatData is true, samples will not be segmented`)}unsetSegmentOptions(e){let t=-1;for(let n=0;n-1&&this.fragmentedTracks.splice(t,1)}setExtractionOptions(e,t,{nbSamples:n=1e3}={}){let r=this.getTrackById(e);r&&(this.extractedTracks.push({id:e,user:t,trak:r,nb_samples:n,samples:[]}),r.nextSample=0),this.discardMdatData&&N.warn(`ISOFile`,`Extraction options set but discardMdatData is true, samples will not be extracted`)}unsetExtractionOptions(e){let t=-1;for(let n=0;n-1&&this.extractedTracks.splice(t,1)}parse(){if(!this.restoreParsePosition||this.restoreParsePosition())for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else{this.saveParsePosition&&this.saveParsePosition();let e=z(this.stream,!1);if(e.code===0){if(this.processIncompleteBox){if(this.processIncompleteBox(e))continue;return}return}if(e.code===1){let t=e.box;if(this.boxes.push(t),t.type===`uuid`)this[t.uuid]!==void 0&&N.warn(`ISOFile`,`Duplicate Box of uuid: `+t.uuid+`, overriding previous occurrence`),this[t.uuid]=t;else switch(t.type){case`mdat`:this.mdats.push(t),this.transferMdatData(t);break;case`moof`:this.moofs.push(t);break;case`free`:case`skip`:break;case`moov`:this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[t.type]===void 0?(this[t.type]=t,Array.isArray(this[t.type+`s`])&&this[t.type+`s`].push(t)):Array.isArray(this[t.type+`s`])?(N.info(`ISOFile`,`Found multiple boxes of type ${t.type} in ISOFile, adding to array`),this[t.type+`s`].push(t)):(N.warn(`ISOFile`,`Found multiple boxes of type ${t.type} but no array exists. Creating array dynamically.`),this[t.type+`s`]=[this[t.type],t])}this.updateUsedBytes&&this.updateUsedBytes(t,e)}else if(e.code===-1){N.error(`ISOFile`,`Invalid data found while parsing box of type '${e.type}' at position ${e.start}. Aborting parsing.`,this);break}}}checkBuffer(e){if(!e)throw Error(`Buffer must be defined and non empty`);return e.byteLength===0?(N.warn(`ISOFile`,`Ignoring empty buffer (fileStart: `+e.fileStart+`)`),this.stream.logBufferLevel(),!1):(N.info(`ISOFile`,`Processing buffer (fileStart: `+e.fileStart+`)`),e.usedBytes=0,this.stream.insertBuffer(e),this.stream.logBufferLevel(),this.stream.initialized()?!0:(N.warn(`ISOFile`,`Not ready to start parsing`),!1))}appendBuffer(e,t){let n;if(this.checkBuffer(e))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||=(this.buildSampleLists(),!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(t),this.nextSeekPosition?(n=this.nextSeekPosition,this.nextSeekPosition=void 0):n=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(n=this.stream.getEndFilePositionAfter(n))):n=this.nextParsePosition?this.nextParsePosition:0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(N.info(`ISOFile`,`Done processing buffer (fileStart: `+e.fileStart+`) - next buffer to fetch should have a fileStart position of `+n),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),N.info(`ISOFile`,`Sample data size in memory: `+this.getAllocatedSampleDataSize())),n}getFragmentDuration(){let e=this.getBox(`mvex`);if(!e)return;if(e.mehd)return{num:e.mehd.fragment_duration,den:this.moov.mvhd.timescale};let t=this.getBoxes(`trak`,!1),n={num:0,den:1};for(let e of t){let t=e.samples_duration,r=e.mdia.mdhd.timescale;t&&r&&t/r>n.num/n.den&&(n={num:t,den:r})}return n}getInfo(){if(!this.moov)return{hasMoov:!1,mime:``};let e=(/* @__PURE__ */ new Date(`1904-01-01T00:00:00Z`)).getTime(),t=this.getBox(`mvex`)!==void 0,n={hasMoov:!0,duration:this.moov.mvhd.duration,timescale:this.moov.mvhd.timescale,isFragmented:t,fragment_duration:this.getFragmentDuration(),isProgressive:this.isProgressive,hasIOD:this.moov.iods!==void 0,brands:[this.ftyp.major_brand].concat(this.ftyp.compatible_brands),created:new Date(e+this.moov.mvhd.creation_time*1e3),modified:new Date(e+this.moov.mvhd.modification_time*1e3),tracks:[],audioTracks:[],videoTracks:[],subtitleTracks:[],metadataTracks:[],hintTracks:[],otherTracks:[],mime:``};for(let t=0;t0?n.mime+=`video/mp4; codecs="`:n.audioTracks&&n.audioTracks.length>0?n.mime+=`audio/mp4; codecs="`:n.mime+=`application/mp4; codecs="`;for(let e=0;ee.trak.nextSamplen.nb_samples_per_fragment,s=a-n.state.lastSegmentSampleNumber>n.nb_samples,c=o||a%n.nb_samples_per_fragment===0,l=s||a%n.nb_samples===0,u=n.state.accumulatedSize>=n.size_per_segment,d=!n.rapAlignement||i.is_sync,f=e||r.nextSample+1>=r.samples.length;if(f&&!d&&N.warn(`ISOFile`,`Flushing track #`+n.id+` at sample #`+r.nextSample+` which is not a RAP, this may lead to playback issues`),c&&=d,l&&=d,u&&=d,c||u||f){o?N.warn(`ISOFile`,`Fragment on track #`+n.id+` is overdue, creating it with samples [`+n.state.lastFragmentSampleNumber+`, `+r.nextSample+`]`):N.debug(`ISOFile`,`Creating media fragment on track #`+n.id+` for samples [`+n.state.lastFragmentSampleNumber+`, `+r.nextSample+`]`);let e=this.createFragment(n.id,n.state.lastFragmentSampleNumber,r.nextSample,n.segmentStream);if(e)n.segmentStream=e,n.state.lastFragmentSampleNumber=r.nextSample+1;else{t.add(n.id);continue}}(l||u||f)&&(s?N.warn(`ISOFile`,`Segment on track #`+n.id+` is overdue, sending it with samples [`+Math.max(0,r.nextSample-n.nb_samples)+`, `+(r.nextSample-1)+`]`):N.info(`ISOFile`,`Sending fragmented data on track #`+n.id+` for samples [`+Math.max(0,r.nextSample-n.nb_samples)+`, `+(r.nextSample-1)+`]`),N.info(`ISOFile`,`Sample data size in memory: `+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(n.id,n.user,n.segmentStream.buffer,r.nextSample+1,e||r.nextSample+1>=r.samples.length),n.segmentStream=void 0,n.state.accumulatedSize=0,n.state.lastSegmentSampleNumber=r.nextSample+1),r.nextSample++}}}if(this.onSamples!==void 0)for(let e=0;e=n.samples.length)&&(N.debug(`ISOFile`,`Sending samples on track #`+t.id+` for sample `+n.nextSample),this.onSamples&&this.onSamples(t.id,t.user,t.samples),t.samples=[],t!==this.extractedTracks[e]))break}}}}getBox(e){let t=this.getBoxes(e,!0);return t.length?t[0]:void 0}getBoxes(e,t){let n=[],r=i=>{i instanceof P&&i.type&&i.type===e&&n.push(i);let a=[];i.boxes&&a.push(...i.boxes),i.entries&&a.push(...i.entries),i.item_infos&&a.push(...i.item_infos),i.references&&a.push(...i.references);for(let e of a){if(n.length&&t)return;r(e)}};return r(this),n}getTrackSamplesInfo(e){let t=this.getTrackById(e);if(t)return t.samples}getTrackSample(e,t){let n=this.getTrackById(e);return this.getSample(n,t)}releaseUsedSamples(e,t){let n=0,r=this.getTrackById(e);r.lastValidSample||=0;for(let e=r.lastValidSample;ee*s.timescale){i=o-1;break}t&&s.is_sync&&(r=o)}for(t&&(i=r),e=n.samples[i].cts,n.nextSample=i,this.resetFragmentedTrackStateAfterSeek(n,i),this.resetExtractedTrackStateAfterSeek(n);n.samples[i].alreadyRead===n.samples[i].size&&n.samples[i+1];)i++;let o=n.samples[i].offset+n.samples[i].alreadyRead;return N.info(`ISOFile`,`Seeking to `+(t?`RAP`:``)+` sample #`+n.nextSample+` on track `+n.tkhd.track_id+`, time `+N.getDurationString(e,a)+` and offset: `+o),{offset:o,time:e/a}}resetFragmentedTrackStateAfterSeek(e,t){let n=this.fragmentedTracks.find(t=>t.trak===e);n&&(n.state.lastFragmentSampleNumber=t,n.state.lastSegmentSampleNumber=t,n.state.accumulatedSize=0,n.segmentStream=void 0)}resetExtractedTrackStateAfterSeek(e){let t=this.extractedTracks.find(t=>t.trak===e);t&&(t.samples=[])}getTrackDuration(e){if(!e.samples)return 1/0;let t=e.samples[e.samples.length-1];return(t.cts+t.duration)/t.timescale}seek(e,t){let n=this.moov,r={offset:1/0,time:1/0};if(this.moov){for(let i=0;ithis.getTrackDuration(a))continue;let o=this.seekTrack(e,t,a);o.offset=0;e--)o[e]()}return a.buffer}save(e){let t=new j;return t.isofile=this,this.write(t),t.save(e)}getBuffer(){let e=new j;return e.isofile=this,this.write(e),e}static normalizeAudioSampleEntriesForMSEFragmentedInit(e,t){let n=[];for(let r of e)if(t?.has(r.tkhd.track_id))for(let e of r.mdia.minf.stbl.stsd?.entries??[]){if(!(e instanceof xn))continue;let t=e.wave?.esds;if(e.esds||!t)continue;let r=e.esds,i=e.wave,a=e.boxes;n.push(()=>{e.esds=r,e.wave=i,e.boxes=a});let o=Array.isArray(e.boxes)?e.boxes.filter(e=>e?.type!==`wave`&&e?.type!==`esds`):[];e.esds=t,e.boxes=[...o,t],e.wave=void 0}return n}initializeSegmentation(t){if(this.onSegment||N.warn(`MP4Box`,`No segmentation callback set!`),t!==void 0&&t!==`combined`&&t!==`per-track`)throw Error(`Invalid segmentation mode: ${t}`);this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.resetTables());let n=[];for(let e of this.fragmentedTracks){let t=this.getTrackById(e.id);t?n.push({id:e.id,user:e.user,trak:t}):N.warn(`ISOFile`,`Track with id ${e.id} not found, skipping fragmentation initialization`)}let r=this.moov?.mvex?.mehd?.fragment_duration,i=new Set(this.fragmentedTracks.filter(e=>e.normalizeAudioSampleEntriesForMSE!==!1).map(e=>e.id));if(t===`per-track`)return n.map(({id:t,user:n,trak:a})=>{let o=new Ue;return o.addBox(this.moov.mvhd),o.addBox(a),{id:t,user:n,buffer:e.writeInitializationSegment(this.ftyp,o,r,i)}});let a=new Ue;a.addBox(this.moov.mvhd);for(let e of n)a.addBox(e.trak);return{tracks:n.map(({id:e,user:t})=>({id:e,user:t})),buffer:e.writeInitializationSegment(this.ftyp,a,r,i)}}resetTables(){this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0;for(let e=0;e=2){let n=r[t].grouping_type+`/0`,i=new lr(r[t].grouping_type,0);e.sample_groups_info[n]||(e.sample_groups_info[n]=i)}}else if(i){for(let e=0;e=2){let n=i[e].grouping_type+`/0`,r=new lr(i[e].grouping_type,0);r.is_fragment=!0,t.sample_groups_info[n]||(t.sample_groups_info[n]=r)}}}static setSampleGroupProperties(e,t,n,r){t.sample_groups=[];for(let e in r)if(t.sample_groups[e]={grouping_type:r[e].grouping_type,grouping_type_parameter:r[e].grouping_type_parameter},n>=r[e].last_sample_in_run&&(r[e].last_sample_in_run<0&&(r[e].last_sample_in_run=0),r[e].entry_index++,r[e].entry_index<=r[e].sbgp.entries.length-1&&(r[e].last_sample_in_run+=r[e].sbgp.entries[r[e].entry_index].sample_count)),r[e].entry_index<=r[e].sbgp.entries.length-1?t.sample_groups[e].group_description_index=r[e].sbgp.entries[r[e].entry_index].group_description_index:t.sample_groups[e].group_description_index=-1,t.sample_groups[e].group_description_index!==0){let n;if(n=r[e].fragment_description?r[e].fragment_description:r[e].description,t.sample_groups[e].group_description_index>0){let r;r=t.sample_groups[e].group_description_index>65535?(t.sample_groups[e].group_description_index>>16)-1:t.sample_groups[e].group_description_index-1,n&&r>=0&&(t.sample_groups[e].description=n.entries[r])}else n&&n.version>=2&&n.default_group_description_index>0&&(t.sample_groups[e].description=n.entries[n.default_group_description_index-1])}}static process_sdtp(e,t,n){t&&(e?(t.is_leading=e.is_leading[n],t.depends_on=e.sample_depends_on[n],t.is_depended_on=e.sample_is_depended_on[n],t.has_redundancy=e.sample_has_redundancy[n]):(t.is_leading=0,t.depends_on=0,t.is_depended_on=0,t.has_redundancy=0))}buildSampleLists(){for(let e=0;ey&&(b++,y<0&&(y=0),y+=d.sample_counts[b]),n>0?(t.samples[n-1].duration=d.sample_deltas[b],t.samples_duration+=t.samples[n-1].duration,E.dts=t.samples[n-1].dts+t.samples[n-1].duration):E.dts=0,f?(n>=x&&(S++,x<0&&(x=0),x+=f.sample_counts[S]),E.cts=t.samples[n].dts+f.sample_offsets[S]):E.cts=E.dts,p?(n===p.sample_numbers[C]-1?(E.is_sync=!0,C++):(E.is_sync=!1,E.degradation_priority=0),h&&h.entries[w].sample_delta+T===n+1&&(E.subsamples=h.entries[w].subsamples,T+=h.entries[w].sample_delta,w++)):E.is_sync=!0,e.process_sdtp(t.mdia.minf.stbl.sdtp,E,E.number),E.degradation_priority=g?g.priority[n]:0,h&&h.entries[w].sample_delta+T===n&&(E.subsamples=h.entries[w].subsamples,T+=h.entries[w].sample_delta),(_.length>0||v.length>0)&&e.setSampleGroupProperties(t,E,n,t.sample_groups_info)}n>0&&(t.samples[n-1].duration=Math.max(t.mdia.mdhd.duration-t.samples[n-1].dts,0),t.samples_duration+=t.samples[n-1].duration)}}updateSampleLists(){let t,n,r,i,a;if(this.moov!==void 0)for(;this.lastMoofIndex0&&e.initSampleGroups(l,c,c.sbgps,l.mdia.minf.stbl.sgpds,c.sgpds);for(let o=0;o0?g=l.samples[l.samples.length-1].dts+l.samples[l.samples.length-1].duration:(g=c.tfdt?c.tfdt.baseMediaDecodeTime:0,l.first_traf_merged=!0);let _=g;u.flags&2048&&(_=g+u.sample_composition_time_offset[d]);let v=!!(c.tfhd.flags&1),y=!!(c.tfhd.flags&131072),b=!!(u.flags&1),x=0;x=v?c.tfhd.base_data_offset:y||o===0?s.start:a;let S;S=o===0&&d===0?b?x+u.data_offset:x:a,a=S+m;let C=c.sample_number;c.sample_number++;let w={cts:_,description_index:f,description:l.mdia.minf.stbl.stsd.entries[f],dts:g,duration:h,moof_number:this.lastMoofIndex,number_in_traf:C,number:l.samples.length,offset:S,size:m,timescale:l.mdia.mdhd.timescale,track_id:l.tkhd.track_id,is_sync:!(p>>16&1),is_leading:p>>26&3,depends_on:p>>24&3,is_depended_on:p>>22&3,has_redundancy:p>>20&3,degradation_priority:p&65535};c.first_sample_index=l.samples.length,l.samples.push(w),(c.sbgps.length>0||c.sgpds.length>0||l.mdia.minf.stbl.sbgps.length>0||l.mdia.minf.stbl.sgpds.length>0)&&e.setSampleGroupProperties(l,w,w.number_in_traf,c.sample_groups_info)}}if(c.subs){l.has_fragment_subsamples=!0;let e=c.first_sample_index;for(let t=0;t-1)i=e.buffers[r],a=i.fileStart;else for(let t of this.mdats)if(!t.stream)N.debug(`ISOFile`,`mdat stream not yet fully read for #`+this.mdats.indexOf(t)+` mdat`);else if(r=t.stream.findPosition(!0,n.offset+n.alreadyRead-t.start-t.hdr_size,!1),r>-1){e=t.stream,i=t.stream.buffers[r],a=t.start+t.hdr_size+i.fileStart;break}if(i){let r=i.byteLength-(n.offset+n.alreadyRead-a);if(n.size-n.alreadyRead<=r)return N.debug(`ISOFile`,`Getting sample #`+t+` data (alreadyRead: `+n.alreadyRead+` offset: `+(n.offset+n.alreadyRead-a)+` read size: `+(n.size-n.alreadyRead)+` full size: `+n.size+`)`),j.memcpy(n.data.buffer,n.alreadyRead,i,n.offset+n.alreadyRead-a,n.size-n.alreadyRead),i.usedBytes+=n.size-n.alreadyRead,e.logBufferLevel(),n.alreadyRead=n.size,n;if(r===0)return;N.debug(`ISOFile`,`Getting sample #`+t+` partial data (alreadyRead: `+n.alreadyRead+` offset: `+(n.offset+n.alreadyRead-a)+` read size: `+r+` full size: `+n.size+`)`),j.memcpy(n.data.buffer,n.alreadyRead,i,n.offset+n.alreadyRead-a,r),n.alreadyRead+=r,i.usedBytes+=r,e.logBufferLevel()}else return}}}releaseSample(e,t){let n=e.samples[t];return n.data?(this.samplesDataSize-=n.size,n.data=void 0,n.alreadyRead=0,n.size):0}getAllocatedSampleDataSize(){return this.samplesDataSize}getCodecs(){let e=``;for(let t=0;t0&&(e+=`,`),e+=n.mdia.minf.stbl.stsd.entries[0].getCodec()}return e}getTrexById(e){if(this.moov&&this.moov.mvex)for(let t=0;t0?n.ipro.protections[n.iinf.item_infos[t].item_protection_index-1]:void 0}}if(n.grpl)for(let e=0;e0&&t.property_index-1-1){let a=this.stream.buffers[i],o=a.byteLength-(r.offset+r.alreadyRead-a.fileStart);if(r.length-r.alreadyRead<=o)N.debug(`ISOFile`,`Getting item #`+e+` extent #`+n+` data (alreadyRead: `+r.alreadyRead+` offset: `+(r.offset+r.alreadyRead-a.fileStart)+` read size: `+(r.length-r.alreadyRead)+` full extent size: `+r.length+` full item size: `+t.size+`)`),j.memcpy(t.data.buffer,t.alreadyRead,a,r.offset+r.alreadyRead-a.fileStart,r.length-r.alreadyRead),(!this.parsingMdat||this.discardMdatData)&&(a.usedBytes+=r.length-r.alreadyRead),this.stream.logBufferLevel(),t.alreadyRead+=r.length-r.alreadyRead,r.alreadyRead=r.length;else{N.debug(`ISOFile`,`Getting item #`+e+` extent #`+n+` partial data (alreadyRead: `+r.alreadyRead+` offset: `+(r.offset+r.alreadyRead-a.fileStart)+` read size: `+o+` full extent size: `+r.length+` full item size: `+t.size+`)`),j.memcpy(t.data.buffer,t.alreadyRead,a,r.offset+r.alreadyRead-a.fileStart,o),r.alreadyRead+=o,t.alreadyRead+=o,(!this.parsingMdat||this.discardMdatData)&&(a.usedBytes+=o),this.stream.logBufferLevel();return}}else return}}if(t.alreadyRead===t.size)return t}releaseItem(e){let t=this.items[e];if(t.data){this.itemsDataSize-=t.size,t.data=void 0,t.alreadyRead=0;for(let e=0;ea){N.debug(`ISOFile`,`Transferring 'mdat' data from buffer #`+e+` (`+a+` to `+o+`)`);let n=o-a,r=new A(n),s=t.stream.getAbsoluteEndPosition();j.memcpy(r,0,i,a,n),r.fileStart=s,t.stream.insertBuffer(r),i.usedBytes+=n}}}}processIncompleteMdat(){let e=this.parsingMdat;return this.stream.seek(e.start+e.size,!1,this.discardMdatData)?(N.debug(`ISOFile`,`Found 'mdat' end in buffered data`),this.transferMdatData(),this.parsingMdat=void 0,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)}restoreParsePosition(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)}saveParsePosition(){this.lastBoxStartPosition=this.stream.getPosition()}updateUsedBytes(e,t){this.stream.addUsedBytes&&(e.type===`mdat`?(this.stream.addUsedBytes(e.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(e.size-e.hdr_size)):this.stream.addUsedBytes(e.size))}addBox(e){return P.prototype.addBox.call(this,e)}init(e={}){let t=this.addBox(new yt);t.major_brand=e.brands&&e.brands[0]||`iso4`,t.minor_version=0,t.compatible_brands=e.brands||[`iso4`];let n=this.addBox(new Ue);n.addBox(new Xe);let r=n.addBox(new Mt);return r.timescale=e.timescale||600,r.rate=e.rate||65536,r.creation_time=0,r.modification_time=0,r.duration=e.duration||0,r.volume=e.width?0:256,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.next_track_id=1,this}addTrack(e={}){this.moov||this.init(e);let t=e||{};t.width=t.width||320,t.height=t.height||320,t.id=t.id||this.moov.mvhd.next_track_id,t.type=t.type||`avc1`;let n=this.moov.addBox(new We);this.moov.mvhd.next_track_id=t.id+1;let r=n.addBox(new ir);r.flags=7,r.creation_time=0,r.modification_time=0,r.track_id=t.id,r.duration=t.duration||0,r.layer=t.layer||0,r.alternate_group=0,r.volume=1,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.width=t.width<<16,r.height=t.height<<16;let i=n.addBox(new Ke),a=i.addBox(new St);a.creation_time=0,a.modification_time=0,a.timescale=t.timescale||1,a.duration=t.media_duration||0,a.language=t.language||`und`;let o=i.addBox(new bt);o.handler=t.hdlr||`vide`,o.name=t.name||`Track created with MP4Box.js`;let s=i.addBox(new vt);s.extended_language=t.language||`fr-FR`;let c=i.addBox(new qe),l=L.sampleEntry[t.type];if(!l)return;let u=new l;if(u.data_reference_index=1,u instanceof W){let e=u,n=c.addBox(new cr);n.graphicsmode=0,n.opcolor=[0,0,0],e.width=t.width,e.height=t.height,e.horizresolution=72<<16,e.vertresolution=72<<16,e.frame_count=1,e.compressorname=t.type+` Compressor`,e.depth=24,t.avcDecoderConfigRecord?e.addBox(new Me(t.avcDecoderConfigRecord.byteLength)).parse(new j(t.avcDecoderConfigRecord)):t.hevcDecoderConfigRecord&&e.addBox(new xt(t.hevcDecoderConfigRecord.byteLength)).parse(new j(t.hevcDecoderConfigRecord))}else if(u instanceof G){let e=u,n=c.addBox(new Yn);n.balance=t.balance||0,e.channel_count=t.channel_count||2,e.samplesize=t.samplesize||16,e.samplerate=t.samplerate||65536}else u instanceof Oe?c.addBox(new Le):u instanceof U?(c.addBox(new Zn),u instanceof Vn&&(u.namespace=t.namespace||`nonamespace`,u.schema_location=t.schema_location||``,u.auxiliary_mime_types=t.auxiliary_mime_types||``)):(u instanceof H||u instanceof Ae,c.addBox(new Re));t.description&&u.addBox.call(u,t.description),t.description_boxes&&t.description_boxes.forEach(function(e){u.addBox.call(u,e)});let d=c.addBox(new Je).addBox(new _t),f=new sr;f.flags=1,d.addEntry(f);let p=c.addBox(new Ye);p.addBox(new $n).addEntry(u);let m=p.addBox(new tr);m.sample_counts=[],m.sample_deltas=[];let h=p.addBox(new Qn);h.first_chunk=[],h.samples_per_chunk=[],h.sample_description_index=[];let g=p.addBox(new Xn);g.chunk_offsets=[];let _=p.addBox(new er);_.sample_sizes=[];let v=this.moov.mvex.addBox(new ar);return v.track_id=t.id,v.default_sample_description_index=t.default_sample_description_index||1,v.default_sample_duration=t.default_sample_duration||0,v.default_sample_size=t.default_sample_size||0,v.default_sample_flags=t.default_sample_flags||0,this.buildTrakSampleLists(n),t.id}addSample(e,t,{sample_description_index:n,duration:r=1,cts:i=0,dts:a=0,is_sync:o=!1,is_leading:s=0,depends_on:c=0,is_depended_on:l=0,has_redundancy:u=0,degradation_priority:d=0,subsamples:f,offset:p=0}={}){let m=this.getTrackById(e);if(m===void 0)return;let h=n?n-1:0,g={number:m.samples.length,track_id:m.tkhd.track_id,timescale:m.mdia.mdhd.timescale,description_index:h,description:m.mdia.minf.stbl.stsd.entries[h],data:t,size:t.byteLength,alreadyRead:t.byteLength,duration:r,cts:i,dts:a,is_sync:o,is_leading:s,depends_on:c,is_depended_on:l,has_redundancy:u,degradation_priority:d,offset:p,subsamples:f};m.samples.push(g),m.samples_size+=g.size,m.samples_duration+=g.duration,m.first_dts===void 0&&(m.first_dts=a),this.processSamples();let _=this.addBox(this.createMoof([g]));_.computeSize(),_.trafs[0].truns[0].data_offset=_.size+8;let v=this.addBox(new Ne);return v.data=new Uint8Array(t),g}createMoof(e){if(e.length===0)return;if(e.some(t=>t.track_id!==e[0].track_id))throw Error(`Cannot create moof for samples from different tracks: `+e.map(e=>e.track_id).join(`, `));let t=e[0].track_id,n=this.getTrackById(t);if(!n)throw Error(`Cannot create moof for non-existing track: `+t);let r=new Ze,i=r.addBox(new jt);i.sequence_number=++this.nextMoofNumber;let a=r.addBox(new Qe),o=a.addBox(new rr);o.track_id=t,o.flags=131072;let s=a.addBox(new nr);s.baseMediaDecodeTime=e[0].dts-(n.first_dts||0);let c=a.addBox(new or);c.flags=3841,c.data_offset=0,c.first_sample_flags=0,c.sample_count=e.length;for(let t of e){let e=0;e=t.is_sync?1<<25:65536,c.sample_duration.push(t.duration),c.sample_size.push(t.size),c.sample_flags.push(e),c.sample_composition_time_offset.push(t.cts-t.dts)}return r}print(e){e.indent=``;for(let t=0;t=4;)this.compatible_brands[n]=e.readString(4),t-=4,n++}write(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,void 0,4),e.writeUint32(this.minor_version);for(let t=0;tq,ES_Descriptor:()=>gr,MPEG4DescriptorParser:()=>yr}),q=class e{constructor(e,t){this.tag=e,this.size=t,this.descs=[]}parse(e){this.data=e.readUint8Array(this.size)}findDescriptor(e){for(let t=0;t>3;return e===31&&t.data.length>=2&&(e=32+((t.data[0]&7)<<3)+((t.data[1]&224)>>5)),e}}};const _r={Descriptor:q,ES_Descriptor:gr,DecoderConfigDescriptor:class extends q{constructor(e){super(4,e)}parse(e){this.oti=e.readUint8(),this.streamType=e.readUint8(),this.upStream=!!(this.streamType>>1&1),this.streamType>>>=2,this.bufferSize=e.readUint24(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32(),this.size-=13,this.parseRemainingDescriptors(e)}},DecoderSpecificInfo:class extends q{constructor(e){super(5,e)}},SLConfigDescriptor:class extends q{constructor(e){super(6,e)}}},vr={3:`ES_Descriptor`,4:`DecoderConfigDescriptor`,5:`DecoderSpecificInfo`,6:`SLConfigDescriptor`};var yr=class{constructor(){this.parseOneDescriptor=q.prototype.parseOneDescriptor}getDescriptorName(e){return vr[e]}},br=class extends P{constructor(...e){super(...e),this.box_name=`AV1LayeredImageIndexingProperty`}static{this.fourcc=`a1lx`}parse(e){let t=((e.readUint8()&1)+1)*16;this.layer_size=[];for(let n=0;n<3;n++)t===16?this.layer_size[n]=e.readUint16():this.layer_size[n]=e.readUint32()}},xr=class extends P{constructor(...e){super(...e),this.box_name=`OperatingPointSelectorProperty`}static{this.fourcc=`a1op`}parse(e){this.op_index=e.readUint8()}},Sr=class extends F{constructor(...e){super(...e),this.box_name=`AuxiliaryTypeProperty`}static{this.fourcc=`auxC`}parse(e){this.parseFullHeader(e),this.aux_type=e.readCString();let t=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=e.readUint8Array(t)}},Cr=class extends P{constructor(...e){super(...e),this.box_name=`BitRateBox`}static{this.fourcc=`btrt`}parse(e){this.bufferSizeDB=e.readUint32(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32()}},wr=class extends F{constructor(...e){super(...e),this.box_name=`CodingConstraintsBox`}static{this.fourcc=`ccst`}parse(e){this.parseFullHeader(e);let t=e.readUint8();this.all_ref_pics_intra=(t&128)==128,this.intra_pred_used=(t&64)==64,this.max_ref_per_pic=(t&63)>>2,e.readUint24()}},Tr=class extends P{constructor(...e){super(...e),this.box_name=`ComponentDefinitionBox`}static{this.fourcc=`cdef`}parse(e){this.channel_count=e.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[];for(let t=0;t=32768&&this.component_type_urls.push(e.readCString())}}},Mr=class extends F{constructor(...e){super(...e),this.box_name=`ChunkLargeOffsetBox`}static{this.fourcc=`co64`}parse(e){this.parseFullHeader(e);let t=e.readUint32();if(this.chunk_offsets=[],this.version===0)for(let n=0;n>5),this.coverage_regions=[];for(let n=0;n>6),t.sphere_region=this.parseSphereRegion(e,!0,!0),this.coverage_regions.push(t)}}parseSphereRegion(e,t,n){let r=new Pr;return r.centre_azimuth=e.readInt32(),r.centre_elevation=e.readInt32(),r.centre_tilt=e.readInt32(),r.range_included_flag=t,t&&(r.azimuth_range=e.readUint32(),r.elevation_range=e.readUint32()),r.interpolate_included_flag=n,n&&(r.interpolate=(e.readUint8()&128)==128),r}},Lr=class extends F{constructor(...e){super(...e),this.box_name=`CopyrightBox`}static{this.fourcc=`cprt`}parse(e){this.parseFullHeader(e),this.parseLanguage(e),this.notice=e.readCString()}},Rr=class extends F{constructor(...e){super(...e),this.box_name=`CompatibleSchemeTypeBox`}static{this.fourcc=`csch`}parse(e){this.parseFullHeader(e),this.scheme_type=e.readString(4),this.scheme_version=e.readUint32(),this.flags&1&&(this.scheme_uri=e.readCString())}};const J=2147483647;var zr=class extends F{constructor(...e){super(...e),this.box_name=`CompositionToDecodeBox`}static{this.fourcc=`cslg`}parse(e){this.parseFullHeader(e),this.version===0?(this.compositionToDTSShift=e.readInt32(),this.leastDecodeToDisplayDelta=e.readInt32(),this.greatestDecodeToDisplayDelta=e.readInt32(),this.compositionStartTime=e.readInt32(),this.compositionEndTime=e.readInt32()):this.version===1&&(this.compositionToDTSShift=e.readInt64(),this.leastDecodeToDisplayDelta=e.readInt64(),this.greatestDecodeToDisplayDelta=e.readInt64(),this.compositionStartTime=e.readInt64(),this.compositionEndTime=e.readInt64())}write(e){this.version=0,(this.compositionToDTSShift>J||this.leastDecodeToDisplayDelta>J||this.greatestDecodeToDisplayDelta>J||this.compositionStartTime>J||this.compositionEndTime>J)&&(this.version=1),this.flags=0,this.version===0?(this.size=20,this.writeHeader(e),e.writeInt32(this.compositionToDTSShift),e.writeInt32(this.leastDecodeToDisplayDelta),e.writeInt32(this.greatestDecodeToDisplayDelta),e.writeInt32(this.compositionStartTime),e.writeInt32(this.compositionEndTime)):this.version===1&&(this.size=40,this.writeHeader(e),e.writeInt64(this.compositionToDTSShift),e.writeInt64(this.leastDecodeToDisplayDelta),e.writeInt64(this.greatestDecodeToDisplayDelta),e.writeInt64(this.compositionStartTime),e.writeInt64(this.compositionEndTime))}},Br=class extends F{constructor(...e){super(...e),this.box_name=`CompositionOffsetBox`}static{this.fourcc=`ctts`}parse(e){this.parseFullHeader(e);let t=e.readUint32();if(this.sample_counts=[],this.sample_offsets=[],this.version===0)for(let n=0;ne<0),this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length);for(let t=0;t>6,this.bsid=t>>1&31,this.bsmod=(t&1)<<2|n>>6&3,this.acmod=n>>3&7,this.lfeon=n>>2&1,this.bit_rate_code=n&3|r>>5&7}},Hr=class extends P{constructor(...e){super(...e),this.box_name=`EC3SpecificBox`}static{this.fourcc=`dec3`}parse(e){let t=e.readUint16();this.data_rate=t>>3,this.num_ind_sub=t&7,this.ind_subs=[];for(let t=0;t>6,bsid:t>>1&31,bsmod:(t&1)<<4|n>>4&15,acmod:n>>1&7,lfeon:n&1,num_dep_sub:r>>1&15};this.ind_subs.push(i),i.num_dep_sub>0&&(i.chan_loc=(r&1)<<8|e.readUint8())}}},Ur=class extends F{constructor(...e){super(...e),this.box_name=`FLACSpecificBox`}static{this.fourcc=`dfLa`}parse(e){this.parseFullHeader(e);let t=[],n=[`STREAMINFO`,`PADDING`,`APPLICATION`,`SEEKTABLE`,`VORBIS_COMMENT`,`CUESHEET`,`PICTURE`,`RESERVED`],r;do{r=e.readUint8();let i=Math.min(r&127,n.length-1);i?e.readUint8Array(e.readUint24()):(e.readUint8Array(13),this.samplerate=e.readUint32()>>12,e.readUint8Array(20)),t.push(n[i])}while(r&128);this.numMetadataBlocks=t.length+` (`+t.join(`, `)+`)`}},Wr=class extends P{constructor(...e){super(...e),this.box_name=`hintimmediateBytesSent`}static{this.fourcc=`dimm`}parse(e){this.bytessent=e.readUint64()}},Gr=class extends P{constructor(...e){super(...e),this.box_name=`hintlongestpacket`}static{this.fourcc=`dmax`}parse(e){this.time=e.readUint32()}},Kr=class extends P{constructor(...e){super(...e),this.box_name=`hintmediaBytesSent`}static{this.fourcc=`dmed`}parse(e){this.bytessent=e.readUint64()}},qr=class extends P{constructor(...e){super(...e),this.box_name=`OpusSpecificBox`}static{this.fourcc=`dOps`}parse(e){if(this.Version=e.readUint8(),this.OutputChannelCount=e.readUint8(),this.PreSkip=e.readUint16(),this.InputSampleRate=e.readUint32(),this.OutputGain=e.readInt16(),this.ChannelMappingFamily=e.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=e.readUint8(),this.CoupledCount=e.readUint8(),this.ChannelMapping=[];for(let t=0;te.segment_duration>k||e.media_time>k)||this.version===1;this.version=+!!t,this.size=4+12*this.entries.length,this.size+=t?8*this.entries.length:0,this.writeHeader(e),e.writeUint32(this.entries.length);for(let n=0;n>7,this.axis=t&1}},gi=class extends F{constructor(...e){super(...e),this.box_name=`ItemPropertyAssociationBox`}static{this.fourcc=`ipma`}parse(e){this.parseFullHeader(e);let t=e.readUint32();this.associations=[];for(let n=0;n>7==1,property_index:this.flags&1?(t&127)<<8|e.readUint8():t&127})}this.associations.push({id:t,props:n})}}},_i=class extends P{constructor(...e){super(...e),this.box_name=`ImageRotation`}static{this.fourcc=`irot`}parse(e){this.angle=e.readUint8()&3}},vi=class extends F{constructor(...e){super(...e),this.box_name=`ImageSpatialExtentsProperty`}static{this.fourcc=`ispe`}parse(e){this.parseFullHeader(e),this.image_width=e.readUint32(),this.image_height=e.readUint32()}},yi=class extends F{constructor(...e){super(...e),this.box_name=`TAITimestampBox`}static{this.fourcc=`itai`}parse(e){this.TAI_timestamp=e.readUint64();let t=e.readUint8();this.sychronization_state=t>>7&1,this.timestamp_generation_failure=t>>6&1,this.timestamp_is_modified=t>>5&1}},bi=class extends F{constructor(...e){super(...e),this.box_name=`KindBox`}static{this.fourcc=`kind`}parse(e){this.parseFullHeader(e),this.schemeURI=e.readCString(),this.isEndOfBox(e)||(this.value=e.readCString())}write(e){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value?this.value.length+1:0),this.writeHeader(e),e.writeCString(this.schemeURI),this.value&&e.writeCString(this.value)}},xi=class extends F{constructor(...e){super(...e),this.box_name=`LevelAssignmentBox`}static{this.fourcc=`leva`}parse(e){this.parseFullHeader(e);let t=e.readUint8();this.levels=[];for(let n=0;n>7,t.assignment_type=r&127,t.assignment_type){case 0:t.grouping_type=e.readString(4);break;case 1:t.grouping_type=e.readString(4),t.grouping_type_parameter=e.readUint32();break;case 2:break;case 3:break;case 4:t.sub_track_id=e.readUint32();break;default:N.warn(`BoxParser`,`Unknown level assignment type: ${t.assignment_type}`)}}}},Si=class extends P{constructor(...e){super(...e),this.box_name=`LHEVCConfigurationBox`}static{this.fourcc=`lhvC`}parse(e){this.configurationVersion=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3;let t=e.readUint8();this.numTemporalLayers=(t&13)>>3,this.temporalIdNested=(t&4)>>2,this.lengthSizeMinusOne=t&3,this.nalu_arrays=[];let n=e.readUint8();for(let r=0;r>7,n.nalu_type=t&63;let r=e.readUint16();for(let t=0;t>4,r=t&7;this.padbits.push(new ji(n,r))}}},Ni=class extends P{constructor(...e){super(...e),this.box_name=`PixelAspectRatioBox`}static{this.fourcc=`pasp`}parse(e){this.hSpacing=e.readUint32(),this.vSpacing=e.readUint32()}},Pi=class extends P{constructor(...e){super(...e),this.box_name=`CuePayloadBox`}static{this.fourcc=`payl`}parse(e){this.text=e.readString(this.size-this.hdr_size)}},Fi=class extends P{constructor(...e){super(...e),this.box_name=`hintpayloadID`}static{this.fourcc=`payt`}parse(e){this.payloadID=e.readUint32();let t=e.readUint8();this.rtpmap_string=e.readString(t)}},Ii=class extends F{constructor(...e){super(...e),this.box_name=`ProgressiveDownloadInfoBox`,this.rate=[],this.initial_delay=[]}static{this.fourcc=`pdin`}parse(e){this.parseFullHeader(e);let t=(this.size-this.hdr_size)/8;for(let n=0;n0){let t=e.readUint32();for(let n=0;n0&&(this.protection_data=e.readUint8Array(t))}},Ui=class extends F{constructor(...e){super(...e),this.box_name=`TrackCleanApertureDimensionsBox`}static{this.fourcc=`clef`}parse(e){this.parseFullHeader(e),this.width=e.readUint32(),this.height=e.readUint32()}};function Wi(e,t){if(e===Gi.Types.UTF8)return new TextDecoder(`utf-8`).decode(t);let n=new DataView(t.buffer);if(e===Gi.Types.BE_UNSIGNED_INT){if(t.length===1)return n.getUint8(0);if(t.length===2)return n.getUint16(0,!1);if(t.length===4)return n.getUint32(0,!1);if(t.length===8)return n.getBigUint64(0,!1);throw Error(`Unsupported ITIF_TYPE_BE_UNSIGNED_INT length `+t.length)}if(e===Gi.Types.BE_SIGNED_INT){if(t.length===1)return n.getInt8(0);if(t.length===2)return n.getInt16(0,!1);if(t.length===4)return n.getInt32(0,!1);if(t.length===8)return n.getBigInt64(0,!1);throw Error(`Unsupported ITIF_TYPE_BE_SIGNED_INT length `+t.length)}if(e===Gi.Types.BE_FLOAT32)return n.getFloat32(0,!1);N.warn(`DataBox`,`Unsupported or unimplemented itif data type: `+e)}var Gi=class extends P{constructor(...e){super(...e),this.box_name=`DataBox`}static{this.fourcc=`data`}static{this.Types={RESERVED:0,UTF8:1,UTF16:2,SJIS:3,UTF8_SORT:4,UTF16_SORT:5,JPEG:13,PNG:14,BE_SIGNED_INT:21,BE_UNSIGNED_INT:22,BE_FLOAT32:23,BE_FLOAT64:24,BMP:27,QT_ATOM:28,BE_SIGNED_INT8:65,BE_SIGNED_INT16:66,BE_SIGNED_INT32:67,BE_FLOAT32_POINT:70,BE_FLOAT32_DIMENSIONS:71,BE_FLOAT32_RECT:72,BE_SIGNED_INT64:74,BE_UNSIGNED_INT8:75,BE_UNSIGNED_INT16:76,BE_UNSIGNED_INT32:77,BE_UNSIGNED_INT64:78,BE_FLOAT64_AFFINE_TRANSFORM:79}}parse(e){this.valueType=e.readUint32(),this.country=e.readUint16(),this.country>255&&(e.seek(e.getPosition()-2),this.countryString=e.readString(2)),this.language=e.readUint16(),this.language>255&&(e.seek(e.getPosition()-2),this.parseLanguage(e)),this.raw=e.readUint8Array(this.size-this.hdr_size-8),this.value=Wi(this.valueType,this.raw)}},Ki=class extends F{constructor(...e){super(...e),this.box_name=`TrackEncodedPixelsDimensionsBox`}static{this.fourcc=`enof`}parse(e){this.parseFullHeader(e),this.width=e.readUint32(),this.height=e.readUint32()}},qi=class extends P{constructor(...e){super(...e),this.box_name=`IlstBox`}static{this.fourcc=`ilst`}parse(e){this.list={};let t=this.size-this.hdr_size;for(;t>0;){let n=e.readUint32(),r=e.readUint32(),i=z(e,!1,n-8);i.code===1&&(this.list[r]=i.box),t-=n}}},Ji=class extends F{constructor(...e){super(...e),this.box_name=`KeysBox`}static{this.fourcc=`keys`}parse(e){this.parseFullHeader(e),this.count=e.readUint32(),this.keys={};for(let t=0;t>4&15,this.sample_sizes[n+1]=t&15}else if(this.field_size===8)for(let n=0;n0)for(let r=0;r>6}},ga=class extends F{constructor(...e){super(...e),this.box_name=`TrackEncryptionBox`}static{this.fourcc=`tenc`}parse(e){if(this.parseFullHeader(e),e.readUint8(),this.version===0)e.readUint8();else{let t=e.readUint8();this.default_crypt_byte_block=t>>4&15,this.default_skip_byte_block=t&15}this.default_isProtected=e.readUint8(),this.default_Per_Sample_IV_Size=e.readUint8(),this.default_KID=R(e),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=e.readUint8(),this.default_constant_IV=e.readUint8Array(this.default_constant_IV_size))}},_a=class{},va=class extends F{constructor(...e){super(...e),this.box_name=`TrackFragmentRandomAccessBox`}static{this.fourcc=`tfra`}parse(e){this.parseFullHeader(e),this.track_ID=e.readUint32(),e.readUint24();let t=e.readUint8();this.length_size_of_traf_num=t>>4&3,this.length_size_of_trun_num=t>>2&3,this.length_size_of_sample_num=t&3,this.entries=[];let n=e.readUint32();for(let t=0;t>7&1,this.block_pad_lsb=t>>6&1,this.block_little_endian=t>>5&1,this.block_reversed=t>>4&1,this.pad_unknown=t>>3&1,this.pixel_size=e.readUint32(),this.row_align_size=e.readUint32(),this.tile_align_size=e.readUint32(),this.num_tile_cols_minus_one=e.readUint32(),this.num_tile_rows_minus_one=e.readUint32()}}},Na=class extends F{constructor(...e){super(...e),this.box_name=`DataEntryUrnBox`}static{this.fourcc=`urn `}parse(e){this.parseFullHeader(e),this.name=e.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=e.readCString())}write(e){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(e),e.writeCString(this.name),this.location&&e.writeCString(this.location)}},Pa=class extends P{constructor(...e){super(...e),this.box_name=`WebVTTConfigurationBox`}static{this.fourcc=`vttC`}parse(e){this.text=e.readString(this.size-this.hdr_size)}},Fa=class extends F{constructor(...e){super(...e),this.box_name=`VvcNALUConfigBox`}static{this.fourcc=`vvnC`}parse(e){this.parseFullHeader(e);let t=e.readUint8();this.lengthSizeMinusOne=t&3}},Ia=class extends I{static{this.grouping_type=`alst`}parse(e){let t=e.readUint16();this.first_output_sample=e.readUint16(),this.sample_offset=[];for(let n=0;n>7,this.avgRateFlag=t>>6&1,this.durationFlag&&(this.duration=e.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()),this.dependency=[];let n=e.readUint8();for(let t=0;t>7,this.num_leading_samples=t&127}},Ua=class extends I{static{this.grouping_type=`rash`}parse(e){if(this.operation_point_count=e.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)N.warn(`BoxParser`,`Mismatch in `+this.grouping_type+` sample group length`),this.data=e.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=e.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(let t=0;t>4,this.skip_byte_block=t&15,this.isProtected=e.readUint8(),this.Per_Sample_IV_Size=e.readUint8(),this.KID=R(e),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=e.readUint8(),this.constant_IV=e.readUint8Array(this.constant_IV_size))}},Ja=class extends I{static{this.grouping_type=`stsa`}parse(e){N.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}},Ya=class extends I{static{this.grouping_type=`sync`}parse(e){let t=e.readUint8();this.NAL_unit_type=t&63}},Xa=class extends I{static{this.grouping_type=`tele`}parse(e){let t=e.readUint8();this.level_independently_decodable=t>>7}},Za=class extends I{static{this.grouping_type=`tsas`}parse(e){N.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}},Qa=class extends I{static{this.grouping_type=`tscl`}parse(e){N.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}},$a=class extends I{static{this.grouping_type=`vipr`}parse(e){N.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}},eo=class extends P{static{this.fourcc=`uuid`}},X=class extends F{static{this.fourcc=`uuid`}},to=class extends X{constructor(...e){super(...e),this.box_name=`LiveServerManifestBox`}static{this.uuid=`a5d40b30e81411ddba2f0800200c9a66`}parse(e){this.parseFullHeader(e),this.LiveServerManifest=e.readString(this.size-this.hdr_size).replace(/&/g,`&`).replace(//g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}},no=class extends X{constructor(...e){super(...e),this.box_name=`PiffProtectionSystemSpecificHeaderBox`}static{this.uuid=`d08a4f1810f34a82b6c832d8aba183d3`}parse(e){this.parseFullHeader(e),this.system_id=R(e);let t=e.readUint32();t>0&&(this.data=e.readUint8Array(t))}},ro=class extends X{constructor(...e){super(...e),this.box_name=`PiffSampleEncryptionBox`}static{this.uuid=`a2394f525a9b4f14a2446c427c648df4`}},io=class extends X{constructor(...e){super(...e),this.box_name=`PiffTrackEncryptionBox`}static{this.uuid=`8974dbce7be74c5184f97148f9882554`}parse(e){this.parseFullHeader(e),this.default_AlgorithmID=e.readUint24(),this.default_IV_size=e.readUint8(),this.default_KID=R(e)}},ao=class extends X{constructor(...e){super(...e),this.box_name=`TfrfBox`}static{this.uuid=`d4807ef2ca3946958e5426cb9e46a79f`}parse(e){this.parseFullHeader(e),this.fragment_count=e.readUint8(),this.entries=[];for(let t=0;tNr,ItemComponentContentIDPropertyBox:()=>co,ItemContentIDPropertyBox:()=>so,OpusSampleEntry:()=>En,SmDmBox:()=>aa,a1lxBox:()=>br,a1opBox:()=>xr,ac_3SampleEntry:()=>Cn,ac_4SampleEntry:()=>wn,aebrBox:()=>Xr,afbrBox:()=>Zr,albcBox:()=>Qr,alstSampleGroupEntry:()=>Ia,altrBox:()=>$r,auxCBox:()=>Sr,av01SampleEntry:()=>qt,av1CBox:()=>Ft,avc1SampleEntry:()=>Ut,avc2SampleEntry:()=>Wt,avc3SampleEntry:()=>Gt,avc4SampleEntry:()=>Kt,avcCBox:()=>Me,avllSampleGroupEntry:()=>La,avs3SampleEntry:()=>hn,avssSampleGroupEntry:()=>Ra,brstBox:()=>ei,btrtBox:()=>Cr,bxmlBox:()=>Ve,ccstBox:()=>wr,cdefBox:()=>Tr,clapBox:()=>Er,clefBox:()=>Ui,clliBox:()=>Dr,cmexBox:()=>Or,cminBox:()=>kr,cmpCBox:()=>Ar,cmpdBox:()=>jr,co64Box:()=>Mr,colrBox:()=>Vt,coviBox:()=>Ir,cprtBox:()=>Lr,cschBox:()=>Rr,cslgBox:()=>zr,cttsBox:()=>Br,dOpsBox:()=>qr,dac3Box:()=>Vr,dataBox:()=>Gi,dav1SampleEntry:()=>Jt,dec3Box:()=>Hr,dfLaBox:()=>Ur,dimmBox:()=>Wr,dinfBox:()=>Je,dmax:()=>Gr,dmedBox:()=>Kr,dobrBox:()=>ti,drefBox:()=>_t,drepBox:()=>Jr,dtrtSampleGroupEntry:()=>za,dvh1SampleEntry:()=>an,dvheSampleEntry:()=>on,ec_3SampleEntry:()=>Tn,edtsBox:()=>Ge,elngBox:()=>vt,elstBox:()=>Yr,emsgBox:()=>fr,encaSampleEntry:()=>Nn,encmSampleEntry:()=>Rn,encsSampleEntry:()=>Fn,enctSampleEntry:()=>Ln,encuSampleEntry:()=>Pn,encvSampleEntry:()=>Mn,enofBox:()=>Ki,eqivBox:()=>ni,esdsBox:()=>It,etypBox:()=>ht,fLaCSampleEntry:()=>jn,favcBox:()=>ri,fielBox:()=>pi,fobrBox:()=>ii,freeBox:()=>Fe,frmaBox:()=>mi,ftypBox:()=>yt,grplBox:()=>pt,hdlrBox:()=>bt,hev1SampleEntry:()=>Qt,hev2SampleEntry:()=>$t,hinfBox:()=>rt,hmhdBox:()=>Le,hntiBox:()=>nt,hvc1SampleEntry:()=>Xt,hvc2SampleEntry:()=>Zt,hvcCBox:()=>xt,hvt1SampleEntry:()=>en,iaugBox:()=>ai,idatBox:()=>Pe,iinfBox:()=>Tt,ilocBox:()=>Et,ilstBox:()=>qi,imirBox:()=>hi,infeBox:()=>wt,iodsBox:()=>ze,ipcoBox:()=>ft,ipmaBox:()=>gi,iproBox:()=>He,iprpBox:()=>dt,irefBox:()=>Ot,irotBox:()=>_i,ispeBox:()=>vi,itaiBox:()=>yi,j2kHBox:()=>mt,j2kiSampleEntry:()=>gn,keysBox:()=>Ji,kindBox:()=>bi,levaBox:()=>xi,lhe1SampleEntry:()=>tn,lhv1SampleEntry:()=>nn,lhvCBox:()=>Si,lselBox:()=>Ci,lvc1SampleEntry:()=>rn,lvcCBox:()=>Rt,m4aeSampleEntry:()=>Sn,maxrBox:()=>wi,mdatBox:()=>Ne,mdcvBox:()=>Ei,mdhdBox:()=>St,mdiaBox:()=>Ke,mecoBox:()=>tt,mehdBox:()=>Ct,metaBox:()=>At,mettSampleEntry:()=>Nt,metxSampleEntry:()=>Pt,mfhdBox:()=>jt,mfraBox:()=>et,mfroBox:()=>Di,mha1SampleEntry:()=>Dn,mha2SampleEntry:()=>On,mhm1SampleEntry:()=>kn,mhm2SampleEntry:()=>An,minfBox:()=>qe,mjp2SampleEntry:()=>_n,mjpgSampleEntry:()=>vn,moofBox:()=>Ze,moovBox:()=>Ue,mp4aSampleEntry:()=>xn,mp4sSampleEntry:()=>In,mp4vSampleEntry:()=>bn,mskCBox:()=>Oi,msrcTrackGroupTypeBox:()=>wa,mvexBox:()=>Xe,mvhdBox:()=>Mt,mvifSampleGroupEntry:()=>Ba,nmhdBox:()=>Re,npckBox:()=>ki,numpBox:()=>Ai,padbBox:()=>Mi,panoBox:()=>oi,paspBox:()=>Ni,paylBox:()=>Pi,paytBox:()=>Fi,pdinBox:()=>Ii,piffLsmBox:()=>to,piffPsshBox:()=>no,piffSencBox:()=>ro,piffTencBox:()=>io,piffTfrfBox:()=>ao,piffTfxdBox:()=>oo,pitmBox:()=>kt,pixiBox:()=>Li,pmaxBox:()=>Ri,povdBox:()=>gt,prdiBox:()=>zi,prfrBox:()=>Bi,prftBox:()=>Vi,prgrBox:()=>di,profBox:()=>Yi,prolSampleGroupEntry:()=>Va,psshBox:()=>Hi,pymdBox:()=>fi,rapSampleGroupEntry:()=>Ha,rashSampleGroupEntry:()=>Ua,resvSampleEntry:()=>zn,rinfBox:()=>st,rollSampleGroupEntry:()=>Wa,rtp_Box:()=>Zi,saioBox:()=>Qi,saizBox:()=>$i,sbgpBox:()=>Gn,sbpmBox:()=>ta,sbttSampleEntry:()=>Bn,schiBox:()=>ct,schmBox:()=>na,scifSampleGroupEntry:()=>Ga,scnmSampleGroupEntry:()=>Ka,sdp_Box:()=>ra,sdtpBox:()=>Kn,seigSampleGroupEntry:()=>qa,sencBox:()=>ia,sgpdBox:()=>qn,sidxBox:()=>Jn,sinfBox:()=>ot,skipBox:()=>Ie,slidBox:()=>si,smhdBox:()=>Yn,sratBox:()=>oa,ssixBox:()=>pr,stblBox:()=>Ye,stcoBox:()=>Xn,stdpBox:()=>sa,sterBox:()=>ci,sthdBox:()=>Zn,stppSampleEntry:()=>Vn,strdBox:()=>at,striBox:()=>ca,strkBox:()=>it,stsaSampleGroupEntry:()=>Ja,stscBox:()=>Qn,stsdBox:()=>$n,stsgBox:()=>la,stshBox:()=>ua,stssBox:()=>da,stszBox:()=>er,sttsBox:()=>tr,stviBox:()=>fa,stxtSampleEntry:()=>Hn,stypBox:()=>mr,stz2Box:()=>pa,subsBox:()=>ma,syncSampleGroupEntry:()=>Ya,taicBox:()=>ha,taptBox:()=>Xi,teleSampleGroupEntry:()=>Xa,tencBox:()=>ga,tfdtBox:()=>nr,tfhdBox:()=>rr,tfraBox:()=>va,tkhdBox:()=>ir,tmaxBox:()=>ya,tminBox:()=>ba,totlBox:()=>xa,tpayBox:()=>Sa,tpylBox:()=>Ca,trafBox:()=>Qe,trakBox:()=>We,trefBox:()=>Ta,trepBox:()=>Ea,trexBox:()=>ar,trgrBox:()=>lt,trpyBox:()=>Da,trunBox:()=>or,tsasSampleGroupEntry:()=>Za,tsclSampleGroupEntry:()=>Qa,tselBox:()=>Oa,tsynBox:()=>li,tx3gSampleEntry:()=>Un,txtcBox:()=>ka,tycoBox:()=>Aa,udesBox:()=>ja,udtaBox:()=>ut,uncCBox:()=>Ma,uncvSampleEntry:()=>yn,urlBox:()=>sr,urnBox:()=>Na,viprSampleGroupEntry:()=>$a,vmhdBox:()=>cr,vp08SampleEntry:()=>pn,vp09SampleEntry:()=>mn,vpcCBox:()=>zt,vttCBox:()=>Pa,vttcBox:()=>$e,vvc1SampleEntry:()=>cn,vvcCBox:()=>Bt,vvcNSampleEntry:()=>dn,vvi1SampleEntry:()=>ln,vvnCBox:()=>Fa,vvs1SampleEntry:()=>un,waveBox:()=>Lt,wbbrBox:()=>ui,wvttSampleEntry:()=>Wn,xmlBox:()=>Be})),Ee(hr);function lo(e){let t=0,n=.005;for(let r of[23.976,24,25,29.97,30,48,50,59.94,60,120,240]){let i=Math.abs(e-r)/r;i`u`)return null;let t=A.fromArrayBuffer(await e.arrayBuffer(),0),n=dr(),r=null,i=[];n.onReady=e=>{r=e;let t=e.videoTracks[0];t&&(n.setExtractionOptions(t.id,null,{nbSamples:2**53-1}),n.start())},n.onSamples=(e,t,n)=>{i.push(...n)},n.onError=()=>{};try{n.appendBuffer(t),n.flush()}catch{return null}let a=r,o=a?.videoTracks[0];if(!a||!o)return null;let s={codec:o.codec.startsWith(`vp08`)?`vp8`:o.codec,codedWidth:o.video.width,codedHeight:o.video.height,description:uo(n,o.id)};if(!(await VideoDecoder.isConfigSupported(s).catch(()=>({supported:!1}))).supported||!i.length)return null;i.sort((e,t)=>e.dts-t.dts);let c=o.duration/o.timescale||i.length/30,l={width:o.video.width,height:o.video.height,fps:lo(i.length/c),frameCount:i.length,codec:o.codec},u=i.map(e=>new EncodedVideoChunk({type:e.is_sync?`key`:`delta`,timestamp:1e6*e.cts/e.timescale,duration:1e6*e.duration/e.timescale,data:e.data}));return i.length=0,{info:l,frames:po(s,u)}}async function*po(e,t){let n=[],r=null,i=null,a=()=>{i?.(),i=null},o=new VideoDecoder({output:e=>{n.push(e),a()},error:e=>{r=e,a()}});o.addEventListener(`dequeue`,a),o.configure(e);let s=0,c=!1,l=!1;try{for(;;){for(;s=t.length&&!c&&(c=!0,o.flush().then(()=>{l=!0,a()},e=>{r=e,a()})),n.length)yield n.shift();else{if(r)throw r;if(l)return;await new Promise(e=>{i=e})}}}finally{for(let e of n)e.close();o.state!==`closed`&&o.close()}}function mo(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function ho(e,t,n,r){let i=[],a=[],o=0;for(let t=0;t>1;a[e]<=n?l=e+1:u=e}let d=i[l];c[e]=d,s[2*e]=d%t+r(),s[2*e+1]=Math.floor(d/t)+r()}return{uv:s,pixel:c,area:o}}function go(e,t,n,r,i,a,o){let s=Math.min(Math.max(r/a*t-.5,0),t-1),c=Math.min(Math.max(i/o*n-.5,0),n-1),l=Math.floor(s),u=Math.floor(c),d=Math.min(l+1,t-1),f=Math.min(u+1,n-1),p=s-l,m=c-u,h=e[u*t+l],g=e[u*t+d],_=e[f*t+l],v=e[f*t+d];return(h*(1-p)+g*p)*(1-m)+(_*(1-p)+v*p)*m}function _o(e,t,n,r,i,a,o,s){let c=Math.min(Math.max(i/o*n-.5,0),n-1),l=Math.min(Math.max(a/s*r-.5,0),r-1),u=Math.floor(c),d=Math.floor(l),f=Math.min(u+1,n-1),p=Math.min(d+1,r-1),m=c-u,h=l-d,g=0,_=0,v=(n,r)=>{t[n]&&r>0&&(g+=e[n]*r,_+=r)};if(v(d*n+u,(1-m)*(1-h)),v(d*n+f,m*(1-h)),v(p*n+u,(1-m)*h),v(p*n+f,m*h),_>0)return g/_;let y=Math.round(l)*n+Math.round(c);return t[y]?e[y]:NaN}const Z=(e,t=[])=>self.postMessage(e,t);let vo=0;function Q(e,t,n=!1){let r=performance.now();!n&&r-vo<100||(vo=r,Z({type:`progress`,stage:e,fraction:t}))}const yo=[];let bo=null,xo=null;async function*So(){for(;;){for(;!yo.length;)await new Promise(e=>{bo=e});let e=yo.shift();if(!e)return;Z({type:`ack`}),yield e}}let $=null;self.onmessage=e=>{let t=e.data,n=e=>Z({type:`error`,message:e?.message??String(e)});if(t.type===`start`)Do(t).catch(n);else if(t.type===`rebuild`)try{if(!$)throw Error(`nothing imported to rebuild`);Co($.builder,t.settings,$.depth,$.note)}catch(e){n(e)}else t.type===`info`?xo=t.info:(t.type===`frame`||t.type===`end`)&&(yo.push(t.type===`frame`?t.bitmap:null),bo?.(),bo=null)};function Co(e,t,n,r){let i=e.finish(t),a=[i.position.buffer,i.time.buffer,i.color.buffer];i.frameStart&&a.push(i.frameStart.buffer),Z({type:`done`,block:i,depth:n,note:r,maxPointsPerFrame:e.o.pointsPerFrame},a)}async function wo(e){if(e===`standin`)return{est:new b,note:`stand-in depth requested`};try{let{loadDepthModel:e}=await import(`./depthModel-BEeGmccg.js`);return{est:await e(e=>Q(`Loading depth model ${Math.round(e*100)}%`,.08+.04*e))}}catch(e){return{est:new b,note:`depth model unavailable (${e?.message??e}); used a silhouette stand-in`}}}async function*To(e,t){let n=await fo(e);if(n){let e=0;for await(let r of n.frames)e%t===0?yield[e,r]:r.close(),e++;return}yo.length=0,Z({type:`need-frames`,step:t});let r=0;for await(let e of So())yield[r,e],r+=t}async function Eo(e){let t=await fo(e);if(t)return await t.frames.return(void 0),t.info;for(xo=null,Z({type:`need-frames`,step:0});!xo;)await new Promise(e=>{bo=e});for await(let e of So())e.close();return xo}async function Do(e){$=null,Q(`Reading video`,0,!0);let t=await Eo(e.file),n=Math.min(1,960/Math.max(t.width,t.height)),r=Math.max(2,Math.round(t.width*n)),i=Math.max(2,Math.round(t.height*n)),a=Math.min(1,518/Math.max(r,i)),o=Math.max(14,Math.round(r*a)),l=Math.max(14,Math.round(i*a)),u=new OffscreenCanvas(r,i).getContext(`2d`,{willReadFrequently:!0}),d=new OffscreenCanvas(o,l).getContext(`2d`,{willReadFrequently:!0}),m=e=>(u.drawImage(e,0,0,r,i),u.getImageData(0,0,r,i).data),h=null,_=null;if(e.plate){let n=Math.max(1,Math.floor(t.frameCount/32)),a=[];for await(let[o,l]of To(e.file,n)){try{if(a.length>=32)continue;let e=m(l);a.push(e),_=c(_,s(e,r,i),1/a.length)}finally{l.close()}Q(`Reading the empty screen`,.06*(o/t.frameCount))}Q(`Reading the empty screen`,.06,!0),_&&(h=f(a,r,i,_))}Q(`Loading depth model`,.08,!0);let{est:v,note:y}=await wo(e.depth),x=Math.max(1,Math.min(e.settings.pointsPerFrame,Math.floor(6e6/Math.max(1,t.frameCount)))),S=null,C=mo(1),T=0;for await(let[n,a]of To(e.file,1)){try{if(n>=t.frameCount)continue;let u=m(a);h||(_=c(_,s(u,r,i),n===0?1:.1));let f=h?h.key:_;S??=new ne({width:r,height:i,fps:t.fps,frameCount:t.frameCount,pointsPerFrame:x,channel:f.channel,meta:{generator:`v4d-viewer video import 0.2.0`,source:e.file.name,srcFps:t.fps,srcSize:[t.width,t.height],depth:v.name,cleanPlate:!!h,snapEdges:e.snap,...y?{depthNote:y}:{}}});let T=g(p(u,r,i,f,void 0,h),r,i),E=ho(T,r,x,C);if(E.area>=5e-4*r*i){let t;v instanceof b?t=await v.estimate({rgba:u,width:r,height:i,alpha:T}):(d.drawImage(a,0,0,o,l),t=await v.estimate({rgba:d.getImageData(0,0,o,l).data,width:o,height:l,alpha:T}));let s=e.snap?D(t,w(T,r,i,t.width,t.height)):null,c=(e,n)=>s?_o(s.data,s.known,t.width,t.height,e,n,r,i):go(t.data,t.width,t.height,e,n,r,i),p=E.pixel.length,m=new Float32Array(2*p),g=new Float32Array(p),_=new Uint8Array(3*p),y=new Float32Array(p),x=new Uint8Array(3*p),C=0;for(let e=0;e>6|192;else{if(t>=55296&&t<=57343){if(t<=56319&&i=56320&&a<=57343){t=1024*(t-55296)+a-56320+65536,r[n++]=t>>18|240,r[n++]=t>>12&63|128,r[n++]=t>>6&63|128,r[n++]=63&t|128;continue}i--}t=65533}r[n++]=t>>12|224,r[n++]=t>>6&63|128}r[n++]=63&t|128}}e=n===r.length?r:r.subarray(0,n)}return e}function d(t){e.setTimeout(()=>{throw t},0)}var ee=t(610401301,!1),te=t(748402147,!0);function ne(){var t=e.navigator;return(t&&=t.userAgent)?t:``}var re,ie=e.navigator;function ae(e){return ae[` `](e),e}re=ie&&ie.userAgentData||null,ae[` `]=function(){};var oe={},se=null;function ce(e){var t=e.length,n=3*t/4;n%3?n=Math.floor(n):`=.`.indexOf(e[t-1])!=-1&&(n=`=.`.indexOf(e[t-2])==-1?n-1:n-2);var r=new Uint8Array(n),i=0;return function(e,t){function n(t){for(;r>4),i!=64&&(t(r<<4&240|i>>2),a!=64&&t(i<<6&192|a))}}(e,function(e){r[i++]=e}),i===n?r:r.subarray(0,i)}function le(){if(!se){se={};var e=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``),t=[`+/=`,`+/`,`-_=`,`-_.`,`-_`];for(let n=0;n<5;n++){let r=e.concat(t[n].split(``));oe[n]=r;for(let e=0;e0)||ne().indexOf(`Trident`)==-1&&ne().indexOf(`MSIE`)==-1)&&typeof btoa==`function`,fe=/[-_.]/g,pe={"-":`+`,_:`/`,".":`=`};function me(e){return pe[e]||``}function he(e){if(!de)return ce(e);e=fe.test(e)?e.replace(fe,me):e,e=atob(e);var t=new Uint8Array(e.length);for(let n=0;n=t||(n[e]=r+1,Ce(e=Error(),`incident`),d(e))}}function De(){return typeof BigInt==`function`}var Oe=typeof Symbol==`function`&&typeof Symbol()==`symbol`;function ke(e,t,n=!1){return typeof Symbol==`function`&&typeof Symbol()==`symbol`?n&&Symbol.for&&e?Symbol.for(e):e==null?Symbol():Symbol(e):t}var Ae,je=ke(`jas`,void 0,!0),Me=ke(void 0,`0di`),Ne=ke(void 0,`1oa`),Pe=ke(void 0,Symbol()),Fe=ke(void 0,`0ub`),Ie=ke(void 0,`0ubs`),Le=ke(void 0,`0ubsb`),Re=ke(void 0,`0actk`),ze=ke(`m_m`,`lb`,!0),Be=ke(),Ve={Wa:{value:0,configurable:!0,writable:!0,enumerable:!1}},He=Object.defineProperties,f=Oe?je:`Wa`,Ue=[];function We(e,t){Oe||f in e||He(e,Ve),e[f]|=t}function p(e,t){Oe||f in e||He(e,Ve),e[f]=t}function Ge(e){return We(e,34),e}function Ke(e){return We(e,8192),e}p(Ue,7),Ae=Object.freeze(Ue);var qe={};function Je(e,t){return t===void 0?e.i!==Ye&&!!(2&e.B[f]):!!(2&t)&&e.i!==Ye}var Ye={};function Xe(e,t){if(e!=null){if(typeof e==`string`)e=e?new xe(e,_e):ve();else if(e.constructor!==xe){if(ge(e))e=e.length?new xe(new Uint8Array(e),_e):ve();else{if(!t)throw Error();e=void 0}}}return e}var Ze=class{constructor(e,t,n){this.h=e,this.i=t,this.l=n}next(){var e=this.h.next();return e.done||(e.value=this.i.call(this.l,e.value)),e}[Symbol.iterator](){return this}},Qe=Object.freeze({});function $e(e,t,n){var r,i=128&t?0:-1,a=e.length;(r=!!a)&&(r=(r=e[a-1])!=null&&typeof r==`object`&&r.constructor===Object);var o=a+(r?-1:0);for(t=128&t?1:0;ttypeof e==`number`),it=nt(e=>typeof e==`string`),at=nt(e=>typeof e==`boolean`),ot=typeof e.BigInt==`function`&&typeof e.BigInt(0)==`bigint`;function m(e){var t=e;if(it(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(rt(t)&&!Number.isSafeInteger(t))throw Error(String(t));return ot?BigInt(e):e=at(e)?e?`1`:`0`:it(e)?e.trim()||`0`:String(e)}var st=nt(e=>ot?e>=lt&&e<=dt:e[0]===`-`?ft(e,ct):ft(e,ut)),ct=(-(2**53-1)).toString(),lt=ot?BigInt(-(2**53-1)):void 0,ut=(2**53-1).toString(),dt=ot?BigInt(2**53-1):void 0;function ft(e,t){if(e.length>t.length)return!1;if(e.lengthi)return!1;if(r>>0;h=t,g=(e-t)/4294967296>>>0}function gt(e){if(e<0){ht(-e);let[t,n]=Tt(h,g);h=t>>>0,g=n>>>0}else ht(e)}function _t(e){var t=pt||=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));t.setFloat32(0,+e,!0),g=0,h=t.getUint32(0,!0)}function vt(e,t){var n=4294967296*t+(e>>>0);return Number.isSafeInteger(n)?n:xt(e,t)}function yt(e,t){return m(De()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):xt(e,t))}function bt(e,t){return De()?m(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=``+(4294967296*t+e);else De()?n=``+(BigInt(t)<>>24|t<<8))+6710656*(t=t>>16&65535),n+=8147497*t,t*=2,e>=1e7&&(n+=e/1e7>>>0,e%=1e7),n>=1e7&&(t+=n/1e7>>>0,n%=1e7),n=t+St(n)+St(e));return n}function St(e){return e=String(e),`0000000`.slice(e.length)+e}function Ct(e,t){if(2147483648&t){if(De())e=``+(BigInt(0|t)<>>0));else{let[n,r]=Tt(e,t);e=`-`+xt(n,r)}}else e=xt(e,t);return e}function wt(e){if(e.length<16)gt(Number(e));else if(De())e=BigInt(e),h=Number(e&BigInt(4294967295))>>>0,g=Number(e>>BigInt(32)&BigInt(4294967295));else{let t=+(e[0]===`-`);g=h=0;let n=e.length;for(let r=t,i=(n-t)%6+t;i<=n;r=i,i+=6){let t=Number(e.slice(r,i));g*=1e6,(h=1e6*h+t)>=4294967296&&(g+=Math.trunc(h/4294967296),g>>>=0,h>>>=0)}if(t){let[e,t]=Tt(h,g);h=e,g=t}}}function Tt(e,t){return t=~t,e?e=1+~e:t+=1,[e,t]}function Et(e){return Array.prototype.slice.call(e)}var Dt=typeof BigInt==`function`?BigInt.asIntN:void 0,Ot=typeof BigInt==`function`?BigInt.asUintN:void 0,kt=Number.isSafeInteger,At=Number.isFinite,jt=Math.trunc,Mt=m(0);function Nt(e){if(typeof e!=`number`)throw Error(`Value of float/double field must be a number, found ${typeof e}: ${e}`);return e}function Pt(e){return e==null||typeof e==`number`?e:e===`NaN`||e===`Infinity`||e===`-Infinity`?Number(e):void 0}function Ft(e){if(typeof e!=`boolean`){var t=typeof e;throw Error(`Expected boolean but got ${t==`object`?e?Array.isArray(e)?`array`:t:`null`:t}: ${e}`)}return e}var It=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function Lt(e){switch(typeof e){case`bigint`:return!0;case`number`:return At(e);case`string`:return It.test(e);default:return!1}}function Rt(e){if(e!=null){if(!At(e))throw Te(`enum`);e|=0}return e}function zt(e){if(e==null)return e;if(typeof e==`string`&&e)e=+e;else if(typeof e!=`number`)return;return At(e)?0|e:void 0}function Bt(e){if(e==null)return e;if(typeof e==`string`&&e)e=+e;else if(typeof e!=`number`)return;return At(e)?e>>>0:void 0}function Vt(e,t){if(t??=1024,!Lt(e))throw Te(`int64`);var n=typeof e;switch(t){case 512:switch(n){case`string`:return qt(e);case`bigint`:return String(Dt(64,e));default:return Kt(e)}case 1024:switch(n){case`string`:return Jt(e);case`bigint`:return m(Dt(64,e));default:return Yt(e)}case 0:switch(n){case`string`:return qt(e);case`bigint`:return m(Dt(64,e));default:return Wt(e)}default:return function(e,t=`unexpected value ${e}!`){throw Error(t)}(t,`Unknown format requested type for int64`)}}function Ht(e){var t=e.length;return(e[0]===`-`?t<20||t===20&&e<=`-9223372036854775808`:t<19||t===19&&e<=`9223372036854775807`)?e:(wt(e),Ct(h,g))}function Ut(e){if(e[0]===`-`)var t=!1;else t=(t=e.length)<20||t===20&&e<=`18446744073709551615`;return t?e:(wt(e),xt(h,g))}function Wt(e){if(e=jt(e),!kt(e)){gt(e);var t=h,n=g;(e=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),e=typeof(t=vt(t,n))==`number`?e?-t:t:e?`-`+t:t}return e}function Gt(e){return(e=jt(e))>=0&&kt(e)||(gt(e),e=vt(h,g)),e}function Kt(e){return e=jt(e),kt(e)?e=String(e):(gt(e),e=Ct(h,g)),e}function qt(e){var t=jt(Number(e));return kt(t)?String(t):((t=e.indexOf(`.`))!==-1&&(e=e.substring(0,t)),Ht(e))}function Jt(e){var t=jt(Number(e));return kt(t)?m(t):((t=e.indexOf(`.`))!==-1&&(e=e.substring(0,t)),De()?m(Dt(64,BigInt(e))):m(Ht(e)))}function Yt(e){return kt(e)?m(Wt(e)):m(Kt(e))}function Xt(e){var t=typeof e;return e==null?e:t===`bigint`?m(Dt(64,e)):Lt(e)?t===`string`?Jt(e):Yt(e):void 0}function Zt(e){if(e==null)return e;var t=typeof e;if(t===`bigint`)return String(Dt(64,e));if(Lt(e)){if(t===`string`)return qt(e);if(t===`number`)return Wt(e)}}function Qt(e){if(e==null||typeof e==`string`||e instanceof xe)return e}function $t(e){if(typeof e!=`string`)throw Error();return e}function en(e){if(e!=null&&typeof e!=`string`)throw Error();return e}function _(e){return e==null||typeof e==`string`?e:void 0}function tn(e,t,n,r){return e!=null&&e[ze]===qe?e:Array.isArray(e)?((r=(n=0|e[f])|32&r|2&r)!==n&&p(e,r),new t(e)):(n?2&r?((e=t[Me])||(Ge((e=new t).B),e=t[Me]=e),t=e):t=new t:t=void 0,t)}function nn(e,t,n){return(e=t?Vt(e,1024):Xt(e))??(n?Mt:void 0)}function rn(e){return e}var an={},on=function(){try{return ae(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),sn=class{constructor(){this.h=/* @__PURE__ */ new Map}get(e){return this.h.get(e)}set(e,t){return this.h.set(e,t),this.size=this.h.size,this}delete(e){return e=this.h.delete(e),this.size=this.h.size,e}clear(){this.h.clear(),this.size=this.h.size}has(e){return this.h.has(e)}entries(){return this.h.entries()}keys(){return this.h.keys()}values(){return this.h.values()}forEach(e,t){return this.h.forEach(e,t)}[Symbol.iterator](){return this.entries()}},cn=on?(Object.setPrototypeOf(sn.prototype,Map.prototype),Object.defineProperties(sn.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),sn):class extends Map{constructor(){super()}};function ln(e){return e}function un(e){if(2&e.N)throw Error(`Cannot mutate an immutable Map`)}var dn,fn=class extends cn{constructor(e,t,n=ln,r=ln){super(),this.N=0|e[f],this.O=t,this.ca=n,this.oa=this.O?pn:r;for(let i=0;i{e.call(t,i.get(r),r,i)}):super.forEach(e,t)}set(e,t){return un(this),(e=this.ca(e,!0,!1))==null?this:t==null?(super.delete(e),this):super.set(e,this.oa(t,!0,!0,this.O,!1,this.N))}hb(e){var t=this.ca(e[0],!1,!0);e=e[1],e=this.O?e===void 0?null:e:this.oa(e,!1,!0,void 0,!1,this.N),super.set(t,e)}has(e){return super.has(this.ca(e,!1,!1))}get(e){e=this.ca(e,!1,!1);var t=super.get(e);if(t!==void 0){var n=this.O;return n?((n=this.oa(t,!1,!0,n,this.Ga,this.N))!==t&&super.set(e,n),n):t}}[Symbol.iterator](){return this.entries()}};function pn(e,t,n,r,i,a){return e=tn(e,r,n,a),i&&(e=Pn(e)),e}function mn(e){return[e,this.get(e)]}function hn(){return dn||=new fn(Ge([]),void 0,void 0,void 0,an)}function gn(e){return Pe?e[Pe]:void 0}function _n(e,t){for(let n in e)!isNaN(n)&&t(e,+n,e[n])}fn.prototype.toJSON=void 0;var vn,yn,bn=class{},xn={eb:!0};function Sn(e,t){t<100||Ee(Ie,1)}function Cn(e,t,n,r){var i=r!==void 0;r=!!r;var a,o=Pe;!i&&Oe&&o&&(a=e[o])&&_n(a,Sn),o=[];var s=e.length;a=4294967295;var c=!1,l=!!(64&t),u=l?128&t?0:-1:void 0;if(!(1&t)){var d=s&&e[s-1];typeof d==`object`&&d&&d.constructor===Object?a=--s:d=void 0,!l||128&t||i||(c=!0,a=rn(a-u,u,e,d,void 0)+u)}t=void 0;for(var ee=0;ee=a){let e=ee-u;(t??={})[e]=i}else o[ee]=i}}if(d)for(let e in d){if((s=d[e])==null||(s=n(s,r))==null)continue;let i;ee=+e,l&&!Number.isNaN(ee)&&(i=ee+u){t[n]=Et(r)}),t.la=e.la,t}(e)),o}function wn(e){return e[0]=Tn(e[0]),e[1]=Tn(e[1]),e}function Tn(e){switch(typeof e){case`number`:return Number.isFinite(e)?e:``+e;case`bigint`:return st(e)?Number(e):``+e;case`boolean`:return+!!e;case`object`:if(Array.isArray(e)){var t=0|e[f];return e.length===0&&1&t?void 0:Cn(e,t,Tn)}if(e!=null&&e[ze]===qe)return En(e);if(e instanceof xe){if((t=e.h)==null)e=``;else if(typeof t==`string`)e=t;else{if(de){for(var n=``,r=0,i=t.length-10240;r>2];a=n[(3&a)<<4|o>>4],o=n[(15&o)<<2|s>>6],s=n[63&s],r[l++]=c+a+o+s}switch(c=0,s=i,t.length-e){case 2:s=n[(15&(c=t[e+1]))<<2]||i;case 1:t=t[e],r[l]=n[t>>2]+n[(3&t)<<4|c>>4]+s+i}t=r.join(``)}e=e.h=t}return e}return e instanceof fn?e=e.size===0?void 0:e.fa(wn):void 0}return e}function En(e){return Cn(e=e.B,0|e[f],Tn)}function Dn(e,t){return On(e,t[0],t[1])}function On(e,t,n,r=0){if(e==null){var i=32;n?(e=[n],i|=128):e=[],t&&(i=-16760833&i|(1023&t)<<14)}else{if(!Array.isArray(e))throw Error(`narr`);if(i=0|e[f],te&&1&i)throw Error(`rfarr`);if(2048&i&&!(2&i)&&function(){if(te)throw Error(`carr`);Ee(Re,5)}(),256&i)throw Error(`farr`);if(64&i)return(i|r)!==i&&p(e,i|r),e;if(n&&(i|=128,n!==e[0]))throw Error(`mid`);t:{i|=64;var a=(n=e).length;if(a){var o=a-1;let e=n[o];if(typeof e==`object`&&e&&e.constructor===Object){if((o-=t=128&i?0:-1)>=1024)throw Error(`pvtlmt`);for(var s in e)(a=+s)1024)throw Error(`spvt`);i=-16760833&i|(1023&s)<<14}}}return p(e,64|i|r),e}function kn(e,t){if(typeof e!=`object`)return e;if(Array.isArray(e)){var n=0|e[f];return e.length===0&&1&n?void 0:An(e,n,t)}if(e!=null&&e[ze]===qe)return Mn(e);if(e instanceof fn){if(2&(t=e.N))return e;if(!e.size)return;if(n=Ge(e.fa()),e.O)for(e=0;e=a){var o=e[a];if(typeof o==`object`&&o&&o.constructor===Object){n=o[t];var s=!0}else{if(i!==a)return;n=o}}else n=e[i];if(r&&n!=null){if((r=r(n))==null)return r;if(!Object.is(r,n))return s?o[t]=r:e[i]=r,r}return n}}function y(e,t,n,r){In(e);var i=e.B;return b(i,0|i[f],t,n,r),e}function b(e,t,n,r,i){var a=n+(i?0:-1),o=e.length-1;if(o>=1+(i?0:-1)&&a>=o){let i=e[o];if(typeof i==`object`&&i&&i.constructor===Object)return i[n]=r,t}return a<=o?(e[a]=r,t):(r!==void 0&&(n>=(o=(t??=0|e[f])>>14&1023||536870912)?r!=null&&(e[o+(i?0:-1)]={[n]:r}):e[a]=r),t)}function Hn(e,t,n,r){var i=e.B;return ir(i,0|i[f],t,e=$n(e,r)===n?n:-1)!==void 0}function Un(){return Qe===void 0?2:4}function Wn(e,t,n,r,i){var a=e.B,o=0|a[f];r=Je(e,o)?1:r,i=!!i||r===3,r===2&&Fn(e)&&(o=0|(a=e.B)[f]);var s=(e=Kn(a,t))===Ae?7:0|e[f],c=qn(s,o),l=!(4&c);if(l){4&c&&(e=Et(e),s=0,c=ur(c,o),o=b(a,o,t,e));let r=0,i=0;for(;r{var r=tn(e,n,!1,t);return a=r!==e&&r!=null,r}))!=null)return a&&!Je(r)&&Ln(e,t),r}function x(e,t,n,r){var i=e.B,a=0|i[f];if((t=ir(i,a,t,n,r))==null)return t;if(!Je(e,a=0|i[f])){let o=Pn(t);o!==t&&(Fn(e)&&(a=0|(i=e.B)[f]),Ln(i,a=b(i,a,n,t=o,r)))}return t}function ar(e,t,n,r,i,a,o,s){var c=Je(e,n);a=c?1:a,o=!!o||a===3,c=s&&!c,(a===2||c)&&Fn(e)&&(n=0|(t=e.B)[f]);var l=(e=Kn(t,i))===Ae?7:0|e[f],u=qn(l,n);if(s=!(4&u)){var d=e,ee=n;let t=!!(2&u);t&&(ee|=2);let i=!t,a=!0,o=0,s=0;for(;o=0?e=m(t):((t=e.indexOf(`.`))!==-1&&(e=e.substring(0,t)),e=De()?m(Ot(64,BigInt(e))):m(Ut(e))),e;case`bigint`:return m(Ot(64,e));default:return kt(e)?e=m(Gt(e)):((e=jt(e))>=0&&kt(e)?e=String(e):(gt(e),e=xt(h,g)),e=m(e)),e}}(n))}function w(e,t,n){y(e,t,n==null?n:Nt(n))}function vr(e,t,n){Zn(e,t,n==null?n:Nt(n),0)}function yr(e,t,n){Zn(e,t,en(n),``)}function br(e,t,n){{In(e);let o=e.B,s=0|o[f];if(n==null)b(o,s,t);else{var r=e=n===Ae?7:0|n[f],i=Jn(e),a=i||Object.isFrozen(n);for(i||(e=0),a||=(n=Et(n),r=0,e=ur(e,s),!1),e|=5,e|=(4&e?512&e?512:1024&e?1024:0:void 0)??1024,i=0;i32)for(r|=(127&s)>>4,i=3;i<32&&128&s;i+=7)r|=(127&(s=a[o++]))<>>0,r>>>0);throw Error()}function Tr(e){for(var t=0,n=e.h,r=n+10,i=e.i;n>>0}function Or(e){return wr(e,bt)}function kr(e){var t=e.i,n=e.h,r=t[n],i=t[n+1],a=t[n+2];return t=t[n+3],Mr(e,e.h+4),(r|i<<8|a<<16|t<<24)>>>0}function Ar(e){var t=kr(e);e=2*(t>>31)+1;var n=t>>>23&255;return t&=8388607,n==255?t?NaN:1/0*e:n==0?1401298464324817e-60*e*t:e*2**(n-150)*(t+8388608)}function jr(e){return Er(e)}function Mr(e,t){if(e.h=t,t>e.l)throw Error()}function Nr(e,t){if(t<0)throw Error();var n=e.h;if((t=n+t)>e.l)throw Error();return e.h=t,n}function Pr(e,t){if(t==0)return ve();var n=Nr(e,t);return e.ga&&e.u?n=e.i.subarray(n,n+t):(e=e.i,n=n===(t=n+t)?/* @__PURE__ */ new Uint8Array:mt?e.slice(n,t):new Uint8Array(e.subarray(n,t))),n.length==0?ve():new xe(n,_e)}var Fr=class{constructor(e,t,n,r){this.i=null,this.u=!1,this.h=this.l=this.o=0,this.init(e,t,n,r)}init(e,t,n,{ga:r=!1,na:i=!1}={}){this.ga=r,this.na=i,e&&(e=Cr(e,this.na),this.i=e.buffer,this.u=e.h,this.o=t||0,this.l=n===void 0?this.i.length:this.o+n,this.h=this.o)}clear(){this.i=null,this.u=!1,this.h=this.l=this.o=0,this.ga=!1}},Ir=[],Lr=0;function Rr(e,t,n,r){if(Jr.length){let i=Jr.pop();return i.A(r),i.h.init(e,t,n,r),i}return new qr(e,t,n,r)}function zr(e){e.h.clear(),e.l=-1,e.i=-1,Jr.length<100&&Jr.push(e)}function Br(e){var t=e.h;if(t.h==t.l)return!1;e.o=e.h.h;var n=Dr(e.h);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return e.l=t,e.i=n,!0}function Vr(e){try{switch(e.i){case 0:e.i==0?Tr(e.h):Vr(e);break;case 1:var t=e.h;Mr(t,t.h+8);break;case 2:if(e.i!=2)Vr(e);else{var n=Dr(e.h),r=e.h;Mr(r,r.h+n)}break;case 5:var i=e.h;Mr(i,i.h+4);break;case 3:Hr();let a=e.l;try{for(;;){if(!Br(e))throw Error();if(e.i==4){if(e.l!=a)throw Error();break}Vr(e)}}catch(e){throw e instanceof RangeError?SyntaxError():e}finally{Lr>0&&Lr--}break;default:throw Error()}}catch(e){throw e instanceof RangeError?SyntaxError():e}}function Hr(){if(Lr>=100)throw SyntaxError();Lr++}function Ur(e,t,n){var r=e.h.l,i=Dr(e.h),a=(i=e.h.h+i)-r;if(a<=0&&(e.h.l=i,n(t,e,void 0,void 0,void 0),a=i-e.h.h),a)throw Error();return e.h.h=i,e.h.l=r,t}function Wr(e){var t=Dr(e.h),n=Nr(e=e.h,t);if(e=e.i,c){var o,l=e;(o=a)||(o=a=new TextDecoder(`utf-8`,{fatal:!0})),t=n+t,l=n===0&&t===l.length?l:l.subarray(n,t);try{var u=o.decode(l)}catch(e){if(s===void 0){try{o.decode(new Uint8Array([128]))}catch{}try{o.decode(new Uint8Array([97])),s=!0}catch{s=!1}}throw!s&&(a=void 0),e}}else{t=(u=n)+t,n=[];let a,s=null;for(;u=t?r():(a=e[u++],d<194||(192&a)!=128?(u--,r()):n.push((31&d)<<6|63&a)):d<240?u>=t-1?r():(a=e[u++],(192&a)!=128||d===224&&a<160||d===237&&a>=160||(192&(o=e[u++]))!=128?(u--,r()):n.push((15&d)<<12|(63&a)<<6|63&o)):d<=244?u>=t-2?r():(a=e[u++],(192&a)!=128||a-144+(d<<28)>>30||(192&(o=e[u++]))!=128||(192&(l=e[u++]))!=128?(u--,r()):(d=(7&d)<<18|(63&a)<<12|(63&o)<<6|63&l,d-=65536,n.push(55296+(d>>10&1023),56320+(1023&d)))):r(),n.length>=8192&&(s=i(s,n),n.length=0)}u=i(s,n)}return u}function Gr(e){var t=Dr(e.h);return Pr(e.h,t)}function Kr(e,t,n){var r=Dr(e.h);for(r=e.h.h+r;e.h.h>>0,this.h=t>>>0}};function $r(e){return new li(0|e,Math.floor(e/4294967296))}function ei(e){return e?/^-?\d+$/.test(e)?(wt(e),new li(h,g)):null:ti||=new li(0,0)}var ti,ni,ri,ii,ai,oi,si,ci,li=class{constructor(e,t){this.i=e>>>0,this.h=t>>>0}};function ui(e,t,n){return typeof BigInt64Array<`u`?(si||(si=/* @__PURE__ */ new BigInt64Array(1),ci=new Uint32Array(si.buffer),si[0]=BigInt(1),oi=ci[0]===1),si[0]=e,new t(ci[e=+!oi],ci[1-e])):(ai||=(ni=BigInt(-(2**53-1)),ri=BigInt(2**53-1),ii=BigInt(4294967295),BigInt(32)),e>=ni&&e<=ri?n(Number(e)):(e=BigInt.asUintN(64,e),new t(Number(e&ii),Number(e>>ai))))}function di(e,t,n){for(;n>0||t>127;)e.h.push(127&t|128),t=(t>>>7|n<<25)>>>0,n>>>=7;e.h.push(t)}function fi(e,t){for(;t>127;)e.h.push(127&t|128),t>>>=7;e.h.push(t)}function pi(e,t){if(t>=0)fi(e,t);else{for(let n=0;n<9;n++)e.h.push(127&t|128),t>>=7;e.h.push(1)}}function mi(e,t){wt(t),function(e){var t=g>>31;e(h<<1^t,(g<<1|h>>>31)^t)}((t,n)=>{di(e,t>>>0,n>>>0)})}function hi(e,t){e.h.push(t>>>0&255),e.h.push(t>>>8&255),e.h.push(t>>>16&255),e.h.push(t>>>24&255)}var gi=class{constructor(){this.h=[]}length(){return this.h.length}end(){var e=this.h;return this.h=[],e}};function _i(e,t){t.length!==0&&(e.l.push(t),e.i+=t.length)}function T(e,t,n){fi(e.h,8*t+n)}function vi(e,t){return T(e,t,2),t=e.h.end(),_i(e,t),t.push(e.i),t}function yi(e,t){var n=t.pop();for(n=e.i+e.h.length()-n;n>127;)t.push(127&n|128),n>>>=7,e.i++;t.push(n),e.i++}function bi(e,t,n){if(n!=null)switch(T(e,t,0),typeof n){case`number`:e=e.h,gt(n),di(e,h,g);break;case`bigint`:n=ui(n,li,$r),di(e.h,n.i,n.h);break;default:n=ei(n),di(e.h,n.i,n.h)}}function xi(e,t,n){T(e,t,2),fi(e.h,n.length),_i(e,e.h.end()),_i(e,n)}function Si(e,t,n,r){n!=null&&(t=vi(e,t),r(n,e),yi(e,t))}var Ci=class{constructor(){this.l=[],this.i=0,this.h=new gi}};function wi(e){typeof e==`string`&&ei(e)}function Ti(){var e=class{constructor(){throw Error()}};return Object.setPrototypeOf(e,e.prototype),e}var Ei=Ti(),Di=Ti(),Oi=Ti(),ki=Ti(),Ai=Ti(),ji=Ti(),Mi=Ti(),Ni=Ti(),Pi=Ti(),Fi=Ti(),Ii=Ti(),Li=Ti();function Ri(e,t,n){var r=e.B;Pe&&Pe in r&&(r=r[Pe])&&delete r[t.h],t.i?t.u(e,t.i,t.h,n,t.l):t.u(e,t.h,n,t.l)}var E=class{constructor(e,t){this.B=On(e,t,void 0,2048)}toJSON(){return En(this)}u(){var e=Rs,t=this.B,n=e.h,r=Pe;if(Oe&&r&&t[r]?.[n]!=null&&Ee(Fe,3),t=e.h,Be&&Pe&&Be===void 0&&(r=(n=this.B)[Pe])&&(r=r.la))try{r(n,t,xn)}catch(e){d(e)}return e.i?e.o(this,e.i,e.h,e.l):e.o(this,e.h,e.defaultValue,e.l)}clone(){var e=this.B,t=0|e[f];return Rn(this,e,t)?jn(this,e,!0):new this.constructor(Nn(e,t,!1))}};E.prototype[ze]=qe,E.prototype.toString=function(){return this.B.toString()};var zi=class{constructor(e,t,n){this.h=e,this.i=t,e=Ei,this.l=!!e&&n===e||!1}};function Bi(e,t){return new zi(e,t,Ei)}function Vi(e,t,n,r,i){Si(e,n,$i(t,r),i)}var Hi,Ui,Wi=Bi(function(e,t,n,r,i){return e.i===2&&(Ur(e,rr(t,r,n),i),!0)},Vi),Gi=Bi(function(e,t,n,r,i){return e.i===2&&(Ur(e,rr(t,r,n),i),!0)},Vi),Ki=Symbol(),qi=Symbol(),Ji=Symbol(),Yi=Symbol(),Xi=Symbol();function Zi(e,t,n,r){var i=r[e];if(i)return i;(i={}).Fa=r,i.da=function(e){switch(typeof e){case`boolean`:return vn||=[0,void 0,!0];case`number`:return e>0?void 0:e===0?yn||=[0,void 0]:[-e,void 0];case`string`:return[0,e];case`object`:return e}}(r[0]);var a=r[1],o=1;a&&a.constructor===Object&&(i.ja=a,typeof(a=r[++o])==`function`&&(i.xa=!0,Hi??=a,Ui??=r[o+1],a=r[o+=2]));for(var s={};a&&Array.isArray(a)&&a.length&&typeof a[0]==`number`&&a[0]>0;){for(var c=0;ci(e,t,n,r):i}function ta(e,t,n,r,i){var a,o,s=n.h;e[t]=(e,t,n)=>s(e,t,n,o||=Zi(qi,ea,ta,r).da,a||=na(r),i)}function na(e){var t=e[Ji];if(t!=null)return t;var n=Zi(qi,ea,ta,e);return t=n.xa?(e,t)=>Hi(e,t,n):(e,t)=>{t:{Hr();try{for(;Br(t)&&t.i!=4;){let c=t.l,l=n[c];if(l==null){let e=n.ja;if(e){let t=e[c];if(t){let e=ia(t);e!=null&&(l=n[c]=e)}}}if(l==null||!l(t,e,c)){var r=t;let n=r.o;if(Vr(r),r.sa)var i=void 0;else{let e=r.h.h-n;r.h.h=n,i=Pr(r.h,e)}r=void 0;var a=e,o=c,s=i;s&&((r=a[Pe]??(a[Pe]=new bn))[o]??(r[o]=[])).push(s)}}let l=gn(e);l&&(l.la=n.Fa[Xi]);var c=!0;break t}catch(e){throw e instanceof RangeError?SyntaxError():e}finally{Lr>0&&Lr--}}return c},e[Ji]=t,e[Xi]=ra.bind(e),t}function ra(e,t,n,r){var i=this[qi],a=this[Ji],o=Dn(void 0,i.da),s=gn(e);if(s){var c=!1,l=i.ja;if(l){if(i=(t,n,i)=>{if(i.length!==0){if(l[n])for(let e of i){t=Rr(e);try{c=!0,a(o,t)}finally{zr(t)}}else r?.(e,n,i)}},t==null)_n(s,i);else if(s!=null){let e=s[t];e&&i(s,t,e)}if(c){let r=0|e[f];if(2&r&&2048&r&&!n?.eb)throw Error();let i=tt(r),a=(t,a)=>{if(Vn(e,t,i)!=null){if(n?.mb===1)return;throw Error()}a!=null&&(r=b(e,r,t,a,i)),delete s[t]};t==null?$e(o,0|o[f],(e,t)=>{a(e,t)}):a(t,Vn(o,t,i))}}}}function ia(e){var t=(e=Qi(e))[0].h;if(e=e[1]){let n=na(e),r=Zi(qi,ea,ta,e).da;return(e,i,a)=>t(e,i,a,r,n)}return t}function aa(e,t,n){e[t]=n.i}function oa(e,t,n,r){var i,a,o=n.i;e[t]=(e,t,n)=>o(e,t,n,a||=Zi(Ki,aa,oa,r).da,i||=sa(r))}function sa(e){var t=e[Yi];if(!t){let n=Zi(Ki,aa,oa,e);t=(e,t)=>ca(e,t,n),e[Yi]=t}return t}function ca(e,t,n){$e(e,0|e[f],(e,r)=>{if(r!=null){var i=function(e,t){var n=e[t];if(n)return n;if((n=e.ja)&&(n=n[t])){var r=(n=Qi(n))[0].i;if(n=n[1]){let t=sa(n),i=Zi(Ki,aa,oa,n).da;n=e.xa?Ui(i,t):(e,n,a)=>r(e,n,a,i,t)}else n=r;return e[t]=n}}(n,e);i?i(t,r,e):e<500||Ee(Le,3)}}),(e=gn(e))&&_n(e,(e,n,r)=>{for(_i(t,t.h.end()),e=0;e{var n=new Ci;ca(e.B,n,Zi(Ki,aa,oa,t)),_i(n,n.h.end()),e=new Uint8Array(n.i);var r=(t=n.l).length,i=0;for(let n=0;n{Si(e,n,Dn([a,t],r),i)});else if(Array.isArray(t)){for(let a=0;a>31)+1;var a=i>>>20&2047;return e=4294967296*(1048575&i)+e,O(t,n,a==2047?e?NaN:1/0*r:a==0?5e-324*r*e:r*2**(a-1075)*(e+4503599627370496)),!0},function(e,t,n){(t=Pt(t))!=null&&(T(e,n,1),e=e.h,(n=pt||=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8))).setFloat64(0,+t,!0),h=n.getUint32(0,!0),g=n.getUint32(4,!0),hi(e,h),hi(e,g))},Fi),k=D(function(e,t,n){return e.i===5&&(O(t,n,Ar(e.h)),!0)},ma,Pi),Oa=fa(Ca,function(e,t,n){if((t=ua(Pt,t,!0))!=null)for(let o=0;o=0?e=String(t):((t=e.indexOf(`.`))!==-1&&(e=e.substring(0,t)),e=Ut(e)),e;if(t===`number`)return Gt(e)}}(t),t!=null&&(typeof t==`string`&&Xr(t),t!=null))switch(T(e,n,0),typeof t){case`number`:e=e.h,gt(t),di(e,h,g);break;case`bigint`:n=ui(t,Qr,Yr),di(e.h,n.i,n.h);break;default:n=Xr(t),di(e.h,n.i,n.h)}},Mi),j=D(function(e,t,n){return e.i===0&&(O(t,n,Er(e.h)),!0)},ga,ki),Fa=fa(Ta,function(e,t,n){if((t=ua(zt,t,!0))!=null)for(let o=0;o{var n=-(1&e);return bt(e=(e>>>1|t<<31)^n,t>>>1^n)})}(e.h)),e=!0):e=!1,e},function(e,t,n){if((t=Zt(t))!=null&&(wi(t),t!=null))switch(T(e,n,0),typeof t){case`number`:e=e.h,t=(n=t)<0,ht(n=2*Math.abs(n)),n=h;let r=g;t&&(n==0?r==0?r=n=4294967295:(r--,n=4294967295):n--),di(e,h=n,g=r);break;case`bigint`:e=e.h,t=t<>BigInt(63),h=Number(BigInt.asUintN(32,t)),g=Number(BigInt.asUintN(32,t>>BigInt(32))),di(e,h,g);break;default:mi(e.h,t)}},Ni),qa=class{constructor(e,t){var n=_o;this.h=e,this.i=t,this.o=x,this.u=S,this.defaultValue=void 0,this.l=n.kb==null?void 0:et}register(){ae(this)}};function Ja(e,t){return new qa(e,t)}function Ya(e,t){return(n,r)=>{t:{let a={na:!0};r&&Object.assign(a,r),n=Rr(n,void 0,void 0,a);try{let r=new e,a=r.B;na(t)(a,n);var i=r;break t}catch(e){throw e instanceof RangeError?SyntaxError():e}finally{zr(n)}}return i}}function Xa(e){return t=>da(t,e)}function Za(e){return function(){return da(this,e)}}var Qa=[0,Ba,Va,M,P],$a=[0,za,[0,Ga,[0,Na,La],Ga,-1,[0,L],Ga,-1],D(Ea,ba,Ii)],eo=class extends E{constructor(e){super(e)}},to=[0,za,D(Ea,function(e,t,n){if(t!=null){if(t instanceof E){let r=t.nb;r?(t=r(t),t!=null&&xi(e,n,Cr(t,!0).buffer)):Ee(Le,3);return}if(Array.isArray(t))return void Ee(Le,3)}ba(e,t,n)},Ii)],no=[0,1,[0,12,j,10,M],[0,7,[0,j,-1]]];globalThis.trustedTypes;var ro=[0,j,L,M,-1,Ia,L,-1,M,-1],io=[0,L,-1,M],ao=class extends E{constructor(e){super(e)}},oo=[0,M,P,M,L,-1,fa(function(e,t,n){return(e.i===0||e.i===2)&&(t=Qn(t,0|t[f],n),e.i==2?Kr(e,jr,t):t.push(Er(e.h)),!0)},function(e,t,n){if((t=ua(zt,t,!0))!=null&&t.length){n=vi(e,n);for(let n=0;n({index:fr(e,1)??0??-1,score:C(e,2)??0,categoryName:_(v(e,3))??``??``,displayName:_(v(e,4))??``??``})),headIndex:t,headName:n}}function rc(e){var t={classifications:or(e,Ho,1).map(e=>nc(x(e,Oo,4)?.h()??[],fr(e,2)??0,_(v(e,3))??``))};return function(e){return e==null?e:typeof e==`bigint`?(st(e)?e=Number(e):(e=Dt(64,e),e=st(e)?Number(e):String(e)),e):Lt(e)?typeof e==`number`?Wt(e):qt(e):void 0}(v(e,2,void 0,Xt))!=null&&(t.timestampMs=tc(v(e,2,void 0,Xt)??zn)),t}function ic(e){var t=Wn(e,3,Pt,Un()),n=Wn(e,2,zt,Un()),r=Wn(e,1,_,Un()),i=Wn(e,9,_,Un()),a={categories:[],keypoints:[]};for(let e=0;ee>127?e-256:e)}function cc(e,t){if(e.length!==t.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${e.length} vs. ${t.length}).`);var n=0,r=0,i=0;for(let a=0;a0?setTimeout(()=>{r.abort()},e.ma):void 0;try{let i=await fetch(e.url,{method:e.cb,headers:{...e.bb},...e.body&&{body:e.body},...e.withCredentials&&{credentials:`include`},signal:e.ma&&r?r.signal:null});i.status===200?t?.(await i.text()):n?.(i.status)}catch(e){e?.name===`AbortError`?n?.(408):n?.(400)}finally{clearTimeout(i)}}},Sc=class extends E{constructor(e){super(e,37)}},Cc=[-4,{},no,L,$a],wc=[0,P,L,1,P,-1,L,1,L,1,A],Tc=[0,L,P,-2],Ec=[0,P,L],Dc=[0,P,L],Oc=[0,M,-3],kc=[0,L,P,-1,A,j,-1,P,-5,F,[0,P,-4],-1,M,[0,M,-3],L],Ac=class extends E{constructor(e){super(e,19)}},jc=Xa([-19,{},[0,L,1,[0,P,-6,A,j,P,-1,A],1,[0,P,1,P,-5],P,-1,[0,L,P,-8],[0,P,-3],[0,P,L,P,-2],[0,P,-1,L,P,-1,L,P,-1,[0,F,[0,P,-1],M,P,-5],[0,L,M,j,-2]],A,[0,P,-3,A,j,P,-1],[0,L,P,-1],[0,P,-9],[0,P,-6,L,P,1,P,M,L,-1,M,P,-2,L,P,L,P,j,-1],1,[0,L],1,[0,P,-4],1,wc,[0,[1,2,3,4,5,6],I,wc,I,Ec,I,Dc,I,[0,L],I,kc,I,Tc],Ec,Dc,kc,[0,[0,L,P,-1,A,j,-1,P,-4,F,[0,P,-4],-1,1,Oc],[0,L,P,-1,A,j,-1,P,-4,Oc]],Tc,[0,P,[0,j,-3,L],L,-2,[0,j,-1],M],4,[0,P,L,P,-1,A,L,P,-1,L,j,-1]],L,F,[-37,{},ja,P,F,[0,P,-1],Ba,1,Ba,[0,N,-1,Fa,Ma,-1],P,[0,j,P,-1],M,j,A,P,-1,Ka,Qa,ja,Ba,L,Fa,A,-1,[0,L,-1],P,M,P,Ia,P,-1,Da,1,Da,Cc,M,[0,L,[0,k,j,-2],[0,k]],[0,L,A]],ja,Va,P,-1,ja,L,-1,[0,M,-1,L,M],[0,A,-1,P],[0,ja,M,A],A,1,Ha,1,Cc]),Mc=class{constructor(e){this.i=[],this.o=new xc,this.l=e??``,this.h=setInterval(()=>{this.flush()},6e4)}close(){this.h!==void 0&&(clearInterval(this.h),this.h=void 0),this.flush()}flush(e,t){if(this.error)t?.(`net-send-failed`);else if(this.i.length===0)e?.();else{var n=this.i;this.i=[],n=function(e){var t=new Ac;return lr(t=y(t,2,Rt(1786)),3,e)}(n),n=jc(n),this.o.send({url:`https://odml.pa.googleapis.com/v1/log`,cb:`POST`,ma:1e4,body:n,ib:2,bb:{"Content-Type":`application/x-protobuf`,"x-goog-api-key":this.l},withCredentials:!1},()=>{e?.()},e=>{this.error=Error(`Logging failed with HTTP error: ${e}`),this.i=[],this.h!==void 0&&(clearInterval(this.h),this.h=void 0),t?.(`net-send-failed`,e)})}}},Nc=class{constructor(){this.ba=this.V=this.Y=this.S=this.W=this.U=this.R=0}};function Pc(e,t){var n=new bc;n=S(n,0,1,e.C),n=S(n,0,2,t),t=y(t=new Sc,6,Xe(n=n.h(),!1)),(e=e.m).error||e.i.push(t)}function Fc(e,t){var n={R:t.R-e.l.R,U:t.U-e.l.U,W:t.W-e.l.W,S:t.S-e.l.S,Y:t.Y-e.l.Y,V:t.V,ba:t.ba},r=gc(hc(new _c,e.D),1);n=Ic(e,n),Pc(e,r=cr(r,4,vc,n)),e.l=t}function Ic(e,t){var n=new dc;return e=_r(e=gr(e=y(n,1,Rt(e.F)),7,t.S),5,t.V),e=_r(e,6,t.ba),t.W>0&&_r(e,4,t.Y/t.W),t.R!==0&&(n=gr(n=lc(3),2,t.R),dr(e,8,uc,n)),t.U!==0&&(t=gr(n=lc(4),2,t.U),dr(e,8,uc,t)),e}var Lc=class{constructor(e,t,n){this.v=performance.now(),this.o=performance.now(),this.i=/* @__PURE__ */ new Map,this.u=0,this.h=new Nc,this.l=new Nc,this.m=new Mc(n),this.D=function(e){switch(e){case`AudioClassifier`:return 4;case`AudioEmbedder`:return 5;case`TextClassifier`:return 6;case`TextEmbedder`:return 7;case`GestureRecognizer`:return 8;case`HandDetector`:return 9;case`HandLandmarker`:return 10;case`ImageClassifier`:return 11;case`ImageEmbedder`:return 12;case`ImageSegmenter`:return 13;case`ObjectDetector`:return 14;case`FaceDetector`:return 15;case`FaceLandmarker`:return 16;case`InteractiveSegmenter`:case`InteractiveSegmenterLegacy`:return 18;case`HolisticLandmarker`:return 20;case`LlmInference`:return 21;case`LanguageDetector`:return 22;case`PoseLandmarker`:return 23;case`UniversalEmbedder`:return 28;case`SemanticRetriever`:return 29;case`DecisionMaker`:return 30;default:return 0}}(e),this.F=function(e){switch(e){case`IMAGE`:return 11;case`VIDEO`:return 12;case`LIVE_STREAM`:return 13;case`AUDIO_CLIPS`:return 14;case`AUDIO_STREAM`:return 15;default:return 10}}(t),e=new yc,typeof window>`u`?t=0:(t=navigator.userAgent,t=/Android/i.test(t)?1:/iPhone|iPad|iPod/i.test(t)?2:/Windows/i.test(t)?5:/Macintosh/i.test(t)?4:/Linux/i.test(t)?3:0),e=y(e,1,Rt(t)),e=y(e,2,en(``)),e=y(e,3,en(``)),e=y(e,4,en(`1.1.0`)),e=y(e,5,en(``)),this.C=y(e,6,Rt(4))}za(){var e=new mc;e=_r(e=y(e,1,Rt(this.F)),3,performance.now()-this.v),Pc(this,e=cr(gc(hc(new _c,this.D),0),3,vc,e)),this.o=performance.now()}Aa(e){var t=this.i.get(e);if(t!==void 0&&(this.i.delete(e),e=performance.now()-t,++this.h.W,this.h.Y+=e,this.h.V=Math.max(this.h.V,e),this.u=Math.max(this.u,e),performance.now()>this.o+3e4)){for(let[n,r]of this.i.entries())e=n,r=1&&Number(e[1])>=17))}async function zc(e){if(typeof importScripts!=`function`){let t=document.createElement(`script`);return t.src=e.toString(),t.crossOrigin=`anonymous`,new Promise((e,n)=>{t.addEventListener(`load`,()=>{e()},!1),t.addEventListener(`error`,e=>{n(e)},!1),document.body.appendChild(t)})}try{importScripts(e.toString())}catch(t){if(!(t instanceof TypeError))throw t;{let t=self.import;t?await t(e.toString()):await import(e.toString())}}}function Bc(e){return e.videoWidth===void 0?e.naturalWidth===void 0?e.displayWidth===void 0?[e.width,e.height]:[e.displayWidth,e.displayHeight]:[e.naturalWidth,e.naturalHeight]:[e.videoWidth,e.videoHeight]}function G(e,t,n){e.o||console.error(`No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target`),n(t=e.j.stringToNewUTF8(t)),e.j._free(t)}function Vc(e,t,n){if(!e.j.canvas)throw Error(`No OpenGL canvas configured.`);if(n?e.j._bindTextureToStream(n):e.j._bindTextureToCanvas(),!(n=e.j.canvas.getContext(`webgl2`)||e.j.canvas.getContext(`webgl`)))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");e.j.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!0),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),e.j.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1);var[r,i]=Bc(t);return!e.l||r===e.j.canvas.width&&i===e.j.canvas.height||(e.j.canvas.width=r,e.j.canvas.height=i),[r,i]}function Hc(e,t,n){e.o||console.error(`No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target`);var r=new Uint32Array(t.length);for(let n=0;n>2),n(t);for(let t of r)e.j._free(t);e.j._free(t)}function Uc(e,t,n){e.j.simpleListeners=e.j.simpleListeners||{},e.j.simpleListeners[t]=n}function Wc(e,t,n){var r=[];e.j.simpleListeners=e.j.simpleListeners||{},e.j.simpleListeners[t]=(e,t,i)=>{t?(n(r,i),r=[]):r.push(e)}}var Gc=class{constructor(e,t){this.l=!0,this.j=e,this.h=null,this.i=0,this.o=typeof this.j._addIntToInputStream==`function`,t===void 0?Rc()?this.j.canvas=new OffscreenCanvas(1,1):(console.warn(`OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas.`),this.j.canvas=document.createElement(`canvas`)):this.j.canvas=t}async initializeGraph(e){var t=await(await fetch(e)).arrayBuffer();e=!(e.endsWith(`.pbtxt`)||e.endsWith(`.textproto`)),this.setGraph(new Uint8Array(t),e)}setGraphFromString(e){this.setGraph(new TextEncoder().encode(e),!1)}setGraph(e,t){var n=e.length,r=this.j._malloc(n);this.j.HEAPU8.set(e,r),t?this.j._changeBinaryGraph(n,r):this.j._changeTextGraph(n,r),this.j._free(r)}configureAudio(e,t,n,r,i){this.j._configureAudio||console.warn(`Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?`),G(this,r||`input_audio`,r=>{G(this,i||=`audio_header`,i=>{this.j._configureAudio(r,i,e,t??0,n)})})}setAutoResizeCanvas(e){this.l=e}setAutoRenderToScreen(e){this.j._setAutoRenderToScreen(e)}setGpuBufferVerticalFlip(e){this.j.gpuOriginForWebTexturesIsBottomLeft=e}ka(e){Uc(this,`__graph_config__`,t=>{e(t)}),G(this,`__graph_config__`,e=>{this.j._getGraphConfig(e,void 0)}),delete this.j.simpleListeners.__graph_config__}attachErrorListener(e){this.j.errorListener=e}attachEmptyPacketListener(e,t){this.j.emptyPacketListeners=this.j.emptyPacketListeners||{},this.j.emptyPacketListeners[e]=t}addAudioToStream(e,t,n){this.addAudioToStreamWithShape(e,0,0,t,n)}addAudioToStreamWithShape(e,t,n,r,i){var a=4*e.length;this.i!==a&&(this.h&&this.j._free(this.h),this.h=this.j._malloc(a),this.i=a),this.j.HEAPF32.set(e,this.h/4),G(this,r,e=>{this.j._addAudioToInputStream(this.h,t,n,e,i)})}addGpuBufferToStream(e,t,n){G(this,t,t=>{var[r,i]=Vc(this,e,t);this.j._addBoundTextureToStream(t,r,i,n)})}addBoolToStream(e,t,n){G(this,t,t=>{this.j._addBoolToInputStream(e,t,n)})}addDoubleToStream(e,t,n){G(this,t,t=>{this.j._addDoubleToInputStream(e,t,n)})}addFloatToStream(e,t,n){G(this,t,t=>{this.j._addFloatToInputStream(e,t,n)})}addIntToStream(e,t,n){G(this,t,t=>{this.j._addIntToInputStream(e,t,n)})}addUintToStream(e,t,n){G(this,t,t=>{this.j._addUintToInputStream(e,t,n)})}addStringToStream(e,t,n){G(this,t,t=>{G(this,e,e=>{this.j._addStringToInputStream(e,t,n)})})}addStringRecordToStream(e,t,n){G(this,t,t=>{Hc(this,Object.keys(e),r=>{Hc(this,Object.values(e),i=>{this.j._addFlatHashMapToInputStream(r,i,Object.keys(e).length,t,n)})})})}addProtoToStream(e,t,n,r){G(this,n,n=>{G(this,t,t=>{var i=this.j._malloc(e.length);this.j.HEAPU8.set(e,i),this.j._addProtoToInputStream(i,e.length,t,n,r),this.j._free(i)})})}addEmptyPacketToStream(e,t){G(this,e,e=>{this.j._addEmptyPacketToInputStream(e,t)})}addBoolVectorToStream(e,t,n){G(this,t,t=>{var r=this.j._allocateBoolVector(e.length);if(!r)throw Error(`Unable to allocate new bool vector on heap.`);for(let t of e)this.j._addBoolVectorEntry(r,t);this.j._addBoolVectorToInputStream(r,t,n)})}addDoubleVectorToStream(e,t,n){G(this,t,t=>{var r=this.j._allocateDoubleVector(e.length);if(!r)throw Error(`Unable to allocate new double vector on heap.`);for(let t of e)this.j._addDoubleVectorEntry(r,t);this.j._addDoubleVectorToInputStream(r,t,n)})}addFloatVectorToStream(e,t,n){G(this,t,t=>{var r=this.j._allocateFloatVector(e.length);if(!r)throw Error(`Unable to allocate new float vector on heap.`);for(let t of e)this.j._addFloatVectorEntry(r,t);this.j._addFloatVectorToInputStream(r,t,n)})}addIntVectorToStream(e,t,n){G(this,t,t=>{var r=this.j._allocateIntVector(e.length);if(!r)throw Error(`Unable to allocate new int vector on heap.`);for(let t of e)this.j._addIntVectorEntry(r,t);this.j._addIntVectorToInputStream(r,t,n)})}addUintVectorToStream(e,t,n){G(this,t,t=>{var r=this.j._allocateUintVector(e.length);if(!r)throw Error(`Unable to allocate new unsigned int vector on heap.`);for(let t of e)this.j._addUintVectorEntry(r,t);this.j._addUintVectorToInputStream(r,t,n)})}addStringVectorToStream(e,t,n){G(this,t,t=>{var r=this.j._allocateStringVector(e.length);if(!r)throw Error(`Unable to allocate new string vector on heap.`);for(let t of e)G(this,t,e=>{this.j._addStringVectorEntry(r,e)});this.j._addStringVectorToInputStream(r,t,n)})}addBoolToInputSidePacket(e,t){G(this,t,t=>{this.j._addBoolToInputSidePacket(e,t)})}addDoubleToInputSidePacket(e,t){G(this,t,t=>{this.j._addDoubleToInputSidePacket(e,t)})}addFloatToInputSidePacket(e,t){G(this,t,t=>{this.j._addFloatToInputSidePacket(e,t)})}addIntToInputSidePacket(e,t){G(this,t,t=>{this.j._addIntToInputSidePacket(e,t)})}addUintToInputSidePacket(e,t){G(this,t,t=>{this.j._addUintToInputSidePacket(e,t)})}addStringToInputSidePacket(e,t){G(this,t,t=>{G(this,e,e=>{this.j._addStringToInputSidePacket(e,t)})})}addProtoToInputSidePacket(e,t,n){G(this,n,n=>{G(this,t,t=>{var r=this.j._malloc(e.length);this.j.HEAPU8.set(e,r),this.j._addProtoToInputSidePacket(r,e.length,t,n),this.j._free(r)})})}addBoolVectorToInputSidePacket(e,t){G(this,t,t=>{var n=this.j._allocateBoolVector(e.length);if(!n)throw Error(`Unable to allocate new bool vector on heap.`);for(let t of e)this.j._addBoolVectorEntry(n,t);this.j._addBoolVectorToInputSidePacket(n,t)})}addDoubleVectorToInputSidePacket(e,t){G(this,t,t=>{var n=this.j._allocateDoubleVector(e.length);if(!n)throw Error(`Unable to allocate new double vector on heap.`);for(let t of e)this.j._addDoubleVectorEntry(n,t);this.j._addDoubleVectorToInputSidePacket(n,t)})}addFloatVectorToInputSidePacket(e,t){G(this,t,t=>{var n=this.j._allocateFloatVector(e.length);if(!n)throw Error(`Unable to allocate new float vector on heap.`);for(let t of e)this.j._addFloatVectorEntry(n,t);this.j._addFloatVectorToInputSidePacket(n,t)})}addIntVectorToInputSidePacket(e,t){G(this,t,t=>{var n=this.j._allocateIntVector(e.length);if(!n)throw Error(`Unable to allocate new int vector on heap.`);for(let t of e)this.j._addIntVectorEntry(n,t);this.j._addIntVectorToInputSidePacket(n,t)})}addUintVectorToInputSidePacket(e,t){G(this,t,t=>{var n=this.j._allocateUintVector(e.length);if(!n)throw Error(`Unable to allocate new unsigned int vector on heap.`);for(let t of e)this.j._addUintVectorEntry(n,t);this.j._addUintVectorToInputSidePacket(n,t)})}addStringVectorToInputSidePacket(e,t){G(this,t,t=>{var n=this.j._allocateStringVector(e.length);if(!n)throw Error(`Unable to allocate new string vector on heap.`);for(let t of e)G(this,t,e=>{this.j._addStringVectorEntry(n,e)});this.j._addStringVectorToInputSidePacket(n,t)})}attachBoolListener(e,t){Uc(this,e,t),G(this,e,e=>{this.j._attachBoolListener(e)})}attachBoolVectorListener(e,t){Wc(this,e,t),G(this,e,e=>{this.j._attachBoolVectorListener(e)})}attachIntListener(e,t){Uc(this,e,t),G(this,e,e=>{this.j._attachIntListener(e)})}attachIntVectorListener(e,t){Wc(this,e,t),G(this,e,e=>{this.j._attachIntVectorListener(e)})}attachUintListener(e,t){Uc(this,e,t),G(this,e,e=>{this.j._attachUintListener(e)})}attachUintVectorListener(e,t){Wc(this,e,t),G(this,e,e=>{this.j._attachUintVectorListener(e)})}attachDoubleListener(e,t){Uc(this,e,t),G(this,e,e=>{this.j._attachDoubleListener(e)})}attachDoubleVectorListener(e,t){Wc(this,e,t),G(this,e,e=>{this.j._attachDoubleVectorListener(e)})}attachFloatListener(e,t){Uc(this,e,t),G(this,e,e=>{this.j._attachFloatListener(e)})}attachFloatVectorListener(e,t){Wc(this,e,t),G(this,e,e=>{this.j._attachFloatVectorListener(e)})}attachStringListener(e,t){Uc(this,e,t),G(this,e,e=>{this.j._attachStringListener(e)})}attachStringVectorListener(e,t){Wc(this,e,t),G(this,e,e=>{this.j._attachStringVectorListener(e)})}attachProtoListener(e,t,n){Uc(this,e,t),G(this,e,e=>{this.j._attachProtoListener(e,n||!1)})}attachProtoVectorListener(e,t,n){Wc(this,e,t),G(this,e,e=>{this.j._attachProtoVectorListener(e,n||!1)})}attachAudioListener(e,t,n){this.j._attachAudioListener||console.warn(`Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?`),Uc(this,e,(e,n)=>{e=new Float32Array(e.buffer,e.byteOffset,e.length/4),t(e,n)}),G(this,e,e=>{this.j._attachAudioListener(e,n||!1)})}finishProcessing(){this.j._waitUntilIdle()}closeGraph(){this.j._closeGraph(),this.j.simpleListeners=void 0,this.j.emptyPacketListeners=void 0}};function Kc(e){return class extends e{get qa(){return this.j}Ta(){if(typeof this.qa._mediapipeLoggerGetEncodedApiKey==`function`){let e=this.qa._mediapipeLoggerGetEncodedApiKey();return this.qa._decodeBase64(e)}}}}function qc(e){return class extends e{ab(){this.j._registerModelResourcesGraphService()}}}var Jc=Kc(qc(Gc)),Yc=class extends Jc{};async function Xc(e,t,n,r){return e=await(async(e,t,n,r,i)=>{if(t&&await zc(t),!self.ModuleFactory||n&&(await zc(n),!self.ModuleFactory))throw Error(`ModuleFactory not set.`);return self.Module&&i&&((t=self.Module).locateFile=i.locateFile,i.mainScriptUrlOrBlob&&(t.mainScriptUrlOrBlob=i.mainScriptUrlOrBlob)),i=await self.ModuleFactory(self.Module||i),self.ModuleFactory=self.Module=void 0,new e(i,r)})(e,n.wasmLoaderPath,n.assetLoaderPath,t,{locateFile:e=>e.endsWith(`.wasm`)?n.wasmBinaryPath.toString():n.assetBinaryPath&&e.endsWith(`.data`)?n.assetBinaryPath.toString():e}),function(e,t){t=t.runningMode??``;var n=e.h.Ta();e.o=new Lc(e.D(),t,n)}(e,r),await e.A(r),e}async function Zc(e,t,n,r){return Xc(e,t,n,r)}function Qc(e,t,n){try{e.h.j.FS_unlink(`/${n}`)}catch{}e.h.j.FS_createDataFile(`/`,n,t,!0,!1,!1),$c(e,`/${n}`)}function $c(e,t){var n=x(e.baseOptions,ts,1)||new ts;typeof t==`string`?(y(n,2,en(t)),y(n,1)):t instanceof Uint8Array&&(y(n,1,Xe(t,!1)),y(n,2)),S(e.baseOptions,0,1,n)}function el(e){try{let t=e.L.length;if(t===1)throw Error(e.L[0].message);if(t>1)throw Error(`Encountered multiple errors: `+e.L.map(e=>e.message).join(`, `))}finally{e.L=[]}}function K(e,t){e.J=Math.max(e.J,t)}function tl(e,t){e.F=new yo,yr(e.F,2,`PassThroughCalculator`),z(e.F,`free_memory`),B(e.F,`free_memory_unused_out`),V(t,`free_memory`),Co(t,e.F)}function nl(e,t){z(e.F,t),B(e.F,t+`_unused_out`)}function rl(e){e.h.addBoolToStream(!0,`free_memory`,e.J)}var il=class{constructor(e){this.h=e,this.L=[],this.J=0,this.h.setAutoRenderToScreen(!1)}l(e,t=!0,n=!1,r=!1){if(t){let t=e.baseOptions||{};if(e.baseOptions?.modelAssetBuffer&&e.baseOptions?.modelAssetPath)throw Error(`Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer`);if(!(x(this.baseOptions,ts,1)?.h()||x(this.baseOptions,ts,1)?.l()||e.baseOptions?.modelAssetBuffer||e.baseOptions?.modelAssetPath))throw Error(`Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set`);(function(e,t,n=!1){var r=x(e.baseOptions,$o,3);if(!r){var i=r=new $o,a=new po;cr(i,4,es,a)}`delegate`in t&&(t.delegate===`GPU`?(t=r,i=new ao,cr(t,2,es,i)):(t=r,i=new po,cr(t,4,es,i))),n&&(n=r.l(),t=r.h()||!0===n?.h(),n=new lo,t?S(n,0,9,t=new co):S(n,0,8,t=new so),cr(r,6,es,n)),S(e.baseOptions,0,3,r)})(this,t,r);let i=n?`model.litertlm`:`model.dat`;if(t.modelAssetPath)return fetch(t.modelAssetPath.toString()).then(e=>{if(e.ok)return e.arrayBuffer();throw Error(`Failed to fetch model: ${t.modelAssetPath} (${e.status})`)}).then(e=>{Qc(this,new Uint8Array(e),i),this.u(),this.M()});if(t.modelAssetBuffer instanceof Uint8Array)n?Qc(this,t.modelAssetBuffer,i):$c(this,t.modelAssetBuffer);else if(t.modelAssetBuffer)return async function(e){for(var t=[],n=0;;){let{done:r,value:i}=await e.read();if(r)break;t.push(i),n+=i.length}if(t.length===0)return/* @__PURE__ */ new Uint8Array;if(t.length===1)return t[0];e=new Uint8Array(n),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}(t.modelAssetBuffer).then(e=>{n?Qc(this,e,i):$c(this,e),this.u(),this.M()})}return this.u(),this.M(),Promise.resolve()}M(){}ka(){var e;if(this.h.ka(t=>{e=Eo(t)}),!e)throw Error(`Failed to retrieve CalculatorGraphConfig`);return e}setGraph(e,t){this.h.attachErrorListener((e,t)=>{this.L.push(Error(t))}),this.h.ab(),this.h.setGraph(e,t),this.o?.za(),this.F=void 0,el(this)}finishProcessing(e){this.h.finishProcessing(),el(this),this.o&&e!==void 0&&this.o.Aa(e)}close(){this.F=void 0,this.o?.ya(),this.o?.close(),this.h.closeGraph()}};function q(e,t){if(!e)throw Error(`Unable to obtain required WebGL resource: ${t}`);return e}il.prototype.close=il.prototype.close;var al=class{constructor(e,t,n,r){this.h=e,this.i=t,this.o=n,this.l=r}bind(){this.h.bindVertexArray(this.i)}close(){this.h.deleteVertexArray(this.i),this.h.deleteBuffer(this.o),this.h.deleteBuffer(this.l)}};function ol(e,t,n){var r=e.h;if(n=q(r.createShader(n),`Failed to create WebGL shader`),r.shaderSource(n,t),r.compileShader(n),!r.getShaderParameter(n,r.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${r.getShaderInfoLog(n)}`);return r.attachShader(e.i,n),n}function sl(e,t){var n=e.h,r=q(n.createVertexArray(),`Failed to create vertex array`);n.bindVertexArray(r);var i=q(n.createBuffer(),`Failed to create buffer`);n.bindBuffer(n.ARRAY_BUFFER,i),n.enableVertexAttribArray(e.G),n.vertexAttribPointer(e.G,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),n.STATIC_DRAW);var a=q(n.createBuffer(),`Failed to create buffer`);return n.bindBuffer(n.ARRAY_BUFFER,a),n.enableVertexAttribArray(e.L),n.vertexAttribPointer(e.L,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array(t?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),n.bindVertexArray(null),new al(n,r,i,a)}function cl(e,t){if(e.h){if(t!==e.h)throw Error(`Cannot change GL context once initialized`)}else e.h=t}function ll(e,t,n,r){return cl(e,t),e.i||(e.o(),e.J()),n?(e.m||(e.m=sl(e,!0)),n=e.m):(e.F||(e.F=sl(e,!1)),n=e.F),t.useProgram(e.i),n.bind(),e.l(),e=r(),n.h.bindVertexArray(null),e}function ul(e,t,n){return cl(e,t),e=q(t.createTexture(),`Failed to create texture`),t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,n??t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,n??t.LINEAR),t.bindTexture(t.TEXTURE_2D,null),e}function dl(e,t,n){cl(e,t),e.D||=q(t.createFramebuffer(),`Failed to create framebuffe.`),t.bindFramebuffer(t.FRAMEBUFFER,e.D),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}function fl(e){e.h?.bindFramebuffer(e.h.FRAMEBUFFER,null)}var pl=class{C(){return` + precision mediump float; + varying vec2 vTex; + uniform sampler2D inputTexture; + void main() { + gl_FragColor = texture2D(inputTexture, vTex); + } + `}o(){var e=this.h;if(this.i=q(e.createProgram(),`Failed to create WebGL program`),this.ea=ol(this,` + attribute vec2 aVertex; + attribute vec2 aTex; + varying vec2 vTex; + void main(void) { + gl_Position = vec4(aVertex, 0.0, 1.0); + vTex = aTex; + }`,e.VERTEX_SHADER),this.aa=ol(this,this.C(),e.FRAGMENT_SHADER),e.linkProgram(this.i),!e.getProgramParameter(this.i,e.LINK_STATUS))throw Error(`Error during program linking: ${e.getProgramInfoLog(this.i)}`);this.G=e.getAttribLocation(this.i,`aVertex`),this.L=e.getAttribLocation(this.i,`aTex`)}J(){}l(){}close(){if(this.i){let e=this.h;e.deleteProgram(this.i),e.deleteShader(this.ea),e.deleteShader(this.aa)}this.D&&this.h.deleteFramebuffer(this.D),this.F&&this.F.close(),this.m&&this.m.close()}},ml=class extends pl{C(){return` + precision mediump float; + uniform sampler2D backgroundTexture; + uniform sampler2D maskTexture; + uniform sampler2D colorMappingTexture; + varying vec2 vTex; + void main() { + vec4 backgroundColor = texture2D(backgroundTexture, vTex); + float category = texture2D(maskTexture, vTex).r; + vec4 categoryColor = texture2D(colorMappingTexture, vec2(category, 0.0)); + gl_FragColor = mix(backgroundColor, categoryColor, categoryColor.a); + } + `}J(){var e=this.h;e.activeTexture(e.TEXTURE1),this.v=ul(this,e,e.LINEAR),e.activeTexture(e.TEXTURE2),this.u=ul(this,e,e.NEAREST)}o(){super.o();var e=this.h;this.P=q(e.getUniformLocation(this.i,`backgroundTexture`),`Uniform location`),this.Z=q(e.getUniformLocation(this.i,`colorMappingTexture`),`Uniform location`),this.M=q(e.getUniformLocation(this.i,`maskTexture`),`Uniform location`)}l(){super.l();var e=this.h;e.uniform1i(this.M,0),e.uniform1i(this.P,1),e.uniform1i(this.Z,2)}close(){this.v&&this.h.deleteTexture(this.v),this.u&&this.h.deleteTexture(this.u),super.close()}},hl=class extends pl{C(){return` + precision mediump float; + uniform sampler2D maskTexture; + uniform sampler2D defaultTexture; + uniform sampler2D overlayTexture; + varying vec2 vTex; + void main() { + float confidence = texture2D(maskTexture, vTex).r; + vec4 defaultColor = texture2D(defaultTexture, vTex); + vec4 overlayColor = texture2D(overlayTexture, vTex); + // Apply the alpha from the overlay and merge in the default color + overlayColor = mix(defaultColor, overlayColor, overlayColor.a); + gl_FragColor = mix(defaultColor, overlayColor, confidence); + } + `}J(){var e=this.h;e.activeTexture(e.TEXTURE1),this.u=ul(this,e),e.activeTexture(e.TEXTURE2),this.v=ul(this,e)}o(){super.o();var e=this.h;this.M=q(e.getUniformLocation(this.i,`defaultTexture`),`Uniform location`),this.P=q(e.getUniformLocation(this.i,`overlayTexture`),`Uniform location`),this.K=q(e.getUniformLocation(this.i,`maskTexture`),`Uniform location`)}l(){super.l();var e=this.h;e.uniform1i(this.K,0),e.uniform1i(this.M,1),e.uniform1i(this.P,2)}close(){this.u&&this.h.deleteTexture(this.u),this.v&&this.h.deleteTexture(this.v),super.close()}};function gl(e,t){switch(t){case 0:return e.h.find(e=>e instanceof Uint8Array);case 1:return e.h.find(e=>e instanceof Float32Array);case 2:return e.h.find(e=>typeof WebGLTexture<`u`&&e instanceof WebGLTexture);default:throw Error(`Type is not supported: ${t}`)}}function _l(e){var t=gl(e,1);if(!t){if(t=gl(e,0))t=new Float32Array(t).map(e=>e/255);else{t=new Float32Array(e.width*e.height);let r=yl(e);var n=xl(e);if(dl(n,r,vl(e)),`iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod`.split(`;`).includes(navigator.platform)||navigator.userAgent.includes(`Mac`)&&`document`in self&&`ontouchend`in self.document){n=new Float32Array(e.width*e.height*4),r.readPixels(0,0,e.width,e.height,r.RGBA,r.FLOAT,n);for(let e=0,r=0;eMath.round(255*e))),e.h.push(t)),t;var e,t}ta(){return _l(this)}T(){return vl(this)}clone(){var e=[];for(let t of this.h){let n;if(t instanceof Uint8Array)n=new Uint8Array(t);else if(t instanceof Float32Array)n=new Float32Array(t);else{if(!(t instanceof WebGLTexture))throw Error(`Type is not supported: ${t}`);{let e=yl(this),t=xl(this);e.activeTexture(e.TEXTURE1),n=ul(t,e,this.o?e.LINEAR:e.NEAREST),e.bindTexture(e.TEXTURE_2D,n);let r=bl(this);e.texImage2D(e.TEXTURE_2D,0,r,this.width,this.height,0,e.RED,e.FLOAT,null),e.bindTexture(e.TEXTURE_2D,null),dl(t,e,n),ll(t,e,!1,()=>{Sl(this),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),e.drawArrays(e.TRIANGLE_FAN,0,4),Cl(this)}),fl(t),Cl(this)}}e.push(n)}return new J(e,this.o,this.X(),this.canvas,this.l,this.width,this.height)}close(){this.u&&yl(this).deleteTexture(gl(this,2)),Tl=-1}};J.prototype.close=J.prototype.close,J.prototype.clone=J.prototype.clone,J.prototype.getAsWebGLTexture=J.prototype.T,J.prototype.getAsFloat32Array=J.prototype.ta,J.prototype.getAsUint8Array=J.prototype.ua,J.prototype.hasWebGLTexture=J.prototype.X,J.prototype.hasFloat32Array=J.prototype.va,J.prototype.hasUint8Array=J.prototype.Va;var Tl=250,El={color:`white`,lineWidth:4,radius:6};function Dl(e){return{...El,fillColor:(e||={}).color,...e}}function Ol(e,t){return e instanceof Function?e(t):e}function kl(e,t,n){return Math.max(Math.min(t,n),Math.min(Math.max(t,n),e))}function Al(e){if(!e.l)throw Error(`CPU rendering requested but CanvasRenderingContext2D not provided.`);return e.l}function jl(e){if(!e.u)throw Error(`GPU rendering requested but WebGL2RenderingContext not provided.`);return e.u}function Ml(e,t,n){if(t.X())n(t.T());else{let r=t.va()?t.ta():t.ua();e.o=e.o??new pl;let i=jl(e);n((e=new J([r],t.o,!1,i.canvas,e.o,t.width,t.height)).T()),e.close()}}function Nl(e,t,n,r){var i=function(e){return e.h||=new ml,e.h}(e),a=jl(e),o=Array.isArray(n)?new ImageData(new Uint8ClampedArray(n),1,1):n;ll(i,a,!0,()=>{(function(e,t,n,r){var i=e.h;if(i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,t),i.activeTexture(i.TEXTURE1),i.bindTexture(i.TEXTURE_2D,e.v),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,n),e.K&&function(e,t){if(e!==t)return!1;e=e.entries(),t=t.entries();for(let[n,r]of e){e=n;let i=r,a=t.next();if(a.done)return!1;let[o,s]=a.value;if(e!==o||i[0]!==s[0]||i[1]!==s[1]||i[2]!==s[2]||i[3]!==s[3])return!1}return!!t.next().done}(e.K,r))i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,e.u);else{e.K=r;let t=Array(1024).fill(0);r.forEach((e,n)=>{if(e.length!==4)throw Error(`Color at index ${n} is not a four-channel value.`);t[4*n]=e[0],t[4*n+1]=e[1],t[4*n+2]=e[2],t[4*n+3]=e[3]}),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,e.u),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,256,1,0,i.RGBA,i.UNSIGNED_BYTE,new Uint8Array(t))}})(i,t,o,r),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT),a.drawArrays(a.TRIANGLE_FAN,0,4);var e=i.h;e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,null)})}function Pl(e,t,n,r){var i=jl(e),a=function(e){return e.i||=new hl,e.i}(e),o=Array.isArray(n)?new ImageData(new Uint8ClampedArray(n),1,1):n,s=Array.isArray(r)?new ImageData(new Uint8ClampedArray(r),1,1):r;ll(a,i,!0,()=>{var e=a.h;e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,t),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,a.u),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,o),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,a.v),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,s),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLE_FAN,0,4),i.bindTexture(i.TEXTURE_2D,null),(e=a.h).activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,null)})}var Fl=class{constructor(e,t){typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||e instanceof OffscreenCanvasRenderingContext2D?(this.l=e,this.u=t):this.u=e}Na(e,t){if(e){var n=Al(this);t=Dl(t),n.save();var r=n.canvas,i=0;for(let a of e)n.fillStyle=Ol(t.fillColor,{index:i,from:a}),n.strokeStyle=Ol(t.color,{index:i,from:a}),n.lineWidth=Ol(t.lineWidth,{index:i,from:a}),(e=new Path2D).arc(a.x*r.width,a.y*r.height,Ol(t.radius,{index:i,from:a}),0,2*Math.PI),n.fill(e),n.stroke(e),++i;n.restore()}}Ma(e,t,n){if(e&&t){var r=Al(this);n=Dl(n),r.save();var i=r.canvas,a=0;for(let o of t){r.beginPath(),t=e[o.start];let s=e[o.end];t&&s&&(r.strokeStyle=Ol(n.color,{index:a,from:t,to:s}),r.lineWidth=Ol(n.lineWidth,{index:a,from:t,to:s}),r.moveTo(t.x*i.width,t.y*i.height),r.lineTo(s.x*i.width,s.y*i.height)),++a,r.stroke()}r.restore()}}Ja(e,t){var n=Al(this);t=Dl(t),n.save(),n.beginPath(),n.lineWidth=Ol(t.lineWidth,{}),n.strokeStyle=Ol(t.color,{}),n.fillStyle=Ol(t.fillColor,{}),n.moveTo(e.originX,e.originY),n.lineTo(e.originX+e.width,e.originY),n.lineTo(e.originX+e.width,e.originY+e.height),n.lineTo(e.originX,e.originY+e.height),n.lineTo(e.originX,e.originY),n.stroke(),n.fill(),n.restore()}Ka(e,t,n=[0,0,0,255]){this.l?function(e,t,n,r){var i=jl(e);Ml(e,t,t=>{Nl(e,t,n,r),(t=Al(e)).drawImage(i.canvas,0,0,t.canvas.width,t.canvas.height)})}(this,e,n,t):Nl(this,e.T(),n,t)}La(e,t,n){this.l?function(e,t,n,r){var i=jl(e);Ml(e,t,t=>{Pl(e,t,n,r),(t=Al(e)).drawImage(i.canvas,0,0,t.canvas.width,t.canvas.height)})}(this,e,t,n):Pl(this,e.T(),t,n)}close(){this.h?.close(),this.h=void 0,this.i?.close(),this.i=void 0,this.o?.close(),this.o=void 0}};function Il(e,t){switch(t){case 0:return e.h.find(e=>e instanceof ImageData);case 1:return e.h.find(e=>typeof ImageBitmap<`u`&&e instanceof ImageBitmap);case 2:return e.h.find(e=>typeof WebGLTexture<`u`&&e instanceof WebGLTexture);default:throw Error(`Type is not supported: ${t}`)}}function Ll(e){var t=Il(e,0);if(!t){t=zl(e);let n=Bl(e),r=new Uint8Array(e.width*e.height*4);dl(n,t,Rl(e)),t.readPixels(0,0,e.width,e.height,t.RGBA,t.UNSIGNED_BYTE,r),fl(n),t=new ImageData(new Uint8ClampedArray(r.buffer),e.width,e.height),e.h.push(t)}return t}function Rl(e){var t=Il(e,2);if(!t){let n=zl(e);t=Vl(e);let r=Il(e,1)||Ll(e);n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,r),Hl(e)}return t}function zl(e){if(!e.canvas)throw Error(`Conversion to different image formats require that a canvas is passed when initializing the image.`);return e.i||=q(e.canvas.getContext(`webgl2`),`You cannot use a canvas that is already bound to a different type of rendering context.`),e.i}function Bl(e){return e.l||=new pl,e.l}function Vl(e){var t=zl(e);t.viewport(0,0,e.width,e.height),t.activeTexture(t.TEXTURE0);var n=Il(e,2);return n||(n=ul(Bl(e),t),e.h.push(n),e.o=!0),t.bindTexture(t.TEXTURE_2D,n),n}function Hl(e){e.i.bindTexture(e.i.TEXTURE_2D,null)}function Ul(e){var t=zl(e);return ll(Bl(e),t,!0,()=>function(e,t){var n=e.canvas;if(n.width===e.width&&n.height===e.height)return t();var r=n.width,i=n.height;return n.width=e.width,n.height=e.height,e=t(),n.width=r,n.height=i,e}(e,()=>{if(t.bindFramebuffer(t.FRAMEBUFFER,null),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLE_FAN,0,4),!(e.canvas instanceof OffscreenCanvas))throw Error(`Conversion to ImageBitmap requires that the MediaPipe Tasks is initialized with an OffscreenCanvas`);return e.canvas.transferToImageBitmap()}))}Fl.prototype.close=Fl.prototype.close,Fl.prototype.drawConfidenceMask=Fl.prototype.La,Fl.prototype.drawCategoryMask=Fl.prototype.Ka,Fl.prototype.drawBoundingBox=Fl.prototype.Ja,Fl.prototype.drawConnectors=Fl.prototype.Ma,Fl.prototype.drawLandmarks=Fl.prototype.Na,Fl.lerp=function(e,t,n,r,i){return kl(r*(1-(e-t)/(n-t))+i*(1-(n-e)/(n-t)),r,i)},Fl.clamp=kl;var Y=class{constructor(e,t,n,r,i,a,o){this.h=e,this.u=t,this.o=n,this.canvas=r,this.l=i,this.width=a,this.height=o,(this.u||this.o)&&--Wl===0&&console.error(`You seem to be creating MPImage instances without invoking .close(). This leaks resources.`)}Ua(){return!!Il(this,0)}wa(){return!!Il(this,1)}X(){return!!Il(this,2)}Ra(){return Ll(this)}Qa(){var e=Il(this,1);return e||(Rl(this),Vl(this),e=Ul(this),Hl(this),this.h.push(e),this.u=!0),e}T(){return Rl(this)}clone(){var e=[];for(let t of this.h){let n;if(t instanceof ImageData)n=new ImageData(t.data,this.width,this.height);else if(t instanceof WebGLTexture){let e=zl(this),t=Bl(this);e.activeTexture(e.TEXTURE1),n=ul(t,e),e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,this.width,this.height,0,e.RGBA,e.UNSIGNED_BYTE,null),e.bindTexture(e.TEXTURE_2D,null),dl(t,e,n),ll(t,e,!1,()=>{Vl(this),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),e.drawArrays(e.TRIANGLE_FAN,0,4),Hl(this)}),fl(t),Hl(this)}else{if(!(t instanceof ImageBitmap))throw Error(`Type is not supported: ${t}`);Rl(this),Vl(this),n=Ul(this),Hl(this)}e.push(n)}return new Y(e,this.wa(),this.X(),this.canvas,this.l,this.width,this.height)}close(){this.u&&Il(this,1).close(),this.o&&zl(this).deleteTexture(Il(this,2)),Wl=-1}};Y.prototype.close=Y.prototype.close,Y.prototype.clone=Y.prototype.clone,Y.prototype.getAsWebGLTexture=Y.prototype.T,Y.prototype.getAsImageBitmap=Y.prototype.Qa,Y.prototype.getAsImageData=Y.prototype.Ra,Y.prototype.hasWebGLTexture=Y.prototype.X,Y.prototype.hasImageBitmap=Y.prototype.wa,Y.prototype.hasImageData=Y.prototype.Ua;var Wl=250;function Gl(...e){return e.map(([e,t])=>({start:e,end:t}))}var Kl,ql=qc((Kl=Kc(Gc),class extends Kl{get pa(){return this.j}Ea(e,t,n){G(this,t,t=>{var[r,i]=Vc(this,e,t);this.pa._addBoundTextureAsImageToStream(t,r,i,n)})}ha(e,t){Uc(this,e,t),G(this,e,e=>{this.pa._attachImageListener(e)})}ia(e,t){Wc(this,e,t),G(this,e,e=>{this.pa._attachImageVectorListener(e)})}})),Jl=class extends ql{};async function X(e,t,n){return Zc(e,n.canvas??(Rc()?void 0:document.createElement(`canvas`)),t,n)}function Yl(e,t,n,r){if(e.o&&r!==void 0){var i=x(e.baseOptions,$o,3);i?.h()||i?.l()?.h()?(++(i=e.o).h.U,i.i.set(r,performance.now())):(++(i=e.o).h.R,i.i.set(r,performance.now()))}if(e.ra){if(i=new Vo,n?.regionOfInterest){if(!e.Da)throw Error(`This task doesn't support region-of-interest.`);var a=n.regionOfInterest;if(a.left>=a.right||a.top>=a.bottom)throw Error(`Expected RectF with left < right and top < bottom.`);if(a.left<0||a.top<0||a.right>1||a.bottom>1)throw Error(`Expected RectF values to be in [0,1].`);w(i,1,(a.left+a.right)/2),w(i,2,(a.top+a.bottom)/2),w(i,4,a.right-a.left),w(i,3,a.bottom-a.top)}else w(i,1,.5),w(i,2,.5),w(i,4,1),w(i,3,1);if(n?.rotationDegrees){if(n?.rotationDegrees%90!=0)throw Error(`Expected rotation to be a multiple of 90°.`);if(w(i,5,-Math.PI*n.rotationDegrees/180),n?.rotationDegrees%180!=0){let[e,r]=Bc(t);n=C(i,3)*r/e,a=C(i,4)*e/r,w(i,4,n),w(i,3,a)}}e.h.addProtoToStream(i.h(),`mediapipe.NormalizedRect`,e.ra,r)}e.h.Ea(t,e.Ca,r??performance.now()),e.finishProcessing(r)}function Xl(e,t,n){if(e.K)throw Error(`Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'.`);Yl(e,t,n,e.J+1)}function Zl(e,t,n,r){if(!e.K)throw Error(`Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'.`);Yl(e,t,n,r)}function Ql(e,t,n,r){var i=t.data,a=t.width,o=a*(t=t.height);if((i instanceof Uint8Array||i instanceof Float32Array)&&i.length!==o)throw Error(`Unsupported channel count: `+i.length/o);return e=new J([i],n,!1,e.h.j.canvas,e.ea,a,t),r?e.clone():e}var $l=class extends il{constructor(e,t,n,r){super(e),this.h=e,this.Ca=t,this.ra=n,this.Da=r,this.ea=new pl,this.K=!1}l(e,t=!0,n=!1,r=!1){if(`runningMode`in e){var i=this.K=!!e.runningMode&&e.runningMode!==`IMAGE`;y(this.baseOptions,2,i==null?i:Ft(i))}if(e.canvas!==void 0&&this.h.j.canvas!==e.canvas)throw Error(`You must create a new task to reset the canvas.`);return super.l(e,t,n,r)}close(){this.ea.close(),super.close()}};$l.prototype.close=$l.prototype.close;var eu=class extends $l{constructor(e,t){super(new Jl(e,t),`image_in`,`norm_rect_in`,!1),this.m={detections:[]},S(e=this.i=new is,0,1,t=new U),w(this.i,2,.5),w(this.i,3,.3)}D(){return`FaceDetector`}get baseOptions(){return x(this.i,U,1)}set baseOptions(e){S(this.i,0,1,e)}A(e){return`minDetectionConfidence`in e&&w(this.i,2,e.minDetectionConfidence??.5),`minSuppressionThreshold`in e&&w(this.i,3,e.minSuppressionThreshold??.3),this.l(e)}H(e,t){return this.m={detections:[]},Xl(this,e,t),this.m}I(e,t,n){return this.m={detections:[]},Zl(this,e,n,t),this.m}u(){var e=new wo;V(e,`image_in`),V(e,`norm_rect_in`),H(e,`detections`);var t=new _o;Ri(t,os,this.i);var n=new yo;yr(n,2,`mediapipe.tasks.vision.face_detector.FaceDetectorGraph`),z(n,`IMAGE:image_in`),z(n,`NORM_RECT:norm_rect_in`),B(n,`DETECTIONS:detections`),n.A(t),Co(e,n),this.h.attachProtoVectorListener(`detections`,(e,t)=>{for(let t of e)e=Po(t),this.m.detections.push(ic(e));K(this,t)}),this.h.attachEmptyPacketListener(`detections`,e=>{K(this,e)}),e=e.h(),this.setGraph(new Uint8Array(e),!0)}};eu.prototype.detectForVideo=eu.prototype.I,eu.prototype.detect=eu.prototype.H,eu.prototype.setOptions=eu.prototype.A,eu.createFromModelPath=async function(e,t){return X(eu,e,{baseOptions:{modelAssetPath:t}})},eu.createFromModelBuffer=function(e,t){return X(eu,e,{baseOptions:{modelAssetBuffer:t}})},eu.createFromOptions=function(e,t){return X(eu,e,t)};var tu=Gl([61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]),nu=Gl([263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]),ru=Gl([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),iu=Gl([474,475],[475,476],[476,477],[477,474]),au=Gl([33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]),ou=Gl([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),su=Gl([469,470],[470,471],[471,472],[472,469]),cu=Gl([10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,361],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]),lu=[...tu,...nu,...ru,...au,...ou,...cu],uu=Gl([127,34],[34,139],[139,127],[11,0],[0,37],[37,11],[232,231],[231,120],[120,232],[72,37],[37,39],[39,72],[128,121],[121,47],[47,128],[232,121],[121,128],[128,232],[104,69],[69,67],[67,104],[175,171],[171,148],[148,175],[118,50],[50,101],[101,118],[73,39],[39,40],[40,73],[9,151],[151,108],[108,9],[48,115],[115,131],[131,48],[194,204],[204,211],[211,194],[74,40],[40,185],[185,74],[80,42],[42,183],[183,80],[40,92],[92,186],[186,40],[230,229],[229,118],[118,230],[202,212],[212,214],[214,202],[83,18],[18,17],[17,83],[76,61],[61,146],[146,76],[160,29],[29,30],[30,160],[56,157],[157,173],[173,56],[106,204],[204,194],[194,106],[135,214],[214,192],[192,135],[203,165],[165,98],[98,203],[21,71],[71,68],[68,21],[51,45],[45,4],[4,51],[144,24],[24,23],[23,144],[77,146],[146,91],[91,77],[205,50],[50,187],[187,205],[201,200],[200,18],[18,201],[91,106],[106,182],[182,91],[90,91],[91,181],[181,90],[85,84],[84,17],[17,85],[206,203],[203,36],[36,206],[148,171],[171,140],[140,148],[92,40],[40,39],[39,92],[193,189],[189,244],[244,193],[159,158],[158,28],[28,159],[247,246],[246,161],[161,247],[236,3],[3,196],[196,236],[54,68],[68,104],[104,54],[193,168],[168,8],[8,193],[117,228],[228,31],[31,117],[189,193],[193,55],[55,189],[98,97],[97,99],[99,98],[126,47],[47,100],[100,126],[166,79],[79,218],[218,166],[155,154],[154,26],[26,155],[209,49],[49,131],[131,209],[135,136],[136,150],[150,135],[47,126],[126,217],[217,47],[223,52],[52,53],[53,223],[45,51],[51,134],[134,45],[211,170],[170,140],[140,211],[67,69],[69,108],[108,67],[43,106],[106,91],[91,43],[230,119],[119,120],[120,230],[226,130],[130,247],[247,226],[63,53],[53,52],[52,63],[238,20],[20,242],[242,238],[46,70],[70,156],[156,46],[78,62],[62,96],[96,78],[46,53],[53,63],[63,46],[143,34],[34,227],[227,143],[123,117],[117,111],[111,123],[44,125],[125,19],[19,44],[236,134],[134,51],[51,236],[216,206],[206,205],[205,216],[154,153],[153,22],[22,154],[39,37],[37,167],[167,39],[200,201],[201,208],[208,200],[36,142],[142,100],[100,36],[57,212],[212,202],[202,57],[20,60],[60,99],[99,20],[28,158],[158,157],[157,28],[35,226],[226,113],[113,35],[160,159],[159,27],[27,160],[204,202],[202,210],[210,204],[113,225],[225,46],[46,113],[43,202],[202,204],[204,43],[62,76],[76,77],[77,62],[137,123],[123,116],[116,137],[41,38],[38,72],[72,41],[203,129],[129,142],[142,203],[64,98],[98,240],[240,64],[49,102],[102,64],[64,49],[41,73],[73,74],[74,41],[212,216],[216,207],[207,212],[42,74],[74,184],[184,42],[169,170],[170,211],[211,169],[170,149],[149,176],[176,170],[105,66],[66,69],[69,105],[122,6],[6,168],[168,122],[123,147],[147,187],[187,123],[96,77],[77,90],[90,96],[65,55],[55,107],[107,65],[89,90],[90,180],[180,89],[101,100],[100,120],[120,101],[63,105],[105,104],[104,63],[93,137],[137,227],[227,93],[15,86],[86,85],[85,15],[129,102],[102,49],[49,129],[14,87],[87,86],[86,14],[55,8],[8,9],[9,55],[100,47],[47,121],[121,100],[145,23],[23,22],[22,145],[88,89],[89,179],[179,88],[6,122],[122,196],[196,6],[88,95],[95,96],[96,88],[138,172],[172,136],[136,138],[215,58],[58,172],[172,215],[115,48],[48,219],[219,115],[42,80],[80,81],[81,42],[195,3],[3,51],[51,195],[43,146],[146,61],[61,43],[171,175],[175,199],[199,171],[81,82],[82,38],[38,81],[53,46],[46,225],[225,53],[144,163],[163,110],[110,144],[52,65],[65,66],[66,52],[229,228],[228,117],[117,229],[34,127],[127,234],[234,34],[107,108],[108,69],[69,107],[109,108],[108,151],[151,109],[48,64],[64,235],[235,48],[62,78],[78,191],[191,62],[129,209],[209,126],[126,129],[111,35],[35,143],[143,111],[117,123],[123,50],[50,117],[222,65],[65,52],[52,222],[19,125],[125,141],[141,19],[221,55],[55,65],[65,221],[3,195],[195,197],[197,3],[25,7],[7,33],[33,25],[220,237],[237,44],[44,220],[70,71],[71,139],[139,70],[122,193],[193,245],[245,122],[247,130],[130,33],[33,247],[71,21],[21,162],[162,71],[170,169],[169,150],[150,170],[188,174],[174,196],[196,188],[216,186],[186,92],[92,216],[2,97],[97,167],[167,2],[141,125],[125,241],[241,141],[164,167],[167,37],[37,164],[72,38],[38,12],[12,72],[38,82],[82,13],[13,38],[63,68],[68,71],[71,63],[226,35],[35,111],[111,226],[101,50],[50,205],[205,101],[206,92],[92,165],[165,206],[209,198],[198,217],[217,209],[165,167],[167,97],[97,165],[220,115],[115,218],[218,220],[133,112],[112,243],[243,133],[239,238],[238,241],[241,239],[214,135],[135,169],[169,214],[190,173],[173,133],[133,190],[171,208],[208,32],[32,171],[125,44],[44,237],[237,125],[86,87],[87,178],[178,86],[85,86],[86,179],[179,85],[84,85],[85,180],[180,84],[83,84],[84,181],[181,83],[201,83],[83,182],[182,201],[137,93],[93,132],[132,137],[76,62],[62,183],[183,76],[61,76],[76,184],[184,61],[57,61],[61,185],[185,57],[212,57],[57,186],[186,212],[214,207],[207,187],[187,214],[34,143],[143,156],[156,34],[79,239],[239,237],[237,79],[123,137],[137,177],[177,123],[44,1],[1,4],[4,44],[201,194],[194,32],[32,201],[64,102],[102,129],[129,64],[213,215],[215,138],[138,213],[59,166],[166,219],[219,59],[242,99],[99,97],[97,242],[2,94],[94,141],[141,2],[75,59],[59,235],[235,75],[24,110],[110,228],[228,24],[25,130],[130,226],[226,25],[23,24],[24,229],[229,23],[22,23],[23,230],[230,22],[26,22],[22,231],[231,26],[112,26],[26,232],[232,112],[189,190],[190,243],[243,189],[221,56],[56,190],[190,221],[28,56],[56,221],[221,28],[27,28],[28,222],[222,27],[29,27],[27,223],[223,29],[30,29],[29,224],[224,30],[247,30],[30,225],[225,247],[238,79],[79,20],[20,238],[166,59],[59,75],[75,166],[60,75],[75,240],[240,60],[147,177],[177,215],[215,147],[20,79],[79,166],[166,20],[187,147],[147,213],[213,187],[112,233],[233,244],[244,112],[233,128],[128,245],[245,233],[128,114],[114,188],[188,128],[114,217],[217,174],[174,114],[131,115],[115,220],[220,131],[217,198],[198,236],[236,217],[198,131],[131,134],[134,198],[177,132],[132,58],[58,177],[143,35],[35,124],[124,143],[110,163],[163,7],[7,110],[228,110],[110,25],[25,228],[356,389],[389,368],[368,356],[11,302],[302,267],[267,11],[452,350],[350,349],[349,452],[302,303],[303,269],[269,302],[357,343],[343,277],[277,357],[452,453],[453,357],[357,452],[333,332],[332,297],[297,333],[175,152],[152,377],[377,175],[347,348],[348,330],[330,347],[303,304],[304,270],[270,303],[9,336],[336,337],[337,9],[278,279],[279,360],[360,278],[418,262],[262,431],[431,418],[304,408],[408,409],[409,304],[310,415],[415,407],[407,310],[270,409],[409,410],[410,270],[450,348],[348,347],[347,450],[422,430],[430,434],[434,422],[313,314],[314,17],[17,313],[306,307],[307,375],[375,306],[387,388],[388,260],[260,387],[286,414],[414,398],[398,286],[335,406],[406,418],[418,335],[364,367],[367,416],[416,364],[423,358],[358,327],[327,423],[251,284],[284,298],[298,251],[281,5],[5,4],[4,281],[373,374],[374,253],[253,373],[307,320],[320,321],[321,307],[425,427],[427,411],[411,425],[421,313],[313,18],[18,421],[321,405],[405,406],[406,321],[320,404],[404,405],[405,320],[315,16],[16,17],[17,315],[426,425],[425,266],[266,426],[377,400],[400,369],[369,377],[322,391],[391,269],[269,322],[417,465],[465,464],[464,417],[386,257],[257,258],[258,386],[466,260],[260,388],[388,466],[456,399],[399,419],[419,456],[284,332],[332,333],[333,284],[417,285],[285,8],[8,417],[346,340],[340,261],[261,346],[413,441],[441,285],[285,413],[327,460],[460,328],[328,327],[355,371],[371,329],[329,355],[392,439],[439,438],[438,392],[382,341],[341,256],[256,382],[429,420],[420,360],[360,429],[364,394],[394,379],[379,364],[277,343],[343,437],[437,277],[443,444],[444,283],[283,443],[275,440],[440,363],[363,275],[431,262],[262,369],[369,431],[297,338],[338,337],[337,297],[273,375],[375,321],[321,273],[450,451],[451,349],[349,450],[446,342],[342,467],[467,446],[293,334],[334,282],[282,293],[458,461],[461,462],[462,458],[276,353],[353,383],[383,276],[308,324],[324,325],[325,308],[276,300],[300,293],[293,276],[372,345],[345,447],[447,372],[352,345],[345,340],[340,352],[274,1],[1,19],[19,274],[456,248],[248,281],[281,456],[436,427],[427,425],[425,436],[381,256],[256,252],[252,381],[269,391],[391,393],[393,269],[200,199],[199,428],[428,200],[266,330],[330,329],[329,266],[287,273],[273,422],[422,287],[250,462],[462,328],[328,250],[258,286],[286,384],[384,258],[265,353],[353,342],[342,265],[387,259],[259,257],[257,387],[424,431],[431,430],[430,424],[342,353],[353,276],[276,342],[273,335],[335,424],[424,273],[292,325],[325,307],[307,292],[366,447],[447,345],[345,366],[271,303],[303,302],[302,271],[423,266],[266,371],[371,423],[294,455],[455,460],[460,294],[279,278],[278,294],[294,279],[271,272],[272,304],[304,271],[432,434],[434,427],[427,432],[272,407],[407,408],[408,272],[394,430],[430,431],[431,394],[395,369],[369,400],[400,395],[334,333],[333,299],[299,334],[351,417],[417,168],[168,351],[352,280],[280,411],[411,352],[325,319],[319,320],[320,325],[295,296],[296,336],[336,295],[319,403],[403,404],[404,319],[330,348],[348,349],[349,330],[293,298],[298,333],[333,293],[323,454],[454,447],[447,323],[15,16],[16,315],[315,15],[358,429],[429,279],[279,358],[14,15],[15,316],[316,14],[285,336],[336,9],[9,285],[329,349],[349,350],[350,329],[374,380],[380,252],[252,374],[318,402],[402,403],[403,318],[6,197],[197,419],[419,6],[318,319],[319,325],[325,318],[367,364],[364,365],[365,367],[435,367],[367,397],[397,435],[344,438],[438,439],[439,344],[272,271],[271,311],[311,272],[195,5],[5,281],[281,195],[273,287],[287,291],[291,273],[396,428],[428,199],[199,396],[311,271],[271,268],[268,311],[283,444],[444,445],[445,283],[373,254],[254,339],[339,373],[282,334],[334,296],[296,282],[449,347],[347,346],[346,449],[264,447],[447,454],[454,264],[336,296],[296,299],[299,336],[338,10],[10,151],[151,338],[278,439],[439,455],[455,278],[292,407],[407,415],[415,292],[358,371],[371,355],[355,358],[340,345],[345,372],[372,340],[346,347],[347,280],[280,346],[442,443],[443,282],[282,442],[19,94],[94,370],[370,19],[441,442],[442,295],[295,441],[248,419],[419,197],[197,248],[263,255],[255,359],[359,263],[440,275],[275,274],[274,440],[300,383],[383,368],[368,300],[351,412],[412,465],[465,351],[263,467],[467,466],[466,263],[301,368],[368,389],[389,301],[395,378],[378,379],[379,395],[412,351],[351,419],[419,412],[436,426],[426,322],[322,436],[2,164],[164,393],[393,2],[370,462],[462,461],[461,370],[164,0],[0,267],[267,164],[302,11],[11,12],[12,302],[268,12],[12,13],[13,268],[293,300],[300,301],[301,293],[446,261],[261,340],[340,446],[330,266],[266,425],[425,330],[426,423],[423,391],[391,426],[429,355],[355,437],[437,429],[391,327],[327,326],[326,391],[440,457],[457,438],[438,440],[341,382],[382,362],[362,341],[459,457],[457,461],[461,459],[434,430],[430,394],[394,434],[414,463],[463,362],[362,414],[396,369],[369,262],[262,396],[354,461],[461,457],[457,354],[316,403],[403,402],[402,316],[315,404],[404,403],[403,315],[314,405],[405,404],[404,314],[313,406],[406,405],[405,313],[421,418],[418,406],[406,421],[366,401],[401,361],[361,366],[306,408],[408,407],[407,306],[291,409],[409,408],[408,291],[287,410],[410,409],[409,287],[432,436],[436,410],[410,432],[434,416],[416,411],[411,434],[264,368],[368,383],[383,264],[309,438],[438,457],[457,309],[352,376],[376,401],[401,352],[274,275],[275,4],[4,274],[421,428],[428,262],[262,421],[294,327],[327,358],[358,294],[433,416],[416,367],[367,433],[289,455],[455,439],[439,289],[462,370],[370,326],[326,462],[2,326],[326,370],[370,2],[305,460],[460,455],[455,305],[254,449],[449,448],[448,254],[255,261],[261,446],[446,255],[253,450],[450,449],[449,253],[252,451],[451,450],[450,252],[256,452],[452,451],[451,256],[341,453],[453,452],[452,341],[413,464],[464,463],[463,413],[441,413],[413,414],[414,441],[258,442],[442,441],[441,258],[257,443],[443,442],[442,257],[259,444],[444,443],[443,259],[260,445],[445,444],[444,260],[467,342],[342,445],[445,467],[459,458],[458,250],[250,459],[289,392],[392,290],[290,289],[290,328],[328,460],[460,290],[376,433],[433,435],[435,376],[250,290],[290,392],[392,250],[411,416],[416,433],[433,411],[341,463],[463,464],[464,341],[453,464],[464,465],[465,453],[357,465],[465,412],[412,357],[343,412],[412,399],[399,343],[360,363],[363,440],[440,360],[437,399],[399,456],[456,437],[420,456],[456,363],[363,420],[401,435],[435,288],[288,401],[372,383],[383,353],[353,372],[339,255],[255,249],[249,339],[448,261],[261,255],[255,448],[133,243],[243,190],[190,133],[133,155],[155,112],[112,133],[33,246],[246,247],[247,33],[33,130],[130,25],[25,33],[398,384],[384,286],[286,398],[362,398],[398,414],[414,362],[362,463],[463,341],[341,362],[263,359],[359,467],[467,263],[263,249],[249,255],[255,263],[466,467],[467,260],[260,466],[75,60],[60,166],[166,75],[238,239],[239,79],[79,238],[162,127],[127,139],[139,162],[72,11],[11,37],[37,72],[121,232],[232,120],[120,121],[73,72],[72,39],[39,73],[114,128],[128,47],[47,114],[233,232],[232,128],[128,233],[103,104],[104,67],[67,103],[152,175],[175,148],[148,152],[119,118],[118,101],[101,119],[74,73],[73,40],[40,74],[107,9],[9,108],[108,107],[49,48],[48,131],[131,49],[32,194],[194,211],[211,32],[184,74],[74,185],[185,184],[191,80],[80,183],[183,191],[185,40],[40,186],[186,185],[119,230],[230,118],[118,119],[210,202],[202,214],[214,210],[84,83],[83,17],[17,84],[77,76],[76,146],[146,77],[161,160],[160,30],[30,161],[190,56],[56,173],[173,190],[182,106],[106,194],[194,182],[138,135],[135,192],[192,138],[129,203],[203,98],[98,129],[54,21],[21,68],[68,54],[5,51],[51,4],[4,5],[145,144],[144,23],[23,145],[90,77],[77,91],[91,90],[207,205],[205,187],[187,207],[83,201],[201,18],[18,83],[181,91],[91,182],[182,181],[180,90],[90,181],[181,180],[16,85],[85,17],[17,16],[205,206],[206,36],[36,205],[176,148],[148,140],[140,176],[165,92],[92,39],[39,165],[245,193],[193,244],[244,245],[27,159],[159,28],[28,27],[30,247],[247,161],[161,30],[174,236],[236,196],[196,174],[103,54],[54,104],[104,103],[55,193],[193,8],[8,55],[111,117],[117,31],[31,111],[221,189],[189,55],[55,221],[240,98],[98,99],[99,240],[142,126],[126,100],[100,142],[219,166],[166,218],[218,219],[112,155],[155,26],[26,112],[198,209],[209,131],[131,198],[169,135],[135,150],[150,169],[114,47],[47,217],[217,114],[224,223],[223,53],[53,224],[220,45],[45,134],[134,220],[32,211],[211,140],[140,32],[109,67],[67,108],[108,109],[146,43],[43,91],[91,146],[231,230],[230,120],[120,231],[113,226],[226,247],[247,113],[105,63],[63,52],[52,105],[241,238],[238,242],[242,241],[124,46],[46,156],[156,124],[95,78],[78,96],[96,95],[70,46],[46,63],[63,70],[116,143],[143,227],[227,116],[116,123],[123,111],[111,116],[1,44],[44,19],[19,1],[3,236],[236,51],[51,3],[207,216],[216,205],[205,207],[26,154],[154,22],[22,26],[165,39],[39,167],[167,165],[199,200],[200,208],[208,199],[101,36],[36,100],[100,101],[43,57],[57,202],[202,43],[242,20],[20,99],[99,242],[56,28],[28,157],[157,56],[124,35],[35,113],[113,124],[29,160],[160,27],[27,29],[211,204],[204,210],[210,211],[124,113],[113,46],[46,124],[106,43],[43,204],[204,106],[96,62],[62,77],[77,96],[227,137],[137,116],[116,227],[73,41],[41,72],[72,73],[36,203],[203,142],[142,36],[235,64],[64,240],[240,235],[48,49],[49,64],[64,48],[42,41],[41,74],[74,42],[214,212],[212,207],[207,214],[183,42],[42,184],[184,183],[210,169],[169,211],[211,210],[140,170],[170,176],[176,140],[104,105],[105,69],[69,104],[193,122],[122,168],[168,193],[50,123],[123,187],[187,50],[89,96],[96,90],[90,89],[66,65],[65,107],[107,66],[179,89],[89,180],[180,179],[119,101],[101,120],[120,119],[68,63],[63,104],[104,68],[234,93],[93,227],[227,234],[16,15],[15,85],[85,16],[209,129],[129,49],[49,209],[15,14],[14,86],[86,15],[107,55],[55,9],[9,107],[120,100],[100,121],[121,120],[153,145],[145,22],[22,153],[178,88],[88,179],[179,178],[197,6],[6,196],[196,197],[89,88],[88,96],[96,89],[135,138],[138,136],[136,135],[138,215],[215,172],[172,138],[218,115],[115,219],[219,218],[41,42],[42,81],[81,41],[5,195],[195,51],[51,5],[57,43],[43,61],[61,57],[208,171],[171,199],[199,208],[41,81],[81,38],[38,41],[224,53],[53,225],[225,224],[24,144],[144,110],[110,24],[105,52],[52,66],[66,105],[118,229],[229,117],[117,118],[227,34],[34,234],[234,227],[66,107],[107,69],[69,66],[10,109],[109,151],[151,10],[219,48],[48,235],[235,219],[183,62],[62,191],[191,183],[142,129],[129,126],[126,142],[116,111],[111,143],[143,116],[118,117],[117,50],[50,118],[223,222],[222,52],[52,223],[94,19],[19,141],[141,94],[222,221],[221,65],[65,222],[196,3],[3,197],[197,196],[45,220],[220,44],[44,45],[156,70],[70,139],[139,156],[188,122],[122,245],[245,188],[139,71],[71,162],[162,139],[149,170],[170,150],[150,149],[122,188],[188,196],[196,122],[206,216],[216,92],[92,206],[164,2],[2,167],[167,164],[242,141],[141,241],[241,242],[0,164],[164,37],[37,0],[11,72],[72,12],[12,11],[12,38],[38,13],[13,12],[70,63],[63,71],[71,70],[31,226],[226,111],[111,31],[36,101],[101,205],[205,36],[203,206],[206,165],[165,203],[126,209],[209,217],[217,126],[98,165],[165,97],[97,98],[237,220],[220,218],[218,237],[237,239],[239,241],[241,237],[210,214],[214,169],[169,210],[140,171],[171,32],[32,140],[241,125],[125,237],[237,241],[179,86],[86,178],[178,179],[180,85],[85,179],[179,180],[181,84],[84,180],[180,181],[182,83],[83,181],[181,182],[194,201],[201,182],[182,194],[177,137],[137,132],[132,177],[184,76],[76,183],[183,184],[185,61],[61,184],[184,185],[186,57],[57,185],[185,186],[216,212],[212,186],[186,216],[192,214],[214,187],[187,192],[139,34],[34,156],[156,139],[218,79],[79,237],[237,218],[147,123],[123,177],[177,147],[45,44],[44,4],[4,45],[208,201],[201,32],[32,208],[98,64],[64,129],[129,98],[192,213],[213,138],[138,192],[235,59],[59,219],[219,235],[141,242],[242,97],[97,141],[97,2],[2,141],[141,97],[240,75],[75,235],[235,240],[229,24],[24,228],[228,229],[31,25],[25,226],[226,31],[230,23],[23,229],[229,230],[231,22],[22,230],[230,231],[232,26],[26,231],[231,232],[233,112],[112,232],[232,233],[244,189],[189,243],[243,244],[189,221],[221,190],[190,189],[222,28],[28,221],[221,222],[223,27],[27,222],[222,223],[224,29],[29,223],[223,224],[225,30],[30,224],[224,225],[113,247],[247,225],[225,113],[99,60],[60,240],[240,99],[213,147],[147,215],[215,213],[60,20],[20,166],[166,60],[192,187],[187,213],[213,192],[243,112],[112,244],[244,243],[244,233],[233,245],[245,244],[245,128],[128,188],[188,245],[188,114],[114,174],[174,188],[134,131],[131,220],[220,134],[174,217],[217,236],[236,174],[236,198],[198,134],[134,236],[215,177],[177,58],[58,215],[156,143],[143,124],[124,156],[25,110],[110,7],[7,25],[31,228],[228,25],[25,31],[264,356],[356,368],[368,264],[0,11],[11,267],[267,0],[451,452],[452,349],[349,451],[267,302],[302,269],[269,267],[350,357],[357,277],[277,350],[350,452],[452,357],[357,350],[299,333],[333,297],[297,299],[396,175],[175,377],[377,396],[280,347],[347,330],[330,280],[269,303],[303,270],[270,269],[151,9],[9,337],[337,151],[344,278],[278,360],[360,344],[424,418],[418,431],[431,424],[270,304],[304,409],[409,270],[272,310],[310,407],[407,272],[322,270],[270,410],[410,322],[449,450],[450,347],[347,449],[432,422],[422,434],[434,432],[18,313],[313,17],[17,18],[291,306],[306,375],[375,291],[259,387],[387,260],[260,259],[424,335],[335,418],[418,424],[434,364],[364,416],[416,434],[391,423],[423,327],[327,391],[301,251],[251,298],[298,301],[275,281],[281,4],[4,275],[254,373],[373,253],[253,254],[375,307],[307,321],[321,375],[280,425],[425,411],[411,280],[200,421],[421,18],[18,200],[335,321],[321,406],[406,335],[321,320],[320,405],[405,321],[314,315],[315,17],[17,314],[423,426],[426,266],[266,423],[396,377],[377,369],[369,396],[270,322],[322,269],[269,270],[413,417],[417,464],[464,413],[385,386],[386,258],[258,385],[248,456],[456,419],[419,248],[298,284],[284,333],[333,298],[168,417],[417,8],[8,168],[448,346],[346,261],[261,448],[417,413],[413,285],[285,417],[326,327],[327,328],[328,326],[277,355],[355,329],[329,277],[309,392],[392,438],[438,309],[381,382],[382,256],[256,381],[279,429],[429,360],[360,279],[365,364],[364,379],[379,365],[355,277],[277,437],[437,355],[282,443],[443,283],[283,282],[281,275],[275,363],[363,281],[395,431],[431,369],[369,395],[299,297],[297,337],[337,299],[335,273],[273,321],[321,335],[348,450],[450,349],[349,348],[359,446],[446,467],[467,359],[283,293],[293,282],[282,283],[250,458],[458,462],[462,250],[300,276],[276,383],[383,300],[292,308],[308,325],[325,292],[283,276],[276,293],[293,283],[264,372],[372,447],[447,264],[346,352],[352,340],[340,346],[354,274],[274,19],[19,354],[363,456],[456,281],[281,363],[426,436],[436,425],[425,426],[380,381],[381,252],[252,380],[267,269],[269,393],[393,267],[421,200],[200,428],[428,421],[371,266],[266,329],[329,371],[432,287],[287,422],[422,432],[290,250],[250,328],[328,290],[385,258],[258,384],[384,385],[446,265],[265,342],[342,446],[386,387],[387,257],[257,386],[422,424],[424,430],[430,422],[445,342],[342,276],[276,445],[422,273],[273,424],[424,422],[306,292],[292,307],[307,306],[352,366],[366,345],[345,352],[268,271],[271,302],[302,268],[358,423],[423,371],[371,358],[327,294],[294,460],[460,327],[331,279],[279,294],[294,331],[303,271],[271,304],[304,303],[436,432],[432,427],[427,436],[304,272],[272,408],[408,304],[395,394],[394,431],[431,395],[378,395],[395,400],[400,378],[296,334],[334,299],[299,296],[6,351],[351,168],[168,6],[376,352],[352,411],[411,376],[307,325],[325,320],[320,307],[285,295],[295,336],[336,285],[320,319],[319,404],[404,320],[329,330],[330,349],[349,329],[334,293],[293,333],[333,334],[366,323],[323,447],[447,366],[316,15],[15,315],[315,316],[331,358],[358,279],[279,331],[317,14],[14,316],[316,317],[8,285],[285,9],[9,8],[277,329],[329,350],[350,277],[253,374],[374,252],[252,253],[319,318],[318,403],[403,319],[351,6],[6,419],[419,351],[324,318],[318,325],[325,324],[397,367],[367,365],[365,397],[288,435],[435,397],[397,288],[278,344],[344,439],[439,278],[310,272],[272,311],[311,310],[248,195],[195,281],[281,248],[375,273],[273,291],[291,375],[175,396],[396,199],[199,175],[312,311],[311,268],[268,312],[276,283],[283,445],[445,276],[390,373],[373,339],[339,390],[295,282],[282,296],[296,295],[448,449],[449,346],[346,448],[356,264],[264,454],[454,356],[337,336],[336,299],[299,337],[337,338],[338,151],[151,337],[294,278],[278,455],[455,294],[308,292],[292,415],[415,308],[429,358],[358,355],[355,429],[265,340],[340,372],[372,265],[352,346],[346,280],[280,352],[295,442],[442,282],[282,295],[354,19],[19,370],[370,354],[285,441],[441,295],[295,285],[195,248],[248,197],[197,195],[457,440],[440,274],[274,457],[301,300],[300,368],[368,301],[417,351],[351,465],[465,417],[251,301],[301,389],[389,251],[394,395],[395,379],[379,394],[399,412],[412,419],[419,399],[410,436],[436,322],[322,410],[326,2],[2,393],[393,326],[354,370],[370,461],[461,354],[393,164],[164,267],[267,393],[268,302],[302,12],[12,268],[312,268],[268,13],[13,312],[298,293],[293,301],[301,298],[265,446],[446,340],[340,265],[280,330],[330,425],[425,280],[322,426],[426,391],[391,322],[420,429],[429,437],[437,420],[393,391],[391,326],[326,393],[344,440],[440,438],[438,344],[458,459],[459,461],[461,458],[364,434],[434,394],[394,364],[428,396],[396,262],[262,428],[274,354],[354,457],[457,274],[317,316],[316,402],[402,317],[316,315],[315,403],[403,316],[315,314],[314,404],[404,315],[314,313],[313,405],[405,314],[313,421],[421,406],[406,313],[323,366],[366,361],[361,323],[292,306],[306,407],[407,292],[306,291],[291,408],[408,306],[291,287],[287,409],[409,291],[287,432],[432,410],[410,287],[427,434],[434,411],[411,427],[372,264],[264,383],[383,372],[459,309],[309,457],[457,459],[366,352],[352,401],[401,366],[1,274],[274,4],[4,1],[418,421],[421,262],[262,418],[331,294],[294,358],[358,331],[435,433],[433,367],[367,435],[392,289],[289,439],[439,392],[328,462],[462,326],[326,328],[94,2],[2,370],[370,94],[289,305],[305,455],[455,289],[339,254],[254,448],[448,339],[359,255],[255,446],[446,359],[254,253],[253,449],[449,254],[253,252],[252,450],[450,253],[252,256],[256,451],[451,252],[256,341],[341,452],[452,256],[414,413],[413,463],[463,414],[286,441],[441,414],[414,286],[286,258],[258,441],[441,286],[258,257],[257,442],[442,258],[257,259],[259,443],[443,257],[259,260],[260,444],[444,259],[260,467],[467,445],[445,260],[309,459],[459,250],[250,309],[305,289],[289,290],[290,305],[305,290],[290,460],[460,305],[401,376],[376,435],[435,401],[309,250],[250,392],[392,309],[376,411],[411,433],[433,376],[453,341],[341,464],[464,453],[357,453],[453,465],[465,357],[343,357],[357,412],[412,343],[437,343],[343,399],[399,437],[344,360],[360,440],[440,344],[420,437],[437,456],[456,420],[360,420],[420,363],[363,360],[361,401],[401,288],[288,361],[265,372],[372,353],[353,265],[390,339],[339,249],[249,390],[339,448],[448,255],[255,339]);function du(e){e.m={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var Z=class extends $l{constructor(e,t){super(new Jl(e,t),`image_in`,`norm_rect`,!1),this.m={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,S(e=this.i=new ls,0,1,t=new U),this.C=new cs,S(this.i,0,3,this.C),this.v=new is,S(this.i,0,2,this.v),hr(this.v,4,1),w(this.v,2,.5),w(this.C,2,.5),w(this.i,4,.5)}D(){return`FaceLandmarker`}get baseOptions(){return x(this.i,U,1)}set baseOptions(e){S(this.i,0,1,e)}A(e){return`numFaces`in e&&hr(this.v,4,e.numFaces??1),`minFaceDetectionConfidence`in e&&w(this.v,2,e.minFaceDetectionConfidence??.5),`minTrackingConfidence`in e&&w(this.i,4,e.minTrackingConfidence??.5),`minFacePresenceConfidence`in e&&w(this.C,2,e.minFacePresenceConfidence??.5),`outputFaceBlendshapes`in e&&(this.outputFaceBlendshapes=!!e.outputFaceBlendshapes),`outputFacialTransformationMatrixes`in e&&(this.outputFacialTransformationMatrixes=!!e.outputFacialTransformationMatrixes),this.l(e)}H(e,t){return du(this),Xl(this,e,t),this.m}I(e,t,n){return du(this),Zl(this,e,n,t),this.m}u(){var e=new wo;V(e,`image_in`),V(e,`norm_rect`),H(e,`face_landmarks`);var t=new _o;Ri(t,ds,this.i);var n=new yo;yr(n,2,`mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph`),z(n,`IMAGE:image_in`),z(n,`NORM_RECT:norm_rect`),B(n,`NORM_LANDMARKS:face_landmarks`),n.A(t),Co(e,n),this.h.attachProtoVectorListener(`face_landmarks`,(e,t)=>{for(let t of e)e=Ro(t),this.m.faceLandmarks.push(ac(e));K(this,t)}),this.h.attachEmptyPacketListener(`face_landmarks`,e=>{K(this,e)}),this.outputFaceBlendshapes&&(H(e,`blendshapes`),B(n,`BLENDSHAPES:blendshapes`),this.h.attachProtoVectorListener(`blendshapes`,(e,t)=>{if(this.outputFaceBlendshapes)for(let t of e)e=Ao(t),this.m.faceBlendshapes.push(nc(e.h()??[]));K(this,t)}),this.h.attachEmptyPacketListener(`blendshapes`,e=>{K(this,e)})),this.outputFacialTransformationMatrixes&&(H(e,`face_geometry`),B(n,`FACE_GEOMETRY:face_geometry`),this.h.attachProtoVectorListener(`face_geometry`,(e,t)=>{if(this.outputFacialTransformationMatrixes)for(let t of e)(e=x(e=ss(t),zo,2))&&this.m.facialTransformationMatrixes.push({rows:fr(e,1)??0??0,columns:fr(e,2)??0??0,data:Wn(e,3,Pt,Un()).slice()??[]});K(this,t)}),this.h.attachEmptyPacketListener(`face_geometry`,e=>{K(this,e)})),e=e.h(),this.setGraph(new Uint8Array(e),!0)}};Z.prototype.detectForVideo=Z.prototype.I,Z.prototype.detect=Z.prototype.H,Z.prototype.setOptions=Z.prototype.A,Z.createFromModelPath=function(e,t){return X(Z,e,{baseOptions:{modelAssetPath:t}})},Z.createFromModelBuffer=function(e,t){return X(Z,e,{baseOptions:{modelAssetBuffer:t}})},Z.createFromOptions=function(e,t){return X(Z,e,t)},Z.FACE_LANDMARKS_LIPS=tu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$face_landmarker$face_landmarker.FaceLandmarker.FACE_LANDMARKS_LIPS`,Z.FACE_LANDMARKS_LIPS),Z.FACE_LANDMARKS_LEFT_EYE=nu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$face_landmarker$face_landmarker.FaceLandmarker.FACE_LANDMARKS_LEFT_EYE`,Z.FACE_LANDMARKS_LEFT_EYE),Z.FACE_LANDMARKS_LEFT_EYEBROW=ru,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$face_landmarker$face_landmarker.FaceLandmarker.FACE_LANDMARKS_LEFT_EYEBROW`,Z.FACE_LANDMARKS_LEFT_EYEBROW),Z.FACE_LANDMARKS_LEFT_IRIS=iu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$face_landmarker$face_landmarker.FaceLandmarker.FACE_LANDMARKS_LEFT_IRIS`,Z.FACE_LANDMARKS_LEFT_IRIS),Z.FACE_LANDMARKS_RIGHT_EYE=au,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$face_landmarker$face_landmarker.FaceLandmarker.FACE_LANDMARKS_RIGHT_EYE`,Z.FACE_LANDMARKS_RIGHT_EYE),Z.FACE_LANDMARKS_RIGHT_EYEBROW=ou,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$face_landmarker$face_landmarker.FaceLandmarker.FACE_LANDMARKS_RIGHT_EYEBROW`,Z.FACE_LANDMARKS_RIGHT_EYEBROW),Z.FACE_LANDMARKS_RIGHT_IRIS=su,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$face_landmarker$face_landmarker.FaceLandmarker.FACE_LANDMARKS_RIGHT_IRIS`,Z.FACE_LANDMARKS_RIGHT_IRIS),Z.FACE_LANDMARKS_FACE_OVAL=cu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$face_landmarker$face_landmarker.FaceLandmarker.FACE_LANDMARKS_FACE_OVAL`,Z.FACE_LANDMARKS_FACE_OVAL),Z.FACE_LANDMARKS_CONTOURS=lu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$face_landmarker$face_landmarker.FaceLandmarker.FACE_LANDMARKS_CONTOURS`,Z.FACE_LANDMARKS_CONTOURS),Z.FACE_LANDMARKS_TESSELATION=uu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$face_landmarker$face_landmarker.FaceLandmarker.FACE_LANDMARKS_TESSELATION`,Z.FACE_LANDMARKS_TESSELATION);var fu=Gl([0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[0,17],[17,18],[18,19],[19,20]);function pu(e){e.gestures=[],e.landmarks=[],e.worldLandmarks=[],e.handedness=[]}function mu(e){return e.gestures.length===0?{gestures:[],landmarks:[],worldLandmarks:[],handedness:[],handednesses:[]}:{gestures:e.gestures,landmarks:e.landmarks,worldLandmarks:e.worldLandmarks,handedness:e.handedness,handednesses:e.handedness}}function hu(e,t=!0){var n=[];for(let i of e){var r=Ao(i);e=[];for(let n of r.h())r=t&&fr(n,1)!=null?fr(n,1)??0:-1,e.push({score:C(n,2)??0,index:r,categoryName:_(v(n,3))??``??``,displayName:_(v(n,4))??``??``});n.push(e)}return n}var gu=class extends $l{constructor(e,t){super(new Jl(e,t),`image_in`,`norm_rect`,!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],S(e=this.m=new vs,0,1,t=new U),this.v=new _s,S(this.m,0,2,this.v),this.G=new gs,S(this.v,0,3,this.G),this.C=new hs,S(this.v,0,2,this.C),this.i=new ms,S(this.m,0,3,this.i),w(this.C,2,.5),w(this.v,4,.5),w(this.G,2,.5)}D(){return`GestureRecognizer`}get baseOptions(){return x(this.m,U,1)}set baseOptions(e){S(this.m,0,1,e)}A(e){if(hr(this.C,3,e.numHands??1),`minHandDetectionConfidence`in e&&w(this.C,2,e.minHandDetectionConfidence??.5),`minTrackingConfidence`in e&&w(this.v,4,e.minTrackingConfidence??.5),`minHandPresenceConfidence`in e&&w(this.G,2,e.minHandPresenceConfidence??.5),e.cannedGesturesClassifierOptions){var t=new fs,n=t,r=ec(e.cannedGesturesClassifierOptions,x(this.i,fs,3)?.l());S(n,0,2,r),S(this.i,0,3,t)}else e.cannedGesturesClassifierOptions===void 0&&x(this.i,fs,3)?.h();return e.customGesturesClassifierOptions?(S(n=t=new fs,0,2,r=ec(e.customGesturesClassifierOptions,x(this.i,fs,4)?.l())),S(this.i,0,4,t)):e.customGesturesClassifierOptions===void 0&&x(this.i,fs,4)?.h(),this.l(e)}Ya(e,t){return pu(this),Xl(this,e,t),mu(this)}Za(e,t,n){return pu(this),Zl(this,e,n,t),mu(this)}u(){var e=new wo;V(e,`image_in`),V(e,`norm_rect`),H(e,`hand_gestures`),H(e,`hand_landmarks`),H(e,`world_hand_landmarks`),H(e,`handedness`);var t=new _o;Ri(t,Cs,this.m);var n=new yo;yr(n,2,`mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph`),z(n,`IMAGE:image_in`),z(n,`NORM_RECT:norm_rect`),B(n,`HAND_GESTURES:hand_gestures`),B(n,`LANDMARKS:hand_landmarks`),B(n,`WORLD_LANDMARKS:world_hand_landmarks`),B(n,`HANDEDNESS:handedness`),n.A(t),Co(e,n),this.h.attachProtoVectorListener(`hand_landmarks`,(e,t)=>{for(let t of e)e=Ro(t),this.landmarks.push(ac(e));K(this,t)}),this.h.attachEmptyPacketListener(`hand_landmarks`,e=>{K(this,e)}),this.h.attachProtoVectorListener(`world_hand_landmarks`,(e,t)=>{for(let t of e)e=Io(t),this.worldLandmarks.push(oc(e));K(this,t)}),this.h.attachEmptyPacketListener(`world_hand_landmarks`,e=>{K(this,e)}),this.h.attachProtoVectorListener(`hand_gestures`,(e,t)=>{this.gestures.push(...hu(e,!1)),K(this,t)}),this.h.attachEmptyPacketListener(`hand_gestures`,e=>{K(this,e)}),this.h.attachProtoVectorListener(`handedness`,(e,t)=>{this.handedness.push(...hu(e)),K(this,t)}),this.h.attachEmptyPacketListener(`handedness`,e=>{K(this,e)}),e=e.h(),this.setGraph(new Uint8Array(e),!0)}};function _u(e){return{landmarks:e.landmarks,worldLandmarks:e.worldLandmarks,handednesses:e.handedness,handedness:e.handedness}}gu.prototype.recognizeForVideo=gu.prototype.Za,gu.prototype.recognize=gu.prototype.Ya,gu.prototype.setOptions=gu.prototype.A,gu.createFromModelPath=function(e,t){return X(gu,e,{baseOptions:{modelAssetPath:t}})},gu.createFromModelBuffer=function(e,t){return X(gu,e,{baseOptions:{modelAssetBuffer:t}})},gu.createFromOptions=function(e,t){return X(gu,e,t)},gu.HAND_CONNECTIONS=fu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$gesture_recognizer$gesture_recognizer.GestureRecognizer.HAND_CONNECTIONS`,gu.HAND_CONNECTIONS);var vu=class extends $l{constructor(e,t){super(new Jl(e,t),`image_in`,`norm_rect`,!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],S(e=this.i=new _s,0,1,t=new U),this.v=new gs,S(this.i,0,3,this.v),this.m=new hs,S(this.i,0,2,this.m),hr(this.m,3,1),w(this.m,2,.5),w(this.v,2,.5),w(this.i,4,.5)}D(){return`HandLandmarker`}get baseOptions(){return x(this.i,U,1)}set baseOptions(e){S(this.i,0,1,e)}A(e){return`numHands`in e&&hr(this.m,3,e.numHands??1),`minHandDetectionConfidence`in e&&w(this.m,2,e.minHandDetectionConfidence??.5),`minTrackingConfidence`in e&&w(this.i,4,e.minTrackingConfidence??.5),`minHandPresenceConfidence`in e&&w(this.v,2,e.minHandPresenceConfidence??.5),this.l(e)}H(e,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Xl(this,e,t),_u(this)}I(e,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Zl(this,e,n,t),_u(this)}u(){var e=new wo;V(e,`image_in`),V(e,`norm_rect`),H(e,`hand_landmarks`),H(e,`world_hand_landmarks`),H(e,`handedness`);var t=new _o;Ri(t,ws,this.i);var n=new yo;yr(n,2,`mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph`),z(n,`IMAGE:image_in`),z(n,`NORM_RECT:norm_rect`),B(n,`LANDMARKS:hand_landmarks`),B(n,`WORLD_LANDMARKS:world_hand_landmarks`),B(n,`HANDEDNESS:handedness`),n.A(t),Co(e,n),this.h.attachProtoVectorListener(`hand_landmarks`,(e,t)=>{for(let t of e)e=Ro(t),this.landmarks.push(ac(e));K(this,t)}),this.h.attachEmptyPacketListener(`hand_landmarks`,e=>{K(this,e)}),this.h.attachProtoVectorListener(`world_hand_landmarks`,(e,t)=>{for(let t of e)e=Io(t),this.worldLandmarks.push(oc(e));K(this,t)}),this.h.attachEmptyPacketListener(`world_hand_landmarks`,e=>{K(this,e)}),this.h.attachProtoVectorListener(`handedness`,(e,t)=>{var n=this.handedness,r=n.push,i=[];for(let t of e){e=Ao(t);let n=[];for(let t of e.h())n.push({score:C(t,2)??0,index:fr(t,1)??0??-1,categoryName:_(v(t,3))??``??``,displayName:_(v(t,4))??``??``});i.push(n)}r.call(n,...i),K(this,t)}),this.h.attachEmptyPacketListener(`handedness`,e=>{K(this,e)}),e=e.h(),this.setGraph(new Uint8Array(e),!0)}};vu.prototype.detectForVideo=vu.prototype.I,vu.prototype.detect=vu.prototype.H,vu.prototype.setOptions=vu.prototype.A,vu.createFromModelPath=function(e,t){return X(vu,e,{baseOptions:{modelAssetPath:t}})},vu.createFromModelBuffer=function(e,t){return X(vu,e,{baseOptions:{modelAssetBuffer:t}})},vu.createFromOptions=function(e,t){return X(vu,e,t)},vu.HAND_CONNECTIONS=fu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$hand_landmarker$hand_landmarker.HandLandmarker.HAND_CONNECTIONS`,vu.HAND_CONNECTIONS);var yu=Gl([0,1],[1,2],[2,3],[3,7],[0,4],[4,5],[5,6],[6,8],[9,10],[11,12],[11,13],[13,15],[15,17],[15,19],[15,21],[17,19],[12,14],[14,16],[16,18],[16,20],[16,22],[18,20],[11,23],[12,24],[23,24],[23,25],[24,26],[25,27],[26,28],[27,29],[28,30],[29,31],[30,32],[27,31],[28,32]);function bu(e){e.i={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function xu(e){try{if(!e.G)return e.i;e.G(e.i)}finally{rl(e)}}function Su(e,t){e=Ro(e),t.push(ac(e))}var Q=class extends $l{constructor(e,t){super(new Jl(e,t),`input_frames_image`,null,!1),this.i={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,S(e=this.m=new Os,0,1,t=new U),this.Z=new gs,S(this.m,0,2,this.Z),this.Ba=new Ts,S(this.m,0,3,this.Ba),this.v=new is,S(this.m,0,4,this.v),this.P=new cs,S(this.m,0,5,this.P),this.C=new Es,S(this.m,0,6,this.C),this.aa=new Ds,S(this.m,0,7,this.aa),w(this.v,2,.5),w(this.v,3,.3),w(this.P,2,.5),w(this.C,2,.5),w(this.C,3,.3),w(this.aa,2,.5),w(this.Z,2,.5)}D(){return`HolisticLandmarker`}get baseOptions(){return x(this.m,U,1)}set baseOptions(e){S(this.m,0,1,e)}A(e){return`minFaceDetectionConfidence`in e&&w(this.v,2,e.minFaceDetectionConfidence??.5),`minFaceSuppressionThreshold`in e&&w(this.v,3,e.minFaceSuppressionThreshold??.3),`minFacePresenceConfidence`in e&&w(this.P,2,e.minFacePresenceConfidence??.5),`outputFaceBlendshapes`in e&&(this.outputFaceBlendshapes=!!e.outputFaceBlendshapes),`minPoseDetectionConfidence`in e&&w(this.C,2,e.minPoseDetectionConfidence??.5),`minPoseSuppressionThreshold`in e&&w(this.C,3,e.minPoseSuppressionThreshold??.3),`minPosePresenceConfidence`in e&&w(this.aa,2,e.minPosePresenceConfidence??.5),`outputPoseSegmentationMasks`in e&&(this.outputPoseSegmentationMasks=!!e.outputPoseSegmentationMasks),`minHandLandmarksConfidence`in e&&w(this.Z,2,e.minHandLandmarksConfidence??.5),this.l(e)}H(e,t,n){var r=typeof t==`function`?{}:t;return this.G=typeof t==`function`?t:n,bu(this),Xl(this,e,r),xu(this)}I(e,t,n,r){var i=typeof n==`function`?{}:n;return this.G=typeof n==`function`?n:r,bu(this),Zl(this,e,i,t),xu(this)}u(){var e=new wo;V(e,`input_frames_image`),H(e,`pose_landmarks`),H(e,`pose_world_landmarks`),H(e,`face_landmarks`),H(e,`left_hand_landmarks`),H(e,`left_hand_world_landmarks`),H(e,`right_hand_landmarks`),H(e,`right_hand_world_landmarks`);var t=new _o,n=new eo;yr(n,1,`type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions`),function(e,t){if(t!=null){if(Array.isArray(t))y(e,2,Cn(t,0,Tn));else{if(!(typeof t==`string`||t instanceof xe||ge(t)))throw Error(`invalid value in Any.value field: `+t+` expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array`);Zn(e,2,Xe(t,!1),ve())}}}(n,this.m.h());var r=new yo;yr(r,2,`mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph`),dr(r,8,eo,n),z(r,`IMAGE:input_frames_image`),B(r,`POSE_LANDMARKS:pose_landmarks`),B(r,`POSE_WORLD_LANDMARKS:pose_world_landmarks`),B(r,`FACE_LANDMARKS:face_landmarks`),B(r,`LEFT_HAND_LANDMARKS:left_hand_landmarks`),B(r,`LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks`),B(r,`RIGHT_HAND_LANDMARKS:right_hand_landmarks`),B(r,`RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks`),r.A(t),Co(e,r),tl(this,e),this.h.attachProtoListener(`pose_landmarks`,(e,t)=>{Su(e,this.i.poseLandmarks),K(this,t)}),this.h.attachEmptyPacketListener(`pose_landmarks`,e=>{K(this,e)}),this.h.attachProtoListener(`pose_world_landmarks`,(e,t)=>{var n=this.i.poseWorldLandmarks;e=Io(e),n.push(oc(e)),K(this,t)}),this.h.attachEmptyPacketListener(`pose_world_landmarks`,e=>{K(this,e)}),this.outputPoseSegmentationMasks&&(B(r,`POSE_SEGMENTATION_MASK:pose_segmentation_mask`),nl(this,`pose_segmentation_mask`),this.h.ha(`pose_segmentation_mask`,(e,t)=>{this.i.poseSegmentationMasks=[Ql(this,e,!0,!this.G)],K(this,t)}),this.h.attachEmptyPacketListener(`pose_segmentation_mask`,e=>{this.i.poseSegmentationMasks=[],K(this,e)})),this.h.attachProtoListener(`face_landmarks`,(e,t)=>{Su(e,this.i.faceLandmarks),K(this,t)}),this.h.attachEmptyPacketListener(`face_landmarks`,e=>{K(this,e)}),this.outputFaceBlendshapes&&(H(e,`extra_blendshapes`),B(r,`FACE_BLENDSHAPES:extra_blendshapes`),this.h.attachProtoListener(`extra_blendshapes`,(e,t)=>{var n=this.i.faceBlendshapes;this.outputFaceBlendshapes&&(e=Ao(e),n.push(nc(e.h()??[]))),K(this,t)}),this.h.attachEmptyPacketListener(`extra_blendshapes`,e=>{K(this,e)})),this.h.attachProtoListener(`left_hand_landmarks`,(e,t)=>{Su(e,this.i.leftHandLandmarks),K(this,t)}),this.h.attachEmptyPacketListener(`left_hand_landmarks`,e=>{K(this,e)}),this.h.attachProtoListener(`left_hand_world_landmarks`,(e,t)=>{var n=this.i.leftHandWorldLandmarks;e=Io(e),n.push(oc(e)),K(this,t)}),this.h.attachEmptyPacketListener(`left_hand_world_landmarks`,e=>{K(this,e)}),this.h.attachProtoListener(`right_hand_landmarks`,(e,t)=>{Su(e,this.i.rightHandLandmarks),K(this,t)}),this.h.attachEmptyPacketListener(`right_hand_landmarks`,e=>{K(this,e)}),this.h.attachProtoListener(`right_hand_world_landmarks`,(e,t)=>{var n=this.i.rightHandWorldLandmarks;e=Io(e),n.push(oc(e)),K(this,t)}),this.h.attachEmptyPacketListener(`right_hand_world_landmarks`,e=>{K(this,e)}),e=e.h(),this.setGraph(new Uint8Array(e),!0)}};Q.prototype.detectForVideo=Q.prototype.I,Q.prototype.detect=Q.prototype.H,Q.prototype.setOptions=Q.prototype.A,Q.createFromModelPath=function(e,t){return X(Q,e,{baseOptions:{modelAssetPath:t}})},Q.createFromModelBuffer=function(e,t){return X(Q,e,{baseOptions:{modelAssetBuffer:t}})},Q.createFromOptions=function(e,t){return X(Q,e,t)},Q.HAND_CONNECTIONS=fu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.HAND_CONNECTIONS`,Q.HAND_CONNECTIONS),Q.POSE_CONNECTIONS=yu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.POSE_CONNECTIONS`,Q.POSE_CONNECTIONS),Q.FACE_LANDMARKS_LIPS=tu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.FACE_LANDMARKS_LIPS`,Q.FACE_LANDMARKS_LIPS),Q.FACE_LANDMARKS_LEFT_EYE=nu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.FACE_LANDMARKS_LEFT_EYE`,Q.FACE_LANDMARKS_LEFT_EYE),Q.FACE_LANDMARKS_LEFT_EYEBROW=ru,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.FACE_LANDMARKS_LEFT_EYEBROW`,Q.FACE_LANDMARKS_LEFT_EYEBROW),Q.FACE_LANDMARKS_LEFT_IRIS=iu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.FACE_LANDMARKS_LEFT_IRIS`,Q.FACE_LANDMARKS_LEFT_IRIS),Q.FACE_LANDMARKS_RIGHT_EYE=au,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.FACE_LANDMARKS_RIGHT_EYE`,Q.FACE_LANDMARKS_RIGHT_EYE),Q.FACE_LANDMARKS_RIGHT_EYEBROW=ou,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.FACE_LANDMARKS_RIGHT_EYEBROW`,Q.FACE_LANDMARKS_RIGHT_EYEBROW),Q.FACE_LANDMARKS_RIGHT_IRIS=su,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.FACE_LANDMARKS_RIGHT_IRIS`,Q.FACE_LANDMARKS_RIGHT_IRIS),Q.FACE_LANDMARKS_FACE_OVAL=cu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.FACE_LANDMARKS_FACE_OVAL`,Q.FACE_LANDMARKS_FACE_OVAL),Q.FACE_LANDMARKS_CONTOURS=lu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.FACE_LANDMARKS_CONTOURS`,Q.FACE_LANDMARKS_CONTOURS),Q.FACE_LANDMARKS_TESSELATION=uu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$holistic_landmarker$holistic_landmarker.HolisticLandmarker.FACE_LANDMARKS_TESSELATION`,Q.FACE_LANDMARKS_TESSELATION);var Cu=class extends $l{constructor(e,t){super(new Jl(e,t),`input_image`,`norm_rect`,!0),this.m={classifications:[]},S(e=this.i=new js,0,1,t=new U)}D(){return`ImageClassifier`}get baseOptions(){return x(this.i,U,1)}set baseOptions(e){S(this.i,0,1,e)}A(e){return S(this.i,0,2,ec(e,x(this.i,Yo,2))),this.l(e)}Ha(e,t){return this.m={classifications:[]},Xl(this,e,t),this.m}Ia(e,t,n){return this.m={classifications:[]},Zl(this,e,n,t),this.m}u(){var e=new wo;V(e,`input_image`),V(e,`norm_rect`),H(e,`classifications`);var t=new _o;Ri(t,Ms,this.i);var n=new yo;yr(n,2,`mediapipe.tasks.vision.image_classifier.ImageClassifierGraph`),z(n,`IMAGE:input_image`),z(n,`NORM_RECT:norm_rect`),B(n,`CLASSIFICATIONS:classifications`),n.A(t),Co(e,n),this.h.attachProtoListener(`classifications`,(e,t)=>{this.m=rc(Uo(e)),K(this,t)}),this.h.attachEmptyPacketListener(`classifications`,e=>{K(this,e)}),e=e.h(),this.setGraph(new Uint8Array(e),!0)}};Cu.prototype.classifyForVideo=Cu.prototype.Ia,Cu.prototype.classify=Cu.prototype.Ha,Cu.prototype.setOptions=Cu.prototype.A,Cu.createFromModelPath=function(e,t){return X(Cu,e,{baseOptions:{modelAssetPath:t}})},Cu.createFromModelBuffer=function(e,t){return X(Cu,e,{baseOptions:{modelAssetBuffer:t}})},Cu.createFromOptions=function(e,t){return X(Cu,e,t)};var wu=class extends $l{constructor(e,t){super(new Jl(e,t),`image_in`,`norm_rect`,!0),this.i=new Ns,this.embeddings={embeddings:[]},S(e=this.i,0,1,t=new U)}D(){return`ImageEmbedder`}get baseOptions(){return x(this.i,U,1)}set baseOptions(e){S(this.i,0,1,e)}A(e){var t=this.i,n=x(this.i,Zo,2);if(n=n?n.clone():new Zo,e.l2Normalize!==void 0){var r=e.l2Normalize;y(n,1,r==null?r:Ft(r))}else`l2Normalize`in e&&y(n,1);return e.quantize===void 0?`quantize`in e&&y(n,2):y(n,2,(r=e.quantize)==null?r:Ft(r)),S(t,0,2,n),this.l(e)}Oa(e,t){return Xl(this,e,t),this.embeddings}Pa(e,t,n){return Zl(this,e,n,t),this.embeddings}u(){var e=new wo;V(e,`image_in`),V(e,`norm_rect`),H(e,`embeddings_out`);var t=new _o;Ri(t,Ps,this.i);var n=new yo;yr(n,2,`mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph`),z(n,`IMAGE:image_in`),z(n,`NORM_RECT:norm_rect`),B(n,`EMBEDDINGS:embeddings_out`),n.A(t),Co(e,n),this.h.attachProtoListener(`embeddings_out`,(e,t)=>{e=Jo(e),this.embeddings=function(e){return{embeddings:or(e,Ko,1).map(e=>{var t={headIndex:fr(e,3)??0??-1,headName:_(v(e,4))??``??``};if(Hn(e,Wo,1,qo))e=Wn(e=pr(e,Wo,1,qo),1,Pt,Un()),t.floatEmbedding=e.slice();else{let n=/* @__PURE__ */ new Uint8Array;t.quantizedEmbedding=pr(e,Go,2,qo)?.h()?.i()??n}return t}),timestampMs:tc(v(e,2,void 0,Xt)??zn)}}(e),K(this,t)}),this.h.attachEmptyPacketListener(`embeddings_out`,e=>{K(this,e)}),e=e.h(),this.setGraph(new Uint8Array(e),!0)}};wu.cosineSimilarity=function(e,t){if(e.floatEmbedding&&t.floatEmbedding)e=cc(e.floatEmbedding,t.floatEmbedding);else{if(!e.quantizedEmbedding||!t.quantizedEmbedding)throw Error(`Cannot compute cosine similarity between quantized and float embeddings.`);e=cc(sc(e.quantizedEmbedding),sc(t.quantizedEmbedding))}return e},wu.prototype.embedForVideo=wu.prototype.Pa,wu.prototype.embed=wu.prototype.Oa,wu.prototype.setOptions=wu.prototype.A,wu.createFromModelPath=function(e,t){return X(wu,e,{baseOptions:{modelAssetPath:t}})},wu.createFromModelBuffer=function(e,t){return X(wu,e,{baseOptions:{modelAssetBuffer:t}})},wu.createFromOptions=function(e,t){return X(wu,e,t)};var Tu=class{constructor(e,t,n){this.confidenceMasks=e,this.categoryMask=t,this.qualityScores=n}close(){this.confidenceMasks?.forEach(e=>{e.close()}),this.categoryMask?.close()}};function Eu(e){var t=function(e){return or(e,yo,1)}(e.ka()).filter(e=>(_(v(e,1))??``).includes(`mediapipe.tasks.TensorsToSegmentationCalculator`));if(e.v=[],t.length>1)throw Error(`The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator.`);t.length===1&&(x(t[0],_o,7)?.u()?.h()??/* @__PURE__ */ new Map).forEach((t,n)=>{e.v[Number(n)]=_(v(t,1))??``})}function Du(e){e.categoryMask=void 0,e.confidenceMasks=void 0,e.qualityScores=void 0}function Ou(e){try{let t=new Tu(e.confidenceMasks,e.categoryMask,e.qualityScores);if(!e.m)return t;e.m(t)}finally{rl(e)}}Tu.prototype.close=Tu.prototype.close;var $=class extends $l{constructor(e,t){super(new Jl(e,t),`image_in`,`norm_rect`,!1),this.v=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.i=new zs,this.C=new Fs,S(this.i,0,3,this.C),S(e=this.i,0,1,t=new U)}D(){return`ImageSegmenter`}get baseOptions(){return x(this.i,U,1)}set baseOptions(e){S(this.i,0,1,e)}A(e){return e.displayNamesLocale===void 0?`displayNamesLocale`in e&&y(this.i,2):y(this.i,2,en(e.displayNamesLocale)),`outputCategoryMask`in e&&(this.outputCategoryMask=e.outputCategoryMask??!1),`outputConfidenceMasks`in e&&(this.outputConfidenceMasks=e.outputConfidenceMasks??!0),super.l(e)}M(){Eu(this)}segment(e,t,n){var r=typeof t==`function`?{}:t;return this.m=typeof t==`function`?t:n,Du(this),Xl(this,e,r),Ou(this)}fb(e,t,n,r){var i=typeof n==`function`?{}:n;return this.m=typeof n==`function`?n:r,Du(this),Zl(this,e,i,t),Ou(this)}Sa(){return this.v}u(){var e=new wo;V(e,`image_in`),V(e,`norm_rect`);var t=new _o;Ri(t,Bs,this.i);var n=new yo;yr(n,2,`mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph`),z(n,`IMAGE:image_in`),z(n,`NORM_RECT:norm_rect`),n.A(t),Co(e,n),tl(this,e),this.outputConfidenceMasks&&(H(e,`confidence_masks`),B(n,`CONFIDENCE_MASKS:confidence_masks`),nl(this,`confidence_masks`),this.h.ia(`confidence_masks`,(e,t)=>{this.confidenceMasks=e.map(e=>Ql(this,e,!0,!this.m)),K(this,t)}),this.h.attachEmptyPacketListener(`confidence_masks`,e=>{this.confidenceMasks=[],K(this,e)})),this.outputCategoryMask&&(H(e,`category_mask`),B(n,`CATEGORY_MASK:category_mask`),nl(this,`category_mask`),this.h.ha(`category_mask`,(e,t)=>{this.categoryMask=Ql(this,e,!1,!this.m),K(this,t)}),this.h.attachEmptyPacketListener(`category_mask`,e=>{this.categoryMask=void 0,K(this,e)})),H(e,`quality_scores`),B(n,`QUALITY_SCORES:quality_scores`),this.h.attachFloatVectorListener(`quality_scores`,(e,t)=>{this.qualityScores=e,K(this,t)}),this.h.attachEmptyPacketListener(`quality_scores`,e=>{this.categoryMask=void 0,K(this,e)}),e=e.h(),this.setGraph(new Uint8Array(e),!0)}};$.prototype.getLabels=$.prototype.Sa,$.prototype.segmentForVideo=$.prototype.fb,$.prototype.segment=$.prototype.segment,$.prototype.setOptions=$.prototype.A,$.createFromModelPath=function(e,t){return X($,e,{baseOptions:{modelAssetPath:t}})},$.createFromModelBuffer=function(e,t){return X($,e,{baseOptions:{modelAssetBuffer:t}})},$.createFromOptions=function(e,t){return X($,e,t)};var ku={0:0,1:1,2:2,3:3};function Au(){return Rc()?void 0:document.createElement(`canvas`)}var ju=class extends il{constructor(e,t){super(new Yc(e,t)),this.v=new pl,this.delegate=`CPU`,this.i=0,this.baseOptions=new U,this.C=this.m=0}D(){return`InteractiveSegmenter`}get j(){return this.h.j}A(e){return this.delegate=e.baseOptions?.delegate??`CPU`,super.l(e)}gb(e){if(this.i===0)throw Error(`Segmenter is not initialized.`);var t;if(this.m!==0&&(this.j._free(this.m),this.m=0),!(t=typeof ImageData<`u`&&e instanceof ImageData)){if(typeof e!=`object`||!e)t=!1;else{t=e.data;var n=e.width,r=e.height;t=Number.isInteger(n)&&n>0&&Number.isInteger(r)&&r>0&&(t instanceof Uint8ClampedArray||t instanceof Uint8Array)}}if(t)t=e.width,n=e.height,e=e.data;else{if([t,n]=Bc(e),typeof OffscreenCanvas<`u`)r=new OffscreenCanvas(t,n);else{if(typeof document>`u`)throw Error(`Canvas is not supported in this environment.`);r=document.createElement(`canvas`)}if(r.width=t,r.height=n,!(r=r.getContext(`2d`)))throw Error(`Canvas 2D context is not supported in this environment.`);r.drawImage(e,0,0),e=r.getImageData(0,0,t,n).data}if(!e)throw Error(`Unsupported image source or failed to extract image pixels.`);r=function({Xa:e,width:t,height:n}){if(t<=0||n<=0)throw Error(`Invalid image dimensions: ${t}x${n}. Dimensions must be positive.`);if(e%(t*n)!==0)throw Error(`Invalid image dimensions or pixel data length. Pixel data length ${e} is not a multiple of the number of pixels (${t*n}).`);if((e/=t*n)!==4&&e!==3&&e!==1)throw Error(`Invalid image dimensions or pixel data length. Calculated channels: ${e}. Expected 1, 3, or 4.`);return e}({Xa:e.length,width:t,height:n});var i=this.j._malloc(e.length);if(this.j.HEAPU8.set(e,i),this.m=i,!this.j._interactive_segmenter_set_image(this.i,i,t,n,r))throw Error(`Failed to set image on native engine.`)}segment(e){if(this.i===0)throw Error(`Segmenter is not initialized.`);var t=function(e){e=e.map(({isCompleted:e,brushMode:t,point:n})=>{t=ku[t]??0,n=n.map(({x:e,y:t})=>{var n=new Vs;return vr(n,1,e),vr(n,2,t),n});var r=new Hs;return mr(r,e),Zn(r,1,Rt(t),0),lr(r,2,n),r});var t=new Us;return lr(t,1,e),Ws(t)}(e);e=this.j._malloc(t.length),this.j.HEAPU8.set(t,e);var n=this.j._malloc(12),r=n+4,i=n+8,a=0,o=this.C++;try{if(this.o){if(this.delegate===`GPU`){var s=this.o;++s.h.U,s.i.set(o,performance.now())}else{var c=this.o;++c.h.R,c.i.set(o,performance.now())}}if((a=this.j._interactive_segmenter_segment(this.i,e,t.length,n,r,i))===0)throw Error(`Segmentation failed.`);this.o?.Aa(o);let u=this.j.HEAPU32[n/4],d=this.j.HEAPU32[r/4],ee=new Float32Array(this.j.HEAPU8.buffer,a,this.j.HEAPU32[i/4]/4);var l=new Float32Array(ee);if(s=u*d,(l instanceof Uint8Array||l instanceof Float32Array)&&l.length!==s)throw Error(`Unsupported channel count: `+l.length/s);return new J([l],!0,!1,this.h.j.canvas??void 0,this.v,u,d)}finally{e!==0&&this.j._free(e),n!==0&&this.j._free(n),a!==0&&this.j._free(a)}}u(){this.i!==0&&(this.o?.ya(),this.j._interactive_segmenter_close(this.i),this.i=0),this.m!==0&&(this.j._free(this.m),this.m=0);var e=new $o;if(this.delegate===`GPU`){var t=new ao;cr(e,2,es,t)}else hr(t=new ho,1,4),cr(e,1,es,t);if(S(this.baseOptions,0,3,e),e=rs(this.baseOptions),t=this.j._malloc(e.length),this.j.HEAPU8.set(e,t),this.i=this.j._interactive_segmenter_create(t,e.length),this.j._free(t),this.i===0)throw Error(`Failed to create native InteractiveSegmenter engine.`);this.o?.za()}close(){this.i!==0&&(this.j._interactive_segmenter_close(this.i),this.i=0),this.m!==0&&(this.j._free(this.m),this.m=0),this.v.close(),super.close()}};ju.prototype.close=ju.prototype.close,ju.prototype.segment=ju.prototype.segment,ju.prototype.setImage=ju.prototype.gb,ju.prototype.setOptions=ju.prototype.A,ju.createFromModelPath=function(e,t){return Zc(ju,Au(),e,{baseOptions:{modelAssetPath:t}})},ju.createFromModelBuffer=function(e,t){return Zc(ju,Au(),e,{baseOptions:{modelAssetBuffer:t}})},ju.createFromOptions=function(e,t){return Zc(ju,t.canvas??Au(),e,t)};var Mu=class{constructor(e,t,n){this.confidenceMasks=e,this.categoryMask=t,this.qualityScores=n}close(){this.confidenceMasks?.forEach(e=>{e.close()}),this.categoryMask?.close()}};Mu.prototype.close=Mu.prototype.close;var Nu=class extends $l{constructor(e,t){super(new Jl(e,t),`image_in`,`norm_rect_in`,!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.i=new zs,this.v=new Fs,S(this.i,0,3,this.v),S(e=this.i,0,1,t=new U)}D(){return`InteractiveSegmenterLegacy`}get baseOptions(){return x(this.i,U,1)}set baseOptions(e){S(this.i,0,1,e)}A(e){return`outputCategoryMask`in e&&(this.outputCategoryMask=e.outputCategoryMask??!1),`outputConfidenceMasks`in e&&(this.outputConfidenceMasks=e.outputConfidenceMasks??!0),super.l(e)}segment(e,t,n,r){var i=typeof n==`function`?{}:n;if(this.m=typeof n==`function`?n:r,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,n=this.J+1,r=new Js,t.keypoint&&t.scribble)throw Error(`Cannot provide both keypoint and scribble.`);if(t.keypoint){var a=new Gs;mr(a,!0),vr(a,1,t.keypoint.x),vr(a,2,t.keypoint.y),cr(r,1,Ys,a)}else{if(!t.scribble)throw Error(`Must provide either a keypoint or a scribble.`);{let e=new qs;for(a of t.scribble)mr(t=new Gs,!0),vr(t,1,a.x),vr(t,2,a.y),dr(e,1,Gs,t);cr(r,2,Ys,e)}}this.h.addProtoToStream(r.h(),`mediapipe.tasks.vision.interactive_segmenter_legacy.proto.RegionOfInterest`,`roi_in`,n),Xl(this,e,i);t:{try{let e=new Mu(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.m){var o=e;break t}this.m(e)}finally{rl(this)}o=void 0}return o}u(){var e=new wo;V(e,`image_in`),V(e,`roi_in`),V(e,`norm_rect_in`);var t=new _o;Ri(t,Bs,this.i);var n=new yo;yr(n,2,`mediapipe.tasks.vision.interactive_segmenter_legacy.InteractiveSegmenterLegacyGraph`),z(n,`IMAGE:image_in`),z(n,`ROI:roi_in`),z(n,`NORM_RECT:norm_rect_in`),n.A(t),Co(e,n),tl(this,e),this.outputConfidenceMasks&&(H(e,`confidence_masks`),B(n,`CONFIDENCE_MASKS:confidence_masks`),nl(this,`confidence_masks`),this.h.ia(`confidence_masks`,(e,t)=>{this.confidenceMasks=e.map(e=>Ql(this,e,!0,!this.m)),K(this,t)}),this.h.attachEmptyPacketListener(`confidence_masks`,e=>{this.confidenceMasks=[],K(this,e)})),this.outputCategoryMask&&(H(e,`category_mask`),B(n,`CATEGORY_MASK:category_mask`),nl(this,`category_mask`),this.h.ha(`category_mask`,(e,t)=>{this.categoryMask=Ql(this,e,!1,!this.m),K(this,t)}),this.h.attachEmptyPacketListener(`category_mask`,e=>{this.categoryMask=void 0,K(this,e)})),H(e,`quality_scores`),B(n,`QUALITY_SCORES:quality_scores`),this.h.attachFloatVectorListener(`quality_scores`,(e,t)=>{this.qualityScores=e,K(this,t)}),this.h.attachEmptyPacketListener(`quality_scores`,e=>{this.categoryMask=void 0,K(this,e)}),e=e.h(),this.setGraph(new Uint8Array(e),!0)}};Nu.prototype.segment=Nu.prototype.segment,Nu.prototype.setOptions=Nu.prototype.A,Nu.createFromModelPath=function(e,t){return X(Nu,e,{baseOptions:{modelAssetPath:t}})},Nu.createFromModelBuffer=function(e,t){return X(Nu,e,{baseOptions:{modelAssetBuffer:t}})},Nu.createFromOptions=function(e,t){return X(Nu,e,t)};var Pu=class extends $l{constructor(e,t){super(new Jl(e,t),`input_frame_gpu`,`norm_rect`,!1),this.m={detections:[]},S(e=this.i=new Xs,0,1,t=new U)}D(){return`ObjectDetector`}get baseOptions(){return x(this.i,U,1)}set baseOptions(e){S(this.i,0,1,e)}A(e){return e.displayNamesLocale===void 0?`displayNamesLocale`in e&&y(this.i,2):y(this.i,2,en(e.displayNamesLocale)),e.maxResults===void 0?`maxResults`in e&&y(this.i,3):hr(this.i,3,e.maxResults),e.scoreThreshold===void 0?`scoreThreshold`in e&&y(this.i,4):w(this.i,4,e.scoreThreshold),e.categoryAllowlist===void 0?`categoryAllowlist`in e&&y(this.i,5):br(this.i,5,e.categoryAllowlist),e.categoryDenylist===void 0?`categoryDenylist`in e&&y(this.i,6):br(this.i,6,e.categoryDenylist),this.l(e)}H(e,t){return this.m={detections:[]},Xl(this,e,t),this.m}I(e,t,n){return this.m={detections:[]},Zl(this,e,n,t),this.m}u(){var e=new wo;V(e,`input_frame_gpu`),V(e,`norm_rect`),H(e,`detections`);var t=new _o;Ri(t,Zs,this.i);var n=new yo;yr(n,2,`mediapipe.tasks.vision.ObjectDetectorGraph`),z(n,`IMAGE:input_frame_gpu`),z(n,`NORM_RECT:norm_rect`),B(n,`DETECTIONS:detections`),n.A(t),Co(e,n),this.h.attachProtoVectorListener(`detections`,(e,t)=>{for(let t of e)e=Po(t),this.m.detections.push(ic(e));K(this,t)}),this.h.attachEmptyPacketListener(`detections`,e=>{K(this,e)}),e=e.h(),this.setGraph(new Uint8Array(e),!0)}};Pu.prototype.detectForVideo=Pu.prototype.I,Pu.prototype.detect=Pu.prototype.H,Pu.prototype.setOptions=Pu.prototype.A,Pu.createFromModelPath=async function(e,t){return X(Pu,e,{baseOptions:{modelAssetPath:t}})},Pu.createFromModelBuffer=function(e,t){return X(Pu,e,{baseOptions:{modelAssetBuffer:t}})},Pu.createFromOptions=function(e,t){return X(Pu,e,t)};var Fu=class{constructor(e,t,n){this.landmarks=e,this.worldLandmarks=t,this.segmentationMasks=n}close(){this.segmentationMasks?.forEach(e=>{e.close()})}};function Iu(e){e.landmarks=[],e.worldLandmarks=[],e.segmentationMasks=void 0}function Lu(e){try{let t=new Fu(e.landmarks,e.worldLandmarks,e.segmentationMasks);if(!e.v)return t;e.v(t)}finally{rl(e)}}Fu.prototype.close=Fu.prototype.close;var Ru=class extends $l{constructor(e,t){super(new Jl(e,t),`image_in`,`norm_rect`,!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,S(e=this.i=new Qs,0,1,t=new U),this.C=new Ds,S(this.i,0,3,this.C),this.m=new Es,S(this.i,0,2,this.m),hr(this.m,4,1),w(this.m,2,.5),w(this.C,2,.5),w(this.i,4,.5)}D(){return`PoseLandmarker`}get baseOptions(){return x(this.i,U,1)}set baseOptions(e){S(this.i,0,1,e)}A(e){return`numPoses`in e&&hr(this.m,4,e.numPoses??1),`minPoseDetectionConfidence`in e&&w(this.m,2,e.minPoseDetectionConfidence??.5),`minTrackingConfidence`in e&&w(this.i,4,e.minTrackingConfidence??.5),`minPosePresenceConfidence`in e&&w(this.C,2,e.minPosePresenceConfidence??.5),`outputSegmentationMasks`in e&&(this.outputSegmentationMasks=e.outputSegmentationMasks??!1),this.l(e)}H(e,t,n){var r=typeof t==`function`?{}:t;return this.v=typeof t==`function`?t:n,Iu(this),Xl(this,e,r),Lu(this)}I(e,t,n,r){var i=typeof n==`function`?{}:n;return this.v=typeof n==`function`?n:r,Iu(this),Zl(this,e,i,t),Lu(this)}u(){var e=new wo;V(e,`image_in`),V(e,`norm_rect`),H(e,`normalized_landmarks`),H(e,`world_landmarks`),H(e,`segmentation_masks`);var t=new _o;Ri(t,$s,this.i);var n=new yo;yr(n,2,`mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph`),z(n,`IMAGE:image_in`),z(n,`NORM_RECT:norm_rect`),B(n,`NORM_LANDMARKS:normalized_landmarks`),B(n,`WORLD_LANDMARKS:world_landmarks`),n.A(t),Co(e,n),tl(this,e),this.h.attachProtoVectorListener(`normalized_landmarks`,(e,t)=>{this.landmarks=[];for(let t of e)e=Ro(t),this.landmarks.push(ac(e));K(this,t)}),this.h.attachEmptyPacketListener(`normalized_landmarks`,e=>{this.landmarks=[],K(this,e)}),this.h.attachProtoVectorListener(`world_landmarks`,(e,t)=>{this.worldLandmarks=[];for(let t of e)e=Io(t),this.worldLandmarks.push(oc(e));K(this,t)}),this.h.attachEmptyPacketListener(`world_landmarks`,e=>{this.worldLandmarks=[],K(this,e)}),this.outputSegmentationMasks&&(B(n,`SEGMENTATION_MASK:segmentation_masks`),nl(this,`segmentation_masks`),this.h.ia(`segmentation_masks`,(e,t)=>{this.segmentationMasks=e.map(e=>Ql(this,e,!0,!this.v)),K(this,t)}),this.h.attachEmptyPacketListener(`segmentation_masks`,e=>{this.segmentationMasks=[],K(this,e)})),e=e.h(),this.setGraph(new Uint8Array(e),!0)}};Ru.prototype.detectForVideo=Ru.prototype.I,Ru.prototype.detect=Ru.prototype.H,Ru.prototype.setOptions=Ru.prototype.A,Ru.createFromModelPath=function(e,t){return X(Ru,e,{baseOptions:{modelAssetPath:t}})},Ru.createFromModelBuffer=function(e,t){return X(Ru,e,{baseOptions:{modelAssetBuffer:t}})},Ru.createFromOptions=function(e,t){return X(Ru,e,t)},Ru.POSE_CONNECTIONS=yu,n(`module$exports$google3$third_party$mediapipe$tasks$web$vision$pose_landmarker$pose_landmarker.PoseLandmarker.POSE_CONNECTIONS`,Ru.POSE_CONNECTIONS);export{$ as ImageSegmenter}; \ No newline at end of file diff --git a/v4d-next/assets/vision_wasm_module_internal-3CmJfNd5.wasm b/v4d-next/assets/vision_wasm_module_internal-3CmJfNd5.wasm new file mode 100644 index 0000000..31e3de5 Binary files /dev/null and b/v4d-next/assets/vision_wasm_module_internal-3CmJfNd5.wasm differ diff --git a/v4d-next/assets/vision_wasm_module_internal-DpeA7n9s.js b/v4d-next/assets/vision_wasm_module_internal-DpeA7n9s.js new file mode 100644 index 0000000..68aa335 --- /dev/null +++ b/v4d-next/assets/vision_wasm_module_internal-DpeA7n9s.js @@ -0,0 +1,9167 @@ +// This code implements the `-sMODULARIZE` settings by taking the generated +// JS program code (INNER_JS_CODE) and wrapping it in a factory function. + +// When targeting node and ES6 we use `await import ..` in the generated code +// so the outer function needs to be marked as async. +async function ModuleFactory(moduleArg = {}) { + var Module = moduleArg; +// include: shell.js +// include: minimum_runtime_check.js +// end include: minimum_runtime_check.js +// The Module object: Our interface to the outside world. We import +// and export values on it. There are various ways Module can be used: +// 1. Not defined. We create it here +// 2. A function parameter, function(moduleArg) => Promise +// 3. pre-run appended it, var Module = {}; ..generated code.. +// 4. External script tag defines var Module. +// We need to check if Module already exists (e.g. case 3 above). +// Substitution will be replaced with actual code on later stage of the build, +// this way Closure Compiler will not mangle it (e.g. case 4. above). +// Note that if you want to run closure, and also to use Module +// after the generated code, you will need to define var Module = {}; +// before the code. Then that object will be used in the code, and you +// can continue to use Module afterwards as well. +// Determine the runtime environment we are in. You can customize this by +// setting the ENVIRONMENT setting at compile time (see settings.js). +// Attempt to auto-detect the environment +var ENVIRONMENT_IS_WEB = !!globalThis.window; + +var ENVIRONMENT_IS_WORKER = !!globalThis.WorkerGlobalScope; + +// N.b. Electron.js environment is simultaneously a NODE-environment, but +// also a web environment. +var ENVIRONMENT_IS_NODE = globalThis.process?.versions?.node && globalThis.process?.type != "renderer"; + +if (ENVIRONMENT_IS_NODE) { + // When building an ES module `require` is not normally available. + // We need to use `createRequire()` to construct the require()` function. + const {createRequire} = await import("node:module"); + /** @suppress{duplicate} */ var require = createRequire(import.meta.url); +} + +// --pre-jses are emitted after the Module integration code, so that they can +// refer to Module (if they choose; they can also define Module) +var programArgs = []; + +var thisProgram = "./this.program"; + +var quit_ = (status, toThrow) => { + throw toThrow; +}; + +var _scriptName = import.meta.url; + +// `/` should be present at the end if `scriptDirectory` is not empty +var scriptDirectory = ""; + +function locateFile(path) { + if (Module["locateFile"]) { + return Module["locateFile"](path, scriptDirectory); + } + return scriptDirectory + path; +} + +// Hooks that are implemented differently in different runtime environments. +var readAsync, readBinary; + +if (ENVIRONMENT_IS_NODE) { + // These modules will usually be used on Node.js. Load them eagerly to avoid + // the complexity of lazy-loading. + var fs = require("node:fs"); + if (_scriptName.startsWith("file:")) { + scriptDirectory = require("node:path").dirname(require("node:url").fileURLToPath(_scriptName)) + "/"; + } + // include: node_shell_read.js + readBinary = filename => { + // We need to re-wrap `file://` strings to URLs. + filename = isFileURI(filename) ? new URL(filename) : filename; + var ret = fs.readFileSync(filename); + return ret; + }; + readAsync = async (filename, binary = true) => { + // See the comment in the `readBinary` function. + filename = isFileURI(filename) ? new URL(filename) : filename; + var ret = fs.readFileSync(filename, binary ? undefined : "utf8"); + return ret; + }; + // end include: node_shell_read.js + if (process.argv.length > 1) { + thisProgram = process.argv[1].replace(/\\/g, "/"); + } + programArgs = process.argv.slice(2); + quit_ = (status, toThrow) => { + process.exitCode = status; + throw toThrow; + }; +} else // Note that this includes Node.js workers when relevant (pthreads is enabled). +// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and +// ENVIRONMENT_IS_NODE. +if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { + try { + scriptDirectory = new URL(".", _scriptName).href; + } catch {} + { + // include: web_or_worker_shell_read.js + if (ENVIRONMENT_IS_WORKER) { + readBinary = url => { + var xhr = new XMLHttpRequest; + xhr.open("GET", url, false); + xhr.responseType = "arraybuffer"; + xhr.send(null); + return new Uint8Array(/** @type{!ArrayBuffer} */ (xhr.response)); + }; + } + readAsync = async url => { + // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url. + // See https://github.com/github/fetch/pull/92#issuecomment-140665932 + // Cordova or Electron apps are typically loaded from a file:// url. + // So use XHR on webview if URL is a file URL. + if (isFileURI(url)) { + return new Promise((resolve, reject) => { + var xhr = new XMLHttpRequest; + xhr.open("GET", url, true); + xhr.responseType = "arraybuffer"; + xhr.onload = () => { + if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { + // file URLs can return 0 + resolve(xhr.response); + return; + } + reject(xhr.status); + }; + xhr.onerror = reject; + xhr.send(null); + }); + } + var response = await fetch(url, { + credentials: "same-origin" + }); + if (response.ok) { + return response.arrayBuffer(); + } + throw new Error(response.status + " : " + response.url); + }; + } +} else {} + +var out = console.log.bind(console); + +var err = console.error.bind(console); + +// end include: shell.js +// include: preamble.js +// === Preamble library stuff === +// Documentation for the public APIs defined in this file must be updated in: +// site/source/docs/api_reference/preamble.js.rst +// A prebuilt local version of the documentation is available at: +// site/build/text/docs/api_reference/preamble.js.txt +// You can also build docs locally as HTML or other formats in site/ +// An online HTML version (which may be of a different version of Emscripten) +// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html +var wasmBinary; + +// Wasm globals +//======================================== +// Runtime essentials +//======================================== +// whether we are quitting the application. no code should run after this. +// set in exit() and abort() +var ABORT = false; + +// set by exit() and abort(). Passed to 'onExit' handler. +// NOTE: This is also used as the process return code in shell environments +// but only when noExitRuntime is false. +var EXITSTATUS; + +// In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we +// don't define it at all in release modes. This matches the behaviour of +// MINIMAL_RUNTIME. +// TODO(sbc): Make this the default even without STRICT enabled. +/** @type {function(*, string=)} */ function assert(condition, text) { + if (!condition) { + // This build was created without ASSERTIONS defined. `assert()` should not + // ever be called in this configuration but in case there are callers in + // the wild leave this simple abort() implementation here for now. + abort(text); + } +} + +/** + * Indicates whether filename is delivered via file protocol (as opposed to http/https) + * @noinline + */ var isFileURI = filename => filename.startsWith("file://"); + +// include: runtime_common.js +// include: runtime_exceptions.js +// Base Emscripten EH error class +class EmscriptenEH {} + +class EmscriptenSjLj extends EmscriptenEH {} + +// end include: runtime_exceptions.js +// include: runtime_debug.js +// end include: runtime_debug.js +// Memory management +var runtimeInitialized = false; + +// When ALLOW_MEMORY_GROWTH is enabled, the conversion from Wasm +// memory to ArrayBuffer requires some additional logic. +function getMemoryBuffer() { + return wasmMemory.buffer; +} + +function updateMemoryViews() { + // If we already have a heap that is resizeable/growable buffer we don't + // need to do anything in updateMemoryViews. + if (HEAP8?.buffer?.resizable) return; + var b = getMemoryBuffer(); + HEAP8 = new Int8Array(b); + HEAP16 = new Int16Array(b); + Module["HEAPU8"] = HEAPU8 = new Uint8Array(b); + HEAPU16 = new Uint16Array(b); + HEAP32 = new Int32Array(b); + Module["HEAPU32"] = HEAPU32 = new Uint32Array(b); + Module["HEAPF32"] = HEAPF32 = new Float32Array(b); + Module["HEAPF64"] = HEAPF64 = new Float64Array(b); +} + +// include: memoryprofiler.js +// end include: memoryprofiler.js +// end include: runtime_common.js +function preRun() { + var preRun = Module["preRun"]; + if (preRun) { + if (typeof preRun == "function") preRun = [ preRun ]; + onPreRuns.push(...preRun); + } + // Begin ATPRERUNS hooks + callRuntimeCallbacks(onPreRuns); +} + +function initRuntime() { + runtimeInitialized = true; + // Begin ATINITS hooks + if (!Module["noFSInit"] && !FS.initialized) FS.init(); + TTY.init(); + // End ATINITS hooks + wasmExports["ud"](); + // Begin ATPOSTCTORS hooks + FS.ignorePermissions = false; +} + +function postRun() { + var postRun = Module["postRun"]; + if (postRun) { + if (typeof postRun == "function") postRun = [ postRun ]; + onPostRuns.push(...postRun); + } + // Begin ATPOSTRUNS hooks + callRuntimeCallbacks(onPostRuns); +} + +/** + * @param {string|number=} what + */ function abort(what) { + Module["onAbort"]?.(what); + what = `Aborted(${what})`; + // TODO(sbc): Should we remove printing and leave it up to whoever + // catches the exception? + err(what); + ABORT = true; + what += ". Build with -sASSERTIONS for more info."; + // Use a wasm runtime error, because a JS error might be seen as a foreign + // exception, which means we'd run destructors on it. We need the error to + // simply make the program stop. + // FIXME This approach does not work in Wasm EH because it currently does not assume + // all RuntimeErrors are from traps; it decides whether a RuntimeError is from + // a trap or not based on a hidden field within the object. So at the moment + // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that + // allows this in the wasm spec. + // Suppress closure compiler warning here. Closure compiler's builtin extern + // definition for WebAssembly.RuntimeError claims it takes no arguments even + // though it can. + // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed. + /** @suppress {checkTypes} */ var e = new WebAssembly.RuntimeError(what); + // Throw the error whether or not MODULARIZE is set because abort is used + // in code paths apart from instantiation where an exception is expected + // to be thrown when abort is called. + throw e; +} + +var wasmBinaryFile; + +function findWasmBinary() { + if (Module["locateFile"]) { + return locateFile("vision_wasm_module_raw_internal.wasm"); + } + // Use bundler-friendly `new URL(..., import.meta.url)` pattern; works in browsers too. + return new URL("vision_wasm_module_raw_internal.wasm", import.meta.url).href; +} + +function getBinarySync(file) { + if (readBinary) { + return readBinary(file); + } + // Throwing a plain string here, even though it not normally advisable since + // this gets turning into an `abort` in instantiateArrayBuffer. + throw "both async and sync fetching of the wasm failed"; +} + +async function getWasmBinary(binaryFile) { + // If we don't have the binary yet, load it asynchronously using readAsync. + if (!wasmBinary) { + // Fetch the binary using readAsync + try { + var response = await readAsync(binaryFile); + return new Uint8Array(response); + } catch {} + } + // Otherwise, getBinarySync should be able to get it synchronously + return getBinarySync(binaryFile); +} + +async function instantiateArrayBuffer(binaryFile, imports) { + try { + var binary = await getWasmBinary(binaryFile); + var instance = await WebAssembly.instantiate(binary, imports); + return instance; + } catch (reason) { + err(`failed to asynchronously prepare wasm: ${reason}`); + abort(reason); + } +} + +async function instantiateAsync(binary, binaryFile, imports) { + if (!binary && !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE) { + try { + var response = fetch(binaryFile, { + credentials: "same-origin" + }); + var instantiationResult = await WebAssembly.instantiateStreaming(response, imports); + return instantiationResult; + } catch (reason) { + // We expect the most common failure cause to be a bad MIME type for the binary, + // in which case falling back to ArrayBuffer instantiation should work. + err(`wasm streaming compile failed: ${reason}`); + err("falling back to ArrayBuffer instantiation"); + } + } + return instantiateArrayBuffer(binaryFile, imports); +} + +function getWasmImports() { + // prepare imports + var imports = { + "a": wasmImports + }; + return imports; +} + +// Create the wasm instance. +// Receives the wasm imports, returns the exports. +async function createWasm() { + // Load the wasm module and create an instance of using native support in the JS engine. + // handle a generated wasm instance, receiving its exports and + // performing other necessary setup + function receiveInstance(instance) { + wasmExports = instance.exports; + assignWasmExports(wasmExports); + updateMemoryViews(); + return wasmExports; + } + // Prefer streaming instantiation if available. + function receiveInstantiationResult(result) { + // 'result' is a ResultObject object which has both the module and instance. + // receiveInstance() will swap in the exports (to Module.asm) so they can be called + // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line. + // When the regression is fixed, can restore the above PTHREADS-enabled path. + return receiveInstance(result["instance"]); + } + var info = getWasmImports(); + // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback + // to manually instantiate the Wasm module themselves. This allows pages to + // run the instantiation parallel to any other async startup actions they are + // performing. + // Also pthreads and wasm workers initialize the wasm instance through this + // path. + var instantiateWasm = Module["instantiateWasm"]; + if (instantiateWasm) { + return new Promise(resolve => { + instantiateWasm(info, inst => resolve(receiveInstance(inst))); + }); + } + wasmBinaryFile ??= findWasmBinary(); + var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info); + var exports = receiveInstantiationResult(result); + return exports; +} + +// Globals used by JS i64 conversions (see makeSetValue) +var tempDouble; + +var tempI64; + +// end include: preamble.js +// Begin JS library code +var handleException = e => { + // Certain exception types we do not treat as errors since they are used for + // internal control flow. + // 1. ExitStatus, which is thrown by exit() + // 2. "unwind", which is thrown by emscripten_unwind_to_js_event_loop() and others + // that wish to return to JS event loop. + if (e instanceof ExitStatus || e == "unwind") { + return EXITSTATUS; + } + quit_(1, e); +}; + +class ExitStatus { + name="ExitStatus"; + constructor(status) { + this.message = `Program terminated with exit(${status})`; + this.status = status; + } +} + +var runtimeKeepaliveCounter = 0; + +var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0; + +var _proc_exit = code => { + EXITSTATUS = code; + if (!keepRuntimeAlive()) { + Module["onExit"]?.(code); + ABORT = true; + } + quit_(code, new ExitStatus(code)); +}; + +/** @param {boolean|number=} implicit */ var exitJS = (status, implicit) => { + EXITSTATUS = status; + _proc_exit(status); +}; + +var _exit = exitJS; + +var maybeExit = () => { + if (!keepRuntimeAlive()) { + try { + _exit(EXITSTATUS); + } catch (e) { + handleException(e); + } + } +}; + +var callUserCallback = func => { + if (ABORT) { + return; + } + try { + return func(); + } catch (e) { + handleException(e); + } finally { + maybeExit(); + } +}; + +function getFullscreenElement() { + return document.fullscreenElement ?? document.webkitFullscreenElement; +} + +/** @param {number=} timeout */ var safeSetTimeout = (func, timeout) => setTimeout(() => { + callUserCallback(func); +}, timeout); + +var warnOnce = text => { + warnOnce.shown ||= {}; + if (!warnOnce.shown[text]) { + warnOnce.shown[text] = 1; + if (ENVIRONMENT_IS_NODE) text = "warning: " + text; + err(text); + } +}; + +var preloadPlugins = []; + +/** @type {!Int32Array} */ var HEAP32; + +/** @type {!Uint32Array} */ var HEAPU32; + +var Browser = { + useWebGL: false, + isFullscreen: false, + pointerLock: false, + moduleContextCreatedCallbacks: [], + preloadedImages: {}, + preloadedAudios: {}, + getCanvas: () => Module["canvas"], + init() { + if (Browser.initted) return; + Browser.initted = true; + // Support for plugins that can process preloaded files. You can add more of these to + // your app by creating and appending to preloadPlugins. + // Each plugin is asked if it can handle a file based on the file's name. If it can, + // it is given the file's raw data. When it is done, it calls a callback with the file's + // (possibly modified) data. For example, a plugin might decompress a file, or it + // might create some side data structure for use later (like an Image element, etc.). + var imagePlugin = {}; + imagePlugin["canHandle"] = name => !Module["noImageDecoding"] && /\.(jpg|jpeg|png|bmp|webp)$/i.test(name); + imagePlugin["handle"] = async (byteArray, name) => { + var b = new Blob([ byteArray ], { + type: Browser.getMimetype(name) + }); + if (b.size !== byteArray.length) { + // Safari bug #118630 + // Safari's Blob can only take an ArrayBuffer + b = new Blob([ (new Uint8Array(byteArray)).buffer ], { + type: Browser.getMimetype(name) + }); + } + var url = URL.createObjectURL(b); + return new Promise((resolve, reject) => { + var img = new Image; + img.onload = () => { + var canvas = /** @type {!HTMLCanvasElement} */ (document.createElement("canvas")); + canvas.width = img.width; + canvas.height = img.height; + var ctx = canvas.getContext("2d"); + ctx.drawImage(img, 0, 0); + Browser.preloadedImages[name] = canvas; + URL.revokeObjectURL(url); + resolve(byteArray); + }; + img.onerror = event => { + err(`Image ${url} could not be decoded`); + reject(); + }; + img.src = url; + }); + }; + preloadPlugins.push(imagePlugin); + var audioPlugin = {}; + audioPlugin["canHandle"] = name => !Module["noAudioDecoding"] && name.slice(-4) in { + ".ogg": 1, + ".wav": 1, + ".mp3": 1 + }; + audioPlugin["handle"] = async (byteArray, name) => new Promise((resolve, reject) => { + var done = false; + function finish(audio) { + if (done) return; + done = true; + Browser.preloadedAudios[name] = audio; + resolve(byteArray); + } + var b = new Blob([ byteArray ], { + type: Browser.getMimetype(name) + }); + var url = URL.createObjectURL(b); + // XXX we never revoke this! + var audio = new Audio; + audio.addEventListener("canplaythrough", () => finish(audio)); + // use addEventListener due to chromium bug 124926 + audio.onerror = event => { + if (done) return; + err(`warning: browser could not fully decode audio ${name}, trying slower base64 approach`); + function encode64(data) { + var BASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var PAD = "="; + var ret = ""; + var leftchar = 0; + var leftbits = 0; + for (var byte of data) { + leftchar = (leftchar << 8) | byte; + leftbits += 8; + while (leftbits >= 6) { + var curr = (leftchar >> (leftbits - 6)) & 63; + leftbits -= 6; + ret += BASE[curr]; + } + } + if (leftbits == 2) { + ret += BASE[(leftchar & 3) << 4]; + ret += PAD + PAD; + } else if (leftbits == 4) { + ret += BASE[(leftchar & 15) << 2]; + ret += PAD; + } + return ret; + } + audio.src = "data:audio/x-" + name.slice(-3) + ";base64," + encode64(byteArray); + finish(audio); + }; + audio.src = url; + // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror + safeSetTimeout(() => { + finish(audio); + }, 1e4); + }); + preloadPlugins.push(audioPlugin); + // Canvas event setup + function pointerLockChange() { + var canvas = Browser.getCanvas(); + Browser.pointerLock = document.pointerLockElement === canvas; + } + var canvas = Browser.getCanvas(); + if (canvas) { + // forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module + // Module['forcedAspectRatio'] = 4 / 3; + document.addEventListener("pointerlockchange", pointerLockChange); + if (Module["elementPointerLock"]) { + canvas.addEventListener("click", ev => { + if (!Browser.pointerLock && Browser.getCanvas().requestPointerLock) { + Browser.getCanvas().requestPointerLock(); + ev.preventDefault(); + } + }); + } + } + }, + createContext(/** @type {HTMLCanvasElement} */ canvas, useWebGL, setInModule, webGLContextAttributes) { + if (useWebGL && Module["ctx"] && canvas == Browser.getCanvas()) return Module["ctx"]; + // no need to recreate GL context if it's already been created for this canvas. + var ctx; + var contextHandle; + if (useWebGL) { + // For GLES2/desktop GL compatibility, adjust a few defaults to be different to WebGL defaults, so that they align better with the desktop defaults. + var contextAttributes = { + antialias: false, + alpha: false, + majorVersion: (typeof WebGL2RenderingContext != "undefined") ? 2 : 1 + }; + if (webGLContextAttributes) { + for (var attribute in webGLContextAttributes) { + contextAttributes[attribute] = webGLContextAttributes[attribute]; + } + } + // This check of existence of GL is here to satisfy Closure compiler, which yells if variable GL is referenced below but GL object is not + // actually compiled in because application is not doing any GL operations. TODO: Ideally if GL is not being used, this function + // Browser.createContext() should not even be emitted. + if (typeof GL != "undefined") { + contextHandle = GL.createContext(canvas, contextAttributes); + if (contextHandle) { + ctx = GL.getContext(contextHandle).GLctx; + } + } + } else { + ctx = canvas.getContext("2d"); + } + if (!ctx) return null; + if (setInModule) { + Module["ctx"] = ctx; + if (useWebGL) GL.makeContextCurrent(contextHandle); + Browser.useWebGL = useWebGL; + Browser.moduleContextCreatedCallbacks.forEach(callback => callback()); + Browser.init(); + } + return ctx; + }, + fullscreenHandlersInstalled: false, + lockPointer: undefined, + resizeCanvas: undefined, + requestFullscreen(lockPointer, resizeCanvas) { + Browser.lockPointer = lockPointer; + Browser.resizeCanvas = resizeCanvas; + if (typeof Browser.lockPointer == "undefined") Browser.lockPointer = true; + if (typeof Browser.resizeCanvas == "undefined") Browser.resizeCanvas = false; + var canvas = Browser.getCanvas(); + function fullscreenChange() { + Browser.isFullscreen = false; + var canvasContainer = canvas.parentNode; + if (getFullscreenElement() === canvasContainer) { + canvas.exitFullscreen = Browser.exitFullscreen; + if (Browser.lockPointer) canvas.requestPointerLock(); + Browser.isFullscreen = true; + if (Browser.resizeCanvas) { + Browser.setFullscreenCanvasSize(); + } else { + Browser.updateCanvasDimensions(canvas); + } + } else { + // remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen + canvasContainer.parentNode.insertBefore(canvas, canvasContainer); + canvasContainer.parentNode.removeChild(canvasContainer); + if (Browser.resizeCanvas) { + Browser.setWindowedCanvasSize(); + } else { + Browser.updateCanvasDimensions(canvas); + } + } + } + if (!Browser.fullscreenHandlersInstalled) { + Browser.fullscreenHandlersInstalled = true; + document.addEventListener("fullscreenchange", fullscreenChange); + document.addEventListener("webkitfullscreenchange", fullscreenChange); + } + // create a new parent to ensure the canvas has no siblings. this allows browsers to optimize full screen performance when its parent is the full screen root + var canvasContainer = document.createElement("div"); + canvas.parentNode.insertBefore(canvasContainer, canvas); + canvasContainer.appendChild(canvas); + // use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size) + // Safari didn't support Element.requestFullscreen until 16.4 + // See: https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen + /** @suppress {checkTypes} */ canvasContainer.requestFullscreen ??= (canvasContainer["webkitRequestFullscreen"] ? () => canvasContainer["webkitRequestFullscreen"](Element.ALLOW_KEYBOARD_INPUT) : null) ?? (canvasContainer["webkitRequestFullScreen"] ? () => canvasContainer["webkitRequestFullScreen"](Element.ALLOW_KEYBOARD_INPUT) : null); + canvasContainer.requestFullscreen(); + }, + exitFullscreen() { + // This is workaround for chrome. Trying to exit from fullscreen + // not in fullscreen state will cause 'TypeError: Document not active' + // in chrome. See https://github.com/emscripten-core/emscripten/pull/8236 + if (!Browser.isFullscreen) { + return false; + } + var CFS = document.exitFullscreen ?? document["webkitCancelFullScreen"]; + CFS.apply(document, []); + return true; + }, + safeSetTimeout(func, timeout) { + // Legacy function, this is used by the SDL2 port so we need to keep it + // around at least until that is updated. + // See https://github.com/libsdl-org/SDL/pull/6304 + return safeSetTimeout(func, timeout); + }, + getMimetype(name) { + return { + "jpg": "image/jpeg", + "jpeg": "image/jpeg", + "png": "image/png", + "bmp": "image/bmp", + "ogg": "audio/ogg", + "wav": "audio/wav", + "mp3": "audio/mpeg" + }[name.slice(name.lastIndexOf(".") + 1)]; + }, + getUserMedia(func) { + return navigator.mediaDevices.getUserMedia(func); + }, + getMouseWheelDelta(event) { + var delta = 0; + switch (event.type) { + case "DOMMouseScroll": + // 3 lines make up a step + delta = event.detail / 3; + break; + + case "mousewheel": + // 120 units make up a step + delta = event.wheelDelta / 120; + break; + + case "wheel": + delta = event.deltaY; + switch (event.deltaMode) { + case 0: + // DOM_DELTA_PIXEL: 100 pixels make up a step + delta /= 100; + break; + + case 1: + // DOM_DELTA_LINE: 3 lines make up a step + delta /= 3; + break; + + case 2: + // DOM_DELTA_PAGE: A page makes up 80 steps + delta *= 80; + break; + + default: + abort("unrecognized mouse wheel delta mode: " + event.deltaMode); + } + break; + + default: + abort("unrecognized mouse wheel event: " + event.type); + } + return delta; + }, + mouseX: 0, + mouseY: 0, + mouseMovementX: 0, + mouseMovementY: 0, + touches: {}, + lastTouches: {}, + calculateMouseCoords(pageX, pageY) { + // Calculate the movement based on the changes + // in the coordinates. + var canvas = Browser.getCanvas(); + var rect = canvas.getBoundingClientRect(); + var adjustedX = pageX - (window.scrollX + rect.left); + var adjustedY = pageY - (window.scrollY + rect.top); + // the canvas might be CSS-scaled compared to its backbuffer; + // SDL-using content will want mouse coordinates in terms + // of backbuffer units. + adjustedX = adjustedX * (canvas.width / rect.width); + adjustedY = adjustedY * (canvas.height / rect.height); + return { + x: adjustedX, + y: adjustedY + }; + }, + setMouseCoords(pageX, pageY) { + const {x, y} = Browser.calculateMouseCoords(pageX, pageY); + Browser.mouseMovementX = x - Browser.mouseX; + Browser.mouseMovementY = y - Browser.mouseY; + Browser.mouseX = x; + Browser.mouseY = y; + }, + calculateMouseEvent(event) { + // event should be mousemove, mousedown or mouseup + if (Browser.pointerLock) { + // When the pointer is locked, calculate the coordinates + // based on the movement of the mouse. + Browser.mouseMovementX = event.movementX; + Browser.mouseMovementY = event.movementY; + // add the mouse delta to the current absolute mouse position + Browser.mouseX += Browser.mouseMovementX; + Browser.mouseY += Browser.mouseMovementY; + } else { + if (event.type === "touchstart" || event.type === "touchend" || event.type === "touchmove") { + var touch = event.touch; + if (touch === undefined) { + return; + } + var coords = Browser.calculateMouseCoords(touch.pageX, touch.pageY); + if (event.type === "touchstart") { + Browser.lastTouches[touch.identifier] = coords; + Browser.touches[touch.identifier] = coords; + } else if (event.type === "touchend" || event.type === "touchmove") { + var last = Browser.touches[touch.identifier]; + last ||= coords; + Browser.lastTouches[touch.identifier] = last; + Browser.touches[touch.identifier] = coords; + } + return; + } + Browser.setMouseCoords(event.pageX, event.pageY); + } + }, + resizeListeners: [], + updateResizeListeners() { + var canvas = Browser.getCanvas(); + Browser.resizeListeners.forEach(listener => listener(canvas.width, canvas.height)); + }, + setCanvasSize(width, height, noUpdates) { + var canvas = Browser.getCanvas(); + Browser.updateCanvasDimensions(canvas, width, height); + if (!noUpdates) Browser.updateResizeListeners(); + }, + windowedWidth: 0, + windowedHeight: 0, + setFullscreenCanvasSize() { + // check if SDL is available + if (typeof SDL != "undefined") { + var flags = HEAPU32[((SDL.screen) >> 2)]; + flags = flags | 8388608; + // set SDL_FULLSCREEN flag + HEAP32[((SDL.screen) >> 2)] = flags; + } + Browser.updateCanvasDimensions(Browser.getCanvas()); + Browser.updateResizeListeners(); + }, + setWindowedCanvasSize() { + // check if SDL is available + if (typeof SDL != "undefined") { + var flags = HEAPU32[((SDL.screen) >> 2)]; + flags = flags & ~8388608; + // clear SDL_FULLSCREEN flag + HEAP32[((SDL.screen) >> 2)] = flags; + } + Browser.updateCanvasDimensions(Browser.getCanvas()); + Browser.updateResizeListeners(); + }, + updateCanvasDimensions(canvas, wNative, hNative) { + if (wNative && hNative) { + canvas.widthNative = wNative; + canvas.heightNative = hNative; + } else { + wNative = canvas.widthNative; + hNative = canvas.heightNative; + } + var w = wNative; + var h = hNative; + if ((getFullscreenElement() === canvas.parentNode) && (typeof screen != "undefined")) { + var factor = Math.min(screen.width / w, screen.height / h); + w = Math.round(w * factor); + h = Math.round(h * factor); + } + if (Browser.resizeCanvas) { + if (canvas.width != w) canvas.width = w; + if (canvas.height != h) canvas.height = h; + if (typeof canvas.style != "undefined") { + canvas.style.removeProperty("width"); + canvas.style.removeProperty("height"); + } + } else { + if (canvas.width != wNative) canvas.width = wNative; + if (canvas.height != hNative) canvas.height = hNative; + if (typeof canvas.style != "undefined") { + if (w != wNative || h != hNative) { + canvas.style.setProperty("width", w + "px", "important"); + canvas.style.setProperty("height", h + "px", "important"); + } else { + canvas.style.removeProperty("width"); + canvas.style.removeProperty("height"); + } + } + } + } +}; + +/** @type {!Int8Array} */ var HEAP8; + +var callRuntimeCallbacks = callbacks => { + while (callbacks.length > 0) { + // Pass the module as the first argument. + callbacks.shift()(Module); + } +}; + +var onPostRuns = []; + +var onPreRuns = []; + +var noExitRuntime = true; + +var stackRestore = val => __emscripten_stack_restore(val); + +var stackSave = () => _emscripten_stack_get_current(); + +class ExceptionInfo { + // excPtr - Thrown object pointer to wrap. Metadata pointer is calculated from it. + constructor(excPtr) { + this.excPtr = excPtr; + this.ptr = excPtr - 24; + } + set_type(type) { + HEAPU32[(((this.ptr) + (4)) >> 2)] = type; + } + get_type() { + return HEAPU32[(((this.ptr) + (4)) >> 2)]; + } + set_destructor(destructor) { + HEAPU32[(((this.ptr) + (8)) >> 2)] = destructor; + } + get_destructor() { + return HEAPU32[(((this.ptr) + (8)) >> 2)]; + } + set_caught(caught) { + caught = caught ? 1 : 0; + HEAP8[(this.ptr) + (12)] = caught; + } + get_caught() { + return HEAP8[(this.ptr) + (12)] != 0; + } + set_rethrown(rethrown) { + rethrown = rethrown ? 1 : 0; + HEAP8[(this.ptr) + (13)] = rethrown; + } + get_rethrown() { + return HEAP8[(this.ptr) + (13)] != 0; + } + // Initialize native structure fields. Should be called once after allocated. + init(type, destructor) { + this.set_adjusted_ptr(0); + this.set_type(type); + this.set_destructor(destructor); + } + set_adjusted_ptr(adjustedPtr) { + HEAPU32[(((this.ptr) + (16)) >> 2)] = adjustedPtr; + } + get_adjusted_ptr() { + return HEAPU32[(((this.ptr) + (16)) >> 2)]; + } +} + +var uncaughtExceptionCount = 0; + +var __Unwind_RaiseException = ex => { + abort(); +}; + +var ___cxa_throw = (ptr, type, destructor) => { + var info = new ExceptionInfo(ptr); + // Initialize ExceptionInfo content after it was allocated in __cxa_allocate_exception. + info.init(type, destructor); + uncaughtExceptionCount++; + __Unwind_RaiseException(ptr); +}; + +var PATH = { + isAbs: path => path.charAt(0) === "/", + splitPath: filename => { + var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; + return splitPathRe.exec(filename).slice(1); + }, + normalizeArray: (parts, allowAboveRoot) => { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === ".") { + parts.splice(i, 1); + } else if (last === "..") { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (;up; up--) { + parts.unshift(".."); + } + } + return parts; + }, + normalize: path => { + var isAbsolute = PATH.isAbs(path), trailingSlash = path.slice(-1) === "/"; + // Normalize the path + path = PATH.normalizeArray(path.split("/").filter(p => !!p), !isAbsolute).join("/"); + if (!path && !isAbsolute) { + path = "."; + } + if (path && trailingSlash) { + path += "/"; + } + return (isAbsolute ? "/" : "") + path; + }, + dirname: path => { + var result = PATH.splitPath(path), root = result[0], dir = result[1]; + if (!root && !dir) { + // No dirname whatsoever + return "."; + } + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.slice(0, -1); + } + return root + dir; + }, + basename: path => path && path.match(/([^\/]+|\/)\/*$/)[1], + join: (...paths) => PATH.normalize(paths.join("/")), + join2: (l, r) => PATH.normalize(l + "/" + r) +}; + +var initRandomFill = () => { + // This block is not needed on v19+ since crypto.getRandomValues is builtin + if (ENVIRONMENT_IS_NODE) { + var nodeCrypto = require("node:crypto"); + return view => (nodeCrypto.randomFillSync(view), 0); + } + return view => (crypto.getRandomValues(view), 0); +}; + +var randomFill = view => (randomFill = initRandomFill())(view); + +var PATH_FS = { + resolve: (...args) => { + var resolvedPath = "", resolvedAbsolute = false; + for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? args[i] : FS.cwd(); + // Skip empty and invalid entries + if (typeof path != "string") { + throw new TypeError("Arguments to path.resolve must be strings"); + } else if (!path) { + return ""; + } + resolvedPath = path + "/" + resolvedPath; + resolvedAbsolute = PATH.isAbs(path); + } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + resolvedPath = PATH.normalizeArray(resolvedPath.split("/").filter(p => !!p), !resolvedAbsolute).join("/"); + return ((resolvedAbsolute ? "/" : "") + resolvedPath) || "."; + }, + relative: (from, to) => { + from = PATH_FS.resolve(from).slice(1); + to = PATH_FS.resolve(to).slice(1); + function trim(arr) { + var start = 0; + for (;start < arr.length; start++) { + if (arr[start] !== "") break; + } + var end = arr.length - 1; + for (;end >= 0; end--) { + if (arr[end] !== "") break; + } + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + var fromParts = trim(from.split("/")); + var toParts = trim(to.split("/")); + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push(".."); + } + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + return outputParts.join("/"); + } +}; + +var UTF8Decoder = new TextDecoder; + +/** + * heapOrArray is either a regular array, or a JavaScript typed array view. + * @param {number} idx + * @param {number=} maxBytesToRead + * @param {boolean=} ignoreNul + * @return {number} + */ var findStringEnd = (heapOrArray, idx, maxBytesToRead, ignoreNul) => { + var maxIdx = idx + maxBytesToRead; + if (ignoreNul) return maxIdx; + // TextDecoder needs to know the byte length in advance, it doesn't stop on + // null terminator by itself. + // As a tiny code save trick, compare idx against maxIdx using a negation, + // so that maxBytesToRead=undefined/NaN means Infinity. + while (heapOrArray[idx] && !(idx >= maxIdx)) ++idx; + return idx; +}; + +/** + * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given + * array that contains uint8 values, returns a copy of that string as a + * Javascript String object. + * heapOrArray is either a regular array, or a JavaScript typed array view. + * @param {number=} idx + * @param {number=} maxBytesToRead + * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character. + * @return {string} + */ var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead, ignoreNul) => { + var endPtr = findStringEnd(heapOrArray, idx, maxBytesToRead, ignoreNul); + return UTF8Decoder.decode(heapOrArray.buffer ? heapOrArray.subarray(idx, endPtr) : new Uint8Array(heapOrArray.slice(idx, endPtr))); +}; + +var FS_stdin_getChar_buffer = []; + +var lengthBytesUTF8 = str => { + var len = 0; + for (var i = 0; i < str.length; ++i) { + // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code + // unit, not a Unicode code point of the character! So decode + // UTF16->UTF32->UTF8. + // See http://unicode.org/faq/utf_bom.html#utf16-3 + var c = str.charCodeAt(i); + // possibly a lead surrogate + if (c <= 127) { + len++; + } else if (c <= 2047) { + len += 2; + } else if (c >= 55296 && c <= 57343) { + len += 4; + ++i; + } else { + len += 3; + } + } + return len; +}; + +var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => { + // Parameter maxBytesToWrite is not optional. Negative values, 0, null, + // undefined and false each don't write out any bytes. + if (!(maxBytesToWrite > 0)) return 0; + var startIdx = outIdx; + var endIdx = outIdx + maxBytesToWrite - 1; + // -1 for string null terminator. + for (var i = 0; i < str.length; ++i) { + // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description + // and https://www.ietf.org/rfc/rfc2279.txt + // and https://tools.ietf.org/html/rfc3629 + var u = str.codePointAt(i); + if (u <= 127) { + if (outIdx >= endIdx) break; + heap[outIdx++] = u; + } else if (u <= 2047) { + if (outIdx + 1 >= endIdx) break; + heap[outIdx++] = 192 | (u >> 6); + heap[outIdx++] = 128 | (u & 63); + } else if (u <= 65535) { + if (outIdx + 2 >= endIdx) break; + heap[outIdx++] = 224 | (u >> 12); + heap[outIdx++] = 128 | ((u >> 6) & 63); + heap[outIdx++] = 128 | (u & 63); + } else { + if (outIdx + 3 >= endIdx) break; + heap[outIdx++] = 240 | (u >> 18); + heap[outIdx++] = 128 | ((u >> 12) & 63); + heap[outIdx++] = 128 | ((u >> 6) & 63); + heap[outIdx++] = 128 | (u & 63); + // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16. + // We need to manually skip over the second code unit for correct iteration. + i++; + } + } + // Null-terminate the pointer to the buffer. + heap[outIdx] = 0; + return outIdx - startIdx; +}; + +/** @type {function(string, boolean=, number=)} */ var intArrayFromString = (stringy, dontAddNull, length) => { + var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1; + var u8array = new Array(len); + var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length); + if (dontAddNull) u8array.length = numBytesWritten; + return u8array; +}; + +var FS_stdin_getChar = () => { + if (!FS_stdin_getChar_buffer.length) { + var result = null; + if (ENVIRONMENT_IS_NODE) { + // we will read data by chunks of BUFSIZE + var BUFSIZE = 256; + var buf = Buffer.alloc(BUFSIZE); + var bytesRead = 0; + // For some reason we must suppress a closure warning here, even though + // fd definitely exists on process.stdin, and is even the proper way to + // get the fd of stdin, + // https://github.com/nodejs/help/issues/2136#issuecomment-523649904 + // This started to happen after moving this logic out of library_tty.js, + // so it is related to the surrounding code in some unclear manner. + /** @suppress {missingProperties} */ var fd = process.stdin.fd; + try { + bytesRead = fs.readSync(fd, buf, 0, BUFSIZE); + } catch (e) { + // Cross-platform differences: on Windows, reading EOF throws an + // exception, but on other OSes, reading EOF returns 0. Uniformize + // behavior by treating the EOF exception to return 0. + if (e.toString().includes("EOF")) bytesRead = 0; else throw e; + } + if (bytesRead > 0) { + result = buf.slice(0, bytesRead).toString("utf-8"); + } + } else if (globalThis.window?.prompt) { + // Browser. + result = window.prompt("Input: "); + // returns null on cancel + if (result !== null) { + result += "\n"; + } + } else {} + if (!result) { + return null; + } + FS_stdin_getChar_buffer = intArrayFromString(result, true); + } + return FS_stdin_getChar_buffer.shift(); +}; + +var TTY = { + ttys: [], + init() {}, + shutdown() {}, + register(dev, ops) { + TTY.ttys[dev] = { + input: [], + output: [], + ops + }; + FS.registerDevice(dev, TTY.stream_ops); + }, + stream_ops: { + open(stream) { + var tty = TTY.ttys[stream.node.rdev]; + if (!tty) { + throw new FS.ErrnoError(43); + } + stream.tty = tty; + stream.seekable = false; + }, + close(stream) { + // flush any pending line data + stream.tty.ops.fsync(stream.tty); + }, + fsync(stream) { + stream.tty.ops.fsync(stream.tty); + }, + read(stream, buffer, offset, length, pos) { + if (!stream.tty || !stream.tty.ops.get_char) { + throw new FS.ErrnoError(60); + } + var bytesRead = 0; + for (var i = 0; i < length; i++) { + var result; + try { + result = stream.tty.ops.get_char(stream.tty); + } catch (e) { + throw new FS.ErrnoError(29); + } + if (result === undefined && !bytesRead) { + throw new FS.ErrnoError(6); + } + if (result === null || result === undefined) break; + bytesRead++; + buffer[offset + i] = result; + // We currently only support canonical mode (ICANON), where + // read(2) returns as soon as a line delimiter is read. + if (result === 10) break; + } + if (bytesRead) { + stream.node.atime = Date.now(); + } + return bytesRead; + }, + write(stream, buffer, offset, length, pos) { + if (!stream.tty || !stream.tty.ops.put_char) { + throw new FS.ErrnoError(60); + } + try { + for (var i = 0; i < length; i++) { + stream.tty.ops.put_char(stream.tty, buffer[offset + i]); + } + } catch (e) { + throw new FS.ErrnoError(29); + } + if (length) { + stream.node.mtime = stream.node.ctime = Date.now(); + } + return i; + } + }, + default_tty_ops: { + get_char(tty) { + return FS_stdin_getChar(); + }, + put_char(tty, val) { + if (val === null || val === 10) { + out(UTF8ArrayToString(tty.output)); + tty.output = []; + } else { + if (val != 0) tty.output.push(val); + } + }, + fsync(tty) { + if (tty.output?.length > 0) { + out(UTF8ArrayToString(tty.output)); + tty.output = []; + } + }, + ioctl_tcgets(tty) { + // typical setting + return { + c_iflag: 25856, + c_oflag: 5, + c_cflag: 191, + c_lflag: 35387, + c_cc: [ 3, 28, 127, 21, 4, 0, 1, 0, 17, 19, 26, 0, 18, 15, 23, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] + }; + }, + ioctl_tcsets(tty, optional_actions, data) { + // currently just ignore + return 0; + }, + ioctl_tiocgwinsz(tty) { + return [ 24, 80 ]; + } + }, + default_tty1_ops: { + put_char(tty, val) { + if (val === null || val === 10) { + err(UTF8ArrayToString(tty.output)); + tty.output = []; + } else { + if (val != 0) tty.output.push(val); + } + }, + fsync(tty) { + if (tty.output?.length > 0) { + err(UTF8ArrayToString(tty.output)); + tty.output = []; + } + } + } +}; + +/** @type {!Uint8Array} */ var HEAPU8; + +var zeroMemory = (ptr, size) => HEAPU8.fill(0, ptr, ptr + size); + +var alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment; + +var mmapAlloc = size => { + size = alignMemory(size, 65536); + var ptr = _emscripten_builtin_memalign(65536, size); + if (ptr) zeroMemory(ptr, size); + return ptr; +}; + +var MEMFS = { + ops_table: null, + mount(mount) { + return MEMFS.createNode(null, "/", 16895, 0); + }, + createNode(parent, name, mode, dev) { + if (FS.isBlkdev(mode) || FS.isFIFO(mode)) { + // not supported + throw new FS.ErrnoError(63); + } + MEMFS.ops_table ||= { + dir: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr, + lookup: MEMFS.node_ops.lookup, + mknod: MEMFS.node_ops.mknod, + rename: MEMFS.node_ops.rename, + unlink: MEMFS.node_ops.unlink, + rmdir: MEMFS.node_ops.rmdir, + readdir: MEMFS.node_ops.readdir, + symlink: MEMFS.node_ops.symlink + }, + stream: { + llseek: MEMFS.stream_ops.llseek + } + }, + file: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr + }, + stream: { + llseek: MEMFS.stream_ops.llseek, + read: MEMFS.stream_ops.read, + write: MEMFS.stream_ops.write, + mmap: MEMFS.stream_ops.mmap, + msync: MEMFS.stream_ops.msync + } + }, + link: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr, + readlink: MEMFS.node_ops.readlink + }, + stream: {} + }, + chrdev: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr + }, + stream: FS.chrdev_stream_ops + } + }; + var node = FS.createNode(parent, name, mode, dev); + if (FS.isDir(node.mode)) { + node.node_ops = MEMFS.ops_table.dir.node; + node.stream_ops = MEMFS.ops_table.dir.stream; + node.contents = {}; + } else if (FS.isFile(node.mode)) { + node.node_ops = MEMFS.ops_table.file.node; + node.stream_ops = MEMFS.ops_table.file.stream; + // The actual number of bytes used in the typed array, as opposed to + // contents.length which gives the whole capacity. + node.usedBytes = 0; + // The byte data of the file is stored in a typed array. + // Note: typed arrays are not resizable like normal JS arrays are, so + // there is a small penalty involved for appending file writes that + // continuously grow a file similar to std::vector capacity vs used. + node.contents = MEMFS.emptyFileContents ??= new Uint8Array(0); + } else if (FS.isLink(node.mode)) { + node.node_ops = MEMFS.ops_table.link.node; + node.stream_ops = MEMFS.ops_table.link.stream; + } else if (FS.isChrdev(node.mode)) { + node.node_ops = MEMFS.ops_table.chrdev.node; + node.stream_ops = MEMFS.ops_table.chrdev.stream; + } + node.atime = node.mtime = node.ctime = Date.now(); + // add the new node to the parent + if (parent) { + parent.contents[name] = node; + parent.atime = parent.mtime = parent.ctime = node.atime; + } + return node; + }, + getFileDataAsTypedArray(node) { + return node.contents.subarray(0, node.usedBytes); + }, + expandFileStorage(node, newCapacity) { + var prevCapacity = node.contents.length; + if (prevCapacity >= newCapacity) return; + // No need to expand, the storage was already large enough. + // Don't expand strictly to the given requested limit if it's only a very + // small increase, but instead geometrically grow capacity. + // For small filesizes (<1MB), perform size*2 geometric increase, but for + // large sizes, do a much more conservative size*1.125 increase to avoid + // overshooting the allocation cap by a very large margin. + var CAPACITY_DOUBLING_MAX = 1024 * 1024; + newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125)) >>> 0); + if (prevCapacity) newCapacity = Math.max(newCapacity, 256); + // At minimum allocate 256b for each file when expanding. + var oldContents = MEMFS.getFileDataAsTypedArray(node); + node.contents = new Uint8Array(newCapacity); + // Allocate new storage. + node.contents.set(oldContents); + }, + resizeFileStorage(node, newSize) { + if (node.usedBytes == newSize) return; + var oldContents = node.contents; + node.contents = new Uint8Array(newSize); + // Allocate new storage. + node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes))); + // Copy old data over to the new storage. + node.usedBytes = newSize; + }, + node_ops: { + getattr(node) { + var attr = {}; + // device numbers reuse inode numbers. + attr.dev = FS.isChrdev(node.mode) ? node.id : 1; + attr.ino = node.id; + attr.mode = node.mode; + attr.nlink = 1; + attr.uid = 0; + attr.gid = 0; + attr.rdev = node.rdev; + if (FS.isDir(node.mode)) { + attr.size = 4096; + } else if (FS.isFile(node.mode)) { + attr.size = node.usedBytes; + } else if (FS.isLink(node.mode)) { + attr.size = node.link.length; + } else { + attr.size = 0; + } + attr.atime = new Date(node.atime); + attr.mtime = new Date(node.mtime); + attr.ctime = new Date(node.ctime); + // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize), + // but this is not required by the standard. + attr.blksize = 4096; + attr.blocks = Math.ceil(attr.size / attr.blksize); + return attr; + }, + setattr(node, attr) { + for (const key of [ "mode", "atime", "mtime", "ctime" ]) { + if (attr[key] != null) { + node[key] = attr[key]; + } + } + if (attr.size !== undefined) { + MEMFS.resizeFileStorage(node, attr.size); + } + }, + lookup(parent, name) { + // This error may happen quite a bit. To avoid overhead we reuse it (and + // suffer a lack of stack info). + if (!MEMFS.doesNotExistError) { + MEMFS.doesNotExistError = new FS.ErrnoError(44); + /** @suppress {checkTypes} */ MEMFS.doesNotExistError.stack = ""; + } + throw MEMFS.doesNotExistError; + }, + mknod(parent, name, mode, dev) { + return MEMFS.createNode(parent, name, mode, dev); + }, + rename(old_node, new_dir, new_name) { + var new_node; + try { + new_node = FS.lookupNode(new_dir, new_name); + } catch (e) {} + if (new_node) { + if (FS.isDir(old_node.mode)) { + // if we're overwriting a directory at new_name, make sure it's empty. + for (var i in new_node.contents) { + throw new FS.ErrnoError(55); + } + } + FS.hashRemoveNode(new_node); + } + // do the internal rewiring + delete old_node.parent.contents[old_node.name]; + new_dir.contents[new_name] = old_node; + old_node.name = new_name; + new_dir.ctime = new_dir.mtime = old_node.parent.ctime = old_node.parent.mtime = Date.now(); + }, + unlink(parent, name) { + delete parent.contents[name]; + parent.ctime = parent.mtime = Date.now(); + }, + rmdir(parent, name) { + var node = FS.lookupNode(parent, name); + for (var i in node.contents) { + throw new FS.ErrnoError(55); + } + delete parent.contents[name]; + parent.ctime = parent.mtime = Date.now(); + }, + readdir(node) { + return [ ".", "..", ...Object.keys(node.contents) ]; + }, + symlink(parent, newname, oldpath) { + var node = MEMFS.createNode(parent, newname, 511 | 40960, 0); + node.link = oldpath; + return node; + }, + readlink(node) { + if (!FS.isLink(node.mode)) { + throw new FS.ErrnoError(28); + } + return node.link; + } + }, + stream_ops: { + read(stream, buffer, offset, length, position) { + var contents = stream.node.contents; + if (position >= stream.node.usedBytes) return 0; + var size = Math.min(stream.node.usedBytes - position, length); + buffer.set(contents.subarray(position, position + size), offset); + return size; + }, + write(stream, buffer, offset, length, position, canOwn) { + // If the buffer is located in main memory (HEAP), and if + // memory can grow, we can't hold on to references of the + // memory buffer, as they may get invalidated. That means we + // need to copy its contents. + if (buffer.buffer === HEAP8.buffer) { + canOwn = false; + } + if (!length) return 0; + var node = stream.node; + node.mtime = node.ctime = Date.now(); + if (canOwn) { + node.contents = buffer.subarray(offset, offset + length); + node.usedBytes = length; + } else if (!node.usedBytes && !position) { + // If this is a simple first write to an empty file, do a fast set since we don't need to care about old data. + node.contents = buffer.slice(offset, offset + length); + node.usedBytes = length; + } else { + MEMFS.expandFileStorage(node, position + length); + // Use typed array write which is available. + node.contents.set(buffer.subarray(offset, offset + length), position); + node.usedBytes = Math.max(node.usedBytes, position + length); + } + return length; + }, + llseek(stream, offset, whence) { + var position = offset; + if (whence === 1) { + position += stream.position; + } else if (whence === 2) { + if (FS.isFile(stream.node.mode)) { + position += stream.node.usedBytes; + } + } + if (position < 0) { + throw new FS.ErrnoError(28); + } + return position; + }, + mmap(stream, length, position, prot, flags) { + if (!FS.isFile(stream.node.mode)) { + throw new FS.ErrnoError(43); + } + var ptr; + var allocated; + var contents = stream.node.contents; + // Only make a new copy when MAP_PRIVATE is specified. + if (!(flags & 2) && contents.buffer === HEAP8.buffer) { + // We can't emulate MAP_SHARED when the file is not backed by the + // buffer we're mapping to (e.g. the HEAP buffer). + allocated = false; + ptr = contents.byteOffset; + } else { + allocated = true; + ptr = mmapAlloc(length); + if (!ptr) { + throw new FS.ErrnoError(48); + } + if (contents) { + // Try to avoid unnecessary slices. + if (position > 0 || position + length < contents.length) { + if (contents.subarray) { + contents = contents.subarray(position, position + length); + } else { + contents = Array.prototype.slice.call(contents, position, position + length); + } + } + HEAP8.set(contents, ptr); + } + } + return { + ptr, + allocated + }; + }, + msync(stream, buffer, offset, length, mmapFlags) { + MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false); + // should we check if bytesWritten and length are the same? + return 0; + } + } +}; + +var FS_modeStringToFlags = str => { + if (typeof str != "string") return str; + var flagModes = { + "r": 0, + "r+": 2, + "w": 512 | 64 | 1, + "w+": 512 | 64 | 2, + "a": 1024 | 64 | 1, + "a+": 1024 | 64 | 2 + }; + var flags = flagModes[str]; + if (typeof flags == "undefined") { + throw new Error(`Unknown file open mode: ${str}`); + } + return flags; +}; + +var FS_fileDataToTypedArray = data => { + if (typeof data == "string") { + data = intArrayFromString(data, true); + } + if (!data.subarray) { + data = new Uint8Array(data); + } + return data; +}; + +var FS_getMode = (canRead, canWrite) => { + var mode = 0; + if (canRead) mode |= 292 | 73; + if (canWrite) mode |= 146; + return mode; +}; + +var asyncLoad = async url => { + var arrayBuffer = await readAsync(url); + return new Uint8Array(arrayBuffer); +}; + +var FS_createDataFile = (...args) => FS.createDataFile(...args); + +var getUniqueRunDependency = id => id; + +var dependenciesPromise = null; + +var resolveRunDependencies = async () => dependenciesPromise; + +var runDependencies = 0; + +var dependenciesPromiseResolve = null; + +var removeRunDependency = id => { + runDependencies--; + Module["monitorRunDependencies"]?.(runDependencies); + if (!runDependencies) { + dependenciesPromiseResolve(); + } +}; + +var addRunDependency = id => { + if (!runDependencies) { + dependenciesPromise = new Promise(resolve => dependenciesPromiseResolve = resolve); + } + runDependencies++; + Module["monitorRunDependencies"]?.(runDependencies); +}; + +var FS_handledByPreloadPlugin = async (byteArray, fullname) => { + // Ensure plugins are ready. + if (typeof Browser != "undefined") Browser.init(); + for (var plugin of preloadPlugins) { + if (plugin["canHandle"](fullname)) { + return plugin["handle"](byteArray, fullname); + } + } + // If no plugin handled this file then return the original/unmodified + // byteArray. + return byteArray; +}; + +var FS_preloadFile = async (parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish) => { + // TODO we should allow people to just pass in a complete filename instead + // of parent and name being that we just join them anyways + var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent; + var dep = getUniqueRunDependency(`cp ${fullname}`); + // might have several active requests for the same fullname + addRunDependency(dep); + try { + var byteArray = url; + if (typeof url == "string") { + byteArray = await asyncLoad(url); + } + byteArray = await FS_handledByPreloadPlugin(byteArray, fullname); + preFinish?.(); + if (!dontCreateFile) { + FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn); + } + } finally { + removeRunDependency(dep); + } +}; + +var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => { + FS_preloadFile(parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish).then(onload).catch(onerror); +}; + +var FS = { + root: null, + mounts: [], + devices: {}, + streams: [], + nextInode: 1, + nameTable: null, + currentPath: "/", + initialized: false, + ignorePermissions: true, + filesystems: null, + syncFSRequests: 0, + ErrnoError: class { + name="ErrnoError"; + // We set the `name` property to be able to identify `FS.ErrnoError` + // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway. + // - when using PROXYFS, an error can come from an underlying FS + // as different FS objects have their own FS.ErrnoError each, + // the test `err instanceof FS.ErrnoError` won't detect an error coming from another filesystem, causing bugs. + // we'll use the reliable test `err.name == "ErrnoError"` instead + constructor(errno) { + this.errno = errno; + } + }, + FSStream: class { + shared={}; + get object() { + return this.node; + } + set object(val) { + this.node = val; + } + get isRead() { + return (this.flags & 2097155) !== 1; + } + get isWrite() { + return (this.flags & 2097155) !== 0; + } + get isAppend() { + return (this.flags & 1024); + } + get flags() { + return this.shared.flags; + } + set flags(val) { + this.shared.flags = val; + } + get position() { + return this.shared.position; + } + set position(val) { + this.shared.position = val; + } + }, + FSNode: class { + node_ops={}; + stream_ops={}; + readMode=292 | 73; + writeMode=146; + mounted=null; + constructor(parent, name, mode, rdev) { + if (!parent) { + parent = this; + } + this.parent = parent; + this.mount = parent.mount; + this.id = FS.nextInode++; + this.name = name; + this.mode = mode; + this.rdev = rdev; + this.atime = this.mtime = this.ctime = Date.now(); + } + get read() { + return (this.mode & this.readMode) === this.readMode; + } + set read(val) { + val ? this.mode |= this.readMode : this.mode &= ~this.readMode; + } + get write() { + return (this.mode & this.writeMode) === this.writeMode; + } + set write(val) { + val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode; + } + get isFolder() { + return FS.isDir(this.mode); + } + get isDevice() { + return FS.isChrdev(this.mode); + } + // The per-inode readiness wait-queue. The node carries a Set of listener + // entries {cb}; producers (SOCKFS, PIPEFS) call notifyListeners on a + // readiness transition, and poll()/epoll consume it. It lives on the node + // (not the fd) so dup'd fds share one queue. Only nodes that derive real + // readiness (sockets, pipes, and an epoll's own node) ever use this - + // always-ready types (regular files, ttys) never register or notify. + addListener(cb, exclusive = false) { + var entry = { + cb, + exclusive + }; + var listeners = (this.listeners ??= new Set); + listeners.add(entry); + return { + listeners, + entry + }; + } + notifyListeners(flags) { + // Iterates the set without copying, which is safe ONLY under a + // load-bearing contract that every internal listener must honour: + // 1. A listener must not run user code synchronously (a poll waiter only + // resolves a Promise; an epoll registration only re-lists + + // re-notifies; the epoll callback only schedules a tick). User code + // runs on a later tick, never inside this loop. + // 2. A listener may delete entries only from ITS OWN waiter, never from + // a sibling node's set that may be mid-iteration. (Deleting an entry + // of the set being iterated here is fine - a Set tolerates removal of + // a not-yet-visited entry mid-iteration; mutating a *different* node's + // set is fine because that set is not being iterated.) + // Violating either gives silently skipped wakeups that are near-impossible + // to reproduce. Any new producer/listener must preserve it. + if (!this.listeners) return; + // Fire every non-exclusive listener. Among EPOLLEXCLUSIVE registrations + // (one fd watched by several epolls) wake only one, rotating round-robin + // per node, to avoid a thundering herd. (Only epoll registrations are ever + // exclusive; poll waiters and a node's own consumers are not.) + var excl; + for (var entry of this.listeners) { + if (entry.exclusive) (excl ||= []).push(entry); else entry.cb(flags); + } + if (excl) { + var i = (this.exclTurn || 0) % excl.length; + this.exclTurn = i + 1; + excl[i].cb(flags); + } + } + }, + lookupPath(path, opts = {}) { + if (!path) { + throw new FS.ErrnoError(44); + } + opts.follow_mount ??= true; + if (!PATH.isAbs(path)) { + path = FS.cwd() + "/" + path; + } + // limit max consecutive symlinks to SYMLOOP_MAX. + linkloop: for (var nlinks = 0; nlinks < 40; nlinks++) { + // split the absolute path + var parts = path.split("/").filter(p => !!p); + // start at the root + var current = FS.root; + var current_path = "/"; + for (var i = 0; i < parts.length; i++) { + var islast = (i === parts.length - 1); + if (islast && opts.parent) { + // stop resolving + break; + } + if (parts[i] === ".") { + continue; + } + if (parts[i] === "..") { + current_path = PATH.dirname(current_path); + if (FS.isRoot(current)) { + path = current_path + "/" + parts.slice(i + 1).join("/"); + // We're making progress here, don't let many consecutive ..'s + // lead to ELOOP + nlinks--; + continue linkloop; + } else { + current = current.parent; + } + continue; + } + current_path = PATH.join2(current_path, parts[i]); + try { + current = FS.lookupNode(current, parts[i]); + } catch (e) { + // if noent_okay is true, suppress a ENOENT in the last component + // and return an object with an undefined node. This is needed for + // resolving symlinks in the path when creating a file. + if ((e?.errno === 44) && islast && opts.noent_okay) { + return { + path: current_path + }; + } + throw e; + } + // jump to the mount's root node if this is a mountpoint + if (FS.isMountpoint(current) && (!islast || opts.follow_mount)) { + current = current.mounted.root; + } + // by default, lookupPath will not follow a symlink if it is the final path component. + // setting opts.follow = true will override this behavior. + if (FS.isLink(current.mode) && (!islast || opts.follow)) { + if (!current.node_ops.readlink) { + throw new FS.ErrnoError(52); + } + var link = current.node_ops.readlink(current); + if (!PATH.isAbs(link)) { + link = PATH.dirname(current_path) + "/" + link; + } + path = link + "/" + parts.slice(i + 1).join("/"); + continue linkloop; + } + } + return { + path: current_path, + node: current + }; + } + throw new FS.ErrnoError(32); + }, + getPath(node) { + var path; + while (true) { + if (FS.isRoot(node)) { + var mount = node.mount.mountpoint; + if (!path) return mount; + return mount[mount.length - 1] !== "/" ? `${mount}/${path}` : mount + path; + } + path = path ? `${node.name}/${path}` : node.name; + node = node.parent; + } + }, + hashName(parentid, name) { + var hash = 0; + for (var i = 0; i < name.length; i++) { + hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0; + } + return ((parentid + hash) >>> 0) % FS.nameTable.length; + }, + hashAddNode(node) { + var hash = FS.hashName(node.parent.id, node.name); + node.name_next = FS.nameTable[hash]; + FS.nameTable[hash] = node; + }, + hashRemoveNode(node) { + var hash = FS.hashName(node.parent.id, node.name); + if (FS.nameTable[hash] === node) { + FS.nameTable[hash] = node.name_next; + } else { + var current = FS.nameTable[hash]; + while (current) { + if (current.name_next === node) { + current.name_next = node.name_next; + break; + } + current = current.name_next; + } + } + }, + lookupNode(parent, name) { + var errCode = FS.mayLookup(parent); + if (errCode) { + throw new FS.ErrnoError(errCode); + } + var hash = FS.hashName(parent.id, name); + for (var node = FS.nameTable[hash]; node; node = node.name_next) { + var nodeName = node.name; + if (node.parent.id === parent.id && nodeName === name) { + return node; + } + } + // if we failed to find it in the cache, call into the VFS + return FS.lookup(parent, name); + }, + createNode(parent, name, mode, rdev) { + var node = new FS.FSNode(parent, name, mode, rdev); + FS.hashAddNode(node); + return node; + }, + destroyNode(node) { + FS.hashRemoveNode(node); + }, + isRoot(node) { + return node === node.parent; + }, + isMountpoint(node) { + return !!node.mounted; + }, + isFile(mode) { + return (mode & 61440) === 32768; + }, + isDir(mode) { + return (mode & 61440) === 16384; + }, + isLink(mode) { + return (mode & 61440) === 40960; + }, + isChrdev(mode) { + return (mode & 61440) === 8192; + }, + isBlkdev(mode) { + return (mode & 61440) === 24576; + }, + isFIFO(mode) { + return (mode & 61440) === 4096; + }, + isSocket(mode) { + return (mode & 49152) === 49152; + }, + flagsToPermissionString(flag) { + var perms = [ "r", "w", "rw" ][flag & 3]; + if ((flag & 512)) { + perms += "w"; + } + return perms; + }, + nodePermissions(node, perms) { + if (FS.ignorePermissions) { + return 0; + } + // return 0 if any user, group or owner bits are set. + if (perms.includes("r") && !(node.mode & 292)) { + return 2; + } + if (perms.includes("w") && !(node.mode & 146)) { + return 2; + } + if (perms.includes("x") && !(node.mode & 73)) { + return 2; + } + return 0; + }, + mayLookup(dir) { + if (!FS.isDir(dir.mode)) return 54; + var errCode = FS.nodePermissions(dir, "x"); + if (errCode) return errCode; + if (!dir.node_ops.lookup) return 2; + return 0; + }, + mayCreate(dir, name) { + if (!FS.isDir(dir.mode)) { + return 54; + } + try { + var node = FS.lookupNode(dir, name); + return 20; + } catch (e) {} + return FS.nodePermissions(dir, "wx"); + }, + mayDelete(dir, name, isdir) { + var node; + try { + node = FS.lookupNode(dir, name); + } catch (e) { + return e.errno; + } + var errCode = FS.nodePermissions(dir, "wx"); + if (errCode) { + return errCode; + } + if (isdir) { + if (!FS.isDir(node.mode)) { + return 54; + } + if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) { + return 10; + } + } else if (FS.isDir(node.mode)) { + return 31; + } + return 0; + }, + mayOpen(node, flags) { + if (!node) { + return 44; + } + if (FS.isLink(node.mode)) { + return 32; + } + var mode = FS.flagsToPermissionString(flags); + if (FS.isDir(node.mode)) { + // opening for write + // TODO: check for O_SEARCH? (== search for dir only) + if (mode !== "r" || (flags & (512 | 64))) { + return 31; + } + } + return FS.nodePermissions(node, mode); + }, + checkOpExists(op, err) { + if (!op) { + throw new FS.ErrnoError(err); + } + return op; + }, + MAX_OPEN_FDS: 4096, + nextfd() { + for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) { + if (!FS.streams[fd]) { + return fd; + } + } + throw new FS.ErrnoError(33); + }, + getStreamChecked(fd) { + var stream = FS.getStream(fd); + if (!stream) { + throw new FS.ErrnoError(8); + } + return stream; + }, + getStream: fd => FS.streams[fd], + createStream(stream, fd = -1) { + // clone it, so we can return an instance of FSStream + stream = Object.assign(new FS.FSStream, stream); + if (fd == -1) { + fd = FS.nextfd(); + } + stream.fd = fd; + FS.streams[fd] = stream; + return stream; + }, + closeStream(fd) { + FS.streams[fd] = null; + }, + dupStream(origStream, fd = -1) { + var stream = FS.createStream(origStream, fd); + stream.stream_ops?.dup?.(stream); + return stream; + }, + doSetAttr(stream, node, attr) { + var setattr = stream?.stream_ops.setattr; + var arg = setattr ? stream : node; + setattr ??= node.node_ops.setattr; + FS.checkOpExists(setattr, 63); + try { + setattr(arg, attr); + } catch (e) { + if (e instanceof RangeError) { + throw new FS.ErrnoError(22); + } + throw e; + } + }, + chrdev_stream_ops: { + open(stream) { + var device = FS.getDevice(stream.node.rdev); + // override node's stream ops with the device's + stream.stream_ops = device.stream_ops; + // forward the open call + stream.stream_ops.open?.(stream); + }, + llseek() { + throw new FS.ErrnoError(70); + } + }, + major: dev => ((dev) >> 8), + minor: dev => ((dev) & 255), + makedev: (ma, mi) => ((ma) << 8 | (mi)), + registerDevice(dev, ops) { + FS.devices[dev] = { + stream_ops: ops + }; + }, + getDevice: dev => FS.devices[dev], + getMounts(mount) { + var mounts = []; + var check = [ mount ]; + while (check.length) { + var m = check.pop(); + mounts.push(m); + check.push(...m.mounts); + } + return mounts; + }, + syncfs(populate, callback) { + if (typeof populate == "function") { + callback = populate; + populate = false; + } + FS.syncFSRequests++; + if (FS.syncFSRequests > 1) { + err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`); + } + var mounts = FS.getMounts(FS.root.mount); + var completed = 0; + function doCallback(errCode) { + FS.syncFSRequests--; + return callback(errCode); + } + function done(errCode) { + if (errCode) { + if (!done.errored) { + done.errored = true; + return doCallback(errCode); + } + return; + } + if (++completed >= mounts.length) { + doCallback(null); + } + } + // sync all mounts + for (var mount of mounts) { + if (mount.type.syncfs) { + mount.type.syncfs(mount, populate, done); + } else { + done(null); + } + } + }, + mount(type, opts, mountpoint) { + var root = mountpoint === "/"; + var pseudo = !mountpoint; + var node; + if (root && FS.root) { + throw new FS.ErrnoError(10); + } else if (!root && !pseudo) { + var lookup = FS.lookupPath(mountpoint, { + follow_mount: false + }); + mountpoint = lookup.path; + // use the absolute path + node = lookup.node; + if (FS.isMountpoint(node)) { + throw new FS.ErrnoError(10); + } + if (!FS.isDir(node.mode)) { + throw new FS.ErrnoError(54); + } + } + var mount = { + type, + opts, + mountpoint, + mounts: [] + }; + // create a root node for the fs + var mountRoot = type.mount(mount); + mountRoot.mount = mount; + mount.root = mountRoot; + if (root) { + FS.root = mountRoot; + } else if (node) { + // set as a mountpoint + node.mounted = mount; + // add the new mount to the current mount's children + if (node.mount) { + node.mount.mounts.push(mount); + } + } + return mountRoot; + }, + unmount(mountpoint) { + var lookup = FS.lookupPath(mountpoint, { + follow_mount: false + }); + if (!FS.isMountpoint(lookup.node)) { + throw new FS.ErrnoError(28); + } + // destroy the nodes for this mount, and all its child mounts + var node = lookup.node; + var mount = node.mounted; + var mounts = FS.getMounts(mount); + for (var [hash, current] of Object.entries(FS.nameTable)) { + while (current) { + var next = current.name_next; + if (mounts.includes(current.mount)) { + FS.destroyNode(current); + } + current = next; + } + } + // no longer a mountpoint + node.mounted = null; + // remove this mount from the child mounts + var idx = node.mount.mounts.indexOf(mount); + node.mount.mounts.splice(idx, 1); + }, + lookup(parent, name) { + return parent.node_ops.lookup(parent, name); + }, + mknod(path, mode, dev) { + var lookup = FS.lookupPath(path, { + parent: true + }); + var parent = lookup.node; + var name = PATH.basename(path); + if (!name) { + throw new FS.ErrnoError(28); + } + if (name === "." || name === "..") { + throw new FS.ErrnoError(20); + } + var errCode = FS.mayCreate(parent, name); + if (errCode) { + throw new FS.ErrnoError(errCode); + } + if (!parent.node_ops.mknod) { + throw new FS.ErrnoError(63); + } + return parent.node_ops.mknod(parent, name, mode, dev); + }, + statfs(path) { + return FS.statfsNode(FS.lookupPath(path, { + follow: true + }).node); + }, + statfsStream(stream) { + // We keep a separate statfsStream function because noderawfs overrides + // it. In noderawfs, stream.node is sometimes null. Instead, we need to + // look at stream.path. + return FS.statfsNode(stream.node); + }, + statfsNode(node) { + // NOTE: None of the defaults here are true. We're just returning safe and + // sane values. Currently nodefs and rawfs replace these defaults, + // other file systems leave them alone. + var rtn = { + bsize: 4096, + frsize: 4096, + blocks: 1e6, + bfree: 5e5, + bavail: 5e5, + files: FS.nextInode, + ffree: FS.nextInode - 1, + fsid: 42, + flags: 2, + namelen: 255 + }; + if (node.node_ops.statfs) { + Object.assign(rtn, node.node_ops.statfs(node.mount.opts.root)); + } + return rtn; + }, + create(path, mode = 438) { + mode &= 4095; + mode |= 32768; + return FS.mknod(path, mode, 0); + }, + mkdir(path, mode = 511) { + mode &= 511 | 512; + mode |= 16384; + return FS.mknod(path, mode, 0); + }, + mkdirTree(path, mode) { + var dirs = path.split("/"); + var d = ""; + for (var dir of dirs) { + if (!dir) continue; + if (d || PATH.isAbs(path)) d += "/"; + d += dir; + try { + FS.mkdir(d, mode); + } catch (e) { + if (e.errno != 20) throw e; + } + } + }, + mkdev(path, mode, dev) { + if (typeof dev == "undefined") { + dev = mode; + mode = 438; + } + mode |= 8192; + return FS.mknod(path, mode, dev); + }, + symlink(oldpath, newpath) { + if (!PATH_FS.resolve(oldpath)) { + throw new FS.ErrnoError(44); + } + var lookup = FS.lookupPath(newpath, { + parent: true + }); + var parent = lookup.node; + if (!parent) { + throw new FS.ErrnoError(44); + } + var newname = PATH.basename(newpath); + var errCode = FS.mayCreate(parent, newname); + if (errCode) { + throw new FS.ErrnoError(errCode); + } + if (!parent.node_ops.symlink) { + throw new FS.ErrnoError(63); + } + return parent.node_ops.symlink(parent, newname, oldpath); + }, + link(oldpath, newpath, flags) { + var lookup = FS.lookupPath(newpath, { + parent: true + }); + var parent = lookup.node; + if (!parent) { + throw new FS.ErrnoError(44); + } + var newname = PATH.basename(newpath); + var errCode = FS.mayCreate(parent, newname); + if (errCode) { + throw new FS.ErrnoError(errCode); + } + // Hardlinks are only supported by filesystem backends that provide a + // `link` node op (e.g. NODERAWFS backed by the host). NODEFS omits it: + // a host hardlink cannot be confined to the mount root. + if (!parent.node_ops.link) { + throw new FS.ErrnoError(34); + } + return parent.node_ops.link(parent, newname, oldpath, flags); + }, + rename(old_path, new_path) { + var old_dirname = PATH.dirname(old_path); + var new_dirname = PATH.dirname(new_path); + var old_name = PATH.basename(old_path); + var new_name = PATH.basename(new_path); + // parents must exist + var lookup, old_dir, new_dir; + // let the errors from non existent directories percolate up + lookup = FS.lookupPath(old_path, { + parent: true + }); + old_dir = lookup.node; + lookup = FS.lookupPath(new_path, { + parent: true + }); + new_dir = lookup.node; + if (!old_dir || !new_dir) throw new FS.ErrnoError(44); + // need to be part of the same mount + if (old_dir.mount !== new_dir.mount) { + throw new FS.ErrnoError(75); + } + // source must exist + var old_node = FS.lookupNode(old_dir, old_name); + // old path should not be an ancestor of the new path + var relative = PATH_FS.relative(old_path, new_dirname); + if (relative.charAt(0) !== ".") { + throw new FS.ErrnoError(28); + } + // new path should not be an ancestor of the old path + relative = PATH_FS.relative(new_path, old_dirname); + if (relative.charAt(0) !== ".") { + throw new FS.ErrnoError(55); + } + // see if the new path already exists + var new_node; + try { + new_node = FS.lookupNode(new_dir, new_name); + } catch (e) {} + // early out if nothing needs to change + if (old_node === new_node) { + return; + } + // we'll need to delete the old entry + var isdir = FS.isDir(old_node.mode); + var errCode = FS.mayDelete(old_dir, old_name, isdir); + if (errCode) { + throw new FS.ErrnoError(errCode); + } + // need delete permissions if we'll be overwriting. + // need create permissions if new doesn't already exist. + errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name); + if (errCode) { + throw new FS.ErrnoError(errCode); + } + if (!old_dir.node_ops.rename) { + throw new FS.ErrnoError(63); + } + if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) { + throw new FS.ErrnoError(10); + } + // if we are going to change the parent, check write permissions + if (new_dir !== old_dir) { + errCode = FS.nodePermissions(old_dir, "w"); + if (errCode) { + throw new FS.ErrnoError(errCode); + } + } + // remove the node from the lookup hash + FS.hashRemoveNode(old_node); + // do the underlying fs rename + try { + old_dir.node_ops.rename(old_node, new_dir, new_name); + // update old node (we do this here to avoid each backend + // needing to) + old_node.parent = new_dir; + } catch (e) { + throw e; + } finally { + // add the node back to the hash (in case node_ops.rename + // changed its name) + FS.hashAddNode(old_node); + } + }, + rmdir(path) { + var lookup = FS.lookupPath(path, { + parent: true + }); + var parent = lookup.node; + var name = PATH.basename(path); + var node = FS.lookupNode(parent, name); + var errCode = FS.mayDelete(parent, name, true); + if (errCode) { + throw new FS.ErrnoError(errCode); + } + if (!parent.node_ops.rmdir) { + throw new FS.ErrnoError(63); + } + if (FS.isMountpoint(node)) { + throw new FS.ErrnoError(10); + } + parent.node_ops.rmdir(parent, name); + FS.destroyNode(node); + }, + readdir(path) { + var lookup = FS.lookupPath(path, { + follow: true + }); + var node = lookup.node; + var readdir = FS.checkOpExists(node.node_ops.readdir, 54); + return readdir(node); + }, + unlink(path) { + var lookup = FS.lookupPath(path, { + parent: true + }); + var parent = lookup.node; + if (!parent) { + throw new FS.ErrnoError(44); + } + var name = PATH.basename(path); + var node = FS.lookupNode(parent, name); + var errCode = FS.mayDelete(parent, name, false); + if (errCode) { + // According to POSIX, we should map EISDIR to EPERM, but + // we instead do what Linux does (and we must, as we use + // the musl linux libc). + throw new FS.ErrnoError(errCode); + } + if (!parent.node_ops.unlink) { + throw new FS.ErrnoError(63); + } + if (FS.isMountpoint(node)) { + throw new FS.ErrnoError(10); + } + parent.node_ops.unlink(parent, name); + FS.destroyNode(node); + }, + readlink(path) { + var lookup = FS.lookupPath(path); + var link = lookup.node; + if (!link) { + throw new FS.ErrnoError(44); + } + if (!link.node_ops.readlink) { + throw new FS.ErrnoError(28); + } + return link.node_ops.readlink(link); + }, + stat(path, dontFollow) { + var lookup = FS.lookupPath(path, { + follow: !dontFollow + }); + var node = lookup.node; + var getattr = FS.checkOpExists(node.node_ops.getattr, 63); + return getattr(node); + }, + fstat(fd) { + var stream = FS.getStreamChecked(fd); + var node = stream.node; + var getattr = stream.stream_ops.getattr; + var arg = getattr ? stream : node; + getattr ??= node.node_ops.getattr; + FS.checkOpExists(getattr, 63); + return getattr(arg); + }, + lstat(path) { + return FS.stat(path, true); + }, + doChmod(stream, node, mode, dontFollow) { + FS.doSetAttr(stream, node, { + mode: (mode & 4095) | (node.mode & ~4095), + ctime: Date.now(), + dontFollow + }); + }, + chmod(path, mode, dontFollow) { + var node; + if (typeof path == "string") { + var lookup = FS.lookupPath(path, { + follow: !dontFollow + }); + node = lookup.node; + } else { + node = path; + } + FS.doChmod(null, node, mode, dontFollow); + }, + lchmod(path, mode) { + FS.chmod(path, mode, true); + }, + fchmod(fd, mode) { + var stream = FS.getStreamChecked(fd); + FS.doChmod(stream, stream.node, mode, false); + }, + doChown(stream, node, dontFollow) { + FS.doSetAttr(stream, node, { + timestamp: Date.now(), + dontFollow + }); + }, + chown(path, uid, gid, dontFollow) { + var node; + if (typeof path == "string") { + var lookup = FS.lookupPath(path, { + follow: !dontFollow + }); + node = lookup.node; + } else { + node = path; + } + FS.doChown(null, node, dontFollow); + }, + lchown(path, uid, gid) { + FS.chown(path, uid, gid, true); + }, + fchown(fd, uid, gid) { + var stream = FS.getStreamChecked(fd); + FS.doChown(stream, stream.node, false); + }, + doTruncate(stream, node, len) { + if (FS.isDir(node.mode)) { + throw new FS.ErrnoError(31); + } + if (!FS.isFile(node.mode)) { + throw new FS.ErrnoError(28); + } + var errCode = FS.nodePermissions(node, "w"); + if (errCode) { + throw new FS.ErrnoError(errCode); + } + FS.doSetAttr(stream, node, { + size: len, + timestamp: Date.now() + }); + }, + truncate(path, len) { + if (len < 0) { + throw new FS.ErrnoError(28); + } + var node; + if (typeof path == "string") { + var lookup = FS.lookupPath(path, { + follow: true + }); + node = lookup.node; + } else { + node = path; + } + FS.doTruncate(null, node, len); + }, + ftruncate(fd, len) { + var stream = FS.getStreamChecked(fd); + if (len < 0 || (stream.flags & 2097155) === 0) { + throw new FS.ErrnoError(28); + } + FS.doTruncate(stream, stream.node, len); + }, + utime(path, atime, mtime, dontFollow) { + var lookup = FS.lookupPath(path, { + follow: !dontFollow + }); + FS.doSetAttr(null, lookup.node, { + atime, + mtime, + dontFollow + }); + }, + open(path, flags, mode = 438) { + if (path === "") { + throw new FS.ErrnoError(44); + } + flags = FS_modeStringToFlags(flags); + if ((flags & 64)) { + mode = (mode & 4095) | 32768; + } else { + mode = 0; + } + var node; + var isDirPath; + if (typeof path == "object") { + node = path; + } else { + isDirPath = path.endsWith("/"); + // noent_okay makes it so that if the final component of the path + // doesn't exist, lookupPath returns `node: undefined`. `path` will be + // updated to point to the target of all symlinks. + var lookup = FS.lookupPath(path, { + follow: !(flags & 131072), + noent_okay: true + }); + node = lookup.node; + path = lookup.path; + } + // perhaps we need to create the node + var created = false; + if ((flags & 64)) { + if (node) { + // if O_CREAT and O_EXCL are set, error out if the node already exists + if ((flags & 128)) { + throw new FS.ErrnoError(20); + } + } else if (isDirPath) { + throw new FS.ErrnoError(31); + } else { + // node doesn't exist, try to create it + // Ignore the permission bits here to ensure we can `open` this new + // file below. We use chmod below to apply the permissions once the + // file is open. + node = FS.mknod(path, mode | 511, 0); + created = true; + } + } + if (!node) { + throw new FS.ErrnoError(44); + } + // can't truncate a device + if (FS.isChrdev(node.mode)) { + flags &= ~512; + } + // if asked only for a directory, then this must be one + if ((flags & 65536) && !FS.isDir(node.mode)) { + throw new FS.ErrnoError(54); + } + // check permissions, if this is not a file we just created now (it is ok to + // create and write to a file with read-only permissions; it is read-only + // for later use) + if (!created) { + var errCode = FS.mayOpen(node, flags); + if (errCode) { + throw new FS.ErrnoError(errCode); + } + } + // do truncation if necessary + if ((flags & 512) && !created) { + FS.truncate(node, 0); + } + // we've already handled these, don't pass down to the underlying vfs + flags &= ~(128 | 512 | 131072); + // register the stream with the filesystem + var stream = FS.createStream({ + node, + path: FS.getPath(node), + // we want the absolute path to the node + flags, + seekable: true, + position: 0, + stream_ops: node.stream_ops, + // used by the file family libc calls (fopen, fwrite, ferror, etc.) + ungotten: [], + error: false + }); + // call the new stream's open function + if (stream.stream_ops.open) { + stream.stream_ops.open(stream); + } + if (created) { + FS.chmod(node, mode & 511); + } + return stream; + }, + close(stream) { + if (FS.isClosed(stream)) { + throw new FS.ErrnoError(8); + } + if (stream.getdents) stream.getdents = null; + // free readdir state + // The fd is going away: wake anything waiting on it (poll/epoll) with + // POLLNVAL so a blocking wait unblocks and an epoll registration is evicted + // on its next derive. Only sockets/pipes/epoll ever carry a wait-queue, so + // for every other stream (incl. nodeless noderawfs stdio) this is a no-op. + stream.node?.notifyListeners(32); + try { + if (stream.stream_ops.close) { + stream.stream_ops.close(stream); + } + } catch (e) { + throw e; + } finally { + FS.closeStream(stream.fd); + } + stream.fd = null; + }, + isClosed(stream) { + return stream.fd === null; + }, + llseek(stream, offset, whence) { + if (FS.isClosed(stream)) { + throw new FS.ErrnoError(8); + } + if (!stream.seekable || !stream.stream_ops.llseek) { + throw new FS.ErrnoError(70); + } + if (whence != 0 && whence != 1 && whence != 2) { + throw new FS.ErrnoError(28); + } + stream.position = stream.stream_ops.llseek(stream, offset, whence); + stream.ungotten = []; + return stream.position; + }, + read(stream, buffer, offset, length, position) { + if (length < 0 || position < 0) { + throw new FS.ErrnoError(28); + } + if (FS.isClosed(stream)) { + throw new FS.ErrnoError(8); + } + if ((stream.flags & 2097155) === 1) { + throw new FS.ErrnoError(8); + } + if (FS.isDir(stream.node.mode)) { + throw new FS.ErrnoError(31); + } + if (!stream.stream_ops.read) { + throw new FS.ErrnoError(28); + } + var seeking = typeof position != "undefined"; + if (!seeking) { + position = stream.position; + } else if (!stream.seekable) { + throw new FS.ErrnoError(70); + } + var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position); + if (!seeking) stream.position += bytesRead; + return bytesRead; + }, + write(stream, buffer, offset, length, position, canOwn) { + if (length < 0 || position < 0) { + throw new FS.ErrnoError(28); + } + if (FS.isClosed(stream)) { + throw new FS.ErrnoError(8); + } + if ((stream.flags & 2097155) === 0) { + throw new FS.ErrnoError(8); + } + if (FS.isDir(stream.node.mode)) { + throw new FS.ErrnoError(31); + } + if (!stream.stream_ops.write) { + throw new FS.ErrnoError(28); + } + if (stream.seekable && stream.flags & 1024) { + // seek to the end before writing in append mode + FS.llseek(stream, 0, 2); + } + var seeking = typeof position != "undefined"; + if (!seeking) { + position = stream.position; + } else if (!stream.seekable) { + throw new FS.ErrnoError(70); + } + var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn); + if (!seeking) stream.position += bytesWritten; + return bytesWritten; + }, + mmap(stream, length, position, prot, flags) { + // User requests writing to file (prot & PROT_WRITE != 0). + // Checking if we have permissions to write to the file unless + // MAP_PRIVATE flag is set. According to POSIX spec it is possible + // to write to file opened in read-only mode with MAP_PRIVATE flag, + // as all modifications will be visible only in the memory of + // the current process. + if ((prot & 2) && !(flags & 2) && (stream.flags & 2097155) !== 2) { + throw new FS.ErrnoError(2); + } + if ((stream.flags & 2097155) === 1) { + throw new FS.ErrnoError(2); + } + if (!stream.stream_ops.mmap) { + throw new FS.ErrnoError(43); + } + if (!length) { + throw new FS.ErrnoError(28); + } + return stream.stream_ops.mmap(stream, length, position, prot, flags); + }, + msync(stream, buffer, offset, length, mmapFlags) { + if (!stream.stream_ops.msync) { + return 0; + } + return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags); + }, + ioctl(stream, cmd, arg) { + if (!stream.stream_ops.ioctl) { + throw new FS.ErrnoError(59); + } + return stream.stream_ops.ioctl(stream, cmd, arg); + }, + readFile(path, opts = {}) { + opts.flags = opts.flags ?? 0; + opts.encoding = opts.encoding ?? "binary"; + if (opts.encoding !== "utf8" && opts.encoding !== "binary") { + abort(`Invalid encoding type "${opts.encoding}"`); + } + var stream = FS.open(path, opts.flags); + var stat = FS.stat(path); + var length = stat.size; + var buf = new Uint8Array(length); + FS.read(stream, buf, 0, length, 0); + if (opts.encoding === "utf8") { + buf = UTF8ArrayToString(buf); + } + FS.close(stream); + return buf; + }, + writeFile(path, data, opts = {}) { + opts.flags = opts.flags ?? 577; + var stream = FS.open(path, opts.flags, opts.mode); + data = FS_fileDataToTypedArray(data); + FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn); + FS.close(stream); + }, + cwd: () => FS.currentPath, + chdir(path) { + var lookup = FS.lookupPath(path, { + follow: true + }); + if (lookup.node === null) { + throw new FS.ErrnoError(44); + } + if (!FS.isDir(lookup.node.mode)) { + throw new FS.ErrnoError(54); + } + var errCode = FS.nodePermissions(lookup.node, "x"); + if (errCode) { + throw new FS.ErrnoError(errCode); + } + FS.currentPath = lookup.path; + }, + createDefaultDirectories() { + FS.mkdir("/tmp"); + FS.mkdir("/home"); + FS.mkdir("/home/web_user"); + }, + createDefaultDevices() { + // create /dev + FS.mkdir("/dev"); + // setup /dev/null + FS.registerDevice(FS.makedev(1, 3), { + read: () => 0, + write: (stream, buffer, offset, length, pos) => length, + llseek: () => 0 + }); + FS.mkdev("/dev/null", FS.makedev(1, 3)); + // setup /dev/tty and /dev/tty1 + // stderr needs to print output using err() rather than out() + // so we register a second tty just for it. + TTY.register(FS.makedev(5, 0), TTY.default_tty_ops); + TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops); + FS.mkdev("/dev/tty", FS.makedev(5, 0)); + FS.mkdev("/dev/tty1", FS.makedev(6, 0)); + // setup /dev/[u]random + // use a buffer to avoid overhead of individual crypto calls per byte + var randomBuffer = new Uint8Array(1024), randomLeft = 0; + var randomByte = () => { + if (!randomLeft) { + randomFill(randomBuffer); + randomLeft = randomBuffer.byteLength; + } + return randomBuffer[--randomLeft]; + }; + FS.createDevice("/dev", "random", randomByte); + FS.createDevice("/dev", "urandom", randomByte); + // we're not going to emulate the actual shm device, + // just create the tmp dirs that reside in it commonly + FS.mkdir("/dev/shm"); + FS.mkdir("/dev/shm/tmp"); + }, + createSpecialDirectories() { + // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the + // name of the stream for fd 6 (see test_unistd_ttyname) + FS.mkdir("/proc"); + var proc_self = FS.mkdir("/proc/self"); + FS.mkdir("/proc/self/fd"); + FS.mount({ + mount() { + var node = FS.createNode(proc_self, "fd", 16895, 73); + node.stream_ops = { + llseek: MEMFS.stream_ops.llseek + }; + node.node_ops = { + lookup(parent, name) { + var fd = +name; + var stream = FS.getStreamChecked(fd); + var ret = { + parent: null, + mount: { + mountpoint: "fake" + }, + node_ops: { + readlink: () => stream.path + }, + id: fd + 1 + }; + ret.parent = ret; + // make it look like a simple root node + return ret; + }, + readdir() { + return Array.from(FS.streams.entries()).filter(([k, v]) => v).map(([k, v]) => k.toString()); + } + }; + return node; + } + }, {}, "/proc/self/fd"); + }, + createStandardStreams(input, output, error) { + // TODO deprecate the old functionality of a single + // input / output callback and that utilizes FS.createDevice + // and instead require a unique set of stream ops + // by default, we symlink the standard streams to the + // default tty devices. however, if the standard streams + // have been overwritten we create a unique device for + // them instead. + if (input) { + FS.createDevice("/dev", "stdin", input); + } else { + FS.symlink("/dev/tty", "/dev/stdin"); + } + if (output) { + FS.createDevice("/dev", "stdout", null, output); + } else { + FS.symlink("/dev/tty", "/dev/stdout"); + } + if (error) { + FS.createDevice("/dev", "stderr", null, error); + } else { + FS.symlink("/dev/tty1", "/dev/stderr"); + } + // open default streams for the stdin, stdout and stderr devices + var stdin = FS.open("/dev/stdin", 0); + var stdout = FS.open("/dev/stdout", 1); + var stderr = FS.open("/dev/stderr", 1); + }, + staticInit() { + FS.nameTable = new Array(4096); + FS.mount(MEMFS, {}, "/"); + FS.createDefaultDirectories(); + FS.createDefaultDevices(); + FS.createSpecialDirectories(); + FS.filesystems = { + "MEMFS": MEMFS + }; + }, + init(input, output, error) { + FS.initialized = true; + // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here + input ??= Module["stdin"]; + output ??= Module["stdout"]; + error ??= Module["stderr"]; + FS.createStandardStreams(input, output, error); + }, + quit() { + FS.initialized = false; + // force-flush all streams, so we get musl std streams printed out + // close all of our streams + for (var stream of FS.streams) { + if (stream) { + FS.close(stream); + } + } + }, + findObject(path, dontResolveLastLink) { + var ret = FS.analyzePath(path, dontResolveLastLink); + if (!ret.exists) { + return null; + } + return ret.object; + }, + analyzePath(path, dontResolveLastLink) { + // operate from within the context of the symlink's target + try { + var lookup = FS.lookupPath(path, { + follow: !dontResolveLastLink + }); + path = lookup.path; + } catch (e) {} + var ret = { + isRoot: false, + exists: false, + error: 0, + name: null, + path: null, + object: null, + parentExists: false, + parentPath: null, + parentObject: null + }; + try { + var lookup = FS.lookupPath(path, { + parent: true + }); + ret.parentExists = true; + ret.parentPath = lookup.path; + ret.parentObject = lookup.node; + ret.name = PATH.basename(path); + lookup = FS.lookupPath(path, { + follow: !dontResolveLastLink + }); + ret.exists = true; + ret.path = lookup.path; + ret.object = lookup.node; + ret.name = lookup.node.name; + ret.isRoot = lookup.path === "/"; + } catch (e) { + ret.error = e.errno; + } + return ret; + }, + createPath(parent, path, canRead, canWrite) { + parent = typeof parent == "string" ? parent : FS.getPath(parent); + var parts = path.split("/").reverse(); + while (parts.length) { + var part = parts.pop(); + if (!part) continue; + var current = PATH.join2(parent, part); + try { + FS.mkdir(current); + } catch (e) { + if (e.errno != 20) throw e; + } + parent = current; + } + return current; + }, + createFile(parent, name, properties, canRead, canWrite) { + var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name); + var mode = FS_getMode(canRead, canWrite); + return FS.create(path, mode); + }, + createDataFile(parent, name, data, canRead, canWrite, canOwn) { + var path = name; + if (parent) { + parent = typeof parent == "string" ? parent : FS.getPath(parent); + path = name ? PATH.join2(parent, name) : parent; + } + var mode = FS_getMode(canRead, canWrite); + var node = FS.create(path, mode); + if (data) { + data = FS_fileDataToTypedArray(data); + // make sure we can write to the file + FS.chmod(node, mode | 146); + var stream = FS.open(node, 577); + FS.write(stream, data, 0, data.length, 0, canOwn); + FS.close(stream); + FS.chmod(node, mode); + } + }, + createDevice(parent, name, input, output) { + var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name); + var mode = FS_getMode(!!input, !!output); + FS.createDevice.major ??= 64; + var dev = FS.makedev(FS.createDevice.major++, 0); + // Create a fake device that a set of stream ops to emulate + // the old behavior. + FS.registerDevice(dev, { + open(stream) { + stream.seekable = false; + }, + close(stream) { + // flush any pending line data + if (output?.buffer?.length) { + output(10); + } + }, + read(stream, buffer, offset, length, pos) { + var bytesRead = 0; + for (var i = 0; i < length; i++) { + var result; + try { + result = input(); + } catch (e) { + throw new FS.ErrnoError(29); + } + if (result === undefined && !bytesRead) { + throw new FS.ErrnoError(6); + } + if (result === null || result === undefined) break; + bytesRead++; + buffer[offset + i] = result; + } + if (bytesRead) { + stream.node.atime = Date.now(); + } + return bytesRead; + }, + write(stream, buffer, offset, length, pos) { + for (var i = 0; i < length; i++) { + try { + output(buffer[offset + i]); + } catch (e) { + throw new FS.ErrnoError(29); + } + } + if (length) { + stream.node.mtime = stream.node.ctime = Date.now(); + } + return i; + } + }); + return FS.mkdev(path, mode, dev); + }, + forceLoadFile(obj) { + if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true; + if (globalThis.XMLHttpRequest) { + abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread."); + } else { + // Command-line. + try { + obj.contents = readBinary(obj.url); + } catch (e) { + throw new FS.ErrnoError(29); + } + } + }, + createLazyFile(parent, name, url, canRead, canWrite) { + // Lazy chunked Uint8Array (implements get and length from Uint8Array). + // Actual getting is abstracted away for eventual reuse. + class LazyUint8Array { + lengthKnown=false; + chunks=[]; + // Loaded chunks. Index is the chunk number + get(idx) { + if (idx > this.length - 1 || idx < 0) { + return undefined; + } + var chunkOffset = idx % this.chunkSize; + var chunkNum = (idx / this.chunkSize) | 0; + return this.getter(chunkNum)[chunkOffset]; + } + setDataGetter(getter) { + this.getter = getter; + } + cacheLength() { + // Find length + var xhr = new XMLHttpRequest; + xhr.open("HEAD", url, false); + xhr.send(null); + if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort(`Couldn't load ${url}. Status: ${xhr.status}`); + var datalength = Number(xhr.getResponseHeader("Content-length")); + var header; + var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes"; + var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip"; + var chunkSize = 1024 * 1024; + // Chunk size in bytes + if (!hasByteServing) chunkSize = datalength; + // Function to get a range from the remote URL. + var doXHR = (from, to) => { + if (from > to) abort(`invalid range (${from}, ${to}) or no bytes requested!`); + if (to > datalength - 1) abort(`only ${datalength} bytes available! programmer error!`); + // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available. + var xhr = new XMLHttpRequest; + xhr.open("GET", url, false); + if (datalength !== chunkSize) xhr.setRequestHeader("Range", `bytes=${from}-${to}`); + // Some hints to the browser that we want binary data. + xhr.responseType = "arraybuffer"; + if (xhr.overrideMimeType) { + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + } + xhr.send(null); + if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort(`Couldn't load ${url}. Status: ${xhr.status}`); + if (xhr.response !== undefined) { + return new Uint8Array(/** @type{Array} */ (xhr.response || [])); + } + return intArrayFromString(xhr.responseText ?? "", true); + }; + var lazyArray = this; + lazyArray.setDataGetter(chunkNum => { + var start = chunkNum * chunkSize; + var end = (chunkNum + 1) * chunkSize - 1; + // including this byte + end = Math.min(end, datalength - 1); + // if datalength-1 is selected, this is the last block + if (typeof lazyArray.chunks[chunkNum] == "undefined") { + lazyArray.chunks[chunkNum] = doXHR(start, end); + } + if (typeof lazyArray.chunks[chunkNum] == "undefined") abort("doXHR failed!"); + return lazyArray.chunks[chunkNum]; + }); + if (usesGzip || !datalength) { + // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length + chunkSize = datalength = 1; + // this will force getter(0)/doXHR do download the whole file + datalength = this.getter(0).length; + chunkSize = datalength; + out("LazyFiles on gzip forces download of the whole file when length is accessed"); + } + this._length = datalength; + this._chunkSize = chunkSize; + this.lengthKnown = true; + } + get length() { + if (!this.lengthKnown) { + this.cacheLength(); + } + return this._length; + } + get chunkSize() { + if (!this.lengthKnown) { + this.cacheLength(); + } + return this._chunkSize; + } + } + if (globalThis.XMLHttpRequest) { + if (!ENVIRONMENT_IS_WORKER) abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc"); + var lazyArray = new LazyUint8Array; + var properties = { + isDevice: false, + contents: lazyArray + }; + } else { + var properties = { + isDevice: false, + url + }; + } + var node = FS.createFile(parent, name, properties, canRead, canWrite); + // This is a total hack, but I want to get this lazy file code out of the + // core of MEMFS. If we want to keep this lazy file concept I feel it should + // be its own thin LAZYFS proxying calls to MEMFS. + if (properties.contents) { + node.contents = properties.contents; + } else if (properties.url) { + node.contents = null; + node.url = properties.url; + } + // Add a function that defers querying the file size until it is asked the first time. + Object.defineProperties(node, { + usedBytes: { + get: function() { + return this.contents.length; + } + } + }); + // override each stream op with one that tries to force load the lazy file first + var stream_ops = {}; + for (const [key, fn] of Object.entries(node.stream_ops)) { + stream_ops[key] = (...args) => { + FS.forceLoadFile(node); + return fn(...args); + }; + } + function writeChunks(stream, buffer, offset, length, position) { + var contents = stream.node.contents; + if (position >= contents.length) return 0; + var size = Math.min(contents.length - position, length); + if (contents.slice) { + // normal array + for (var i = 0; i < size; i++) { + buffer[offset + i] = contents[position + i]; + } + } else { + for (var i = 0; i < size; i++) { + // LazyUint8Array from sync binary XHR + buffer[offset + i] = contents.get(position + i); + } + } + return size; + } + // use a custom read function + stream_ops.read = (stream, buffer, offset, length, position) => { + FS.forceLoadFile(node); + return writeChunks(stream, buffer, offset, length, position); + }; + // use a custom mmap function + stream_ops.mmap = (stream, length, position, prot, flags) => { + FS.forceLoadFile(node); + var ptr = mmapAlloc(length); + if (!ptr) { + throw new FS.ErrnoError(48); + } + writeChunks(stream, HEAP8, ptr, length, position); + return { + ptr, + allocated: true + }; + }; + node.stream_ops = stream_ops; + return node; + } +}; + +/** + * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the + * emscripten HEAP, returns a copy of that string as a Javascript String object. + * + * @param {number} ptr + * @param {number=} maxBytesToRead - An optional length that specifies the + * maximum number of bytes to read. You can omit this parameter to scan the + * string until the first 0 byte. If maxBytesToRead is passed, and the string + * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the + * string will cut short at that byte index. + * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character. + * @return {string} + */ var UTF8ToString = (ptr, maxBytesToRead, ignoreNul) => { + if (!ptr) return ""; + var end = findStringEnd(HEAPU8, ptr, maxBytesToRead, ignoreNul); + return UTF8Decoder.decode(HEAPU8.subarray(ptr, end)); +}; + +var SYSCALLS = { + currentUmask: 18, + calculateAt(dirfd, path, allowEmpty) { + if (PATH.isAbs(path)) { + return path; + } + // relative path + var dir; + if (dirfd === -100) { + dir = FS.cwd(); + } else { + var dirstream = SYSCALLS.getStreamFromFD(dirfd); + dir = dirstream.path; + } + if (path.length == 0) { + if (!allowEmpty) { + throw new FS.ErrnoError(44); + } + return dir; + } + return dir + "/" + path; + }, + writeStat(buf, stat) { + HEAPU32[((buf) >> 2)] = stat.dev; + HEAPU32[(((buf) + (4)) >> 2)] = stat.mode; + HEAPU32[(((buf) + (8)) >> 2)] = stat.nlink; + HEAPU32[(((buf) + (12)) >> 2)] = stat.uid; + HEAPU32[(((buf) + (16)) >> 2)] = stat.gid; + HEAPU32[(((buf) + (20)) >> 2)] = stat.rdev; + (tempI64 = [ stat.size >>> 0, (tempDouble = stat.size, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[(((buf) + (24)) >> 2)] = tempI64[0], HEAP32[(((buf) + (28)) >> 2)] = tempI64[1]); + HEAP32[(((buf) + (32)) >> 2)] = 4096; + HEAP32[(((buf) + (36)) >> 2)] = stat.blocks; + var atime = stat.atime.getTime(); + var mtime = stat.mtime.getTime(); + var ctime = stat.ctime.getTime(); + (tempI64 = [ Math.floor(atime / 1e3) >>> 0, (tempDouble = Math.floor(atime / 1e3), + (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[(((buf) + (40)) >> 2)] = tempI64[0], HEAP32[(((buf) + (44)) >> 2)] = tempI64[1]); + HEAPU32[(((buf) + (48)) >> 2)] = (atime % 1e3) * 1e3 * 1e3; + (tempI64 = [ Math.floor(mtime / 1e3) >>> 0, (tempDouble = Math.floor(mtime / 1e3), + (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[(((buf) + (56)) >> 2)] = tempI64[0], HEAP32[(((buf) + (60)) >> 2)] = tempI64[1]); + HEAPU32[(((buf) + (64)) >> 2)] = (mtime % 1e3) * 1e3 * 1e3; + (tempI64 = [ Math.floor(ctime / 1e3) >>> 0, (tempDouble = Math.floor(ctime / 1e3), + (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[(((buf) + (72)) >> 2)] = tempI64[0], HEAP32[(((buf) + (76)) >> 2)] = tempI64[1]); + HEAPU32[(((buf) + (80)) >> 2)] = (ctime % 1e3) * 1e3 * 1e3; + (tempI64 = [ stat.ino >>> 0, (tempDouble = stat.ino, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[(((buf) + (88)) >> 2)] = tempI64[0], HEAP32[(((buf) + (92)) >> 2)] = tempI64[1]); + return 0; + }, + writeStatFs(buf, stats) { + HEAPU32[(((buf) + (4)) >> 2)] = stats.bsize; + HEAPU32[(((buf) + (60)) >> 2)] = stats.bsize; + (tempI64 = [ stats.blocks >>> 0, (tempDouble = stats.blocks, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[(((buf) + (8)) >> 2)] = tempI64[0], HEAP32[(((buf) + (12)) >> 2)] = tempI64[1]); + (tempI64 = [ stats.bfree >>> 0, (tempDouble = stats.bfree, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[(((buf) + (16)) >> 2)] = tempI64[0], HEAP32[(((buf) + (20)) >> 2)] = tempI64[1]); + (tempI64 = [ stats.bavail >>> 0, (tempDouble = stats.bavail, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[(((buf) + (24)) >> 2)] = tempI64[0], HEAP32[(((buf) + (28)) >> 2)] = tempI64[1]); + (tempI64 = [ stats.files >>> 0, (tempDouble = stats.files, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[(((buf) + (32)) >> 2)] = tempI64[0], HEAP32[(((buf) + (36)) >> 2)] = tempI64[1]); + (tempI64 = [ stats.ffree >>> 0, (tempDouble = stats.ffree, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[(((buf) + (40)) >> 2)] = tempI64[0], HEAP32[(((buf) + (44)) >> 2)] = tempI64[1]); + HEAPU32[(((buf) + (48)) >> 2)] = stats.fsid; + HEAPU32[(((buf) + (64)) >> 2)] = stats.flags; + // ST_NOSUID + HEAPU32[(((buf) + (56)) >> 2)] = stats.namelen; + }, + doMsync(addr, stream, len, flags, offset) { + if (!FS.isFile(stream.node.mode)) { + throw new FS.ErrnoError(43); + } + if (flags & 2) { + // MAP_PRIVATE calls need not to be synced back to underlying fs + return 0; + } + var buffer = HEAPU8.subarray(addr, addr + len); + FS.msync(stream, buffer, offset, len, flags); + }, + getStreamFromFD(fd) { + var stream = FS.getStreamChecked(fd); + return stream; + }, + varargs: undefined, + getStr(ptr) { + var ret = UTF8ToString(ptr); + return ret; + } +}; + +function ___syscall_dup(fd) { + try { + var old = SYSCALLS.getStreamFromFD(fd); + return FS.dupStream(old).fd; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function ___syscall_faccessat(dirfd, path, amode, flags) { + try { + path = SYSCALLS.getStr(path); + path = SYSCALLS.calculateAt(dirfd, path); + if (amode & ~7) { + // need a valid mode + return -28; + } + var lookup = FS.lookupPath(path, { + follow: true + }); + var node = lookup.node; + if (!node) { + return -44; + } + var perms = ""; + if (amode & 4) perms += "r"; + if (amode & 2) perms += "w"; + if (amode & 1) perms += "x"; + if (perms && FS.nodePermissions(node, perms)) { + return -2; + } + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +var syscallGetVarargI = () => { + // the `+` prepended here is necessary to convince the JSCompiler that varargs is indeed a number. + var ret = HEAP32[((+SYSCALLS.varargs) >> 2)]; + SYSCALLS.varargs += 4; + return ret; +}; + +var syscallGetVarargP = syscallGetVarargI; + +/** @type {!Int16Array} */ var HEAP16; + +function ___syscall_fcntl64(fd, cmd, varargs) { + SYSCALLS.varargs = varargs; + try { + var stream = SYSCALLS.getStreamFromFD(fd); + switch (cmd) { + case 0: + { + var arg = syscallGetVarargI(); + if (arg < 0) { + return -28; + } + while (FS.streams[arg]) { + arg++; + } + var newStream; + newStream = FS.dupStream(stream, arg); + return newStream.fd; + } + + case 1: + case 2: + return 0; + + // FD_CLOEXEC makes no sense for a single process. + case 3: + return stream.flags; + + case 4: + { + var arg = syscallGetVarargI(); + var mask = 289792; + stream.flags = (stream.flags & ~mask) | (arg & mask); + return 0; + } + + case 12: + { + var arg = syscallGetVarargP(); + var offset = 0; + // We're always unlocked. + HEAP16[(((arg) + (offset)) >> 1)] = 2; + return 0; + } + + case 13: + case 14: + // Pretend that the locking is successful. These are process-level locks, + // and Emscripten programs are a single process. If we supported linking a + // filesystem between programs, we'd need to do more here. + // See https://github.com/emscripten-core/emscripten/issues/23697 + return 0; + } + return -28; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function ___syscall_fstat64(fd, buf) { + try { + return SYSCALLS.writeStat(buf, FS.fstat(fd)); + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +var convertI32PairToI53Checked = (lo, hi) => ((hi + 2097152) >>> 0 < 4194305 - !!lo) ? (lo >>> 0) + hi * 4294967296 : NaN; + +function ___syscall_ftruncate64(fd, length_low, length_high) { + var length = convertI32PairToI53Checked(length_low, length_high); + try { + if (isNaN(length)) return -22; + FS.ftruncate(fd, length); + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +var stringToUTF8 = (str, outPtr, maxBytesToWrite) => stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite); + +function ___syscall_getcwd(buf, size) { + try { + if (!size) return -28; + var cwd = FS.cwd(); + var cwdLengthInBytes = lengthBytesUTF8(cwd) + 1; + if (size < cwdLengthInBytes) return -68; + stringToUTF8(cwd, buf, size); + return cwdLengthInBytes; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function ___syscall_getdents64(fd, dirp, count) { + try { + var stream = SYSCALLS.getStreamFromFD(fd); + stream.getdents ||= FS.readdir(stream.path); + var struct_size = 280; + var pos = 0; + var off = FS.llseek(stream, 0, 1); + var startIdx = Math.floor(off / struct_size); + var endIdx = Math.min(stream.getdents.length, startIdx + Math.floor(count / struct_size)); + for (var idx = startIdx; idx < endIdx; idx++) { + var id; + var type; + var name = stream.getdents[idx]; + if (name === ".") { + id = stream.node.id; + type = 4; + } else if (name === "..") { + var lookup = FS.lookupPath(stream.path, { + parent: true + }); + id = lookup.node.id; + type = 4; + } else { + var child; + try { + child = FS.lookupNode(stream.node, name); + } catch (e) { + // If the entry is not a directory, file, or symlink, nodefs + // lookupNode will raise EINVAL. Skip these and continue. + if (e?.errno === 28) { + continue; + } + throw e; + } + id = child.id; + type = FS.isChrdev(child.mode) ? 2 : // character device. + FS.isDir(child.mode) ? 4 : // directory + FS.isLink(child.mode) ? 10 : // symbolic link. + 8; + } + (tempI64 = [ id >>> 0, (tempDouble = id, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[((dirp + pos) >> 2)] = tempI64[0], HEAP32[(((dirp + pos) + (4)) >> 2)] = tempI64[1]); + (tempI64 = [ (idx + 1) * struct_size >>> 0, (tempDouble = (idx + 1) * struct_size, + (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[(((dirp + pos) + (8)) >> 2)] = tempI64[0], HEAP32[(((dirp + pos) + (12)) >> 2)] = tempI64[1]); + HEAP16[(((dirp + pos) + (16)) >> 1)] = 280; + HEAP8[(dirp + pos) + (18)] = type; + stringToUTF8(name, dirp + pos + 19, 256); + pos += struct_size; + } + FS.llseek(stream, idx * struct_size, 0); + return pos; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +var ___syscall_getuid32 = () => 0; + +function ___syscall_ioctl(fd, op, varargs) { + SYSCALLS.varargs = varargs; + try { + var stream = SYSCALLS.getStreamFromFD(fd); + switch (op) { + case 21509: + { + if (!stream.tty) return -59; + return 0; + } + + case 21505: + { + if (!stream.tty) return -59; + if (stream.tty.ops.ioctl_tcgets) { + var termios = stream.tty.ops.ioctl_tcgets(stream); + var argp = syscallGetVarargP(); + HEAP32[((argp) >> 2)] = termios.c_iflag || 0; + HEAP32[(((argp) + (4)) >> 2)] = termios.c_oflag || 0; + HEAP32[(((argp) + (8)) >> 2)] = termios.c_cflag || 0; + HEAP32[(((argp) + (12)) >> 2)] = termios.c_lflag || 0; + for (var i = 0; i < 32; i++) { + HEAP8[(argp + i) + (17)] = termios.c_cc[i] || 0; + } + return 0; + } + return 0; + } + + case 21510: + case 21511: + case 21512: + { + if (!stream.tty) return -59; + return 0; + } + + case 21506: + case 21507: + case 21508: + { + if (!stream.tty) return -59; + if (stream.tty.ops.ioctl_tcsets) { + var argp = syscallGetVarargP(); + var c_iflag = HEAP32[((argp) >> 2)]; + var c_oflag = HEAP32[(((argp) + (4)) >> 2)]; + var c_cflag = HEAP32[(((argp) + (8)) >> 2)]; + var c_lflag = HEAP32[(((argp) + (12)) >> 2)]; + var c_cc = []; + for (var i = 0; i < 32; i++) { + c_cc.push(HEAP8[(argp + i) + (17)]); + } + return stream.tty.ops.ioctl_tcsets(stream.tty, op, { + c_iflag, + c_oflag, + c_cflag, + c_lflag, + c_cc + }); + } + return 0; + } + + case 21519: + { + if (!stream.tty) return -59; + var argp = syscallGetVarargP(); + HEAP32[((argp) >> 2)] = 0; + return 0; + } + + case 21520: + { + if (!stream.tty) return -59; + return -28; + } + + case 21537: + case 21531: + { + var argp = syscallGetVarargP(); + return FS.ioctl(stream, op, argp); + } + + case 21523: + { + // TODO: in theory we should write to the winsize struct that gets + // passed in, but for now musl doesn't read anything on it + if (!stream.tty) return -59; + if (stream.tty.ops.ioctl_tiocgwinsz) { + var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty); + var argp = syscallGetVarargP(); + HEAP16[((argp) >> 1)] = winsize[0]; + HEAP16[(((argp) + (2)) >> 1)] = winsize[1]; + } + return 0; + } + + case 21524: + { + // TODO: technically, this ioctl call should change the window size. + // but, since emscripten doesn't have any concept of a terminal window + // yet, we'll just silently throw it away as we do TIOCGWINSZ + if (!stream.tty) return -59; + return 0; + } + + case 21515: + { + if (!stream.tty) return -59; + return 0; + } + + default: + return -28; + } + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function ___syscall_lstat64(path, buf) { + try { + path = SYSCALLS.getStr(path); + return SYSCALLS.writeStat(buf, FS.lstat(path)); + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function ___syscall_mkdirat(dirfd, path, mode) { + try { + path = SYSCALLS.getStr(path); + path = SYSCALLS.calculateAt(dirfd, path); + mode &= ~SYSCALLS.currentUmask; + FS.mkdir(path, mode, 0); + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function ___syscall_newfstatat(dirfd, path, buf, flags) { + try { + path = SYSCALLS.getStr(path); + var nofollow = flags & 256; + var allowEmpty = flags & 4096; + flags = flags & (~6400); + path = SYSCALLS.calculateAt(dirfd, path, allowEmpty); + return SYSCALLS.writeStat(buf, nofollow ? FS.lstat(path) : FS.stat(path)); + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function ___syscall_openat(dirfd, path, flags, varargs) { + SYSCALLS.varargs = varargs; + try { + path = SYSCALLS.getStr(path); + path = SYSCALLS.calculateAt(dirfd, path); + var mode = varargs ? syscallGetVarargI() : 0; + if (flags & 64) { + mode &= ~SYSCALLS.currentUmask; + } + return FS.open(path, flags, mode).fd; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function ___syscall_readlinkat(dirfd, path, buf, bufsize) { + try { + path = SYSCALLS.getStr(path); + path = SYSCALLS.calculateAt(dirfd, path); + if (bufsize <= 0) return -28; + var ret = FS.readlink(path); + var len = Math.min(bufsize, lengthBytesUTF8(ret)); + var endChar = HEAP8[buf + len]; + stringToUTF8(ret, buf, bufsize + 1); + // readlink is one of the rare functions that write out a C string, but does never append a null to the output buffer(!) + // stringToUTF8() always appends a null byte, so restore the character under the null byte after the write. + HEAP8[buf + len] = endChar; + return len; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function ___syscall_rmdir(path) { + try { + path = SYSCALLS.getStr(path); + FS.rmdir(path); + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function ___syscall_stat64(path, buf) { + try { + path = SYSCALLS.getStr(path); + return SYSCALLS.writeStat(buf, FS.stat(path)); + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function ___syscall_unlinkat(dirfd, path, flags) { + try { + path = SYSCALLS.getStr(path); + path = SYSCALLS.calculateAt(dirfd, path); + if (!flags) { + FS.unlink(path); + } else if (flags === 512) { + FS.rmdir(path); + } else { + return -28; + } + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +var readI53FromI64 = ptr => HEAPU32[((ptr) >> 2)] + HEAP32[(((ptr) + (4)) >> 2)] * 4294967296; + +function ___syscall_utimensat(dirfd, path, times, flags) { + try { + var nofollow = flags & 256; + path = SYSCALLS.getStr(path); + path = SYSCALLS.calculateAt(dirfd, path, true); + var now = Date.now(), atime, mtime; + if (!times) { + atime = now; + mtime = now; + } else { + var seconds = readI53FromI64(times); + var nanoseconds = HEAP32[(((times) + (8)) >> 2)]; + if (nanoseconds == 1073741823) { + atime = now; + } else if (nanoseconds == 1073741822) { + atime = null; + } else { + atime = (seconds * 1e3) + (nanoseconds / (1e3 * 1e3)); + } + times += 16; + seconds = readI53FromI64(times); + nanoseconds = HEAP32[(((times) + (8)) >> 2)]; + if (nanoseconds == 1073741823) { + mtime = now; + } else if (nanoseconds == 1073741822) { + mtime = null; + } else { + mtime = (seconds * 1e3) + (nanoseconds / (1e3 * 1e3)); + } + } + // null here means UTIME_OMIT was passed. If both were set to UTIME_OMIT then + // we can skip the call completely. + if ((mtime ?? atime) !== null) { + FS.utime(path, atime, mtime, nofollow); + } + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +var __abort_js = () => abort(""); + +var __embind_register_bigint = (primitiveType, name, size, minRange, maxRange) => {}; + +var AsciiToString = ptr => { + var str = ""; + while (1) { + var ch = HEAPU8[ptr++]; + if (!ch) return str; + str += String.fromCharCode(ch); + } +}; + +var awaitingDependencies = {}; + +var registeredTypes = {}; + +var typeDependencies = {}; + +class BindingError extends Error { + constructor(message) { + super(message); + this.name = "BindingError"; + } +} + +var throwBindingError = message => { + throw new BindingError(message); +}; + +/** @param {Object=} options */ function sharedRegisterType(rawType, registeredInstance, options = {}) { + var name = registeredInstance.name; + if (!rawType) { + throwBindingError(`type "${name}" must have a positive integer typeid pointer`); + } + if (registeredTypes.hasOwnProperty(rawType)) { + if (options.ignoreDuplicateRegistrations) { + return; + } else { + throwBindingError(`Cannot register type '${name}' twice`); + } + } + registeredTypes[rawType] = registeredInstance; + delete typeDependencies[rawType]; + if (awaitingDependencies.hasOwnProperty(rawType)) { + var callbacks = awaitingDependencies[rawType]; + delete awaitingDependencies[rawType]; + callbacks.forEach(cb => cb()); + } +} + +/** @param {Object=} options */ function registerType(rawType, registeredInstance, options = {}) { + return sharedRegisterType(rawType, registeredInstance, options); +} + +/** @suppress {globalThis} */ var __embind_register_bool = (rawType, name, trueValue, falseValue) => { + name = AsciiToString(name); + registerType(rawType, { + name, + fromWireType: function(wt) { + // ambiguous emscripten ABI: sometimes return values are + // true or false, and sometimes integers (0 or 1) + return !!wt; + }, + toWireType: function(destructors, o) { + return o ? trueValue : falseValue; + }, + readValueFromPointer: function(pointer) { + return this.fromWireType(HEAPU8[pointer]); + }, + destructorFunction: null + }); +}; + +var emval_freelist = []; + +var emval_handles = [ 0, 1, , 1, null, 1, true, 1, false, 1 ]; + +var __emval_decref = handle => { + if (handle > 9 && 0 === --emval_handles[handle + 1]) { + var value = emval_handles[handle]; + emval_handles[handle] = undefined; + emval_freelist.push(handle); + } +}; + +var Emval = { + toValue: handle => { + if (!handle) { + throwBindingError(`Cannot use deleted val. handle = ${handle}`); + } + return emval_handles[handle]; + }, + toHandle: value => { + switch (value) { + case undefined: + return 2; + + case null: + return 4; + + case true: + return 6; + + case false: + return 8; + + default: + { + const handle = emval_freelist.pop() || emval_handles.length; + emval_handles[handle] = value; + emval_handles[handle + 1] = 1; + return handle; + } + } + } +}; + +/** @suppress {globalThis} */ function readPointer(pointer) { + return this.fromWireType(HEAPU32[((pointer) >> 2)]); +} + +var EmValType = { + name: "emscripten::val", + fromWireType: handle => { + var rv = Emval.toValue(handle); + __emval_decref(handle); + return rv; + }, + toWireType: (destructors, value) => Emval.toHandle(value), + readValueFromPointer: readPointer, + destructorFunction: null +}; + +var __embind_register_emval = rawType => registerType(rawType, EmValType); + +/** @type {!Float32Array} */ var HEAPF32; + +/** @type {!Float64Array} */ var HEAPF64; + +var floatReadValueFromPointer = (name, width) => { + switch (width) { + case 4: + return function(pointer) { + return this.fromWireType(HEAPF32[((pointer) >> 2)]); + }; + + case 8: + return function(pointer) { + return this.fromWireType(HEAPF64[((pointer) >> 3)]); + }; + + default: + throw new TypeError(`invalid float width (${width}): ${name}`); + } +}; + +var __embind_register_float = (rawType, name, size) => { + name = AsciiToString(name); + registerType(rawType, { + name, + fromWireType: value => value, + toWireType: (destructors, value) => value, + readValueFromPointer: floatReadValueFromPointer(name, size), + destructorFunction: null + }); +}; + +/** @type {!Uint16Array} */ var HEAPU16; + +var integerReadValueFromPointer = (name, width, signed) => { + // integers are quite common, so generate very specialized functions + switch (width) { + case 1: + return signed ? pointer => HEAP8[pointer] : pointer => HEAPU8[pointer]; + + case 2: + return signed ? pointer => HEAP16[((pointer) >> 1)] : pointer => HEAPU16[((pointer) >> 1)]; + + case 4: + return signed ? pointer => HEAP32[((pointer) >> 2)] : pointer => HEAPU32[((pointer) >> 2)]; + + default: + throw new TypeError(`invalid integer width (${width}): ${name}`); + } +}; + +/** @suppress {globalThis} */ var __embind_register_integer = (primitiveType, name, size, minRange, maxRange) => { + name = AsciiToString(name); + const isUnsignedType = minRange === 0; + let fromWireType = value => value; + if (isUnsignedType) { + var bitshift = 32 - 8 * size; + fromWireType = value => (value << bitshift) >>> bitshift; + maxRange = fromWireType(maxRange); + } + registerType(primitiveType, { + name, + fromWireType, + toWireType: (destructors, value) => value, + readValueFromPointer: integerReadValueFromPointer(name, size, minRange !== 0), + destructorFunction: null + }); +}; + +var __embind_register_memory_view = (rawType, dataTypeIndex, name) => { + var typeMapping = [ Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ]; + var TA = typeMapping[dataTypeIndex]; + function decodeMemoryView(handle) { + var size = HEAPU32[((handle) >> 2)]; + var data = HEAPU32[(((handle) + (4)) >> 2)]; + return new TA(HEAP8.buffer, data, size); + } + name = AsciiToString(name); + registerType(rawType, { + name, + fromWireType: decodeMemoryView, + readValueFromPointer: decodeMemoryView + }, { + ignoreDuplicateRegistrations: true + }); +}; + +var __embind_register_std_string = (rawType, name) => { + name = AsciiToString(name); + var stdStringIsUTF8 = true; + registerType(rawType, { + name, + // For some method names we use string keys here since they are part of + // the public/external API and/or used by the runtime-generated code. + fromWireType(value) { + var length = HEAPU32[((value) >> 2)]; + var payload = value + 4; + var str; + if (stdStringIsUTF8) { + str = UTF8ToString(payload, length, true); + } else { + str = ""; + for (var i = 0; i < length; ++i) { + str += String.fromCharCode(HEAPU8[payload + i]); + } + } + _free(value); + return str; + }, + toWireType(destructors, value) { + if (value instanceof ArrayBuffer) { + value = new Uint8Array(value); + } + var length; + var valueIsOfTypeString = (typeof value == "string"); + // We accept `string` or array views with single byte elements + if (!(valueIsOfTypeString || (ArrayBuffer.isView(value) && value.BYTES_PER_ELEMENT == 1))) { + throwBindingError("Cannot pass non-string to std::string"); + } + if (stdStringIsUTF8 && valueIsOfTypeString) { + length = lengthBytesUTF8(value); + } else { + length = value.length; + } + // assumes POINTER_SIZE alignment + var base = _malloc(4 + length + 1); + var ptr = base + 4; + HEAPU32[((base) >> 2)] = length; + if (valueIsOfTypeString) { + if (stdStringIsUTF8) { + stringToUTF8(value, ptr, length + 1); + } else { + for (var i = 0; i < length; ++i) { + var charCode = value.charCodeAt(i); + if (charCode > 255) { + _free(base); + throwBindingError("String has UTF-16 code units that do not fit in 8 bits"); + } + HEAPU8[ptr + i] = charCode; + } + } + } else { + HEAPU8.set(value, ptr); + } + if (destructors !== null) { + destructors.push(_free, base); + } + return base; + }, + readValueFromPointer: readPointer, + destructorFunction(ptr) { + _free(ptr); + } + }); +}; + +var UTF16Decoder = new TextDecoder("utf-16le"); + +var UTF16ToString = (ptr, maxBytesToRead, ignoreNul) => { + var idx = ((ptr) >> 1); + var endIdx = findStringEnd(HEAPU16, idx, maxBytesToRead / 2, ignoreNul); + return UTF16Decoder.decode(HEAPU16.subarray(idx, endIdx)); +}; + +var stringToUTF16 = (str, outPtr, maxBytesToWrite = 2147483647) => { + if (maxBytesToWrite < 2) return 0; + maxBytesToWrite -= 2; + // Null terminator. + var startPtr = outPtr; + var numCharsToWrite = (maxBytesToWrite < str.length * 2) ? (maxBytesToWrite / 2) : str.length; + for (var i = 0; i < numCharsToWrite; ++i) { + // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP. + var codeUnit = str.charCodeAt(i); + // possibly a lead surrogate + HEAP16[((outPtr) >> 1)] = codeUnit; + outPtr += 2; + } + // Null-terminate the pointer to the HEAP. + HEAP16[((outPtr) >> 1)] = 0; + return outPtr - startPtr; +}; + +var lengthBytesUTF16 = str => str.length * 2; + +var UTF32ToString = (ptr, maxBytesToRead, ignoreNul) => { + var str = ""; + var startIdx = ((ptr) >> 2); + // If maxBytesToRead is not passed explicitly, it will be undefined, and this + // will always evaluate to true. This saves on code size. + for (var i = 0; !(i >= maxBytesToRead / 4); i++) { + var utf32 = HEAPU32[startIdx + i]; + if (!utf32 && !ignoreNul) break; + str += String.fromCodePoint(utf32); + } + return str; +}; + +var stringToUTF32 = (str, outPtr, maxBytesToWrite = 2147483647) => { + if (maxBytesToWrite < 4) return 0; + var startPtr = outPtr; + var endPtr = startPtr + maxBytesToWrite - 4; + for (var i = 0; i < str.length; ++i) { + var codePoint = str.codePointAt(i); + // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16. + // We need to manually skip over the second code unit for correct iteration. + if (codePoint > 65535) { + i++; + } + HEAP32[((outPtr) >> 2)] = codePoint; + outPtr += 4; + if (outPtr + 4 > endPtr) break; + } + // Null-terminate the pointer to the HEAP. + HEAP32[((outPtr) >> 2)] = 0; + return outPtr - startPtr; +}; + +var lengthBytesUTF32 = str => { + var len = 0; + for (var i = 0; i < str.length; ++i) { + var codePoint = str.codePointAt(i); + // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16. + // We need to manually skip over the second code unit for correct iteration. + if (codePoint > 65535) { + i++; + } + len += 4; + } + return len; +}; + +var __embind_register_std_wstring = (rawType, charSize, name) => { + name = AsciiToString(name); + var decodeString, encodeString, lengthBytesUTF; + if (charSize === 2) { + decodeString = UTF16ToString; + encodeString = stringToUTF16; + lengthBytesUTF = lengthBytesUTF16; + } else { + decodeString = UTF32ToString; + encodeString = stringToUTF32; + lengthBytesUTF = lengthBytesUTF32; + } + registerType(rawType, { + name, + fromWireType: value => { + // Code mostly taken from _embind_register_std_string fromWireType + var length = HEAPU32[((value) >> 2)]; + var str = decodeString(value + 4, length * charSize, true); + _free(value); + return str; + }, + toWireType: (destructors, value) => { + if (!(typeof value == "string")) { + throwBindingError(`Cannot pass non-string to C++ string type ${name}`); + } + // assumes POINTER_SIZE alignment + var length = lengthBytesUTF(value); + var ptr = _malloc(4 + length + charSize); + HEAPU32[((ptr) >> 2)] = length / charSize; + encodeString(value, ptr + 4, length + charSize); + if (destructors !== null) { + destructors.push(_free, ptr); + } + return ptr; + }, + readValueFromPointer: readPointer, + destructorFunction(ptr) { + _free(ptr); + } + }); +}; + +var __embind_register_void = (rawType, name) => { + name = AsciiToString(name); + registerType(rawType, { + isVoid: true, + // void return values can be optimized out sometimes + name, + fromWireType: () => undefined, + // TODO: assert if anything else is given? + toWireType: (destructors, o) => undefined + }); +}; + +var emval_methodCallers = []; + +var emval_addMethodCaller = caller => { + var id = emval_methodCallers.length; + emval_methodCallers.push(caller); + return id; +}; + +var getTypeName = type => { + var ptr = ___getTypeName(type); + var rv = AsciiToString(ptr); + _free(ptr); + return rv; +}; + +var requireRegisteredType = (rawType, humanName) => { + var impl = registeredTypes[rawType]; + if (undefined === impl) { + throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`); + } + return impl; +}; + +var emval_lookupTypes = (argCount, argTypes) => { + var a = new Array(argCount); + for (var i = 0; i < argCount; ++i) { + a[i] = requireRegisteredType(HEAPU32[(((argTypes) + (i * 4)) >> 2)], `parameter ${i}`); + } + return a; +}; + +var createNamedFunction = (name, func) => Object.defineProperty(func, "name", { + value: name +}); + +var emval_returnValue = (toReturnWire, destructorsRef, handle) => { + var destructors = []; + var result = toReturnWire(destructors, handle); + if (destructors.length) { + // void, primitives and any other types w/o destructors don't need to allocate a handle + HEAPU32[((destructorsRef) >> 2)] = Emval.toHandle(destructors); + } + return result; +}; + +var emval_symbols = {}; + +var getStringOrSymbol = address => { + var symbol = emval_symbols[address]; + if (symbol === undefined) { + return AsciiToString(address); + } + return symbol; +}; + +var __emval_create_invoker = (argCount, argTypesPtr, kind) => { + var GenericWireTypeSize = 8; + var [retType, ...argTypes] = emval_lookupTypes(argCount, argTypesPtr); + var toReturnWire = retType.toWireType.bind(retType); + var argFromPtr = argTypes.map(type => type.readValueFromPointer.bind(type)); + argCount--; + // remove the extracted return type + var argN = new Array(argCount); + var invokerFunction = (handle, methodName, destructorsRef, args) => { + var offset = 0; + for (var i = 0; i < argCount; ++i) { + argN[i] = argFromPtr[i](args + offset); + offset += GenericWireTypeSize; + } + var rv; + switch (kind) { + case 0: + rv = Emval.toValue(handle).apply(null, argN); + break; + + case 2: + rv = Reflect.construct(Emval.toValue(handle), argN); + break; + + case 3: + // no-op, just return the argument + rv = argN[0]; + break; + + case 1: + rv = Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN); + break; + } + return emval_returnValue(toReturnWire, destructorsRef, rv); + }; + var functionName = `methodCaller<(${argTypes.map(t => t.name)}) => ${retType.name}>`; + return emval_addMethodCaller(createNamedFunction(functionName, invokerFunction)); +}; + +var __emval_get_global = name => { + if (!name) { + return Emval.toHandle(globalThis); + } + name = getStringOrSymbol(name); + return Emval.toHandle(globalThis[name]); +}; + +var __emval_get_property = (handle, key) => { + handle = Emval.toValue(handle); + key = Emval.toValue(key); + return Emval.toHandle(handle[key]); +}; + +var __emval_incref = handle => { + if (handle > 9) { + emval_handles[handle + 1] += 1; + } +}; + +var __emval_instanceof = (object, constructor) => { + object = Emval.toValue(object); + constructor = Emval.toValue(constructor); + return object instanceof constructor; +}; + +var __emval_invoke = (caller, handle, methodName, destructorsRef, args) => emval_methodCallers[caller](handle, methodName, destructorsRef, args); + +var __emval_new_cstring = v => Emval.toHandle(getStringOrSymbol(v)); + +var runDestructors = destructors => { + while (destructors.length) { + var ptr = destructors.pop(); + var del = destructors.pop(); + del(ptr); + } +}; + +var __emval_run_destructors = handle => { + var destructors = Emval.toValue(handle); + runDestructors(destructors); + __emval_decref(handle); +}; + +var __emval_set_property = (handle, key, value) => { + handle = Emval.toValue(handle); + key = Emval.toValue(key); + value = Emval.toValue(value); + handle[key] = value; +}; + +var __emval_typeof = handle => { + handle = Emval.toValue(handle); + return Emval.toHandle(typeof handle); +}; + +function __gmtime_js(time_low, time_high, tmPtr) { + var time = convertI32PairToI53Checked(time_low, time_high); + var date = new Date(time * 1e3); + if (isNaN(date.getTime())) { + return 1; + } + HEAP32[((tmPtr) >> 2)] = date.getUTCSeconds(); + HEAP32[(((tmPtr) + (4)) >> 2)] = date.getUTCMinutes(); + HEAP32[(((tmPtr) + (8)) >> 2)] = date.getUTCHours(); + HEAP32[(((tmPtr) + (12)) >> 2)] = date.getUTCDate(); + HEAP32[(((tmPtr) + (16)) >> 2)] = date.getUTCMonth(); + HEAP32[(((tmPtr) + (20)) >> 2)] = date.getUTCFullYear() - 1900; + HEAP32[(((tmPtr) + (24)) >> 2)] = date.getUTCDay(); + var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0); + var yday = ((date.getTime() - start) / (1e3 * 60 * 60 * 24)) | 0; + HEAP32[(((tmPtr) + (28)) >> 2)] = yday; + return 0; +} + +var isLeapYear = year => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + +var MONTH_DAYS_LEAP_CUMULATIVE = [ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 ]; + +var MONTH_DAYS_REGULAR_CUMULATIVE = [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 ]; + +var ydayFromDate = date => { + var leap = isLeapYear(date.getFullYear()); + var monthDaysCumulative = (leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE); + var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1; + // -1 since it's days since Jan 1 + return yday; +}; + +function __localtime_js(time_low, time_high, tmPtr) { + var time = convertI32PairToI53Checked(time_low, time_high); + var date = new Date(time * 1e3); + if (isNaN(date.getTime())) { + return 1; + } + HEAP32[((tmPtr) >> 2)] = date.getSeconds(); + HEAP32[(((tmPtr) + (4)) >> 2)] = date.getMinutes(); + HEAP32[(((tmPtr) + (8)) >> 2)] = date.getHours(); + HEAP32[(((tmPtr) + (12)) >> 2)] = date.getDate(); + HEAP32[(((tmPtr) + (16)) >> 2)] = date.getMonth(); + HEAP32[(((tmPtr) + (20)) >> 2)] = date.getFullYear() - 1900; + HEAP32[(((tmPtr) + (24)) >> 2)] = date.getDay(); + var yday = ydayFromDate(date) | 0; + HEAP32[(((tmPtr) + (28)) >> 2)] = yday; + HEAP32[(((tmPtr) + (36)) >> 2)] = -(date.getTimezoneOffset() * 60); + // Attention: DST is in December in South, and some regions don't have DST at all. + var start = new Date(date.getFullYear(), 0, 1); + var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset(); + var winterOffset = start.getTimezoneOffset(); + var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0; + HEAP32[(((tmPtr) + (32)) >> 2)] = dst; + return 0; +} + +var setTempRet0 = val => __emscripten_tempret_set(val); + +var __mktime_js = function(tmPtr) { + var ret = (() => { + var date = new Date(HEAP32[(((tmPtr) + (20)) >> 2)] + 1900, HEAP32[(((tmPtr) + (16)) >> 2)], HEAP32[(((tmPtr) + (12)) >> 2)], HEAP32[(((tmPtr) + (8)) >> 2)], HEAP32[(((tmPtr) + (4)) >> 2)], HEAP32[((tmPtr) >> 2)], 0); + if (isNaN(date.getTime())) { + return -1; + } + // There's an ambiguous hour when the time goes back; the tm_isdst field is + // used to disambiguate it. Date() basically guesses, so we fix it up if it + // guessed wrong, or fill in tm_isdst with the guess if it's -1. + var dst = HEAP32[(((tmPtr) + (32)) >> 2)]; + var guessedOffset = date.getTimezoneOffset(); + var start = new Date(date.getFullYear(), 0, 1); + var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset(); + var winterOffset = start.getTimezoneOffset(); + var dstOffset = Math.min(winterOffset, summerOffset); + // DST is in December in South + if (dst < 0) { + // Attention: some regions don't have DST at all. + dst = Number(summerOffset != winterOffset && dstOffset == guessedOffset); + } else if ((dst > 0) != (dstOffset == guessedOffset)) { + var nonDstOffset = Math.max(winterOffset, summerOffset); + var trueOffset = dst > 0 ? dstOffset : nonDstOffset; + // Don't try setMinutes(date.getMinutes() + ...) -- it's messed up. + date.setTime(date.getTime() + (trueOffset - guessedOffset) * 6e4); + if (isNaN(date.getTime())) { + return -1; + } + } + HEAP32[(((tmPtr) + (32)) >> 2)] = dst; + HEAP32[(((tmPtr) + (24)) >> 2)] = date.getDay(); + var yday = ydayFromDate(date) | 0; + HEAP32[(((tmPtr) + (28)) >> 2)] = yday; + // To match expected behavior, update fields from date + HEAP32[((tmPtr) >> 2)] = date.getSeconds(); + HEAP32[(((tmPtr) + (4)) >> 2)] = date.getMinutes(); + HEAP32[(((tmPtr) + (8)) >> 2)] = date.getHours(); + HEAP32[(((tmPtr) + (12)) >> 2)] = date.getDate(); + HEAP32[(((tmPtr) + (16)) >> 2)] = date.getMonth(); + HEAP32[(((tmPtr) + (20)) >> 2)] = date.getYear(); + // Return time in seconds + return date.getTime() / 1e3; + })(); + return (setTempRet0((tempDouble = ret, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0)), + ret >>> 0); +}; + +function __mmap_js(len, prot, flags, fd, offset_low, offset_high, allocated, addr) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); + try { + var stream = SYSCALLS.getStreamFromFD(fd); + var res = FS.mmap(stream, len, offset, prot, flags); + var ptr = res.ptr; + HEAP32[((allocated) >> 2)] = res.allocated; + HEAPU32[((addr) >> 2)] = ptr; + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +function __munmap_js(addr, len, prot, flags, fd, offset_low, offset_high) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); + try { + var stream = SYSCALLS.getStreamFromFD(fd); + if (prot & 2) { + SYSCALLS.doMsync(addr, stream, len, flags, offset); + } + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return -e.errno; + } +} + +var __tzset_js = (timezone, daylight, std_name, dst_name) => { + // TODO: Use (malleable) environment variables instead of system settings. + var currentYear = (new Date).getFullYear(); + var winter = new Date(currentYear, 0, 1); + var summer = new Date(currentYear, 6, 1); + var winterOffset = winter.getTimezoneOffset(); + var summerOffset = summer.getTimezoneOffset(); + // Local standard timezone offset. Local standard time is not adjusted for + // daylight savings. This code uses the fact that getTimezoneOffset returns + // a greater value during Standard Time versus Daylight Saving Time (DST). + // Thus it determines the expected output during Standard Time, and it + // compares whether the output of the given date the same (Standard) or less + // (DST). + var stdTimezoneOffset = Math.max(winterOffset, summerOffset); + // timezone is specified as seconds west of UTC ("The external variable + // `timezone` shall be set to the difference, in seconds, between + // Coordinated Universal Time (UTC) and local standard time."), the same + // as returned by stdTimezoneOffset. + // See http://pubs.opengroup.org/onlinepubs/009695399/functions/tzset.html + HEAPU32[((timezone) >> 2)] = stdTimezoneOffset * 60; + HEAP32[((daylight) >> 2)] = Number(winterOffset != summerOffset); + var extractZone = timezoneOffset => { + // Why inverse sign? + // Read here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset + var sign = timezoneOffset >= 0 ? "-" : "+"; + var absOffset = Math.abs(timezoneOffset); + var hours = String(Math.floor(absOffset / 60)).padStart(2, "0"); + var minutes = String(absOffset % 60).padStart(2, "0"); + return `UTC${sign}${hours}${minutes}`; + }; + var winterName = extractZone(winterOffset); + var summerName = extractZone(summerOffset); + if (summerOffset < winterOffset) { + // Northern hemisphere + stringToUTF8(winterName, std_name, 17); + stringToUTF8(summerName, dst_name, 17); + } else { + stringToUTF8(winterName, dst_name, 17); + stringToUTF8(summerName, std_name, 17); + } +}; + +var _emscripten_get_now = () => performance.now(); + +var _emscripten_date_now = () => Date.now(); + +var nowIsMonotonic = 1; + +var checkWasiClock = clock_id => clock_id >= 0 && clock_id <= 3; + +function _clock_time_get(clk_id, ignored_precision_low, ignored_precision_high, ptime) { + var ignored_precision = convertI32PairToI53Checked(ignored_precision_low, ignored_precision_high); + if (!checkWasiClock(clk_id)) { + return 28; + } + var now; + // all wasi clocks but realtime are monotonic + if (clk_id === 0) { + now = _emscripten_date_now(); + } else if (nowIsMonotonic) { + now = _emscripten_get_now(); + } else { + return 52; + } + // "now" is in ms, and wasi times are in ns. + var nsec = Math.round(now * 1e3 * 1e3); + (tempI64 = [ nsec >>> 0, (tempDouble = nsec, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[((ptime) >> 2)] = tempI64[0], HEAP32[(((ptime) + (4)) >> 2)] = tempI64[1]); + return 0; +} + +var readEmAsmArgsArray = []; + +var readEmAsmArgs = (sigPtr, buf) => { + readEmAsmArgsArray.length = 0; + var ch; + // Most arguments are i32s, so shift the buffer pointer so it is a plain + // index into HEAP32. + while (ch = HEAPU8[sigPtr++]) { + // Floats are always passed as doubles, so all types except for 'i' + // are 8 bytes and require alignment. + var wide = (ch != 105); + wide &= (ch != 112); + buf += wide && (buf % 8) ? 4 : 0; + readEmAsmArgsArray.push(// Special case for pointers under wasm64 or CAN_ADDRESS_2GB mode. + ch == 112 ? HEAPU32[((buf) >> 2)] : ch == 105 ? HEAP32[((buf) >> 2)] : HEAPF64[((buf) >> 3)]); + buf += wide ? 8 : 4; + } + return readEmAsmArgsArray; +}; + +var runEmAsmFunction = (code, sigPtr, argbuf) => { + var args = readEmAsmArgs(sigPtr, argbuf); + return ASM_CONSTS[code](...args); +}; + +var _emscripten_asm_const_int = (code, sigPtr, argbuf) => runEmAsmFunction(code, sigPtr, argbuf); + +var _emscripten_asm_const_ptr = (code, sigPtr, argbuf) => runEmAsmFunction(code, sigPtr, argbuf); + +var _emscripten_errn = (str, len) => err(UTF8ToString(str, len)); + +var getHeapMax = () => // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate +// full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side +// for any code that deals with heap sizes, which would require special +// casing all heap size related code to treat 0 specially. +2147483648; + +var _emscripten_get_heap_max = () => getHeapMax(); + +var _emscripten_has_asyncify = () => 0; + +var _emscripten_outn = (str, len) => out(UTF8ToString(str, len)); + +var UNWIND_CACHE = {}; + +var stringToNewUTF8 = str => { + var size = lengthBytesUTF8(str) + 1; + var ret = _malloc(size); + if (ret) stringToUTF8(str, ret, size); + return ret; +}; + +/** @returns {number} */ var convertFrameToPC = frame => { + var match; + if (match = /\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(frame)) { + // Wasm engines give the binary offset directly, so we use that as return address + return +match[1]; + } else if (match = /:(\d+):\d+(?:\)|$)/.exec(frame)) { + // If we are in js, we can use the js line number as the "return address". + // This should work for wasm2js. We tag the high bit to distinguish this + // from wasm addresses. + return 2147483648 | +match[1]; + } + // return 0 if we can't find any + return 0; +}; + +var saveInUnwindCache = callstack => { + for (var line of callstack) { + var pc = convertFrameToPC(line); + if (pc) { + UNWIND_CACHE[pc] = line; + } + } +}; + +var jsStackTrace = () => (new Error).stack.toString(); + +var _emscripten_stack_snapshot = () => { + var callstack = jsStackTrace().split("\n"); + if (callstack[0] == "Error") { + callstack.shift(); + } + saveInUnwindCache(callstack); + // Caches the stack snapshot so that emscripten_stack_unwind_buffer() can + // unwind from this spot. + UNWIND_CACHE.last_addr = convertFrameToPC(callstack[3]); + UNWIND_CACHE.last_stack = callstack; + return UNWIND_CACHE.last_addr; +}; + +var _emscripten_pc_get_function = pc => { + var frame = UNWIND_CACHE[pc]; + if (!frame) return 0; + var name; + var match; + // First try to match foo.wasm.sym files explcitly. e.g. + // at test_return_address.wasm.main (wasm://wasm/test_return_address.wasm-0012cc2a:wasm-function[26]:0x9f3 + // Then match JS symbols which don't include that module name: + // at invokeEntryPoint (.../test_return_address.js:1500:42) + // Finally match firefox format: + // Object._main@http://server.com:4324:12' + if (match = /^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(frame)) { + name = match[1]; + } else if (match = /^\s+at (.*) \(.*\)$/.exec(frame)) { + name = match[1]; + } else if (match = /^(.+?)@/.exec(frame)) { + name = match[1]; + } else { + return 0; + } + _free(_emscripten_pc_get_function.ret ?? 0); + _emscripten_pc_get_function.ret = stringToNewUTF8(name); + return _emscripten_pc_get_function.ret; +}; + +var growMemory = size => { + var oldHeapSize = wasmMemory.buffer.byteLength; + var pages = ((size - oldHeapSize + 65535) / 65536) | 0; + try { + // round size grow request up to wasm page size (fixed 64KB per spec) + wasmMemory.grow(pages); + // .grow() takes a delta compared to the previous size + updateMemoryViews(); + return 1; + } catch (e) {} +}; + +var _emscripten_resize_heap = requestedSize => { + var oldSize = HEAPU8.length; + // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned. + requestedSize >>>= 0; + // With multithreaded builds, races can happen (another thread might increase the size + // in between), so return a failure, and let the caller retry. + // Memory resize rules: + // 1. Always increase heap size to at least the requested size, rounded up + // to next page multiple. + // 2a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap + // geometrically: increase the heap size according to + // MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%), At most + // overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB). + // 2b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap + // linearly: increase the heap size by at least + // MEMORY_GROWTH_LINEAR_STEP bytes. + // 3. Max size for the heap is capped at 2048MB-WASM_PAGE_SIZE, or by + // MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest + // 4. If we were unable to allocate as much memory, it may be due to + // over-eager decision to excessively reserve due to (3) above. + // Hence if an allocation fails, cut down on the amount of excess + // growth, in an attempt to succeed to perform a smaller allocation. + // A limit is set for how much we can grow. We should not exceed that + // (the wasm binary specifies it, so if we tried, we'd fail anyhow). + var maxHeapSize = getHeapMax(); + if (requestedSize > maxHeapSize) { + return false; + } + // Loop through potential heap size increases. If we attempt a too eager + // reservation that fails, cut down on the attempted size and reserve a + // smaller bump instead. (max 3 times, chosen somewhat arbitrarily) + for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + .2 / cutDown); + // ensure geometric growth + // but limit overreserving (default to capping at +96MB overgrowth at most) + overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); + var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536)); + var replacement = growMemory(newSize); + if (replacement) { + return true; + } + } + return false; +}; + +var _emscripten_stack_unwind_buffer = (addr, buffer, count) => { + var stack; + if (UNWIND_CACHE.last_addr == addr) { + stack = UNWIND_CACHE.last_stack; + } else { + stack = jsStackTrace().split("\n"); + if (stack[0] == "Error") { + stack.shift(); + } + saveInUnwindCache(stack); + } + var offset = 3; + while (stack[offset] && convertFrameToPC(stack[offset]) != addr) { + ++offset; + } + for (var i = 0; i < count && stack[i + offset]; ++i) { + HEAPU32[(((buffer) + (i * 4)) >> 2)] = convertFrameToPC(stack[i + offset]); + } + return i; +}; + +var GLctx; + +var webgl_enable_ANGLE_instanced_arrays = ctx => { + // Extension available in WebGL 1 from Firefox 26 and Google Chrome 30 onwards. Core feature in WebGL 2. + var ext = ctx.getExtension("ANGLE_instanced_arrays"); + // Because this extension is a core function in WebGL 2, assign the extension entry points in place of + // where the core functions will reside in WebGL 2. This way the calling code can call these without + // having to dynamically branch depending if running against WebGL 1 or WebGL 2. + if (ext) { + ctx["vertexAttribDivisor"] = (index, divisor) => ext["vertexAttribDivisorANGLE"](index, divisor); + ctx["drawArraysInstanced"] = (mode, first, count, primcount) => ext["drawArraysInstancedANGLE"](mode, first, count, primcount); + ctx["drawElementsInstanced"] = (mode, count, type, indices, primcount) => ext["drawElementsInstancedANGLE"](mode, count, type, indices, primcount); + return 1; + } +}; + +var webgl_enable_OES_vertex_array_object = ctx => { + // Extension available in WebGL 1 from Firefox 25 and WebKit 536.28/desktop Safari 6.0.3 onwards. Core feature in WebGL 2. + var ext = ctx.getExtension("OES_vertex_array_object"); + if (ext) { + ctx["createVertexArray"] = () => ext["createVertexArrayOES"](); + ctx["deleteVertexArray"] = vao => ext["deleteVertexArrayOES"](vao); + ctx["bindVertexArray"] = vao => ext["bindVertexArrayOES"](vao); + ctx["isVertexArray"] = vao => ext["isVertexArrayOES"](vao); + return 1; + } +}; + +var webgl_enable_WEBGL_draw_buffers = ctx => { + // Extension available in WebGL 1 from Firefox 28 onwards. Core feature in WebGL 2. + var ext = ctx.getExtension("WEBGL_draw_buffers"); + if (ext) { + ctx["drawBuffers"] = (n, bufs) => ext["drawBuffersWEBGL"](n, bufs); + return 1; + } +}; + +var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance = ctx => // Closure is expected to be allowed to minify the '.dibvbi' property, so not accessing it quoted. +!!(ctx.dibvbi = ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance")); + +var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance = ctx => !!(ctx.mdibvbi = ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance")); + +var webgl_enable_EXT_polygon_offset_clamp = ctx => !!(ctx.extPolygonOffsetClamp = ctx.getExtension("EXT_polygon_offset_clamp")); + +var webgl_enable_EXT_clip_control = ctx => !!(ctx.extClipControl = ctx.getExtension("EXT_clip_control")); + +var webgl_enable_WEBGL_polygon_mode = ctx => !!(ctx.webglPolygonMode = ctx.getExtension("WEBGL_polygon_mode")); + +var webgl_enable_WEBGL_multi_draw = ctx => // Closure is expected to be allowed to minify the '.multiDrawWebgl' property, so not accessing it quoted. +!!(ctx.multiDrawWebgl = ctx.getExtension("WEBGL_multi_draw")); + +var getEmscriptenSupportedExtensions = ctx => { + // Restrict the list of advertised extensions to those that we actually + // support. + var supportedExtensions = [ // WebGL 1 extensions + "ANGLE_instanced_arrays", "EXT_blend_minmax", "EXT_disjoint_timer_query", "EXT_frag_depth", "EXT_shader_texture_lod", "EXT_sRGB", "OES_element_index_uint", "OES_fbo_render_mipmap", "OES_standard_derivatives", "OES_texture_float", "OES_texture_half_float", "OES_texture_half_float_linear", "OES_vertex_array_object", "WEBGL_color_buffer_float", "WEBGL_depth_texture", "WEBGL_draw_buffers", // WebGL 2 extensions + "EXT_color_buffer_float", "EXT_conservative_depth", "EXT_disjoint_timer_query_webgl2", "EXT_texture_norm16", "NV_shader_noperspective_interpolation", "WEBGL_clip_cull_distance", // WebGL 1 and WebGL 2 extensions + "EXT_clip_control", "EXT_color_buffer_half_float", "EXT_depth_clamp", "EXT_float_blend", "EXT_polygon_offset_clamp", "EXT_texture_compression_bptc", "EXT_texture_compression_rgtc", "EXT_texture_filter_anisotropic", "KHR_parallel_shader_compile", "OES_texture_float_linear", "WEBGL_blend_func_extended", "WEBGL_compressed_texture_astc", "WEBGL_compressed_texture_etc", "WEBGL_compressed_texture_etc1", "WEBGL_compressed_texture_s3tc", "WEBGL_compressed_texture_s3tc_srgb", "WEBGL_debug_renderer_info", "WEBGL_debug_shaders", "WEBGL_lose_context", "WEBGL_multi_draw", "WEBGL_polygon_mode" ]; + // .getSupportedExtensions() can return null if context is lost, so coerce to empty array. + return ctx.getSupportedExtensions()?.filter(ext => supportedExtensions.includes(ext)) ?? []; +}; + +var registerPreMainLoop = f => { + // Does nothing unless $MainLoop is included/used. + typeof MainLoop != "undefined" && MainLoop.preMainLoop.push(f); +}; + +var webglBufferSubData = (target, offset, size, data, src = HEAPU8) => { + if (GL.currentContext.version >= 2) { + size && GLctx.bufferSubData(target, offset, src, data, size); + return; + } + GLctx.bufferSubData(target, offset, src.subarray(data, data + size)); +}; + +var GL = { + counter: 1, + buffers: [], + mappedBuffers: {}, + programs: [], + framebuffers: [], + renderbuffers: [], + textures: [], + shaders: [], + vaos: [], + contexts: [], + offscreenCanvases: {}, + queries: [], + samplers: [], + transformFeedbacks: [], + syncs: [], + byteSizeByTypeRoot: 5120, + byteSizeByType: [ 1, 1, 2, 2, 4, 4, 4, 2, 3, 4, 8 ], + stringCache: {}, + stringiCache: {}, + unpackAlignment: 4, + unpackRowLength: 0, + recordError: errorCode => { + if (!GL.lastError) { + GL.lastError = errorCode; + } + }, + getNewId: table => { + var ret = GL.counter++; + for (var i = table.length; i < ret; i++) { + table[i] = null; + } + // Skip over any non-null elements that might have been created by + // glBindBuffer. + while (table[ret]) { + ret = GL.counter++; + } + return ret; + }, + genObject: (n, buffers, createFunction, objectTable) => { + for (var i = 0; i < n; i++) { + var buffer = GLctx[createFunction](); + var id = buffer && GL.getNewId(objectTable); + if (buffer) { + buffer.name = id; + objectTable[id] = buffer; + } else { + GL.recordError(1282); + } + HEAP32[(((buffers) + (i * 4)) >> 2)] = id; + } + }, + MAX_TEMP_BUFFER_SIZE: 2097152, + numTempVertexBuffersPerSize: 64, + log2ceilLookup: i => 32 - Math.clz32(i ? i - 1 : 0), + generateTempBuffers: (quads, context) => { + var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE); + context.tempVertexBufferCounters1 = []; + context.tempVertexBufferCounters2 = []; + context.tempVertexBufferCounters1.length = context.tempVertexBufferCounters2.length = largestIndex + 1; + context.tempVertexBuffers1 = []; + context.tempVertexBuffers2 = []; + context.tempVertexBuffers1.length = context.tempVertexBuffers2.length = largestIndex + 1; + context.tempIndexBuffers = []; + context.tempIndexBuffers.length = largestIndex + 1; + for (var i = 0; i <= largestIndex; ++i) { + context.tempIndexBuffers[i] = null; + // Created on-demand + context.tempVertexBufferCounters1[i] = context.tempVertexBufferCounters2[i] = 0; + var ringbufferLength = GL.numTempVertexBuffersPerSize; + context.tempVertexBuffers1[i] = []; + context.tempVertexBuffers2[i] = []; + var ringbuffer1 = context.tempVertexBuffers1[i]; + var ringbuffer2 = context.tempVertexBuffers2[i]; + ringbuffer1.length = ringbuffer2.length = ringbufferLength; + for (var j = 0; j < ringbufferLength; ++j) { + ringbuffer1[j] = ringbuffer2[j] = null; + } + } + if (quads) { + // GL_QUAD indexes can be precalculated + context.tempQuadIndexBuffer = GLctx.createBuffer(); + context.GLctx.bindBuffer(34963, context.tempQuadIndexBuffer); + var numIndexes = GL.MAX_TEMP_BUFFER_SIZE >> 1; + var quadIndexes = new Uint16Array(numIndexes); + var i = 0, v = 0; + while (1) { + quadIndexes[i++] = v; + if (i >= numIndexes) break; + quadIndexes[i++] = v + 1; + if (i >= numIndexes) break; + quadIndexes[i++] = v + 2; + if (i >= numIndexes) break; + quadIndexes[i++] = v; + if (i >= numIndexes) break; + quadIndexes[i++] = v + 2; + if (i >= numIndexes) break; + quadIndexes[i++] = v + 3; + if (i >= numIndexes) break; + v += 4; + } + context.GLctx.bufferData(34963, quadIndexes, 35044); + context.GLctx.bindBuffer(34963, null); + } + }, + getTempVertexBuffer: sizeBytes => { + var idx = GL.log2ceilLookup(sizeBytes); + var ringbuffer = GL.currentContext.tempVertexBuffers1[idx]; + var nextFreeBufferIndex = GL.currentContext.tempVertexBufferCounters1[idx]; + GL.currentContext.tempVertexBufferCounters1[idx] = (GL.currentContext.tempVertexBufferCounters1[idx] + 1) & (GL.numTempVertexBuffersPerSize - 1); + var vbo = ringbuffer[nextFreeBufferIndex]; + if (vbo) { + return vbo; + } + var prevVBO = GLctx.getParameter(34964); + ringbuffer[nextFreeBufferIndex] = GLctx.createBuffer(); + GLctx.bindBuffer(34962, ringbuffer[nextFreeBufferIndex]); + GLctx.bufferData(34962, 1 << idx, 35048); + GLctx.bindBuffer(34962, prevVBO); + return ringbuffer[nextFreeBufferIndex]; + }, + getTempIndexBuffer: sizeBytes => { + var idx = GL.log2ceilLookup(sizeBytes); + var ibo = GL.currentContext.tempIndexBuffers[idx]; + if (ibo) { + return ibo; + } + var prevIBO = GLctx.getParameter(34965); + GL.currentContext.tempIndexBuffers[idx] = GLctx.createBuffer(); + GLctx.bindBuffer(34963, GL.currentContext.tempIndexBuffers[idx]); + GLctx.bufferData(34963, 1 << idx, 35048); + GLctx.bindBuffer(34963, prevIBO); + return GL.currentContext.tempIndexBuffers[idx]; + }, + newRenderingFrameStarted: () => { + if (!GL.currentContext) { + return; + } + var vb = GL.currentContext.tempVertexBuffers1; + GL.currentContext.tempVertexBuffers1 = GL.currentContext.tempVertexBuffers2; + GL.currentContext.tempVertexBuffers2 = vb; + vb = GL.currentContext.tempVertexBufferCounters1; + GL.currentContext.tempVertexBufferCounters1 = GL.currentContext.tempVertexBufferCounters2; + GL.currentContext.tempVertexBufferCounters2 = vb; + var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE); + for (var i = 0; i <= largestIndex; ++i) { + GL.currentContext.tempVertexBufferCounters1[i] = 0; + } + }, + getSource: (shader, count, string, length) => { + var source = ""; + for (var i = 0; i < count; ++i) { + var len = length ? HEAPU32[(((length) + (i * 4)) >> 2)] : undefined; + source += UTF8ToString(HEAPU32[(((string) + (i * 4)) >> 2)], len); + } + return source; + }, + calcBufLength: (size, type, stride, count) => { + if (stride > 0) { + return count * stride; + } + var typeSize = GL.byteSizeByType[type - GL.byteSizeByTypeRoot]; + return size * typeSize * count; + }, + usedTempBuffers: [], + preDrawHandleClientVertexAttribBindings: count => { + GL.resetBufferBinding = false; + // TODO: initial pass to detect ranges we need to upload, might not need + // an upload per attrib + for (var i = 0; i < GL.currentContext.maxVertexAttribs; ++i) { + var cb = GL.currentContext.clientBuffers[i]; + if (!cb.clientside || !cb.enabled) continue; + GL.resetBufferBinding = true; + var size = GL.calcBufLength(cb.size, cb.type, cb.stride, count); + var buf = GL.getTempVertexBuffer(size); + GLctx.bindBuffer(34962, buf); + webglBufferSubData(34962, 0, size, cb.ptr); + cb.vertexAttribPointerAdaptor.call(GLctx, i, cb.size, cb.type, cb.normalized, cb.stride, 0); + } + }, + postDrawHandleClientVertexAttribBindings: () => { + if (GL.resetBufferBinding) { + GLctx.bindBuffer(34962, GL.buffers[GLctx.currentArrayBufferBinding]); + } + }, + createContext: (/** @type {HTMLCanvasElement} */ canvas, webGLContextAttributes) => { + // BUG: Workaround Safari WebGL issue: After successfully acquiring WebGL + // context on a canvas, calling .getContext() will always return that + // context independent of which 'webgl' or 'webgl2' + // context version was passed. See: + // https://webkit.org/b/222758 + // and: + // https://github.com/emscripten-core/emscripten/issues/13295. + // TODO: Once the bug is fixed and shipped in Safari, adjust the Safari + // version field in above check. + if (!canvas.getContextSafariWebGL2Fixed) { + canvas.getContextSafariWebGL2Fixed = canvas.getContext; + /** @type {function(this:HTMLCanvasElement, string, (Object|null)=): (Object|null)} */ function fixedGetContext(ver, attrs) { + var gl = canvas.getContextSafariWebGL2Fixed(ver, attrs); + return ((ver == "webgl") == (gl instanceof WebGLRenderingContext)) ? gl : null; + } + canvas.getContext = fixedGetContext; + } + var ctx = (webGLContextAttributes.majorVersion > 1) ? canvas.getContext("webgl2", webGLContextAttributes) : canvas.getContext("webgl", webGLContextAttributes); + if (!ctx) return 0; + var handle = GL.registerContext(ctx, webGLContextAttributes); + return handle; + }, + registerContext: (ctx, webGLContextAttributes) => { + // without pthreads a context is just an integer ID + var handle = GL.getNewId(GL.contexts); + var context = { + handle, + attributes: webGLContextAttributes, + version: webGLContextAttributes.majorVersion, + GLctx: ctx + }; + // Store the created context object so that we can access the context + // given a canvas without having to pass the parameters again. + if (ctx.canvas) ctx.canvas.GLctxObject = context; + GL.contexts[handle] = context; + if (typeof webGLContextAttributes.enableExtensionsByDefault == "undefined" || webGLContextAttributes.enableExtensionsByDefault) { + GL.initExtensions(context); + } + context.maxVertexAttribs = context.GLctx.getParameter(34921); + context.clientBuffers = []; + for (var i = 0; i < context.maxVertexAttribs; i++) { + context.clientBuffers[i] = { + enabled: false, + clientside: false, + size: 0, + type: 0, + normalized: 0, + stride: 0, + ptr: 0, + vertexAttribPointerAdaptor: null + }; + } + GL.generateTempBuffers(false, context); + return handle; + }, + makeContextCurrent: contextHandle => { + // Active Emscripten GL layer context object. + GL.currentContext = GL.contexts[contextHandle]; + // Active WebGL context object. + Module["ctx"] = GLctx = GL.currentContext?.GLctx; + return !(contextHandle && !GLctx); + }, + getContext: contextHandle => GL.contexts[contextHandle], + deleteContext: contextHandle => { + if (GL.currentContext === GL.contexts[contextHandle]) { + GL.currentContext = null; + } + if (typeof JSEvents == "object") { + // Release all JS event handlers on the DOM element that the GL context is + // associated with since the context is now deleted. + JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas); + } + // Make sure the canvas object no longer refers to the context object so + // there are no GC surprises. + if (GL.contexts[contextHandle]?.GLctx.canvas) { + GL.contexts[contextHandle].GLctx.canvas.GLctxObject = undefined; + } + GL.contexts[contextHandle] = null; + }, + initExtensions: context => { + // If this function is called without a specific context object, init the + // extensions of the currently active context. + context ||= GL.currentContext; + if (context.initExtensionsDone) return; + context.initExtensionsDone = true; + var GLctx = context.GLctx; + // Detect the presence of a few extensions manually, since the GL interop + // layer itself will need to know if they exist. + // Extensions that are available in both WebGL 1 and WebGL 2 + webgl_enable_WEBGL_multi_draw(GLctx); + webgl_enable_EXT_polygon_offset_clamp(GLctx); + webgl_enable_EXT_clip_control(GLctx); + webgl_enable_WEBGL_polygon_mode(GLctx); + // Extensions that are only available in WebGL 1 (the calls will be no-ops + // if called on a WebGL 2 context active) + webgl_enable_ANGLE_instanced_arrays(GLctx); + webgl_enable_OES_vertex_array_object(GLctx); + webgl_enable_WEBGL_draw_buffers(GLctx); + // Extensions that are available from WebGL >= 2 (no-op if called on a WebGL 1 context active) + webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx); + webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx); + // On WebGL 2, EXT_disjoint_timer_query is replaced with an alternative + // that's based on core APIs, and exposes only the queryCounterEXT() + // entrypoint. + if (context.version >= 2) { + GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query_webgl2"); + } + // However, Firefox exposes the WebGL 1 version on WebGL 2 as well and + // thus we look for the WebGL 1 version again if the WebGL 2 version + // isn't present. https://bugzil.la/1328882 + if (context.version < 2 || !GLctx.disjointTimerQueryExt) { + GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query"); + } + for (var ext of getEmscriptenSupportedExtensions(GLctx)) { + // WEBGL_lose_context, WEBGL_debug_renderer_info and WEBGL_debug_shaders + // are not enabled by default. + if (!ext.includes("lose_context") && !ext.includes("debug")) { + // Call .getExtension() to enable that extension permanently. + GLctx.getExtension(ext); + } + } + } +}; + +var webglPowerPreferences = [ "default", "low-power", "high-performance" ]; + +/** @type {Object} */ var specialHTMLTargets = [ 0, globalThis.document ?? 0, globalThis.window ?? 0 ]; + +var findEventTarget = target => { + // The sensible 'default' target varies between events, but use window as the default + // since DOM events mostly can default to that. Specific callback registrations + // override their own defaults. + if (!target) return window; + if (typeof target == "number") target = specialHTMLTargets[target] || UTF8ToString(target); + if (target === "#window") return window; else if (target === "#document") return document; else if (target === "#screen") return screen; else if (target === "#canvas") return Module["canvas"]; else if (typeof target == "string") return globalThis.document?.getElementById(target); + return target; +}; + +var findCanvasEventTarget = target => { + if (typeof target == "number") target = UTF8ToString(target); + if (!target || target === "#canvas") { + if (typeof GL != "undefined" && GL.offscreenCanvases["canvas"]) return GL.offscreenCanvases["canvas"]; + // TODO: Remove this line, target '#canvas' should refer only to Module['canvas'], not to GL.offscreenCanvases['canvas'] - but need stricter tests to be able to remove this line. + return Module["canvas"]; + } + if (typeof GL != "undefined" && GL.offscreenCanvases[target]) return GL.offscreenCanvases[target]; + return findEventTarget(target); +}; + +var _emscripten_webgl_do_create_context = (target, attributes) => { + var attr32 = ((attributes) >> 2); + var powerPreference = HEAP32[attr32 + (8 >> 2)]; + var contextAttributes = { + "alpha": !!HEAP8[attributes + 0], + "depth": !!HEAP8[attributes + 1], + "stencil": !!HEAP8[attributes + 2], + "antialias": !!HEAP8[attributes + 3], + "premultipliedAlpha": !!HEAP8[attributes + 4], + "preserveDrawingBuffer": !!HEAP8[attributes + 5], + "powerPreference": webglPowerPreferences[powerPreference], + "failIfMajorPerformanceCaveat": !!HEAP8[attributes + 12], + "desynchronized": !!HEAP8[attributes + 33], + // The following are not predefined WebGL context attributes in the WebGL specification, so the property names can be minified by Closure. + majorVersion: HEAP32[attr32 + (16 >> 2)], + minorVersion: HEAP32[attr32 + (20 >> 2)], + enableExtensionsByDefault: HEAP8[attributes + 24], + explicitSwapControl: HEAP8[attributes + 25], + proxyContextToMainThread: HEAP32[attr32 + (28 >> 2)], + renderViaOffscreenBackBuffer: HEAP8[attributes + 32] + }; + var canvas = findCanvasEventTarget(target); + if (!canvas) { + return 0; + } + if (contextAttributes.explicitSwapControl) { + return 0; + } + var contextHandle = GL.createContext(canvas, contextAttributes); + return contextHandle; +}; + +var _emscripten_webgl_create_context = _emscripten_webgl_do_create_context; + +var _emscripten_webgl_destroy_context = contextHandle => { + if (GL.currentContext == contextHandle) GL.currentContext = 0; + GL.deleteContext(contextHandle); +}; + +var _emscripten_webgl_get_context_attributes = (c, a) => { + if (!a) return -5; + c = GL.contexts[c]; + if (!c) return -3; + var t = c.GLctx?.getContextAttributes(); + if (!t) return -3; + HEAP8[a] = t.alpha; + HEAP8[(a) + (1)] = t.depth; + HEAP8[(a) + (2)] = t.stencil; + HEAP8[(a) + (3)] = t.antialias; + HEAP8[(a) + (4)] = t.premultipliedAlpha; + HEAP8[(a) + (5)] = t.preserveDrawingBuffer; + var power = t["powerPreference"] && webglPowerPreferences.indexOf(t["powerPreference"]); + HEAP32[(((a) + (8)) >> 2)] = power; + HEAP8[(a) + (12)] = t.failIfMajorPerformanceCaveat; + HEAP8[(a) + (33)] = t.desynchronized; + HEAP32[(((a) + (16)) >> 2)] = c.version; + HEAP32[(((a) + (20)) >> 2)] = 0; + HEAP8[(a) + (24)] = c.attributes.enableExtensionsByDefault; + return 0; +}; + +var _emscripten_webgl_do_get_current_context = () => GL.currentContext ? GL.currentContext.handle : 0; + +var _emscripten_webgl_get_current_context = _emscripten_webgl_do_get_current_context; + +var _emscripten_webgl_make_context_current = contextHandle => { + var success = GL.makeContextCurrent(contextHandle); + return success ? 0 : -5; +}; + +var stackAlloc = sz => __emscripten_stack_alloc(sz); + +var stringToUTF8OnStack = str => { + var size = lengthBytesUTF8(str) + 1; + var ret = stackAlloc(size); + stringToUTF8(str, ret, size); + return ret; +}; + +var writeI53ToI64 = (ptr, num) => { + HEAPU32[((ptr) >> 2)] = num; + var lower = HEAPU32[((ptr) >> 2)]; + HEAPU32[(((ptr) + (4)) >> 2)] = (num - lower) / 4294967296; +}; + +var wasmTableMirror = []; + +var getWasmTableEntry = funcPtr => { + var func = wasmTableMirror[funcPtr]; + if (!func) { + /** @suppress {checkTypes} */ wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr); + } + return func; +}; + +var WebGPU = { + Internals: { + jsObjects: [], + jsObjectInsert: (ptr, jsObject) => { + ptr >>>= 0; + WebGPU.Internals.jsObjects[ptr] = jsObject; + }, + bufferOnUnmaps: [], + futures: [], + futureInsert: (futureId, promise) => {} + }, + getJsObject: ptr => { + if (!ptr) return undefined; + ptr >>>= 0; + return WebGPU.Internals.jsObjects[ptr]; + }, + importJsAdapter: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateAdapter(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsBindGroup: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateBindGroup(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsBindGroupLayout: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateBindGroupLayout(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsBuffer: (buffer, parentPtr = 0) => { + // At the moment, we do not allow importing pending buffers. + assert(buffer.mapState === "unmapped"); + var bufferPtr = _emwgpuImportBuffer(parentPtr); + WebGPU.Internals.jsObjectInsert(bufferPtr, buffer); + return bufferPtr; + }, + importJsCommandBuffer: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateCommandBuffer(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsCommandEncoder: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateCommandEncoder(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsComputePassEncoder: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateComputePassEncoder(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsComputePipeline: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateComputePipeline(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsDevice: (device, parentPtr = 0) => { + var queuePtr = _emwgpuCreateQueue(parentPtr); + var devicePtr = _emwgpuCreateDevice(parentPtr, queuePtr); + WebGPU.Internals.jsObjectInsert(queuePtr, device.queue); + WebGPU.Internals.jsObjectInsert(devicePtr, device); + return devicePtr; + }, + importJsExternalTexture: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateExternalTexture(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsPipelineLayout: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreatePipelineLayout(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsQuerySet: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateQuerySet(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsQueue: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateQueue(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsRenderBundle: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateRenderBundle(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsRenderBundleEncoder: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateRenderBundleEncoder(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsRenderPassEncoder: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateRenderPassEncoder(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsRenderPipeline: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateRenderPipeline(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsSampler: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateSampler(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsShaderModule: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateShaderModule(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsSurface: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateSurface(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsTexture: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateTexture(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + importJsTextureView: (obj, parentPtr = 0) => { + var ptr = _emwgpuCreateTextureView(parentPtr); + WebGPU.Internals.jsObjects[ptr] = obj; + return ptr; + }, + errorCallback: (callback, type, message, userdata) => { + var sp = stackSave(); + var messagePtr = stringToUTF8OnStack(message); + getWasmTableEntry(callback)(type, messagePtr, userdata); + stackRestore(sp); + }, + iterateExtensions: (root, handlers) => { + for (var ptr = HEAPU32[((root) >> 2)]; ptr; ptr = HEAPU32[((ptr) >> 2)]) { + var sType = HEAP32[(((ptr) + (4)) >> 2)]; + // This will crash if there's no handler indicating either a bogus + // sType, or one we haven't implemented yet. + var handler = handlers[sType](ptr); + } + }, + setStringView: (ptr, data, length) => { + HEAPU32[((ptr) >> 2)] = data; + HEAPU32[(((ptr) + (4)) >> 2)] = length; + }, + makeStringFromStringView: stringViewPtr => { + var ptr = HEAPU32[((stringViewPtr) >> 2)]; + var length = HEAPU32[(((stringViewPtr) + (4)) >> 2)]; + // UTF8ToString stops at the first null terminator character in the + // string regardless of the length. + return UTF8ToString(ptr, length); + }, + makeStringFromOptionalStringView: stringViewPtr => { + var ptr = HEAPU32[((stringViewPtr) >> 2)]; + var length = HEAPU32[(((stringViewPtr) + (4)) >> 2)]; + // If we don't have a valid string pointer, just return undefined when + // optional. + if (!ptr) { + if (length === 0) { + return ""; + } + return undefined; + } + // UTF8ToString stops at the first null terminator character in the + // string regardless of the length. + return UTF8ToString(ptr, length); + }, + makeColor: ptr => ({ + "r": HEAPF64[((ptr) >> 3)], + "g": HEAPF64[(((ptr) + (8)) >> 3)], + "b": HEAPF64[(((ptr) + (16)) >> 3)], + "a": HEAPF64[(((ptr) + (24)) >> 3)] + }), + makeExtent3D: ptr => ({ + "width": HEAPU32[((ptr) >> 2)], + "height": HEAPU32[(((ptr) + (4)) >> 2)], + "depthOrArrayLayers": HEAPU32[(((ptr) + (8)) >> 2)] + }), + makeOrigin3D: ptr => ({ + "x": HEAPU32[((ptr) >> 2)], + "y": HEAPU32[(((ptr) + (4)) >> 2)], + "z": HEAPU32[(((ptr) + (8)) >> 2)] + }), + makeTexelCopyTextureInfo: ptr => ({ + "texture": WebGPU.getJsObject(HEAPU32[((ptr) >> 2)]), + "mipLevel": HEAPU32[(((ptr) + (4)) >> 2)], + "origin": WebGPU.makeOrigin3D(ptr + 8), + "aspect": WebGPU.TextureAspect[HEAP32[(((ptr) + (20)) >> 2)]] + }), + makeTexelCopyBufferLayout: ptr => { + var bytesPerRow = HEAPU32[(((ptr) + (8)) >> 2)]; + var rowsPerImage = HEAPU32[(((ptr) + (12)) >> 2)]; + return { + "offset": readI53FromI64(ptr), + "bytesPerRow": bytesPerRow === 4294967295 ? undefined : bytesPerRow, + "rowsPerImage": rowsPerImage === 4294967295 ? undefined : rowsPerImage + }; + }, + makeTexelCopyBufferInfo: ptr => { + var layoutPtr = ptr + 0; + var bufferCopyView = WebGPU.makeTexelCopyBufferLayout(layoutPtr); + bufferCopyView["buffer"] = WebGPU.getJsObject(HEAPU32[(((ptr) + (16)) >> 2)]); + return bufferCopyView; + }, + makePassTimestampWrites: ptr => { + if (ptr === 0) return undefined; + return { + "querySet": WebGPU.getJsObject(HEAPU32[(((ptr) + (4)) >> 2)]), + "beginningOfPassWriteIndex": HEAPU32[(((ptr) + (8)) >> 2)], + "endOfPassWriteIndex": HEAPU32[(((ptr) + (12)) >> 2)] + }; + }, + makePipelineConstants: (constantCount, constantsPtr) => { + if (!constantCount) return; + var constants = {}; + for (var i = 0; i < constantCount; ++i) { + var entryPtr = constantsPtr + 24 * i; + var key = WebGPU.makeStringFromStringView(entryPtr + 4); + constants[key] = HEAPF64[(((entryPtr) + (16)) >> 3)]; + } + return constants; + }, + makePipelineLayout: layoutPtr => { + if (!layoutPtr) return "auto"; + return WebGPU.getJsObject(layoutPtr); + }, + makeComputeState: ptr => { + if (!ptr) return undefined; + var desc = { + "module": WebGPU.getJsObject(HEAPU32[(((ptr) + (4)) >> 2)]), + "constants": WebGPU.makePipelineConstants(HEAPU32[(((ptr) + (16)) >> 2)], HEAPU32[(((ptr) + (20)) >> 2)]), + "entryPoint": WebGPU.makeStringFromOptionalStringView(ptr + 8) + }; + return desc; + }, + makeComputePipelineDesc: descriptor => { + var desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "layout": WebGPU.makePipelineLayout(HEAPU32[(((descriptor) + (12)) >> 2)]), + "compute": WebGPU.makeComputeState(descriptor + 16) + }; + return desc; + }, + makeRenderPipelineDesc: descriptor => { + function makePrimitiveState(psPtr) { + if (!psPtr) return undefined; + return { + "topology": WebGPU.PrimitiveTopology[HEAP32[(((psPtr) + (4)) >> 2)]], + "stripIndexFormat": WebGPU.IndexFormat[HEAP32[(((psPtr) + (8)) >> 2)]], + "frontFace": WebGPU.FrontFace[HEAP32[(((psPtr) + (12)) >> 2)]], + "cullMode": WebGPU.CullMode[HEAP32[(((psPtr) + (16)) >> 2)]], + "unclippedDepth": !!(HEAPU32[(((psPtr) + (20)) >> 2)]) + }; + } + function makeBlendComponent(bdPtr) { + if (!bdPtr) return undefined; + return { + "operation": WebGPU.BlendOperation[HEAP32[((bdPtr) >> 2)]], + "srcFactor": WebGPU.BlendFactor[HEAP32[(((bdPtr) + (4)) >> 2)]], + "dstFactor": WebGPU.BlendFactor[HEAP32[(((bdPtr) + (8)) >> 2)]] + }; + } + function makeBlendState(bsPtr) { + if (!bsPtr) return undefined; + return { + "alpha": makeBlendComponent(bsPtr + 12), + "color": makeBlendComponent(bsPtr + 0) + }; + } + function makeColorState(csPtr) { + var format = WebGPU.TextureFormat[HEAP32[(((csPtr) + (4)) >> 2)]]; + return format ? { + "format": format, + "blend": makeBlendState(HEAPU32[(((csPtr) + (8)) >> 2)]), + "writeMask": HEAPU32[(((csPtr) + (16)) >> 2)] + } : undefined; + } + function makeColorStates(count, csArrayPtr) { + var states = []; + for (var i = 0; i < count; ++i) { + states.push(makeColorState(csArrayPtr + 24 * i)); + } + return states; + } + function makeStencilStateFace(ssfPtr) { + return { + "compare": WebGPU.CompareFunction[HEAP32[((ssfPtr) >> 2)]], + "failOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (4)) >> 2)]], + "depthFailOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (8)) >> 2)]], + "passOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (12)) >> 2)]] + }; + } + function makeDepthStencilState(dssPtr) { + if (!dssPtr) return undefined; + return { + "format": WebGPU.TextureFormat[HEAP32[(((dssPtr) + (4)) >> 2)]], + "depthWriteEnabled": !!(HEAPU32[(((dssPtr) + (8)) >> 2)]), + "depthCompare": WebGPU.CompareFunction[HEAP32[(((dssPtr) + (12)) >> 2)]], + "stencilFront": makeStencilStateFace(dssPtr + 16), + "stencilBack": makeStencilStateFace(dssPtr + 32), + "stencilReadMask": HEAPU32[(((dssPtr) + (48)) >> 2)], + "stencilWriteMask": HEAPU32[(((dssPtr) + (52)) >> 2)], + "depthBias": HEAP32[(((dssPtr) + (56)) >> 2)], + "depthBiasSlopeScale": HEAPF32[(((dssPtr) + (60)) >> 2)], + "depthBiasClamp": HEAPF32[(((dssPtr) + (64)) >> 2)] + }; + } + function makeVertexAttribute(vaPtr) { + return { + "format": WebGPU.VertexFormat[HEAP32[(((vaPtr) + (4)) >> 2)]], + "offset": readI53FromI64((vaPtr) + (8)), + "shaderLocation": HEAPU32[(((vaPtr) + (16)) >> 2)] + }; + } + function makeVertexAttributes(count, vaArrayPtr) { + var vas = []; + for (var i = 0; i < count; ++i) { + vas.push(makeVertexAttribute(vaArrayPtr + i * 24)); + } + return vas; + } + function makeVertexBuffer(vbPtr) { + if (!vbPtr) return undefined; + var stepMode = WebGPU.VertexStepMode[HEAP32[(((vbPtr) + (4)) >> 2)]]; + var attributeCount = HEAPU32[(((vbPtr) + (16)) >> 2)]; + if (!stepMode && !attributeCount) { + return null; + } + return { + "arrayStride": readI53FromI64((vbPtr) + (8)), + "stepMode": stepMode, + "attributes": makeVertexAttributes(attributeCount, HEAPU32[(((vbPtr) + (20)) >> 2)]) + }; + } + function makeVertexBuffers(count, vbArrayPtr) { + if (!count) return undefined; + var vbs = []; + for (var i = 0; i < count; ++i) { + vbs.push(makeVertexBuffer(vbArrayPtr + i * 24)); + } + return vbs; + } + function makeVertexState(viPtr) { + if (!viPtr) return undefined; + var desc = { + "module": WebGPU.getJsObject(HEAPU32[(((viPtr) + (4)) >> 2)]), + "constants": WebGPU.makePipelineConstants(HEAPU32[(((viPtr) + (16)) >> 2)], HEAPU32[(((viPtr) + (20)) >> 2)]), + "buffers": makeVertexBuffers(HEAPU32[(((viPtr) + (24)) >> 2)], HEAPU32[(((viPtr) + (28)) >> 2)]), + "entryPoint": WebGPU.makeStringFromOptionalStringView(viPtr + 8) + }; + return desc; + } + function makeMultisampleState(msPtr) { + if (!msPtr) return undefined; + return { + "count": HEAPU32[(((msPtr) + (4)) >> 2)], + "mask": HEAPU32[(((msPtr) + (8)) >> 2)], + "alphaToCoverageEnabled": !!(HEAPU32[(((msPtr) + (12)) >> 2)]) + }; + } + function makeFragmentState(fsPtr) { + if (!fsPtr) return undefined; + var desc = { + "module": WebGPU.getJsObject(HEAPU32[(((fsPtr) + (4)) >> 2)]), + "constants": WebGPU.makePipelineConstants(HEAPU32[(((fsPtr) + (16)) >> 2)], HEAPU32[(((fsPtr) + (20)) >> 2)]), + "targets": makeColorStates(HEAPU32[(((fsPtr) + (24)) >> 2)], HEAPU32[(((fsPtr) + (28)) >> 2)]), + "entryPoint": WebGPU.makeStringFromOptionalStringView(fsPtr + 8) + }; + return desc; + } + var desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "layout": WebGPU.makePipelineLayout(HEAPU32[(((descriptor) + (12)) >> 2)]), + "vertex": makeVertexState(descriptor + 16), + "primitive": makePrimitiveState(descriptor + 48), + "depthStencil": makeDepthStencilState(HEAPU32[(((descriptor) + (72)) >> 2)]), + "multisample": makeMultisampleState(descriptor + 76), + "fragment": makeFragmentState(HEAPU32[(((descriptor) + (92)) >> 2)]) + }; + return desc; + }, + fillLimitStruct: (limits, limitsOutPtr) => { + var nextInChainPtr = HEAPU32[((limitsOutPtr) >> 2)]; + function setLimitValueU32(name, basePtr, limitOffset, fallbackValue = 0) { + var limitValue = limits[name] ?? fallbackValue; + HEAPU32[(((basePtr) + (limitOffset)) >> 2)] = limitValue; + } + function setLimitValueU64(name, basePtr, limitOffset, fallbackValue = 0) { + var limitValue = limits[name] ?? fallbackValue; + // Limits are integer-valued JS `Number`s, so they fit in 'i53'. + writeI53ToI64((basePtr) + (limitOffset), limitValue); + } + setLimitValueU32("maxTextureDimension1D", limitsOutPtr, 4); + setLimitValueU32("maxTextureDimension2D", limitsOutPtr, 8); + setLimitValueU32("maxTextureDimension3D", limitsOutPtr, 12); + setLimitValueU32("maxTextureArrayLayers", limitsOutPtr, 16); + setLimitValueU32("maxBindGroups", limitsOutPtr, 20); + setLimitValueU32("maxBindGroupsPlusVertexBuffers", limitsOutPtr, 24); + setLimitValueU32("maxBindingsPerBindGroup", limitsOutPtr, 28); + setLimitValueU32("maxDynamicUniformBuffersPerPipelineLayout", limitsOutPtr, 32); + setLimitValueU32("maxDynamicStorageBuffersPerPipelineLayout", limitsOutPtr, 36); + setLimitValueU32("maxSampledTexturesPerShaderStage", limitsOutPtr, 40); + setLimitValueU32("maxSamplersPerShaderStage", limitsOutPtr, 44); + setLimitValueU32("maxStorageBuffersPerShaderStage", limitsOutPtr, 48); + setLimitValueU32("maxStorageTexturesPerShaderStage", limitsOutPtr, 52); + setLimitValueU32("maxUniformBuffersPerShaderStage", limitsOutPtr, 56); + setLimitValueU32("minUniformBufferOffsetAlignment", limitsOutPtr, 80); + setLimitValueU32("minStorageBufferOffsetAlignment", limitsOutPtr, 84); + setLimitValueU64("maxUniformBufferBindingSize", limitsOutPtr, 64); + setLimitValueU64("maxStorageBufferBindingSize", limitsOutPtr, 72); + setLimitValueU32("maxVertexBuffers", limitsOutPtr, 88); + setLimitValueU64("maxBufferSize", limitsOutPtr, 96); + setLimitValueU32("maxVertexAttributes", limitsOutPtr, 104); + setLimitValueU32("maxVertexBufferArrayStride", limitsOutPtr, 108); + setLimitValueU32("maxInterStageShaderVariables", limitsOutPtr, 112); + setLimitValueU32("maxColorAttachments", limitsOutPtr, 116); + setLimitValueU32("maxColorAttachmentBytesPerSample", limitsOutPtr, 120); + setLimitValueU32("maxComputeWorkgroupStorageSize", limitsOutPtr, 124); + setLimitValueU32("maxComputeInvocationsPerWorkgroup", limitsOutPtr, 128); + setLimitValueU32("maxComputeWorkgroupSizeX", limitsOutPtr, 132); + setLimitValueU32("maxComputeWorkgroupSizeY", limitsOutPtr, 136); + setLimitValueU32("maxComputeWorkgroupSizeZ", limitsOutPtr, 140); + setLimitValueU32("maxComputeWorkgroupsPerDimension", limitsOutPtr, 144); + // Note this limit is new and won't be present in all browsers for a while. Fall back to 0. + setLimitValueU32("maxImmediateSize", limitsOutPtr, 148); + if (nextInChainPtr !== 0) { + var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)]; + var compatibilityModeLimitsPtr = nextInChainPtr; + // Note these limits are new and won't be present in all browsers for a while. Fall back to exposing the PerShaderStage limit. + setLimitValueU32("maxStorageBuffersInVertexStage", compatibilityModeLimitsPtr, 8, limits.maxStorageBuffersPerShaderStage); + setLimitValueU32("maxStorageBuffersInFragmentStage", compatibilityModeLimitsPtr, 16, limits.maxStorageBuffersPerShaderStage); + setLimitValueU32("maxStorageTexturesInVertexStage", compatibilityModeLimitsPtr, 12, limits.maxStorageTexturesPerShaderStage); + setLimitValueU32("maxStorageTexturesInFragmentStage", compatibilityModeLimitsPtr, 20, limits.maxStorageTexturesPerShaderStage); + } + }, + fillAdapterInfoStruct: (info, infoStruct) => { + // Populate subgroup limits. + HEAPU32[(((infoStruct) + (52)) >> 2)] = info.subgroupMinSize; + HEAPU32[(((infoStruct) + (56)) >> 2)] = info.subgroupMaxSize; + // Append all the strings together to condense into a single malloc. + var strs = info.vendor + info.architecture + info.device + info.description; + var strPtr = stringToNewUTF8(strs); + var vendorLen = lengthBytesUTF8(info.vendor); + WebGPU.setStringView(infoStruct + 4, strPtr, vendorLen); + strPtr += vendorLen; + var architectureLen = lengthBytesUTF8(info.architecture); + WebGPU.setStringView(infoStruct + 12, strPtr, architectureLen); + strPtr += architectureLen; + var deviceLen = lengthBytesUTF8(info.device); + WebGPU.setStringView(infoStruct + 20, strPtr, deviceLen); + strPtr += deviceLen; + var descriptionLen = lengthBytesUTF8(info.description); + WebGPU.setStringView(infoStruct + 28, strPtr, descriptionLen); + strPtr += descriptionLen; + HEAP32[(((infoStruct) + (36)) >> 2)] = 2; + var adapterType = info.isFallbackAdapter ? 3 : 4; + HEAP32[(((infoStruct) + (40)) >> 2)] = adapterType; + HEAPU32[(((infoStruct) + (44)) >> 2)] = 0; + HEAPU32[(((infoStruct) + (48)) >> 2)] = 0; + WebGPU.iterateExtensions(infoStruct, { + 327739: ext => { + let configCount = 0; + let configsPtr = 0; + if (info.subgroupMatrixConfigs) { + configCount = info.subgroupMatrixConfigs.length; + configsPtr = _malloc(configCount * 20); + for (const [i, cfg] of info.subgroupMatrixConfigs.entries()) { + const ptr = configsPtr + i * 20; + const componentType = WebGPU.SubgroupMatrixComponentType.indexOf(cfg.componentType); + const resultComponentType = WebGPU.SubgroupMatrixComponentType.indexOf(cfg.resultComponentType); + HEAP32[((ptr) >> 2)] = componentType; + HEAP32[(((ptr) + (4)) >> 2)] = resultComponentType; + HEAPU32[(((ptr) + (8)) >> 2)] = cfg.M; + HEAPU32[(((ptr) + (12)) >> 2)] = cfg.N; + HEAPU32[(((ptr) + (16)) >> 2)] = cfg.K; + } + } + HEAPU32[(((ext) + (12)) >> 2)] = configsPtr; + HEAPU32[(((ext) + (8)) >> 2)] = configCount; + } + }); + }, + AddressMode: [ , "clamp-to-edge", "repeat", "mirror-repeat" ], + BlendFactor: [ , "zero", "one", "src", "one-minus-src", "src-alpha", "one-minus-src-alpha", "dst", "one-minus-dst", "dst-alpha", "one-minus-dst-alpha", "src-alpha-saturated", "constant", "one-minus-constant", "src1", "one-minus-src1", "src1-alpha", "one-minus-src1-alpha" ], + BlendOperation: [ , "add", "subtract", "reverse-subtract", "min", "max" ], + BufferBindingType: [ , , "uniform", "storage", "read-only-storage" ], + BufferMapState: [ , "unmapped", "pending", "mapped" ], + CompareFunction: [ , "never", "less", "equal", "less-equal", "greater", "not-equal", "greater-equal", "always" ], + CompilationInfoRequestStatus: [ , "success", "callback-cancelled" ], + ComponentSwizzle: [ , "0", "1", "r", "g", "b", "a" ], + CompositeAlphaMode: [ , "opaque", "premultiplied", "unpremultiplied", "inherit" ], + CullMode: [ , "none", "front", "back" ], + ErrorFilter: [ , "validation", "out-of-memory", "internal" ], + FeatureLevel: [ , "compatibility", "core" ], + FeatureName: { + 1: "core-features-and-limits", + 2: "depth-clip-control", + 3: "depth32float-stencil8", + 4: "texture-compression-bc", + 5: "texture-compression-bc-sliced-3d", + 6: "texture-compression-etc2", + 7: "texture-compression-astc", + 8: "texture-compression-astc-sliced-3d", + 9: "timestamp-query", + 10: "indirect-first-instance", + 11: "shader-f16", + 12: "rg11b10ufloat-renderable", + 13: "bgra8unorm-storage", + 14: "float32-filterable", + 15: "float32-blendable", + 16: "clip-distances", + 17: "dual-source-blending", + 18: "subgroups", + 19: "texture-formats-tier1", + 20: "texture-formats-tier2", + 21: "primitive-index", + 22: "texture-component-swizzle", + 23: "subgroup-size-control", + 327692: "chromium-experimental-unorm16-texture-formats", + 327729: "chromium-experimental-multi-draw-indirect", + 327732: "chromium-experimental-subgroup-matrix" + }, + FilterMode: [ , "nearest", "linear" ], + FrontFace: [ , "ccw", "cw" ], + IndexFormat: [ , "uint16", "uint32" ], + InstanceFeatureName: [ , "timed-wait-any", "shader-source-spirv", "multiple-devices-per-adapter" ], + LoadOp: [ , "load", "clear" ], + MipmapFilterMode: [ , "nearest", "linear" ], + OptionalBool: [ "false", "true" ], + PowerPreference: [ , "low-power", "high-performance" ], + PredefinedColorSpace: [ , "srgb", "display-p3" ], + PrimitiveTopology: [ , "point-list", "line-list", "line-strip", "triangle-list", "triangle-strip" ], + QueryType: [ , "occlusion", "timestamp" ], + SamplerBindingType: [ , , "filtering", "non-filtering", "comparison" ], + Status: [ , "success", "error" ], + StencilOperation: [ , "keep", "zero", "replace", "invert", "increment-clamp", "decrement-clamp", "increment-wrap", "decrement-wrap" ], + StorageTextureAccess: [ , , "write-only", "read-only", "read-write" ], + StoreOp: [ , "store", "discard" ], + SubgroupMatrixComponentType: [ , "f32", "f16", "u32", "i32", "u8", "i8" ], + SurfaceGetCurrentTextureStatus: [ , "success-optimal", "success-suboptimal", "timeout", "outdated", "lost", "error" ], + TextureAspect: [ , "all", "stencil-only", "depth-only" ], + TextureDimension: [ , "1d", "2d", "3d" ], + TextureFormat: [ , "r8unorm", "r8snorm", "r8uint", "r8sint", "r16unorm", "r16snorm", "r16uint", "r16sint", "r16float", "rg8unorm", "rg8snorm", "rg8uint", "rg8sint", "r32float", "r32uint", "r32sint", "rg16unorm", "rg16snorm", "rg16uint", "rg16sint", "rg16float", "rgba8unorm", "rgba8unorm-srgb", "rgba8snorm", "rgba8uint", "rgba8sint", "bgra8unorm", "bgra8unorm-srgb", "rgb10a2uint", "rgb10a2unorm", "rg11b10ufloat", "rgb9e5ufloat", "rg32float", "rg32uint", "rg32sint", "rgba16unorm", "rgba16snorm", "rgba16uint", "rgba16sint", "rgba16float", "rgba32float", "rgba32uint", "rgba32sint", "stencil8", "depth16unorm", "depth24plus", "depth24plus-stencil8", "depth32float", "depth32float-stencil8", "bc1-rgba-unorm", "bc1-rgba-unorm-srgb", "bc2-rgba-unorm", "bc2-rgba-unorm-srgb", "bc3-rgba-unorm", "bc3-rgba-unorm-srgb", "bc4-r-unorm", "bc4-r-snorm", "bc5-rg-unorm", "bc5-rg-snorm", "bc6h-rgb-ufloat", "bc6h-rgb-float", "bc7-rgba-unorm", "bc7-rgba-unorm-srgb", "etc2-rgb8unorm", "etc2-rgb8unorm-srgb", "etc2-rgb8a1unorm", "etc2-rgb8a1unorm-srgb", "etc2-rgba8unorm", "etc2-rgba8unorm-srgb", "eac-r11unorm", "eac-r11snorm", "eac-rg11unorm", "eac-rg11snorm", "astc-4x4-unorm", "astc-4x4-unorm-srgb", "astc-5x4-unorm", "astc-5x4-unorm-srgb", "astc-5x5-unorm", "astc-5x5-unorm-srgb", "astc-6x5-unorm", "astc-6x5-unorm-srgb", "astc-6x6-unorm", "astc-6x6-unorm-srgb", "astc-8x5-unorm", "astc-8x5-unorm-srgb", "astc-8x6-unorm", "astc-8x6-unorm-srgb", "astc-8x8-unorm", "astc-8x8-unorm-srgb", "astc-10x5-unorm", "astc-10x5-unorm-srgb", "astc-10x6-unorm", "astc-10x6-unorm-srgb", "astc-10x8-unorm", "astc-10x8-unorm-srgb", "astc-10x10-unorm", "astc-10x10-unorm-srgb", "astc-12x10-unorm", "astc-12x10-unorm-srgb", "astc-12x12-unorm", "astc-12x12-unorm-srgb" ], + TextureSampleType: [ , , "float", "unfilterable-float", "depth", "sint", "uint" ], + TextureViewDimension: [ , "1d", "2d", "2d-array", "cube", "cube-array", "3d" ], + ToneMappingMode: [ , "standard", "extended" ], + VertexFormat: [ , "uint8", "uint8x2", "uint8x4", "sint8", "sint8x2", "sint8x4", "unorm8", "unorm8x2", "unorm8x4", "snorm8", "snorm8x2", "snorm8x4", "uint16", "uint16x2", "uint16x4", "sint16", "sint16x2", "sint16x4", "unorm16", "unorm16x2", "unorm16x4", "snorm16", "snorm16x2", "snorm16x4", "float16", "float16x2", "float16x4", "float32", "float32x2", "float32x3", "float32x4", "uint32", "uint32x2", "uint32x3", "uint32x4", "sint32", "sint32x2", "sint32x3", "sint32x4", "unorm10-10-10-2", "unorm8x4-bgra", "snorm10-10-10-2" ], + VertexStepMode: [ , "vertex", "instance" ], + WGSLLanguageFeatureName: [ , "readonly_and_readwrite_storage_textures", "packed_4x8_integer_dot_product", "unrestricted_pointer_parameters", "pointer_composite_access", "uniform_buffer_standard_layout", "subgroup_id", "texture_and_sampler_let", "subgroup_uniformity", "texture_formats_tier1", "linear_indexing", "immediate_address_space", "buffer_view", "swizzle_assignment", "fragment_depth" ] +}; + +var _emscripten_webgpu_get_device = () => { + if (WebGPU.preinitializedDeviceId === undefined) { + WebGPU.preinitializedDeviceId = WebGPU.importJsDevice(Module["preinitializedWebGPUDevice"]); + // Some users depend on this keeping the device alive, so we add an + // additional reference when we first initialize it. + _wgpuDeviceAddRef(WebGPU.preinitializedDeviceId); + } + _wgpuDeviceAddRef(WebGPU.preinitializedDeviceId); + return WebGPU.preinitializedDeviceId; +}; + +var _emwgpuBufferDestroy = bufferPtr => { + var buffer = WebGPU.getJsObject(bufferPtr); + var onUnmap = WebGPU.Internals.bufferOnUnmaps[bufferPtr]; + if (onUnmap) { + for (var i = 0; i < onUnmap.length; ++i) { + onUnmap[i](); + } + delete WebGPU.Internals.bufferOnUnmaps[bufferPtr]; + } + buffer.destroy(); +}; + +var _emwgpuBufferGetMappedRange = (bufferPtr, offset, size) => { + var buffer = WebGPU.getJsObject(bufferPtr); + if (size == -1) size = undefined; + var mapped; + try { + mapped = buffer.getMappedRange(offset, size); + } catch (ex) { + return 0; + } + var data = _memalign(16, mapped.byteLength); + HEAPU8.fill(0, data, mapped.byteLength); + WebGPU.Internals.bufferOnUnmaps[bufferPtr].push(() => { + new Uint8Array(mapped).set(HEAPU8.subarray(data, data + mapped.byteLength)); + _free(data); + }); + return data; +}; + +var _emwgpuBufferUnmap = bufferPtr => { + var buffer = WebGPU.getJsObject(bufferPtr); + var onUnmap = WebGPU.Internals.bufferOnUnmaps[bufferPtr]; + if (!onUnmap) { + // Already unmapped + return; + } + for (var i = 0; i < onUnmap.length; ++i) { + onUnmap[i](); + } + delete WebGPU.Internals.bufferOnUnmaps[bufferPtr]; + buffer.unmap(); +}; + +var _emwgpuDelete = ptr => { + delete WebGPU.Internals.jsObjects[ptr]; +}; + +var _emwgpuDeviceCreateBuffer = (devicePtr, descriptor, bufferPtr) => { + var mappedAtCreation = !!(HEAPU32[(((descriptor) + (32)) >> 2)]); + var desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "usage": HEAPU32[(((descriptor) + (16)) >> 2)], + "size": readI53FromI64((descriptor) + (24)), + "mappedAtCreation": mappedAtCreation + }; + var device = WebGPU.getJsObject(devicePtr); + var buffer; + try { + buffer = device.createBuffer(desc); + } catch (ex) { + // The only exception should be RangeError if mapping at creation ran out of memory. + return false; + } + WebGPU.Internals.jsObjectInsert(bufferPtr, buffer); + if (mappedAtCreation) { + WebGPU.Internals.bufferOnUnmaps[bufferPtr] = []; + } + return true; +}; + +var _emwgpuDeviceCreateComputePipelineAsync = function(devicePtr, futureId_low, futureId_high, descriptor, pipelinePtr) { + var futureId = convertI32PairToI53Checked(futureId_low, futureId_high); + var desc = WebGPU.makeComputePipelineDesc(descriptor); + var device = WebGPU.getJsObject(devicePtr); + // createComputePipelineAsync + WebGPU.Internals.futureInsert(futureId, device.createComputePipelineAsync(desc).then(pipeline => { + // createComputePipelineAsync fulfilled + callUserCallback(() => { + WebGPU.Internals.jsObjectInsert(pipelinePtr, pipeline); + _emwgpuOnCreateComputePipelineCompleted(futureId, 1, pipelinePtr, 0); + }); + }, pipelineError => { + // createComputePipelineAsync rejected + callUserCallback(() => { + var sp = stackSave(); + var messagePtr = stringToUTF8OnStack(pipelineError.message); + var status = pipelineError.reason === "validation" ? 3 : pipelineError.reason === "internal" ? 4 : 0; + _emwgpuOnCreateComputePipelineCompleted(futureId, status, pipelinePtr, messagePtr); + stackRestore(sp); + }); + })); +}; + +var _emwgpuDeviceCreateRenderPipelineAsync = function(devicePtr, futureId_low, futureId_high, descriptor, pipelinePtr) { + var futureId = convertI32PairToI53Checked(futureId_low, futureId_high); + var desc = WebGPU.makeRenderPipelineDesc(descriptor); + var device = WebGPU.getJsObject(devicePtr); + // createRenderPipelineAsync + WebGPU.Internals.futureInsert(futureId, device.createRenderPipelineAsync(desc).then(pipeline => { + // createRenderPipelineAsync fulfilled + callUserCallback(() => { + WebGPU.Internals.jsObjectInsert(pipelinePtr, pipeline); + _emwgpuOnCreateRenderPipelineCompleted(futureId, 1, pipelinePtr, 0); + }); + }, pipelineError => { + // createRenderPipelineAsync rejected + callUserCallback(() => { + var sp = stackSave(); + var messagePtr = stringToUTF8OnStack(pipelineError.message); + var status = pipelineError.reason === "validation" ? 3 : pipelineError.reason === "internal" ? 4 : 0; + _emwgpuOnCreateRenderPipelineCompleted(futureId, status, pipelinePtr, messagePtr); + stackRestore(sp); + }); + })); +}; + +var _emwgpuDeviceCreateShaderModule = (devicePtr, descriptor, shaderModulePtr) => { + var nextInChainPtr = HEAPU32[((descriptor) >> 2)]; + var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)]; + var desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "code": "" + }; + switch (sType) { + case 2: + { + desc["code"] = WebGPU.makeStringFromStringView(nextInChainPtr + 8); + break; + } + } + var device = WebGPU.getJsObject(devicePtr); + WebGPU.Internals.jsObjectInsert(shaderModulePtr, device.createShaderModule(desc)); +}; + +var _emwgpuDeviceDestroy = devicePtr => { + const device = WebGPU.getJsObject(devicePtr); + // Remove the onuncapturederror handler which holds a pointer to the WGPUDevice. + device.onuncapturederror = null; + device.destroy(); +}; + +var _emwgpuWaitAny = (futurePtr, futureCount, timeoutMSPtr) => { + abort("TODO: Implement asyncify-free WaitAny for timeout=0"); +}; + +var ENV = {}; + +var getExecutableName = () => thisProgram; + +var getEnvStrings = () => { + if (!getEnvStrings.strings) { + // Default values. + var lang = (globalThis.navigator?.language ?? "C").replace("-", "_") + ".UTF-8"; + var env = { + "USER": "web_user", + "LOGNAME": "web_user", + "PATH": "/", + "PWD": "/", + "HOME": "/home/web_user", + "LANG": lang, + "_": getExecutableName() + }; + // Apply the user-provided values, if any. + for (var x in ENV) { + // x is a key in ENV; if ENV[x] is undefined, that means it was + // explicitly set to be so. We allow user code to do that to + // force variables with default values to remain unset. + if (ENV[x] === undefined) delete env[x]; else env[x] = ENV[x]; + } + var strings = []; + for (var x in env) { + strings.push(`${x}=${env[x]}`); + } + getEnvStrings.strings = strings; + } + return getEnvStrings.strings; +}; + +var _environ_get = (__environ, environ_buf) => { + var bufSize = 0; + var envp = 0; + for (var string of getEnvStrings()) { + var ptr = environ_buf + bufSize; + HEAPU32[(((__environ) + (envp)) >> 2)] = ptr; + bufSize += stringToUTF8(string, ptr, Infinity) + 1; + envp += 4; + } + return 0; +}; + +var _environ_sizes_get = (penviron_count, penviron_buf_size) => { + var strings = getEnvStrings(); + HEAPU32[((penviron_count) >> 2)] = strings.length; + var bufSize = 0; + for (var string of strings) { + bufSize += lengthBytesUTF8(string) + 1; + } + HEAPU32[((penviron_buf_size) >> 2)] = bufSize; + return 0; +}; + +function _fd_close(fd) { + try { + var stream = SYSCALLS.getStreamFromFD(fd); + FS.close(stream); + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return e.errno; + } +} + +/** @param {number=} offset */ var doReadv = (stream, iov, iovcnt, offset) => { + var ret = 0; + for (var i = 0; i < iovcnt; i++) { + var ptr = HEAPU32[((iov) >> 2)]; + var len = HEAPU32[(((iov) + (4)) >> 2)]; + iov += 8; + try { + var curr = FS.read(stream, HEAP8, ptr, len, offset); + } catch (e) { + // On a non-blocking stream a subsequent read may would-block after we + // already gathered data. POSIX readv is a single gather-read: return + // what we have rather than failing the whole call. + if (ret > 0 && e instanceof FS.ErrnoError && (e.errno == 6 || e.errno == 6)) { + break; + } + throw e; + } + if (curr < 0) return -1; + ret += curr; + if (curr < len) break; + // nothing more to read + if (typeof offset != "undefined") { + offset += curr; + } + } + return ret; +}; + +function _fd_pread(fd, iov, iovcnt, offset_low, offset_high, pnum) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); + try { + if (isNaN(offset)) return 22; + var stream = SYSCALLS.getStreamFromFD(fd); + var num = doReadv(stream, iov, iovcnt, offset); + HEAPU32[((pnum) >> 2)] = num; + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return e.errno; + } +} + +function _fd_read(fd, iov, iovcnt, pnum) { + try { + var stream = SYSCALLS.getStreamFromFD(fd); + var num = doReadv(stream, iov, iovcnt); + HEAPU32[((pnum) >> 2)] = num; + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return e.errno; + } +} + +function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); + try { + if (isNaN(offset)) return 22; + var stream = SYSCALLS.getStreamFromFD(fd); + FS.llseek(stream, offset, whence); + (tempI64 = [ stream.position >>> 0, (tempDouble = stream.position, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ], + HEAP32[((newOffset) >> 2)] = tempI64[0], HEAP32[(((newOffset) + (4)) >> 2)] = tempI64[1]); + if (stream.getdents && !offset && whence === 0) stream.getdents = null; + // reset readdir state + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return e.errno; + } +} + +/** @param {number=} offset */ var doWritev = (stream, iov, iovcnt, offset) => { + // Gather all iovecs into one contiguous buffer and issue a single + // FS.write, matching POSIX writev's single gather-write semantics (as + // __syscall_sendmsg already does). Per-iovec writes fragment a stream + // socket send into multiple segments, breaking stream byte semantics. + if (iovcnt == 1) { + // Single iovec: write directly from HEAP8, no gather buffer needed. + return FS.write(stream, HEAP8, HEAPU32[((iov) >> 2)], HEAPU32[(((iov) + (4)) >> 2)], offset); + } + var total = 0; + for (var i = 0, p = iov; i < iovcnt; i++, p += 8) { + total += HEAPU32[(((p) + (4)) >> 2)]; + } + var view = new Uint8Array(total); + var voff = 0; + for (var i = 0; i < iovcnt; i++, iov += 8) { + var ptr = HEAPU32[((iov) >> 2)]; + var len = HEAPU32[(((iov) + (4)) >> 2)]; + view.set(HEAPU8.subarray(ptr, ptr + len), voff); + voff += len; + } + return FS.write(stream, view, 0, total, offset); +}; + +function _fd_write(fd, iov, iovcnt, pnum) { + try { + var stream = SYSCALLS.getStreamFromFD(fd); + var num = doWritev(stream, iov, iovcnt); + HEAPU32[((pnum) >> 2)] = num; + return 0; + } catch (e) { + if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e; + return e.errno; + } +} + +var _emscripten_glActiveTexture = x0 => GLctx.activeTexture(x0); + +var _glActiveTexture = _emscripten_glActiveTexture; + +var _emscripten_glAttachShader = (program, shader) => { + GLctx.attachShader(GL.programs[program], GL.shaders[shader]); +}; + +var _glAttachShader = _emscripten_glAttachShader; + +var _emscripten_glBindAttribLocation = (program, index, name) => { + GLctx.bindAttribLocation(GL.programs[program], index, UTF8ToString(name)); +}; + +var _glBindAttribLocation = _emscripten_glBindAttribLocation; + +var _emscripten_glBindBuffer = (target, buffer) => { + // Calling glBindBuffer with an unknown buffer will implicitly create a + // new one. Here we bypass `GL.counter` and directly using the ID passed + // in. + if (buffer && !GL.buffers[buffer]) { + var b = GLctx.createBuffer(); + b.name = buffer; + GL.buffers[buffer] = b; + } + if (target == 34962) { + GLctx.currentArrayBufferBinding = buffer; + } else if (target == 34963) { + GLctx.currentElementArrayBufferBinding = buffer; + } + if (target == 35051) { + // In WebGL 2 glReadPixels entry point, we need to use a different WebGL 2 + // API function call when a buffer is bound to + // GL_PIXEL_PACK_BUFFER_BINDING point, so must keep track whether that + // binding point is non-null to know what is the proper API function to + // call. + GLctx.currentPixelPackBufferBinding = buffer; + } else if (target == 35052) { + // In WebGL 2 gl(Compressed)Tex(Sub)Image[23]D entry points, we need to + // use a different WebGL 2 API function call when a buffer is bound to + // GL_PIXEL_UNPACK_BUFFER_BINDING point, so must keep track whether that + // binding point is non-null to know what is the proper API function to + // call. + GLctx.currentPixelUnpackBufferBinding = buffer; + } + GLctx.bindBuffer(target, GL.buffers[buffer]); +}; + +var _glBindBuffer = _emscripten_glBindBuffer; + +var _emscripten_glBindBufferBase = (target, index, buffer) => { + GLctx.bindBufferBase(target, index, GL.buffers[buffer]); +}; + +var _glBindBufferBase = _emscripten_glBindBufferBase; + +var _emscripten_glBindFramebuffer = (target, framebuffer) => { + GLctx.bindFramebuffer(target, GL.framebuffers[framebuffer]); +}; + +var _glBindFramebuffer = _emscripten_glBindFramebuffer; + +var _emscripten_glBindTexture = (target, texture) => { + GLctx.bindTexture(target, GL.textures[texture]); +}; + +var _glBindTexture = _emscripten_glBindTexture; + +var _emscripten_glBindVertexArray = vao => { + GLctx.bindVertexArray(GL.vaos[vao]); + var ibo = GLctx.getParameter(34965); + GLctx.currentElementArrayBufferBinding = ibo ? (ibo.name | 0) : 0; +}; + +var _glBindVertexArray = _emscripten_glBindVertexArray; + +var _emscripten_glBlendEquation = x0 => GLctx.blendEquation(x0); + +var _glBlendEquation = _emscripten_glBlendEquation; + +var _emscripten_glBlendFunc = (x0, x1) => GLctx.blendFunc(x0, x1); + +var _glBlendFunc = _emscripten_glBlendFunc; + +var _emscripten_glBufferData = (target, size, data, usage) => { + if (GL.currentContext.version >= 2) { + // If size is zero, WebGL would interpret uploading the whole input + // arraybuffer (starting from given offset), which would not make sense in + // WebAssembly, so avoid uploading if size is zero. However we must still + // call bufferData to establish a backing storage of zero bytes. + if (data && size) { + GLctx.bufferData(target, HEAPU8, usage, data, size); + } else { + GLctx.bufferData(target, size, usage); + } + return; + } + // N.b. here first form specifies a heap subarray, second form an integer + // size, so the ?: code here is polymorphic. It is advised to avoid + // randomly mixing both uses in calling code, to avoid any potential JS + // engine JIT issues. + GLctx.bufferData(target, data ? HEAPU8.subarray(data, data + size) : size, usage); +}; + +var _glBufferData = _emscripten_glBufferData; + +var _emscripten_glClear = x0 => GLctx.clear(x0); + +var _glClear = _emscripten_glClear; + +var _emscripten_glClearColor = (x0, x1, x2, x3) => GLctx.clearColor(x0, x1, x2, x3); + +var _glClearColor = _emscripten_glClearColor; + +var convertI32PairToI53 = (lo, hi) => (lo >>> 0) + hi * 4294967296; + +var _emscripten_glClientWaitSync = (sync, flags, timeout_low, timeout_high) => { + // WebGL2 vs GLES3 differences: in GLES3, the timeout parameter is a uint64, where 0xFFFFFFFFFFFFFFFFULL means GL_TIMEOUT_IGNORED. + // In JS, there's no 64-bit value types, so instead timeout is taken to be signed, and GL_TIMEOUT_IGNORED is given value -1. + // Inherently the value accepted in the timeout is lossy, and can't take in arbitrary u64 bit pattern (but most likely doesn't matter) + // See https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.15 + var timeout = convertI32PairToI53(timeout_low, timeout_high); + return GLctx.clientWaitSync(GL.syncs[sync], flags, timeout); +}; + +var _glClientWaitSync = _emscripten_glClientWaitSync; + +var _emscripten_glColorMask = (red, green, blue, alpha) => { + GLctx.colorMask(!!red, !!green, !!blue, !!alpha); +}; + +var _glColorMask = _emscripten_glColorMask; + +var _emscripten_glCompileShader = shader => { + GLctx.compileShader(GL.shaders[shader]); +}; + +var _glCompileShader = _emscripten_glCompileShader; + +var _emscripten_glCreateProgram = () => { + var id = GL.getNewId(GL.programs); + var program = GLctx.createProgram(); + // Store additional information needed for each shader program: + program.name = id; + // Lazy cache results of + // glGetProgramiv(GL_ACTIVE_UNIFORM_MAX_LENGTH/GL_ACTIVE_ATTRIBUTE_MAX_LENGTH/GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH) + program.maxUniformLength = program.maxAttributeLength = program.maxUniformBlockNameLength = 0; + program.uniformIdCounter = 1; + GL.programs[id] = program; + return id; +}; + +var _glCreateProgram = _emscripten_glCreateProgram; + +var _emscripten_glCreateShader = shaderType => { + var id = GL.getNewId(GL.shaders); + GL.shaders[id] = GLctx.createShader(shaderType); + return id; +}; + +var _glCreateShader = _emscripten_glCreateShader; + +var _emscripten_glDeleteBuffers = (n, buffers) => { + for (var i = 0; i < n; i++) { + var id = HEAP32[(((buffers) + (i * 4)) >> 2)]; + var buffer = GL.buffers[id]; + // From spec: "glDeleteBuffers silently ignores 0's and names that do not + // correspond to existing buffer objects." + if (!buffer) continue; + GLctx.deleteBuffer(buffer); + buffer.name = 0; + GL.buffers[id] = null; + if (id == GLctx.currentArrayBufferBinding) GLctx.currentArrayBufferBinding = 0; + if (id == GLctx.currentElementArrayBufferBinding) GLctx.currentElementArrayBufferBinding = 0; + if (id == GLctx.currentPixelPackBufferBinding) GLctx.currentPixelPackBufferBinding = 0; + if (id == GLctx.currentPixelUnpackBufferBinding) GLctx.currentPixelUnpackBufferBinding = 0; + } +}; + +var _glDeleteBuffers = _emscripten_glDeleteBuffers; + +var _emscripten_glDeleteFramebuffers = (n, framebuffers) => { + for (var i = 0; i < n; ++i) { + var id = HEAP32[(((framebuffers) + (i * 4)) >> 2)]; + var framebuffer = GL.framebuffers[id]; + if (!framebuffer) continue; + // GL spec: "glDeleteFramebuffers silently ignores 0s and names that do not correspond to existing framebuffer objects". + GLctx.deleteFramebuffer(framebuffer); + framebuffer.name = 0; + GL.framebuffers[id] = null; + } +}; + +var _glDeleteFramebuffers = _emscripten_glDeleteFramebuffers; + +var _emscripten_glDeleteProgram = id => { + if (!id) return; + var program = GL.programs[id]; + if (!program) { + // glDeleteProgram actually signals an error when deleting a nonexisting + // object, unlike some other GL delete functions. + GL.recordError(1281); + return; + } + GLctx.deleteProgram(program); + program.name = 0; + GL.programs[id] = null; +}; + +var _glDeleteProgram = _emscripten_glDeleteProgram; + +var _emscripten_glDeleteShader = id => { + if (!id) return; + var shader = GL.shaders[id]; + if (!shader) { + // glDeleteShader actually signals an error when deleting a nonexisting + // object, unlike some other GL delete functions. + GL.recordError(1281); + return; + } + GLctx.deleteShader(shader); + GL.shaders[id] = null; +}; + +var _glDeleteShader = _emscripten_glDeleteShader; + +var _emscripten_glDeleteSync = id => { + if (!id) return; + var sync = GL.syncs[id]; + if (!sync) { + // glDeleteSync signals an error when deleting a nonexisting object, unlike some other GL delete functions. + GL.recordError(1281); + return; + } + GLctx.deleteSync(sync); + sync.name = 0; + GL.syncs[id] = null; +}; + +var _glDeleteSync = _emscripten_glDeleteSync; + +var _emscripten_glDeleteTextures = (n, textures) => { + for (var i = 0; i < n; i++) { + var id = HEAP32[(((textures) + (i * 4)) >> 2)]; + var texture = GL.textures[id]; + // GL spec: "glDeleteTextures silently ignores 0s and names that do not + // correspond to existing textures". + if (!texture) continue; + GLctx.deleteTexture(texture); + texture.name = 0; + GL.textures[id] = null; + } +}; + +var _glDeleteTextures = _emscripten_glDeleteTextures; + +var _emscripten_glDeleteVertexArrays = (n, vaos) => { + for (var i = 0; i < n; i++) { + var id = HEAP32[(((vaos) + (i * 4)) >> 2)]; + GLctx.deleteVertexArray(GL.vaos[id]); + GL.vaos[id] = null; + } +}; + +var _glDeleteVertexArrays = _emscripten_glDeleteVertexArrays; + +var _emscripten_glDetachShader = (program, shader) => { + GLctx.detachShader(GL.programs[program], GL.shaders[shader]); +}; + +var _glDetachShader = _emscripten_glDetachShader; + +var _emscripten_glDisable = x0 => GLctx.disable(x0); + +var _glDisable = _emscripten_glDisable; + +var _emscripten_glDisableVertexAttribArray = index => { + var cb = GL.currentContext.clientBuffers[index]; + cb.enabled = false; + GLctx.disableVertexAttribArray(index); +}; + +var _glDisableVertexAttribArray = _emscripten_glDisableVertexAttribArray; + +var _emscripten_glDrawArrays = (mode, first, count) => { + // bind any client-side buffers + GL.preDrawHandleClientVertexAttribBindings(first + count); + GLctx.drawArrays(mode, first, count); + GL.postDrawHandleClientVertexAttribBindings(); +}; + +var _glDrawArrays = _emscripten_glDrawArrays; + +var tempFixedLengthArray = []; + +var _emscripten_glDrawBuffers = (n, bufs) => { + var bufArray = tempFixedLengthArray[n]; + for (var i = 0; i < n; i++) { + bufArray[i] = HEAP32[(((bufs) + (i * 4)) >> 2)]; + } + GLctx.drawBuffers(bufArray); +}; + +var _glDrawBuffers = _emscripten_glDrawBuffers; + +var _emscripten_glEnable = x0 => GLctx.enable(x0); + +var _glEnable = _emscripten_glEnable; + +var _emscripten_glEnableVertexAttribArray = index => { + var cb = GL.currentContext.clientBuffers[index]; + cb.enabled = true; + GLctx.enableVertexAttribArray(index); +}; + +var _glEnableVertexAttribArray = _emscripten_glEnableVertexAttribArray; + +var _emscripten_glFenceSync = (condition, flags) => { + var sync = GLctx.fenceSync(condition, flags); + if (sync) { + var id = GL.getNewId(GL.syncs); + sync.name = id; + GL.syncs[id] = sync; + return id; + } + return 0; +}; + +var _glFenceSync = _emscripten_glFenceSync; + +var _emscripten_glFinish = () => GLctx.finish(); + +var _glFinish = _emscripten_glFinish; + +var _emscripten_glFlush = () => GLctx.flush(); + +var _glFlush = _emscripten_glFlush; + +var _emscripten_glFramebufferTexture2D = (target, attachment, textarget, texture, level) => { + GLctx.framebufferTexture2D(target, attachment, textarget, GL.textures[texture], level); +}; + +var _glFramebufferTexture2D = _emscripten_glFramebufferTexture2D; + +var _emscripten_glFramebufferTextureLayer = (target, attachment, texture, level, layer) => { + GLctx.framebufferTextureLayer(target, attachment, GL.textures[texture], level, layer); +}; + +var _glFramebufferTextureLayer = _emscripten_glFramebufferTextureLayer; + +var _emscripten_glGenBuffers = (n, buffers) => { + GL.genObject(n, buffers, "createBuffer", GL.buffers); +}; + +var _glGenBuffers = _emscripten_glGenBuffers; + +var _emscripten_glGenFramebuffers = (n, ids) => { + GL.genObject(n, ids, "createFramebuffer", GL.framebuffers); +}; + +var _glGenFramebuffers = _emscripten_glGenFramebuffers; + +var _emscripten_glGenTextures = (n, textures) => { + GL.genObject(n, textures, "createTexture", GL.textures); +}; + +var _glGenTextures = _emscripten_glGenTextures; + +var _emscripten_glGenVertexArrays = (n, arrays) => { + GL.genObject(n, arrays, "createVertexArray", GL.vaos); +}; + +var _glGenVertexArrays = _emscripten_glGenVertexArrays; + +var _emscripten_glGetAttribLocation = (program, name) => GLctx.getAttribLocation(GL.programs[program], UTF8ToString(name)); + +var _glGetAttribLocation = _emscripten_glGetAttribLocation; + +var _emscripten_glGetError = () => { + var error = GLctx.getError() || GL.lastError; + GL.lastError = 0; + return error; +}; + +var _glGetError = _emscripten_glGetError; + +var webglGetExtensions = () => { + var exts = getEmscriptenSupportedExtensions(GLctx); + exts = exts.concat(exts.map(e => "GL_" + e)); + return exts; +}; + +var emscriptenWebGLGet = (name_, p, type) => { + // Guard against user passing a null pointer. + // Note that GLES2 spec does not say anything about how passing a null + // pointer should be treated. Testing on desktop core GL 3, the application + // crashes on glGetIntegerv to a null pointer, but better to report an error + // instead of doing anything random. + if (!p) { + GL.recordError(1281); + return; + } + var ret = undefined; + switch (name_) { + // Handle a few trivial GLES values + case 36346: + // GL_SHADER_COMPILER + ret = 1; + break; + + case 36344: + // GL_SHADER_BINARY_FORMATS + if (type != 0 && type != 1) { + GL.recordError(1280); + } + // Do not write anything to the out pointer, since no binary formats are + // supported. + return; + + case 34814: + // GL_NUM_PROGRAM_BINARY_FORMATS + case 36345: + // GL_NUM_SHADER_BINARY_FORMATS + ret = 0; + break; + + case 34466: + // GL_NUM_COMPRESSED_TEXTURE_FORMATS + // WebGL doesn't have GL_NUM_COMPRESSED_TEXTURE_FORMATS (it's obsolete + // since GL_COMPRESSED_TEXTURE_FORMATS returns a JS array that can be + // queried for length), so implement it ourselves to allow C++ GLES2 + // code to get the length. + var formats = GLctx.getParameter(34467); + ret = formats ? formats.length : 0; + break; + + case 33309: + // GL_NUM_EXTENSIONS + if (GL.currentContext.version < 2) { + // Calling GLES3/WebGL2 function with a GLES2/WebGL1 context + GL.recordError(1282); + return; + } + ret = webglGetExtensions().length; + break; + + case 33307: + // GL_MAJOR_VERSION + case 33308: + // GL_MINOR_VERSION + if (GL.currentContext.version < 2) { + GL.recordError(1280); + // GL_INVALID_ENUM + return; + } + ret = name_ == 33307 ? 3 : 0; + // return version 3.0 + break; + } + if (ret === undefined) { + var result = GLctx.getParameter(name_); + switch (typeof result) { + case "number": + ret = result; + break; + + case "boolean": + ret = result ? 1 : 0; + break; + + case "string": + GL.recordError(1280); + // GL_INVALID_ENUM + return; + + case "object": + if (result === null) { + // null is a valid result for some (e.g., which buffer is bound - + // perhaps nothing is bound), but otherwise can mean an invalid + // name_, which we need to report as an error + switch (name_) { + case 34964: + // ARRAY_BUFFER_BINDING + case 35725: + // CURRENT_PROGRAM + case 34965: + // ELEMENT_ARRAY_BUFFER_BINDING + case 36006: + // FRAMEBUFFER_BINDING or DRAW_FRAMEBUFFER_BINDING + case 36007: + // RENDERBUFFER_BINDING + case 32873: + // TEXTURE_BINDING_2D + case 34229: + // WebGL 2 GL_VERTEX_ARRAY_BINDING, or WebGL 1 extension OES_vertex_array_object GL_VERTEX_ARRAY_BINDING_OES + case 36662: + // COPY_READ_BUFFER_BINDING or COPY_READ_BUFFER + case 36663: + // COPY_WRITE_BUFFER_BINDING or COPY_WRITE_BUFFER + case 35053: + // PIXEL_PACK_BUFFER_BINDING + case 35055: + // PIXEL_UNPACK_BUFFER_BINDING + case 36010: + // READ_FRAMEBUFFER_BINDING + case 35097: + // SAMPLER_BINDING + case 35869: + // TEXTURE_BINDING_2D_ARRAY + case 32874: + // TEXTURE_BINDING_3D + case 36389: + // TRANSFORM_FEEDBACK_BINDING + case 35983: + // TRANSFORM_FEEDBACK_BUFFER_BINDING + case 35368: + // UNIFORM_BUFFER_BINDING + case 34068: + { + // TEXTURE_BINDING_CUBE_MAP + ret = 0; + break; + } + + default: + { + GL.recordError(1280); + // GL_INVALID_ENUM + return; + } + } + } else if (result instanceof Float32Array || result instanceof Uint32Array || result instanceof Int32Array || result instanceof Array) { + for (var i = 0; i < result.length; ++i) { + switch (type) { + case 0: + HEAP32[(((p) + (i * 4)) >> 2)] = result[i]; + break; + + case 2: + HEAPF32[(((p) + (i * 4)) >> 2)] = result[i]; + break; + + case 4: + HEAP8[(p) + (i)] = result[i] ? 1 : 0; + break; + } + } + return; + } else { + try { + ret = result.name | 0; + } catch (e) { + GL.recordError(1280); + // GL_INVALID_ENUM + err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`); + return; + } + } + break; + + default: + GL.recordError(1280); + // GL_INVALID_ENUM + err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof (result)}!`); + return; + } + } + switch (type) { + case 1: + writeI53ToI64(p, ret); + break; + + case 0: + HEAP32[((p) >> 2)] = ret; + break; + + case 2: + HEAPF32[((p) >> 2)] = ret; + break; + + case 4: + HEAP8[p] = ret ? 1 : 0; + break; + } +}; + +var _emscripten_glGetFloatv = (name_, p) => emscriptenWebGLGet(name_, p, 2); + +var _glGetFloatv = _emscripten_glGetFloatv; + +var _emscripten_glGetIntegerv = (name_, p) => emscriptenWebGLGet(name_, p, 0); + +var _glGetIntegerv = _emscripten_glGetIntegerv; + +var _emscripten_glGetProgramiv = (program, pname, p) => { + if (!p) { + // GLES2 specification does not specify how to behave if p is a null + // pointer. Since calling this function does not make sense if p == null, + // issue a GL error to notify user about it. + GL.recordError(1281); + return; + } + if (program >= GL.counter) { + GL.recordError(1281); + return; + } + program = GL.programs[program]; + if (pname == 35716) { + // GL_INFO_LOG_LENGTH + var log = GLctx.getProgramInfoLog(program); + if (log === null) log = "(unknown error)"; + HEAP32[((p) >> 2)] = log.length + 1; + } else if (pname == 35719) { + if (!program.maxUniformLength) { + var numActiveUniforms = GLctx.getProgramParameter(program, 35718); + for (var i = 0; i < numActiveUniforms; ++i) { + program.maxUniformLength = Math.max(program.maxUniformLength, GLctx.getActiveUniform(program, i).name.length + 1); + } + } + HEAP32[((p) >> 2)] = program.maxUniformLength; + } else if (pname == 35722) { + if (!program.maxAttributeLength) { + var numActiveAttributes = GLctx.getProgramParameter(program, 35721); + for (var i = 0; i < numActiveAttributes; ++i) { + program.maxAttributeLength = Math.max(program.maxAttributeLength, GLctx.getActiveAttrib(program, i).name.length + 1); + } + } + HEAP32[((p) >> 2)] = program.maxAttributeLength; + } else if (pname == 35381) { + if (!program.maxUniformBlockNameLength) { + var numActiveUniformBlocks = GLctx.getProgramParameter(program, 35382); + for (var i = 0; i < numActiveUniformBlocks; ++i) { + program.maxUniformBlockNameLength = Math.max(program.maxUniformBlockNameLength, GLctx.getActiveUniformBlockName(program, i).length + 1); + } + } + HEAP32[((p) >> 2)] = program.maxUniformBlockNameLength; + } else { + HEAP32[((p) >> 2)] = GLctx.getProgramParameter(program, pname); + } +}; + +var _glGetProgramiv = _emscripten_glGetProgramiv; + +var _emscripten_glGetShaderInfoLog = (shader, maxLength, length, infoLog) => { + var log = GLctx.getShaderInfoLog(GL.shaders[shader]); + if (log === null) log = "(unknown error)"; + var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0; + if (length) HEAP32[((length) >> 2)] = numBytesWrittenExclNull; +}; + +var _glGetShaderInfoLog = _emscripten_glGetShaderInfoLog; + +var _emscripten_glGetShaderiv = (shader, pname, p) => { + if (!p) { + // GLES2 specification does not specify how to behave if p is a null + // pointer. Since calling this function does not make sense if p == null, + // issue a GL error to notify user about it. + GL.recordError(1281); + return; + } + if (pname == 35716) { + // GL_INFO_LOG_LENGTH + var log = GLctx.getShaderInfoLog(GL.shaders[shader]); + if (log === null) log = "(unknown error)"; + // The GLES2 specification says that if the shader has an empty info log, + // a value of 0 is returned. Otherwise the log has a null char appended. + // (An empty string is falsey, so we can just check that instead of + // looking at log.length.) + var logLength = log ? log.length + 1 : 0; + HEAP32[((p) >> 2)] = logLength; + } else if (pname == 35720) { + // GL_SHADER_SOURCE_LENGTH + var source = GLctx.getShaderSource(GL.shaders[shader]); + // source may be a null, or the empty string, both of which are falsey + // values that we report a 0 length for. + var sourceLength = source ? source.length + 1 : 0; + HEAP32[((p) >> 2)] = sourceLength; + } else { + HEAP32[((p) >> 2)] = GLctx.getShaderParameter(GL.shaders[shader], pname); + } +}; + +var _glGetShaderiv = _emscripten_glGetShaderiv; + +var _emscripten_glGetString = name_ => { + var ret = GL.stringCache[name_]; + if (!ret) { + switch (name_) { + case 7939: + ret = stringToNewUTF8(webglGetExtensions().join(" ")); + break; + + case 7936: + case 7937: + case 37445: + case 37446: + var s = GLctx.getParameter(name_); + if (!s) { + GL.recordError(1280); + } + ret = s ? stringToNewUTF8(s) : 0; + break; + + case 7938: + var webGLVersion = GLctx.getParameter(7938); + // return GLES version string corresponding to the version of the WebGL context + var glVersion = `OpenGL ES 2.0 (${webGLVersion})`; + if (GL.currentContext.version >= 2) glVersion = `OpenGL ES 3.0 (${webGLVersion})`; + ret = stringToNewUTF8(glVersion); + break; + + case 35724: + var glslVersion = GLctx.getParameter(35724); + // extract the version number 'N.M' from the string 'WebGL GLSL ES N.M ...' + var ver_re = /^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/; + var ver_num = glslVersion.match(ver_re); + if (ver_num !== null) { + if (ver_num[1].length == 3) ver_num[1] = ver_num[1] + "0"; + // ensure minor version has 2 digits + glslVersion = `OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`; + } + ret = stringToNewUTF8(glslVersion); + break; + + default: + GL.recordError(1280); + } + GL.stringCache[name_] = ret; + } + return ret; +}; + +var _glGetString = _emscripten_glGetString; + +var _emscripten_glGetUniformBlockIndex = (program, uniformBlockName) => GLctx.getUniformBlockIndex(GL.programs[program], UTF8ToString(uniformBlockName)); + +var _glGetUniformBlockIndex = _emscripten_glGetUniformBlockIndex; + +/** @suppress {checkTypes} */ var jstoi_q = str => parseInt(str); + +/** @noinline */ var webglGetLeftBracePos = name => name.slice(-1) == "]" && name.lastIndexOf("["); + +var webglPrepareUniformLocationsBeforeFirstUse = program => { + var uniformLocsById = program.uniformLocsById, // Maps GLuint -> WebGLUniformLocation + uniformSizeAndIdsByName = program.uniformSizeAndIdsByName, // Maps name -> [uniform array length, GLuint] + i, j; + // On the first time invocation of glGetUniformLocation on this shader program: + // initialize cache data structures and discover which uniforms are arrays. + if (!uniformLocsById) { + // maps GLint integer locations to WebGLUniformLocations + program.uniformLocsById = uniformLocsById = {}; + // maps integer locations back to uniform name strings, so that we can lazily fetch uniform array locations + program.uniformArrayNamesById = {}; + var numActiveUniforms = GLctx.getProgramParameter(program, 35718); + for (i = 0; i < numActiveUniforms; ++i) { + var u = GLctx.getActiveUniform(program, i); + var nm = u.name; + var sz = u.size; + var lb = webglGetLeftBracePos(nm); + var arrayName = lb > 0 ? nm.slice(0, lb) : nm; + // Assign a new location. + var id = program.uniformIdCounter; + program.uniformIdCounter += sz; + // Eagerly get the location of the uniformArray[0] base element. + // The remaining indices >0 will be left for lazy evaluation to + // improve performance. Those may never be needed to fetch, if the + // application fills arrays always in full starting from the first + // element of the array. + uniformSizeAndIdsByName[arrayName] = [ sz, id ]; + // Store placeholder integers in place that highlight that these + // >0 index locations are array indices pending population. + for (j = 0; j < sz; ++j) { + uniformLocsById[id] = j; + program.uniformArrayNamesById[id++] = arrayName; + } + } + } +}; + +var _emscripten_glGetUniformLocation = (program, name) => { + name = UTF8ToString(name); + if (program = GL.programs[program]) { + webglPrepareUniformLocationsBeforeFirstUse(program); + var uniformLocsById = program.uniformLocsById; + // Maps GLuint -> WebGLUniformLocation + var arrayIndex = 0; + var uniformBaseName = name; + // Invariant: when populating integer IDs for uniform locations, we must + // maintain the precondition that arrays reside in contiguous addresses, + // i.e. for a 'vec4 colors[10];', colors[4] must be at location + // colors[0]+4. However, user might call glGetUniformLocation(program, + // "colors") for an array, so we cannot discover based on the user input + // arguments whether the uniform we are dealing with is an array. The only + // way to discover which uniforms are arrays is to enumerate over all the + // active uniforms in the program. + var leftBrace = webglGetLeftBracePos(name); + // If user passed an array accessor "[index]", parse the array index off the accessor. + if (leftBrace > 0) { + arrayIndex = jstoi_q(name.slice(leftBrace + 1)) >>> 0; + // "index]", coerce parseInt(']') with >>>0 to treat "foo[]" as "foo[0]" and foo[-1] as unsigned out-of-bounds. + uniformBaseName = name.slice(0, leftBrace); + } + // Have we cached the location of this uniform before? + // A pair [array length, GLint of the uniform location] + var sizeAndId = program.uniformSizeAndIdsByName[uniformBaseName]; + // If a uniform with this name exists, and if its index is within the + // array limits (if it's even an array), query the WebGLlocation, or + // return an existing cached location. + if (sizeAndId && arrayIndex < sizeAndId[0]) { + arrayIndex += sizeAndId[1]; + // Add the base location of the uniform to the array index offset. + if ((uniformLocsById[arrayIndex] = uniformLocsById[arrayIndex] || GLctx.getUniformLocation(program, name))) { + return arrayIndex; + } + } + } else { + // N.b. we are currently unable to distinguish between GL program IDs that + // never existed vs GL program IDs that have been deleted, so report + // GL_INVALID_VALUE in both cases. + GL.recordError(1281); + } + return -1; +}; + +var _glGetUniformLocation = _emscripten_glGetUniformLocation; + +var _emscripten_glLineWidth = x0 => GLctx.lineWidth(x0); + +var _glLineWidth = _emscripten_glLineWidth; + +var _emscripten_glLinkProgram = program => { + program = GL.programs[program]; + GLctx.linkProgram(program); + // Invalidate earlier computed uniform->ID mappings, those have now become stale + program.uniformLocsById = 0; + // Mark as null-like so that glGetUniformLocation() knows to populate this again. + program.uniformSizeAndIdsByName = {}; +}; + +var _glLinkProgram = _emscripten_glLinkProgram; + +var _emscripten_glPixelStorei = (pname, param) => { + if (pname == 3317) { + GL.unpackAlignment = param; + } else if (pname == 3314) { + GL.unpackRowLength = param; + } + GLctx.pixelStorei(pname, param); +}; + +var _glPixelStorei = _emscripten_glPixelStorei; + +var computeUnpackAlignedImageSize = (width, height, sizePerPixel) => { + function roundedToNextMultipleOf(x, y) { + return (x + y - 1) & -y; + } + var plainRowSize = (GL.unpackRowLength || width) * sizePerPixel; + var alignedRowSize = roundedToNextMultipleOf(plainRowSize, GL.unpackAlignment); + return height * alignedRowSize; +}; + +var colorChannelsInGlTextureFormat = format => { + // Micro-optimizations for size: map format to size by subtracting smallest + // enum value (0x1902) from all values first. Also omit the most common + // size value (1) from the list, which is assumed by formats not on the + // list. + var colorChannels = { + // 0x1902 /* GL_DEPTH_COMPONENT */ - 0x1902: 1, + // 0x1906 /* GL_ALPHA */ - 0x1902: 1, + 5: 3, + 6: 4, + // 0x1909 /* GL_LUMINANCE */ - 0x1902: 1, + 8: 2, + 29502: 3, + 29504: 4, + // 0x1903 /* GL_RED */ - 0x1902: 1, + 26917: 2, + 26918: 2, + // 0x8D94 /* GL_RED_INTEGER */ - 0x1902: 1, + 29846: 3, + 29847: 4 + }; + return colorChannels[format - 6402] || 1; +}; + +var heapObjectForWebGLType = type => { + // Micro-optimization for size: Subtract lowest GL enum number (0x1400/* GL_BYTE */) from type to compare + // smaller values for the heap, for shorter generated code size. + // Also the type HEAPU16 is not tested for explicitly, but any unrecognized type will return out HEAPU16. + // (since most types are HEAPU16) + type -= 5120; + if (type == 0) return HEAP8; + if (type == 1) return HEAPU8; + if (type == 2) return HEAP16; + if (type == 4) return HEAP32; + if (type == 6) return HEAPF32; + if (type == 5 || type == 28922 || type == 28520 || type == 30779 || type == 30782) return HEAPU32; + return HEAPU16; +}; + +var toTypedArrayIndex = (pointer, heap) => pointer >>> (31 - Math.clz32(heap.BYTES_PER_ELEMENT)); + +var emscriptenWebGLGetTexPixelData = (type, format, width, height, pixels) => { + var heap = heapObjectForWebGLType(type); + var sizePerPixel = colorChannelsInGlTextureFormat(format) * heap.BYTES_PER_ELEMENT; + var bytes = computeUnpackAlignedImageSize(width, height, sizePerPixel); + return heap.subarray(toTypedArrayIndex(pixels, heap), toTypedArrayIndex(pixels + bytes, heap)); +}; + +var _emscripten_glReadPixels = (x, y, width, height, format, type, pixels) => { + if (GL.currentContext.version >= 2) { + if (GLctx.currentPixelPackBufferBinding) { + GLctx.readPixels(x, y, width, height, format, type, pixels); + return; + } + var heap = heapObjectForWebGLType(type); + var target = toTypedArrayIndex(pixels, heap); + GLctx.readPixels(x, y, width, height, format, type, heap, target); + return; + } + var pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels); + if (!pixelData) { + GL.recordError(1280); + return; + } + GLctx.readPixels(x, y, width, height, format, type, pixelData); +}; + +var _glReadPixels = _emscripten_glReadPixels; + +var _emscripten_glShaderSource = (shader, count, string, length) => { + var source = GL.getSource(shader, count, string, length); + GLctx.shaderSource(GL.shaders[shader], source); +}; + +var _glShaderSource = _emscripten_glShaderSource; + +var _emscripten_glTexImage2D = (target, level, internalFormat, width, height, border, format, type, pixels) => { + if (GL.currentContext.version >= 2) { + if (GLctx.currentPixelUnpackBufferBinding) { + GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels); + return; + } + if (pixels) { + var heap = heapObjectForWebGLType(type); + var index = toTypedArrayIndex(pixels, heap); + GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, heap, index); + return; + } + } + var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels) : null; + GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixelData); +}; + +var _glTexImage2D = _emscripten_glTexImage2D; + +var _emscripten_glTexParameterf = (x0, x1, x2) => GLctx.texParameterf(x0, x1, x2); + +var _glTexParameterf = _emscripten_glTexParameterf; + +var _emscripten_glTexParameterfv = (target, pname, params) => { + var param = HEAPF32[((params) >> 2)]; + GLctx.texParameterf(target, pname, param); +}; + +var _glTexParameterfv = _emscripten_glTexParameterfv; + +var _emscripten_glTexParameteri = (x0, x1, x2) => GLctx.texParameteri(x0, x1, x2); + +var _glTexParameteri = _emscripten_glTexParameteri; + +var _emscripten_glTexStorage2D = (x0, x1, x2, x3, x4) => GLctx.texStorage2D(x0, x1, x2, x3, x4); + +var _glTexStorage2D = _emscripten_glTexStorage2D; + +var _emscripten_glTexStorage3D = (x0, x1, x2, x3, x4, x5) => GLctx.texStorage3D(x0, x1, x2, x3, x4, x5); + +var _glTexStorage3D = _emscripten_glTexStorage3D; + +var _emscripten_glTexSubImage2D = (target, level, xoffset, yoffset, width, height, format, type, pixels) => { + if (GL.currentContext.version >= 2) { + if (GLctx.currentPixelUnpackBufferBinding) { + GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); + return; + } + if (pixels) { + var heap = heapObjectForWebGLType(type); + GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, heap, toTypedArrayIndex(pixels, heap)); + return; + } + } + var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels) : null; + GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixelData); +}; + +var _glTexSubImage2D = _emscripten_glTexSubImage2D; + +var _emscripten_glTexSubImage3D = (target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels) => { + if (GLctx.currentPixelUnpackBufferBinding) { + GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels); + } else if (pixels) { + var heap = heapObjectForWebGLType(type); + GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, heap, toTypedArrayIndex(pixels, heap)); + } else { + GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, null); + } +}; + +var _glTexSubImage3D = _emscripten_glTexSubImage3D; + +var webglGetProgramUniformLocation = (program, location) => { + if (program) { + var webglLoc = program.uniformLocsById[location]; + // program.uniformLocsById[location] stores either an integer, or a + // WebGLUniformLocation. + // If an integer, we have not yet bound the location, so do it now. The + // integer value specifies the array index we should bind to. + if (typeof webglLoc == "number") { + program.uniformLocsById[location] = webglLoc = GLctx.getUniformLocation(program, program.uniformArrayNamesById[location] + (webglLoc > 0 ? `[${webglLoc}]` : "")); + } + // Else an already cached WebGLUniformLocation, return it. + return webglLoc; + } else { + GL.recordError(1282); + } +}; + +var webglGetUniformLocation = location => webglGetProgramUniformLocation(GLctx.currentProgram, location); + +var _emscripten_glUniform1f = (location, v0) => { + GLctx.uniform1f(webglGetUniformLocation(location), v0); +}; + +var _glUniform1f = _emscripten_glUniform1f; + +var miniTempWebGLFloatBuffers = []; + +var _emscripten_glUniform1fv = (location, count, value) => { + if (GL.currentContext.version >= 2) { + count && GLctx.uniform1fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count); + return; + } + if (count <= 288) { + // avoid allocation when uploading few enough uniforms + var view = miniTempWebGLFloatBuffers[count]; + for (var i = 0; i < count; ++i) { + view[i] = HEAPF32[(((value) + (4 * i)) >> 2)]; + } + } else { + var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 4) >> 2)); + } + GLctx.uniform1fv(webglGetUniformLocation(location), view); +}; + +var _glUniform1fv = _emscripten_glUniform1fv; + +var _emscripten_glUniform1i = (location, v0) => { + GLctx.uniform1i(webglGetUniformLocation(location), v0); +}; + +var _glUniform1i = _emscripten_glUniform1i; + +var _emscripten_glUniform2f = (location, v0, v1) => { + GLctx.uniform2f(webglGetUniformLocation(location), v0, v1); +}; + +var _glUniform2f = _emscripten_glUniform2f; + +var _emscripten_glUniform2fv = (location, count, value) => { + if (GL.currentContext.version >= 2) { + count && GLctx.uniform2fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count * 2); + return; + } + if (count <= 144) { + // avoid allocation when uploading few enough uniforms + count *= 2; + var view = miniTempWebGLFloatBuffers[count]; + for (var i = 0; i < count; i += 2) { + view[i] = HEAPF32[(((value) + (4 * i)) >> 2)]; + view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)]; + } + } else { + var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 8) >> 2)); + } + GLctx.uniform2fv(webglGetUniformLocation(location), view); +}; + +var _glUniform2fv = _emscripten_glUniform2fv; + +var _emscripten_glUniform3f = (location, v0, v1, v2) => { + GLctx.uniform3f(webglGetUniformLocation(location), v0, v1, v2); +}; + +var _glUniform3f = _emscripten_glUniform3f; + +var _emscripten_glUniform4f = (location, v0, v1, v2, v3) => { + GLctx.uniform4f(webglGetUniformLocation(location), v0, v1, v2, v3); +}; + +var _glUniform4f = _emscripten_glUniform4f; + +var _emscripten_glUniform4fv = (location, count, value) => { + if (GL.currentContext.version >= 2) { + count && GLctx.uniform4fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count * 4); + return; + } + if (count <= 72) { + // avoid allocation when uploading few enough uniforms + var view = miniTempWebGLFloatBuffers[4 * count]; + // hoist the heap out of the loop for size and for pthreads+growth. + var heap = HEAPF32; + value = ((value) >> 2); + count *= 4; + for (var i = 0; i < count; i += 4) { + var dst = value + i; + view[i] = heap[dst]; + view[i + 1] = heap[dst + 1]; + view[i + 2] = heap[dst + 2]; + view[i + 3] = heap[dst + 3]; + } + } else { + var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 16) >> 2)); + } + GLctx.uniform4fv(webglGetUniformLocation(location), view); +}; + +var _glUniform4fv = _emscripten_glUniform4fv; + +var miniTempWebGLIntBuffers = []; + +var _emscripten_glUniform4iv = (location, count, value) => { + if (GL.currentContext.version >= 2) { + count && GLctx.uniform4iv(webglGetUniformLocation(location), HEAP32, ((value) >> 2), count * 4); + return; + } + if (count <= 72) { + // avoid allocation when uploading few enough uniforms + count *= 4; + var view = miniTempWebGLIntBuffers[count]; + for (var i = 0; i < count; i += 4) { + view[i] = HEAP32[(((value) + (4 * i)) >> 2)]; + view[i + 1] = HEAP32[(((value) + (4 * i + 4)) >> 2)]; + view[i + 2] = HEAP32[(((value) + (4 * i + 8)) >> 2)]; + view[i + 3] = HEAP32[(((value) + (4 * i + 12)) >> 2)]; + } + } else { + var view = HEAP32.subarray((((value) >> 2)), ((value + count * 16) >> 2)); + } + GLctx.uniform4iv(webglGetUniformLocation(location), view); +}; + +var _glUniform4iv = _emscripten_glUniform4iv; + +var _emscripten_glUniformBlockBinding = (program, uniformBlockIndex, uniformBlockBinding) => { + program = GL.programs[program]; + GLctx.uniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding); +}; + +var _glUniformBlockBinding = _emscripten_glUniformBlockBinding; + +var _emscripten_glUniformMatrix2fv = (location, count, transpose, value) => { + if (GL.currentContext.version >= 2) { + count && GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 4); + return; + } + if (count <= 72) { + // avoid allocation when uploading few enough uniforms + count *= 4; + var view = miniTempWebGLFloatBuffers[count]; + for (var i = 0; i < count; i += 4) { + view[i] = HEAPF32[(((value) + (4 * i)) >> 2)]; + view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)]; + view[i + 2] = HEAPF32[(((value) + (4 * i + 8)) >> 2)]; + view[i + 3] = HEAPF32[(((value) + (4 * i + 12)) >> 2)]; + } + } else { + var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 16) >> 2)); + } + GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, view); +}; + +var _glUniformMatrix2fv = _emscripten_glUniformMatrix2fv; + +var _emscripten_glUniformMatrix3fv = (location, count, transpose, value) => { + if (GL.currentContext.version >= 2) { + count && GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 9); + return; + } + if (count <= 32) { + // avoid allocation when uploading few enough uniforms + count *= 9; + var view = miniTempWebGLFloatBuffers[count]; + for (var i = 0; i < count; i += 9) { + view[i] = HEAPF32[(((value) + (4 * i)) >> 2)]; + view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)]; + view[i + 2] = HEAPF32[(((value) + (4 * i + 8)) >> 2)]; + view[i + 3] = HEAPF32[(((value) + (4 * i + 12)) >> 2)]; + view[i + 4] = HEAPF32[(((value) + (4 * i + 16)) >> 2)]; + view[i + 5] = HEAPF32[(((value) + (4 * i + 20)) >> 2)]; + view[i + 6] = HEAPF32[(((value) + (4 * i + 24)) >> 2)]; + view[i + 7] = HEAPF32[(((value) + (4 * i + 28)) >> 2)]; + view[i + 8] = HEAPF32[(((value) + (4 * i + 32)) >> 2)]; + } + } else { + var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 36) >> 2)); + } + GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, view); +}; + +var _glUniformMatrix3fv = _emscripten_glUniformMatrix3fv; + +var _emscripten_glUniformMatrix4fv = (location, count, transpose, value) => { + if (GL.currentContext.version >= 2) { + count && GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 16); + return; + } + if (count <= 18) { + // avoid allocation when uploading few enough uniforms + var view = miniTempWebGLFloatBuffers[16 * count]; + // hoist the heap out of the loop for size and for pthreads+growth. + var heap = HEAPF32; + value = ((value) >> 2); + count *= 16; + for (var i = 0; i < count; i += 16) { + var dst = value + i; + view[i] = heap[dst]; + view[i + 1] = heap[dst + 1]; + view[i + 2] = heap[dst + 2]; + view[i + 3] = heap[dst + 3]; + view[i + 4] = heap[dst + 4]; + view[i + 5] = heap[dst + 5]; + view[i + 6] = heap[dst + 6]; + view[i + 7] = heap[dst + 7]; + view[i + 8] = heap[dst + 8]; + view[i + 9] = heap[dst + 9]; + view[i + 10] = heap[dst + 10]; + view[i + 11] = heap[dst + 11]; + view[i + 12] = heap[dst + 12]; + view[i + 13] = heap[dst + 13]; + view[i + 14] = heap[dst + 14]; + view[i + 15] = heap[dst + 15]; + } + } else { + var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 64) >> 2)); + } + GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, view); +}; + +var _glUniformMatrix4fv = _emscripten_glUniformMatrix4fv; + +var _emscripten_glUseProgram = program => { + program = GL.programs[program]; + GLctx.useProgram(program); + // Record the currently active program so that we can access the uniform + // mapping table of that program. + GLctx.currentProgram = program; +}; + +var _glUseProgram = _emscripten_glUseProgram; + +var _emscripten_glVertexAttribPointer = (index, size, type, normalized, stride, ptr) => { + var cb = GL.currentContext.clientBuffers[index]; + if (!GLctx.currentArrayBufferBinding) { + cb.size = size; + cb.type = type; + cb.normalized = normalized; + cb.stride = stride; + cb.ptr = ptr; + cb.clientside = true; + cb.vertexAttribPointerAdaptor = /** @this {WebGLRenderingContext} */ function(index, size, type, normalized, stride, ptr) { + this.vertexAttribPointer(index, size, type, normalized, stride, ptr); + }; + return; + } + cb.clientside = false; + GLctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr); +}; + +var _glVertexAttribPointer = _emscripten_glVertexAttribPointer; + +var _emscripten_glViewport = (x0, x1, x2, x3) => GLctx.viewport(x0, x1, x2, x3); + +var _glViewport = _emscripten_glViewport; + +function _mediapipe_find_canvas_event_target(canvasSelector) { + let target = findCanvasEventTarget(canvasSelector); + // WebGPU-on-worker uses this function to try to grab the canvas, but + // doesn't have a DOM element to find. So as a quick patch, if the default + // behavior is unsuccessful here then we try a webgpu canvas property + // which is set by the user directly on the Module, much like how our old + // pipeline used the Module.canvas property. See b/265271517 for details. + if (Module && !target) { + target = Module.canvasWebGpu; + } + return Emval.toHandle(target); +} + +function _mediapipe_webgl_tex_image_drawable(drawableHandle) { + const drawable = Emval.toValue(drawableHandle); + GLctx.texImage2D(GLctx.TEXTURE_2D, 0, GLctx.RGBA, GLctx.RGBA, GLctx.UNSIGNED_BYTE, drawable); +} + +var _random_get = (buffer, size) => randomFill(HEAPU8.subarray(buffer, buffer + size)); + +var _wgpuCommandEncoderBeginComputePass = (encoderPtr, descriptor) => { + var desc; + if (descriptor) { + desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "timestampWrites": WebGPU.makePassTimestampWrites(HEAPU32[(((descriptor) + (12)) >> 2)]) + }; + } + var commandEncoder = WebGPU.getJsObject(encoderPtr); + var ptr = _emwgpuCreateComputePassEncoder(0); + WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.beginComputePass(desc)); + return ptr; +}; + +var _wgpuCommandEncoderBeginRenderPass = (encoderPtr, descriptor) => { + function makeColorAttachment(caPtr) { + var viewPtr = HEAPU32[(((caPtr) + (4)) >> 2)]; + if (viewPtr === 0) { + // Null `view` means no attachment in this slot. + return undefined; + } + var depthSlice = HEAPU32[(((caPtr) + (8)) >> 2)]; + if (depthSlice == 4294967295) depthSlice = undefined; + return { + "view": WebGPU.getJsObject(viewPtr), + "depthSlice": depthSlice, + "resolveTarget": WebGPU.getJsObject(HEAPU32[(((caPtr) + (12)) >> 2)]), + "clearValue": WebGPU.makeColor(caPtr + 24), + "loadOp": WebGPU.LoadOp[HEAP32[(((caPtr) + (16)) >> 2)]], + "storeOp": WebGPU.StoreOp[HEAP32[(((caPtr) + (20)) >> 2)]] + }; + } + function makeColorAttachments(count, caPtr) { + var attachments = []; + for (var i = 0; i < count; ++i) { + attachments.push(makeColorAttachment(caPtr + 56 * i)); + } + return attachments; + } + function makeDepthStencilAttachment(dsaPtr) { + if (dsaPtr === 0) return undefined; + return { + "view": WebGPU.getJsObject(HEAPU32[(((dsaPtr) + (4)) >> 2)]), + "depthClearValue": HEAPF32[(((dsaPtr) + (16)) >> 2)], + "depthLoadOp": WebGPU.LoadOp[HEAP32[(((dsaPtr) + (8)) >> 2)]], + "depthStoreOp": WebGPU.StoreOp[HEAP32[(((dsaPtr) + (12)) >> 2)]], + "depthReadOnly": !!(HEAPU32[(((dsaPtr) + (20)) >> 2)]), + "stencilClearValue": HEAPU32[(((dsaPtr) + (32)) >> 2)], + "stencilLoadOp": WebGPU.LoadOp[HEAP32[(((dsaPtr) + (24)) >> 2)]], + "stencilStoreOp": WebGPU.StoreOp[HEAP32[(((dsaPtr) + (28)) >> 2)]], + "stencilReadOnly": !!(HEAPU32[(((dsaPtr) + (36)) >> 2)]) + }; + } + function makeRenderPassDescriptor(descriptor) { + var nextInChainPtr = HEAPU32[((descriptor) >> 2)]; + var maxDrawCount = undefined; + if (nextInChainPtr !== 0) { + var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)]; + var renderPassMaxDrawCount = nextInChainPtr; + // Note: The user could have passed a really huge value here, which is technically valid in + // C but will not be allowed by WebGPU in JS because of [EnforceRange]. We intentionally + // ignore that case because it's not useful - apps can just pick a smaller maxDrawCount. + maxDrawCount = readI53FromI64((renderPassMaxDrawCount) + (8)); + } + var desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "colorAttachments": makeColorAttachments(HEAPU32[(((descriptor) + (12)) >> 2)], HEAPU32[(((descriptor) + (16)) >> 2)]), + "depthStencilAttachment": makeDepthStencilAttachment(HEAPU32[(((descriptor) + (20)) >> 2)]), + "occlusionQuerySet": WebGPU.getJsObject(HEAPU32[(((descriptor) + (24)) >> 2)]), + "timestampWrites": WebGPU.makePassTimestampWrites(HEAPU32[(((descriptor) + (28)) >> 2)]), + "maxDrawCount": maxDrawCount + }; + return desc; + } + var desc = makeRenderPassDescriptor(descriptor); + var commandEncoder = WebGPU.getJsObject(encoderPtr); + var ptr = _emwgpuCreateRenderPassEncoder(0); + WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.beginRenderPass(desc)); + return ptr; +}; + +var _wgpuCommandEncoderCopyBufferToTexture = (encoderPtr, srcPtr, dstPtr, copySizePtr) => { + var commandEncoder = WebGPU.getJsObject(encoderPtr); + var copySize = WebGPU.makeExtent3D(copySizePtr); + commandEncoder.copyBufferToTexture(WebGPU.makeTexelCopyBufferInfo(srcPtr), WebGPU.makeTexelCopyTextureInfo(dstPtr), copySize); +}; + +var _wgpuCommandEncoderCopyTextureToBuffer = (encoderPtr, srcPtr, dstPtr, copySizePtr) => { + var commandEncoder = WebGPU.getJsObject(encoderPtr); + var copySize = WebGPU.makeExtent3D(copySizePtr); + commandEncoder.copyTextureToBuffer(WebGPU.makeTexelCopyTextureInfo(srcPtr), WebGPU.makeTexelCopyBufferInfo(dstPtr), copySize); +}; + +var _wgpuCommandEncoderCopyTextureToTexture = (encoderPtr, srcPtr, dstPtr, copySizePtr) => { + var commandEncoder = WebGPU.getJsObject(encoderPtr); + var copySize = WebGPU.makeExtent3D(copySizePtr); + commandEncoder.copyTextureToTexture(WebGPU.makeTexelCopyTextureInfo(srcPtr), WebGPU.makeTexelCopyTextureInfo(dstPtr), copySize); +}; + +var _wgpuCommandEncoderFinish = (encoderPtr, descriptor) => { + // TODO: Use the descriptor. + var commandEncoder = WebGPU.getJsObject(encoderPtr); + var ptr = _emwgpuCreateCommandBuffer(0); + WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.finish()); + return ptr; +}; + +var _wgpuComputePassEncoderDispatchWorkgroups = (passPtr, x, y, z) => { + var pass = WebGPU.getJsObject(passPtr); + pass.dispatchWorkgroups(x, y, z); +}; + +var _wgpuComputePassEncoderEnd = passPtr => { + var pass = WebGPU.getJsObject(passPtr); + pass.end(); +}; + +var _wgpuComputePassEncoderSetBindGroup = (passPtr, groupIndex, groupPtr, dynamicOffsetCount, dynamicOffsetsPtr) => { + var pass = WebGPU.getJsObject(passPtr); + var group = WebGPU.getJsObject(groupPtr); + if (dynamicOffsetCount == 0) { + pass.setBindGroup(groupIndex, group); + } else { + pass.setBindGroup(groupIndex, group, HEAPU32, ((dynamicOffsetsPtr) >> 2), dynamicOffsetCount); + } +}; + +var _wgpuComputePassEncoderSetPipeline = (passPtr, pipelinePtr) => { + var pass = WebGPU.getJsObject(passPtr); + var pipeline = WebGPU.getJsObject(pipelinePtr); + pass.setPipeline(pipeline); +}; + +var _wgpuComputePipelineGetBindGroupLayout = (pipelinePtr, groupIndex) => { + var pipeline = WebGPU.getJsObject(pipelinePtr); + var ptr = _emwgpuCreateBindGroupLayout(0); + WebGPU.Internals.jsObjectInsert(ptr, pipeline.getBindGroupLayout(groupIndex)); + return ptr; +}; + +var _wgpuDeviceCreateBindGroup = (devicePtr, descriptor) => { + function makeEntry(entryPtr) { + var bufferPtr = HEAPU32[(((entryPtr) + (8)) >> 2)]; + var samplerPtr = HEAPU32[(((entryPtr) + (32)) >> 2)]; + var textureViewPtr = HEAPU32[(((entryPtr) + (36)) >> 2)]; + var externalTexturePtr = 0; + WebGPU.iterateExtensions(entryPtr, { + 14: ptr => { + externalTexturePtr = HEAPU32[(((ptr) + (8)) >> 2)]; + } + }); + var resource; + if (bufferPtr) { + // Note the sentinel UINT64_MAX will be read as -1. + var size = readI53FromI64((entryPtr) + (24)); + if (size == -1) size = undefined; + resource = { + "buffer": WebGPU.getJsObject(bufferPtr), + "offset": readI53FromI64((entryPtr) + (16)), + "size": size + }; + } else { + resource = WebGPU.getJsObject(samplerPtr || textureViewPtr || externalTexturePtr); + } + return { + "binding": HEAPU32[(((entryPtr) + (4)) >> 2)], + "resource": resource + }; + } + function makeEntries(count, entriesPtrs) { + var entries = []; + for (var i = 0; i < count; ++i) { + entries.push(makeEntry(entriesPtrs + 40 * i)); + } + return entries; + } + var desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "layout": WebGPU.getJsObject(HEAPU32[(((descriptor) + (12)) >> 2)]), + "entries": makeEntries(HEAPU32[(((descriptor) + (16)) >> 2)], HEAPU32[(((descriptor) + (20)) >> 2)]) + }; + var device = WebGPU.getJsObject(devicePtr); + var ptr = _emwgpuCreateBindGroup(0); + WebGPU.Internals.jsObjectInsert(ptr, device.createBindGroup(desc)); + return ptr; +}; + +var _wgpuDeviceCreateBindGroupLayout = (devicePtr, descriptor) => { + function makeBufferEntry(substructPtr) { + var typeInt = HEAPU32[(((substructPtr) + (4)) >> 2)]; + if (!typeInt) return undefined; + return { + "type": WebGPU.BufferBindingType[typeInt], + "hasDynamicOffset": !!(HEAPU32[(((substructPtr) + (8)) >> 2)]), + "minBindingSize": readI53FromI64((substructPtr) + (16)) + }; + } + function makeSamplerEntry(substructPtr) { + var typeInt = HEAPU32[(((substructPtr) + (4)) >> 2)]; + if (!typeInt) return undefined; + return { + "type": WebGPU.SamplerBindingType[typeInt] + }; + } + function makeTextureEntry(substructPtr) { + var sampleTypeInt = HEAPU32[(((substructPtr) + (4)) >> 2)]; + if (!sampleTypeInt) return undefined; + return { + "sampleType": WebGPU.TextureSampleType[sampleTypeInt], + "viewDimension": WebGPU.TextureViewDimension[HEAP32[(((substructPtr) + (8)) >> 2)]], + "multisampled": !!(HEAPU32[(((substructPtr) + (12)) >> 2)]) + }; + } + function makeStorageTextureEntry(substructPtr) { + var accessInt = HEAPU32[(((substructPtr) + (4)) >> 2)]; + if (!accessInt) return undefined; + return { + "access": WebGPU.StorageTextureAccess[accessInt], + "format": WebGPU.TextureFormat[HEAP32[(((substructPtr) + (8)) >> 2)]], + "viewDimension": WebGPU.TextureViewDimension[HEAP32[(((substructPtr) + (12)) >> 2)]] + }; + } + function makeEntry(entryPtr) { + var entry = { + "binding": HEAPU32[(((entryPtr) + (4)) >> 2)], + "visibility": HEAPU32[(((entryPtr) + (8)) >> 2)], + "buffer": makeBufferEntry(entryPtr + 24), + "sampler": makeSamplerEntry(entryPtr + 48), + "texture": makeTextureEntry(entryPtr + 56), + "storageTexture": makeStorageTextureEntry(entryPtr + 72) + }; + WebGPU.iterateExtensions(entryPtr, { + 13: ptr => { + entry["externalTexture"] = {}; + } + }); + return entry; + } + function makeEntries(count, entriesPtrs) { + var entries = []; + for (var i = 0; i < count; ++i) { + entries.push(makeEntry(entriesPtrs + 88 * i)); + } + return entries; + } + var desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "entries": makeEntries(HEAPU32[(((descriptor) + (12)) >> 2)], HEAPU32[(((descriptor) + (16)) >> 2)]) + }; + var device = WebGPU.getJsObject(devicePtr); + var ptr = _emwgpuCreateBindGroupLayout(0); + WebGPU.Internals.jsObjectInsert(ptr, device.createBindGroupLayout(desc)); + return ptr; +}; + +var _wgpuDeviceCreateCommandEncoder = (devicePtr, descriptor) => { + var desc; + if (descriptor) { + desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4) + }; + } + var device = WebGPU.getJsObject(devicePtr); + var ptr = _emwgpuCreateCommandEncoder(0); + WebGPU.Internals.jsObjectInsert(ptr, device.createCommandEncoder(desc)); + return ptr; +}; + +var _wgpuDeviceCreateComputePipeline = (devicePtr, descriptor) => { + var desc = WebGPU.makeComputePipelineDesc(descriptor); + var device = WebGPU.getJsObject(devicePtr); + var ptr = _emwgpuCreateComputePipeline(0); + WebGPU.Internals.jsObjectInsert(ptr, device.createComputePipeline(desc)); + return ptr; +}; + +var _wgpuDeviceCreatePipelineLayout = (devicePtr, descriptor) => { + var bglCount = HEAPU32[(((descriptor) + (12)) >> 2)]; + var bglPtr = HEAPU32[(((descriptor) + (16)) >> 2)]; + var bgls = []; + for (var i = 0; i < bglCount; ++i) { + bgls.push(WebGPU.getJsObject(HEAPU32[(((bglPtr) + (4 * i)) >> 2)])); + } + var desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "bindGroupLayouts": bgls, + "immediateSize": HEAPU32[(((descriptor) + (20)) >> 2)] + }; + var device = WebGPU.getJsObject(devicePtr); + var ptr = _emwgpuCreatePipelineLayout(0); + WebGPU.Internals.jsObjectInsert(ptr, device.createPipelineLayout(desc)); + return ptr; +}; + +var _wgpuDeviceCreateRenderPipeline = (devicePtr, descriptor) => { + var desc = WebGPU.makeRenderPipelineDesc(descriptor); + var device = WebGPU.getJsObject(devicePtr); + var ptr = _emwgpuCreateRenderPipeline(0); + WebGPU.Internals.jsObjectInsert(ptr, device.createRenderPipeline(desc)); + return ptr; +}; + +var _wgpuDeviceCreateSampler = (devicePtr, descriptor) => { + var desc; + if (descriptor) { + desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "addressModeU": WebGPU.AddressMode[HEAP32[(((descriptor) + (12)) >> 2)]], + "addressModeV": WebGPU.AddressMode[HEAP32[(((descriptor) + (16)) >> 2)]], + "addressModeW": WebGPU.AddressMode[HEAP32[(((descriptor) + (20)) >> 2)]], + "magFilter": WebGPU.FilterMode[HEAP32[(((descriptor) + (24)) >> 2)]], + "minFilter": WebGPU.FilterMode[HEAP32[(((descriptor) + (28)) >> 2)]], + "mipmapFilter": WebGPU.MipmapFilterMode[HEAP32[(((descriptor) + (32)) >> 2)]], + "lodMinClamp": HEAPF32[(((descriptor) + (36)) >> 2)], + "lodMaxClamp": HEAPF32[(((descriptor) + (40)) >> 2)], + "compare": WebGPU.CompareFunction[HEAP32[(((descriptor) + (44)) >> 2)]], + "maxAnisotropy": HEAPU16[(((descriptor) + (48)) >> 1)] + }; + } + var device = WebGPU.getJsObject(devicePtr); + var ptr = _emwgpuCreateSampler(0); + WebGPU.Internals.jsObjectInsert(ptr, device.createSampler(desc)); + return ptr; +}; + +var _wgpuDeviceCreateTexture = (devicePtr, descriptor) => { + var nextInChainPtr = HEAPU32[((descriptor) >> 2)]; + var textureBindingViewDimension; + if (nextInChainPtr !== 0) { + var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)]; + var textureBindingViewDimensionDescriptor = nextInChainPtr; + textureBindingViewDimension = WebGPU.TextureViewDimension[HEAP32[(((textureBindingViewDimensionDescriptor) + (8)) >> 2)]]; + } + var desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "size": WebGPU.makeExtent3D(descriptor + 28), + "mipLevelCount": HEAPU32[(((descriptor) + (44)) >> 2)], + "sampleCount": HEAPU32[(((descriptor) + (48)) >> 2)], + "dimension": WebGPU.TextureDimension[HEAP32[(((descriptor) + (24)) >> 2)]], + "format": WebGPU.TextureFormat[HEAP32[(((descriptor) + (40)) >> 2)]], + "usage": HEAPU32[(((descriptor) + (16)) >> 2)], + "textureBindingViewDimension": textureBindingViewDimension + }; + var viewFormatCount = HEAPU32[(((descriptor) + (52)) >> 2)]; + if (viewFormatCount) { + var viewFormatsPtr = HEAPU32[(((descriptor) + (56)) >> 2)]; + // viewFormatsPtr pointer to an array of TextureFormat which is an enum of size uint32_t + desc["viewFormats"] = Array.from(HEAP32.subarray((((viewFormatsPtr) >> 2)), ((viewFormatsPtr + viewFormatCount * 4) >> 2)), format => WebGPU.TextureFormat[format]); + } + var device = WebGPU.getJsObject(devicePtr); + var ptr = _emwgpuCreateTexture(0); + WebGPU.Internals.jsObjectInsert(ptr, device.createTexture(desc)); + return ptr; +}; + +var _wgpuQueueSubmit = (queuePtr, commandCount, commands) => { + var queue = WebGPU.getJsObject(queuePtr); + var cmds = Array.from(HEAP32.subarray((((commands) >> 2)), ((commands + commandCount * 4) >> 2)), id => WebGPU.getJsObject(id)); + queue.submit(cmds); +}; + +function _wgpuQueueWriteBuffer(queuePtr, bufferPtr, bufferOffset_low, bufferOffset_high, data, size) { + var bufferOffset = convertI32PairToI53Checked(bufferOffset_low, bufferOffset_high); + var queue = WebGPU.getJsObject(queuePtr); + var buffer = WebGPU.getJsObject(bufferPtr); + // There is a size limitation for ArrayBufferView. Work around by passing in a subarray + // instead of the whole heap. crbug.com/1201109 + var subarray = HEAPU8.subarray(data, data + size); + queue.writeBuffer(buffer, bufferOffset, subarray, 0, size); +} + +var _wgpuQueueWriteTexture = (queuePtr, destinationPtr, data, dataSize, dataLayoutPtr, writeSizePtr) => { + var queue = WebGPU.getJsObject(queuePtr); + var destination = WebGPU.makeTexelCopyTextureInfo(destinationPtr); + var dataLayout = WebGPU.makeTexelCopyBufferLayout(dataLayoutPtr); + var writeSize = WebGPU.makeExtent3D(writeSizePtr); + // This subarray isn't strictly necessary, but helps work around an issue + // where Chromium makes a copy of the entire heap. crbug.com/1134457 + var subarray = HEAPU8.subarray(data, data + dataSize); + queue.writeTexture(destination, subarray, dataLayout, writeSize); +}; + +var _wgpuRenderPassEncoderDraw = (passPtr, vertexCount, instanceCount, firstVertex, firstInstance) => { + firstVertex >>>= 0; + firstInstance >>>= 0; + var pass = WebGPU.getJsObject(passPtr); + pass.draw(vertexCount, instanceCount, firstVertex, firstInstance); +}; + +var _wgpuRenderPassEncoderEnd = encoderPtr => { + var encoder = WebGPU.getJsObject(encoderPtr); + encoder.end(); +}; + +var _wgpuRenderPassEncoderSetBindGroup = (passPtr, groupIndex, groupPtr, dynamicOffsetCount, dynamicOffsetsPtr) => { + var pass = WebGPU.getJsObject(passPtr); + var group = WebGPU.getJsObject(groupPtr); + if (dynamicOffsetCount == 0) { + pass.setBindGroup(groupIndex, group); + } else { + pass.setBindGroup(groupIndex, group, HEAPU32, ((dynamicOffsetsPtr) >> 2), dynamicOffsetCount); + } +}; + +var _wgpuRenderPassEncoderSetPipeline = (passPtr, pipelinePtr) => { + var pass = WebGPU.getJsObject(passPtr); + var pipeline = WebGPU.getJsObject(pipelinePtr); + pass.setPipeline(pipeline); +}; + +var _wgpuRenderPipelineGetBindGroupLayout = (pipelinePtr, groupIndex) => { + var pipeline = WebGPU.getJsObject(pipelinePtr); + var ptr = _emwgpuCreateBindGroupLayout(0); + WebGPU.Internals.jsObjectInsert(ptr, pipeline.getBindGroupLayout(groupIndex)); + return ptr; +}; + +var _wgpuTextureCreateView = (texturePtr, descriptor) => { + var desc; + if (descriptor) { + var swizzle; + var nextInChainPtr = HEAPU32[((descriptor) >> 2)]; + if (nextInChainPtr !== 0) { + var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)]; + var swizzleDescriptor = nextInChainPtr; + var swizzlePtr = swizzleDescriptor + 8; + var r = WebGPU.ComponentSwizzle[HEAP32[((swizzlePtr) >> 2)]] || "r"; + var g = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (4)) >> 2)]] || "g"; + var b = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (8)) >> 2)]] || "b"; + var a = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (12)) >> 2)]] || "a"; + swizzle = `${r}${g}${b}${a}`; + } + var mipLevelCount = HEAPU32[(((descriptor) + (24)) >> 2)]; + var arrayLayerCount = HEAPU32[(((descriptor) + (32)) >> 2)]; + desc = { + "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4), + "format": WebGPU.TextureFormat[HEAP32[(((descriptor) + (12)) >> 2)]], + "dimension": WebGPU.TextureViewDimension[HEAP32[(((descriptor) + (16)) >> 2)]], + "baseMipLevel": HEAPU32[(((descriptor) + (20)) >> 2)], + "mipLevelCount": mipLevelCount === 4294967295 ? undefined : mipLevelCount, + "baseArrayLayer": HEAPU32[(((descriptor) + (28)) >> 2)], + "arrayLayerCount": arrayLayerCount === 4294967295 ? undefined : arrayLayerCount, + "aspect": WebGPU.TextureAspect[HEAP32[(((descriptor) + (36)) >> 2)]], + "usage": HEAPU32[(((descriptor) + (40)) >> 2)], + "swizzle": swizzle + }; + } + var texture = WebGPU.getJsObject(texturePtr); + var ptr = _emwgpuCreateTextureView(0); + WebGPU.Internals.jsObjectInsert(ptr, texture.createView(desc)); + return ptr; +}; + +var _wgpuTextureDestroy = texturePtr => { + WebGPU.getJsObject(texturePtr).destroy(); +}; + +var _wgpuTextureGetFormat = texturePtr => { + var texture = WebGPU.getJsObject(texturePtr); + // Should return the enum integer instead of string. + return WebGPU.TextureFormat.indexOf(texture.format); +}; + +var getCFunc = ident => { + var func = Module["_" + ident]; + // closure exported function + return func; +}; + +var writeArrayToMemory = (array, buffer) => { + HEAP8.set(array, buffer); +}; + +/** + * @param {string|null=} returnType + * @param {Array=} argTypes + * @param {Array=} args + * @param {Object=} opts + */ var ccall = (ident, returnType, argTypes, args, opts) => { + // For fast lookup of conversion functions + var toC = { + "string": str => { + var ret = 0; + if (str !== null && str !== undefined && str !== 0) { + // null string + ret = stringToUTF8OnStack(str); + } + return ret; + }, + "array": arr => { + var ret = stackAlloc(arr.length); + writeArrayToMemory(arr, ret); + return ret; + } + }; + function convertReturnValue(ret) { + if (returnType === "string") { + return UTF8ToString(ret); + } + if (returnType === "boolean") return Boolean(ret); + return ret; + } + var func = getCFunc(ident); + var cArgs = []; + var stack = 0; + if (args) { + for (var i = 0; i < args.length; i++) { + var converter = toC[argTypes[i]]; + if (converter) { + if (!stack) stack = stackSave(); + cArgs[i] = converter(args[i]); + } else { + cArgs[i] = args[i]; + } + } + } + var ret = func(...cArgs); + function onDone(ret) { + if (stack) stackRestore(stack); + return convertReturnValue(ret); + } + ret = onDone(ret); + return ret; +}; + +var FS_createPath = (...args) => FS.createPath(...args); + +var FS_unlink = (...args) => FS.unlink(...args); + +var FS_createLazyFile = (...args) => FS.createLazyFile(...args); + +var FS_createDevice = (...args) => FS.createDevice(...args); + +FS.createPreloadedFile = FS_createPreloadedFile; + +FS.preloadFile = FS_preloadFile; + +FS.staticInit(); + +// Signal GL rendering layer that processing of a new frame is about to +// start. This helps it optimize VBO double-buffering and reduce GPU stalls. +registerPreMainLoop(() => GL.newRenderingFrameStarted()); + +for (let i = 0; i < 32; ++i) tempFixedLengthArray.push(new Array(i)); + +var miniTempWebGLFloatBuffersStorage = new Float32Array(288); + +// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive +for (/**@suppress{duplicate}*/ var i = 0; i <= 288; ++i) { + miniTempWebGLFloatBuffers[i] = miniTempWebGLFloatBuffersStorage.subarray(0, i); +} + +var miniTempWebGLIntBuffersStorage = new Int32Array(288); + +// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive +for (/**@suppress{duplicate}*/ var i = 0; i <= 288; ++i) { + miniTempWebGLIntBuffers[i] = miniTempWebGLIntBuffersStorage.subarray(0, i); +} + +// End JS library code +// include: postlibrary.js +// This file is included after the automatically-generated JS library code +// but before the wasm module is created. +{ + // Begin ATMODULES hooks + if (Module["noExitRuntime"]) noExitRuntime = Module["noExitRuntime"]; + if (Module["print"]) out = Module["print"]; + if (Module["printErr"]) err = Module["printErr"]; + // End ATMODULES hooks + if (Module["arguments"]) programArgs = Module["arguments"]; + if (Module["thisProgram"]) thisProgram = Module["thisProgram"]; + var preInit = Module["preInit"]; + if (preInit) { + if (typeof preInit == "function") Module["preInit"] = preInit = [ preInit ]; + // Written as a loop so that preInit functions that themselves add more + // preInit functions. Is this actually needed? + while (preInit.length > 0) { + preInit.shift()(); + } + } +} + +// Begin runtime exports +Module["addRunDependency"] = addRunDependency; + +Module["removeRunDependency"] = removeRunDependency; + +Module["ccall"] = ccall; + +Module["stringToNewUTF8"] = stringToNewUTF8; + +Module["FS_preloadFile"] = FS_preloadFile; + +Module["FS_unlink"] = FS_unlink; + +Module["FS_createPath"] = FS_createPath; + +Module["FS_createDevice"] = FS_createDevice; + +Module["FS_createDataFile"] = FS_createDataFile; + +Module["FS_createLazyFile"] = FS_createLazyFile; + +// End runtime exports +// Begin JS library exports +// End JS library exports +// end include: postlibrary.js +var ASM_CONSTS = { + 1588153: $0 => { + const canvas = Emval.toValue($0); + const context = canvas.getContext("webgpu"); + return WebGPU.importJsTexture(context.getCurrentTexture()); + }, + 1588296: ($0, $1, $2, $3, $4) => { + const drawable = Emval.toValue($0); + const device = WebGPU.getJsObject($1); + const texture = WebGPU.getJsObject($2); + const width = $3; + const height = $4; + device.queue.copyExternalImageToTexture({ + source: drawable + }, { + texture + }, [ width, height ]); + }, + 1588555: ($0, $1, $2, $3) => { + const sourceExtTex = Emval.toValue($0); + const device = WebGPU.getJsObject($1); + const sampler = WebGPU.getJsObject($2); + const bgLayout = WebGPU.getJsObject($3); + const bindGroup = device.createBindGroup({ + layout: bgLayout, + entries: [ { + binding: 0, + resource: sampler + }, { + binding: 1, + resource: sourceExtTex + } ] + }); + return WebGPU.importJsBindGroup(bindGroup); + }, + 1588925: ($0, $1) => { + const input = Emval.toValue($0); + const output = Emval.toValue($1); + const ctx = output.getContext("2d"); + ctx.drawImage(input, 0, 0, output.width, output.height); + }, + 1589090: ($0, $1) => { + const inputArray = Emval.toValue($0); + const output = Emval.toValue($1); + const ctx = output.getContext("2d"); + const image_data = new ImageData(inputArray, output.width, output.height); + ctx.putImageData(image_data, 0, 0); + }, + 1589314: ($0, $1) => { + const input = Emval.toValue($0); + const outputArray = Emval.toValue($1); + const ctx = input.getContext("2d"); + const data = ctx.getImageData(0, 0, input.width, input.height); + outputArray.set(data.data); + }, + 1589518: () => (typeof HTMLCanvasElement !== "undefined"), + 1589573: () => !!Module["preinitializedWebGPUDevice"], + 1589624: () => { + specialHTMLTargets["#canvas"] = Module.canvas; + } +}; + +function __asyncjs__CallStreamWeightsOnWeb(tfl_ids, wgpu_buffers, offsets, lengths, count) { + return Asyncify.handleAsync(async () => { + const callback = Module.getStreamWeightsCallback(); + if (typeof callback !== "function") { + console.error("Stream weights callback is not registered or is not a function"); + return 1; + } + const view = new DataView(Module.HEAPU8.buffer); + const tflIdsPtr = tfl_ids >>> 0; + const wgpuBuffersPtr = wgpu_buffers >>> 0; + const offsetsPtr = offsets >>> 0; + const lengthsPtr = lengths >>> 0; + const tflIdsArray = new Int32Array(count); + const wgpuBuffersArray = new Uint32Array(count); + const offsetsArray = new Float64Array(count); + const lengthsArray = new Float64Array(count); + for (let i = 0; i < count; i++) { + tflIdsArray[i] = view.getInt32(tflIdsPtr + i * 4, true); + wgpuBuffersArray[i] = view.getUint32(wgpuBuffersPtr + i * 4, true); + offsetsArray[i] = view.getFloat64(offsetsPtr + i * 8, true); + lengthsArray[i] = view.getFloat64(lengthsPtr + i * 8, true); + } + try { + await callback(tflIdsArray, wgpuBuffersArray, offsetsArray, lengthsArray); + } catch (e) { + console.error("Error in streamWeightsOnWeb:", e); + return 1; + } + return 0; + }); +} + +function BeginGlQueryTiming(calc_name, num_repetitions) { + const gl = Module.canvas.getContext("webgl2"); + const query = gl.createQuery(); + Module.WEBGL_SHADER_CALC_METRICS = Module.WEBGL_SHADER_CALC_METRICS || {}; + Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)] = { + query, + repetitions: num_repetitions + }; + Module.WEBGL_QUERY_TIMER_EXT = Module.WEBGL_QUERY_TIMER_EXT || gl.getExtension("EXT_disjoint_timer_query_webgl2"); + gl.beginQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT, query); +} + +function EndGlQueryTiming(calc_name) { + const gl = Module.canvas.getContext("webgl2"); + gl.endQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT, Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)].query); +} + +function JsWrapImageConverter() { + if (!Module._imageConverter) { + Module._imageConverter = (binaryPtr, binarySize, width, height, numChannels, makeDeepCopy, outputType) => { + const imageData = new outputType(makeDeepCopy ? Module.HEAPU8.slice(binaryPtr, binaryPtr + binarySize).buffer : Module.HEAPU8.buffer, binaryPtr, width * height * numChannels); + return { + data: imageData, + width, + height + }; + }; + } +} + +function JsOnUint8ArrayImageListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) { + const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Uint8Array); + Module._wrapSimpleListenerOutput(output_stream_name, image, timestamp_ms); +} + +function JsOnFloat32ArrayImageListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) { + const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Float32Array); + Module._wrapSimpleListenerOutput(output_stream_name, image, timestamp_ms); +} + +function JsOnWebGLTextureListener(output_stream_name, name, width, height, timestamp_ms) { + Module._wrapSimpleListenerOutput(output_stream_name, { + data: GL.textures[name], + width, + height + }, timestamp_ms); +} + +function JsOnUint8ArrayImageVectorListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) { + const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Uint8Array); + Module._wrapSimpleListenerOutput(output_stream_name, image, false, timestamp_ms); +} + +function JsOnFloat32ArrayImageVectorListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) { + const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Float32Array); + Module._wrapSimpleListenerOutput(output_stream_name, image, false, timestamp_ms); +} + +function JsOnWebGLTextureVectorListener(output_stream_name, name, width, height, timestamp_ms) { + Module._wrapSimpleListenerOutput(output_stream_name, { + data: GL.textures[name], + width, + height + }, false, timestamp_ms); +} + +function JsWrapLoggingHelpers() { + if (!Module["_decodeBase64"]) { + Module["_decodeBase64"] = function(encoded_key_ptr) { + const encodedStr = UTF8ToString(encoded_key_ptr); + return atob(encodedStr); + }; + } +} + +function JsOnEmptyPacketListener(output_stream_name, timestamp) { + Module._wrapEmptyPacketListenerOutput(output_stream_name, timestamp); +} + +function JsOnVectorFinishedListener(output_stream_name, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, undefined, true, timestamp); +} + +function JsOnSimpleListenerBool(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp); +} + +function JsOnVectorListenerBool(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp); +} + +function JsOnSimpleListenerInt(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp); +} + +function JsOnVectorListenerInt(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp); +} + +function JsOnSimpleListenerUint(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp); +} + +function JsOnVectorListenerUint(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp); +} + +function JsOnSimpleListenerDouble(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp); +} + +function JsOnVectorListenerDouble(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp); +} + +function JsOnSimpleListenerFloat(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp); +} + +function JsOnVectorListenerFloat(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp); +} + +function JsOnSimpleListenerString(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, UTF8ToString(out_data), timestamp); +} + +function JsOnVectorListenerString(output_stream_name, out_data, timestamp) { + Module._wrapSimpleListenerOutput(output_stream_name, UTF8ToString(out_data), false, timestamp); +} + +function JsOnVectorListenerProto(output_stream_name, proto_ptr, proto_size, make_deep_copy, timestamp) { + const newProtoArray = make_deep_copy ? Module.HEAPU8.slice(proto_ptr, proto_ptr + proto_size) : new Uint8Array(Module.HEAPU8.buffer, proto_ptr, proto_size); + Module._wrapSimpleListenerOutput(output_stream_name, newProtoArray, false, timestamp); +} + +function JsWrapSimpleListeners() { + if (!Module._wrapSimpleListenerOutput) { + Module._wrapSimpleListenerOutput = (outputStreamName, ...args) => { + if (Module.simpleListeners) { + const streamName = UTF8ToString(outputStreamName); + if (Module.simpleListeners[streamName]) { + Module.simpleListeners[streamName](...args); + } + } + }; + } + if (!Module._wrapEmptyPacketListenerOutput) { + Module._wrapEmptyPacketListenerOutput = (outputStreamName, timestamp) => { + if (Module.emptyPacketListeners) { + const streamName = UTF8ToString(outputStreamName); + if (Module.emptyPacketListeners[streamName]) { + Module.emptyPacketListeners[streamName](timestamp); + } + } + }; + } +} + +function JsOnSimpleListenerBinaryArray(output_stream_name, binary_ptr, binary_size, make_deep_copy, timestamp) { + const newProtoArray = make_deep_copy ? Module.HEAPU8.slice(binary_ptr, binary_ptr + binary_size) : new Uint8Array(Module.HEAPU8.buffer, binary_ptr, binary_size); + Module._wrapSimpleListenerOutput(output_stream_name, newProtoArray, timestamp); +} + +function mediapipe_import_external_texture(device_handle, source_handle) { + const device = WebGPU.getJsObject(device_handle); + const source = Emval.toValue(source_handle); + const externalTexture = device.importExternalTexture({ + source + }); + return Emval.toHandle(externalTexture); +} + +function mediapipe_create_utility_canvas2d() { + let canvas; + if (typeof HTMLCanvasElement !== "undefined") { + canvas = document.createElement("canvas"); + canvas.style.display = "none"; + } else { + canvas = new OffscreenCanvas(0, 0); + } + return Emval.toHandle(canvas); +} + +function GetAdapterArchitecture() { + const device = Module["preinitializedWebGPUDevice"]; + const architecture = device.adapterInfo ? device.adapterInfo.architecture : "Unknown"; + return stringToNewUTF8(architecture); +} + +function GetAdapterDescription() { + const device = Module["preinitializedWebGPUDevice"]; + const description = device.adapterInfo ? device.adapterInfo.description : "Unknown"; + return stringToNewUTF8(description); +} + +function GetAdapterDeviceName() { + const device = Module["preinitializedWebGPUDevice"]; + const deviceName = device.adapterInfo ? device.adapterInfo.device : "Unknown"; + return stringToNewUTF8(deviceName); +} + +function GetAdapterVendor() { + const device = Module["preinitializedWebGPUDevice"]; + const vendor = device.adapterInfo ? device.adapterInfo.vendor : "Unknown"; + return stringToNewUTF8(vendor); +} + +function __asyncjs__mediapipe_map_buffer_jspi(buffer_handle, data) { + return Asyncify.handleAsync(async () => { + const buffer = WebGPU.getJsObject(buffer_handle); + if ("mapSync" in buffer) { + buffer.mapSync(GPUMapMode.READ); + } else { + await buffer.mapAsync(GPUMapMode.READ); + } + const mapped = buffer.getMappedRange(); + HEAPU8.set(new Uint8Array(mapped), data); + buffer.unmap(); + }); +} + +function hardware_concurrency() { + var concurrency = 1; + try { + concurrency = self.navigator.hardwareConcurrency; + } catch (e) {} + return concurrency; +} + +function UseBottomLeftGpuOrigin() { + return (Module && Module.gpuOriginForWebTexturesIsBottomLeft); +} + +function custom_emscripten_dbgn(str, len) { + if (typeof (dbg) !== "undefined") { + dbg(UTF8ToString(str, len)); + } else { + if (typeof (custom_dbg) === "undefined") { + function custom_dbg(text) { + console.warn.apply(console, arguments); + } + } + custom_dbg(UTF8ToString(str, len)); + } +} + +function JsWrapErrorListenerInternal(code, message) { + if (Module.errorListener) { + const stringMessage = UTF8ToString(message); + Module.errorListener(code, stringMessage); + } +} + +// Imports from the Wasm binary. +var _free, _malloc, _wgpuDeviceAddRef, _interactive_segmenter_create, _interactive_segmenter_set_image, _interactive_segmenter_segment, _interactive_segmenter_close, _addBoundTextureAsImageToStream, _attachImageListener, _attachImageVectorListener, _mediapipeLoggerGetEncodedApiKey, _registerModelResourcesGraphService, _bindTextureToStream, _addBoundTextureToStream, _addDoubleToInputStream, _addFloatToInputStream, _addBoolToInputStream, _addIntToInputStream, _addUintToInputStream, _addStringToInputStream, _addRawDataSpanToInputStream, _allocateBoolVector, _allocateFloatVector, _allocateDoubleVector, _allocateIntVector, _allocateUintVector, _allocateStringVector, _addBoolVectorEntry, _addFloatVectorEntry, _addDoubleVectorEntry, _addIntVectorEntry, _addUintVectorEntry, _addStringVectorEntry, _addBoolVectorToInputStream, _addFloatVectorToInputStream, _addDoubleVectorToInputStream, _addIntVectorToInputStream, _addUintVectorToInputStream, _addStringVectorToInputStream, _addFlatHashMapToInputStream, _addProtoToInputStream, _addEmptyPacketToInputStream, _addBoolToInputSidePacket, _addDoubleToInputSidePacket, _addFloatToInputSidePacket, _addIntToInputSidePacket, _addUintToInputSidePacket, _addStringToInputSidePacket, _addRawDataSpanToInputSidePacket, _addProtoToInputSidePacket, _addBoolVectorToInputSidePacket, _addDoubleVectorToInputSidePacket, _addFloatVectorToInputSidePacket, _addIntVectorToInputSidePacket, _addUintVectorToInputSidePacket, _addStringVectorToInputSidePacket, _attachBoolListener, _attachBoolVectorListener, _attachDoubleListener, _attachDoubleVectorListener, _attachFloatListener, _attachFloatVectorListener, _attachIntListener, _attachIntVectorListener, _attachUintListener, _attachUintVectorListener, _attachStringListener, _attachStringVectorListener, _attachProtoListener, _attachProtoVectorListener, _getGraphConfig, ___getTypeName, _emwgpuCreateBindGroup, _emwgpuCreateBindGroupLayout, _emwgpuCreateCommandBuffer, _emwgpuCreateCommandEncoder, _emwgpuCreateComputePassEncoder, _emwgpuCreateComputePipeline, _emwgpuCreateExternalTexture, _emwgpuCreatePipelineLayout, _emwgpuCreateQuerySet, _emwgpuCreateRenderBundle, _emwgpuCreateRenderBundleEncoder, _emwgpuCreateRenderPassEncoder, _emwgpuCreateRenderPipeline, _emwgpuCreateSampler, _emwgpuCreateSurface, _emwgpuCreateTexture, _emwgpuCreateTextureView, _emwgpuCreateAdapter, _emwgpuImportBuffer, _emwgpuCreateDevice, _emwgpuCreateQueue, _emwgpuCreateShaderModule, _emwgpuOnCreateComputePipelineCompleted, _emwgpuOnCreateRenderPipelineCompleted, _clearSubgraphs, _pushBinarySubgraph, _pushTextSubgraph, _changeBinaryGraph, _changeTextGraph, _processGl, _process, _bindTextureToCanvas, _requestShaderRefreshOnGraphChange, _waitUntilIdle, _closeGraph, _setAutoRenderToScreen, _emscripten_builtin_memalign, _memalign, __emscripten_tempret_set, __emscripten_stack_restore, __emscripten_stack_alloc, _emscripten_stack_get_current, dynCall_ji, dynCall_jii, dynCall_iiiijij, dynCall_iij, dynCall_iiiijj, dynCall_viijj, dynCall_viiijjj, dynCall_vij, dynCall_viiji, dynCall_viji, dynCall_iiiji, dynCall_jjj, dynCall_jiii, dynCall_viijii, dynCall_vijjj, dynCall_vj, dynCall_viij, dynCall_jiji, dynCall_iiiiij, dynCall_iiiiijj, dynCall_iiiiiijj, memory, _kVersionStampBuildChangelistStr, _kVersionStampCitcSnapshotStr, _kVersionStampCitcWorkspaceIdStr, _kVersionStampSourceUriStr, _kVersionStampBuildClientStr, _kVersionStampBuildClientMintStatusStr, _kVersionStampBuildCompilerStr, _kVersionStampBuildDateTimePstStr, _kVersionStampBuildDepotPathStr, _kVersionStampBuildIdStr, _kVersionStampBuildInfoStr, _kVersionStampBuildLabelStr, _kVersionStampBuildTargetStr, _kVersionStampBuildTimestampStr, _kVersionStampBuildToolStr, _kVersionStampG3BuildTargetStr, _kVersionStampVerifiableStr, _kVersionStampBuildFdoTypeStr, _kVersionStampBuildBaselineChangelistStr, _kVersionStampBuildLtoTypeStr, _kVersionStampBuildPropellerTypeStr, _kVersionStampBuildPghoTypeStr, _kVersionStampBuildFdoProfileChangelistStr, _kVersionStampBuildMemprofProfileChangelistStr, _kVersionStampBuildUsernameStr, _kVersionStampBuildHostnameStr, _kVersionStampBuildDirectoryStr, _kVersionStampBuildChangelistInt, _kVersionStampCitcSnapshotInt, _kVersionStampBuildClientMintStatusInt, _kVersionStampBuildTimestampInt, _kVersionStampVerifiableInt, _kVersionStampBuildCoverageEnabledInt, _kVersionStampBuildBaselineChangelistInt, _kVersionStampPrecookedTimestampStr, _kVersionStampPrecookedClientInfoStr, __indirect_function_table, _kVersionStampBuildHasHardeningProtobuf, wasmMemory, wasmTable; + +function assignWasmExports(wasmExports) { + _free = Module["_free"] = wasmExports["ee"]; + _malloc = Module["_malloc"] = wasmExports["fe"]; + _wgpuDeviceAddRef = wasmExports["ge"]; + _interactive_segmenter_create = Module["_interactive_segmenter_create"] = wasmExports["he"]; + _interactive_segmenter_set_image = Module["_interactive_segmenter_set_image"] = wasmExports["ie"]; + _interactive_segmenter_segment = Module["_interactive_segmenter_segment"] = wasmExports["je"]; + _interactive_segmenter_close = Module["_interactive_segmenter_close"] = wasmExports["ke"]; + _addBoundTextureAsImageToStream = Module["_addBoundTextureAsImageToStream"] = wasmExports["le"]; + _attachImageListener = Module["_attachImageListener"] = wasmExports["me"]; + _attachImageVectorListener = Module["_attachImageVectorListener"] = wasmExports["ne"]; + _mediapipeLoggerGetEncodedApiKey = Module["_mediapipeLoggerGetEncodedApiKey"] = wasmExports["oe"]; + _registerModelResourcesGraphService = Module["_registerModelResourcesGraphService"] = wasmExports["pe"]; + _bindTextureToStream = Module["_bindTextureToStream"] = wasmExports["qe"]; + _addBoundTextureToStream = Module["_addBoundTextureToStream"] = wasmExports["re"]; + _addDoubleToInputStream = Module["_addDoubleToInputStream"] = wasmExports["se"]; + _addFloatToInputStream = Module["_addFloatToInputStream"] = wasmExports["te"]; + _addBoolToInputStream = Module["_addBoolToInputStream"] = wasmExports["ue"]; + _addIntToInputStream = Module["_addIntToInputStream"] = wasmExports["ve"]; + _addUintToInputStream = Module["_addUintToInputStream"] = wasmExports["we"]; + _addStringToInputStream = Module["_addStringToInputStream"] = wasmExports["xe"]; + _addRawDataSpanToInputStream = Module["_addRawDataSpanToInputStream"] = wasmExports["ye"]; + _allocateBoolVector = Module["_allocateBoolVector"] = wasmExports["ze"]; + _allocateFloatVector = Module["_allocateFloatVector"] = wasmExports["Ae"]; + _allocateDoubleVector = Module["_allocateDoubleVector"] = wasmExports["Be"]; + _allocateIntVector = Module["_allocateIntVector"] = wasmExports["Ce"]; + _allocateUintVector = Module["_allocateUintVector"] = wasmExports["De"]; + _allocateStringVector = Module["_allocateStringVector"] = wasmExports["Ee"]; + _addBoolVectorEntry = Module["_addBoolVectorEntry"] = wasmExports["Fe"]; + _addFloatVectorEntry = Module["_addFloatVectorEntry"] = wasmExports["Ge"]; + _addDoubleVectorEntry = Module["_addDoubleVectorEntry"] = wasmExports["He"]; + _addIntVectorEntry = Module["_addIntVectorEntry"] = wasmExports["Ie"]; + _addUintVectorEntry = Module["_addUintVectorEntry"] = wasmExports["Je"]; + _addStringVectorEntry = Module["_addStringVectorEntry"] = wasmExports["Ke"]; + _addBoolVectorToInputStream = Module["_addBoolVectorToInputStream"] = wasmExports["Le"]; + _addFloatVectorToInputStream = Module["_addFloatVectorToInputStream"] = wasmExports["Me"]; + _addDoubleVectorToInputStream = Module["_addDoubleVectorToInputStream"] = wasmExports["Ne"]; + _addIntVectorToInputStream = Module["_addIntVectorToInputStream"] = wasmExports["Oe"]; + _addUintVectorToInputStream = Module["_addUintVectorToInputStream"] = wasmExports["Pe"]; + _addStringVectorToInputStream = Module["_addStringVectorToInputStream"] = wasmExports["Qe"]; + _addFlatHashMapToInputStream = Module["_addFlatHashMapToInputStream"] = wasmExports["Re"]; + _addProtoToInputStream = Module["_addProtoToInputStream"] = wasmExports["Se"]; + _addEmptyPacketToInputStream = Module["_addEmptyPacketToInputStream"] = wasmExports["Te"]; + _addBoolToInputSidePacket = Module["_addBoolToInputSidePacket"] = wasmExports["Ue"]; + _addDoubleToInputSidePacket = Module["_addDoubleToInputSidePacket"] = wasmExports["Ve"]; + _addFloatToInputSidePacket = Module["_addFloatToInputSidePacket"] = wasmExports["We"]; + _addIntToInputSidePacket = Module["_addIntToInputSidePacket"] = wasmExports["Xe"]; + _addUintToInputSidePacket = Module["_addUintToInputSidePacket"] = wasmExports["Ye"]; + _addStringToInputSidePacket = Module["_addStringToInputSidePacket"] = wasmExports["Ze"]; + _addRawDataSpanToInputSidePacket = Module["_addRawDataSpanToInputSidePacket"] = wasmExports["_e"]; + _addProtoToInputSidePacket = Module["_addProtoToInputSidePacket"] = wasmExports["$e"]; + _addBoolVectorToInputSidePacket = Module["_addBoolVectorToInputSidePacket"] = wasmExports["af"]; + _addDoubleVectorToInputSidePacket = Module["_addDoubleVectorToInputSidePacket"] = wasmExports["bf"]; + _addFloatVectorToInputSidePacket = Module["_addFloatVectorToInputSidePacket"] = wasmExports["cf"]; + _addIntVectorToInputSidePacket = Module["_addIntVectorToInputSidePacket"] = wasmExports["df"]; + _addUintVectorToInputSidePacket = Module["_addUintVectorToInputSidePacket"] = wasmExports["ef"]; + _addStringVectorToInputSidePacket = Module["_addStringVectorToInputSidePacket"] = wasmExports["ff"]; + _attachBoolListener = Module["_attachBoolListener"] = wasmExports["gf"]; + _attachBoolVectorListener = Module["_attachBoolVectorListener"] = wasmExports["hf"]; + _attachDoubleListener = Module["_attachDoubleListener"] = wasmExports["jf"]; + _attachDoubleVectorListener = Module["_attachDoubleVectorListener"] = wasmExports["kf"]; + _attachFloatListener = Module["_attachFloatListener"] = wasmExports["lf"]; + _attachFloatVectorListener = Module["_attachFloatVectorListener"] = wasmExports["mf"]; + _attachIntListener = Module["_attachIntListener"] = wasmExports["nf"]; + _attachIntVectorListener = Module["_attachIntVectorListener"] = wasmExports["of"]; + _attachUintListener = Module["_attachUintListener"] = wasmExports["pf"]; + _attachUintVectorListener = Module["_attachUintVectorListener"] = wasmExports["qf"]; + _attachStringListener = Module["_attachStringListener"] = wasmExports["rf"]; + _attachStringVectorListener = Module["_attachStringVectorListener"] = wasmExports["sf"]; + _attachProtoListener = Module["_attachProtoListener"] = wasmExports["tf"]; + _attachProtoVectorListener = Module["_attachProtoVectorListener"] = wasmExports["uf"]; + _getGraphConfig = Module["_getGraphConfig"] = wasmExports["vf"]; + ___getTypeName = wasmExports["wf"]; + _emwgpuCreateBindGroup = wasmExports["xf"]; + _emwgpuCreateBindGroupLayout = wasmExports["yf"]; + _emwgpuCreateCommandBuffer = wasmExports["zf"]; + _emwgpuCreateCommandEncoder = wasmExports["Af"]; + _emwgpuCreateComputePassEncoder = wasmExports["Bf"]; + _emwgpuCreateComputePipeline = wasmExports["Cf"]; + _emwgpuCreateExternalTexture = wasmExports["Df"]; + _emwgpuCreatePipelineLayout = wasmExports["Ef"]; + _emwgpuCreateQuerySet = wasmExports["Ff"]; + _emwgpuCreateRenderBundle = wasmExports["Gf"]; + _emwgpuCreateRenderBundleEncoder = wasmExports["Hf"]; + _emwgpuCreateRenderPassEncoder = wasmExports["If"]; + _emwgpuCreateRenderPipeline = wasmExports["Jf"]; + _emwgpuCreateSampler = wasmExports["Kf"]; + _emwgpuCreateSurface = wasmExports["Lf"]; + _emwgpuCreateTexture = wasmExports["Mf"]; + _emwgpuCreateTextureView = wasmExports["Nf"]; + _emwgpuCreateAdapter = wasmExports["Of"]; + _emwgpuImportBuffer = wasmExports["Pf"]; + _emwgpuCreateDevice = wasmExports["Qf"]; + _emwgpuCreateQueue = wasmExports["Rf"]; + _emwgpuCreateShaderModule = wasmExports["Sf"]; + _emwgpuOnCreateComputePipelineCompleted = wasmExports["Tf"]; + _emwgpuOnCreateRenderPipelineCompleted = wasmExports["Uf"]; + _clearSubgraphs = Module["_clearSubgraphs"] = wasmExports["Vf"]; + _pushBinarySubgraph = Module["_pushBinarySubgraph"] = wasmExports["Wf"]; + _pushTextSubgraph = Module["_pushTextSubgraph"] = wasmExports["Xf"]; + _changeBinaryGraph = Module["_changeBinaryGraph"] = wasmExports["Yf"]; + _changeTextGraph = Module["_changeTextGraph"] = wasmExports["Zf"]; + _processGl = Module["_processGl"] = wasmExports["_f"]; + _process = Module["_process"] = wasmExports["$f"]; + _bindTextureToCanvas = Module["_bindTextureToCanvas"] = wasmExports["ag"]; + _requestShaderRefreshOnGraphChange = Module["_requestShaderRefreshOnGraphChange"] = wasmExports["bg"]; + _waitUntilIdle = Module["_waitUntilIdle"] = wasmExports["cg"]; + _closeGraph = Module["_closeGraph"] = wasmExports["dg"]; + _setAutoRenderToScreen = Module["_setAutoRenderToScreen"] = wasmExports["eg"]; + _emscripten_builtin_memalign = wasmExports["gg"]; + _memalign = wasmExports["hg"]; + __emscripten_tempret_set = wasmExports["ig"]; + __emscripten_stack_restore = wasmExports["jg"]; + __emscripten_stack_alloc = wasmExports["kg"]; + _emscripten_stack_get_current = wasmExports["lg"]; + dynCall_ji = wasmExports["dynCall_ji"]; + dynCall_jii = wasmExports["dynCall_jii"]; + dynCall_iiiijij = wasmExports["dynCall_iiiijij"]; + dynCall_iij = wasmExports["dynCall_iij"]; + dynCall_iiiijj = wasmExports["dynCall_iiiijj"]; + dynCall_viijj = wasmExports["dynCall_viijj"]; + dynCall_viiijjj = wasmExports["dynCall_viiijjj"]; + dynCall_vij = wasmExports["dynCall_vij"]; + dynCall_viiji = wasmExports["dynCall_viiji"]; + dynCall_viji = wasmExports["dynCall_viji"]; + dynCall_iiiji = wasmExports["dynCall_iiiji"]; + dynCall_jjj = wasmExports["dynCall_jjj"]; + dynCall_jiii = wasmExports["dynCall_jiii"]; + dynCall_viijii = wasmExports["dynCall_viijii"]; + dynCall_vijjj = wasmExports["dynCall_vijjj"]; + dynCall_vj = wasmExports["dynCall_vj"]; + dynCall_viij = wasmExports["dynCall_viij"]; + dynCall_jiji = wasmExports["dynCall_jiji"]; + dynCall_iiiiij = wasmExports["dynCall_iiiiij"]; + dynCall_iiiiijj = wasmExports["dynCall_iiiiijj"]; + dynCall_iiiiiijj = wasmExports["dynCall_iiiiiijj"]; + memory = wasmMemory = wasmExports["td"]; + _kVersionStampBuildChangelistStr = Module["_kVersionStampBuildChangelistStr"] = wasmExports["vd"].value; + _kVersionStampCitcSnapshotStr = Module["_kVersionStampCitcSnapshotStr"] = wasmExports["wd"].value; + _kVersionStampCitcWorkspaceIdStr = Module["_kVersionStampCitcWorkspaceIdStr"] = wasmExports["xd"].value; + _kVersionStampSourceUriStr = Module["_kVersionStampSourceUriStr"] = wasmExports["yd"].value; + _kVersionStampBuildClientStr = Module["_kVersionStampBuildClientStr"] = wasmExports["zd"].value; + _kVersionStampBuildClientMintStatusStr = Module["_kVersionStampBuildClientMintStatusStr"] = wasmExports["Ad"].value; + _kVersionStampBuildCompilerStr = Module["_kVersionStampBuildCompilerStr"] = wasmExports["Bd"].value; + _kVersionStampBuildDateTimePstStr = Module["_kVersionStampBuildDateTimePstStr"] = wasmExports["Cd"].value; + _kVersionStampBuildDepotPathStr = Module["_kVersionStampBuildDepotPathStr"] = wasmExports["Dd"].value; + _kVersionStampBuildIdStr = Module["_kVersionStampBuildIdStr"] = wasmExports["Ed"].value; + _kVersionStampBuildInfoStr = Module["_kVersionStampBuildInfoStr"] = wasmExports["Fd"].value; + _kVersionStampBuildLabelStr = Module["_kVersionStampBuildLabelStr"] = wasmExports["Gd"].value; + _kVersionStampBuildTargetStr = Module["_kVersionStampBuildTargetStr"] = wasmExports["Hd"].value; + _kVersionStampBuildTimestampStr = Module["_kVersionStampBuildTimestampStr"] = wasmExports["Id"].value; + _kVersionStampBuildToolStr = Module["_kVersionStampBuildToolStr"] = wasmExports["Jd"].value; + _kVersionStampG3BuildTargetStr = Module["_kVersionStampG3BuildTargetStr"] = wasmExports["Kd"].value; + _kVersionStampVerifiableStr = Module["_kVersionStampVerifiableStr"] = wasmExports["Ld"].value; + _kVersionStampBuildFdoTypeStr = Module["_kVersionStampBuildFdoTypeStr"] = wasmExports["Md"].value; + _kVersionStampBuildBaselineChangelistStr = Module["_kVersionStampBuildBaselineChangelistStr"] = wasmExports["Nd"].value; + _kVersionStampBuildLtoTypeStr = Module["_kVersionStampBuildLtoTypeStr"] = wasmExports["Od"].value; + _kVersionStampBuildPropellerTypeStr = Module["_kVersionStampBuildPropellerTypeStr"] = wasmExports["Pd"].value; + _kVersionStampBuildPghoTypeStr = Module["_kVersionStampBuildPghoTypeStr"] = wasmExports["Qd"].value; + _kVersionStampBuildFdoProfileChangelistStr = Module["_kVersionStampBuildFdoProfileChangelistStr"] = wasmExports["Rd"].value; + _kVersionStampBuildMemprofProfileChangelistStr = Module["_kVersionStampBuildMemprofProfileChangelistStr"] = wasmExports["Sd"].value; + _kVersionStampBuildUsernameStr = Module["_kVersionStampBuildUsernameStr"] = wasmExports["Td"].value; + _kVersionStampBuildHostnameStr = Module["_kVersionStampBuildHostnameStr"] = wasmExports["Ud"].value; + _kVersionStampBuildDirectoryStr = Module["_kVersionStampBuildDirectoryStr"] = wasmExports["Vd"].value; + _kVersionStampBuildChangelistInt = Module["_kVersionStampBuildChangelistInt"] = wasmExports["Wd"].value; + _kVersionStampCitcSnapshotInt = Module["_kVersionStampCitcSnapshotInt"] = wasmExports["Xd"].value; + _kVersionStampBuildClientMintStatusInt = Module["_kVersionStampBuildClientMintStatusInt"] = wasmExports["Yd"].value; + _kVersionStampBuildTimestampInt = Module["_kVersionStampBuildTimestampInt"] = wasmExports["Zd"].value; + _kVersionStampVerifiableInt = Module["_kVersionStampVerifiableInt"] = wasmExports["_d"].value; + _kVersionStampBuildCoverageEnabledInt = Module["_kVersionStampBuildCoverageEnabledInt"] = wasmExports["$d"].value; + _kVersionStampBuildBaselineChangelistInt = Module["_kVersionStampBuildBaselineChangelistInt"] = wasmExports["ae"].value; + _kVersionStampPrecookedTimestampStr = Module["_kVersionStampPrecookedTimestampStr"] = wasmExports["be"].value; + _kVersionStampPrecookedClientInfoStr = Module["_kVersionStampPrecookedClientInfoStr"] = wasmExports["ce"].value; + __indirect_function_table = wasmTable = wasmExports["de"]; + _kVersionStampBuildHasHardeningProtobuf = Module["_kVersionStampBuildHasHardeningProtobuf"] = wasmExports["fg"].value; +} + +var wasmImports = { + /** @export */ sd: BeginGlQueryTiming, + /** @export */ qd: EndGlQueryTiming, + /** @export */ pd: GetAdapterArchitecture, + /** @export */ od: GetAdapterDescription, + /** @export */ nd: GetAdapterDeviceName, + /** @export */ md: GetAdapterVendor, + /** @export */ ld: JsOnEmptyPacketListener, + /** @export */ kd: JsOnFloat32ArrayImageListener, + /** @export */ jd: JsOnFloat32ArrayImageVectorListener, + /** @export */ pb: JsOnSimpleListenerBinaryArray, + /** @export */ id: JsOnSimpleListenerBool, + /** @export */ hd: JsOnSimpleListenerDouble, + /** @export */ gd: JsOnSimpleListenerFloat, + /** @export */ fd: JsOnSimpleListenerInt, + /** @export */ ed: JsOnSimpleListenerString, + /** @export */ dd: JsOnSimpleListenerUint, + /** @export */ cd: JsOnUint8ArrayImageListener, + /** @export */ bd: JsOnUint8ArrayImageVectorListener, + /** @export */ R: JsOnVectorFinishedListener, + /** @export */ ad: JsOnVectorListenerBool, + /** @export */ $c: JsOnVectorListenerDouble, + /** @export */ _c: JsOnVectorListenerFloat, + /** @export */ Zc: JsOnVectorListenerInt, + /** @export */ Yc: JsOnVectorListenerProto, + /** @export */ Xc: JsOnVectorListenerString, + /** @export */ Wc: JsOnVectorListenerUint, + /** @export */ Vc: JsOnWebGLTextureListener, + /** @export */ Uc: JsOnWebGLTextureVectorListener, + /** @export */ Tc: JsWrapErrorListenerInternal, + /** @export */ ob: JsWrapImageConverter, + /** @export */ Sc: JsWrapLoggingHelpers, + /** @export */ v: JsWrapSimpleListeners, + /** @export */ nb: UseBottomLeftGpuOrigin, + /** @export */ rd: __asyncjs__CallStreamWeightsOnWeb, + /** @export */ yb: __asyncjs__mediapipe_map_buffer_jspi, + /** @export */ u: ___cxa_throw, + /** @export */ Rc: ___syscall_dup, + /** @export */ Qc: ___syscall_faccessat, + /** @export */ E: ___syscall_fcntl64, + /** @export */ Pc: ___syscall_fstat64, + /** @export */ Nb: ___syscall_ftruncate64, + /** @export */ Oc: ___syscall_getcwd, + /** @export */ Nc: ___syscall_getdents64, + /** @export */ Mc: ___syscall_getuid32, + /** @export */ Lc: ___syscall_ioctl, + /** @export */ Kc: ___syscall_lstat64, + /** @export */ Jc: ___syscall_mkdirat, + /** @export */ Ic: ___syscall_newfstatat, + /** @export */ Qa: ___syscall_openat, + /** @export */ Hc: ___syscall_readlinkat, + /** @export */ Gc: ___syscall_rmdir, + /** @export */ Fc: ___syscall_stat64, + /** @export */ mb: ___syscall_unlinkat, + /** @export */ Ec: ___syscall_utimensat, + /** @export */ zc: __abort_js, + /** @export */ Jb: __embind_register_bigint, + /** @export */ yc: __embind_register_bool, + /** @export */ xc: __embind_register_emval, + /** @export */ kb: __embind_register_float, + /** @export */ I: __embind_register_integer, + /** @export */ q: __embind_register_memory_view, + /** @export */ wc: __embind_register_std_string, + /** @export */ Oa: __embind_register_std_wstring, + /** @export */ vc: __embind_register_void, + /** @export */ ba: __emval_create_invoker, + /** @export */ p: __emval_decref, + /** @export */ Na: __emval_get_global, + /** @export */ jb: __emval_get_property, + /** @export */ ka: __emval_incref, + /** @export */ Ma: __emval_instanceof, + /** @export */ aa: __emval_invoke, + /** @export */ wa: __emval_new_cstring, + /** @export */ $: __emval_run_destructors, + /** @export */ ib: __emval_set_property, + /** @export */ uc: __emval_typeof, + /** @export */ Ib: __gmtime_js, + /** @export */ Hb: __localtime_js, + /** @export */ Gb: __mktime_js, + /** @export */ Fb: __mmap_js, + /** @export */ Eb: __munmap_js, + /** @export */ tc: __tzset_js, + /** @export */ Mb: _clock_time_get, + /** @export */ sc: custom_emscripten_dbgn, + /** @export */ _: _emscripten_asm_const_int, + /** @export */ hb: _emscripten_asm_const_ptr, + /** @export */ La: _emscripten_errn, + /** @export */ rc: _emscripten_get_heap_max, + /** @export */ y: _emscripten_get_now, + /** @export */ T: _emscripten_has_asyncify, + /** @export */ qc: _emscripten_outn, + /** @export */ pc: _emscripten_pc_get_function, + /** @export */ oc: _emscripten_resize_heap, + /** @export */ gb: _emscripten_stack_snapshot, + /** @export */ nc: _emscripten_stack_unwind_buffer, + /** @export */ mc: _emscripten_webgl_create_context, + /** @export */ lc: _emscripten_webgl_destroy_context, + /** @export */ kc: _emscripten_webgl_get_context_attributes, + /** @export */ ja: _emscripten_webgl_get_current_context, + /** @export */ jc: _emscripten_webgl_make_context_current, + /** @export */ Q: _emscripten_webgpu_get_device, + /** @export */ ic: _emwgpuBufferDestroy, + /** @export */ hc: _emwgpuBufferGetMappedRange, + /** @export */ gc: _emwgpuBufferUnmap, + /** @export */ t: _emwgpuDelete, + /** @export */ fc: _emwgpuDeviceCreateBuffer, + /** @export */ Db: _emwgpuDeviceCreateComputePipelineAsync, + /** @export */ Cb: _emwgpuDeviceCreateRenderPipelineAsync, + /** @export */ ec: _emwgpuDeviceCreateShaderModule, + /** @export */ dc: _emwgpuDeviceDestroy, + /** @export */ cc: _emwgpuWaitAny, + /** @export */ Dc: _environ_get, + /** @export */ Cc: _environ_sizes_get, + /** @export */ fb: _exit, + /** @export */ la: _fd_close, + /** @export */ Lb: _fd_pread, + /** @export */ lb: _fd_read, + /** @export */ Kb: _fd_seek, + /** @export */ Pa: _fd_write, + /** @export */ b: _glActiveTexture, + /** @export */ va: _glAttachShader, + /** @export */ bc: _glBindAttribLocation, + /** @export */ c: _glBindBuffer, + /** @export */ eb: _glBindBufferBase, + /** @export */ s: _glBindFramebuffer, + /** @export */ a: _glBindTexture, + /** @export */ m: _glBindVertexArray, + /** @export */ db: _glBlendEquation, + /** @export */ ac: _glBlendFunc, + /** @export */ j: _glBufferData, + /** @export */ P: _glClear, + /** @export */ O: _glClearColor, + /** @export */ fa: _glClientWaitSync, + /** @export */ ia: _glColorMask, + /** @export */ cb: _glCompileShader, + /** @export */ bb: _glCreateProgram, + /** @export */ ab: _glCreateShader, + /** @export */ o: _glDeleteBuffers, + /** @export */ S: _glDeleteFramebuffers, + /** @export */ h: _glDeleteProgram, + /** @export */ ua: _glDeleteShader, + /** @export */ ta: _glDeleteSync, + /** @export */ D: _glDeleteTextures, + /** @export */ A: _glDeleteVertexArrays, + /** @export */ $a: _glDetachShader, + /** @export */ H: _glDisable, + /** @export */ n: _glDisableVertexAttribArray, + /** @export */ i: _glDrawArrays, + /** @export */ ha: _glDrawBuffers, + /** @export */ $b: _glEnable, + /** @export */ l: _glEnableVertexAttribArray, + /** @export */ _a: _glFenceSync, + /** @export */ sa: _glFinish, + /** @export */ x: _glFlush, + /** @export */ C: _glFramebufferTexture2D, + /** @export */ Za: _glFramebufferTextureLayer, + /** @export */ r: _glGenBuffers, + /** @export */ Z: _glGenFramebuffers, + /** @export */ G: _glGenTextures, + /** @export */ B: _glGenVertexArrays, + /** @export */ Ya: _glGetAttribLocation, + /** @export */ ga: _glGetError, + /** @export */ _b: _glGetFloatv, + /** @export */ w: _glGetIntegerv, + /** @export */ Zb: _glGetProgramiv, + /** @export */ Yb: _glGetShaderInfoLog, + /** @export */ Xb: _glGetShaderiv, + /** @export */ N: _glGetString, + /** @export */ Wb: _glGetUniformBlockIndex, + /** @export */ d: _glGetUniformLocation, + /** @export */ Vb: _glLineWidth, + /** @export */ Xa: _glLinkProgram, + /** @export */ ra: _glPixelStorei, + /** @export */ qa: _glReadPixels, + /** @export */ Wa: _glShaderSource, + /** @export */ F: _glTexImage2D, + /** @export */ pa: _glTexParameterf, + /** @export */ Va: _glTexParameterfv, + /** @export */ f: _glTexParameteri, + /** @export */ oa: _glTexStorage2D, + /** @export */ Ub: _glTexStorage3D, + /** @export */ Y: _glTexSubImage2D, + /** @export */ Tb: _glTexSubImage3D, + /** @export */ M: _glUniform1f, + /** @export */ na: _glUniform1fv, + /** @export */ e: _glUniform1i, + /** @export */ X: _glUniform2f, + /** @export */ Sb: _glUniform2fv, + /** @export */ Ka: _glUniform3f, + /** @export */ Ua: _glUniform4f, + /** @export */ W: _glUniform4fv, + /** @export */ Rb: _glUniform4iv, + /** @export */ Qb: _glUniformBlockBinding, + /** @export */ Pb: _glUniformMatrix2fv, + /** @export */ Ob: _glUniformMatrix3fv, + /** @export */ Ja: _glUniformMatrix4fv, + /** @export */ g: _glUseProgram, + /** @export */ k: _glVertexAttribPointer, + /** @export */ V: _glViewport, + /** @export */ Ia: hardware_concurrency, + /** @export */ Bb: mediapipe_create_utility_canvas2d, + /** @export */ Ab: _mediapipe_find_canvas_event_target, + /** @export */ zb: mediapipe_import_external_texture, + /** @export */ xb: _mediapipe_webgl_tex_image_drawable, + /** @export */ Bc: _proc_exit, + /** @export */ Ac: _random_get, + /** @export */ Ha: _wgpuCommandEncoderBeginComputePass, + /** @export */ Ga: _wgpuCommandEncoderBeginRenderPass, + /** @export */ wb: _wgpuCommandEncoderCopyBufferToTexture, + /** @export */ vb: _wgpuCommandEncoderCopyTextureToBuffer, + /** @export */ ub: _wgpuCommandEncoderCopyTextureToTexture, + /** @export */ L: _wgpuCommandEncoderFinish, + /** @export */ Fa: _wgpuComputePassEncoderDispatchWorkgroups, + /** @export */ Ea: _wgpuComputePassEncoderEnd, + /** @export */ Da: _wgpuComputePassEncoderSetBindGroup, + /** @export */ Ca: _wgpuComputePassEncoderSetPipeline, + /** @export */ Ba: _wgpuComputePipelineGetBindGroupLayout, + /** @export */ ea: _wgpuDeviceCreateBindGroup, + /** @export */ tb: _wgpuDeviceCreateBindGroupLayout, + /** @export */ K: _wgpuDeviceCreateCommandEncoder, + /** @export */ sb: _wgpuDeviceCreateComputePipeline, + /** @export */ rb: _wgpuDeviceCreatePipelineLayout, + /** @export */ Ta: _wgpuDeviceCreateRenderPipeline, + /** @export */ U: _wgpuDeviceCreateSampler, + /** @export */ da: _wgpuDeviceCreateTexture, + /** @export */ J: _wgpuQueueSubmit, + /** @export */ ma: _wgpuQueueWriteBuffer, + /** @export */ qb: _wgpuQueueWriteTexture, + /** @export */ Aa: _wgpuRenderPassEncoderDraw, + /** @export */ za: _wgpuRenderPassEncoderEnd, + /** @export */ ya: _wgpuRenderPassEncoderSetBindGroup, + /** @export */ xa: _wgpuRenderPassEncoderSetPipeline, + /** @export */ Sa: _wgpuRenderPipelineGetBindGroupLayout, + /** @export */ z: _wgpuTextureCreateView, + /** @export */ Ra: _wgpuTextureDestroy, + /** @export */ ca: _wgpuTextureGetFormat +}; + +// include: postamble.js +// === Auto-generated postamble setup entry stuff === +async function run() { + preRun(); + if (runDependencies) { + await resolveRunDependencies(); + } + var setStatus = Module["setStatus"]; + if (setStatus) { + setStatus("Running..."); + // Yield to the event loop to allow the browser to paint "Running..." + await new Promise(resolve => setTimeout(resolve, 1)); + // Then we want to clear the status text, but only after the rest of this function runs. + setTimeout(setStatus, 1, ""); + } + if (ABORT) return; + initRuntime(); + Module["onRuntimeInitialized"]?.(); + postRun(); +} + +var wasmExports; + +// In modularize mode the generated code is within a factory function so we +// can use await here (since it's not top-level-await). +wasmExports = await createWasm(); + +await run(); + + + return Module; +} + +// Export using a UMD style export, or ES6 exports if selected +globalThis.ModuleFactory = ModuleFactory; globalThis.custom_dbg = console.warn.bind(console); export default ModuleFactory; + diff --git a/v4d-next/demo/README.md b/v4d-next/demo/README.md new file mode 100644 index 0000000..779824b --- /dev/null +++ b/v4d-next/demo/README.md @@ -0,0 +1,20 @@ +# Demo subjects + +Blocks served with the site for the **Studio (the Atelier) only**. They are fetched when +opened there, never on a plain visit, and the public Viewer never shows them: leaving the +Studio goes back to the work. + +| File | What it is | +|---|---| +| `dancer.v4d` | A dancer **generated by the author with Kling AI 4.0: not a capture of a real person.** The clip was cropped to keep its watermark out of the tracked pixels, lifted into 3D tracks by ReLift on the author's PC (6 November 2026), and imported with `v4d_lab.relift import` at 1.5M points, 73 frames, 3 s. It carries tracks, what the camera saw (`observed`) and the raw lift (`rawPosition`), so TRACE, ANATOMY and WITNESS all work on it. See `docs/research/relift-report.md` §6.4. | + +The block's own `meta.origin` says the same, and the Studio shows it (Source panel, and the +word *generated* beside the subject). + +**Rights.** The image is the author's work, © Mehran Ahmadi, all rights reserved +(`LICENSE-ART.md`), not covered by the code's Apache licence. ReLift itself is MIT, but its +default path, used here, runs on Depth Anything 3 weights that are CC BY-NC 4.0: treat this +block as **non-commercial** (a demo on the author's site), and do not sell prints of it. + +It is published as a stand-in for a real subject with real tracks, which the Lab cannot yet +make from a sitting (`docs/HANDOFF.md` §6). diff --git a/v4d-next/demo/dancer.v4d b/v4d-next/demo/dancer.v4d new file mode 100644 index 0000000..1d348d6 Binary files /dev/null and b/v4d-next/demo/dancer.v4d differ diff --git a/v4d-next/favicon-32.png b/v4d-next/favicon-32.png new file mode 100644 index 0000000..f18cbfd Binary files /dev/null and b/v4d-next/favicon-32.png differ diff --git a/v4d-next/icon-192.png b/v4d-next/icon-192.png new file mode 100644 index 0000000..d7fa53e Binary files /dev/null and b/v4d-next/icon-192.png differ diff --git a/v4d-next/icon-512.png b/v4d-next/icon-512.png new file mode 100644 index 0000000..1a3a72f Binary files /dev/null and b/v4d-next/icon-512.png differ diff --git a/v4d-next/index.html b/v4d-next/index.html new file mode 100644 index 0000000..334ce70 --- /dev/null +++ b/v4d-next/index.html @@ -0,0 +1,104 @@ + + + + + + V4D · Virtual Fourth Dimension + + + + + + + + + + + + + + + + + +
+ + + + + + diff --git a/v4d-next/models/README.md b/v4d-next/models/README.md new file mode 100644 index 0000000..054b6d8 --- /dev/null +++ b/v4d-next/models/README.md @@ -0,0 +1,17 @@ +# The walker model + +Put a rigged, animated glTF figure here as **`walker.glb`**; the `walker` and `walker-2m` blocks then use it instead of the procedural walker. One file holds everything: mesh, skeleton and all animations. The viewer plays the clip named "walk" (or the first clip that contains "walk"), samples points on the skinned surface every frame (the same points each frame, so KALAM's tracked identity works), scales the figure to 1.75 m and, if the clip walks on the spot, carries it across at 1.3 m/s. + +From Sketchfab: on the model's page, **Download 3D Model → glTF → "glb"** (one file). If only the zipped `.gltf` is offered, open it in Blender (File → Import → glTF) and export again as **glTF Binary (.glb)**. + +From Mixamo: download the character (FBX, T-pose) and a walk animation (FBX, "without skin" is fine), then build `walker.glb` with Blender: + + blender -b -P apps/viewer/scripts/fbx-to-walker.py -- Character/character.fbx Character/Walking.fbx apps/viewer/public/models/walker.glb + +The script moves the walk onto the character, names it "walk", keeps only the base-colour texture (1024 px JPEG; points take their colour from it) and writes one `.glb`. A walk with root motion (Mixamo's default, "In Place" unticked) keeps walking across loops; an in-place walk is carried at 1.3 m/s. + +The current `walker.glb` is Mixamo's Ch36 with its "Walking" clip, built this way. The source `.fbx` files stay out of git (`Character/` is ignored). + +Check the model's licence on its page before committing it here: a CC Attribution model needs a credit line in the README. + +To try another file without copying it here: `?model=`. `?model=none` forces the procedural walker. diff --git a/v4d-next/models/walker.glb b/v4d-next/models/walker.glb new file mode 100644 index 0000000..32870b1 Binary files /dev/null and b/v4d-next/models/walker.glb differ diff --git a/v4d-next/og.jpg b/v4d-next/og.jpg new file mode 100644 index 0000000..5a3e21a Binary files /dev/null and b/v4d-next/og.jpg differ diff --git a/v4d-next/still.jpg b/v4d-next/still.jpg new file mode 100644 index 0000000..b5c8b34 Binary files /dev/null and b/v4d-next/still.jpg differ diff --git a/v4d-next/test/greenclip-suit.mp4 b/v4d-next/test/greenclip-suit.mp4 new file mode 100644 index 0000000..4aafea6 Binary files /dev/null and b/v4d-next/test/greenclip-suit.mp4 differ diff --git a/v4d-next/test/greenclip.mp4 b/v4d-next/test/greenclip.mp4 new file mode 100644 index 0000000..51ebb58 Binary files /dev/null and b/v4d-next/test/greenclip.mp4 differ diff --git a/v4d-next/test/rig.glb b/v4d-next/test/rig.glb new file mode 100644 index 0000000..ad9d47c Binary files /dev/null and b/v4d-next/test/rig.glb differ diff --git a/v4d-next/works/README.md b/v4d-next/works/README.md new file mode 100644 index 0000000..7268458 --- /dev/null +++ b/v4d-next/works/README.md @@ -0,0 +1,40 @@ +# Works + +The authored sitters the public Viewer shows. A plain visit opens the first one listed in +`works.json`; with no `works.json` here (as now), the Viewer shows the stand-in walker. + +Everything in this folder is artwork, © Mehran Ahmadi, all rights reserved (`LICENSE-ART.md`), +not covered by the code's Apache licence. + +## Publishing a sitter + +1. Rebuild the kept sitting in the Lab (`lab/sitting-to-v4d.bat`). For the web, keep it light: + set `POINTS=8000` at the top of the `.bat` (a 20 s sitting is then about 25 MB; GitHub + refuses files over 100 MB, and visitors on phones download it whole). +2. Copy the `…-lab.v4d` here, under a plain name, e.g. `sitter-01.v4d`. +3. Write `works.json` next to it: + + ```json + { + "works": [ + { + "file": "sitter-01.v4d", + "title": "Sitter, I", + "line": "Someone, kept in time.", + "about": "The sitter is …, kept for twenty seconds on 3 November 2026.", + "colour": "material" + } + ] + } + ``` + + - `line`: the words under V4D (default: the Viewer's own line). + - `about`: replaces the About panel's paragraph on the figure. + - `colour`: `material` (default) draws the sitter in the lenses' silver and light; `source` + keeps the colours the camera saw, on the same grounds. + - `ev`: a bias in stops on the Viewer's auto-exposure for the light lenses (Echo, + Exposure). Usually not needed: auto-exposure keeps a still sitter from burning white. + Use it to lean darker (−1) or brighter (+1). +4. Commit and push to `main`; the Pages workflow publishes it. + +Links: `?work=1` opens the second work listed, `?work=none` the walker.