@rqmii_immersive/agent-react-sdk 5.6.5 → 5.6.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Orb-B1DErA0O.cjs +4517 -0
- package/dist/Orb-B1DErA0O.cjs.map +1 -0
- package/dist/RqmiiAgentChat-C0ymqkkq.cjs +2 -0
- package/dist/RqmiiAgentChat-C0ymqkkq.cjs.map +1 -0
- package/dist/RqmiiCloudAvatarPlayer-CmovoCKk.cjs +2918 -0
- package/dist/RqmiiCloudAvatarPlayer-CmovoCKk.cjs.map +1 -0
- package/dist/RqmiiErrorBoundary-Byif85f5.cjs +2 -0
- package/dist/RqmiiErrorBoundary-Byif85f5.cjs.map +1 -0
- package/dist/embed/chunks/Orb-CBt2svdc.js +40903 -0
- package/dist/embed/chunks/Orb-CBt2svdc.js.map +1 -0
- package/dist/embed/chunks/RqmiiCloudAvatarPlayer-DpvI9bmI.js +3357 -0
- package/dist/embed/chunks/RqmiiCloudAvatarPlayer-DpvI9bmI.js.map +1 -0
- package/dist/embed/chunks/chat-box-avatar-DlUI3fDi.js +10 -0
- package/dist/embed/chunks/chat-box-avatar-DlUI3fDi.js.map +1 -0
- package/dist/embed/chunks/chat-box-text-and-voice-BgdFP0_P.js +112 -0
- package/dist/embed/chunks/chat-box-text-and-voice-BgdFP0_P.js.map +1 -0
- package/dist/embed/chunks/chat-box-voice-D0gPyOVt.js +74 -0
- package/dist/embed/chunks/chat-box-voice-D0gPyOVt.js.map +1 -0
- package/dist/embed/chunks/embed-core-B3d4u3wf.js +12623 -0
- package/dist/embed/chunks/embed-core-B3d4u3wf.js.map +1 -0
- package/dist/embed/chunks/highlighted-body-KPVGNVTW-CJl4AHHd.js +19 -0
- package/dist/embed/chunks/highlighted-body-KPVGNVTW-CJl4AHHd.js.map +1 -0
- package/dist/embed/chunks/mermaid-HWGCJPDP-DD9SRoUR.js +22773 -0
- package/dist/embed/chunks/mermaid-HWGCJPDP-DD9SRoUR.js.map +1 -0
- package/dist/embed/chunks/use-rqmii-vad-COqAsQsT.js +10225 -0
- package/dist/embed/chunks/use-rqmii-vad-COqAsQsT.js.map +1 -0
- package/dist/embed/core.js +6 -0
- package/dist/embed/core.js.map +1 -0
- package/dist/embed.js +2 -0
- package/dist/embed.js.map +1 -0
- package/dist/highlighted-body-KPVGNVTW-CSL27xRm.cjs +2 -0
- package/dist/highlighted-body-KPVGNVTW-CSL27xRm.cjs.map +1 -0
- package/dist/index.cjs +50 -0
- package/dist/index.cjs.map +1 -0
- package/dist/lazy.cjs +2 -0
- package/dist/lazy.cjs.map +1 -0
- package/dist/mermaid-HWGCJPDP-CssnmrD3.cjs +2 -0
- package/dist/mermaid-HWGCJPDP-CssnmrD3.cjs.map +1 -0
- package/dist/schedule-load-DbAlv7OH.cjs +2 -0
- package/dist/schedule-load-DbAlv7OH.cjs.map +1 -0
- package/dist/ui-1UzY5QCI.cjs +251 -0
- package/dist/ui-1UzY5QCI.cjs.map +1 -0
- package/dist/ui.cjs +2 -0
- package/dist/ui.cjs.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,2918 @@
|
|
|
1
|
+
"use strict";const zt=require("./RqmiiErrorBoundary-Byif85f5.cjs"),Ke=require("react"),xr=require("react/jsx-runtime");function ef(){const S=zt.useRqmiiAgentContext();return{sendAudioChunk:S.sendAudioChunk,endAudioStream:S.endAudioStream,isAudioPlaying:S.isAudioPlaying,transcript:S.transcript,partialTranscript:S.partialTranscript,interrupt:S.interrupt,resumeAudioPlayback:S.resumeAudioPlayback,pauseAudioPlayback:S.pauseAudioPlayback,attachAudioElement:S.attachAudioElement}}function Xh(){const S=zt.useRqmiiAgentContext(),s=S.cloudStream?.state||zt.CLOUD_STREAM_STATE.IDLE;return{streamingUrl:S.session.streamingUrl,isAvatarSpeaking:S.isAvatarSpeaking,speakingSource:"avatar_events",isCloudAvatar:S.session.agentType===zt.AGENT_TYPES.CLOUD_AVATAR,isDesktopAvatar:S.session.agentType===zt.AGENT_TYPES.DESKTOP_AVATAR,cloudStreamState:s,cloudStreamError:S.cloudStream?.error||null,isCloudStreamConnected:s===zt.CLOUD_STREAM_STATE.CONNECTED,isCloudStreamLoading:s===zt.CLOUD_STREAM_STATE.CONNECTING||s===zt.CLOUD_STREAM_STATE.LOADING,setCloudStreamState:S.setCloudStreamState}}var Ca={},Ea={},Ai={},Th;function Zh(){if(Th)return Ai;Th=1,Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.baseAssetPath=void 0;const s=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let n="/";return s&&(n=s.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Ai.baseAssetPath=n,Ai}var Pi={},Ch;function Ga(){if(Ch)return Pi;Ch=1,Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.defaultModelFetcher=void 0;const S=s=>fetch(s).then(n=>n.arrayBuffer());return Pi.defaultModelFetcher=S,Pi}var _r={},Oi={},Eh;function Ds(){if(Eh)return Oi;Eh=1,Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.log=void 0;const S=s=>n=>{console.log(`VAD | ${s} >`,n)};return Oi.log={error:S("error"),debug:S("debug"),warn:S("warn")},Oi}var zi={},kh;function cn(){if(kh)return zi;kh=1,Object.defineProperty(zi,"__esModule",{value:!0}),zi.Message=void 0;var S;return(function(s){s.AudioFrame="AUDIO_FRAME",s.SpeechStart="SPEECH_START",s.VADMisfire="VAD_MISFIRE",s.SpeechEnd="SPEECH_END",s.SpeechStop="SPEECH_STOP",s.SpeechRealStart="SPEECH_REAL_START",s.FrameProcessed="FRAME_PROCESSED"})(S||(zi.Message=S={})),zi}var Mh;function Wa(){if(Mh)return _r;Mh=1,Object.defineProperty(_r,"__esModule",{value:!0}),_r.FrameProcessor=_r.validateOptions=_r.defaultFrameProcessorOptions=void 0;const S=Ds(),s=cn();_r.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function n(A){(A.positiveSpeechThreshold<0||A.positiveSpeechThreshold>1)&&S.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(A.negativeSpeechThreshold<0||A.negativeSpeechThreshold>A.positiveSpeechThreshold)&&S.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),A.preSpeechPadMs<0&&S.log.error("preSpeechPadMs should be positive"),A.redemptionMs<0&&S.log.error("redemptionMs should be positive"),A.minSpeechMs<0&&S.log.error("minSpeechMs should be positive")}_r.validateOptions=n;const d=A=>{const O=A.reduce((K,G)=>(K.push(K.at(-1)+G.length),K),[0]),T=new Float32Array(O.at(-1));return A.forEach((K,G)=>{const ae=O[G];T.set(K,ae)}),T};function g(A,O){const T=Math.floor(A.redemptionMs/O),K=Math.floor(A.preSpeechPadMs/O),G=Math.floor(A.minSpeechMs/O);return{redemptionFrames:T,preSpeechPadFrames:K,minSpeechFrames:G}}class E{constructor(O,T,K,G){this.modelProcessFunc=O,this.modelResetFunc=T,this.options=K,this.msPerFrame=G,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=re=>{this.options={...this.options,...re};const{redemptionFrames:ne,preSpeechPadFrames:fe,minSpeechFrames:Re}=g(this.options,this.msPerFrame);this.redemptionFrames=ne,this.preSpeechPadFrames=fe,this.minSpeechFrames=Re},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=re=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(re):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=re=>{const ne=this.audioBuffer;this.audioBuffer=[];const fe=this.speaking;if(this.reset(),fe)if(ne.reduce((Pe,ce)=>ce.isSpeech?Pe+1:Pe,0)>=this.minSpeechFrames){const Pe=d(ne.map(ce=>ce.frame));re({msg:s.Message.SpeechEnd,audio:Pe})}else re({msg:s.Message.VADMisfire});return{}},this.process=async(re,ne)=>{if(!this.active)return;const fe=await this.modelProcessFunc(re),Re=fe.isSpeech>=this.options.positiveSpeechThreshold;if(ne({probs:fe,msg:s.Message.FrameProcessed,frame:re}),this.audioBuffer.push({frame:re,isSpeech:Re}),Re&&(this.speechFrameCount++,this.redemptionCounter=0),Re&&!this.speaking&&(this.speaking=!0,ne({msg:s.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,ne({msg:s.Message.SpeechRealStart})),fe.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const Pe=this.audioBuffer;if(this.audioBuffer=[],Pe.reduce((le,ye)=>ye.isSpeech?le+1:le,0)>=this.minSpeechFrames){const le=d(Pe.map(ye=>ye.frame));ne({msg:s.Message.SpeechEnd,audio:le})}else ne({msg:s.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:ae,preSpeechPadFrames:J,minSpeechFrames:ie}=g(this.options,this.msPerFrame);this.redemptionFrames=ae,this.preSpeechPadFrames=J,this.minSpeechFrames=ie,this.reset()}}return _r.FrameProcessor=E,_r}var Sr={};function jt(S){throw new Error('Could not dynamically require "'+S+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var ka={exports:{}};/*!
|
|
2
|
+
* ONNX Runtime Web v1.26.0
|
|
3
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
4
|
+
* Licensed under the MIT License.
|
|
5
|
+
*/var Rh;function tf(){return Rh||(Rh=1,(function(S,s){var n=(()=>{var d=Object.defineProperty,g=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,A=Object.prototype.hasOwnProperty,O=(e=>typeof jt<"u"?jt:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof jt<"u"?jt:t)[r]}):e)(function(e){if(typeof jt<"u")return jt.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),T=(e,t)=>()=>(e&&(t=e(e=0)),t),K=(e,t)=>{for(var r in t)d(e,r,{get:t[r],enumerable:!0})},G=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of E(t))!A.call(e,a)&&a!==r&&d(e,a,{get:()=>t[a],enumerable:!(i=g(t,a))||i.enumerable});return e},ae=e=>G(d({},"__esModule",{value:!0}),e),J,ie,re,ne,fe,Re=T(()=>{J=new Map,ie=[],re=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=J.get(e);if(i===void 0)J.set(e,{backend:t,priority:r});else{if(i.priority>r)return;if(i.priority===r&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let a=ie.indexOf(e);a!==-1&&ie.splice(a,1);for(let o=0;o<ie.length;o++)if(J.get(ie[o]).priority<=r){ie.splice(o,0,e);return}ie.push(e)}return}throw new TypeError("not a valid backend")},ne=async e=>{let t=J.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return r||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},fe=async e=>{let t=e.executionProviders||[],r=t.map(c=>typeof c=="string"?c:c.name),i=r.length===0?ie:r,a,o=[],l=new Set;for(let c of i){let h=await ne(c);typeof h=="string"?o.push({name:c,err:h}):(a||(a=h),a===h&&l.add(c))}if(!a)throw new Error(`no available backend found. ERR: ${o.map(c=>`[${c.name}] ${c.err}`).join(", ")}`);for(let{name:c,err:h}of o)r.includes(c)&&console.warn(`removing requested execution provider "${c}" from session options because it is not available: ${h}`);let u=t.filter(c=>l.has(typeof c=="string"?c:c.name));return[a,new Proxy(e,{get:(c,h)=>h==="executionProviders"?u:Reflect.get(c,h)})]}}),Pe=T(()=>{Re()}),ce,le=T(()=>{ce="1.26.0"}),ye,me,We=T(()=>{le(),ye="warning",me={wasm:{},webgl:{},webgpu:{},versions:{common:ce},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);ye=e}},get logLevel(){return ye}},Object.defineProperty(me,"logLevel",{enumerable:!0})}),de,st=T(()=>{We(),de=me}),qe,dt,Qe=T(()=>{qe=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let i=r.getContext("2d");if(i!=null){let a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(a=e.dims[2],o=e.dims[3]):(a=e.dims[3],o=e.dims[2]);let l=t?.format!==void 0?t.format:"RGB",u=t?.norm,c,h;u===void 0||u.mean===void 0?c=[255,255,255,255]:typeof u.mean=="number"?c=[u.mean,u.mean,u.mean,u.mean]:(c=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(c[3]=u.mean[3])),u===void 0||u.bias===void 0?h=[0,0,0,0]:typeof u.bias=="number"?h=[u.bias,u.bias,u.bias,u.bias]:(h=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(h[3]=u.bias[3]));let p=o*a,m=0,y=p,w=p*2,v=-1;l==="RGBA"?(m=0,y=p,w=p*2,v=p*3):l==="RGB"?(m=0,y=p,w=p*2):l==="RBG"&&(m=0,w=p,y=p*2);for(let x=0;x<o;x++)for(let R=0;R<a;R++){let C=(e.data[m++]-h[0])*c[0],$=(e.data[y++]-h[1])*c[1],I=(e.data[w++]-h[2])*c[2],M=v===-1?255:(e.data[v++]-h[3])*c[3];i.fillStyle="rgba("+C+","+$+","+I+","+M+")",i.fillRect(R,x,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},dt=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(r!=null){let a,o,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(a=e.dims[2],o=e.dims[1],l=e.dims[3]):(a=e.dims[3],o=e.dims[2],l=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",c=t?.norm,h,p;c===void 0||c.mean===void 0?h=[255,255,255,255]:typeof c.mean=="number"?h=[c.mean,c.mean,c.mean,c.mean]:(h=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(h[3]=c.mean[3])),c===void 0||c.bias===void 0?p=[0,0,0,0]:typeof c.bias=="number"?p=[c.bias,c.bias,c.bias,c.bias]:(p=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(p[3]=c.bias[3]));let m=o*a;if(t!==void 0&&(t.format!==void 0&&l===4&&t.format!=="RGBA"||l===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let y=4,w=0,v=1,x=2,R=3,C=0,$=m,I=m*2,M=-1;u==="RGBA"?(C=0,$=m,I=m*2,M=m*3):u==="RGB"?(C=0,$=m,I=m*2):u==="RBG"&&(C=0,I=m,$=m*2),i=r.createImageData(a,o);for(let L=0;L<o*a;w+=y,v+=y,x+=y,R+=y,L++)i.data[w]=(e.data[C++]-p[0])*h[0],i.data[v]=(e.data[$++]-p[1])*h[1],i.data[x]=(e.data[I++]-p[2])*h[2],i.data[R]=M===-1?255:(e.data[M++]-p[3])*h[3]}else throw new Error("Can not access image data");return i}}),ut,at,Kt,Ct,je,Ve,et=T(()=>{zr(),ut=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:i}=t,a=t.norm??{mean:255,bias:0},o,l;typeof a.mean=="number"?o=[a.mean,a.mean,a.mean,a.mean]:o=[a.mean[0],a.mean[1],a.mean[2],a.mean[3]??255],typeof a.bias=="number"?l=[a.bias,a.bias,a.bias,a.bias]:l=[a.bias[0],a.bias[1],a.bias[2],a.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=r*i,p=c==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),m=4,y=0,w=1,v=2,x=3,R=0,C=h,$=h*2,I=-1;u==="RGB"&&(m=3,y=0,w=1,v=2,x=-1),c==="RGBA"?I=h*3:c==="RBG"?(R=0,$=h,C=h*2):c==="BGR"&&($=0,C=h,R=h*2);for(let M=0;M<h;M++,y+=m,v+=m,w+=m,x+=m)p[R++]=(e[y]+l[0])/o[0],p[C++]=(e[w]+l[1])/o[1],p[$++]=(e[v]+l[2])/o[2],I!==-1&&x!==-1&&(p[I++]=(e[x]+l[3])/o[3]);return c==="RGBA"?new Je("float32",p,[1,4,r,i]):new Je("float32",p,[1,3,r,i])},at=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,a=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string",l,u=t??{},c=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=c();p.width=e.width,p.height=e.height;let m=h(p);if(m!=null){let y=e.height,w=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(y=t.resizedHeight,w=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=y,u.width=w}else u.tensorFormat="RGBA",u.height=y,u.width=w;m.drawImage(e,0,0),l=m.getImageData(0,0,w,y).data}else throw new Error("Can not access image data")}else if(i){let p,m;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(p=t.resizedHeight,m=t.resizedWidth):(p=e.height,m=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=p,u.width=m,t!==void 0){let y=c();y.width=m,y.height=p;let w=h(y);if(w!=null)w.putImageData(e,0,0),l=w.getImageData(0,0,m,p).data;else throw new Error("Can not access image data")}else l=e.data}else if(a){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=c();p.width=e.width,p.height=e.height;let m=h(p);if(m!=null){let y=e.height,w=e.width;return m.drawImage(e,0,0,w,y),l=m.getImageData(0,0,w,y).data,u.height=y,u.width=w,ut(l,u)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,m)=>{let y=c(),w=h(y);if(!e||!w)return m();let v=new Image;v.crossOrigin="Anonymous",v.src=e,v.onload=()=>{y.width=v.width,y.height=v.height,w.drawImage(v,0,0,y.width,y.height);let x=w.getImageData(0,0,y.width,y.height);u.height=y.height,u.width=y.width,p(ut(x.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(l!==void 0)return ut(l,u);throw new Error("Input data provided is not supported - aborted tensor creation")},Kt=(e,t)=>{let{width:r,height:i,download:a,dispose:o}=t,l=[1,i,r,4];return new Je({location:"texture",type:"float32",texture:e,dims:l,download:a,dispose:o})},Ct=(e,t)=>{let{dataType:r,dims:i,download:a,dispose:o}=t;return new Je({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:i,download:a,dispose:o})},je=(e,t)=>{let{dataType:r,dims:i,download:a,dispose:o}=t;return new Je({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:i,download:a,dispose:o})},Ve=(e,t,r)=>new Je({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Xe,Rt,mr,Bs,hn=T(()=>{Xe=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Rt=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),mr=!1,Bs=()=>{if(!mr){mr=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,i=typeof r<"u"&&r.from;e&&(Xe.set("int64",BigInt64Array),Rt.set(BigInt64Array,"int64")),t&&(Xe.set("uint64",BigUint64Array),Rt.set(BigUint64Array,"uint64")),i?(Xe.set("float16",r),Rt.set(r,"float16")):Xe.set("float16",Uint16Array)}}}),Us,Fs,pn=T(()=>{zr(),Us=e=>{let t=1;for(let r=0;r<e.length;r++){let i=e[r];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${r}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${i}`);t*=i}return t},Fs=(e,t)=>{switch(e.location){case"cpu":return new Je(e.type,e.data,t);case"cpu-pinned":return new Je({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Je({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Je({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Je({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Je,zr=T(()=>{Qe(),et(),hn(),pn(),Je=class{constructor(e,t,r){Bs();let i,a;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,a=e.dims,e.location){case"cpu-pinned":{let l=Xe.get(i);if(!l)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof l))throw new TypeError(`buffer should be of type ${l.name}`);this.cpuData=e.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let l,u;if(typeof e=="string")if(i=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");l=t}else{let c=Xe.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?l=c.from(t,BigInt):l=c.from(t)}else if(t instanceof c)l=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")l=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&c!==Uint16Array)l=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${c}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")i="string",l=e;else if(c==="boolean")i="bool",l=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(e instanceof Uint8ClampedArray)i="uint8",l=Uint8Array.from(e);else{let c=Rt.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=c,l=e}if(u===void 0)u=[l.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");a=u,this.cpuData=l,this.dataLocation="cpu"}let o=Us(a);if(this.cpuData&&o!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=a,this.size=o}static async fromImage(e,t){return at(e,t)}static fromTexture(e,t){return Kt(e,t)}static fromGpuBuffer(e,t){return Ct(e,t)}static fromMLTensor(e,t){return je(e,t)}static fromPinnedBuffer(e,t,r){return Ve(e,t,r)}toDataURL(e){return qe(this,e)}toImageData(e){return dt(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new 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 new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new 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 new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new 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 new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(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 new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Fs(this,e)}}}),ot,Ns=T(()=>{zr(),ot=Je}),ar,Dr,bt,yt,Et,kt,Vs=T(()=>{We(),ar=(e,t)=>{(typeof me.trace>"u"?!me.wasm.trace:!me.trace)||console.timeStamp(`${e}::ORT::${t}`)},Dr=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let a=0;a<r.length;a++){if(i&&!r[a].includes("TRACE_FUNC")){let o=`FUNC_${e}::${r[a].trim().split(" ")[1]}`;t&&(o+=`::${t}`),ar("CPU",o);return}r[a].includes("TRACE_FUNC")&&(i=!0)}},bt=e=>{(typeof me.trace>"u"?!me.wasm.trace:!me.trace)||Dr("BEGIN",e)},yt=e=>{(typeof me.trace>"u"?!me.wasm.trace:!me.trace)||Dr("END",e)},Et=e=>{(typeof me.trace>"u"?!me.wasm.trace:!me.trace)||console.time(`ORT::${e}`)},kt=e=>{(typeof me.trace>"u"?!me.wasm.trace:!me.trace)||console.timeEnd(`ORT::${e}`)}}),Gs,mn=T(()=>{Re(),Ns(),Vs(),Gs=class Jh{constructor(t){this.handler=t}async run(t,r,i){bt(),Et("InferenceSession.run");let a={},o={};if(typeof t!="object"||t===null||t instanceof ot||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let l=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof ot)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(let h of r){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);a[h]=null}if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,p=Object.getOwnPropertyNames(r);for(let m of this.outputNames)if(p.indexOf(m)!==-1){let y=r[m];(y===null||y instanceof ot)&&(h=!0,l=!1,a[m]=y)}if(h){if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(l)for(let h of this.outputNames)a[h]=null;let u=await this.handler.run(t,a,o),c={};for(let h in u)if(Object.hasOwnProperty.call(u,h)){let p=u[h];p instanceof ot?c[h]=p:c[h]=new ot(p.type,p.data,p.dims)}return kt("InferenceSession.run"),yt(),c}async release(){return this.handler.dispose()}static async create(t,r,i,a){bt(),Et("InferenceSession.create");let o,l={};if(typeof t=="string"){if(o=t,typeof r=="object"&&r!==null)l=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(o=t,typeof r=="object"&&r!==null)l=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let p=t,m=0,y=t.byteLength;if(typeof r=="object"&&r!==null)l=r;else if(typeof r=="number"){if(m=r,!Number.isSafeInteger(m))throw new RangeError("'byteOffset' must be an integer.");if(m<0||m>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(y=t.byteLength-m,typeof i=="number"){if(y=i,!Number.isSafeInteger(y))throw new RangeError("'byteLength' must be an integer.");if(y<=0||m+y>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-m}].`);if(typeof a=="object"&&a!==null)l=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,m,y)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,c]=await fe(l),h=await u.createInferenceSessionHandler(o,c);return kt("InferenceSession.create"),yt(),new Jh(h)}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}}}),Lr,fn=T(()=>{mn(),Lr=Gs}),gn=T(()=>{}),yn=T(()=>{}),wn=T(()=>{}),vn=T(()=>{}),Ws={};K(Ws,{InferenceSession:()=>Lr,TRACE:()=>ar,TRACE_EVENT_BEGIN:()=>Et,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>bt,TRACE_FUNC_END:()=>yt,Tensor:()=>ot,env:()=>de,registerBackend:()=>re});var wt=T(()=>{Pe(),st(),fn(),Ns(),gn(),yn(),Vs(),wn(),vn()}),Br=T(()=>{}),qs={};K(qs,{default:()=>Hs});var Ur,Fr,Hs,bn=T(()=>{dh(),Dt(),qr(),Ur="ort-wasm-proxy-worker",Fr=globalThis.self?.name===Ur,Fr&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":Kr(r.wasm).then(()=>{pa(r).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:a}=r;ma(a,i).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})});break}case"copy-from":{let{buffer:i}=r,a=sn(i);postMessage({type:t,out:a});break}case"create":{let{model:i,options:a}=r;ga(i,a).then(o=>{postMessage({type:t,out:o})},o=>{postMessage({type:t,err:o})});break}case"release":ya(r),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:a,inputs:o,outputIndices:l,options:u}=r;va(i,a,o,l,new Array(l.length).fill(null),u).then(c=>{c.some(h=>h[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:c},_a([...o,...c]))},c=>{postMessage({type:t,err:c})});break}case"end-profiling":ba(r),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),Hs=Fr?null:e=>new Worker(e??Ye,{type:"classic",name:Ur})}),js,Ks,Ye,Nr,fr,Qs,Xs,Vr,Zs,Gr,Js,Wr,Ys,qr=T(()=>{Br(),js=typeof location>"u"?void 0:location.origin,Ks=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,Ye=Ks(),Nr=()=>{if(Ye&&!Ye.startsWith("blob:"))return Ye.substring(0,Ye.lastIndexOf("/")+1)},fr=(e,t)=>{try{let r=t??Ye;return(r?new URL(e,r):new URL(e)).origin===js}catch{return!1}},Qs=(e,t)=>{let r=t??Ye;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Xs=(e,t)=>`${t??"./"}${e}`,Vr=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Zs=async e=>(await import(e)).default,Gr=(bn(),ae(qs)).default,Js=async()=>{if(!Ye)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(fr(Ye))return[void 0,Gr()];let e=await Vr(Ye);return[e,Gr(e)]},Wr=void 0,Ys=async(e,t,r,i)=>{let a=Wr&&!(e||t);if(a)if(Ye)a=fr(Ye)||i&&!r;else if(i&&!r)a=!0;else throw new Error("cannot determine the script source URL.");if(a)return[void 0,Wr];{let o="ort-wasm-simd-threaded.jsep.mjs",l=e??Qs(o,t),u=r&&l&&!fr(l,t),c=u?await Vr(l):l??Xs(o,t);return[u?c:void 0,await Zs(c)]}}}),Hr,gr,Qt,jr,ei,ti,ri,Kr,Me,Dt=T(()=>{qr(),gr=!1,Qt=!1,jr=!1,ei=()=>{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}},ti=()=>{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}},ri=()=>{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}},Kr=async e=>{if(gr)return Promise.resolve();if(Qt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(jr)throw new Error("previous call to 'initializeWebAssembly()' failed.");Qt=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!ri())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ti())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=ei();r>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", 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=r=1);let a=e.wasmPaths,o=typeof a=="string"?a:void 0,l=a?.mjs,u=l?.href??l,c=a?.wasm,h=c?.href??c,p=e.wasmBinary,[m,y]=await Ys(u,o,r>1,!!p||!!h),w=!1,v=[];if(t>0&&v.push(new Promise(x=>{setTimeout(()=>{w=!0,x()},t)})),v.push(new Promise((x,R)=>{let C={numThreads:r};if(p)C.wasmBinary=p,C.locateFile=$=>$;else if(h||o)C.locateFile=$=>h??o+$;else if(u&&u.indexOf("blob:")!==0)C.locateFile=$=>new URL($,u).href;else if(m){let $=Nr();$&&(C.locateFile=I=>$+I)}y(C).then($=>{Qt=!1,gr=!0,Hr=$,x(),m&&URL.revokeObjectURL(m)},$=>{Qt=!1,jr=!0,R($)})})),await Promise.race(v),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Me=()=>{if(gr&&Hr)return Hr;throw new Error("WebAssembly is not initialized yet.")}}),lt,yr,$e,Qr=T(()=>{Dt(),lt=(e,t)=>{let r=Me(),i=r.lengthBytesUTF8(e)+1,a=r._malloc(i);return r.stringToUTF8(e,a,i),t.push(a),a},yr=(e,t,r,i)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([a,o])=>{let l=t?t+a:a;if(typeof o=="object")yr(o,l+".",r,i);else if(typeof o=="string"||typeof o=="number")i(l,o.toString());else if(typeof o=="boolean")i(l,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},$e=e=>{let t=Me(),r=t.stackSave();try{let i=t.PTR_SIZE,a=t.stackAlloc(2*i);t._OrtGetLastError(a,a+i);let o=Number(t.getValue(a,i===4?"i32":"i64")),l=t.getValue(a+i,"*"),u=l?t.UTF8ToString(l):"";throw new Error(`${e} ERROR_CODE: ${o}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(r)}}}),si,_n=T(()=>{Dt(),Qr(),si=e=>{let t=Me(),r=0,i=[],a=e||{};try{if(e?.logSeverityLevel===void 0)a.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)a.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(a.terminate=!1);let o=0;return e?.tag!==void 0&&(o=lt(e.tag,i)),r=t._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,o),r===0&&$e("Can't create run options."),e?.extra!==void 0&&yr(e.extra,"",new WeakSet,(l,u)=>{let c=lt(l,i),h=lt(u,i);t._OrtAddRunConfigEntry(r,c,h)!==0&&$e(`Can't set a run config entry: ${l} - ${u}.`)}),[r,i]}catch(o){throw r!==0&&t._OrtReleaseRunOptions(r),i.forEach(l=>t._free(l)),o}}}),ii,ni,ai,It,oi,li,Sn=T(()=>{Dt(),Qr(),ii=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 new Error(`unsupported graph optimization level: ${e}`)}},ni=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},ai=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},It=(e,t,r,i)=>{let a=lt(t,i),o=lt(r,i);Me()._OrtAddSessionConfigEntry(e,a,o)!==0&&$e(`Can't set a session config entry: ${t} - ${r}.`)},oi=async(e,t,r)=>{let i=t.executionProviders;for(let a of i){let o=typeof a=="string"?a:a.name,l=[];switch(o){case"webnn":if(o="WEBNN",It(e,"session.disable_quant_qdq","1",r),It(e,"session.disable_qdq_constant_folding","1",r),typeof a!="string"){let m=a?.deviceType;m&&It(e,"deviceType",m,r)}break;case"webgpu":if(o="JS",typeof a!="string"){let m=a;if(m?.preferredLayout){if(m.preferredLayout!=="NCHW"&&m.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${m.preferredLayout}`);It(e,"preferredLayout",m.preferredLayout,r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let u=lt(o,r),c=l.length,h=0,p=0;if(c>0){h=Me()._malloc(c*Me().PTR_SIZE),r.push(h),p=Me()._malloc(c*Me().PTR_SIZE),r.push(p);for(let m=0;m<c;m++)Me().setValue(h+m*Me().PTR_SIZE,l[m][0],"*"),Me().setValue(p+m*Me().PTR_SIZE,l[m][1],"*")}await Me()._OrtAppendExecutionProvider(e,u,h,p,c)!==0&&$e(`Can't append execution provider: ${o}.`)}},li=async e=>{let t=Me(),r=0,i=[],a=e||{};ai(a);try{let o=ii(a.graphOptimizationLevel??"all"),l=ni(a.executionMode??"sequential"),u=typeof a.logId=="string"?lt(a.logId,i):0,c=a.logSeverityLevel??2;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log severity level is not valid: ${c}`);let h=a.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let p=typeof a.optimizedModelFilePath=="string"?lt(a.optimizedModelFilePath,i):0;if(r=t._OrtCreateSessionOptions(o,!!a.enableCpuMemArena,!!a.enableMemPattern,l,!!a.enableProfiling,0,u,c,h,p),r===0&&$e("Can't create session options."),a.executionProviders&&await oi(r,a,i),a.enableGraphCapture!==void 0){if(typeof a.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${a.enableGraphCapture}`);It(r,"enableGraphCapture",a.enableGraphCapture.toString(),i)}if(a.freeDimensionOverrides)for(let[m,y]of Object.entries(a.freeDimensionOverrides)){if(typeof m!="string")throw new Error(`free dimension override name must be a string: ${m}`);if(typeof y!="number"||!Number.isInteger(y)||y<0)throw new Error(`free dimension override value must be a non-negative integer: ${y}`);let w=lt(m,i);t._OrtAddFreeDimensionOverride(r,w,y)!==0&&$e(`Can't set a free dimension override: ${m} - ${y}.`)}return a.extra!==void 0&&yr(a.extra,"",new WeakSet,(m,y)=>{It(r,m,y,i)}),[r,i]}catch(o){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&$e("Can't release session options."),i.forEach(l=>t._free(l)),o}}}),Lt,Bt,Ut,Xr,Zr,Jr,Yr,gs,Ee=T(()=>{Lt=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 new Error(`unsupported data type: ${e}`)}},Bt=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 new Error(`unsupported data type: ${e}`)}},Ut=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i=typeof t=="number"?t:t.reduce((a,o)=>a*o,1);return r>0?Math.ceil(i*r):void 0},Xr=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?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 new Error(`unsupported type: ${e}`)}},Zr=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 new Error(`unsupported logging level: ${e}`)}},Jr=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Yr=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",gs=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 new Error(`unsupported data location: ${e}`)}}}),es,ui=T(()=>{Br(),es=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),i=r?parseInt(r,10):0;if(i<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let a=t.body.getReader(),o;try{o=new ArrayBuffer(i)}catch(u){if(u instanceof RangeError){let c=Math.ceil(i/65536);o=new WebAssembly.Memory({initial:c,maximum:c}).buffer}else throw u}let l=0;for(;;){let{done:u,value:c}=await a.read();if(u)break;let h=c.byteLength;new Uint8Array(o,l,h).set(c),l+=h}return new Uint8Array(o,0,i)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),di,ys,ws,or,vs,bs,Fe,Vt=T(()=>{Ee(),di=["V","I","W","E","F"],ys=(e,t)=>{console.log(`[${di[e]},${new Date().toISOString()}]${t}`)},vs=(e,t)=>{ws=e,or=t},bs=(e,t)=>{let r=Zr(e),i=Zr(ws);r>=i&&ys(r,typeof t=="function"?t():t)},Fe=(...e)=>{or&&bs(...e)}}),_s,lr,q,Er,Ss,ci,Xt,xe=T(()=>{_s=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},lr=class{static calcShape(e,t,r=!1){let i=e.length,a=t.length;if(i===0)return t;if(a===0)return e;let o=Math.max(e.length,t.length),l=new Array(o);if(r){if(i<2||a<2)return;let u=_s.calcMatMulShape([e[i-2],e[i-1]],[t[a-2],t[a-1]]);if(u===void 0)return;[l[o-2],l[o-1]]=u}for(let u=r?3:1;u<=o;u++){let c=i-u<0?1:e[i-u],h=a-u<0?1:t[a-u];if(c!==h&&c>1&&h>1)return;let p=Math.max(c,h);if(c&&h)l[o-u]=Math.max(c,h);else{if(p>1)return;l[o-u]=0}}return l}static isValidBroadcast(e,t){let r=e.length,i=t.length;if(r>i)return!1;for(let a=1;a<=r;a++)if(e[r-a]!==1&&e[r-a]!==t[i-a])return!1;return!0}},q=class ln{static size(t){return ln.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let i=t.length;if(i===0)return[];let a=new Array(i),o=i-1;for(;o>=0;){if(t[o]%r===0){a[o]=t[o]/r;break}if(r%t[o]!==0)throw new Error("cannot convert shape");a[o]=1,r/=t[o],o--}for(o--;o>=0;o--)a[o]=t[o];return a}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return ln.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return ln.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,i){let a=1;for(let o=r;o<i;o++){if(t[o]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");a*=Number(t[o])}return a}static computeStrides(t){let r=t.length;if(r===0)return[];if(r===1)return[1];let i=new Array(r);i[r-1]=1,i[r-2]=t[r-1];for(let a=r-3;a>=0;--a)i[a]=i[a+1]*t[a+1];return i}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(i=>this.normalizeAxis(i,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(i=>t[i]):t.slice().reverse()}static padShape(t,r){let i=t.length;return t.map((a,o)=>a+r[o]+r[o+i])}static areEqual(t,r){return t.length!==r.length?!1:t.every((i,a)=>i===r[a])}},Er=class Ui{static adjustPoolAttributes(t,r,i,a,o,l){if(!t&&i.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u<r.length-2;u++)u>=i.length?i.push(r[u+2]):i[u]=r[u+2];for(let u=0;u<i.length;u++)if(u<a.length){if(a[u]<0)throw new Error("strides should be greater than or equal to 1")}else a.push(1);for(let u=0;u<i.length;u++)if(u<o.length){if(o[u]<0)throw new Error("dilations should be greater than or equal to 1")}else o.push(1);for(let u=0;u<i.length*2;u++)if(u<l.length){if(l[u]<0)throw new Error("pad should be greater than or equal to 1")}else l.push(0);for(let u=0;u<i.length;u++){if(i[u]<=0)throw new Error("kernel shapes need to be greater than 0");if(l[u]>=i[u]||l[u+i.length]>=i[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,i,a,o,l,u){if(u){if(o.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(a.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let c=0;c<t.length-2;c++)Ui.adjustPadAndReturnShape(t[c+(l?1:2)],r[c],i[c],a[c],o,c,c+t.length-2,u)}}static computePoolOutputShape(t,r,i,a,o,l,u){if(r.length<=0)throw new Error("input shape must be of size greater than 0");let c=[r[0],r[1]];return Ui.computeShapeHelper(t,r,c,i,a,o,l,u),c}static computeConvOutputShape(t,r,i,a,o,l,u){if(t.length<=0||r.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let c=[t[0],r[0]];return Ui.computeShapeHelper(!1,t,c,i,a,o,l,u),c}static computeShapeHelper(t,r,i,a,o,l,u,c){if(t)for(let h=0;h<r.length-2;h++)i.push(1);else for(let h=0;h<r.length-2;h++)i.push(Ui.adjustPadAndReturnShape(r[h+2],a[h],o[h],l[h],u,h,h+r.length-2,c))}static adjustPadAndReturnShape(t,r,i,a,o,l,u,c){let h=i*(a-1)+1;if(c&&c!=="NOTSET")switch(c){case"VALID":return o[l]=0,o[u]=0,Math.floor((t-h)/r+1);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let p=((t+r-1)/r-1)*r+a-t;return o[l]=Math.floor(c==="SAME_LOWER"?(p+1)/2:p/2),o[u]=p-o[l],Math.floor((t+p-a)/r+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((t+o[l]+o[u]-h)/r+1)}},Ss=class{static getShapeOfGemmResult(e,t,r,i,a){if(e.length!==2||r.length!==2)throw new Error("shape need to be of size 2");let o,l,u;t?(o=e[1],l=e[0]):(o=e[0],l=e[1]);let c=-1;if(i?(u=r[0],c=1):(u=r[1],c=0),r[c]!==l)throw new Error("dimension mismatch");if(o<=0||u<=0||l<=0)throw new Error("invalid shape specified");if(a&&!lr.isValidBroadcast(a,[o,u]))throw new Error("gemm: invalid bias shape for broadcast");return[o,u,l]}},ci=-34028234663852886e22,Xt=34028234663852886e22}),ur,kr=T(()=>{Ee(),ur=(e,t)=>new(Xr(t))(e)}),wr,Mr,ts,rs,Zt,dr,$s,xs,Ts,hi,pi,Vi=T(()=>{Ee(),Vt(),wr=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Mr=(e,t)=>{if(t==="int32")return e;let r=wr.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);let i=r/8;if(e.byteLength%i!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${i}.`);let a=e.byteLength/i,o=new(Xr(t))(e.buffer,e.byteOffset,a);switch(t){case"int64":case"uint64":{let l=new Int32Array(a);for(let u=0;u<a;u++){let c=o[u];if(c>2147483647n||c<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");l[u]=Number(c)}return new Uint8Array(l.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&o.some(u=>u>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let l=Int32Array.from(o,Number);return new Uint8Array(l.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},ts=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let a=BigInt64Array.from(i,BigInt);return new Uint8Array(a.buffer)}case"uint64":{if(i.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let a=BigUint64Array.from(i,BigInt);return new Uint8Array(a.buffer)}case"int8":{if(i.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let a=Int8Array.from(i,Number);return new Uint8Array(a.buffer)}case"uint8":{if(i.some(a=>a<0||a>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(i,Number)}case"uint32":{if(i.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let a=Uint32Array.from(i,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},rs=1,Zt=()=>rs++,dr=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),$s=(e,t)=>{let r=wr.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,a)=>i*a)*r/8):0},xs=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:i,dataType:a,shape:o,fallbackDataType:l}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=i,this.dataType=a,this.tensorShape=o,this.fallbackDataType=l}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return $s(this.dataType,this.tensorShape)}destroy(){Fe("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),r=ts(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((i,a)=>i===r[a])}setIsDataConverted(e){this.isDataConverted=e}},Ts=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,r,i){let a=this.tensorManager.getMLContext(e),o=this.tensorManager.getMLOpSupportLimits(e),l;if(!o?.input.dataTypes.includes(t)){if(l=dr.get(t),!l||o?.input.dataTypes.includes(l))throw new Error(`WebNN backend does not support data type: ${t}`);Fe("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${l}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(a,t,r))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==$s(t,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let u=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,u,!0,!0,l),i&&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=Mr(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Fe("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?ts(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}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},hi=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Zt();return this.tensorTrackersById.set(e,new Ts(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,r,i,a){Fe("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${i}, copyOld: ${a}}`);let o=this.tensorTrackersById.get(t);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(e,r,i,a)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){Fe("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.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,r,i){let a=this.getMLContext(e),o=Zt(),l=new xs({sessionId:e,context:a,tensor:t,dataType:r,shape:i});return this.tensorTrackersById.set(o,new Ts(this,l)),this.externalTensors.add(l),o}async getCachedTensor(e,t,r,i,a,o,l){let u=this.getMLContext(e);for(let[h,p]of this.freeTensors.entries())if(p.canReuseTensor(u,t,r)){Fe("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${l?`fallbackDataType: ${l},`:""} shape: ${r}`);let m=this.freeTensors.splice(h,1)[0];return m.sessionId=e,m}Fe("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${l?`fallbackDataType: ${l},`:""} shape: ${r}}`);let c=await u.createTensor({dataType:l??t,shape:r,dimensions:r,usage:i,writable:a,readable:o});return new xs({sessionId:e,context:u,tensor:c,dataType:t,shape:r,fallbackDataType:l})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},pi=(...e)=>new hi(...e)}),Rr,mi,fi,gi=T(()=>{Ee(),Dt(),kr(),Vi(),Vt(),Rr=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),mi=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),i=Object.keys(t).sort();return r.length===i.length&&r.every((a,o)=>a===i[o]&&e[a]===t[a])},fi=class{constructor(e){this.tensorManager=pi(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,vs(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Fe("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Fe("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)Fe("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(i=>i.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let i=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:i}),i}}else if(e===void 0){let r=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let t=this.mlContextCache.findIndex(r=>mi(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.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 r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let i=this.mlContextCache.findIndex(a=>a.mlContext===t);i!==-1&&this.mlContextCache.splice(i,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Fe("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,i,a){let o=Rr.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,o,i,a)}async createTemporaryTensor(e,t,r){Fe("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let i=Rr.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let a=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,a,i,r,!1);let o=this.temporarySessionTensorIds.get(e);return o?o.push(a):this.temporarySessionTensorIds.set(e,[a]),a}uploadTensor(e,t){if(!Me().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Fe("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 r=await this.tensorManager.download(e);return ur(r,t)}}registerMLTensor(e,t,r,i){let a=Rr.get(r);if(!a)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(e,t,a,i);return Fe("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${a}, dimensions: ${i}} -> {tensorId: ${o}}`),o}registerMLConstant(e,t,r,i,a,o,l=!1){if(!o)throw new Error("External mounted files are not available.");let u=e;e.startsWith("./")&&(u=e.substring(2));let c=o.get(u);if(!c)throw new Error(`File with name ${u} not found in preloaded files.`);if(t+r>c.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let h=c.slice(t,t+r).buffer,p;switch(a.dataType){case"float32":p=new Float32Array(h);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(h):new Uint16Array(h);break;case"int32":p=new Int32Array(h);break;case"uint32":p=new Uint32Array(h);break;case"int64":if(l){let m=Mr(new Uint8Array(h),"int64");p=new Int32Array(m.buffer),a.dataType="int32"}else p=new BigInt64Array(h);break;case"uint64":p=new BigUint64Array(h);break;case"int8":p=new Int8Array(h);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(h);break;default:throw new Error(`Unsupported data type: ${a.dataType} in creating WebNN Constant from external data.`)}return Fe("verbose",()=>`[WebNN] registerMLConstant {dataType: ${a.dataType}, shape: ${a.shape}}} ${l?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),i.constant(a,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let i=Rr.get(Lt(t)),a=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:r?!!a?.input.dataTypes.includes(i):!!a?.output.dataTypes.includes(i)}flush(){}}}),Cs=T(()=>{}),Es,ks,ss,Ms,Rs,Is,yi,wi,Gi,$n=T(()=>{Vt(),Cs(),Es=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),ks=[],ss=e=>Math.ceil(Number(e)/16)*16,Ms=e=>{for(let t=0;t<ks.length;t++){let r=ks[t];if(e<=r)return r}return Math.ceil(e/16)*16},Rs=1,Is=()=>Rs++,yi=async(e,t,r,i)=>{let a=ss(r),o=e.device.createBuffer({size:a,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let l=e.getCommandEncoder();e.endComputePass(),l.copyBufferToBuffer(t,0,o,0,a),e.flush(),await o.mapAsync(GPUMapMode.READ);let u=o.getMappedRange();if(i){let c=i();return c.set(new Uint8Array(u,0,r)),c}else return new Uint8Array(u.slice(0,r))}finally{o.destroy()}},wi=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of Es)ks.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let r=t.buffer,i=t.byteOffset,a=t.byteLength,o=ss(a),l=this.storageCache.get(e);if(!l)throw new Error("gpu data for uploading does not exist");if(Number(l.originalSize)!==a)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${a}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=u.getMappedRange();new Uint8Array(c).set(new Uint8Array(r,i,a)),u.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(u,0,l.gpuData.buffer,0,o),this.backend.device.queue.submit([h.finish()]),u.destroy(),Fe("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(t);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let a=ss(r.originalSize),o=this.backend.getCommandEncoder();this.backend.endComputePass(),o.copyBufferToBuffer(r.gpuData.buffer,0,i.gpuData.buffer,0,a)}registerExternalBuffer(e,t,r){let i;if(r){if(i=r[0],e===r[1])return Fe("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.
|
|
6
|
+
Please use the previous external buffer!`)}else i=Is();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:t}),Fe("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Fe("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=Ms(e),i,a=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,o=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(a||o){let u=(a?this.freeBuffers:this.freeUniformBuffers).get(r);u?u.length>0?i=u.pop():i=this.backend.device.createBuffer({size:r,usage:t}):i=this.backend.device.createBuffer({size:r,usage:t})}else i=this.backend.device.createBuffer({size:r,usage:t});let l={id:Is(),type:0,buffer:i};return this.storageCache.set(l.id,{gpuData:l,originalSize:Number(e)}),Fe("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${l.id}`),l}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,r=this.storageCache.get(t);if(!r){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Fe("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(e,t){let r=this.storageCache.get(Number(e));if(!r)throw new Error("data does not exist");await yi(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=Es.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Fe("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(r=>{r.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Gi=(...e)=>new wi(...e)}),f,_,k=T(()=>{f=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},_=e=>new f(e)}),z,P,N,B,D,F,Z,Y,Q,H,ve,U,te,tt,ze,be,De,he=T(()=>{Ee(),xe(),z=64,P=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}<f16>`:"f16";case 1:return t>1?`vec${t}<f32>`:"f32";case 6:return t>1?`vec${t}<i32>`:"i32";case 12:return t>1?`vec${t}<u32>`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4<bool>"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},N=(e,t=1)=>{let r=P(e,t);return typeof r=="string"?r:r[0]},B=(e,t=1)=>{let r=P(e,t);return typeof r=="string"?r:r[1]},D=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:q.computeStrides(r)})}),t},F=e=>e%4===0?4:e%2===0?2:1,Z=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Y=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}<f32>(${r})`,Q=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,H=(e,t,r,i)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?i==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:i==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,ve=(e,t,r,i,a)=>{let o=typeof r=="number",l=o?r:r.length,u=[...new Array(l).keys()],c=l<2?"u32":l<=4?`vec${l}<u32>`:`array<u32, ${l}>`,h=P(t,a),p=typeof h=="string"?h:h[1],m=typeof h=="string"?h:h[0],y={indices:c,value:p,storage:m,tensor:t},w=ee=>typeof ee=="string"?ee:`${ee}u`,v={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},x=o?"uniforms.":"",R=`${x}${e}_shape`,C=`${x}${e}_strides`,$="";for(let ee=0;ee<l-1;ee++)$+=`
|
|
7
|
+
let dim${ee} = current / ${H(C,ee,l)};
|
|
8
|
+
let rest${ee} = current % ${H(C,ee,l)};
|
|
9
|
+
indices[${ee}] = dim${ee};
|
|
10
|
+
current = rest${ee};
|
|
11
|
+
`;$+=`indices[${l-1}] = current;`;let I=l<2?"":`
|
|
12
|
+
fn o2i_${e}(offset: u32) -> ${y.indices} {
|
|
13
|
+
var indices: ${y.indices};
|
|
14
|
+
var current = offset;
|
|
15
|
+
${$}
|
|
16
|
+
return indices;
|
|
17
|
+
}`,M=ee=>(v.offsetToIndices=!0,l<2?ee:`o2i_${e}(${ee})`),L=[];if(l>=2)for(let ee=l-1;ee>=0;ee--)L.push(`${H(C,ee,l)} * (indices[${ee}])`);let V=l<2?"":`
|
|
18
|
+
fn i2o_${e}(indices: ${y.indices}) -> u32 {
|
|
19
|
+
return ${L.join("+")};
|
|
20
|
+
}`,W=ee=>(v.indicesToOffset=!0,l<2?ee:`i2o_${e}(${ee})`),X=(...ee)=>l===0?"0u":`${y.indices}(${ee.map(w).join(",")})`,se=(ee,Ie)=>l<2?`${ee}`:`${H(ee,Ie,l)}`,ge=(ee,Ie,Ce)=>l<2?`${ee}=${Ce};`:`${H(ee,Ie,l)}=${Ce};`,Be={},Te=(ee,Ie)=>{v.broadcastedIndicesToOffset=!0;let Ce=`${Ie.name}broadcastedIndicesTo${e}Offset`;if(Ce in Be)return`${Ce}(${ee})`;let _e=[];for(let xt=l-1;xt>=0;xt--){let Ft=Ie.indicesGet("outputIndices",xt+Ie.rank-l);_e.push(`${se(C,xt)} * (${Ft} % ${se(R,xt)})`)}return Be[Ce]=`fn ${Ce}(outputIndices: ${Ie.type.indices}) -> u32 {
|
|
21
|
+
return ${_e.length>0?_e.join("+"):"0u"};
|
|
22
|
+
}`,`${Ce}(${ee})`},ke=(ee,Ie)=>(()=>{if(y.storage===y.value)return`${e}[${ee}]=${Ie};`;if(y.storage==="vec2<u32>"&&y.value==="i32")return`${e}[${ee}]=vec2<u32>(u32(${Ie}), select(0u, 0xFFFFFFFFu, ${Ie} < 0));`;if(y.storage==="vec2<u32>"&&y.value==="u32")return`${e}[${ee}]=vec2<u32>(u32(${Ie}), 0u);`;if(y.storage==="u32"&&y.value==="vec4<bool>")return`${e}[${ee}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${Ie}));`;throw new Error(`not supported combination of storage type ${y.storage} and value type ${y.value} yet`)})(),Ge=ee=>(()=>{if(y.storage===y.value)return`${e}[${ee}]`;if(y.storage==="vec2<u32>"&&y.value==="i32")return`i32(${e}[${ee}].x)`;if(y.storage==="vec2<u32>"&&y.value==="u32")return`u32(${e}[${ee}].x)`;if(y.storage==="u32"&&y.value==="vec4<bool>")return`vec4<bool>(bool(${e}[${ee}] & 0xFFu), bool(${e}[${ee}] & 0xFF00u), bool(${e}[${ee}] & 0xFF0000u), bool(${e}[${ee}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${y.storage} and value type ${y.value} yet`)})(),ue=l<2?"":`
|
|
23
|
+
fn get_${e}ByIndices(indices: ${y.indices}) -> ${p} {
|
|
24
|
+
return ${Ge(`i2o_${e}(indices)`)};
|
|
25
|
+
}`,Se=l<2?"":(()=>{let ee=u.map(Ce=>`d${Ce}: u32`).join(", "),Ie=u.map(Ce=>`d${Ce}`).join(", ");return`
|
|
26
|
+
fn get_${e}(${ee}) -> ${p} {
|
|
27
|
+
return get_${e}ByIndices(${X(Ie)});
|
|
28
|
+
}`})(),Oe=(...ee)=>{if(ee.length!==l)throw new Error(`indices length must be ${l}`);let Ie=ee.map(w).join(",");return l===0?Ge("0u"):l===1?Ge(Ie[0]):(v.get=!0,v.getByIndices=!0,v.indicesToOffset=!0,`get_${e}(${Ie})`)},Ue=ee=>l<2?Ge(ee):(v.getByIndices=!0,v.indicesToOffset=!0,`get_${e}ByIndices(${ee})`),Ae=l<2?"":`
|
|
29
|
+
fn set_${e}ByIndices(indices: ${y.indices}, value: ${p}) {
|
|
30
|
+
${ke(`i2o_${e}(indices)`,"value")}
|
|
31
|
+
}`,Ne=l<2?"":(()=>{let ee=u.map(Ce=>`d${Ce}: u32`).join(", "),Ie=u.map(Ce=>`d${Ce}`).join(", ");return`
|
|
32
|
+
fn set_${e}(${ee}, value: ${p}) {
|
|
33
|
+
set_${e}ByIndices(${X(Ie)}, value);
|
|
34
|
+
}`})();return{impl:()=>{let ee=[],Ie=!1;return v.offsetToIndices&&(ee.push(I),Ie=!0),v.indicesToOffset&&(ee.push(V),Ie=!0),v.broadcastedIndicesToOffset&&(Object.values(Be).forEach(Ce=>ee.push(Ce)),Ie=!0),v.set&&(ee.push(Ne),Ie=!0),v.setByIndices&&(ee.push(Ae),Ie=!0),v.get&&(ee.push(Se),Ie=!0),v.getByIndices&&(ee.push(ue),Ie=!0),!o&&Ie&&ee.unshift(`const ${R} = ${y.indices}(${r.join(",")});`,`const ${C} = ${y.indices}(${q.computeStrides(r).join(",")});`),ee.join(`
|
|
35
|
+
`)},type:y,offsetToIndices:M,indicesToOffset:W,broadcastedIndicesToOffset:Te,indices:X,indicesGet:se,indicesSet:ge,set:(...ee)=>{if(ee.length!==l+1)throw new Error(`indices length must be ${l}`);let Ie=ee[l];if(typeof Ie!="string")throw new Error("value must be string");let Ce=ee.slice(0,l).map(w).join(",");return l===0?ke("0u",Ie):l===1?ke(Ce[0],Ie):(v.set=!0,v.setByIndices=!0,v.indicesToOffset=!0,`set_${e}(${Ce}, ${Ie})`)},setByOffset:ke,setByIndices:(ee,Ie)=>l<2?ke(ee,Ie):(v.setByIndices=!0,v.indicesToOffset=!0,`set_${e}ByIndices(${ee}, ${Ie});`),get:Oe,getByOffset:Ge,getByIndices:Ue,usage:i,name:e,strides:C,shape:R,rank:l}},U=(e,t,r,i=1)=>ve(e,t,r,"input",i),te=(e,t,r,i=1)=>ve(e,t,r,"output",i),tt=(e,t,r)=>ve(e,t,r,"atomicOutput",1),ze=(e,t,r,i=1)=>ve(e,t,r,"internal",i),be=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=z){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],i=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let a=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,o=a?`@builtin(global_invocation_id) global_id : vec3<u32>,
|
|
36
|
+
@builtin(workgroup_id) workgroup_id : vec3<u32>,
|
|
37
|
+
@builtin(local_invocation_index) local_idx : u32,
|
|
38
|
+
@builtin(local_invocation_id) local_id : vec3<u32>`:`@builtin(global_invocation_id) global_id : vec3<u32>,
|
|
39
|
+
@builtin(local_invocation_id) local_id : vec3<u32>,
|
|
40
|
+
@builtin(local_invocation_index) local_idx : u32,
|
|
41
|
+
@builtin(workgroup_id) workgroup_id : vec3<u32>,
|
|
42
|
+
@builtin(num_workgroups) num_workgroups : vec3<u32>`,l=a?`let global_idx = global_id.x;
|
|
43
|
+
let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +
|
|
44
|
+
workgroup_id.y * num_workgroups[0] + workgroup_id.x;
|
|
45
|
+
let global_idx = workgroup_index * ${t*r*i}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${i})
|
|
46
|
+
fn main(${o}) {
|
|
47
|
+
${l}
|
|
48
|
+
`}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let r=e.usage==="input"?"read":"read_write",i=e.usage==="atomicOutput"?"atomic<i32>":e.type.storage;return`@group(0) @binding(${t}) var<storage, ${r}> ${e.name}: array<${i}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(`
|
|
49
|
+
`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:i}of this.uniforms)if(i&&i>4)r==="f16"?e.push(`@align(16) ${t}:array<mat2x4<${r}>, ${Math.ceil(i/8)}>`):e.push(`${t}:array<vec4<${r}>, ${Math.ceil(i/4)}>`);else{let a=i==null||i===1?r:`vec${i}<${r}>`;e.push(`${t}:${a}`)}return`
|
|
50
|
+
struct Uniforms { ${e.join(", ")} };
|
|
51
|
+
@group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(`
|
|
52
|
+
`)+this.internalVariables.map(e=>e.impl()).join(`
|
|
53
|
+
`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},De=(e,t)=>new be(e,t)}),_t,St,cr,Ir,As,vi,it,Wt,bi,Le=T(()=>{Ee(),xe(),k(),he(),_t=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},St=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),cr=(e,t)=>q.sortBasedOnPerm(e,St(e.length,t)),Ir=(e,t,r,i)=>{let a=`fn perm(i: ${i.type.indices}) -> ${r.type.indices} {
|
|
54
|
+
var a: ${r.type.indices};`;for(let o=0;o<t;++o)a+=`a[${e[o]}]=i[${o}];`;return a+="return a;}"},As=(e,t)=>{let r=[],i=[];for(let a=0;a<e.length;++a)e[a]!==1&&r.push(e[a]),e[t[a]]!==1&&i.push(t[a]);return{newShape:r,newPerm:i}},vi=(e,t)=>{let r=0;for(let i=0;i<e.length;++i)if(t[e[i]]!==1){if(e[i]<r)return!1;r=e[i]}return!0},it=(e,t)=>{let r=e.dataType,i=e.dims.length,a=St(i,t),o=cr(e.dims,a),l=e.dims,u=o,c=i<2||vi(a,e.dims),h;if(c)return h=v=>{let x=U("input",r,l,4),R=te("output",r,u,4);return`
|
|
55
|
+
${v.registerUniform("output_size","u32").declareVariables(x,R)}
|
|
56
|
+
${v.mainStart()}
|
|
57
|
+
${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
58
|
+
output[global_idx] = input[global_idx];
|
|
59
|
+
}`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let v=q.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(v/64/4)},programUniforms:[{type:12,data:Math.ceil(v/4)}]}},getShaderSource:h};let{newShape:p,newPerm:m}=As(e.dims,a),y=q.areEqual(m,[2,3,1]),w=q.areEqual(m,[3,1,2]);if(p.length===2||y||w){l=y?[p[0],p[1]*p[2]]:w?[p[0]*p[1],p[2]]:p,u=[l[1],l[0]];let v=16;return h=x=>{let R=U("a",r,l.length),C=te("output",r,u.length);return`
|
|
60
|
+
${x.registerUniform("output_size","u32").declareVariables(R,C)}
|
|
61
|
+
var<workgroup> tile : array<array<${C.type.value}, ${v+1}>, ${v}>;
|
|
62
|
+
${x.mainStart([v,v,1])}
|
|
63
|
+
let stride = (uniforms.output_shape[1] - 1) / ${v} + 1;
|
|
64
|
+
let workgroup_id_x = workgroup_index % stride;
|
|
65
|
+
let workgroup_id_y = workgroup_index / stride;
|
|
66
|
+
let input_col = workgroup_id_y * ${v}u + local_id.x;
|
|
67
|
+
let input_row = workgroup_id_x * ${v}u + local_id.y;
|
|
68
|
+
if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {
|
|
69
|
+
tile[local_id.y][local_id.x] = ${R.getByIndices(`${R.type.indices}(input_row, input_col)`)};
|
|
70
|
+
}
|
|
71
|
+
workgroupBarrier();
|
|
72
|
+
|
|
73
|
+
let output_col = workgroup_id_x * ${v}u + local_id.x;
|
|
74
|
+
let output_row = workgroup_id_y * ${v}u + local_id.y;
|
|
75
|
+
if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {
|
|
76
|
+
${C.setByIndices(`${C.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")}
|
|
77
|
+
}
|
|
78
|
+
}`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let x=q.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u[1]/v),y:Math.ceil(u[0]/v)},programUniforms:[{type:12,data:x},...D(l,u)]}},getShaderSource:h}}return h=v=>{let x=U("a",r,l.length),R=te("output",r,u.length);return`
|
|
79
|
+
${v.registerUniform("output_size","u32").declareVariables(x,R)}
|
|
80
|
+
|
|
81
|
+
${Ir(a,i,x,R)}
|
|
82
|
+
|
|
83
|
+
${v.mainStart()}
|
|
84
|
+
${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
85
|
+
|
|
86
|
+
let indices = ${R.offsetToIndices("global_idx")};
|
|
87
|
+
let aIndices = perm(indices);
|
|
88
|
+
|
|
89
|
+
${R.setByOffset("global_idx",x.getByIndices("aIndices"))}
|
|
90
|
+
}`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let v=q.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},...D(l,u)]}},getShaderSource:h}},Wt=(e,t)=>{_t(e.inputs,t.perm),e.compute(it(e.inputs[0],t.perm))},bi=e=>_({perm:e.perm})}),Gt,Wi,Jt,is,ct,Mt,Ps,ns,_i,qi,vt,Yt,Ar,ht,nt,qt,Hi,ji,qa,Ha,ja,sm=T(()=>{Ee(),xe(),he(),Tn(),Le(),Gt={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},Wi={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},Jt={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},is={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},ct=(e,t)=>{let r=[];for(let i=t-e;i<t;++i)r.push(i);return r},Mt=(e,t)=>{let r=[],i=e.length;for(let o=0;o<i;o++)t.indexOf(o)===-1&&r.push(e[o]);let a=t.map(o=>e[o]);return[r,a]},Ps=(e,t)=>{let r=e.length+t.length,i=[],a=0;for(let o=0;o<r;o++)t.indexOf(o)===-1?i.push(e[a++]):i.push(1);return i},ns=(e,t)=>{for(let r=0;r<e.length;++r)if(e[e.length-r-1]!==t-1-r)return!1;return!0},_i=(e,t)=>{let r=[];if(!ns(e,t)){for(let i=0;i<t;++i)e.indexOf(i)===-1&&r.push(i);e.forEach(i=>r.push(i))}return r},qi=(e,t,r,i,a,o,l)=>{let u=r[0].dims,c=q.size(o),h=q.size(l),p=U("_A",r[0].dataType,u),m=te("output",a,o),y=64;c===1&&(y=256);let w=`
|
|
91
|
+
var<workgroup> aBestValues : array<f32, ${y}>;
|
|
92
|
+
`,v=x=>`
|
|
93
|
+
${x.registerUniform("reduceSize","u32").declareVariables(p,m)}
|
|
94
|
+
${w}
|
|
95
|
+
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
96
|
+
return ((a - 1u) / b + 1u);
|
|
97
|
+
}
|
|
98
|
+
${x.mainStart(y)}
|
|
99
|
+
|
|
100
|
+
let outputIndex = global_idx / ${y};
|
|
101
|
+
let offset = outputIndex * uniforms.reduceSize;
|
|
102
|
+
|
|
103
|
+
var bestValue = f32(${Jt[i]});
|
|
104
|
+
let Length = uniforms.reduceSize;
|
|
105
|
+
for (var k = local_idx; k < Length; k = k + ${y}) {
|
|
106
|
+
let candidate = f32(${p.getByOffset("offset + k")});
|
|
107
|
+
bestValue = ${Gt[i]};
|
|
108
|
+
}
|
|
109
|
+
aBestValues[local_idx] = bestValue;
|
|
110
|
+
workgroupBarrier();
|
|
111
|
+
|
|
112
|
+
var reduceSize = min(Length, ${y}u);
|
|
113
|
+
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
|
|
114
|
+
currentSize = reduceSize / 2u) {
|
|
115
|
+
let interval = DIV_CEIL(reduceSize, 2u);
|
|
116
|
+
if (local_idx < currentSize) {
|
|
117
|
+
let candidate = aBestValues[local_idx + interval];
|
|
118
|
+
bestValue = ${Wi[i]};
|
|
119
|
+
aBestValues[local_idx] = bestValue;
|
|
120
|
+
}
|
|
121
|
+
reduceSize = interval;
|
|
122
|
+
workgroupBarrier();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (local_idx == 0u) {
|
|
126
|
+
${m.setByOffset("outputIndex",`${i==="mean"?`${m.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${m.type.storage}(${is[i]})`}`)};
|
|
127
|
+
}
|
|
128
|
+
}`;return{name:e,shaderCache:{hint:`${t};${y}`,inputDependencies:["type"]},getShaderSource:v,getRunData:()=>({outputs:[{dims:o,dataType:a}],dispatchGroup:{x:c},programUniforms:[{type:12,data:h}]})}},vt=(e,t,r,i)=>{let a=e.inputs.length===1?r:xn(e.inputs,r),o=a.axes;o.length===0&&!a.noopWithEmptyAxes&&(o=e.inputs[0].dims.map((w,v)=>v));let l=q.normalizeAxes(o,e.inputs[0].dims.length),u=l,c=e.inputs[0],h=_i(u,e.inputs[0].dims.length);h.length>0&&(c=e.compute(it(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],u=ct(u.length,c.dims.length));let[p,m]=Mt(c.dims,u),y=p;a.keepDims&&(y=Ps(p,l)),e.compute(qi(t,a.cacheKey,[c],i,e.inputs[0].dataType,y,m),{inputs:[c]})},Yt=(e,t)=>{vt(e,"ReduceMeanShared",t,"mean")},Ar=(e,t)=>{vt(e,"ReduceL1Shared",t,"l1")},ht=(e,t)=>{vt(e,"ReduceL2Shared",t,"l2")},nt=(e,t)=>{vt(e,"ReduceLogSumExpShared",t,"logSumExp")},qt=(e,t)=>{vt(e,"ReduceMaxShared",t,"max")},Hi=(e,t)=>{vt(e,"ReduceMinShared",t,"min")},ji=(e,t)=>{vt(e,"ReduceProdShared",t,"prod")},qa=(e,t)=>{vt(e,"ReduceSumShared",t,"sum")},Ha=(e,t)=>{vt(e,"ReduceSumSquareShared",t,"sumSquare")},ja=(e,t)=>{vt(e,"ReduceLogSumShared",t,"logSum")}}),er,Ka,Ki,xn,tr,Qa,Xa,Za,Ja,Ya,eo,to,ro,so,io,rr,no,ao,oo,lo,uo,co,ho,po,mo,fo,Tn=T(()=>{Ee(),xe(),k(),he(),sm(),er=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Ka=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Ki=(e,t,r,i,a,o,l=!1,u=!1)=>{let c=[],h=r[0].dims,p=h.length,m=q.normalizeAxes(a,p),y=!u&&m.length===0;h.forEach((x,R)=>{y||m.indexOf(R)>=0?l&&c.push(1):c.push(x)});let w=c.length,v=q.size(c);return{name:e,shaderCache:t,getShaderSource:x=>{let R=[],C=U("_A",r[0].dataType,p),$=te("output",o,w),I=i(C,$,m),M=I[2];for(let L=0,V=0;L<p;L++)y||m.indexOf(L)>=0?(l&&V++,M=`for(var j${L}: u32 = 0; j${L} < ${h[L]}; j${L}++) {
|
|
129
|
+
${I[2].includes("last_index")?`let last_index = j${L};`:""}
|
|
130
|
+
${C.indicesSet("input_indices",L,`j${L}`)}
|
|
131
|
+
${M}
|
|
132
|
+
}`):(R.push(`${C.indicesSet("input_indices",L,$.indicesGet("output_indices",V))};`),V++);return`
|
|
133
|
+
|
|
134
|
+
${x.registerUniform("output_size","u32").declareVariables(C,$)}
|
|
135
|
+
|
|
136
|
+
${x.mainStart()}
|
|
137
|
+
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
138
|
+
var input_indices: ${C.type.indices};
|
|
139
|
+
let output_indices = ${$.offsetToIndices("global_idx")};
|
|
140
|
+
|
|
141
|
+
${R.join(`
|
|
142
|
+
`)}
|
|
143
|
+
${I[0]} // init ops for reduce max/min
|
|
144
|
+
${I[1]}
|
|
145
|
+
${M}
|
|
146
|
+
${I[3]}
|
|
147
|
+
${I.length===4?$.setByOffset("global_idx","value"):I.slice(4).join(`
|
|
148
|
+
`)}
|
|
149
|
+
}`},getRunData:()=>({outputs:[{dims:c,dataType:o}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},...D(h,c)]})}},xn=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(i=>r.push(Number(i))),_({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},tr=(e,t,r,i)=>{let a=e.inputs,o=a.length===1?r:xn(a,r);e.compute(Ki(t,{hint:o.cacheKey,inputDependencies:["rank"]},[a[0]],o.noopWithEmptyAxes&&o.axes.length===0?Ka:i,o.axes,a[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},Qa=(e,t)=>{er(e.inputs),tr(e,"ReduceLogSum",t,(r,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Xa=(e,t)=>{er(e.inputs),tr(e,"ReduceL1",t,(r,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Za=(e,t)=>{er(e.inputs),tr(e,"ReduceL2",t,(r,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Ja=(e,t)=>{er(e.inputs),tr(e,"ReduceLogSumExp",t,(r,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},Ya=(e,t)=>{er(e.inputs),tr(e,"ReduceMax",t,(r,i,a)=>{let o=[];for(let l=0;l<r.rank;l++)(a.indexOf(l)>=0||a.length===0)&&o.push(r.indicesSet("input_indices",l,0));return[`${o.join(`
|
|
150
|
+
`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},eo=(e,t)=>{er(e.inputs),tr(e,"ReduceMean",t,(r,i,a)=>{let o=1;for(let l=0;l<r.rank;l++)(a.indexOf(l)>=0||a.length===0)&&(o*=e.inputs[0].dims[l]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${o});`]})},to=(e,t)=>{er(e.inputs),tr(e,"ReduceMin",t,(r,i,a)=>{let o=[];for(let l=0;l<r.rank;l++)(a.indexOf(l)>=0||a.length===0)&&o.push(`input_indices[${l}] = 0;`);return[`${o.join(`
|
|
151
|
+
`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},ro=(e,t)=>{er(e.inputs),tr(e,"ReduceProd",t,(r,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},so=(e,t)=>{er(e.inputs),tr(e,"ReduceSum",t,(r,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},io=(e,t)=>{er(e.inputs),tr(e,"ReduceSumSquare",t,(r,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},rr=(e,t,r)=>{if(t.length===0)return r;let i=1,a=1;for(let o=0;o<t.length;o++)t.indexOf(o)===-1?i*=e[o]:a*=e[o];return a<32&&i>1024},no=(e,t)=>{rr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?eo(e,t):Yt(e,t)},ao=(e,t)=>{rr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xa(e,t):Ar(e,t)},oo=(e,t)=>{rr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Za(e,t):ht(e,t)},lo=(e,t)=>{rr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ja(e,t):nt(e,t)},uo=(e,t)=>{rr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ya(e,t):qt(e,t)},co=(e,t)=>{rr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?to(e,t):Hi(e,t)},ho=(e,t)=>{rr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ro(e,t):ji(e,t)},po=(e,t)=>{rr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?so(e,t):qa(e,t)},mo=(e,t)=>{rr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?io(e,t):Ha(e,t)},fo=(e,t)=>{rr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Qa(e,t):ja(e,t)}}),Cn,go,yo,En,im=T(()=>{Ee(),k(),Tn(),Cn=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},go=(e,t)=>{Cn(e.inputs);let r=(i,a,o)=>{let l=[];for(let u=0;u<i.rank;u++)(o.indexOf(u)>=0||o.length===0)&&l.push(`input_indices[${u}] = 0;`);return[`${l.join(`
|
|
152
|
+
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
153
|
+
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {
|
|
154
|
+
value = ${i.getByIndices("input_indices")};
|
|
155
|
+
best_index = i32(last_index);
|
|
156
|
+
}`,"",a.setByOffset("global_idx","best_index")]};e.compute(Ki("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},yo=(e,t)=>{Cn(e.inputs);let r=(i,a,o)=>{let l=[];for(let u=0;u<i.rank;u++)(o.indexOf(u)>=0||o.length===0)&&l.push(`input_indices[${u}] = 0;`);return[`${l.join(`
|
|
157
|
+
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
158
|
+
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {
|
|
159
|
+
value = ${i.getByIndices("input_indices")};
|
|
160
|
+
best_index = i32(last_index);
|
|
161
|
+
}`,"",a.setByOffset("global_idx","best_index")]};e.compute(Ki("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},En=e=>_(e)}),wo,Qi,vo,bo,_o,Si,So,$o,kn=T(()=>{Ee(),xe(),Cs(),he(),wo=(e,t)=>{let r=e[0],i=e[1],a=e[2],o=e[3],l=e[4],u=e[5];if(l&&u)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let c=r.dims[0],h=r.dims[1],p=r.dims[2];if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(i.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(i.dims[0]!==p)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(a.dims[0]!==i.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let m=a.dims[0]/3,y=m,w=y;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let I of t.qkvHiddenSizes)if(I%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");m=t.qkvHiddenSizes[0],y=t.qkvHiddenSizes[1],w=t.qkvHiddenSizes[2]}let v=h;if(m!==y)throw new Error("qkv_hidden_sizes first element should be same as the second");if(a.dims[0]!==m+y+w)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let x=0;if(l){if(y!==w)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(l.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(l.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(l.dims[1]!==c)throw new Error('Input "past" second dimension must be batch_size');if(l.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(l.dims[4]!==y/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(x=l.dims[3])}let R=v+x,C=-1,$=0;if(o)throw new Error("Mask not supported");if(l)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==c||u.dims[1]!==t.numHeads||u.dims[2]!==h||u.dims[3]!==R)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:c,sequenceLength:h,pastSequenceLength:x,kvSequenceLength:v,totalSequenceLength:R,maxSequenceLength:C,inputHiddenSize:p,hiddenSize:m,vHiddenSize:w,headSize:Math.floor(m/t.numHeads),vHeadSize:Math.floor(w/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:$,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Qi=(e,t,r)=>t&&e?`
|
|
162
|
+
let total_sequence_length_input = u32(${t.getByOffset("0")});
|
|
163
|
+
let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);
|
|
164
|
+
let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;
|
|
165
|
+
let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;
|
|
166
|
+
total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1;
|
|
167
|
+
var past_sequence_length: u32 = 0;
|
|
168
|
+
if (is_first_prompt == false) {
|
|
169
|
+
past_sequence_length = total_sequence_length - sequence_length;
|
|
170
|
+
}
|
|
171
|
+
`:`
|
|
172
|
+
${r?"let past_sequence_length = uniforms.past_sequence_length":""};
|
|
173
|
+
let present_sequence_length = total_sequence_length;
|
|
174
|
+
`,vo=(e,t,r,i,a,o,l,u)=>{let c=F(l?1:o),h=64,p=o/c;p<h&&(h=32);let m=Math.ceil(o/c/h),y=[{type:12,data:t},{type:12,data:r},{type:12,data:i},{type:12,data:a},{type:12,data:p},{type:12,data:m}],w=N(e.dataType,c),v=B(1,c),x=["type"];l&&x.push("type"),u&&x.push("type");let R=C=>{let $=te("x",e.dataType,e.dims,c),I=[$],M=l?U("seq_lens",l.dataType,l.dims):void 0;M&&I.push(M);let L=u?U("total_sequence_length_input",u.dataType,u.dims):void 0;L&&I.push(L);let V=B(e.dataType),W=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return`
|
|
175
|
+
var<workgroup> thread_max: array<f32, ${h}>;
|
|
176
|
+
var<workgroup> thread_sum: array<f32, ${h}>;
|
|
177
|
+
${C.registerUniforms(W).declareVariables(...I)}
|
|
178
|
+
${C.mainStart([h,1,1])}
|
|
179
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
180
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
181
|
+
let sequence_length = uniforms.sequence_length;
|
|
182
|
+
var total_sequence_length = uniforms.total_sequence_length;
|
|
183
|
+
${Qi(M,L,!1)}
|
|
184
|
+
let local_offset = local_idx * uniforms.elements_per_thread;
|
|
185
|
+
let offset = (global_idx / ${h}) * uniforms.total_sequence_length + local_offset;
|
|
186
|
+
let seq_causal_length = ${l?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"};
|
|
187
|
+
var thread_max_vector = ${v}(-3.4028234663852886e+38f);
|
|
188
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
189
|
+
thread_max_vector = max(${v}(x[offset + i]), thread_max_vector);
|
|
190
|
+
}
|
|
191
|
+
thread_max[local_idx] = ${(()=>{switch(c){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${c}`)}})()};
|
|
192
|
+
workgroupBarrier();
|
|
193
|
+
|
|
194
|
+
var max_value = f32(-3.4028234663852886e+38f);
|
|
195
|
+
for (var i = 0u; i < ${h}; i++) {
|
|
196
|
+
max_value = max(thread_max[i], max_value);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
var sum_vector = ${v}(0);
|
|
200
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
201
|
+
sum_vector += exp(${v}(x[offset + i]) - max_value);
|
|
202
|
+
}
|
|
203
|
+
thread_sum[local_idx] = ${(()=>{switch(c){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${c}`)}})()};
|
|
204
|
+
workgroupBarrier();
|
|
205
|
+
|
|
206
|
+
var sum: f32 = 0;
|
|
207
|
+
for (var i = 0u; i < ${h}; i++) {
|
|
208
|
+
sum += thread_sum[i];
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (sum == 0) {
|
|
212
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
213
|
+
x[offset + i] = ${$.type.value}(${V}(1.0) / ${V}(seq_causal_length));
|
|
214
|
+
}
|
|
215
|
+
} else {
|
|
216
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
217
|
+
var f32input = ${v}(x[offset + i]);
|
|
218
|
+
x[offset + i] = ${$.type.value}(exp(f32input - max_value) / sum);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
${l?`
|
|
222
|
+
for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {
|
|
223
|
+
x[offset + total_seq_id] = ${$.type.value}(${V}(0));
|
|
224
|
+
}`:""};
|
|
225
|
+
}`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${w};${c}`,inputDependencies:x},getShaderSource:R,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:a,z:t*r},programUniforms:y})}},bo=(e,t,r,i,a,o,l,u,c)=>{let h=l+o.kvSequenceLength,p=[o.batchSize,o.numHeads,o.sequenceLength,h],m=e>1&&i,y=o.kvNumHeads?o.kvNumHeads:o.numHeads,w=m?[o.batchSize,y,h,o.headSize]:void 0,v=o.nReps?o.nReps:1,x=o.scale===0?1/Math.sqrt(o.headSize):o.scale,R=F(o.headSize),C=o.headSize/R,$=12,I={x:Math.ceil(h/$),y:Math.ceil(o.sequenceLength/$),z:o.batchSize*o.numHeads},M=[{type:12,data:o.sequenceLength},{type:12,data:C},{type:12,data:h},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:1,data:x},{type:12,data:l},{type:12,data:o.kvSequenceLength},{type:12,data:v}],L=m&&i&&q.size(i.dims)>0,V=["type","type"];L&&V.push("type"),a&&V.push("type"),u&&V.push("type"),c&&V.push("type");let W=[{dims:p,dataType:t.dataType,gpuDataType:0}];m&&W.push({dims:w,dataType:t.dataType,gpuDataType:0});let X=se=>{let ge=U("q",t.dataType,t.dims,R),Be=U("key",r.dataType,r.dims,R),Te=[ge,Be];if(L){let Ae=U("past_key",i.dataType,i.dims,R);Te.push(Ae)}a&&Te.push(U("attention_bias",a.dataType,a.dims));let ke=u?U("seq_lens",u.dataType,u.dims):void 0;ke&&Te.push(ke);let Ge=c?U("total_sequence_length_input",c.dataType,c.dims):void 0;Ge&&Te.push(Ge);let ue=te("output",t.dataType,p),Se=[ue];m&&Se.push(te("present_key",t.dataType,w,R));let Oe=B(1,R),Ue=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return`
|
|
226
|
+
const TILE_SIZE = ${$}u;
|
|
227
|
+
|
|
228
|
+
var<workgroup> tileQ: array<${ge.type.storage}, ${$*$}>;
|
|
229
|
+
var<workgroup> tileK: array<${ge.type.storage}, ${$*$}>;
|
|
230
|
+
${se.registerUniforms(Ue).declareVariables(...Te,...Se)}
|
|
231
|
+
${se.mainStart([$,$,1])}
|
|
232
|
+
// x holds the N and y holds the M
|
|
233
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
234
|
+
let kvHeadIdx = ${v===1?"headIdx":"headIdx / uniforms.n_reps"};
|
|
235
|
+
let kv_num_heads = ${v===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
|
|
236
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
237
|
+
let m = workgroup_id.y * TILE_SIZE;
|
|
238
|
+
let n = workgroup_id.x * TILE_SIZE;
|
|
239
|
+
let sequence_length = uniforms.M;
|
|
240
|
+
var total_sequence_length = uniforms.N;
|
|
241
|
+
${Qi(ke,Ge,!0)}
|
|
242
|
+
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;
|
|
243
|
+
let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
244
|
+
${L&&m?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};
|
|
245
|
+
let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;
|
|
246
|
+
${m?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""}
|
|
247
|
+
var value = ${Oe}(0);
|
|
248
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
249
|
+
if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {
|
|
250
|
+
tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];
|
|
251
|
+
}
|
|
252
|
+
if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {
|
|
253
|
+
var idx = TILE_SIZE * local_id.y + local_id.x;
|
|
254
|
+
${L&&m?`
|
|
255
|
+
if (n + local_id.y < past_sequence_length) {
|
|
256
|
+
tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
|
|
257
|
+
} else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
|
|
258
|
+
tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];
|
|
259
|
+
}`:`
|
|
260
|
+
if (n + local_id.y < uniforms.kv_sequence_length) {
|
|
261
|
+
tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
|
|
262
|
+
}`}
|
|
263
|
+
${m?`if (n + local_id.y < present_sequence_length) {
|
|
264
|
+
present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];
|
|
265
|
+
}`:""}
|
|
266
|
+
}
|
|
267
|
+
workgroupBarrier();
|
|
268
|
+
|
|
269
|
+
for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {
|
|
270
|
+
value += ${Oe}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
workgroupBarrier();
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {
|
|
277
|
+
let headOffset = workgroup_id.z * uniforms.M * uniforms.N;
|
|
278
|
+
let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;
|
|
279
|
+
var sum: f32 = ${(()=>{switch(R){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${R}`)}})()};
|
|
280
|
+
output[outputIdx] = ${ue.type.value} (sum * uniforms.alpha) + ${a?"attention_bias[outputIdx]":"0.0"};
|
|
281
|
+
}
|
|
282
|
+
}`};return{name:"AttentionProbs",shaderCache:{hint:`${R};${a!==void 0};${i!==void 0};${e}`,inputDependencies:V},getRunData:()=>({outputs:W,dispatchGroup:I,programUniforms:M}),getShaderSource:X}},_o=(e,t,r,i,a,o,l=void 0,u=void 0)=>{let c=o+a.kvSequenceLength,h=a.nReps?a.nReps:1,p=a.vHiddenSize*h,m=e>1&&i,y=a.kvNumHeads?a.kvNumHeads:a.numHeads,w=m?[a.batchSize,y,c,a.headSize]:void 0,v=[a.batchSize,a.sequenceLength,p],x=12,R={x:Math.ceil(a.vHeadSize/x),y:Math.ceil(a.sequenceLength/x),z:a.batchSize*a.numHeads},C=[{type:12,data:a.sequenceLength},{type:12,data:c},{type:12,data:a.vHeadSize},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:12,data:p},{type:12,data:o},{type:12,data:a.kvSequenceLength},{type:12,data:h}],$=m&&i&&q.size(i.dims)>0,I=["type","type"];$&&I.push("type"),l&&I.push("type"),u&&I.push("type");let M=[{dims:v,dataType:t.dataType,gpuDataType:0}];m&&M.push({dims:w,dataType:t.dataType,gpuDataType:0});let L=V=>{let W=U("probs",t.dataType,t.dims),X=U("v",r.dataType,r.dims),se=[W,X];$&&se.push(U("past_value",i.dataType,i.dims));let ge=l?U("seq_lens",l.dataType,l.dims):void 0;l&&se.push(ge);let Be=u?U("total_sequence_length_input",u.dataType,u.dims):void 0;u&&se.push(Be);let Te=[te("output",t.dataType,v)];m&&Te.push(te("present_value",t.dataType,w));let ke=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return`
|
|
283
|
+
const TILE_SIZE = ${x}u;
|
|
284
|
+
var<workgroup> tileQ: array<${W.type.value}, ${x*x}>;
|
|
285
|
+
var<workgroup> tileV: array<${W.type.value}, ${x*x}>;
|
|
286
|
+
${V.registerUniforms(ke).declareVariables(...se,...Te)}
|
|
287
|
+
${V.mainStart([x,x,1])}
|
|
288
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
289
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
290
|
+
let kvHeadIdx = ${h===1?"headIdx":"headIdx / uniforms.n_reps"};
|
|
291
|
+
let kv_num_heads = ${h===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
|
|
292
|
+
let m = global_id.y;
|
|
293
|
+
let n = global_id.x;
|
|
294
|
+
let sequence_length = uniforms.M;
|
|
295
|
+
var total_sequence_length = uniforms.K;
|
|
296
|
+
${Qi(ge,Be,!0)}
|
|
297
|
+
let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
298
|
+
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch
|
|
299
|
+
${$&&m?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};
|
|
300
|
+
let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;
|
|
301
|
+
${m?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""}
|
|
302
|
+
var value = ${W.type.storage}(0);
|
|
303
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
304
|
+
if (m < uniforms.M && w + local_id.x < uniforms.K) {
|
|
305
|
+
tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];
|
|
306
|
+
}
|
|
307
|
+
if (n < uniforms.N && w + local_id.y < uniforms.K) {
|
|
308
|
+
var idx = TILE_SIZE * local_id.y + local_id.x;
|
|
309
|
+
${$&&m?`
|
|
310
|
+
if (w + local_id.y < past_sequence_length) {
|
|
311
|
+
tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];
|
|
312
|
+
} else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
|
|
313
|
+
tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];
|
|
314
|
+
}
|
|
315
|
+
`:`
|
|
316
|
+
if (w + local_id.y < uniforms.kv_sequence_length) {
|
|
317
|
+
tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];
|
|
318
|
+
}`}
|
|
319
|
+
${m?`
|
|
320
|
+
if (w + local_id.y < present_sequence_length) {
|
|
321
|
+
present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];
|
|
322
|
+
}`:""}
|
|
323
|
+
}
|
|
324
|
+
workgroupBarrier();
|
|
325
|
+
for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {
|
|
326
|
+
value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];
|
|
327
|
+
}
|
|
328
|
+
workgroupBarrier();
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// we need to transpose output from BNSH_v to BSND_v
|
|
332
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
333
|
+
let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size
|
|
334
|
+
+ headIdx * uniforms.N + n;
|
|
335
|
+
output[outputIdx] = value;
|
|
336
|
+
}
|
|
337
|
+
}`};return{name:"AttentionScore",shaderCache:{hint:`${i!==void 0};${e}`,inputDependencies:I},getRunData:()=>({outputs:M,dispatchGroup:R,programUniforms:C}),getShaderSource:L}},Si=(e,t,r,i,a,o,l,u,c,h,p=void 0,m=void 0)=>{let y=Math.min(e.outputCount,1+(l?1:0)+(u?1:0)),w=y>1?l:void 0,v=y>1?u:void 0,x=y>1?h.pastSequenceLength:0,R=x+h.kvSequenceLength,C=c&&q.size(c.dims)>0?c:void 0,$=[t,r];w&&q.size(w.dims)>0&&$.push(w),C&&$.push(C),p&&$.push(p),m&&$.push(m);let I=e.compute(bo(y,t,r,w,C,h,x,p,m),{inputs:$,outputs:y>1?[-1,1]:[-1]})[0];e.compute(vo(I,h.batchSize,h.numHeads,x,h.sequenceLength,R,p,m),{inputs:p&&m?[I,p,m]:[I],outputs:[]});let M=[I,i];v&&q.size(v.dims)>0&&M.push(v),p&&M.push(p),m&&M.push(m),e.compute(_o(y,I,i,v,h,x,p,m),{inputs:M,outputs:y>1?[0,2]:[0]})},So=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],i=t.sequenceLength,a=t.inputHiddenSize,o=t.headSize,l=12,u={x:Math.ceil(t.headSize/l),y:Math.ceil(t.sequenceLength/l),z:t.batchSize*t.numHeads},c=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:i},{type:12,data:a},{type:12,data:o},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],p=m=>{let y=te("output_q",c[0].dataType,r),w=te("output_k",c[0].dataType,r),v=te("output_v",c[0].dataType,r),x=U("input",c[0].dataType,c[0].dims),R=U("weight",c[1].dataType,c[1].dims),C=U("bias",c[2].dataType,c[2].dims),$=x.type.storage,I=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return`
|
|
338
|
+
const TILE_SIZE = ${l}u;
|
|
339
|
+
var<workgroup> tileInput: array<${$}, ${l*l}>;
|
|
340
|
+
var<workgroup> tileWeightQ: array<${$}, ${l*l}>;
|
|
341
|
+
var<workgroup> tileWeightK: array<${$}, ${l*l}>;
|
|
342
|
+
var<workgroup> tileWeightV: array<${$}, ${l*l}>;
|
|
343
|
+
${m.registerUniforms(I).declareVariables(x,R,C,y,w,v)}
|
|
344
|
+
${m.mainStart([l,l,1])}
|
|
345
|
+
let batchIndex = workgroup_id.z / uniforms.num_heads;
|
|
346
|
+
let headNumber = workgroup_id.z % uniforms.num_heads;
|
|
347
|
+
let m = global_id.y;
|
|
348
|
+
let n = global_id.x;
|
|
349
|
+
|
|
350
|
+
let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;
|
|
351
|
+
let biasOffsetQ = headNumber * uniforms.head_size;
|
|
352
|
+
let biasOffsetK = uniforms.hidden_size + biasOffsetQ;
|
|
353
|
+
let biasOffsetV = uniforms.hidden_size + biasOffsetK;
|
|
354
|
+
|
|
355
|
+
var valueQ = ${$}(0);
|
|
356
|
+
var valueK = ${$}(0);
|
|
357
|
+
var valueV = ${$}(0);
|
|
358
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
359
|
+
if (m < uniforms.M && w + local_id.x < uniforms.K) {
|
|
360
|
+
tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];
|
|
361
|
+
}
|
|
362
|
+
if (n < uniforms.N && w + local_id.y < uniforms.K) {
|
|
363
|
+
let offset = n + (w + local_id.y) * uniforms.ldb;
|
|
364
|
+
tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];
|
|
365
|
+
tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];
|
|
366
|
+
tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];
|
|
367
|
+
}
|
|
368
|
+
workgroupBarrier();
|
|
369
|
+
for (var k: u32 = 0u; k<TILE_SIZE && w+k < uniforms.K; k++) {
|
|
370
|
+
let inputTileOffset = TILE_SIZE * local_id.y + k;
|
|
371
|
+
let weightTileOffset = TILE_SIZE * k + local_id.x;
|
|
372
|
+
valueQ += tileInput[inputTileOffset] * tileWeightQ[weightTileOffset];
|
|
373
|
+
valueK += tileInput[inputTileOffset] * tileWeightK[weightTileOffset];
|
|
374
|
+
valueV += tileInput[inputTileOffset] * tileWeightV[weightTileOffset];
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
workgroupBarrier();
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
let headOffset = (m * uniforms.N + n) % uniforms.head_size;
|
|
381
|
+
valueQ += bias[headOffset + biasOffsetQ];
|
|
382
|
+
valueK += bias[headOffset + biasOffsetK];
|
|
383
|
+
valueV += bias[headOffset + biasOffsetV];
|
|
384
|
+
|
|
385
|
+
let offset = workgroup_id.z * uniforms.M * uniforms.N;
|
|
386
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
387
|
+
let outputIdx = offset + m * uniforms.N + n;
|
|
388
|
+
output_q[outputIdx] = valueQ;
|
|
389
|
+
output_k[outputIdx] = valueK;
|
|
390
|
+
output_v[outputIdx] = valueV;
|
|
391
|
+
}
|
|
392
|
+
}`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:h}),getShaderSource:p},{inputs:c,outputs:[-1,-1,-1]})},$o=(e,t)=>{let r=wo(e.inputs,t),[i,a,o]=So(e,r);return Si(e,i,a,o,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}}),xo,To,Co,Eo,nm=T(()=>{wt(),Ee(),xe(),k(),he(),xo=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(i,a,o)=>{let l=a.length;if(l!==i.length)throw new Error(`${o}: num dimensions != ${l}`);a.forEach((u,c)=>{if(u!==i[c])throw new Error(`${o}: dim[${c}] do not match`)})};if(e[0].dims.length>1){let i=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,i,"Invalid input scale"),r(e[2].dims,i,"Invalid input B"),r(e[3].dims,i,"Invalid input mean"),r(e[4].dims,i,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},To=(e,t)=>{let{epsilon:r,spatial:i,format:a}=t,o=e[0].dims,l=i?F(o[o.length-1]):1,u=a==="NHWC"&&o.length>1?l:1,c=q.size(o)/l,h=i,p=h?o.length:o,m=U("x",e[0].dataType,e[0].dims,l),y=U("scale",e[1].dataType,e[1].dims,u),w=U("bias",e[2].dataType,e[2].dims,u),v=U("inputMean",e[3].dataType,e[3].dims,u),x=U("inputVar",e[4].dataType,e[4].dims,u),R=te("y",e[0].dataType,p,l),C=()=>{let I="";if(i)I=`let cOffset = ${o.length===1?"0u":a==="NHWC"?`outputIndices[${o.length-1}] / ${l}`:"outputIndices[1]"};`;else if(a==="NCHW")I=`
|
|
393
|
+
${R.indicesSet("outputIndices","0","0")}
|
|
394
|
+
let cOffset = ${R.indicesToOffset("outputIndices")};`;else{I=`var cIndices = ${y.type.indices}(0);
|
|
395
|
+
cIndices[0] = outputIndices[${o.length-1}];`;for(let M=1;M<y.rank;M++)I+=`cIndices[${M}] = outputIndices[${M}];`;I+=`let cOffset = ${y.indicesToOffset("cIndices")};`}return I},$=I=>`
|
|
396
|
+
const epsilon = ${r};
|
|
397
|
+
${I.registerUniform("outputSize","u32").declareVariables(m,y,w,v,x,R)}
|
|
398
|
+
${I.mainStart()}
|
|
399
|
+
${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
400
|
+
var outputIndices = ${R.offsetToIndices(`global_idx * ${l}`)};
|
|
401
|
+
${C()}
|
|
402
|
+
let scale = ${y.getByOffset("cOffset")};
|
|
403
|
+
let bias = ${w.getByOffset("cOffset")};
|
|
404
|
+
let inputMean = ${v.getByOffset("cOffset")};
|
|
405
|
+
let inputVar = ${x.getByOffset("cOffset")};
|
|
406
|
+
let x = ${m.getByOffset("global_idx")};
|
|
407
|
+
let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;
|
|
408
|
+
${R.setByOffset("global_idx","value")}
|
|
409
|
+
}`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${i}_${l}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:$,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:h?[{type:12,data:c},...D(o)]:[{type:12,data:c}]})}},Co=e=>_(e),Eo=(e,t)=>{let{inputs:r,outputCount:i}=e,a=Co({...t,outputCount:i});if(de.webgpu.validateInputContent&&xo(r,a),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(To(r,a))}}),ko,Mo,Ro,am=T(()=>{xe(),he(),ko=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Mo=e=>{let t=e[0].dims,r=e[0].dims[2],i=q.size(t)/4,a=e[0].dataType,o=U("input",a,t,4),l=U("bias",a,[r],4),u=U("residual",a,t,4),c=te("output",a,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:h=>`
|
|
410
|
+
const channels = ${r}u / 4;
|
|
411
|
+
${h.declareVariables(o,l,u,c)}
|
|
412
|
+
|
|
413
|
+
${h.mainStart()}
|
|
414
|
+
${h.guardAgainstOutOfBoundsWorkgroupSizes(i)}
|
|
415
|
+
let value = ${o.getByOffset("global_idx")}
|
|
416
|
+
+ ${l.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")};
|
|
417
|
+
${c.setByOffset("global_idx","value")}
|
|
418
|
+
}`}},Ro=e=>{ko(e.inputs),e.compute(Mo(e.inputs))}}),Io,He,Ao,Po,Oo,zo,Do,Lo,Bo,Uo,Fo,No,Vo,Go,Wo,qo,$i,Ho,Xi,jo,Ko,Qo,Xo,Zo,Jo,Yo,el,tl,rl,sl,il,nl,al,ol,ll,Mn,ul,Rn,In,dl,cl,hl,pl,ml,fl,An=T(()=>{Ee(),xe(),k(),he(),Io=(e,t,r,i,a,o,l)=>{let u=Math.ceil(t/4),c="";typeof a=="string"?c=`${a}(a)`:c=a("a");let h=U("inputData",r,[u],4),p=te("outputData",i,[u],4),m=[{name:"vec_size",type:"u32"}];return l&&m.push(...l),`
|
|
419
|
+
${e.registerUniforms(m).declareVariables(h,p)}
|
|
420
|
+
|
|
421
|
+
${o??""}
|
|
422
|
+
|
|
423
|
+
${e.mainStart()}
|
|
424
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
425
|
+
|
|
426
|
+
let a = ${h.getByOffset("global_idx")};
|
|
427
|
+
${p.setByOffset("global_idx",c)}
|
|
428
|
+
}`},He=(e,t,r,i,a,o=e.dataType,l,u)=>{let c=[{type:12,data:Math.ceil(q.size(e.dims)/4)}];return l&&c.push(...l),{name:t,shaderCache:{hint:a,inputDependencies:["type"]},getShaderSource:h=>Io(h,q.size(e.dims),e.dataType,o,r,i,u),getRunData:h=>({outputs:[{dims:e.dims,dataType:o}],dispatchGroup:{x:Math.ceil(q.size(h[0].dims)/64/4)},programUniforms:c})}},Ao=e=>{e.compute(He(e.inputs[0],"Abs","abs"))},Po=e=>{e.compute(He(e.inputs[0],"Acos","acos"))},Oo=e=>{e.compute(He(e.inputs[0],"Acosh","acosh"))},zo=e=>{e.compute(He(e.inputs[0],"Asin","asin"))},Do=e=>{e.compute(He(e.inputs[0],"Asinh","asinh"))},Lo=e=>{e.compute(He(e.inputs[0],"Atan","atan"))},Bo=e=>{e.compute(He(e.inputs[0],"Atanh","atanh"))},Uo=e=>_(e),Fo=(e,t)=>{let r;switch(t.to){case 10:r="vec4<f16>";break;case 1:r="vec4<f32>";break;case 12:r="vec4<u32>";break;case 6:r="vec4<i32>";break;case 9:r="vec4<bool>";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(He(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},No=e=>{let t,r,i=e.length>=2&&e[1].data!==0,a=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=i?e[1].getFloat32Array()[0]:-34028234663852886e22,r=a?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=i?e[1].getUint16Array()[0]:64511,r=a?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return _({min:t,max:r})},Vo=(e,t)=>{let r=t||No(e.inputs),i=B(e.inputs[0].dataType);e.compute(He(e.inputs[0],"Clip",a=>`clamp(${a}, vec4<${i}>(uniforms.min), vec4<${i}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:i},{name:"max",type:i}]),{inputs:[0]})},Go=e=>{e.compute(He(e.inputs[0],"Ceil","ceil"))},Wo=e=>{e.compute(He(e.inputs[0],"Cos","cos"))},qo=e=>{e.compute(He(e.inputs[0],"Cosh","cosh"))},$i=e=>_(e),Ho=(e,t)=>{let r=B(e.inputs[0].dataType);e.compute(He(e.inputs[0],"Elu",i=>`elu_vf32(${i})`,`
|
|
429
|
+
const elu_alpha_ = ${r}(${t.alpha});
|
|
430
|
+
|
|
431
|
+
fn elu_f32(a: ${r}) -> ${r} {
|
|
432
|
+
return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {
|
|
436
|
+
return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));
|
|
437
|
+
}`,t.cacheKey))},Xi=(e="f32")=>`
|
|
438
|
+
const r0: ${e} = 0.3275911;
|
|
439
|
+
const r1: ${e} = 0.254829592;
|
|
440
|
+
const r2: ${e} = -0.284496736;
|
|
441
|
+
const r3: ${e} = 1.421413741;
|
|
442
|
+
const r4: ${e} = -1.453152027;
|
|
443
|
+
const r5: ${e} = 1.061405429;
|
|
444
|
+
|
|
445
|
+
fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {
|
|
446
|
+
let absv = abs(v);
|
|
447
|
+
let x = 1.0 / (1.0 + r0 * absv);
|
|
448
|
+
return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));
|
|
449
|
+
}`,jo=e=>{let t=B(e.inputs[0].dataType);e.compute(He(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Xi(t)))},Ko=e=>{e.compute(He(e.inputs[0],"Exp","exp"))},Qo=e=>{e.compute(He(e.inputs[0],"Floor","floor"))},Xo=e=>{let t=B(e.inputs[0].dataType);e.compute(He(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Xi(t)))},Zo=(e,t)=>{let r=B(e.inputs[0].dataType);e.compute(He(e.inputs[0],"LeakyRelu",i=>`select(leaky_relu_alpha_ * ${i}, ${i}, ${i} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},Jo=e=>{e.compute(He(e.inputs[0],"Not",t=>`!${t}`))},Yo=e=>{e.compute(He(e.inputs[0],"Neg",t=>`-${t}`))},el=e=>{e.compute(He(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},tl=e=>{let t=B(e.inputs[0].dataType);e.compute(He(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},rl=e=>{e.compute(He(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},sl=e=>_(e),il=(e,t)=>{let r=B(e.inputs[0].dataType);e.compute(He(e.inputs[0],"HardSigmoid",i=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${i} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},nl=e=>{e.compute(He(e.inputs[0],"Sin","sin"))},al=e=>{e.compute(He(e.inputs[0],"Sinh","sinh"))},ol=e=>{e.compute(He(e.inputs[0],"Sqrt","sqrt"))},ll=e=>{e.compute(He(e.inputs[0],"Tan","tan"))},Mn=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,ul=e=>{e.compute(He(e.inputs[0],"Tanh",Mn))},Rn=(e="f32")=>`
|
|
450
|
+
const fast_gelu_a: ${e} = 0.5;
|
|
451
|
+
const fast_gelu_b: ${e} = 0.7978845608028654;
|
|
452
|
+
const fast_gelu_c: ${e} = 0.035677408136300125;
|
|
453
|
+
|
|
454
|
+
fn tanh_v(v: vec4<${e}>) -> vec4<${e}> {
|
|
455
|
+
return ${Mn("v")};
|
|
456
|
+
}
|
|
457
|
+
`,In=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,dl=e=>{let t=B(e.inputs[0].dataType);e.compute(He(e.inputs[0],"FastGelu",In,Rn(t),void 0,e.inputs[0].dataType))},cl=(e,t)=>{let r=B(e.inputs[0].dataType);return e.compute(He(e.inputs[0],"ThresholdedRelu",i=>`select(vec4<${r}>(0.0), ${i}, ${i} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},hl=e=>{e.compute(He(e.inputs[0],"Log","log"))},pl=(e,t)=>`
|
|
458
|
+
const alpha = vec4<${e}>(${t});
|
|
459
|
+
const one = ${e}(1.0);
|
|
460
|
+
const zero = ${e}(0.0);
|
|
461
|
+
|
|
462
|
+
fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
463
|
+
let v = x *alpha;
|
|
464
|
+
var x1 : vec4<${e}>;
|
|
465
|
+
for (var i = 0; i < 4; i = i + 1) {
|
|
466
|
+
if (v[i] >= zero) {
|
|
467
|
+
x1[i] = one / (one + exp(-v[i]));
|
|
468
|
+
} else {
|
|
469
|
+
x1[i] = one - one / (one + exp(v[i]));
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
return x * x1;
|
|
473
|
+
}
|
|
474
|
+
`,ml=e=>`quick_gelu_impl(${e})`,fl=(e,t)=>{let r=B(e.inputs[0].dataType);e.compute(He(e.inputs[0],"QuickGelu",ml,pl(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),gl,yl,wl,om=T(()=>{xe(),he(),An(),gl=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},yl=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=U("input",e[0].dataType,e[0].dims,4),i=U("bias",e[0].dataType,[e[0].dims[2]],4),a=te("output",e[0].dataType,t,4),o=q.size(t)/4,l=N(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:u=>`
|
|
475
|
+
const M_SQRT2 = sqrt(2.0);
|
|
476
|
+
const halfChannels = ${e[0].dims[2]/4/2}u;
|
|
477
|
+
|
|
478
|
+
${u.declareVariables(r,i,a)}
|
|
479
|
+
|
|
480
|
+
${Xi(l)}
|
|
481
|
+
|
|
482
|
+
${u.mainStart()}
|
|
483
|
+
${u.guardAgainstOutOfBoundsWorkgroupSizes(o)}
|
|
484
|
+
let biasIdx = global_idx % halfChannels;
|
|
485
|
+
let batchIndex = global_idx / halfChannels;
|
|
486
|
+
let inputOffset = biasIdx + batchIndex * halfChannels * 2;
|
|
487
|
+
let valueLeft = input[inputOffset] + bias[biasIdx];
|
|
488
|
+
let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];
|
|
489
|
+
let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);
|
|
490
|
+
|
|
491
|
+
${a.setByOffset("global_idx","valueLeft * geluRight")}
|
|
492
|
+
}`}},wl=e=>{gl(e.inputs),e.compute(yl(e.inputs))}}),vl,bl,sr,_l,Sl,$l,xl,Tl,Cl,El,kl,Ml,Rl,lm=T(()=>{Ee(),xe(),he(),vl=(e,t,r,i,a,o,l,u,c,h,p,m)=>{let y,w;typeof u=="string"?y=w=($,I)=>`${u}((${$}),(${I}))`:typeof u=="function"?y=w=u:(y=u.scalar,w=u.vector);let v=te("outputData",p,i.length,4),x=U("aData",c,t.length,4),R=U("bData",h,r.length,4),C;if(a)if(o){let $=q.size(t)===1,I=q.size(r)===1,M=t.length>0&&t[t.length-1]%4===0,L=r.length>0&&r[r.length-1]%4===0;$||I?C=v.setByOffset("global_idx",w($?`${x.type.value}(${x.getByOffset("0")}.x)`:x.getByOffset("global_idx"),I?`${R.type.value}(${R.getByOffset("0")}.x)`:R.getByOffset("global_idx"))):C=`
|
|
493
|
+
let outputIndices = ${v.offsetToIndices("global_idx * 4u")};
|
|
494
|
+
let offsetA = ${x.broadcastedIndicesToOffset("outputIndices",v)};
|
|
495
|
+
let offsetB = ${R.broadcastedIndicesToOffset("outputIndices",v)};
|
|
496
|
+
${v.setByOffset("global_idx",w(l||M?x.getByOffset("offsetA / 4u"):`${x.type.value}(${x.getByOffset("offsetA / 4u")}[offsetA % 4u])`,l||L?R.getByOffset("offsetB / 4u"):`${R.type.value}(${R.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}
|
|
497
|
+
`}else C=v.setByOffset("global_idx",w(x.getByOffset("global_idx"),R.getByOffset("global_idx")));else{if(!o)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let $=(I,M,L="")=>{let V=`aData[indexA${M}][componentA${M}]`,W=`bData[indexB${M}][componentB${M}]`;return`
|
|
498
|
+
let outputIndices${M} = ${v.offsetToIndices(`global_idx * 4u + ${M}u`)};
|
|
499
|
+
let offsetA${M} = ${x.broadcastedIndicesToOffset(`outputIndices${M}`,v)};
|
|
500
|
+
let offsetB${M} = ${R.broadcastedIndicesToOffset(`outputIndices${M}`,v)};
|
|
501
|
+
let indexA${M} = offsetA${M} / 4u;
|
|
502
|
+
let indexB${M} = offsetB${M} / 4u;
|
|
503
|
+
let componentA${M} = offsetA${M} % 4u;
|
|
504
|
+
let componentB${M} = offsetB${M} % 4u;
|
|
505
|
+
${I}[${M}] = ${L}(${y(V,W)});
|
|
506
|
+
`};p===9?C=`
|
|
507
|
+
var data = vec4<u32>(0);
|
|
508
|
+
${$("data",0,"u32")}
|
|
509
|
+
${$("data",1,"u32")}
|
|
510
|
+
${$("data",2,"u32")}
|
|
511
|
+
${$("data",3,"u32")}
|
|
512
|
+
outputData[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:C=`
|
|
513
|
+
${$("outputData[global_idx]",0)}
|
|
514
|
+
${$("outputData[global_idx]",1)}
|
|
515
|
+
${$("outputData[global_idx]",2)}
|
|
516
|
+
${$("outputData[global_idx]",3)}
|
|
517
|
+
`}return`
|
|
518
|
+
${e.registerUniform("vec_size","u32").declareVariables(x,R,v)}
|
|
519
|
+
|
|
520
|
+
${m??""}
|
|
521
|
+
|
|
522
|
+
${e.mainStart()}
|
|
523
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
524
|
+
${C}
|
|
525
|
+
}`},bl=(e,t,r,i,a,o,l=r.dataType)=>{let u=r.dims.map(Number),c=i.dims.map(Number),h=!q.areEqual(u,c),p=u,m=q.size(u),y=!1,w=!1,v=[h];if(h){let x=lr.calcShape(u,c,!1);if(!x)throw new Error("Can't perform binary op on the given tensors");p=x.slice(),m=q.size(p);let R=q.size(u)===1,C=q.size(c)===1,$=u.length>0&&u[u.length-1]%4===0,I=c.length>0&&c[c.length-1]%4===0;v.push(R),v.push(C),v.push($),v.push(I);let M=1;for(let L=1;L<p.length;L++){let V=u[u.length-L],W=c[c.length-L];if(V===W)M*=V;else break}M%4===0?(w=!0,y=!0):(R||C||$||I)&&(y=!0)}else y=!0;return v.push(y),{name:e,shaderCache:{hint:t+v.map(x=>x.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:x=>vl(x,u,c,p,y,h,w,a,r.dataType,i.dataType,l,o),getRunData:()=>({outputs:[{dims:p,dataType:l}],dispatchGroup:{x:Math.ceil(m/64/4)},programUniforms:[{type:12,data:Math.ceil(q.size(p)/4)},...D(u,c,p)]})}},sr=(e,t,r,i,a,o)=>{e.compute(bl(t,a??"",e.inputs[0],e.inputs[1],r,i,o))},_l=e=>{sr(e,"Add",(t,r)=>`${t}+${r}`)},Sl=e=>{sr(e,"Div",(t,r)=>`${t}/${r}`)},$l=e=>{sr(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4<u32>(${t}==${r})`},void 0,void 0,9)},xl=e=>{sr(e,"Mul",(t,r)=>`${t}*${r}`)},Tl=e=>{let t=U("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;sr(e,"Pow",{scalar:(r,i)=>`pow_custom(${r},${i})`,vector:(r,i)=>`pow_vector_custom(${r},${i})`},`
|
|
526
|
+
fn pow_custom(a : ${t}, b : ${t}) -> ${t} {
|
|
527
|
+
if (b == ${t}(0.0)) {
|
|
528
|
+
return ${t}(1.0);
|
|
529
|
+
} else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {
|
|
530
|
+
return ${t}(pow(f32(a), f32(b))); // NaN
|
|
531
|
+
}
|
|
532
|
+
return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));
|
|
533
|
+
}
|
|
534
|
+
fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {
|
|
535
|
+
// TODO: implement vectorized pow
|
|
536
|
+
return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));
|
|
537
|
+
}
|
|
538
|
+
`)},Cl=e=>{sr(e,"Sub",(t,r)=>`${t}-${r}`)},El=e=>{sr(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4<u32>(${t}>${r})`},void 0,void 0,9)},kl=e=>{sr(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4<u32>(${t}<${r})`},void 0,void 0,9)},Ml=e=>{sr(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4<u32>(${t}>=${r})`},void 0,void 0,9)},Rl=e=>{sr(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4<u32>(${t}<=${r})`},void 0,void 0,9)}}),Il,Al,Pl,Ol,zl,Dl,um=T(()=>{Ee(),xe(),k(),he(),Il=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,i=e[r],a=i.dataType,o=i.dims.length;e.forEach((l,u)=>{if(u!==r){if(l.dataType!==a)throw new Error("input tensors should be one type");if(l.dims.length!==o)throw new Error("input tensors should have the same shape");l.dims.forEach((c,h)=>{if(h!==t&&c!==i.dims[h])throw new Error("non concat dimensions must match")})}})},Al=(e,t)=>`
|
|
539
|
+
fn calculateInputIndex(index: u32) -> u32 {
|
|
540
|
+
let sizeInConcatAxis = array<u32, ${e}u>(${t});
|
|
541
|
+
for (var i: u32 = 0u; i < ${e}; i += 1u ) {
|
|
542
|
+
if (index < sizeInConcatAxis[i]) {
|
|
543
|
+
return i;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
return ${e}u;
|
|
547
|
+
}`,Pl=(e,t)=>{let r=e.length,i=[];for(let a=0;a<r;++a){let o=t.setByOffset("global_idx",e[a].getByIndices("indices"));r===1?i.push(o):a===0?i.push(`if (inputIndex == ${a}u) { ${o} }`):a===r-1?i.push(`else { ${o} }`):i.push(`else if (inputIndex == ${a}) { ${o} }`)}return i.join(`
|
|
548
|
+
`)},Ol=(e,t,r,i)=>{let a=q.size(r),o=new Array(e.length),l=new Array(e.length),u=0,c=[],h=[],p=[{type:12,data:a}];for(let x=0;x<e.length;++x)u+=e[x].dims[t],o[x]=u,h.push(e[x].dims.length),l[x]=U(`input${x}`,i,h[x]),c.push("rank"),p.push({type:12,data:o[x]});for(let x=0;x<e.length;++x)p.push(...D(e[x].dims));p.push(...D(r));let m=te("output",i,r.length),y=m.indicesGet("indices",t),w=Array.from(Array(o.length).keys()).map(x=>`uniforms.sizeInConcatAxis${x}`).join(","),v=x=>`
|
|
549
|
+
|
|
550
|
+
${(()=>{x.registerUniform("outputSize","u32");for(let R=0;R<e.length;R++)x.registerUniform(`sizeInConcatAxis${R}`,"u32");return x.declareVariables(...l,m)})()}
|
|
551
|
+
|
|
552
|
+
${Al(o.length,w)}
|
|
553
|
+
|
|
554
|
+
${x.mainStart()}
|
|
555
|
+
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
556
|
+
|
|
557
|
+
var indices = ${m.offsetToIndices("global_idx")};
|
|
558
|
+
|
|
559
|
+
let inputIndex = calculateInputIndex(${y});
|
|
560
|
+
if (inputIndex != 0u) {
|
|
561
|
+
let sizeInConcatAxis = array<u32, ${o.length}u>(${w});
|
|
562
|
+
${y} -= sizeInConcatAxis[inputIndex - 1u];
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
${Pl(l,m)}
|
|
566
|
+
}`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:r,dataType:i}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:v}},zl=(e,t)=>{let r=e.inputs,i=r[0].dims,a=q.normalizeAxis(t.axis,i.length);Il(r,a);let o=i.slice();o[a]=r.reduce((u,c)=>u+(c.dims.length>a?c.dims[a]:0),0);let l=r.filter(u=>q.size(u.dims)>0);e.compute(Ol(l,a,o,r[0].dataType),{inputs:l})},Dl=e=>_({axis:e.axis})}),as,os,ls,Pn,us=T(()=>{Ee(),xe(),as=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value));
|
|
567
|
+
value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
|
|
568
|
+
`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},os=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},ls=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},Pn=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,i]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:i}}else if(t==="Clip"){let[r,i]=e?.activation_params||[ci,Xt];return{activation:t,clipMax:i,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}}),$t,Ll,On=T(()=>{$t=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Ll=e=>`
|
|
569
|
+
${e?"value = value + getBiasByOutputCoords(coords);":""}
|
|
570
|
+
`}),Bl,dm=T(()=>{Bl=e=>`
|
|
571
|
+
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
|
|
572
|
+
return dot(coords, vec4<i32>(
|
|
573
|
+
shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
|
|
574
|
+
}
|
|
575
|
+
fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
|
|
576
|
+
return dot(coords, vec4<i32>(
|
|
577
|
+
i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));
|
|
578
|
+
}
|
|
579
|
+
`}),xi,zn,Dn=T(()=>{Ee(),xe(),he(),us(),xi=(e,t,r,i,a)=>{let o=i-r;return`
|
|
580
|
+
${Array.from({length:r}).map((l,u)=>`
|
|
581
|
+
if (${H(t.shape,u,t.rank)} != 1) {
|
|
582
|
+
${t.indicesSet(e,u,H(a,u+o,i))}
|
|
583
|
+
} else {
|
|
584
|
+
${t.indicesSet(e,u,0)}
|
|
585
|
+
}`).join("")}
|
|
586
|
+
`},zn=(e,t,r,i,a=!1,o)=>{let l=e[0].dims,u=e[1].dims,c=l[l.length-2],h=u[u.length-1],p=l[l.length-1],m=F(h),y=F(p),w=F(c),v=q.size(r)/m/w,x=e.length>2,R=i?i.slice(0,-2):r.slice(0,-2),C=[q.size(R),c,h],$=[{type:12,data:v},{type:12,data:c},{type:12,data:h},{type:12,data:p}];os(t,$),$.push(...D(R,l,u)),x&&$.push(...D(e[2].dims)),$.push(...D(C));let I=M=>{let L=ze("batch_dims",e[0].dataType,R.length),V=U("a",e[0].dataType,l.length,y),W=U("b",e[1].dataType,u.length,m),X=te("output",e[0].dataType,C.length,m),se=N(X.type.tensor),ge=as(t,X.type.value,se),Be=[V,W],Te="";if(x){let ue=a?m:1;Be.push(U("bias",e[2].dataType,e[2].dims.length,ue)),Te=`${a?`value += bias[col / ${ue}];`:`value += ${X.type.value}(bias[row + i]);`}`}let ke=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];ls(t,ke);let Ge=()=>{let ue=`var a_data: ${V.type.value};`;for(let Se=0;Se<y;Se++)ue+=`
|
|
587
|
+
let b_data${Se} = b[(b_offset + (k + ${Se}) * uniforms.N + col) / ${m}];`;for(let Se=0;Se<w;Se++){ue+=`a_data = a[(a_offset + (row + ${Se}) * uniforms.K + k) / ${y}];`;for(let Oe=0;Oe<y;Oe++)ue+=`
|
|
588
|
+
values[${Se}] = fma(${W.type.value}(a_data${y===1?"":`[${Oe}]`}), b_data${Oe}, values[${Se}]);
|
|
589
|
+
`}return ue};return`
|
|
590
|
+
${M.registerUniforms(ke).registerInternalVariables(L).declareVariables(...Be,X)}
|
|
591
|
+
${M.mainStart()}
|
|
592
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
593
|
+
let col = (global_idx % (uniforms.N / ${m})) * ${m};
|
|
594
|
+
var index1 = global_idx / (uniforms.N / ${m});
|
|
595
|
+
let stride1 = uniforms.M / ${w};
|
|
596
|
+
let row = (index1 % stride1) * ${w};
|
|
597
|
+
let batch = index1 / stride1;
|
|
598
|
+
|
|
599
|
+
${r.length===2?"":`let batch_indices = ${L.offsetToIndices("batch")};`}
|
|
600
|
+
|
|
601
|
+
var a_indices: ${V.type.indices};
|
|
602
|
+
${xi("a_indices",V,V.rank-2,L.rank,"batch_indices")}
|
|
603
|
+
${V.indicesSet("a_indices",V.rank-2,0)}
|
|
604
|
+
${V.indicesSet("a_indices",V.rank-1,0)}
|
|
605
|
+
let a_offset = ${V.indicesToOffset("a_indices")};
|
|
606
|
+
|
|
607
|
+
var b_indices: ${W.type.indices};
|
|
608
|
+
${xi("b_indices",W,W.rank-2,L.rank,"batch_indices")}
|
|
609
|
+
${W.indicesSet("b_indices",W.rank-2,0)}
|
|
610
|
+
${W.indicesSet("b_indices",W.rank-1,0)}
|
|
611
|
+
let b_offset = ${W.indicesToOffset("b_indices")};
|
|
612
|
+
var values: array<${X.type.value}, ${w}>;
|
|
613
|
+
for (var k: u32 = 0u; k < uniforms.K; k = k + ${y}) {
|
|
614
|
+
${Ge()}
|
|
615
|
+
}
|
|
616
|
+
for (var i = 0u; i < ${w}u; i++) {
|
|
617
|
+
var value = values[i];
|
|
618
|
+
${Te}
|
|
619
|
+
${ge}
|
|
620
|
+
let cur_indices = ${X.type.indices}(batch, row + i, col);
|
|
621
|
+
let offset = ${X.indicesToOffset("cur_indices")};
|
|
622
|
+
${X.setByOffset(`offset / ${m}`,"value")};
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
`};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${m};${y};${w};${a}`,inputDependencies:x?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:o?o(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:$}),getShaderSource:I}}}),Ul,Fl,Ln,Bn,Nl,Un,Vl,Zi,Fn=T(()=>{Ee(),xe(),he(),us(),Dn(),On(),Ul=(e,t)=>e?`
|
|
626
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
627
|
+
kStart + inputRow,
|
|
628
|
+
globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});
|
|
629
|
+
`:`
|
|
630
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
631
|
+
globalRow + innerRow,
|
|
632
|
+
kStart / innerElementSize + inputCol${t?", batchIndices":""});
|
|
633
|
+
`,Fl=(e,t)=>e?`
|
|
634
|
+
let ACached0 = mm_Asub[k * innerElementSize][localRow];
|
|
635
|
+
let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];
|
|
636
|
+
let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];
|
|
637
|
+
${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}
|
|
638
|
+
for (var i = 0; i < rowPerThread; i = i + 1) {
|
|
639
|
+
acc[i] = BCached0 * ACached0[i] + acc[i];
|
|
640
|
+
acc[i] = BCached1 * ACached1[i] + acc[i];
|
|
641
|
+
acc[i] = BCached2 * ACached2[i] + acc[i];
|
|
642
|
+
${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}
|
|
643
|
+
}`:`
|
|
644
|
+
for (var i = 0; i < rowPerThread; i = i + 1) {
|
|
645
|
+
let ACached = mm_Asub[tileRow + i][k];
|
|
646
|
+
acc[i] = BCached0 * ACached.x + acc[i];
|
|
647
|
+
acc[i] = BCached1 * ACached.y + acc[i];
|
|
648
|
+
acc[i] = BCached2 * ACached.z + acc[i];
|
|
649
|
+
${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}
|
|
650
|
+
}`,Ln=(e,t,r="f32",i,a=!1,o=32,l=!1,u=32)=>{let c=t[1]*e[1],h=t[0]*e[0],p=a?c:o,m=a?o:c,y=p/t[0],w=o/t[1];if(!((a&&y===4&&e[1]===4||!a&&(y===3||y===4))&&p%t[0]===0&&o%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${a} is true, innerElementSize ${y} and workPerThread[1] ${e[1]} must be 4.
|
|
651
|
+
Otherwise, innerElementSize ${y} must be 3 or 4.
|
|
652
|
+
tileAWidth ${p} must be divisible by workgroupSize[0]${t[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`
|
|
653
|
+
var<workgroup> mm_Asub: array<array<vec${y}<${r}>, ${p/y}>, ${m}>;
|
|
654
|
+
var<workgroup> mm_Bsub: array<array<vec4<${r}>, ${h/e[0]}>, ${o}>;
|
|
655
|
+
|
|
656
|
+
const rowPerThread = ${e[1]};
|
|
657
|
+
const colPerThread = ${e[0]};
|
|
658
|
+
const innerElementSize = ${y};
|
|
659
|
+
const tileInner = ${o};
|
|
660
|
+
|
|
661
|
+
@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})
|
|
662
|
+
fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
663
|
+
@builtin(global_invocation_id) globalId : vec3<u32>,
|
|
664
|
+
@builtin(workgroup_id) workgroupId : vec3<u32>) {
|
|
665
|
+
let localRow = i32(localId.y);
|
|
666
|
+
let tileRow = localRow * rowPerThread;
|
|
667
|
+
let tileCol = i32(localId.x);
|
|
668
|
+
|
|
669
|
+
let globalRow =i32(globalId.y) * rowPerThread;
|
|
670
|
+
let globalCol = i32(globalId.x);
|
|
671
|
+
let batch = ${l?"0":"i32(globalId.z)"};
|
|
672
|
+
${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""}
|
|
673
|
+
let globalRowStart = i32(workgroupId.y) * ${c};
|
|
674
|
+
|
|
675
|
+
let num_tiles = ${l?`${Math.ceil(u/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
|
|
676
|
+
var kStart = ${l?`i32(globalId.z) * ${u}`:"0"};
|
|
677
|
+
|
|
678
|
+
var acc: array<vec4<${r}>, rowPerThread>;
|
|
679
|
+
|
|
680
|
+
// Loop over shared dimension.
|
|
681
|
+
let tileRowB = localRow * ${w};
|
|
682
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
683
|
+
// Load one tile of A into local memory.
|
|
684
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
685
|
+
let inputRow = tileRow + innerRow;
|
|
686
|
+
let inputCol = tileCol;
|
|
687
|
+
${Ul(a,i)}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// Load one tile of B into local memory.
|
|
691
|
+
for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) {
|
|
692
|
+
let inputRow = tileRowB + innerRow;
|
|
693
|
+
let inputCol = tileCol;
|
|
694
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${i?", batchIndices":""});
|
|
695
|
+
}
|
|
696
|
+
kStart = kStart + tileInner;
|
|
697
|
+
workgroupBarrier();
|
|
698
|
+
|
|
699
|
+
// Compute acc values for a single thread.
|
|
700
|
+
for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {
|
|
701
|
+
let BCached0 = mm_Bsub[k * innerElementSize][tileCol];
|
|
702
|
+
let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];
|
|
703
|
+
let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];
|
|
704
|
+
${y===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}
|
|
705
|
+
|
|
706
|
+
${Fl(a,y)}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
workgroupBarrier();
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
713
|
+
mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
|
|
714
|
+
}
|
|
715
|
+
}`},Bn=(e,t)=>e?`
|
|
716
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
717
|
+
kStart + inputRow,
|
|
718
|
+
globalRowStart + inputCol${t?", batchIndices":""});
|
|
719
|
+
`:`
|
|
720
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
721
|
+
globalRowStart + inputRow,
|
|
722
|
+
kStart + inputCol${t?", batchIndices":""});
|
|
723
|
+
`,Nl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Un=(e,t,r="f32",i,a=!1,o=32,l=!1,u=32,c=!1)=>{let h=e[1]*t[1],p=e[0]*t[0],m=a?h:o,y=a?o:h;if(!(y%t[1]===0&&m%t[0]===0&&o%t[1]===0))throw new Error(`tileAHight ${y} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}, tileInner ${o} must be divisible by workgroupSize[1]${t[1]}`);let w=y/t[1],v=m/t[0],x=o/t[1],R=c?`
|
|
724
|
+
let localRow = i32(localId.y);
|
|
725
|
+
let localCol = i32(localId.x);
|
|
726
|
+
let globalRowStart = i32(workgroupId.y) * ${h};
|
|
727
|
+
let globalColStart = i32(workgroupId.x) * ${p};
|
|
728
|
+
|
|
729
|
+
// Loop over shared dimension.
|
|
730
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
731
|
+
// Load one tile of A into local memory.
|
|
732
|
+
for (var inputRow = localRow; inputRow < ${y}; inputRow = inputRow + ${t[1]}) {
|
|
733
|
+
for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) {
|
|
734
|
+
${Bn(a,i)}
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
// Load one tile of B into local memory.
|
|
738
|
+
for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${t[1]}) {
|
|
739
|
+
for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${t[0]}) {
|
|
740
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch,
|
|
741
|
+
kStart + inputRow,
|
|
742
|
+
globalColStart + inputCol${i?", batchIndices":""});
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
kStart = kStart + tileInner;
|
|
746
|
+
workgroupBarrier();
|
|
747
|
+
|
|
748
|
+
// Compute acc values for a single thread.
|
|
749
|
+
var BCached : array<${r}, colPerThread>;
|
|
750
|
+
for (var k = 0; k < tileInner; k = k + 1) {
|
|
751
|
+
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
|
|
752
|
+
BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];
|
|
753
|
+
}
|
|
754
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
755
|
+
let ACached = ${a?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}
|
|
756
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
757
|
+
acc[innerRow][innerCol] = acc[innerRow][innerCol] +
|
|
758
|
+
ACached * BCached[innerCol];
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
workgroupBarrier();
|
|
763
|
+
}
|
|
764
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
765
|
+
let gRow = globalRowStart + localRow + innerRow * ${t[1]};
|
|
766
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
767
|
+
let gCol = globalColStart + localCol + innerCol * ${t[0]};
|
|
768
|
+
mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
`:`
|
|
772
|
+
let tileRow = i32(localId.y) * rowPerThread;
|
|
773
|
+
let tileCol = i32(localId.x) * colPerThread;
|
|
774
|
+
|
|
775
|
+
let globalRow = i32(globalId.y) * rowPerThread;
|
|
776
|
+
let globalCol = i32(globalId.x) * colPerThread;
|
|
777
|
+
let globalRowStart = i32(workgroupId.y) * ${h};
|
|
778
|
+
|
|
779
|
+
let tileRowA = i32(localId.y) * ${w};
|
|
780
|
+
let tileColA = i32(localId.x) * ${v};
|
|
781
|
+
let tileRowB = i32(localId.y) * ${x};
|
|
782
|
+
// Loop over shared dimension.
|
|
783
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
784
|
+
// Load one tile of A into local memory.
|
|
785
|
+
for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) {
|
|
786
|
+
for (var innerCol = 0; innerCol < ${v}; innerCol = innerCol + 1) {
|
|
787
|
+
let inputRow = tileRowA + innerRow;
|
|
788
|
+
let inputCol = tileColA + innerCol;
|
|
789
|
+
${Bn(a,i)}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
// Load one tile of B into local memory.
|
|
794
|
+
for (var innerRow = 0; innerRow < ${x}; innerRow = innerRow + 1) {
|
|
795
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
796
|
+
let inputRow = tileRowB + innerRow;
|
|
797
|
+
let inputCol = tileCol + innerCol;
|
|
798
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch,
|
|
799
|
+
kStart + inputRow,
|
|
800
|
+
globalCol + innerCol${i?", batchIndices":""});
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
kStart = kStart + tileInner;
|
|
804
|
+
workgroupBarrier();
|
|
805
|
+
|
|
806
|
+
// Compute acc values for a single thread.
|
|
807
|
+
var BCached : array<${r}, colPerThread>;
|
|
808
|
+
for (var k = 0; k < tileInner; k = k + 1) {
|
|
809
|
+
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
|
|
810
|
+
BCached[inner] = mm_Bsub[k][tileCol + inner];
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
814
|
+
${Nl(a)}
|
|
815
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
816
|
+
acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
workgroupBarrier();
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
825
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
826
|
+
mm_write(batch, globalRow + innerRow, globalCol + innerCol,
|
|
827
|
+
acc[innerRow][innerCol]);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
`;return`
|
|
831
|
+
var<workgroup> mm_Asub : array<array<${r}, ${m}>, ${y}>;
|
|
832
|
+
var<workgroup> mm_Bsub : array<array<${r}, ${p}>, ${o}>;
|
|
833
|
+
const rowPerThread = ${e[1]};
|
|
834
|
+
const colPerThread = ${e[0]};
|
|
835
|
+
const tileInner = ${o};
|
|
836
|
+
|
|
837
|
+
@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})
|
|
838
|
+
fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
839
|
+
@builtin(global_invocation_id) globalId : vec3<u32>,
|
|
840
|
+
@builtin(workgroup_id) workgroupId : vec3<u32>) {
|
|
841
|
+
let batch = ${l?"0":"i32(globalId.z)"};
|
|
842
|
+
${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""}
|
|
843
|
+
let num_tiles = ${l?`${Math.ceil(u/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
|
|
844
|
+
var kStart = ${l?`i32(globalId.z) * ${u}`:"0"};
|
|
845
|
+
|
|
846
|
+
var acc : array<array<${r}, colPerThread>, rowPerThread>;
|
|
847
|
+
${R}
|
|
848
|
+
}
|
|
849
|
+
`},Vl=(e,t,r,i,a=!1)=>{let[o,l,u,c]=i,h=N(i[0].type.tensor);return`
|
|
850
|
+
fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${$t(e,h)} {
|
|
851
|
+
var value = ${$t(e,h)}(0.0);
|
|
852
|
+
let col = colIn * ${e};
|
|
853
|
+
if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)
|
|
854
|
+
{
|
|
855
|
+
var aIndices: ${l.type.indices};
|
|
856
|
+
${xi("aIndices",l,l.rank-2,o.rank,"batchIndices")}
|
|
857
|
+
${l.indicesSet("aIndices",l.rank-2,"u32(row)")}
|
|
858
|
+
${l.indicesSet("aIndices",l.rank-1,"u32(colIn)")}
|
|
859
|
+
value = ${l.getByIndices("aIndices")};
|
|
860
|
+
}
|
|
861
|
+
return value;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${$t(e,h)} {
|
|
865
|
+
var value = ${$t(e,h)}(0.0);
|
|
866
|
+
let col = colIn * ${e};
|
|
867
|
+
if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)
|
|
868
|
+
{
|
|
869
|
+
var bIndices: ${u.type.indices};
|
|
870
|
+
${xi("bIndices",u,u.rank-2,o.rank,"batchIndices")}
|
|
871
|
+
${u.indicesSet("bIndices",u.rank-2,"u32(row)")}
|
|
872
|
+
${u.indicesSet("bIndices",u.rank-1,"u32(colIn)")}
|
|
873
|
+
value = ${u.getByIndices("bIndices")};
|
|
874
|
+
}
|
|
875
|
+
return value;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${$t(e,h)}) {
|
|
879
|
+
let col = colIn * ${e};
|
|
880
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {
|
|
881
|
+
var value = valueIn;
|
|
882
|
+
let coords = vec3<i32>(batch, row, colIn);
|
|
883
|
+
${t?`value = value + ${a?"bias[colIn]":`${$t(e,h)}(bias[row])`};`:""}
|
|
884
|
+
${r}
|
|
885
|
+
${c.setByIndices("vec3<u32>(coords)","value")}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
`},Zi=(e,t,r,i,a=!1,o)=>{let l=e[0].dims,u=e[1].dims,c=l.slice(0,-2),h=u.slice(0,-2),p=i?i.slice(0,-2):r.slice(0,-2),m=q.size(p),y=l[l.length-2],w=l[l.length-1],v=u[u.length-1],x=w%4===0&&v%4===0,R=y<=8?[4,1,1]:[4,4,1],C=[8,8,1],$=[Math.ceil(v/C[0]/R[0]),Math.ceil(y/C[1]/R[1]),Math.ceil(m/C[2]/R[2])],I=x?4:1,M=[...c,y,w/I],L=M.length,V=[...h,w,v/I],W=V.length,X=[m,y,v/I],se=[{type:6,data:y},{type:6,data:v},{type:6,data:w}];os(t,se),se.push(...D(p,M,V));let ge=["rank","rank"],Be=e.length>2;Be&&(se.push(...D(e[2].dims)),ge.push("rank")),se.push(...D(X));let Te=ke=>{let Ge=p.length,ue=ze("batchDims",e[0].dataType,Ge,1),Se=N(e[0].dataType),Oe=U("a",e[0].dataType,L,I),Ue=U("b",e[1].dataType,W,I),Ae=te("result",e[0].dataType,X.length,I),Ne=[Oe,Ue];if(Be){let xt=a?I:1;Ne.push(U("bias",e[2].dataType,e[2].dims.length,xt))}let ee=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];ls(t,ee);let Ie=N(Ae.type.tensor),Ce=as(t,Ae.type.value,Ie),_e=Vl(I,Be,Ce,[ue,Oe,Ue,Ae],a);return`
|
|
889
|
+
${ke.registerUniforms(ee).registerInternalVariables(ue).declareVariables(...Ne,Ae)}
|
|
890
|
+
${_e}
|
|
891
|
+
${x?Ln(R,C,Se,ue):Un(R,C,Se,ue)}
|
|
892
|
+
`};return{name:"MatMul",shaderCache:{hint:`${R};${t.activation};${x};${a}`,inputDependencies:ge},getRunData:()=>({outputs:[{dims:o?o(r):r,dataType:e[0].dataType}],dispatchGroup:{x:$[0],y:$[1],z:$[2]},programUniforms:se}),getShaderSource:Te}}}),Gl,Wl,cm=T(()=>{Ee(),Vt(),he(),us(),On(),dm(),Fn(),Gl=(e,t,r,i,a=!1,o,l=4,u=4,c=4,h="f32")=>{let p=se=>{switch(se){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${se} is not supported.`)}},m=se=>{switch(se){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${se} is not supported.`)}},y=e?`
|
|
893
|
+
let coord = vec4<i32>(batch, xRow, xCol, xCh);
|
|
894
|
+
`:`
|
|
895
|
+
let coord = vec4<i32>(batch, xCh, xRow, xCol);
|
|
896
|
+
`,w=e?`
|
|
897
|
+
let coords = vec4<i32>(
|
|
898
|
+
batch,
|
|
899
|
+
row / outWidth,
|
|
900
|
+
row % outWidth,
|
|
901
|
+
col);
|
|
902
|
+
`:`
|
|
903
|
+
let coords = vec4<i32>(
|
|
904
|
+
batch,
|
|
905
|
+
row,
|
|
906
|
+
col / outWidth,
|
|
907
|
+
col % outWidth);
|
|
908
|
+
`,v=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",x=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",R=e?"row":"col",C=e?"col":"row",$=`
|
|
909
|
+
let inChannels = i32(uniforms.w_shape[2]);
|
|
910
|
+
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
|
|
911
|
+
let outRow = ${R} / outWidth;
|
|
912
|
+
let outCol = ${R} % outWidth;
|
|
913
|
+
|
|
914
|
+
let WRow = ${C} / (i32(uniforms.w_shape[1]) * inChannels);
|
|
915
|
+
let WCol = ${C} / inChannels % i32(uniforms.w_shape[1]);
|
|
916
|
+
let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];
|
|
917
|
+
let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];
|
|
918
|
+
let xCh = ${C} % inChannels;
|
|
919
|
+
var resData = ${$t(l,h)}(0.0);
|
|
920
|
+
// The bounds checking is always needed since we use it to pad zero for
|
|
921
|
+
// the 'same' padding type.
|
|
922
|
+
if (xRow >= 0 && xRow < ${v} && xCol >= 0 && xCol < ${x}) {
|
|
923
|
+
${y}
|
|
924
|
+
let xIndex = getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape));
|
|
925
|
+
${p(l)}
|
|
926
|
+
}
|
|
927
|
+
return resData;`,I=e?t&&i?`
|
|
928
|
+
let col = colIn * ${l};
|
|
929
|
+
${$}`:`
|
|
930
|
+
let col = colIn * ${l};
|
|
931
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {
|
|
932
|
+
${$}
|
|
933
|
+
}
|
|
934
|
+
return ${$t(l,h)}(0.0);`:i&&r?`
|
|
935
|
+
let col = colIn * ${l};
|
|
936
|
+
${$}`:`
|
|
937
|
+
let col = colIn * ${l};
|
|
938
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
|
|
939
|
+
${$}
|
|
940
|
+
}
|
|
941
|
+
return ${$t(l,h)}(0.0);`,M=e?i&&r?m(u):`
|
|
942
|
+
let col = colIn * ${u};
|
|
943
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
|
|
944
|
+
${m(u)}
|
|
945
|
+
}
|
|
946
|
+
return ${$t(u,h)}(0.0);`:`
|
|
947
|
+
let col = colIn * ${u};
|
|
948
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {
|
|
949
|
+
${m(u)}
|
|
950
|
+
}
|
|
951
|
+
return ${$t(u,h)}(0.0);`,L=$t(c,h),V=$t(e?l:u,h),W=$t(e?u:l,h),X=as(o,L,h);return`
|
|
952
|
+
fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${V} {
|
|
953
|
+
${e?I:M}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${W} {
|
|
957
|
+
${e?M:I}
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${L}) {
|
|
961
|
+
let col = colIn * ${c};
|
|
962
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)
|
|
963
|
+
{
|
|
964
|
+
var value = valueIn;
|
|
965
|
+
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
|
|
966
|
+
${w}
|
|
967
|
+
${Ll(a)}
|
|
968
|
+
${X}
|
|
969
|
+
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
|
|
970
|
+
}
|
|
971
|
+
}`},Wl=(e,t,r,i,a,o,l,u,c)=>{let h=t.format==="NHWC",p=h?e[0].dims[3]:e[0].dims[1],m=r[0],y=h?r[2]:r[3],w=h?r[1]:r[2],v=h?r[3]:r[1],x=h&&(p%4===0||p%3===0)&&v%4===0,R=h?v:y*w,C=h?y*w:v,$=[8,8,1],I=i<=8?[4,1,1]:[4,4,1],M=[Math.ceil(R/$[0]/I[0]),Math.ceil(C/$[1]/I[1]),Math.ceil(m/$[2]/I[2])];Fe("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${M}`);let L=x?h&&p%4!==0?3:4:1,V=$[1]*I[1],W=$[0]*I[0],X=Math.max($[0]*L,$[1]),se=i%V===0,ge=a%W===0,Be=o%X===0,Te=x?[L,4,4]:[1,1,1],ke=[{type:6,data:i},{type:6,data:a},{type:6,data:o},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];os(t,ke),ke.push(...D(e[0].dims,e[1].dims));let Ge=["rank","rank"];l&&(ke.push(...D(e[2].dims)),Ge.push("rank")),ke.push(...D(r));let ue=Se=>{let Oe=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];ls(t,Oe);let Ue=x?4:1,Ae=N(e[0].dataType),Ne=`
|
|
972
|
+
fn setOutputAtIndex(flatIndex : i32, value : ${x?`vec4<${Ae}>`:Ae}) {
|
|
973
|
+
result[flatIndex] = ${x?`vec4<${Ae}>`:Ae}(value);
|
|
974
|
+
}
|
|
975
|
+
fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${x?`vec4<${Ae}>`:Ae}) {
|
|
976
|
+
let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));
|
|
977
|
+
setOutputAtIndex(flatIndex ${x?"/ 4":""}, value);
|
|
978
|
+
}`,ee=U("x",e[0].dataType,e[0].dims.length,L===3?1:L),Ie=U("w",e[1].dataType,e[1].dims.length,Ue),Ce=[ee,Ie],_e=te("result",e[0].dataType,r.length,Ue);if(l){let xt=U("bias",e[2].dataType,e[2].dims.length,Ue);Ce.push(xt),Ne+=`
|
|
979
|
+
fn getBiasByOutputCoords(coords : vec4<i32>) -> ${x?`vec4<${Ae}>`:Ae} {
|
|
980
|
+
return bias[coords.${h?"w":"y"}${x?"/ 4":""}];
|
|
981
|
+
}`}return`
|
|
982
|
+
${Bl("uniforms.result_strides")}
|
|
983
|
+
//struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>,
|
|
984
|
+
// outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>,
|
|
985
|
+
// dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };
|
|
986
|
+
${Se.registerUniforms(Oe).declareVariables(...Ce,_e)}
|
|
987
|
+
${Ne}
|
|
988
|
+
${Gl(h,se,ge,Be,l,t,Te[0],Te[1],Te[2],Ae)}
|
|
989
|
+
${x?Ln(I,$,Ae,void 0,!h,X):Un(I,$,Ae,void 0,!h,X,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${L};${x};${se};${ge};${Be};${V};${W};${X}`,inputDependencies:Ge},getRunData:()=>({outputs:[{dims:c?c(r):r,dataType:e[0].dataType}],dispatchGroup:{x:M[0],y:M[1],z:M[2]},programUniforms:ke}),getShaderSource:ue}}}),ql,Nn,Ti,Hl,Vn,jl,Kl,Ql,hm=T(()=>{Ee(),Vt(),xe(),he(),us(),On(),ql=e=>{let t=1;for(let r=0;r<e.length;r++)t*=e[r];return t},Nn=e=>typeof e=="number"?[e,e,e]:e,Ti=(e,t)=>t<=1?e:e+(e-1)*(t-1),Hl=(e,t,r,i=1)=>{let a=Ti(t,i);return Math.floor((e[0]*(r-1)-r+a)/2)},Vn=(e,t,r,i,a)=>{a==null&&(a=Hl(e,t[0],i[0]));let o=[0,0,0,r];for(let l=0;l<3;l++)e[l]+2*a>=t[l]&&(o[l]=Math.trunc((e[l]-t[l]+2*a)/i[l]+1));return o},jl=(e,t,r,i,a,o,l,u,c,h)=>{let p,m,y,w;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let v=Vn([t,r,i,1],[u,c,h],1,[a,o,l],e);m=v[0],y=v[1],w=v[2]}else if(Array.isArray(e)){if(!e.every((x,R,C)=>x===C[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let v=Vn([t,r,i,1],[u,c,h],1,[a,o,l],e[0]);m=v[0],y=v[1],w=v[2]}else if(e==="SAME_UPPER"){m=Math.ceil(t/a),y=Math.ceil(r/o),w=Math.ceil(i/l);let v=(m-1)*a+u-t,x=(y-1)*o+c-r,R=(w-1)*l+h-i,C=Math.floor(v/2),$=v-C,I=Math.floor(x/2),M=x-I,L=Math.floor(R/2),V=R-L;p={top:I,bottom:M,left:L,right:V,front:C,back:$}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:m,outHeight:y,outWidth:w}},Kl=(e,t,r,i,a,o=!1,l="channelsLast")=>{let u,c,h,p,m;if(l==="channelsLast")[u,c,h,p,m]=e;else if(l==="channelsFirst")[u,m,c,h,p]=e;else throw new Error(`Unknown dataFormat ${l}`);let[y,,w,v,x]=t,[R,C,$]=Nn(r),[I,M,L]=Nn(i),V=Ti(w,I),W=Ti(v,M),X=Ti(x,L),{padInfo:se,outDepth:ge,outHeight:Be,outWidth:Te}=jl(a,c,h,p,R,C,$,V,W,X),ke=o?y*m:y,Ge=[0,0,0,0,0];return l==="channelsFirst"?Ge=[u,ke,ge,Be,Te]:l==="channelsLast"&&(Ge=[u,ge,Be,Te,ke]),{batchSize:u,dataFormat:l,inDepth:c,inHeight:h,inWidth:p,inChannels:m,outDepth:ge,outHeight:Be,outWidth:Te,outChannels:ke,padInfo:se,strideDepth:R,strideHeight:C,strideWidth:$,filterDepth:w,filterHeight:v,filterWidth:x,effectiveFilterDepth:V,effectiveFilterHeight:W,effectiveFilterWidth:X,dilationDepth:I,dilationHeight:M,dilationWidth:L,inShape:e,outShape:Ge,filterShape:t}},Ql=(e,t,r,i,a,o)=>{let l=o==="channelsLast";l?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],c={x:r.map((R,C)=>C)},h=[Math.ceil(ql(c.x.map(R=>r[R]))/u[0]),1,1];Fe("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let p=1,m=q.size(r),y=[{type:12,data:m},{type:12,data:i},{type:12,data:a},{type:12,data:t.strides},{type:12,data:t.dilations}];os(t,y),y.push(...D(e[0].dims,e[1].dims));let w=["rank","rank"],v=e.length===3;v&&(y.push(...D(e[2].dims)),w.push("rank")),y.push(...D(r));let x=R=>{let C=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:i.length},{name:"pads",type:"u32",length:a.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];ls(t,C);let $=1,I=N(e[0].dataType),M=U("x",e[0].dataType,e[0].dims.length,p),L=U("W",e[1].dataType,e[1].dims.length,$),V=[M,L],W=te("result",e[0].dataType,r.length,$),X="";if(v){let Be=U("bias",e[2].dataType,e[2].dims.length,$);V.push(Be),X+=`
|
|
990
|
+
fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${I} {
|
|
991
|
+
return bias[${l?H("coords",4,5):H("coords",1,5)}];
|
|
992
|
+
}`}let se=$t(p,I),ge=as(t,se,I);return`
|
|
993
|
+
${X}
|
|
994
|
+
fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
|
|
995
|
+
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
|
|
996
|
+
return ${M.getByIndices("aIndices")};
|
|
997
|
+
}
|
|
998
|
+
fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
|
|
999
|
+
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
|
|
1000
|
+
return ${L.getByIndices("aIndices")};
|
|
1001
|
+
}
|
|
1002
|
+
${R.registerUniforms(C).declareVariables(...V,W)}
|
|
1003
|
+
${R.mainStart()}
|
|
1004
|
+
${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1005
|
+
let coords = ${W.offsetToIndices("global_idx")};
|
|
1006
|
+
let batch = ${H("coords",0,M.rank)};
|
|
1007
|
+
let d2 = ${l?H("coords",M.rank-1,M.rank):H("coords",1,M.rank)};
|
|
1008
|
+
let xFRCCorner = vec3<u32>(${l?H("coords",1,M.rank):H("coords",2,M.rank)},
|
|
1009
|
+
${l?H("coords",2,M.rank):H("coords",3,M.rank)},
|
|
1010
|
+
${l?H("coords",3,M.rank):H("coords",4,M.rank)}) * uniforms.strides - uniforms.pads;
|
|
1011
|
+
let xFCorner = xFRCCorner.x;
|
|
1012
|
+
let xRCorner = xFRCCorner.y;
|
|
1013
|
+
let xCCorner = xFRCCorner.z;
|
|
1014
|
+
let xShapeY = ${l?H("uniforms.x_shape",1,M.rank):H("uniforms.x_shape",2,M.rank)};
|
|
1015
|
+
let xShapeZ = ${l?H("uniforms.x_shape",2,M.rank):H("uniforms.x_shape",3,M.rank)};
|
|
1016
|
+
let xShapeW = ${l?H("uniforms.x_shape",3,M.rank):H("uniforms.x_shape",4,M.rank)};
|
|
1017
|
+
let xShapeU = ${l?H("uniforms.x_shape",4,M.rank):H("uniforms.x_shape",1,M.rank)};
|
|
1018
|
+
let inputDepthNearestVec4 = (xShapeU / 4) * 4;
|
|
1019
|
+
let inputDepthVec4Remainder = xShapeU % 4;
|
|
1020
|
+
|
|
1021
|
+
var value = 0.0;
|
|
1022
|
+
for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {
|
|
1023
|
+
let xF = xFCorner + wF * uniforms.dilations[0];
|
|
1024
|
+
if (xF < 0 || xF >= xShapeY) {
|
|
1025
|
+
continue;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {
|
|
1029
|
+
let xR = xRCorner + wR * uniforms.dilations[1];
|
|
1030
|
+
if (xR < 0 || xR >= xShapeZ) {
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {
|
|
1035
|
+
let xC = xCCorner + wC * uniforms.dilations[2];
|
|
1036
|
+
if (xC < 0 || xC >= xShapeW) {
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {
|
|
1041
|
+
${l?`let xValues = vec4<f32>(
|
|
1042
|
+
getX(batch, xF, xR, xC, d1),
|
|
1043
|
+
getX(batch, xF, xR, xC, d1 + 1),
|
|
1044
|
+
getX(batch, xF, xR, xC, d1 + 2),
|
|
1045
|
+
getX(batch, xF, xR, xC, d1 + 3));
|
|
1046
|
+
`:`let xValues = vec4<f32>(
|
|
1047
|
+
getX(batch, d1, xF, xR, xC),
|
|
1048
|
+
getX(batch, d1 + 1, xF, xR, xC),
|
|
1049
|
+
getX(batch, d1 + 2, xF, xR, xC),
|
|
1050
|
+
getX(batch, d1 + 3, xF, xR, xC));
|
|
1051
|
+
`}
|
|
1052
|
+
let wValues = vec4<f32>(
|
|
1053
|
+
getW(d2, d1, wF, wR, wC),
|
|
1054
|
+
getW(d2, d1 + 1, wF, wR, wC),
|
|
1055
|
+
getW(d2, d1 + 2, wF, wR, wC),
|
|
1056
|
+
getW(d2, d1 + 3, wF, wR, wC));
|
|
1057
|
+
value += dot(xValues, wValues);
|
|
1058
|
+
}
|
|
1059
|
+
if (inputDepthVec4Remainder == 1) {
|
|
1060
|
+
${l?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4)
|
|
1061
|
+
* getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC)
|
|
1062
|
+
* getW(d2, inputDepthNearestVec4, wF, wR, wC);`}
|
|
1063
|
+
} else if (inputDepthVec4Remainder == 2) {
|
|
1064
|
+
${l?`let xValues = vec2<f32>(
|
|
1065
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4),
|
|
1066
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));
|
|
1067
|
+
`:`let xValues = vec2<f32>(
|
|
1068
|
+
getX(batch, inputDepthNearestVec4, xF, xR, xC),
|
|
1069
|
+
getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));
|
|
1070
|
+
`}
|
|
1071
|
+
let wValues = vec2<f32>(
|
|
1072
|
+
getW(d2, inputDepthNearestVec4, wF, wR, wC),
|
|
1073
|
+
getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));
|
|
1074
|
+
value += dot(xValues, wValues);
|
|
1075
|
+
} else if (inputDepthVec4Remainder == 3) {
|
|
1076
|
+
${l?`let xValues = vec3<f32>(
|
|
1077
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4),
|
|
1078
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),
|
|
1079
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));
|
|
1080
|
+
`:`let xValues = vec3<f32>(
|
|
1081
|
+
getX(batch, inputDepthNearestVec4, xF, xR, xC),
|
|
1082
|
+
getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),
|
|
1083
|
+
getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));
|
|
1084
|
+
`}
|
|
1085
|
+
let wValues = vec3<f32>(
|
|
1086
|
+
getW(d2, inputDepthNearestVec4, wF, wR, wC),
|
|
1087
|
+
getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),
|
|
1088
|
+
getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));
|
|
1089
|
+
value += dot(xValues, wValues);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
${v?"value = value + getBiasByOutputCoords(coords)":""};
|
|
1095
|
+
${ge}
|
|
1096
|
+
result[global_idx] = f32(value);
|
|
1097
|
+
}`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${l};${p};${v}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:y}),getShaderSource:x}}}),Xl,Zl,pm=T(()=>{Ee(),xe(),he(),us(),Xl=(e,t,r,i)=>{let a=e.length>2,o=a?"value += b[output_channel];":"",l=e[0].dims,u=e[1].dims,c=t.format==="NHWC",h=c?r[3]:r[1],p=h/t.group,m=c&&p>=4?F(h):1,y=q.size(r)/m,w=[{type:12,data:y},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:p}];os(t,w),w.push(...D(l,[u[0],u[1],u[2],u[3]/m]));let v=a?["rank","rank","rank"]:["rank","rank"];w.push(...D([r[0],r[1],r[2],r[3]/m]));let x=R=>{let C=te("output",e[0].dataType,r.length,m),$=N(C.type.tensor),I=as(t,C.type.value,$),M=U("x",e[0].dataType,l.length),L=U("w",e[1].dataType,u.length,m),V=[M,L];a&&V.push(U("b",e[2].dataType,e[2].dims,m));let W=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];ls(t,W);let X=c?`
|
|
1098
|
+
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {
|
|
1099
|
+
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
|
|
1100
|
+
|
|
1101
|
+
if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {
|
|
1102
|
+
continue;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {
|
|
1106
|
+
let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
|
|
1107
|
+
if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {
|
|
1108
|
+
continue;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {
|
|
1112
|
+
let input_channel = in_channel_offset + wInChannel;
|
|
1113
|
+
let xVal = ${M.get("batch","xHeight","xWidth","input_channel")};
|
|
1114
|
+
let wVal = ${L.get("wHeight","wWidth","wInChannel","output_channel")};
|
|
1115
|
+
value += xVal * wVal;
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
`:`
|
|
1120
|
+
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {
|
|
1121
|
+
let input_channel = in_channel_offset + wInChannel;
|
|
1122
|
+
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {
|
|
1123
|
+
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
|
|
1124
|
+
|
|
1125
|
+
if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {
|
|
1126
|
+
continue;
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {
|
|
1130
|
+
let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
|
|
1131
|
+
if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {
|
|
1132
|
+
continue;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
let xVal = ${M.get("batch","input_channel","xHeight","xWidth")};
|
|
1136
|
+
let wVal = ${L.get("output_channel","wInChannel","wHeight","wWidth")};
|
|
1137
|
+
value += xVal * wVal;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
`;return`
|
|
1142
|
+
${R.registerUniforms(W).declareVariables(...V,C)}
|
|
1143
|
+
|
|
1144
|
+
${R.mainStart()}
|
|
1145
|
+
${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1146
|
+
|
|
1147
|
+
let outputIndices = ${C.offsetToIndices("global_idx")};
|
|
1148
|
+
let batch: u32 = outputIndices[0];
|
|
1149
|
+
let output_channel: u32 = outputIndices[${c?3:1}];
|
|
1150
|
+
let xRCCorner: vec2<u32> = vec2<u32>(outputIndices[${c?1:2}], outputIndices[${c?2:3}]) * uniforms.strides - uniforms.pads;
|
|
1151
|
+
let group_id: u32 = output_channel * ${m} / uniforms.output_channels_per_group;
|
|
1152
|
+
var in_channel_offset = group_id * uniforms.w_shape[${c?2:1}];
|
|
1153
|
+
|
|
1154
|
+
var value: ${C.type.value} = ${C.type.value}(0);
|
|
1155
|
+
${X}
|
|
1156
|
+
${o}
|
|
1157
|
+
${I}
|
|
1158
|
+
${C.setByOffset("global_idx","value")}
|
|
1159
|
+
}`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${m}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:w}),getShaderSource:x}},Zl=(e,t,r,i)=>{let a=e.length>2,o=F(r[3]),l=F(r[2]),u=q.size(r)/o/l,c=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/o],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/o],p=[r[0],r[1],r[2],r[3]/o],m=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];os(t,m),m.push(...D(c,h,p));let y=(l-1)*t.strides[1]+h[1],w=v=>{let x=te("output",e[0].dataType,p.length,o),R=N(x.type.tensor),C=as(t,x.type.value,R),$=U("x",e[0].dataType,c.length,o),I=U("w",e[1].dataType,h.length,o),M=[$,I];a&&M.push(U("b",e[2].dataType,e[2].dims,o));let L=a?"value += b[output_channel];":"",V=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return ls(t,V),`
|
|
1160
|
+
${v.registerUniforms(V).declareVariables(...M,x)}
|
|
1161
|
+
${v.mainStart()}
|
|
1162
|
+
${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1163
|
+
let width0 = uniforms.output_shape[3];
|
|
1164
|
+
let output_channel = global_idx % width0;
|
|
1165
|
+
var index1 = global_idx / width0;
|
|
1166
|
+
let width1 = uniforms.output_shape[2] / ${l}u;
|
|
1167
|
+
let col = (index1 % width1) * ${l}u;
|
|
1168
|
+
index1 = index1 / width1;
|
|
1169
|
+
let row = index1 % uniforms.output_shape[1];
|
|
1170
|
+
let batch = index1 / uniforms.output_shape[1];
|
|
1171
|
+
|
|
1172
|
+
let x_corner = vec2<i32>(i32(row), i32(col)) * uniforms.strides - uniforms.pads;
|
|
1173
|
+
|
|
1174
|
+
var x_vals: array<${$.type.value}, ${y}>;
|
|
1175
|
+
var values: array<${x.type.value}, ${l}>;
|
|
1176
|
+
let input_channel = output_channel;
|
|
1177
|
+
// Use constant instead of uniform can give better performance for w's height/width.
|
|
1178
|
+
for (var w_height: u32 = 0u; w_height < ${h[0]}; w_height++) {
|
|
1179
|
+
let x_height = x_corner.x + i32(w_height);
|
|
1180
|
+
if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {
|
|
1181
|
+
for (var i = 0; i < ${y}; i++) {
|
|
1182
|
+
let x_width = x_corner.y + i;
|
|
1183
|
+
if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {
|
|
1184
|
+
x_vals[i] = ${$.get("batch","u32(x_height)","u32(x_width)","input_channel")};
|
|
1185
|
+
} else {
|
|
1186
|
+
x_vals[i] = ${$.type.value}(0);
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) {
|
|
1190
|
+
let w_val = ${I.get("w_height","w_width","0","output_channel")};
|
|
1191
|
+
for (var i = 0u; i < ${l}u; i++) {
|
|
1192
|
+
values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
for (var i = 0u; i < ${l}u; i++) {
|
|
1199
|
+
var value = values[i];
|
|
1200
|
+
${L}
|
|
1201
|
+
${C}
|
|
1202
|
+
${x.set("batch","row","col + i","output_channel","value")};
|
|
1203
|
+
}
|
|
1204
|
+
}`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${o};${l};${y};${h[0]};${h[1]}`,inputDependencies:a?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:m}),getShaderSource:w}}}),Jl,Ji,Yl,Yi,Gn,Wn,eu,tu,qn,mm=T(()=>{xe(),cm(),hm(),Fn(),pm(),us(),Dn(),Le(),Jl=(e,t,r,i,a,o)=>{let l=e[0],u=e.slice(o?1:2,o?3:4),c=u.length,h=t[0],p=t.slice(2).map((y,w)=>y+(y-1)*(r[w]-1)),m=u.map((y,w)=>y+i[w]+i[w+c]).map((y,w)=>Math.floor((y-p[w]+a[w])/a[w]));return m.splice(0,0,l),m.splice(o?3:1,0,h),m},Ji=[2,3,1,0],Yl=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[1]*t.group;if(r!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},Yi=(e,t)=>{let r=e.kernelShape.slice();r.length<t[1].dims.length-2&&r.push(...Array(t[1].dims.length-2-r.length).fill(0));for(let o=2;o<t[1].dims.length;++o)r[o-2]===0&&(r[o-2]=t[1].dims[o]);let i=e.pads.slice();Er.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,r,i,e.format==="NHWC",e.autoPad);let a=Object.assign({},e);return Object.assign(a,{kernelShape:r,pads:i}),a},Gn=e=>{let t=Pn(e),r=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],a=e.dilations,o=e.group,l=e.kernel_shape,u=e.pads,c=e.strides,h=e.w_is_const();return{autoPad:i,format:r,dilations:a,group:o,kernelShape:l,pads:u,strides:c,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Wn=(e,t,r,i)=>{let a=r.format==="NHWC",o=Jl(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,a);if(r.group!==1){let V=[t[0]];if(a){let W=e.kernelCustomData.wT??e.compute(it(t[1],Ji),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=W),V.push(W)}else V.push(t[1]);t.length===3&&V.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&a&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(Zl(V,r,o,i),{inputs:V}):e.compute(Xl(V,r,o,i),{inputs:V});return}let l=t.length===3,u=t[0].dims[a?1:2],c=t[0].dims[a?2:3],h=t[0].dims[a?3:1],p=t[1].dims[2],m=t[1].dims[3],y=o[a?1:2],w=o[a?2:3],v=o[a?3:1],x=a&&p===u&&m===c&&r.pads[0]===0&&r.pads[1]===0;if(x||p===1&&m===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let V=o[0],W,X,se,ge=[];if(a){let ke=e.kernelCustomData.wT??e.compute(it(t[1],Ji),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=ke),x){let Ge=u*c*h;W=t[0].reshape([1,V,Ge]),X=ke.reshape([1,Ge,v]),se=[1,V,v]}else W=t[0].reshape([V,u*c,h]),X=ke.reshape([1,h,v]),se=[V,y*w,v];ge.push(W),ge.push(X)}else W=t[0].reshape([V,h,u*c]),X=t[1].reshape([1,v,h]),se=[V,v,y*w],ge.push(X),ge.push(W);l&&ge.push(t[2]);let Be=se[2],Te=ge[0].dims[ge[0].dims.length-1];Be<8&&Te<8?e.compute(zn(ge,r,o,se,a,i),{inputs:ge}):e.compute(Zi(ge,r,o,se,a,i),{inputs:ge});return}let R=!0,C=e.kernelCustomData.wT??e.compute(it(t[1],Ji),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=C);let $=[t[0],C];l&&$.push(t[2]);let I=a?y*w:v,M=a?v:y*w,L=p*m*h;e.compute(Wl($,r,o,I,M,L,l,R,i),{inputs:$})},eu=(e,t)=>{let r=t.format==="NHWC",i=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&i.push(e.inputs[2]);let a=[0,t.pads[0],0,t.pads[1]],o=[1].concat(t.strides),l=[1].concat(t.dilations),u=[1].concat(t.kernelShape),c=Yi({...t,pads:a,strides:o,dilations:l,kernelShape:u},i);Wn(e,i,c,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},tu=(e,t,r)=>{let i=r.format==="NHWC"?"channelsLast":"channelsFirst",a=Yi(r,t),o=r.autoPad==="NOTSET"?r.pads:r.autoPad,l=Kl(t[0].dims,t[1].dims,r.strides,r.dilations,o,!1,i);e.compute(Ql(t,a,l.outShape,[l.filterDepth,l.filterHeight,l.filterWidth],[l.padInfo.front,l.padInfo.top,l.padInfo.left],i))},qn=(e,t)=>{if(Yl(e.inputs,t),e.inputs[0].dims.length===3)eu(e,t);else if(e.inputs[0].dims.length===5)tu(e,e.inputs,t);else{let r=Yi(t,e.inputs);Wn(e,e.inputs,r)}}}),ru,fm=T(()=>{Ee(),Vt(),xe(),he(),ru=(e,t,r)=>{let i=e.length>2,a=t.outputShape,o=t.format==="NHWC",l=t.group,u=e[1].dims,c=u[2]/l,h=u[3],p=o?F(c):1,m=o&&h===1&&c>=4,y=m?Math.floor(c/4)*4:Math.floor(c/p)*p,w=c-y,v=o?F(h):1,x=o?h===1?p:v:1,R=q.size(a)/v,C=[Math.ceil(R/64),1,1];Fe("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${C}`);let $=["rank","rank"],I=[t.strides[0],t.strides[1]],M=[t.kernelShape[o?1:2],t.kernelShape[o?2:3]],L=[t.dilations[0],t.dilations[1]],V=[M[0]+(t.dilations[0]<=1?0:(t.kernelShape[o?1:2]-1)*(t.dilations[0]-1)),M[1]+(t.dilations[1]<=1?0:(t.kernelShape[o?2:3]-1)*(t.dilations[1]-1))],W=[V[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),V[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],X=[{type:12,data:R},{type:12,data:I},{type:12,data:M},{type:12,data:L},{type:12,data:V},{type:6,data:W},{type:12,data:y},{type:12,data:c},{type:12,data:h},...D(e[0].dims,e[1].dims)];i&&(X.push(...D(e[2].dims)),$.push("rank")),X.push(...D(a));let se=ge=>{let Be=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:I.length},{name:"filter_dims",type:"u32",length:M.length},{name:"dilations",type:"u32",length:M.length},{name:"effective_filter_dims",type:"u32",length:V.length},{name:"pads",type:"i32",length:W.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Te=N(e[0].dataType),ke=o?1:2,Ge=o?2:3,ue=o?3:1,Se=U("W",e[1].dataType,e[1].dims.length,x),Oe=U("Dy",e[0].dataType,e[0].dims.length,p),Ue=[Oe,Se];i&&Ue.push(U("bias",e[2].dataType,[a[ue]].length,v));let Ae=te("result",e[0].dataType,a.length,v),Ne=()=>{let Ce="";if(m)p===4?Ce+=`
|
|
1205
|
+
let xValue = ${Oe.getByOffset("x_offset")};
|
|
1206
|
+
let wValue = ${Se.getByOffset("w_offset")};
|
|
1207
|
+
dotProd = dotProd + dot(xValue, wValue);
|
|
1208
|
+
x_offset += 1u;
|
|
1209
|
+
w_offset += 1u;`:p===2?Ce+=`
|
|
1210
|
+
dotProd = dotProd + dot(vec4<${Te}>(${Oe.getByOffset("x_offset")}, ${Oe.getByOffset("x_offset + 1u")}), vec4<${Te}>(${Se.getByOffset("w_offset")}, ${Se.getByOffset("w_offset + 1u")}));
|
|
1211
|
+
x_offset += 2u;
|
|
1212
|
+
w_offset += 2u;`:p===1&&(Ce+=`
|
|
1213
|
+
dotProd = dotProd + dot(vec4<${Te}>(${Oe.getByOffset("x_offset")}, ${Oe.getByOffset("x_offset + 1u")}, ${Oe.getByOffset("x_offset + 2u")}, ${Oe.getByOffset("x_offset + 3u")}), vec4<${Te}>(${Se.getByOffset("w_offset")}, ${Se.getByOffset("w_offset + 1u")}, ${Se.getByOffset("w_offset + 2u")}, ${Se.getByOffset("w_offset + 3u")}));
|
|
1214
|
+
x_offset += 4u;
|
|
1215
|
+
w_offset += 4u;`);else if(Ce+=`
|
|
1216
|
+
let xValue = ${o?Oe.getByOffset(`${Oe.indicesToOffset(`${Oe.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):Oe.get("batch","inputChannel","idyR","idyC")};
|
|
1217
|
+
`,p===1)Ce+=`
|
|
1218
|
+
let w_offset = ${Se.indicesToOffset(`${Se.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};
|
|
1219
|
+
let wValue = ${Se.getByOffset(`w_offset / ${x}`)};
|
|
1220
|
+
dotProd = dotProd + xValue * wValue;`;else for(let _e=0;_e<p;_e++)Ce+=`
|
|
1221
|
+
let wValue${_e} = ${Se.getByOffset(`${Se.indicesToOffset(`${Se.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${_e}, wOutChannel)`)} / ${x}`)};
|
|
1222
|
+
dotProd = dotProd + xValue[${_e}] * wValue${_e};`;return Ce},ee=()=>{if(w===0)return"";if(!m)throw new Error(`packInputAs4 ${m} is not true.`);let Ce="";if(p===1){Ce+="dotProd = dotProd";for(let _e=0;_e<w;_e++)Ce+=`
|
|
1223
|
+
+ ${Oe.getByOffset(`x_offset + ${_e}`)} * ${Se.getByOffset(`w_offset + ${_e}`)}`;Ce+=";"}else if(p===2){if(w!==2)throw new Error(`Invalid inputChannelsRemainder ${w}.`);Ce+=`
|
|
1224
|
+
let xValue = ${Oe.getByOffset("x_offset")};
|
|
1225
|
+
let wValue = ${Se.getByOffset("w_offset")};
|
|
1226
|
+
dotProd = dotProd + dot(xValue, wValue);`}return Ce},Ie=`
|
|
1227
|
+
let outputIndices = ${Ae.offsetToIndices(`global_idx * ${v}`)};
|
|
1228
|
+
let batch = ${Ae.indicesGet("outputIndices",0)};
|
|
1229
|
+
let d1 = ${Ae.indicesGet("outputIndices",ue)};
|
|
1230
|
+
let r = ${Ae.indicesGet("outputIndices",ke)};
|
|
1231
|
+
let c = ${Ae.indicesGet("outputIndices",Ge)};
|
|
1232
|
+
let dyCorner = vec2<i32>(i32(r), i32(c)) - uniforms.pads;
|
|
1233
|
+
let dyRCorner = dyCorner.x;
|
|
1234
|
+
let dyCCorner = dyCorner.y;
|
|
1235
|
+
let groupId = d1 / uniforms.output_channels_per_group;
|
|
1236
|
+
let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;
|
|
1237
|
+
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
1238
|
+
// ? = to be determined. : = across all values in that axis.
|
|
1239
|
+
var dotProd = ${Ae.type.value}(0.0);
|
|
1240
|
+
var wR: u32 = 0;
|
|
1241
|
+
if (uniforms.dilations.x == 1) {
|
|
1242
|
+
// Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0
|
|
1243
|
+
wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner);
|
|
1244
|
+
}
|
|
1245
|
+
for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {
|
|
1246
|
+
if (wR % uniforms.dilations.x != 0) {
|
|
1247
|
+
continue;
|
|
1248
|
+
}
|
|
1249
|
+
let dyR = (${Te}(dyRCorner) + ${Te}(wR)) / ${Te}(uniforms.strides[0]);
|
|
1250
|
+
let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;
|
|
1251
|
+
if (dyR < 0.0 || dyR >= ${Te}(uniforms.Dy_shape[${ke}]) || fract(dyR) > 0.0 ||
|
|
1252
|
+
wRPerm < 0) {
|
|
1253
|
+
continue;
|
|
1254
|
+
}
|
|
1255
|
+
let idyR: u32 = u32(dyR);
|
|
1256
|
+
var wC: u32 = 0;
|
|
1257
|
+
if (uniforms.dilations.y == 1) {
|
|
1258
|
+
// Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0
|
|
1259
|
+
wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner);
|
|
1260
|
+
}
|
|
1261
|
+
for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {
|
|
1262
|
+
if (wC % uniforms.dilations.y != 0) {
|
|
1263
|
+
continue;
|
|
1264
|
+
}
|
|
1265
|
+
let dyC = (${Te}(dyCCorner) + ${Te}(wC)) / ${Te}(uniforms.strides.y);
|
|
1266
|
+
let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;
|
|
1267
|
+
if (dyC < 0.0 || dyC >= ${Te}(uniforms.Dy_shape[${Ge}]) ||
|
|
1268
|
+
fract(dyC) > 0.0 || wCPerm < 0) {
|
|
1269
|
+
continue;
|
|
1270
|
+
}
|
|
1271
|
+
let idyC: u32 = u32(dyC);
|
|
1272
|
+
var inputChannel = groupId * uniforms.input_channels_per_group;
|
|
1273
|
+
${m?`
|
|
1274
|
+
var x_offset = ${Oe.indicesToOffset(`${Oe.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p};
|
|
1275
|
+
var w_offset = ${Se.indicesToOffset(`${Se.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${x};
|
|
1276
|
+
`:""}
|
|
1277
|
+
for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${m?4:p}) {
|
|
1278
|
+
${Ne()}
|
|
1279
|
+
inputChannel = inputChannel + ${m?4:p};
|
|
1280
|
+
}
|
|
1281
|
+
${ee()}
|
|
1282
|
+
wC = wC + uniforms.strides.y - 1;
|
|
1283
|
+
}
|
|
1284
|
+
wR = wR + uniforms.strides[0] - 1;
|
|
1285
|
+
}
|
|
1286
|
+
let value = dotProd${i?` + bias[d1 / ${v}]`:""};
|
|
1287
|
+
${Ae.setByOffset("global_idx","value")};
|
|
1288
|
+
`;return`
|
|
1289
|
+
${ge.registerUniforms(Be).declareVariables(...Ue,Ae)}
|
|
1290
|
+
${ge.mainStart()}
|
|
1291
|
+
${ge.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};
|
|
1292
|
+
${Ie}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${p}${x}${v}${m}${w}`,inputDependencies:$},getRunData:()=>({dispatchGroup:{x:C[0],y:C[1],z:C[2]},outputs:[{dims:r?r(a):a,dataType:e[0].dataType}],programUniforms:X}),getShaderSource:se}}}),su,iu,nu,Hn,au,ou,jn,lu,uu,gm=T(()=>{fm(),us(),Le(),su=(e,t,r,i,a,o)=>(e-1)*t+r+(i-1)*a+1-o,iu=(e,t,r,i,a)=>{let o=Math.floor(e/2);t==="SAME_UPPER"?(r[i]=o,r[a]=e-o):t==="SAME_LOWER"&&(r[i]=e-o,r[a]=o)},nu=(e,t,r,i,a,o,l,u,c,h)=>{let p=e.length-2,m=h.length===0;c.length<p&&c.push(...Array(p-c.length).fill(0));let y=e[0],w=t[u?3:1]*a;for(let v=0,x=e.length-p-(u?1:0);v<p;++v,++x){let R=e[x],C=m?R*l[v]:h[v],$=su(R,l[v],o[v],t[x],r[v],C);iu($,i,o,v,v+p),m&&h.push(l[v]*(R-1)+c[v]+(t[x]-1)*r[v]+1-o[v]-o[v+p])}h.splice(0,0,y),h.splice(u?3:1,0,w)},Hn=(e,t)=>{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((m,y)=>m*y,1)===0){r.length=0;for(let m=2;m<t[1].dims.length;++m)r.push(t[1].dims[m])}let i=e.format==="NHWC";r.splice(0,0,t[1].dims[0]),r.splice(i?3:1,0,t[1].dims[1]);let a=e.pads.slice(),o=e.outputShape.slice(),l=e.outputPadding.slice(),u=t[0].dims,c=e.dilations.slice();if(c.reduce((m,y)=>m+y,0)===0){let m=t[0].dims.length-2;c=new Array(m).fill(1)}let h=e.strides.slice();if(h.reduce((m,y)=>m+y,0)===0){let m=t[0].dims.length-2;h=new Array(m).fill(1)}nu(u,r,c,e.autoPad,e.group,a,h,i,l,o);let p=Object.assign({},e);return Object.assign(p,{kernelShape:r,pads:a,outputPadding:l,outputShape:o,dilations:c,strides:h}),p},au=e=>{let t=Pn(e),r=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],a=e.dilations,o=e.group??1,l=e.kernelShape,u=e.pads,c=e.strides,h=e.wIsConst(),p=e.outputPadding,m=e.outputShape;return{autoPad:i,format:r,dilations:a,group:o,kernelShape:l,outputPadding:p,outputShape:m,pads:u,strides:c,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},ou=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[0];if(r!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let a=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==a))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.reduce((l,u)=>l+u,0)>0&&t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.reduce((l,u)=>l+u,0)>0&&t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.reduce((l,u)=>l+u,0)>0&&t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.outputPadding.length!==o&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${o}D`);if(t.kernelShape.reduce((l,u)=>l+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},jn=(e,t,r,i)=>{let a=e.kernelCustomData.wT??e.compute(it(t[1],[2,3,0,1]),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=a);let o=[t[0],a];t.length===3&&o.push(t[2]),e.compute(ru(o,r,i),{inputs:o})},lu=(e,t)=>{let r=t.format==="NHWC",i=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&i.push(e.inputs[2]);let a=t.kernelShape;(a.length===0||a[0]===0)&&(a=[e.inputs[1].dims[2]]);let o=t.dilations;(o.length===0||o[0]===0)&&(o=[1]);let l=t.strides;(l.length===0||l[0]===0)&&(l=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],l=[1].concat(l),o=[1].concat(o),a=[1].concat(a);let c=t.outputPadding;c=[0].concat(c);let h=Hn({...t,pads:u,strides:l,dilations:o,kernelShape:a,outputPadding:c},i);jn(e,i,h,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},uu=(e,t)=>{if(ou(e.inputs,t),e.inputs[0].dims.length===3)lu(e,t);else{let r=Hn(t,e.inputs);jn(e,e.inputs,r)}}}),du,cu,hu,ym=T(()=>{Ee(),xe(),k(),he(),du=(e,t,r,i)=>{let a=q.size(t),o=t.length,l=U("input",e,o),u=te("output",e,o),c=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),h=q.normalizeAxis(c,o),p=m=>{let y=` i32(${l.indicesGet("inputIndices","uniforms.axis")}) `,w=H("uniforms.input_shape","uniforms.axis",o),v=i.reverse?y+(i.exclusive?" + 1":""):"0",x=i.reverse?w:y+(i.exclusive?"":" + 1");return`
|
|
1293
|
+
${m.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(l,u)}
|
|
1294
|
+
${m.mainStart()}
|
|
1295
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1296
|
+
var inputIndices = ${u.offsetToIndices("global_idx")};
|
|
1297
|
+
var sum = ${u.type.value}(0);
|
|
1298
|
+
let first : i32 = ${v};
|
|
1299
|
+
let last : i32 = ${x};
|
|
1300
|
+
for (var i : i32 = first; i < last; i++) {
|
|
1301
|
+
${l.indicesSet("inputIndices","uniforms.axis","u32(i)")};
|
|
1302
|
+
sum = sum + ${l.getByIndices("inputIndices")};
|
|
1303
|
+
}
|
|
1304
|
+
${u.setByOffset("global_idx","sum")};
|
|
1305
|
+
}`};return{name:"CumSum",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},{type:12,data:h},...D(t,t)]}),getShaderSource:p}},cu=(e,t)=>{let r=e.inputs[0].dims,i=e.inputs[0].dataType,a=e.inputs[1];e.compute(du(i,r,a,t),{inputs:[0]})},hu=e=>{let t=e.exclusive===1,r=e.reverse===1;return _({exclusive:t,reverse:r})}}),pu,mu,fu,gu,yu,wm=T(()=>{Ee(),xe(),k(),he(),pu=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},mu=(e,t,r,i)=>{let a=[];a.push(`fn perm(i: ${i.type.indices}) -> ${r.type.indices} {
|
|
1306
|
+
var a: ${r.type.indices};`);for(let o=0;o<t;++o)a.push(r.indicesSet("a",e[o],`i[${o}]`));return a.push("return a;}"),a.join(`
|
|
1307
|
+
`)},fu=(e,t)=>{let r,i,a,o,l,u,c=t.format==="NHWC",h=t.blocksize,p=t.mode==="DCR";c?([r,i,a,o]=e.dims,l=p?[r,i,a,h,h,o/h**2]:[r,i,a,o/h**2,h,h],u=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,i,a,o]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],l=p?[r,h,h,o/h**2,i,a]:[r,o/h**2,h,h,i,a],u=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let m=e.reshape(l),y=m.dims.length,w=e.dataType,v=U("a",w,y),x=te("output",w,y),R=C=>`
|
|
1308
|
+
${C.registerUniform("output_size","u32").declareVariables(v,x)}
|
|
1309
|
+
|
|
1310
|
+
${mu(u,y,v,x)}
|
|
1311
|
+
|
|
1312
|
+
${C.mainStart()}
|
|
1313
|
+
${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1314
|
+
|
|
1315
|
+
let indices = ${x.offsetToIndices("global_idx")};
|
|
1316
|
+
let aIndices = perm(indices);
|
|
1317
|
+
|
|
1318
|
+
${x.setByOffset("global_idx",v.getByIndices("aIndices"))}
|
|
1319
|
+
}`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:C=>{let $=c?[r,i*h,a*h,o/h**2]:[r,o/h**2,i*h,a*h],I=q.size($),M=m.dims,L=q.sortBasedOnPerm(M,u);return{outputs:[{dims:$,dataType:C[0].dataType}],dispatchGroup:{x:Math.ceil(I/64)},programUniforms:[{type:12,data:I},...D(M,L)]}},getShaderSource:R}},gu=(e,t)=>{pu(e.inputs),e.compute(fu(e.inputs[0],t))},yu=e=>_({blocksize:e.blocksize,mode:e.mode,format:e.format})}),en,Ci,Kn,wu,vu,bu,_u,Qn,Su,$u,xu,vm=T(()=>{Ee(),xe(),k(),he(),en="[a-zA-Z]|\\.\\.\\.",Ci="("+en+")+",Kn="^"+Ci+"$",wu="("+Ci+",)*"+Ci,vu="^"+wu+"$",bu=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let r=this.symbolToIndices.get(e);r===void 0?r=[t]:r.push(t),this.symbolToIndices.set(e,r)}},_u=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,i]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(vu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,o)=>{let l=e[o].dims.slice();if(!a.match(RegExp(Kn)))throw new Error("Invalid LHS term");let u=this.processTerm(a,!0,l,o);this.lhs.push(u)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([a,o])=>o.count===1||a==="...").map(([a])=>a).join("");else if(!i.match(RegExp(Ci)))throw new Error("Invalid RHS");i.match(RegExp(en,"g"))?.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(a);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(i,!1,this.outputDims)}addSymbol(e,t,r){let i=this.symbolToInfo.get(e);if(i!==void 0){if(i.dimValue!==t&&i.count!==1)throw new Error("Dimension mismatch");i.count++,i.inputIndices.push(r)}else i={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,i)}processTerm(e,t,r,i=-1){let a=r.length,o=!1,l=[],u=0;if(!e.match(RegExp(Kn))&&!t&&e!=="")throw new Error("Invalid LHS term");let c=e.match(RegExp(en,"g")),h=new bu(i);return c?.forEach((p,m)=>{if(p==="..."){if(o)throw new Error("Only one ellipsis is allowed per input term");o=!0;let y=a-c.length+1;if(y<0)throw new Error("Ellipsis out of bounds");if(l=r.slice(u,u+y),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error("Ellipsis must be specified in the LHS");for(let w=0;w<l.length;w++){let v=String.fromCharCode(48+w);h.addSymbol(v,m+w),this.addSymbol(v,r[u++],i)}}else h.addSymbol(p,m+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(p,r[u++],i)}),h}},Qn=e=>e+"_max",Su=(e,t,r,i)=>{let a=e.map(h=>h.length).map((h,p)=>U(`input${p}`,t,h)),o=q.size(i),l=te("output",t,i.length),u=[...r.symbolToInfo.keys()].filter(h=>!r.rhs.symbolToIndices.has(h)),c=h=>{let p=[],m="var prod = 1.0;",y="var sum = 0.0;",w="sum += prod;",v=[],x=[],R=[],C=[],$=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((M,L)=>{if(r.rhs.symbolToIndices.has(L)){let V=r.rhs.symbolToIndices.get(L)?.[0];V!==void 0&&r.lhs.forEach((W,X)=>{if(M.inputIndices.includes(X)){let se=W.symbolToIndices.get(L);if(se===void 0)throw new Error("Invalid symbol error");se.forEach(ge=>{p.push(`${a[X].indicesSet(`input${X}Indices`,ge,l.indicesGet("outputIndices",V))}`)})}})}else r.lhs.forEach((V,W)=>{if(M.inputIndices.includes(W)){let X=V.symbolToIndices.get(L);if(X===void 0)throw new Error("Invalid symbol error");X.forEach(se=>{v.push(`${a[W].indicesSet(`input${W}Indices`,se,`${L}`)}`)}),C.push(`prod *= ${a[W].getByIndices(`input${W}Indices`)};`)}}),x.push(`for(var ${L}: u32 = 0; ${L} < uniforms.${Qn(L)}; ${L}++) {`),R.push("}")});let I=$?[...p,`let sum = ${a.map((M,L)=>M.getByIndices(`input${L}Indices`)).join(" * ")};`]:[...p,y,...x,...v,m,...C,w,...R];return`
|
|
1320
|
+
${h.registerUniforms(u.map(M=>({name:`${Qn(M)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...a,l)}
|
|
1321
|
+
|
|
1322
|
+
${h.mainStart()}
|
|
1323
|
+
${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1324
|
+
var outputIndices = ${l.offsetToIndices("global_idx")};
|
|
1325
|
+
${a.map((M,L)=>`var input${L}Indices: ${a[L].type.indices};`).join(`
|
|
1326
|
+
`)}
|
|
1327
|
+
${I.join(`
|
|
1328
|
+
`)};
|
|
1329
|
+
${l.setByOffset("global_idx","sum")};
|
|
1330
|
+
}`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=u.filter(m=>r.symbolToInfo.has(m)).map(m=>({type:12,data:r.symbolToInfo.get(m)?.dimValue||0}));h.push({type:12,data:o});let p=e.map((m,y)=>[...D(m)]).reduce((m,y)=>m.concat(y),h);return p.push(...D(i)),{outputs:[{dims:i,dataType:t}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}},getShaderSource:c}},$u=(e,t)=>{let r=new _u(e.inputs,t.equation),i=r.outputDims,a=e.inputs.map((o,l)=>o.dims);e.compute(Su(a,e.inputs[0].dataType,r,i))},xu=e=>{let t=e.equation.replace(/\s+/g,"");return _({equation:t})}}),Tu,Xn,Cu,Eu,ku,bm=T(()=>{Ee(),xe(),he(),Tu=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),i=r.length<t.length?0:r.length-t.length,a=t.length<r.length?0:t.length-r.length;for(;i<r.length&&a<t.length;++i,++a)if(r[i]!==t[a]&&r[i]!==1&&t[a]!==1)throw new Error("Expand requires shape to be broadcastable to input")},Xn=(e,t)=>{let r=e.length-t.length,i=[];for(let a=0;a<r;++a)i.push(e[a]);for(let a=0;a<t.length;++a)i.push(t[a]===1?e[a+r]:t[a]);return i},Cu=(e,t)=>e.length>t.length?Xn(e,t):Xn(t,e),Eu=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),i=Cu(t,r),a=e[0].dataType,o=a===9||q.size(t)===1,l=a===9||t.length>0&&t[t.length-1]%4===0?4:1,u=o||i.length>0&&i[i.length-1]%4===0?4:1,c=Math.ceil(q.size(i)/u),h=m=>{let y=U("input",a,t.length,l),w=te("output",a,i.length,u),v;if(a===9){let x=(R,C,$="")=>`
|
|
1331
|
+
let outputIndices${C} = ${w.offsetToIndices(`outputOffset + ${C}u`)};
|
|
1332
|
+
let offset${C} = ${y.broadcastedIndicesToOffset(`outputIndices${C}`,w)};
|
|
1333
|
+
let index${C} = offset${C} / 4u;
|
|
1334
|
+
let component${C} = offset${C} % 4u;
|
|
1335
|
+
${R}[${C}] = ${$}(${y.getByOffset(`index${C}`)}[component${C}]);
|
|
1336
|
+
`;v=`
|
|
1337
|
+
let outputOffset = global_idx * ${u};
|
|
1338
|
+
var data = vec4<u32>(0);
|
|
1339
|
+
${x("data",0,"u32")}
|
|
1340
|
+
${x("data",1,"u32")}
|
|
1341
|
+
${x("data",2,"u32")}
|
|
1342
|
+
${x("data",3,"u32")}
|
|
1343
|
+
${w.setByOffset("global_idx","data")}
|
|
1344
|
+
}`}else v=`
|
|
1345
|
+
let outputIndices = ${w.offsetToIndices(`global_idx * ${u}`)};
|
|
1346
|
+
let inputOffset = ${y.broadcastedIndicesToOffset("outputIndices",w)};
|
|
1347
|
+
let data = ${w.type.value}(${y.getByOffset(`inputOffset / ${l}`)});
|
|
1348
|
+
${w.setByOffset("global_idx","data")}
|
|
1349
|
+
}`;return`
|
|
1350
|
+
${m.registerUniform("vec_size","u32").declareVariables(y,w)}
|
|
1351
|
+
${m.mainStart()}
|
|
1352
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
1353
|
+
${v}`},p=[{type:12,data:c},...D(t,i)];return{name:"Expand",shaderCache:{hint:`${i.length};${l}${u}`,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p})}},ku=e=>{Tu(e.inputs),e.compute(Eu(e.inputs),{inputs:[0]})}}),Mu,Ru,_m=T(()=>{Ee(),xe(),he(),An(),Mu=e=>{let t=e[0].dataType,r=q.size(e[0].dims),i=q.size(e[1].dims),a=i%4===0,o=l=>{let u=U("x",t,[1],4),c=U("bias",t,[1],4),h=te("y",t,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],m=w=>`
|
|
1354
|
+
let bias${w}_offset: u32 = (global_idx * 4 + ${w}) % uniforms.bias_size;
|
|
1355
|
+
let bias${w} = ${c.getByOffset(`bias${w}_offset / 4`)}[bias${w}_offset % 4];`,y=a?`
|
|
1356
|
+
let bias = ${c.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${m(0)}${m(1)}${m(2)}${m(3)}
|
|
1357
|
+
let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${l.registerUniforms(p).declareVariables(u,c,h)}
|
|
1358
|
+
|
|
1359
|
+
${Rn(B(t))}
|
|
1360
|
+
|
|
1361
|
+
${l.mainStart(z)}
|
|
1362
|
+
${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}
|
|
1363
|
+
|
|
1364
|
+
let x = ${u.getByOffset("global_idx")};
|
|
1365
|
+
${y}
|
|
1366
|
+
let x_in = x + bias;
|
|
1367
|
+
${h.setByOffset("global_idx",In("x_in"))}
|
|
1368
|
+
}`};return{name:"FastGeluWithBias",shaderCache:{hint:`${a}`,inputDependencies:["type","type"]},getShaderSource:o,getRunData:l=>({outputs:[{dims:l[0].dims,dataType:l[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:i}],dispatchGroup:{x:Math.ceil(r/z/4)}})}},Ru=e=>{e.inputs.length<2||q.size(e.inputs[1].dims)===0?dl(e):e.compute(Mu(e.inputs))}}),Iu,Au,Pu,Ou,Sm=T(()=>{Ee(),xe(),k(),he(),Iu=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Au=(e,t)=>{let r=e[0].dims,i=e[1].dims,a=r.length,o=q.normalizeAxis(t.axis,a),l=r.slice(0);l.splice(o,1,...i);let u=r[o],c=e[0].dataType===9?4:1,h=Math.ceil(q.size(l)/c),p=[{type:12,data:h},{type:6,data:u},{type:12,data:o},...D(e[0].dims,e[1].dims,l)],m=y=>{let w=U("data",e[0].dataType,e[0].dims.length,c),v=U("inputIndices",e[1].dataType,e[1].dims.length),x=te("output",e[0].dataType,l.length,c),R=$=>{let I=i.length,M=`var indicesIndices${$} = ${v.type.indices}(0);`;for(let L=0;L<I;L++)M+=`${I>1?`indicesIndices${$}[${L}]`:`indicesIndices${$}`} = ${l.length>1?`outputIndices${$}[uniforms.axis + ${L}]`:`outputIndices${$}`};`;M+=`
|
|
1369
|
+
var idx${$} = ${v.getByIndices(`indicesIndices${$}`)};
|
|
1370
|
+
if (idx${$} < 0) {
|
|
1371
|
+
idx${$} = idx${$} + uniforms.axisDimLimit;
|
|
1372
|
+
}
|
|
1373
|
+
var dataIndices${$} : ${w.type.indices};
|
|
1374
|
+
`;for(let L=0,V=0;L<a;L++)L===o?(M+=`${a>1?`dataIndices${$}[${L}]`:`dataIndices${$}`} = u32(idx${$});`,V+=I):(M+=`${a>1?`dataIndices${$}[${L}]`:`dataIndices${$}`} = ${l.length>1?`outputIndices${$}[${V}]`:`outputIndices${$}`};`,V++);return M},C;if(e[0].dataType===9){let $=(I,M,L="")=>`
|
|
1375
|
+
let outputIndices${M} = ${x.offsetToIndices(`outputOffset + ${M}u`)};
|
|
1376
|
+
${R(M)};
|
|
1377
|
+
let offset${M} = ${w.indicesToOffset(`dataIndices${M}`)};
|
|
1378
|
+
let index${M} = offset${M} / 4u;
|
|
1379
|
+
let component${M} = offset${M} % 4u;
|
|
1380
|
+
${I}[${M}] = ${L}(${w.getByOffset(`index${M}`)}[component${M}]);
|
|
1381
|
+
`;C=`
|
|
1382
|
+
let outputOffset = global_idx * ${c};
|
|
1383
|
+
var value = vec4<u32>(0);
|
|
1384
|
+
${$("value",0,"u32")}
|
|
1385
|
+
${$("value",1,"u32")}
|
|
1386
|
+
${$("value",2,"u32")}
|
|
1387
|
+
${$("value",3,"u32")}
|
|
1388
|
+
${x.setByOffset("global_idx","value")}
|
|
1389
|
+
`}else C=`
|
|
1390
|
+
let outputIndices = ${x.offsetToIndices("global_idx")};
|
|
1391
|
+
${R("")};
|
|
1392
|
+
let value = ${w.getByIndices("dataIndices")};
|
|
1393
|
+
${x.setByOffset("global_idx","value")};
|
|
1394
|
+
`;return`
|
|
1395
|
+
${y.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(w,v,x)}
|
|
1396
|
+
${y.mainStart()}
|
|
1397
|
+
${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1398
|
+
${C}
|
|
1399
|
+
}`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p}),getShaderSource:m}},Pu=e=>_({axis:e.axis}),Ou=(e,t)=>{let r=e.inputs;Iu(r),e.compute(Au(e.inputs,t))}}),zu,Du,Lu,$m=T(()=>{Ee(),xe(),he(),zu=(e,t,r,i,a,o,l,u,c)=>{let h=[{type:12,data:o},{type:12,data:i},{type:12,data:a},{type:12,data:r},{type:12,data:l},{type:12,data:u},{type:12,data:c}],p=[o];h.push(...D(t.dims,p));let m=y=>{let w=U("indices_data",t.dataType,t.dims.length),v=te("input_slice_offsets_data",12,1,1),x=[w,v],R=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:a.length},{name:"sizes_from_slice_dims_data",type:"u32",length:r.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return`
|
|
1400
|
+
${y.registerUniforms(R).declareVariables(...x)}
|
|
1401
|
+
${y.mainStart()}
|
|
1402
|
+
${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1403
|
+
let batch_idx = global_idx / uniforms.num_slices_per_batch;
|
|
1404
|
+
let base_offset = batch_idx * uniforms.input_batch_stride;
|
|
1405
|
+
|
|
1406
|
+
let slice_indices_base_offset = global_idx * uniforms.num_slice_dims;
|
|
1407
|
+
var relative_slice_offset = 0;
|
|
1408
|
+
for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) {
|
|
1409
|
+
var index = i32(indices_data[dim_idx + slice_indices_base_offset].x);
|
|
1410
|
+
let input_dim_idx = uniforms.batch_dims + dim_idx;
|
|
1411
|
+
if (index < 0) {
|
|
1412
|
+
${a.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"}
|
|
1413
|
+
}
|
|
1414
|
+
${r.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"}
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset);
|
|
1418
|
+
}`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${a.length}_${r.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:h}),getShaderSource:m},{inputs:[t],outputs:[-1]})[0]},Du=(e,t)=>{let r=e.inputs,i=r[0].dims,a=r[0].dataType,o=r[1].dims,l=o[o.length-1],u=q.sizeToDimension(o,o.length-1),c=q.sizeFromDimension(i,t.batchDims+l),h=q.sizeToDimension(i,t.batchDims),p=q.sizeFromDimension(i,t.batchDims),m=u/h,y=new Array(l),w=c;for(let M=0;M<l;++M)y[l-1-M]=w,w*=i[t.batchDims+l-1-M];let v=zu(e,r[1],y,t.batchDims,i,u,m,p,l),x=t.batchDims+l;if(x>i.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let R=o.slice(0,-1).concat(i.slice(x)),C=q.size(R),$=[{type:12,data:C},{type:12,data:c},...D(r[0].dims,v.dims,R)],I=M=>{let L=U("data",r[0].dataType,r[0].dims.length),V=U("slice_offsets",12,v.dims.length),W=te("output",r[0].dataType,R.length);return`
|
|
1419
|
+
${M.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(L,V,W)}
|
|
1420
|
+
${M.mainStart()}
|
|
1421
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1422
|
+
let slice_offset = slice_offsets[global_idx / uniforms.slice_size];
|
|
1423
|
+
output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size];
|
|
1424
|
+
}`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:R,dataType:a}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:$}),getShaderSource:I},{inputs:[r[0],v]})},Lu=e=>({batchDims:e.batch_dims,cacheKey:""})}),Bu,Uu,Fu,Nu,xm=T(()=>{Ee(),xe(),k(),he(),Bu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=q.normalizeAxis(t.quantizeAxis,e[0].dims.length),i=t.blockSize,a=e[0],o=e[2],l=e.length===4?e[3]:void 0;if(o.dims.length!==a.dims.length||!a.dims.map((u,c)=>c===r?Math.ceil(u/i)===o.dims[c]:u===o.dims[c]).reduce((u,c)=>u&&c,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(l){if(l.dataType!==a.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(l.dims.length!==o.dims.length||!l.dims.map((u,c)=>u===o.dims[c]).reduce((u,c)=>u&&c,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Uu=(e,t)=>{let r=e[0].dims,i=e[1].dims,a=r.length,o=q.normalizeAxis(t.gatherAxis,a),l=q.normalizeAxis(t.quantizeAxis,a),u=r.slice(0);u.splice(o,1,...i);let c=q.size(u),h=e[2].dataType,p=e[0].dataType===22,m=[{type:12,data:c},{type:12,data:l},{type:12,data:o},{type:12,data:t.blockSize},...D(...e.map((w,v)=>w.dims),u)],y=w=>{let v=U("data",e[0].dataType,e[0].dims.length),x=U("inputIndices",e[1].dataType,e[1].dims.length),R=U("scales",e[2].dataType,e[2].dims.length),C=e.length>3?U("zeroPoint",e[3].dataType,e[3].dims.length):void 0,$=te("output",h,u.length),I=[v,x,R];C&&I.push(C);let M=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
1425
|
+
${w.registerUniforms(M).declareVariables(...I,$)}
|
|
1426
|
+
${w.mainStart()}
|
|
1427
|
+
let output_indices = ${$.offsetToIndices("global_idx")};
|
|
1428
|
+
var indices_indices = ${x.type.indices}(0);
|
|
1429
|
+
${i.length>1?`
|
|
1430
|
+
for (var i: u32 = 0; i < ${i.length}; i++) {
|
|
1431
|
+
let index = ${$.indicesGet("output_indices","uniforms.gather_axis + i")};
|
|
1432
|
+
${x.indicesSet("indices_indices","i","index")};
|
|
1433
|
+
}`:`indices_indices = ${$.indicesGet("output_indices","uniforms.gather_axis")};`};
|
|
1434
|
+
var data_indices = ${v.type.indices}(0);
|
|
1435
|
+
for (var i: u32 = 0; i < uniforms.gather_axis; i++) {
|
|
1436
|
+
let index = ${$.indicesGet("output_indices","i")};
|
|
1437
|
+
${v.indicesSet("data_indices","i","index")};
|
|
1438
|
+
}
|
|
1439
|
+
var index_from_indices = ${x.getByIndices("indices_indices")};
|
|
1440
|
+
if (index_from_indices < 0) {
|
|
1441
|
+
index_from_indices += ${r[o]};
|
|
1442
|
+
}
|
|
1443
|
+
${v.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")};
|
|
1444
|
+
for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) {
|
|
1445
|
+
let index = ${$.indicesGet("output_indices",`i + ${i.length} - 1`)};
|
|
1446
|
+
${v.indicesSet("data_indices","i","index")};
|
|
1447
|
+
}
|
|
1448
|
+
let data_offset = ${v.indicesToOffset("data_indices")};
|
|
1449
|
+
let data_index = data_offset % 8;
|
|
1450
|
+
// Convert 4-bit packed data to 8-bit packed data.
|
|
1451
|
+
let packed_4bit_quantized_data = ${v.getByOffset("data_offset / 8")};
|
|
1452
|
+
let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;
|
|
1453
|
+
let quantized_data_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data));
|
|
1454
|
+
let quantized_data = quantized_data_vec[data_index / 2];
|
|
1455
|
+
var scale_indices = data_indices;
|
|
1456
|
+
let quantize_axis_index = ${R.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size;
|
|
1457
|
+
${R.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")};
|
|
1458
|
+
var scale = ${R.getByIndices("scale_indices")};
|
|
1459
|
+
${C?`
|
|
1460
|
+
let zero_point_indices = scale_indices;
|
|
1461
|
+
let zero_point_offset = ${C.indicesToOffset("zero_point_indices")};
|
|
1462
|
+
let zero_point_index = zero_point_offset % 8;
|
|
1463
|
+
let packed_4bit_zero_points = ${C.getByOffset("zero_point_offset / 8")};
|
|
1464
|
+
let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;
|
|
1465
|
+
let zero_point_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points));
|
|
1466
|
+
let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};
|
|
1467
|
+
let dequantized_data = ${B(h)}(quantized_data - zero_point) * scale;
|
|
1468
|
+
${$.setByOffset("global_idx","dequantized_data")};
|
|
1469
|
+
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((w,v)=>v!==1).map(w=>w.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(w,v)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:h}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:m}),getShaderSource:y}},Fu=(e,t)=>{let r=e.inputs;Bu(r,t),e.compute(Uu(e.inputs,t))},Nu=e=>_({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Vu,Gu,Wu,qu,Tm=T(()=>{Ee(),xe(),k(),he(),Vu=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and
|
|
1470
|
+
indices input tensors be of same rank.`)},Gu=(e,t)=>{let r=e[0].dims,i=e[0].dataType,a=r.length,o=e[1].dims,l=e[1].dataType,u=q.normalizeAxis(t.axis,a),c=r[u],h=o.slice(0),p=q.size(h),m=U("input",i,a),y=U("indicesInput",l,o.length),w=te("output",i,h.length),v=[{type:12,data:p},{type:6,data:c},{type:12,data:u}];return v.push(...D(r,o,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:v}),getShaderSource:x=>`
|
|
1471
|
+
${x.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(m,y,w)}
|
|
1472
|
+
${x.mainStart()}
|
|
1473
|
+
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1474
|
+
|
|
1475
|
+
let outputIndices = ${w.offsetToIndices("global_idx")};
|
|
1476
|
+
|
|
1477
|
+
var idx = ${y.getByOffset("global_idx")};
|
|
1478
|
+
if (idx < 0) {
|
|
1479
|
+
idx = idx + uniforms.axisDimLimit;
|
|
1480
|
+
}
|
|
1481
|
+
var inputIndices = ${m.type.indices}(outputIndices);
|
|
1482
|
+
${m.indicesSet("inputIndices","uniforms.axis","u32(idx)")};
|
|
1483
|
+
let value = ${m.getByIndices("inputIndices")};
|
|
1484
|
+
|
|
1485
|
+
${w.setByOffset("global_idx","value")};
|
|
1486
|
+
}`}},Wu=e=>_({axis:e.axis}),qu=(e,t)=>{let r=e.inputs;Vu(r),e.compute(Gu(e.inputs,t))}}),Hu,ju,Ku,Qu,Cm=T(()=>{Ee(),xe(),he(),Hu=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},ju=(e,t)=>{let r=e[0].dims.slice(),i=e[1].dims.slice(),[a,o,l]=Ss.getShapeOfGemmResult(r,t.transA,i,t.transB,e.length===3?e[2].dims:void 0),u=[a,o];if(!u)throw new Error("Can't use gemm on the given tensors");let c=16,h=Math.ceil(o/c),p=Math.ceil(a/c);q.size(u);let m=[{type:12,data:h},{type:12,data:a},{type:12,data:o},{type:12,data:l},{type:1,data:t.alpha},{type:1,data:t.beta}],y=["type","type"];e.length===3&&(m.push(...D(e[2].dims)),y.push("rank")),m.push(...D(u));let w=v=>{let x=U("a",e[0].dataType,e[0].dims),R=U("b",e[1].dataType,e[1].dims),C=null,$=[x,R];e.length===3&&(C=U("c",e[2].dataType,e[2].dims.length),$.push(C));let I=te("output",e[0].dataType,u.length);$.push(I);let M=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],L="",V="";t.transA&&t.transB?(V=`
|
|
1487
|
+
var col = tile_row_start + local_id.x;
|
|
1488
|
+
var row = k_start + local_id.y;
|
|
1489
|
+
if (col < uniforms.M && row < uniforms.K) {
|
|
1490
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
|
|
1491
|
+
} else {
|
|
1492
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
col = k_start + local_id.x;
|
|
1496
|
+
row = tile_col_start + local_id.y;
|
|
1497
|
+
if (col < uniforms.K && row < uniforms.N) {
|
|
1498
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
|
|
1499
|
+
} else {
|
|
1500
|
+
tile_b[local_id.y][local_id.x] = ${R.type.value}(0);
|
|
1501
|
+
}
|
|
1502
|
+
`,L="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(V=`
|
|
1503
|
+
var col = tile_row_start + local_id.x;
|
|
1504
|
+
var row = k_start + local_id.y;
|
|
1505
|
+
if (col < uniforms.M && row < uniforms.K) {
|
|
1506
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
|
|
1507
|
+
} else {
|
|
1508
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
col = tile_col_start + local_id.x;
|
|
1512
|
+
row = k_start + local_id.y;
|
|
1513
|
+
if (col < uniforms.N && row < uniforms.K) {
|
|
1514
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
|
|
1515
|
+
} else {
|
|
1516
|
+
tile_b[local_id.y][local_id.x] = ${R.type.value}(0);
|
|
1517
|
+
}
|
|
1518
|
+
`,L="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(V=`
|
|
1519
|
+
var col = k_start + local_id.x;
|
|
1520
|
+
var row = tile_row_start + local_id.y;
|
|
1521
|
+
if (col < uniforms.K && row < uniforms.M) {
|
|
1522
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
|
|
1523
|
+
} else {
|
|
1524
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
col = k_start + local_id.x;
|
|
1528
|
+
row = tile_col_start + local_id.y;
|
|
1529
|
+
if (col < uniforms.K && row < uniforms.N) {
|
|
1530
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
|
|
1531
|
+
} else {
|
|
1532
|
+
tile_b[local_id.y][local_id.x] = ${R.type.value}(0);
|
|
1533
|
+
}
|
|
1534
|
+
`,L="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(V=`
|
|
1535
|
+
var col = k_start + local_id.x;
|
|
1536
|
+
var row = tile_row_start + local_id.y;
|
|
1537
|
+
if (col < uniforms.K && row < uniforms.M) {
|
|
1538
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
|
|
1539
|
+
} else {
|
|
1540
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
col = tile_col_start + local_id.x;
|
|
1544
|
+
row = k_start + local_id.y;
|
|
1545
|
+
if (col < uniforms.N && row < uniforms.K) {
|
|
1546
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
|
|
1547
|
+
} else {
|
|
1548
|
+
tile_b[local_id.y][local_id.x] = ${R.type.value}(0);
|
|
1549
|
+
}
|
|
1550
|
+
`,L="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let W=t.alpha===1?"":"value *= uniforms.alpha;";return`
|
|
1551
|
+
${v.registerUniforms(M).declareVariables(...$)}
|
|
1552
|
+
var<workgroup> tile_a: array<array<${x.type.storage}, ${c}>, ${c}>;
|
|
1553
|
+
var<workgroup> tile_b: array<array<${R.type.storage}, ${c}>, ${c}>;
|
|
1554
|
+
${v.mainStart([c,c,1])}
|
|
1555
|
+
let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${c};
|
|
1556
|
+
let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${c};
|
|
1557
|
+
let num_tiles = (uniforms.K - 1) / ${c} + 1;
|
|
1558
|
+
var k_start = 0u;
|
|
1559
|
+
var value = ${I.type.value}(0);
|
|
1560
|
+
for (var t: u32 = 0u; t < num_tiles; t++) {
|
|
1561
|
+
${V}
|
|
1562
|
+
k_start = k_start + ${c};
|
|
1563
|
+
workgroupBarrier();
|
|
1564
|
+
|
|
1565
|
+
for (var k: u32 = 0u; k < ${c}; k++) {
|
|
1566
|
+
${L}
|
|
1567
|
+
}
|
|
1568
|
+
workgroupBarrier();
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
${W}
|
|
1572
|
+
let m = tile_row_start + local_id.y;
|
|
1573
|
+
let n = tile_col_start + local_id.x;
|
|
1574
|
+
${C!=null?`let cOffset = ${C.broadcastedIndicesToOffset("vec2(m, n)",I)}; value += ${I.type.value}(uniforms.beta) * ${C.getByOffset("cOffset")};`:""}
|
|
1575
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
1576
|
+
output[m * uniforms.N + n] = value;
|
|
1577
|
+
}
|
|
1578
|
+
}`};return{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:h*p},programUniforms:m}),getShaderSource:w}},Ku=e=>{let t=e.transA,r=e.transB,i=e.alpha,a=e.beta;return{transA:t,transB:r,alpha:i,beta:a,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Qu=(e,t)=>{Hu(e.inputs),e.compute(ju(e.inputs,t))}}),hr,vr,ds,cs,Xu,Zu,Ju,Yu,ed,td,rd,sd,id,nd,Em=T(()=>{Ee(),xe(),k(),he(),[hr,vr,ds,cs]=[0,1,2,3],Xu=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},Zu=`
|
|
1579
|
+
fn gs_get_cubic_coeffs(x: f32) -> vec4<f32> {
|
|
1580
|
+
let cubic_alpha = -0.75f;
|
|
1581
|
+
let x_abs = abs(x);
|
|
1582
|
+
var coeffs: vec4<f32>;
|
|
1583
|
+
coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);
|
|
1584
|
+
coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);
|
|
1585
|
+
coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);
|
|
1586
|
+
coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);
|
|
1587
|
+
return coeffs;
|
|
1588
|
+
}
|
|
1589
|
+
`,Ju=e=>`
|
|
1590
|
+
fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {
|
|
1591
|
+
var v: vec4<f32>;
|
|
1592
|
+
var coeffs = gs_get_cubic_coeffs(x);
|
|
1593
|
+
for (var i = 0; i < 4; i++) {
|
|
1594
|
+
v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];
|
|
1595
|
+
}
|
|
1596
|
+
coeffs = gs_get_cubic_coeffs(y);
|
|
1597
|
+
let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);
|
|
1598
|
+
return pixel;
|
|
1599
|
+
}
|
|
1600
|
+
`,Yu=e=>`
|
|
1601
|
+
fn gs_denormalize(n: f32, length: i32) -> f32 {
|
|
1602
|
+
${e.alignCorners===0?`
|
|
1603
|
+
// alignCorners: false => [-1, 1] to [-0.5, length - 0.5]
|
|
1604
|
+
return ((n + 1.0) * f32(length) - 1.0) / 2.0;
|
|
1605
|
+
`:`
|
|
1606
|
+
// alignCorners: true => [-1, 1] to [0, length - 1]
|
|
1607
|
+
return (n + 1.0) / 2.0 * (f32(length - 1));
|
|
1608
|
+
`}
|
|
1609
|
+
}
|
|
1610
|
+
`,ed=e=>`
|
|
1611
|
+
${e.paddingMode==="reflection"?`
|
|
1612
|
+
fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {
|
|
1613
|
+
var dx = 0.0;
|
|
1614
|
+
var fx = f32(x);
|
|
1615
|
+
let range = x_max - x_min;
|
|
1616
|
+
if (fx < x_min) {
|
|
1617
|
+
dx = x_min - fx;
|
|
1618
|
+
let n = u32(dx / range);
|
|
1619
|
+
let r = dx - f32(n) * range;
|
|
1620
|
+
if (n % 2 == 0) {
|
|
1621
|
+
fx = x_min + r;
|
|
1622
|
+
} else {
|
|
1623
|
+
fx = x_max - r;
|
|
1624
|
+
}
|
|
1625
|
+
} else if (fx > x_max) {
|
|
1626
|
+
dx = fx - x_max;
|
|
1627
|
+
let n = u32(dx / range);
|
|
1628
|
+
let r = dx - f32(n) * range;
|
|
1629
|
+
if (n % 2 == 0) {
|
|
1630
|
+
fx = x_max - r;
|
|
1631
|
+
} else {
|
|
1632
|
+
fx = x_min + r;
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
return u32(fx);
|
|
1636
|
+
}`:""}
|
|
1637
|
+
`,td=(e,t,r)=>`
|
|
1638
|
+
fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4<f32>) -> ${t} {
|
|
1639
|
+
var pixel = ${t}(0);
|
|
1640
|
+
var indices = vec4<u32>(0);
|
|
1641
|
+
indices[${hr}] = batch;
|
|
1642
|
+
indices[${vr}] = channel;`+(()=>{switch(r.paddingMode){case"zeros":return`
|
|
1643
|
+
if (r >= 0 && r < H && c >=0 && c < W) {
|
|
1644
|
+
indices[${ds}] = u32(r);
|
|
1645
|
+
indices[${cs}] = u32(c);
|
|
1646
|
+
} else {
|
|
1647
|
+
return ${t}(0);
|
|
1648
|
+
}
|
|
1649
|
+
`;case"border":return`
|
|
1650
|
+
indices[${ds}] = u32(clamp(r, 0, H - 1));
|
|
1651
|
+
indices[${cs}] = u32(clamp(c, 0, W - 1));
|
|
1652
|
+
`;case"reflection":return`
|
|
1653
|
+
indices[${ds}] = gs_reflect(r, border[1], border[3]);
|
|
1654
|
+
indices[${cs}] = gs_reflect(c, border[0], border[2]);
|
|
1655
|
+
`;default:throw new Error(`padding mode ${r.paddingMode} is not supported`)}})()+`
|
|
1656
|
+
return ${e.getByIndices("indices")};
|
|
1657
|
+
}
|
|
1658
|
+
`,rd=(e,t,r)=>(()=>{switch(r.mode){case"nearest":return`
|
|
1659
|
+
let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${hr}], indices[${vr}], border);
|
|
1660
|
+
`;case"bilinear":return`
|
|
1661
|
+
let x1 = i32(floor(x));
|
|
1662
|
+
let y1 = i32(floor(y));
|
|
1663
|
+
let x2 = x1 + 1;
|
|
1664
|
+
let y2 = y1 + 1;
|
|
1665
|
+
|
|
1666
|
+
let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${hr}], indices[${vr}], border);
|
|
1667
|
+
let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${hr}], indices[${vr}], border);
|
|
1668
|
+
let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${hr}], indices[${vr}], border);
|
|
1669
|
+
let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${hr}], indices[${vr}], border);
|
|
1670
|
+
|
|
1671
|
+
let dx2 = ${t}(f32(x2) - x);
|
|
1672
|
+
let dx1 = ${t}(x - f32(x1));
|
|
1673
|
+
let dy2 = ${t}(f32(y2) - y);
|
|
1674
|
+
let dy1 = ${t}(y - f32(y1));
|
|
1675
|
+
let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);
|
|
1676
|
+
`;case"bicubic":return`
|
|
1677
|
+
let x0 = i32(floor(x)) - 1;
|
|
1678
|
+
let y0 = i32(floor(y)) - 1;
|
|
1679
|
+
var p: mat4x4<${t}>;
|
|
1680
|
+
for (var h = 0; h < 4; h++) {
|
|
1681
|
+
for (var w = 0; w < 4; w++) {
|
|
1682
|
+
p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${hr}], indices[${vr}], border);
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
let dx = x - f32(x0 + 1);
|
|
1687
|
+
let dy = y - f32(y0 + 1);
|
|
1688
|
+
let result = gs_bicubic_interpolate(p, dx, dy);
|
|
1689
|
+
`;default:throw new Error(`mode ${r.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,sd=(e,t)=>{let r=U("x",e[0].dataType,e[0].dims.length),i=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],a=U("grid",e[1].dataType,i.length,2),o=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(o=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[hr,vr,ds,cs]=[0,3,1,2]);let l=te("output",e[0].dataType,o.length),u=r.type.value,c=q.size(o),h=[{type:12,data:c},...D(e[0].dims,i,o)],p=m=>`
|
|
1690
|
+
${m.registerUniform("output_size","u32").declareVariables(r,a,l)}
|
|
1691
|
+
${Zu}
|
|
1692
|
+
${Ju(u)}
|
|
1693
|
+
${Yu(t)}
|
|
1694
|
+
${ed(t)}
|
|
1695
|
+
${td(r,u,t)}
|
|
1696
|
+
|
|
1697
|
+
${m.mainStart()}
|
|
1698
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1699
|
+
let H_in = i32(uniforms.x_shape[${ds}]);
|
|
1700
|
+
let W_in = i32(uniforms.x_shape[${cs}]);
|
|
1701
|
+
|
|
1702
|
+
${t.alignCorners===0?`
|
|
1703
|
+
let x_min = -0.5;
|
|
1704
|
+
let x_max = f32(W_in) - 0.5;
|
|
1705
|
+
let y_min = -0.5;
|
|
1706
|
+
let y_max = f32(H_in) - 0.5;
|
|
1707
|
+
`:`
|
|
1708
|
+
let x_min = 0.0;
|
|
1709
|
+
let x_max = f32(W_in) - 1.0;
|
|
1710
|
+
let y_min = 0.0;
|
|
1711
|
+
let y_max = f32(H_in) - 1.0;
|
|
1712
|
+
`};
|
|
1713
|
+
let border = vec4<f32>(x_min, y_min, x_max, y_max);
|
|
1714
|
+
|
|
1715
|
+
let indices = ${l.offsetToIndices("global_idx")};
|
|
1716
|
+
var grid_indices = vec3<u32>(indices[${hr}], indices[${ds}], indices[${cs}]);
|
|
1717
|
+
let nxy = ${a.getByIndices("grid_indices")};
|
|
1718
|
+
var x = gs_denormalize(f32(nxy[0]), W_in);
|
|
1719
|
+
var y = gs_denormalize(f32(nxy[1]), H_in);
|
|
1720
|
+
|
|
1721
|
+
${rd(l,u,t)}
|
|
1722
|
+
}`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:m=>{let y=q.size(o);return{outputs:[{dims:o,dataType:m[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:h}},getShaderSource:p}},id=(e,t)=>{Xu(e.inputs),e.compute(sd(e.inputs,t))},nd=e=>_({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),At,ad,od,Zn,ld,Ei,ud,dd=T(()=>{Ee(),xe(),k(),Cs(),kn(),he(),Le(),At=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,ad=(e,t)=>{let r=e[0],i=At(e,1),a=At(e,2),o=At(e,3),l=At(e,4),u=At(e,5),c=At(e,6),h=At(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let p=r.dims[0],m=r.dims[1],y=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],w=m,v=0,x=0,R=Math.floor(y/t.numHeads);if(c&&h&&q.size(c.dims)&&q.size(h.dims)){if(c.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(c.dims[0]!==p||c.dims[1]!==t.numHeads||c.dims[3]!==R)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==p||h.dims[1]!==t.numHeads||h.dims[3]!==R)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[2]!==h.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(h.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');v=c.dims[2],x=c.dims[2]}else if(c&&q.size(c.dims)||h&&q.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let C;if(i&&q.size(i.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(i.dims.length<3||i.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(i.dims.length===3){if(i.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');C=2,w=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==R)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(a)throw new Error('Expect "value" be none when "key" has packed kv format.');C=5,w=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==R)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');C=0,w=i.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');C=3}if(o&&q.size(o.dims)>0){if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(i&&i.dims.length===5&&i.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let $=v+w,I=0;if(l&&q.size(l.dims)>0){I=8;let W=l.dims;throw W.length===1?W[0]===p?I=1:W[0]===3*p+2&&(I=3):W.length===2&&W[0]===p&&W[1]===$&&(I=5),I===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let M=!1,L=y;if(a&&q.size(a.dims)>0){if(a.dims.length!==3&&a.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==a.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(a.dims.length===3){if(w!==a.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');L=a.dims[2]}else{if(w!==a.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');L=a.dims[1]*a.dims[3],M=!0}}let V=!1;if(l&&q.size(l.dims)>0)throw new Error("Key padding mask is not supported");if(u&&q.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==p||u.dims[1]!==t.numHeads||u.dims[2]!==m||u.dims[3]!==$)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:m,pastSequenceLength:v,kvSequenceLength:w,totalSequenceLength:$,maxSequenceLength:x,inputHiddenSize:0,hiddenSize:y,vHiddenSize:L,headSize:R,vHeadSize:Math.floor(L/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:I,scale:t.scale,broadcastResPosBias:V,passPastInKv:M,qkvFormat:C}},od=e=>_({...e}),Zn=_({perm:[0,2,1,3]}),ld=(e,t,r,i,a,o,l)=>{let u=[i,a,o],c=q.size(u),h=[{type:12,data:c},{type:12,data:l},{type:12,data:o}],p=m=>{let y=te("qkv_with_bias",t.dataType,u),w=U("qkv",t.dataType,u),v=U("bias",r.dataType,u),x=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`
|
|
1723
|
+
${m.registerUniforms(x).declareVariables(w,v,y)}
|
|
1724
|
+
${m.mainStart()}
|
|
1725
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1726
|
+
let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
|
|
1727
|
+
|
|
1728
|
+
qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];
|
|
1729
|
+
}`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:h}),getShaderSource:p},{inputs:[t,r],outputs:[-1]})[0]},Ei=(e,t,r,i,a,o,l,u)=>{let c=o;if(l&&q.size(l.dims)>0){if(i===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return c=ld(e,o,l,t,i,r*a,u),c=c.reshape([t,i,r,a]),r===1||i===1?c:e.compute(it(c,Zn.perm),{inputs:[c],outputs:[-1]})[0]}else return o.dims.length===3&&(c=o.reshape([t,i,r,a])),r===1||i===1?c:e.compute(it(c,Zn.perm),{inputs:[c],outputs:[-1]})[0]},ud=(e,t)=>{let r=ad(e.inputs,t),i=e.inputs[0],a=At(e.inputs,1),o=At(e.inputs,2),l=At(e.inputs,3),u=At(e.inputs,4),c=At(e.inputs,5),h=At(e.inputs,6),p=At(e.inputs,7);if(i.dims.length===5)throw new Error("Packed QKV is not implemented");if(a?.dims.length===5)throw new Error("Packed KV is not implemented");let m=a&&o&&a.dims.length===4&&o.dims.length===4,y=Ei(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,i,l,0);if(m)return Si(e,y,a,o,u,void 0,h,p,c,r);if(!a||!o)throw new Error("key and value must be provided");let w=Ei(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,a,l,r.hiddenSize),v=Ei(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,o,l,2*r.hiddenSize);Si(e,y,w,v,u,void 0,h,p,c,r)}}),cd,hd,pd,md,Jn,fd,gd,yd=T(()=>{Ee(),xe(),k(),he(),cd=e=>{if(!e||e.length<1)throw new Error("too few inputs")},hd=(e,t)=>{let r=[],i=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(a=>r.push(Number(a))),i=r.length),_({numOutputs:i,axis:t.axis,splitSizes:r})},pd=e=>`
|
|
1730
|
+
fn calculateOutputIndex(index: u32) -> u32 {
|
|
1731
|
+
for (var i: u32 = 0u; i < ${e}u; i += 1u ) {
|
|
1732
|
+
if (index < ${H("uniforms.size_in_split_axis","i",e)}) {
|
|
1733
|
+
return i;
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
return ${e}u;
|
|
1737
|
+
}`,md=e=>{let t=e.length,r=[];for(let i=0;i<t;++i){let a=e[i].setByIndices("indices","input[global_idx]");t===1?r.push(a):i===0?r.push(`if (output_number == ${i}u) { ${a} }`):i===t-1?r.push(`else { ${a} }`):r.push(`else if (output_number == ${i}) { ${a} }`)}return`
|
|
1738
|
+
fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) {
|
|
1739
|
+
${r.join(`
|
|
1740
|
+
`)}
|
|
1741
|
+
}`},Jn=(e,t)=>{let r=e[0].dims,i=q.size(r),a=e[0].dataType,o=q.normalizeAxis(t.axis,r.length),l=new Array(t.numOutputs),u=U("input",a,r.length),c=new Array(t.numOutputs),h=[],p=[],m=0,y=[{type:12,data:i}];for(let v=0;v<t.numOutputs;v++){m+=t.splitSizes[v],c[v]=m;let x=r.slice();x[o]=t.splitSizes[v],p.push(x),l[v]=te(`output${v}`,a,x.length),h.push({dims:p[v],dataType:e[0].dataType})}y.push({type:12,data:c},...D(r,...p));let w=v=>`
|
|
1742
|
+
${v.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",c.length).declareVariables(u,...l)}
|
|
1743
|
+
${pd(c.length)}
|
|
1744
|
+
${md(l)}
|
|
1745
|
+
|
|
1746
|
+
${v.mainStart()}
|
|
1747
|
+
${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}
|
|
1748
|
+
|
|
1749
|
+
var indices = ${u.offsetToIndices("global_idx")};
|
|
1750
|
+
var index = ${u.indicesGet("indices",o)};
|
|
1751
|
+
let output_number = calculateOutputIndex(index);
|
|
1752
|
+
if (output_number != 0) {
|
|
1753
|
+
index -= ${H("uniforms.size_in_split_axis","output_number - 1u",c.length)};
|
|
1754
|
+
${u.indicesSet("indices",o,"index")};
|
|
1755
|
+
}
|
|
1756
|
+
writeBufferData(output_number, indices, global_idx);
|
|
1757
|
+
}`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(i/64)},programUniforms:y})}},fd=(e,t)=>{cd(e.inputs);let r=e.inputs.length===1?t:hd(e.inputs,t);e.compute(Jn(e.inputs,r),{inputs:[0]})},gd=e=>{let t=e.axis,r=e.splitSizes,i=e.numOutputs<0?r.length:e.numOutputs;if(i!==r.length)throw new Error("numOutputs and splitSizes length must be equal");return _({axis:t,numOutputs:i,splitSizes:r})}}),wd,tn,vd,bd=T(()=>{Ee(),xe(),k(),he(),wd=(e,t)=>{let[r,i,a,o]=e,{numHeads:l,rotaryEmbeddingDim:u}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!q.areEqual(i.dims,[])&&!q.areEqual(i.dims,[1])&&i.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${i.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(!q.areEqual(a.dims,o.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&l===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let c=r.dims[0],h=r.dims[r.dims.length-2],p=a.dims[0],m=q.sizeFromDimension(r.dims,1)/h,y=u===0?a.dims[1]*2:m/l;if(u>y)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(i.dims.length===2){if(c!==i.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${i.dims[0]}`);if(h!==i.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${i.dims[1]}`)}if(h>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported");if(y/2!==a.dims[1]&&u/2!==a.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${a.dims[1]}`)},tn=(e,t)=>{let{interleaved:r,numHeads:i,rotaryEmbeddingDim:a,scale:o}=t,l=e[0].dims[0],u=q.sizeFromDimension(e[0].dims,1),c=e[0].dims[e[0].dims.length-2],h=u/c,p=e[2].dims[1],m=a===0?p*2:h/i,y=new Array(l,c,h/m,m-p),w=q.computeStrides(y),v=[{type:1,data:o},{type:12,data:y},{type:12,data:w},...e[0].dims.length===3?new Array({type:12,data:[u,h,m,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,m,c*m,1]}):[],...D(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],x=R=>{let C=U("input",e[0].dataType,e[0].dims.length),$=U("position_ids",e[1].dataType,e[1].dims.length),I=U("cos_cache",e[2].dataType,e[2].dims.length),M=U("sin_cache",e[3].dataType,e[3].dims.length),L=te("output",e[0].dataType,e[0].dims.length);return R.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:y.length},{name:"global_strides",type:"u32",length:w.length},{name:"input_output_strides",type:"u32",length:w.length}]),`
|
|
1758
|
+
${R.declareVariables(C,$,I,M,L)}
|
|
1759
|
+
|
|
1760
|
+
${R.mainStart(z)}
|
|
1761
|
+
let half_rotary_emb_dim = uniforms.${I.name}_shape[1];
|
|
1762
|
+
let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;
|
|
1763
|
+
let size = uniforms.global_shape[0] * uniforms.global_strides[0];
|
|
1764
|
+
${R.guardAgainstOutOfBoundsWorkgroupSizes("size")}
|
|
1765
|
+
|
|
1766
|
+
if (bsnh[3] < half_rotary_emb_dim) {
|
|
1767
|
+
let position_ids_idx =
|
|
1768
|
+
${$.broadcastedIndicesToOffset("bsnh.xy",te("",$.type.tensor,2))};
|
|
1769
|
+
let position_id =
|
|
1770
|
+
u32(${$.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);
|
|
1771
|
+
let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r});
|
|
1772
|
+
let j = i + select(half_rotary_emb_dim, 1, ${r});
|
|
1773
|
+
let re = ${C.getByOffset("i")} * ${I.get("position_id","bsnh[3]")} -
|
|
1774
|
+
${C.getByOffset("j")} * ${M.get("position_id","bsnh[3]")};
|
|
1775
|
+
${L.setByOffset("i","re")}
|
|
1776
|
+
let im = ${C.getByOffset("i")} * ${M.get("position_id","bsnh[3]")} +
|
|
1777
|
+
${C.getByOffset("j")} * ${I.get("position_id","bsnh[3]")};
|
|
1778
|
+
${L.setByOffset("j","im")}
|
|
1779
|
+
} else {
|
|
1780
|
+
let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
|
|
1781
|
+
${L.setByOffset("k",C.getByOffset("k"))}
|
|
1782
|
+
}
|
|
1783
|
+
}`};return{name:"RotaryEmbedding",shaderCache:{hint:_({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(q.size(y)/z)},programUniforms:v})}},vd=(e,t)=>{wd(e.inputs,t),e.compute(tn(e.inputs,t))}}),_d,Sd,Yn,$d,xd,km=T(()=>{k(),Ee(),kn(),dd(),yd(),Le(),bd(),he(),_d=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let r=e[0],i=e[1],a=e[2],o=e[3],l=e[4];if(t.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=r.dims[0],c=r.dims[1],h=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],p=c,m=0,y=!i||i.dims.length===0,w=Math.floor(y?h/(t.numHeads+2*t.kvNumHeads):h/t.numHeads);y&&(h=w*t.numHeads);let v=o&&o.dims.length!==0,x=l&&l.dims.length!==0;if(v&&o.dims.length===4&&o.dims[0]===u&&o.dims[1]!==t.kvNumHeads&&o.dims[2]===t.kvNumHeads&&o.dims[3]===w)throw new Error("BSNH pastKey/pastValue is not supported");if(v&&x){if(o.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');m=o.dims[2]}else if(v||x)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let R=1;if(i&&i.dims.length>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(i.dims.length<3||i.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(i.dims.length===3){if(r.dims[2]%i.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');p=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==w)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(a)throw new Error('Expect "value" be none when "key" has packed kv format.');p=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==w)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');p=i.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');R=3}let C=0,$=!1,I=t.kvNumHeads?w*t.kvNumHeads:h;if(a&&a.dims.length>0){if(a.dims.length!==3&&a.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==a.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(a.dims.length===3){if(p!==a.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');I=a.dims[2]}else{if(p!==a.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');I=a.dims[1]*a.dims[3],$=!0}}let M=e.length>4?e[5]:void 0;if(M){if(M.dims.length===0)throw new Error("seqlens_k must be at least 1D, got scalar.");let L=M.dims.reduce((V,W)=>V*W,1);if(L!==u)throw new Error(`seqlens_k must have batch_size (${u}) elements, got ${L}.`);for(let V=0;V<M.dims.length;V++)if(M.dims[V]!==1&&M.dims[V]!==u)throw new Error(`seqlens_k has unexpected shape. Each dimension must be 1 or batch_size (${u}), got dims[${V}] = ${M.dims[V]}.`)}return{batchSize:u,sequenceLength:c,pastSequenceLength:m,kvSequenceLength:p,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:h,vHiddenSize:I,headSize:w,vHeadSize:Math.floor(I/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:C,scale:t.scale,broadcastResPosBias:!1,passPastInKv:$,qkvFormat:R}},Sd=_({perm:[0,2,1,3]}),Yn=(e,t,r)=>{let i=t,a=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(i=t.reshape([r.batchSize,r.kvSequenceLength,a,r.headSize]),i=e.compute(it(i,Sd.perm),{inputs:[i],outputs:[-1]})[0]),i},$d=(e,t,r,i)=>{let a=7,o=["type","type"],l=[e*t],u=e*t,c=[{type:12,data:u},{type:12,data:t},{type:12,data:e}],h=p=>{let m=U("seq_lens",r.dataType,r.dims),y=U("total_seq_lens",i.dataType,i.dims),w=te("pos_ids",a,l),v=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return`
|
|
1784
|
+
${p.registerUniforms(v).declareVariables(m,y,w)}
|
|
1785
|
+
${p.mainStart()}
|
|
1786
|
+
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1787
|
+
let total_sequence_length = u32(${y.getByOffset("0")});
|
|
1788
|
+
let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length;
|
|
1789
|
+
let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length;
|
|
1790
|
+
let batch_idx = global_idx / uniforms.sequence_length;
|
|
1791
|
+
let sequence_idx = i32(global_idx % uniforms.sequence_length);
|
|
1792
|
+
var pos_id: i32 = 0;
|
|
1793
|
+
let seqlen = ${m.getByOffset("batch_idx")};
|
|
1794
|
+
let total_seqlen = seqlen + 1;
|
|
1795
|
+
if (is_first_prompt) {
|
|
1796
|
+
if (sequence_idx < total_seqlen) {
|
|
1797
|
+
pos_id = sequence_idx;
|
|
1798
|
+
} else {
|
|
1799
|
+
pos_id = 1;
|
|
1800
|
+
}
|
|
1801
|
+
${w.setByOffset("global_idx","pos_id")}
|
|
1802
|
+
} else if (is_subsequent_prompt) {
|
|
1803
|
+
let past_seqlen = total_seqlen - i32(uniforms.sequence_length);
|
|
1804
|
+
if (past_seqlen + sequence_idx < total_seqlen) {
|
|
1805
|
+
pos_id = past_seqlen + sequence_idx;
|
|
1806
|
+
} else {
|
|
1807
|
+
pos_id = 1;
|
|
1808
|
+
}
|
|
1809
|
+
${w.setByOffset("global_idx","pos_id")}
|
|
1810
|
+
} else if (global_idx < uniforms.batch_size) {
|
|
1811
|
+
${w.setByOffset("global_idx","seqlen")}
|
|
1812
|
+
};
|
|
1813
|
+
}
|
|
1814
|
+
`};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:o},getRunData:()=>({outputs:[{dims:l,dataType:a}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}),getShaderSource:h}},xd=(e,t)=>{let r=_d(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let i=e.inputs[0],a=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,o=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,l=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,u=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,c=e.inputs.length>4?e.inputs[5]:void 0,h=e.inputs.length>5?e.inputs[6]:void 0,p=r.kvNumHeads?r.kvNumHeads:r.numHeads,m=_({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,p*r.headSize,p*r.headSize]}),[y,w,v]=!a&&!o?e.compute(Jn([i],m),{inputs:[i],outputs:[-1,-1,-1]}):[i,a,o],x,R;if(t.doRotary){let M=e.compute($d(r.batchSize,r.sequenceLength,c,h),{inputs:[c,h],outputs:[-1]})[0],L=e.inputs[7],V=e.inputs[8],W=_({interleaved:t.rotaryInterleaved!==0,numHeads:r.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),X=[y,M,L,V],se=[-1];x=e.compute(tn(X,W),{inputs:X,outputs:se})[0],X.splice(0,1,w);let ge=_({interleaved:t.rotaryInterleaved!==0,numHeads:r.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});R=e.compute(tn(X,ge),{inputs:X,outputs:se})[0]}let C=Ei(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,t.doRotary?x:y,void 0,0),$=Yn(e,t.doRotary?R:w,r),I=Yn(e,v,r);Si(e,C,$,I,void 0,void 0,l,u,void 0,r,c,h)}}),ea,Td,Cd,Ed,Mm=T(()=>{Ee(),xe(),Le(),he(),ea=(e,t,r,i,a,o,l,u)=>{let c=F(o),h=c===1?"f32":`vec${c}f`,p=c===1?"vec2f":`mat2x${c}f`,m=a*l,y=64;m===1&&(y=256);let w=[a,l,o/c],v=[a,l,2],x=["rank","type","type"],R=[];R.push(...D(w,v));let C=$=>{let I=U("x",t.dataType,3,c),M=U("scale",r.dataType,r.dims),L=U("bias",i.dataType,i.dims),V=te("output",1,3,2),W=[I,M,L,V];return`
|
|
1815
|
+
var<workgroup> workgroup_shared : array<${p}, ${y}>;
|
|
1816
|
+
const workgroup_size = ${y}u;
|
|
1817
|
+
${$.declareVariables(...W)}
|
|
1818
|
+
${$.mainStart(y)}
|
|
1819
|
+
let batch = workgroup_index / uniforms.x_shape[1];
|
|
1820
|
+
let channel = workgroup_index % uniforms.x_shape[1];
|
|
1821
|
+
let hight = uniforms.x_shape[2];
|
|
1822
|
+
// initialize workgroup memory
|
|
1823
|
+
var sum = ${h}(0);
|
|
1824
|
+
var squared_sum = ${h}(0);
|
|
1825
|
+
for (var h = local_idx; h < hight; h += workgroup_size) {
|
|
1826
|
+
let value = ${h}(${I.get("batch","channel","h")});
|
|
1827
|
+
sum += value;
|
|
1828
|
+
squared_sum += value * value;
|
|
1829
|
+
}
|
|
1830
|
+
workgroup_shared[local_idx] = ${p}(sum, squared_sum);
|
|
1831
|
+
workgroupBarrier();
|
|
1832
|
+
|
|
1833
|
+
for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {
|
|
1834
|
+
if (local_idx < currSize) {
|
|
1835
|
+
workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];
|
|
1836
|
+
}
|
|
1837
|
+
workgroupBarrier();
|
|
1838
|
+
}
|
|
1839
|
+
if (local_idx == 0) {
|
|
1840
|
+
let sum_final = ${Q("workgroup_shared[0][0]",c)} / f32(hight * ${c});
|
|
1841
|
+
let squared_sum_final = ${Q("workgroup_shared[0][1]",c)} / f32(hight * ${c});
|
|
1842
|
+
|
|
1843
|
+
let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u}));
|
|
1844
|
+
let channel_scale = inv_std_dev * f32(scale[channel]);
|
|
1845
|
+
let channel_shift = f32(bias[channel]) - sum_final * channel_scale;
|
|
1846
|
+
output[workgroup_index] = vec2f(channel_scale, channel_shift);
|
|
1847
|
+
}
|
|
1848
|
+
}`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${c};${u};${y}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:v,dataType:1}],dispatchGroup:{x:m},programUniforms:R}),getShaderSource:C},{inputs:[t,r,i],outputs:[-1]})[0]},Td=(e,t,r)=>{let i=t[0].dims,a=i,o=2,l=i[0],u=i[1],c=q.sizeFromDimension(i,o),h=F(c),p=q.size(a)/h,m=ea(e,t[0],t[1],t[2],l,c,u,r.epsilon),y=[l,u,c/h],w=[l,u],v=["type","none"],x=R=>{let C=U("x",t[0].dataType,y.length,h),$=U("scale_shift",1,w.length,2),I=te("output",t[0].dataType,y.length,h),M=[C,$,I];return`
|
|
1849
|
+
${R.registerUniform("output_size","u32").declareVariables(...M)}
|
|
1850
|
+
${R.mainStart()}
|
|
1851
|
+
${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1852
|
+
let outputIndices = ${I.offsetToIndices("global_idx")};
|
|
1853
|
+
let batch = outputIndices[0];
|
|
1854
|
+
let channel = outputIndices[1];
|
|
1855
|
+
let scale_shift = ${$.getByIndices("vec2<u32>(batch, channel)")};
|
|
1856
|
+
let value = ${C.getByOffset("global_idx")} * ${I.type.value}(scale_shift.x) + ${I.type.value}(scale_shift.y);
|
|
1857
|
+
${I.setByOffset("global_idx","value")};
|
|
1858
|
+
}`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:a,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...D(y,w,y)]}),getShaderSource:x},{inputs:[t[0],m]})},Cd=(e,t,r)=>{let i=t[0].dims,a=i,o=i[0],l=i[i.length-1],u=q.sizeFromDimension(i,1)/l,c=F(l),h=q.size(a)/c,p=[{type:12,data:u},{type:12,data:Math.floor(l/c)}],m=["type","type"],y=!1,w=[0,i.length-1];for(let C=0;C<i.length-2;C++)y=y||i[C+1]!==1,w.push(C+1);y=y&&i[i.length-1]!==1;let v=y?e.compute(it(e.inputs[0],w),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:i.length},(C,$)=>i[w[$]])),x=ea(e,v,t[1],t[2],o,u,l,r.epsilon),R=C=>{let $=N(t[0].dataType),I=c===1?"vec2f":`mat${c}x2f`,M=W=>{let X=W===0?"x":"y",se=c===1?"f32":`vec${c}f`;switch(c){case 1:return`${$}(${se}(scale.${X}))`;case 2:return`vec2<${$}>(${se}(scale[0].${X}, scale[1].${X}))`;case 4:return`vec4<${$}>(${se}(scale[0].${X}, scale[1].${X}, scale[2].${X}, scale[3].${X}))`;default:throw new Error(`Not supported compoents ${c}`)}},L=U("input",t[0].dataType,t[0].dims,c),V=te("output",t[0].dataType,a,c);return`
|
|
1859
|
+
@group(0) @binding(0) var<storage, read> input : array<${L.type.storage}>;
|
|
1860
|
+
@group(0) @binding(1) var<storage, read> scale_input : array<${I}>;
|
|
1861
|
+
@group(0) @binding(2) var<storage, read_write> output : array<${V.type.storage}>;
|
|
1862
|
+
struct Uniforms {H: u32, C : u32};
|
|
1863
|
+
@group(0) @binding(3) var<uniform> uniforms: Uniforms;
|
|
1864
|
+
|
|
1865
|
+
${C.mainStart()}
|
|
1866
|
+
let current_image_number = global_idx / (uniforms.C * uniforms.H);
|
|
1867
|
+
let current_channel_number = global_idx % uniforms.C;
|
|
1868
|
+
|
|
1869
|
+
let scale_offset = current_image_number * uniforms.C + current_channel_number;
|
|
1870
|
+
let scale = scale_input[scale_offset];
|
|
1871
|
+
output[global_idx] = fma(input[global_idx], ${M(0)}, ${M(1)});
|
|
1872
|
+
}`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${c}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:a,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p}),getShaderSource:R},{inputs:[t[0],x]})},Ed=(e,t)=>{t.format==="NHWC"?Cd(e,e.inputs,t):Td(e,e.inputs,t)}}),kd,Md,Rd,Rm=T(()=>{Ee(),xe(),he(),kd=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Md=(e,t,r)=>{let i=t.simplified,a=e[0].dims,o=e[1],l=!i&&e[2],u=a,c=q.normalizeAxis(t.axis,a.length),h=q.sizeToDimension(a,c),p=q.sizeFromDimension(a,c),m=q.size(o.dims),y=l?q.size(l.dims):0;if(m!==p||l&&y!==p)throw new Error(`Size of X.shape()[axis:] == ${p}.
|
|
1873
|
+
Size of scale and bias (if provided) must match this.
|
|
1874
|
+
Got scale size of ${m} and bias size of ${y}`);let w=[];for(let L=0;L<a.length;++L)L<c?w.push(a[L]):w.push(1);let v=F(p),x=["type","type"],R=[{type:12,data:h},{type:1,data:p},{type:12,data:Math.floor(p/v)},{type:1,data:t.epsilon}];l&&x.push("type");let C=r>1,$=r>2,I=L=>{let V=N(e[0].dataType),W=[U("x",e[0].dataType,e[0].dims,v),U("scale",o.dataType,o.dims,v)];l&&W.push(U("bias",l.dataType,l.dims,v)),W.push(te("output",e[0].dataType,u,v)),C&&W.push(te("mean_data_output",1,w)),$&&W.push(te("inv_std_output",1,w));let X=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`
|
|
1875
|
+
${L.registerUniforms(X).declareVariables(...W)}
|
|
1876
|
+
${L.mainStart()}
|
|
1877
|
+
${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}
|
|
1878
|
+
let offset = global_idx * uniforms.norm_size_vectorized;
|
|
1879
|
+
var mean_vector = ${Z("f32",v)};
|
|
1880
|
+
var mean_square_vector = ${Z("f32",v)};
|
|
1881
|
+
|
|
1882
|
+
for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {
|
|
1883
|
+
let value = ${Y(V,v,"x[h + offset]")};
|
|
1884
|
+
mean_vector += value;
|
|
1885
|
+
mean_square_vector += value * value;
|
|
1886
|
+
}
|
|
1887
|
+
let mean = ${Q("mean_vector",v)} / uniforms.norm_size;
|
|
1888
|
+
let inv_std_dev = inverseSqrt(${Q("mean_square_vector",v)} / uniforms.norm_size ${i?"":"- mean * mean"} + uniforms.epsilon);
|
|
1889
|
+
|
|
1890
|
+
for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {
|
|
1891
|
+
let f32input = ${Y(V,v,"x[j + offset]")};
|
|
1892
|
+
let f32scale = ${Y(V,v,"scale[j]")};
|
|
1893
|
+
output[j + offset] = ${W[0].type.value}((f32input ${i?"":"- mean"}) * inv_std_dev * f32scale
|
|
1894
|
+
${l?`+ ${Y(V,v,"bias[j]")}`:""}
|
|
1895
|
+
);
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
${C?"mean_data_output[global_idx] = mean":""};
|
|
1899
|
+
${$?"inv_std_output[global_idx] = inv_std_dev":""};
|
|
1900
|
+
}`},M=[{dims:u,dataType:e[0].dataType}];return C&&M.push({dims:w,dataType:1}),$&&M.push({dims:w,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${v};${r};${i}`,inputDependencies:x},getRunData:()=>({outputs:M,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:R}),getShaderSource:I}},Rd=(e,t)=>{kd(e.inputs),e.compute(Md(e.inputs,t,e.outputCount))}}),Id,Ad,Im=T(()=>{xe(),Dn(),Fn(),Id=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},Ad=e=>{Id(e.inputs);let t=lr.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],i=e.inputs[0].dims[e.inputs[0].dims.length-1];if(r<8&&i<8)e.compute(zn(e.inputs,{activation:""},t));else{let a=t[t.length-2],o=q.size(e.inputs[0].dims.slice(0,-2)),l=q.size(e.inputs[1].dims.slice(0,-2));if(o!==1&&a===1&&l===1){let u=e.inputs[0].reshape([1,o,i]),c=e.inputs[1].reshape([1,i,r]),h=[1,o,r],p=[u,c];e.compute(Zi(p,{activation:""},t,h),{inputs:p})}else e.compute(Zi(e.inputs,{activation:""},t))}}}),Pd,Od,zd,Dd,Ld,Am=T(()=>{Ee(),xe(),k(),he(),Pd=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],i=r.dims.length;if(r.dims[i-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let a=Math.floor((t.k+t.blockSize-1)/t.blockSize),o=t.blockSize/8*t.bits,l=e[1];if(!q.areEqual(l.dims,[t.n,a,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(q.size(u)!==t.n*a)throw new Error("scales input size error.");if(e.length===4){let c=e[3].dims,h=t.n*(t.bits===8?a:Math.floor((a*t.bits+7)/8));if(q.size(c)!==h)throw new Error("zeroPoints input size error.")}},Od=(e,t)=>{let r=e[0].dims,i=r.length,a=r[i-2],o=t.k,l=t.n,u=r.slice(0,i-2),c=q.size(u),h=e[1].dims[2]/4,p=e[0].dataType,m=F(t.k),y=F(h),w=F(l),v=u.concat([a,l]),x=a>1&&l/w%2===0?2:1,R=q.size(v)/w/x,C=64,$=[],I=[c,a,o/m],M=q.convertShape(e[1].dims).slice();M.splice(-1,1,h/y),$.push(...D(I)),$.push(...D(M)),$.push(...D(e[2].dims)),e.length===4&&$.push(...D(q.convertShape(e[3].dims)));let L=[c,a,l/w];$.push(...D(L));let V=W=>{let X=I.length,se=U("a",e[0].dataType,X,m),ge=U("b",12,M.length,y),Be=U("scales",e[2].dataType,e[2].dims.length),Te=[se,ge,Be],ke=e.length===4?U("zero_points",12,e[3].dims.length):void 0;ke&&Te.push(ke);let Ge=L.length,ue=te("output",e[0].dataType,Ge,w),Se=N(e[0].dataType),Oe=(()=>{switch(m){case 1:return`array<${Se}, 8>`;case 2:return`mat4x2<${Se}>`;case 4:return`mat2x4<${Se}>`;default:throw new Error(`${m}-component is not supported.`)}})(),Ue=Math.floor(32/t.bits),Ae=Math.floor(Ue/8),Ne=()=>{let Ce="";for(let _e=0;_e<Ae;_e++){let xt=_e*t.bits*4,Ft=xt+t.bits;Ce+=`
|
|
1901
|
+
// reuse a data (pass ${_e})
|
|
1902
|
+
var input_offset${_e>0?_e:""} = ${_e===0?se.indicesToOffset(`${se.type.indices}(batch, row, word_offset)`):"input_offset"};
|
|
1903
|
+
var a_data${_e>0?_e:""}: ${Oe};
|
|
1904
|
+
for (var j${_e>0?_e:""}: u32 = 0; j${_e>0?_e:""} < ${8/m}; j${_e>0?_e:""}++) {
|
|
1905
|
+
a_data${_e>0?_e:""}[j${_e>0?_e:""}] = ${se.getByOffset(`input_offset${_e>0?_e:""}`)};
|
|
1906
|
+
input_offset${_e>0?_e:""}++;
|
|
1907
|
+
}
|
|
1908
|
+
`;for(let pt=0;pt<w*x;pt++)Ce+=`
|
|
1909
|
+
b_value = ${y===1?`b${pt}_data`:`b${pt}_data[i]`};
|
|
1910
|
+
${t.bits===2?`{
|
|
1911
|
+
let half_word = b_value >> ${_e*16}u;
|
|
1912
|
+
let byte_lo = half_word & 0xFFu;
|
|
1913
|
+
let byte_hi = (half_word >> 8u) & 0xFFu;
|
|
1914
|
+
let spread_word = (byte_lo & 0xFu) | ((byte_lo >> 4u) << 8u) | ((byte_hi & 0xFu) << 16u) | ((byte_hi >> 4u) << 24u);
|
|
1915
|
+
b_value_lower = unpack4xU8(spread_word & b_mask);
|
|
1916
|
+
b_value_upper = unpack4xU8((spread_word >> 2u) & b_mask);
|
|
1917
|
+
}`:`b_value_lower = unpack4xU8((b_value >> ${xt}u) & b_mask);
|
|
1918
|
+
b_value_upper = unpack4xU8((b_value >> ${Ft}u) & b_mask);`}
|
|
1919
|
+
b_quantized_values = ${Oe}(${Array.from({length:4},(Nt,Ze)=>`${Se}(b_value_lower[${Ze}]), ${Se}(b_value_upper[${Ze}])`).join(", ")});
|
|
1920
|
+
b_dequantized_values = ${m===1?`${Oe}(${Array.from({length:8},(Nt,Ze)=>`(b_quantized_values[${Ze}] - ${ke?`zero_point${pt}`:"zero_point"}) * scale${pt}`).join(", ")});`:`(b_quantized_values - ${Oe}(${Array(8).fill(`${ke?`zero_point${pt}`:"zero_point"}`).join(",")})) * scale${pt};`};
|
|
1921
|
+
workgroup_shared[local_id.x * ${x} + ${Math.floor(pt/w)}]${w>1?`[${pt%w}]`:""} += ${Array.from({length:8/m},(Nt,Ze)=>`${m===1?`a_data${_e>0?_e:""}[${Ze}] * b_dequantized_values[${Ze}]`:`dot(a_data${_e>0?_e:""}[${Ze}], b_dequantized_values[${Ze}])`}`).join(" + ")};
|
|
1922
|
+
`}return Ce},ee=()=>{let Ce=`
|
|
1923
|
+
var col_index = col * ${w};
|
|
1924
|
+
${ke?`
|
|
1925
|
+
let zero_point_values_per_byte: u32 = ${Math.floor(8/t.bits)}u;
|
|
1926
|
+
let zero_point_bytes_per_col = (nBlocksPerCol + zero_point_values_per_byte - 1u) / zero_point_values_per_byte;
|
|
1927
|
+
var zero_point_byte_count: u32;
|
|
1928
|
+
var zero_point_word_index: u32;
|
|
1929
|
+
var zero_point_byte_offset: u32;
|
|
1930
|
+
let zero_point_sub_offset: u32 = block % zero_point_values_per_byte;
|
|
1931
|
+
var zero_point_bits_offset: u32;
|
|
1932
|
+
var zero_point_word: u32;`:`
|
|
1933
|
+
// The default zero point is ${Math.pow(2,t.bits-1)} for unsigned ${t.bits}-bit quantization.
|
|
1934
|
+
let zero_point = ${Se}(${Math.pow(2,t.bits-1).toFixed(1)});`}
|
|
1935
|
+
`;for(let _e=0;_e<w*x;_e++)Ce+=`
|
|
1936
|
+
let scale${_e} = ${Be.getByOffset("col_index * nBlocksPerCol + block")};
|
|
1937
|
+
${ke?`
|
|
1938
|
+
zero_point_byte_count = col_index * zero_point_bytes_per_col + (block / zero_point_values_per_byte);
|
|
1939
|
+
zero_point_word_index = zero_point_byte_count >> 0x2u;
|
|
1940
|
+
zero_point_byte_offset = zero_point_byte_count & 0x3u;
|
|
1941
|
+
zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_sub_offset * ${t.bits}u);
|
|
1942
|
+
zero_point_word = ${ke.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
1943
|
+
let zero_point${_e} = ${Se}((zero_point_word) & ${t.bits===2?"0x3u":"0xFu"});`:""}
|
|
1944
|
+
col_index += 1;`;return Ce},Ie=()=>{let Ce=`col_index = col * ${w};`;for(let _e=0;_e<w*x;_e++)Ce+=`
|
|
1945
|
+
let b${_e}_data = ${ge.getByIndices(`${ge.type.indices}(col_index, block, word)`)};
|
|
1946
|
+
col_index += 1;`;return Ce+=`
|
|
1947
|
+
var b_value: u32;
|
|
1948
|
+
let b_mask: u32 = ${t.bits===2?"0x03030303u":"0x0F0F0F0Fu"};
|
|
1949
|
+
var b_value_lower: vec4<u32>;
|
|
1950
|
+
var b_value_upper: vec4<u32>;
|
|
1951
|
+
var b_quantized_values: ${Oe};
|
|
1952
|
+
var b_dequantized_values: ${Oe};`,Ce};return`
|
|
1953
|
+
var<workgroup> workgroup_shared: array<${ue.type.value}, ${x*C}>;
|
|
1954
|
+
${W.declareVariables(...Te,ue)}
|
|
1955
|
+
${W.mainStart([C,1,1])}
|
|
1956
|
+
let output_indices = ${ue.offsetToIndices(`(global_idx / ${C}) * ${x}`)};
|
|
1957
|
+
let col = output_indices[2];
|
|
1958
|
+
let row = output_indices[1];
|
|
1959
|
+
let batch = output_indices[0];
|
|
1960
|
+
let nBlocksPerCol = uniforms.b_shape[1];
|
|
1961
|
+
|
|
1962
|
+
for (var block = local_id.x; block < nBlocksPerCol; block += ${C}) {
|
|
1963
|
+
//process one block
|
|
1964
|
+
var word_offset: u32 = block * ${t.blockSize/m};
|
|
1965
|
+
${ee()}
|
|
1966
|
+
for (var word: u32 = 0; word < ${h}; word += ${y}) {
|
|
1967
|
+
${Ie()}
|
|
1968
|
+
for (var i: u32 = 0; i < ${y}; i++) {
|
|
1969
|
+
${Ne()}
|
|
1970
|
+
word_offset += ${Ue/m};
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
workgroupBarrier();
|
|
1975
|
+
|
|
1976
|
+
if (local_id.x < ${x}) {
|
|
1977
|
+
var output_value: ${ue.type.value} = ${ue.type.value}(0);
|
|
1978
|
+
var workgroup_shared_offset: u32 = local_id.x;
|
|
1979
|
+
for (var b: u32 = 0u; b < ${C}u; b++) {
|
|
1980
|
+
output_value += workgroup_shared[workgroup_shared_offset];
|
|
1981
|
+
workgroup_shared_offset += ${x};
|
|
1982
|
+
}
|
|
1983
|
+
${ue.setByIndices(`${ue.type.indices}(batch, row, col + local_id.x)`,"output_value")};
|
|
1984
|
+
}
|
|
1985
|
+
}`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${m};${y};${w};${x};${C}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:v,dataType:p}],dispatchGroup:{x:R},programUniforms:$}),getShaderSource:V}},zd=(e,t)=>{let r=e[0].dims,i=r.length,a=r[i-2],o=t.k,l=t.n,u=r.slice(0,i-2),c=q.size(u),h=e[1].dims[2]/4,p=e[0].dataType,m=F(t.k),y=F(h),w=u.concat([a,l]),v=128,x=l%8===0?8:l%4===0?4:1,R=v/x,C=Math.floor(32/t.bits),$=R*y*C,I=$/m,M=$/t.blockSize,L=q.size(w)/x,V=[],W=[c,a,o/m],X=q.convertShape(e[1].dims).slice();X.splice(-1,1,h/y),V.push(...D(W)),V.push(...D(X)),V.push(...D(e[2].dims)),e.length===4&&V.push(...D(q.convertShape(e[3].dims)));let se=[c,a,l];V.push(...D(se));let ge=Be=>{let Te=W.length,ke=U("a",e[0].dataType,Te,m),Ge=U("b",12,X.length,y),ue=U("scales",e[2].dataType,e[2].dims.length),Se=[ke,Ge,ue],Oe=e.length===4?U("zero_points",12,e[3].dims.length):void 0;Oe&&Se.push(Oe);let Ue=se.length,Ae=te("output",e[0].dataType,Ue),Ne=N(e[0].dataType),ee=()=>{switch(m){case 1:return`
|
|
1986
|
+
let a_data0 = vec4<${Ne}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);
|
|
1987
|
+
let a_data1 = vec4<${Ne}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`
|
|
1988
|
+
let a_data0 = vec4<${Ne}>(sub_a[word_offset], sub_a[word_offset + 1]);
|
|
1989
|
+
let a_data1 = vec4<${Ne}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`
|
|
1990
|
+
let a_data0 = sub_a[word_offset];
|
|
1991
|
+
let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${m}-component is not supported.`)}};return`
|
|
1992
|
+
var<workgroup> sub_a: array<${ke.type.value}, ${I}>;
|
|
1993
|
+
var<workgroup> inter_results: array<array<${Ae.type.value}, ${R}>, ${x}>;
|
|
1994
|
+
${Be.declareVariables(...Se,Ae)}
|
|
1995
|
+
${Be.mainStart([R,x,1])}
|
|
1996
|
+
let output_indices = ${Ae.offsetToIndices(`workgroup_index * ${x}`)};
|
|
1997
|
+
let col = output_indices[2];
|
|
1998
|
+
let row = output_indices[1];
|
|
1999
|
+
let batch = output_indices[0];
|
|
2000
|
+
let n_blocks_per_col = uniforms.b_shape[1];
|
|
2001
|
+
let num_tiles = (n_blocks_per_col - 1) / ${M} + 1;
|
|
2002
|
+
|
|
2003
|
+
// Loop over shared dimension.
|
|
2004
|
+
for (var tile: u32 = 0; tile < num_tiles; tile += 1) {
|
|
2005
|
+
let a_col_start = tile * ${I};
|
|
2006
|
+
// load one tile A data into shared memory.
|
|
2007
|
+
for (var a_offset = local_idx; a_offset < ${I}; a_offset += ${v})
|
|
2008
|
+
{
|
|
2009
|
+
let a_col = a_col_start + a_offset;
|
|
2010
|
+
if (a_col < uniforms.a_shape[2])
|
|
2011
|
+
{
|
|
2012
|
+
sub_a[a_offset] = ${ke.getByIndices(`${ke.type.indices}(batch, row, a_col)`)};
|
|
2013
|
+
} else {
|
|
2014
|
+
sub_a[a_offset] = ${ke.type.value}(0);
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
workgroupBarrier();
|
|
2018
|
+
|
|
2019
|
+
// each thread process one block
|
|
2020
|
+
let b_row = col + local_id.y;
|
|
2021
|
+
let block = tile * ${M} + local_id.x;
|
|
2022
|
+
${Oe?`
|
|
2023
|
+
let zero_point_values_per_byte: u32 = ${Math.floor(8/t.bits)}u;
|
|
2024
|
+
let zero_point_bytes_per_col = (n_blocks_per_col + zero_point_values_per_byte - 1u) / zero_point_values_per_byte;
|
|
2025
|
+
let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block / zero_point_values_per_byte);
|
|
2026
|
+
let zero_point_word_index = zero_point_byte_count >> 0x2u;
|
|
2027
|
+
let zero_point_byte_offset = zero_point_byte_count & 0x3u;
|
|
2028
|
+
let zero_point_sub_offset: u32 = block % zero_point_values_per_byte;
|
|
2029
|
+
let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_sub_offset * ${t.bits}u);
|
|
2030
|
+
let zero_point_word = ${Oe.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
2031
|
+
let zero_point = ${Ne}((zero_point_word) & ${t.bits===2?"0x3u":"0xFu"});`:`
|
|
2032
|
+
// The default zero point is ${Math.pow(2,t.bits-1)} for unsigned ${t.bits}-bit quantization.
|
|
2033
|
+
let zero_point = ${Ne}(${Math.pow(2,t.bits-1).toFixed(1)});`}
|
|
2034
|
+
let scale = ${ue.getByOffset("b_row * n_blocks_per_col + block")};
|
|
2035
|
+
let b_data = ${Ge.getByIndices(`${Ge.type.indices}(b_row, block, 0)`)};
|
|
2036
|
+
var word_offset = local_id.x * ${t.blockSize/m};
|
|
2037
|
+
for (var i: u32 = 0; i < ${y}; i++) {
|
|
2038
|
+
let b_value = ${y===1?"b_data":"b_data[i]"};
|
|
2039
|
+
${(()=>{let Ie=Math.floor(C/8),Ce="";for(let _e=0;_e<Ie;_e++){let xt=_e*t.bits*4,Ft=xt+t.bits;Ce+=`
|
|
2040
|
+
${ee()}
|
|
2041
|
+
{${t.bits===2?`
|
|
2042
|
+
let half_word = b_value >> ${_e*16}u;
|
|
2043
|
+
let byte_lo = half_word & 0xFFu;
|
|
2044
|
+
let byte_hi = (half_word >> 8u) & 0xFFu;
|
|
2045
|
+
let spread_word = (byte_lo & 0xFu) | ((byte_lo >> 4u) << 8u) | ((byte_hi & 0xFu) << 16u) | ((byte_hi >> 4u) << 24u);
|
|
2046
|
+
let b_value_lower = unpack4xU8(spread_word & 0x03030303u);
|
|
2047
|
+
let b_value_upper = unpack4xU8((spread_word >> 2u) & 0x03030303u);`:`
|
|
2048
|
+
let b_value_lower = unpack4xU8((b_value >> ${xt}u) & 0x0F0F0F0Fu);
|
|
2049
|
+
let b_value_upper = unpack4xU8((b_value >> ${Ft}u) & 0x0F0F0F0Fu);`}
|
|
2050
|
+
let b_quantized_values = mat2x4<${Ne}>(${Array.from({length:4},(pt,Nt)=>`${Ne}(b_value_lower[${Nt}]), ${Ne}(b_value_upper[${Nt}])`).join(", ")});
|
|
2051
|
+
let b_dequantized_values = (b_quantized_values - mat2x4<${Ne}>(${Array(8).fill("zero_point").join(",")})) * scale;
|
|
2052
|
+
inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(pt,Nt)=>`${`dot(a_data${Nt}, b_dequantized_values[${Nt}])`}`).join(" + ")};
|
|
2053
|
+
}
|
|
2054
|
+
word_offset += ${8/m};`}return Ce})()}
|
|
2055
|
+
}
|
|
2056
|
+
workgroupBarrier();
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
if (local_idx < ${x}) {
|
|
2060
|
+
var output_value: ${Ae.type.value} = ${Ae.type.value}(0);
|
|
2061
|
+
for (var b = 0u; b < ${R}; b++) {
|
|
2062
|
+
output_value += inter_results[local_idx][b];
|
|
2063
|
+
}
|
|
2064
|
+
if (col + local_idx < uniforms.output_shape[2])
|
|
2065
|
+
{
|
|
2066
|
+
${Ae.setByIndices(`${Ae.type.indices}(batch, row, col + local_idx)`,"output_value")}
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${m};${y};${R};${x}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:w,dataType:p}],dispatchGroup:{x:L},programUniforms:V}),getShaderSource:ge}},Dd=(e,t)=>{Pd(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(zd(e.inputs,t)):e.compute(Od(e.inputs,t))},Ld=e=>_(e)}),Bd,Ud,Fd,Nd,Vd,Gd,Wd,qd,Hd,Pm=T(()=>{Ee(),xe(),he(),Bd=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Ud=(e,t,r)=>{let i="";for(let a=t-1;a>=0;--a)i+=`
|
|
2070
|
+
k = i32(${e.indicesGet("indices",a)}) - ${H("uniforms.pads",a,r)};
|
|
2071
|
+
if (k < 0) {
|
|
2072
|
+
break;
|
|
2073
|
+
}
|
|
2074
|
+
if (k >= i32(${H("uniforms.x_shape",a,t)})) {
|
|
2075
|
+
break;
|
|
2076
|
+
}
|
|
2077
|
+
offset += k * i32(${H("uniforms.x_strides",a,t)});
|
|
2078
|
+
`;return`
|
|
2079
|
+
value = ${e.type.value}(uniforms.constant_value);
|
|
2080
|
+
for (var i = 0; i < 1; i++) {
|
|
2081
|
+
var offset = 0;
|
|
2082
|
+
var k = 0;
|
|
2083
|
+
${i}
|
|
2084
|
+
value = x[offset];
|
|
2085
|
+
}
|
|
2086
|
+
`},Fd=(e,t,r)=>{let i="";for(let a=t-1;a>=0;--a)i+=`
|
|
2087
|
+
k = i32(${e.indicesGet("indices",a)}) - ${H("uniforms.pads",a,r)};
|
|
2088
|
+
if (k < 0) {
|
|
2089
|
+
k = -k;
|
|
2090
|
+
}
|
|
2091
|
+
{
|
|
2092
|
+
let _2n_1 = 2 * (i32(${H("uniforms.x_shape",a,t)}) - 1);
|
|
2093
|
+
k = k % _2n_1;
|
|
2094
|
+
if(k >= i32(${H("uniforms.x_shape",a,t)})) {
|
|
2095
|
+
k = _2n_1 - k;
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
offset += k * i32(${H("uniforms.x_strides",a,t)});
|
|
2099
|
+
`;return`
|
|
2100
|
+
var offset = 0;
|
|
2101
|
+
var k = 0;
|
|
2102
|
+
${i}
|
|
2103
|
+
value = x[offset];
|
|
2104
|
+
`},Nd=(e,t,r)=>{let i="";for(let a=t-1;a>=0;--a)i+=`
|
|
2105
|
+
k = i32(${e.indicesGet("indices",a)}) - ${H("uniforms.pads",a,r)};
|
|
2106
|
+
if (k < 0) {
|
|
2107
|
+
k = 0;
|
|
2108
|
+
}
|
|
2109
|
+
if (k >= i32(${H("uniforms.x_shape",a,t)})) {
|
|
2110
|
+
k = i32(${H("uniforms.x_shape",a,t)}) - 1;
|
|
2111
|
+
}
|
|
2112
|
+
offset += k * i32(${H("uniforms.x_strides",a,t)});
|
|
2113
|
+
`;return`
|
|
2114
|
+
var offset = 0;
|
|
2115
|
+
var k = 0;
|
|
2116
|
+
${i}
|
|
2117
|
+
value = x[offset];
|
|
2118
|
+
`},Vd=(e,t,r)=>{let i="";for(let a=t-1;a>=0;--a)i+=`
|
|
2119
|
+
k = i32(${e.indicesGet("indices",a)}) - ${H("uniforms.pads",a,r)};
|
|
2120
|
+
if (k < 0) {
|
|
2121
|
+
k += i32(${H("uniforms.x_shape",a,t)}]);
|
|
2122
|
+
}
|
|
2123
|
+
if (k >= i32(${H("uniforms.x_shape",a,t)})) {
|
|
2124
|
+
k -= i32(${H("uniforms.x_shape",a,t)});
|
|
2125
|
+
}
|
|
2126
|
+
offset += k * i32(${H("uniforms.x_strides",a,t)});
|
|
2127
|
+
`;return`
|
|
2128
|
+
var offset = 0;
|
|
2129
|
+
var k = 0;
|
|
2130
|
+
${i}
|
|
2131
|
+
value = x[offset];
|
|
2132
|
+
`},Gd=(e,t,r)=>{switch(r.mode){case 0:return Ud(e,t,r.pads.length);case 1:return Fd(e,t,r.pads.length);case 2:return Nd(e,t,r.pads.length);case 3:return Vd(e,t,r.pads.length);default:throw new Error("Invalid mode")}},Wd=(e,t)=>{let r=q.padShape(e[0].dims.slice(),t.pads),i=e[0].dims,a=q.size(r),o=[{type:12,data:a},{type:6,data:t.pads}],l=e.length>=3&&e[2].data;t.mode===0&&o.push({type:l?e[2].dataType:1,data:t.value}),o.push(...D(e[0].dims,r));let u=["rank"],c=h=>{let p=te("output",e[0].dataType,r.length),m=U("x",e[0].dataType,i.length),y=m.type.value,w=Gd(p,i.length,t),v=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&v.push({name:"constant_value",type:l?y:"f32"}),`
|
|
2133
|
+
${h.registerUniforms(v).declareVariables(m,p)}
|
|
2134
|
+
${h.mainStart()}
|
|
2135
|
+
${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2136
|
+
|
|
2137
|
+
let indices = ${p.offsetToIndices("global_idx")};
|
|
2138
|
+
|
|
2139
|
+
var value = ${y}(0);
|
|
2140
|
+
${w}
|
|
2141
|
+
output[global_idx] = value;
|
|
2142
|
+
}`};return{name:"Pad",shaderCache:{hint:`${t.mode}${l}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(q.size(r)/64)},programUniforms:o}),getShaderSource:c}},qd=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),i=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,a=e[0].dims.length,o=new Int32Array(2*a).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let c=0;c<u.length;c++)o[Number(u[c])]=Number(r[c]),o[Number(u[c])+a]=Number(r[c+u.length])}else r.forEach((u,c)=>o[Number(c)]=Number(u));let l=[];return o.forEach(u=>l.push(u)),{mode:t.mode,value:i,pads:l}}else return t},Hd=(e,t)=>{Bd(e.inputs);let r=qd(e.inputs,t);e.compute(Wd(e.inputs,r),{inputs:[0]})}}),ki,ta,ra,sa,ia,jd,Kd,na,aa,Qd,Xd,oa,Zd,Jd,la,Yd,ec,tc,rc,Om=T(()=>{wt(),Ee(),xe(),he(),ki=e=>{if(de.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},ta=(e,t,r)=>{let i=t.format==="NHWC",a=e.dims.slice();i&&a.splice(1,0,a.pop());let o=Object.hasOwnProperty.call(t,"dilations"),l=t.kernelShape.slice(),u=t.strides.slice(),c=o?t.dilations.slice():[],h=t.pads.slice();Er.adjustPoolAttributes(r,a,l,u,c,h);let p=Er.computePoolOutputShape(r,a,u,c,l,h,t.autoPad),m=Object.assign({},t);o?Object.assign(m,{kernelShape:l,strides:u,pads:h,dilations:c,cacheKey:t.cacheKey}):Object.assign(m,{kernelShape:l,strides:u,pads:h,cacheKey:t.cacheKey});let y=p.slice();return y.push(y.splice(1,1)[0]),[m,i?y:p]},ra=(e,t)=>{let r=t.format==="NHWC",i=q.size(e),a=q.size(t.kernelShape),o=[{type:12,data:i},{type:12,data:a}],l=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],c=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],p=t.pads[t.pads.length-1],m=!!(h+p);o.push({type:12,data:u},{type:12,data:c},{type:12,data:h},{type:12,data:p}),l.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let y=!1;if(t.kernelShape.length===2){let w=t.kernelShape[t.kernelShape.length-2],v=t.strides[t.strides.length-2],x=t.pads[t.pads.length/2-2],R=t.pads[t.pads.length-2];y=!!(x+R),o.push({type:12,data:w},{type:12,data:v},{type:12,data:x},{type:12,data:R}),l.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,l,!0,m,y]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=q.computeStrides(t.kernelShape);o.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),l.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let c=t.pads.reduce((h,p)=>h+p);return[o,l,!!c,!1,!1]}},sa=(e,t,r,i,a,o,l,u,c,h,p,m)=>{let y=a.format==="NHWC",w=t.type.value,v=te("output",t.type.tensor,i);if(a.kernelShape.length<=2){let x="",R="",C="",$=r-(y?2:1);if(p?x=`
|
|
2143
|
+
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2144
|
+
xIndices[${$}] = indices[${$}] * uniforms.sw - uniforms.pwStart + i;
|
|
2145
|
+
if (xIndices[${$}] < 0 || xIndices[${$}]
|
|
2146
|
+
>= uniforms.x_shape[${$}]) {
|
|
2147
|
+
pad++;
|
|
2148
|
+
continue;
|
|
2149
|
+
}
|
|
2150
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2151
|
+
${o}
|
|
2152
|
+
}`:x=`
|
|
2153
|
+
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2154
|
+
xIndices[${$}] = indices[${$}] * uniforms.sw - uniforms.pwStart + i;
|
|
2155
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2156
|
+
${o}
|
|
2157
|
+
}`,a.kernelShape.length===2){let I=r-(y?3:2);m?R=`
|
|
2158
|
+
for (var j: u32 = 0u; j < uniforms.kh; j++) {
|
|
2159
|
+
xIndices[${I}] = indices[${I}] * uniforms.sh - uniforms.phStart + j;
|
|
2160
|
+
if (xIndices[${I}] < 0 || xIndices[${I}] >= uniforms.x_shape[${I}]) {
|
|
2161
|
+
pad += i32(uniforms.kw);
|
|
2162
|
+
continue;
|
|
2163
|
+
}
|
|
2164
|
+
`:R=`
|
|
2165
|
+
for (var j: u32 = 0u; j < uniforms.kh; j++) {
|
|
2166
|
+
xIndices[${I}] = indices[${I}] * uniforms.sh - uniforms.phStart + j;
|
|
2167
|
+
`,C=`
|
|
2168
|
+
}
|
|
2169
|
+
`}return`
|
|
2170
|
+
${e.registerUniforms(c).declareVariables(t,v)}
|
|
2171
|
+
|
|
2172
|
+
${e.mainStart()}
|
|
2173
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2174
|
+
|
|
2175
|
+
let indices = ${v.offsetToIndices("global_idx")};
|
|
2176
|
+
var xIndices = ${v.offsetToIndices("global_idx")};
|
|
2177
|
+
|
|
2178
|
+
var value = ${w}(${u});
|
|
2179
|
+
var pad = 0;
|
|
2180
|
+
${R}
|
|
2181
|
+
${x}
|
|
2182
|
+
${C}
|
|
2183
|
+
${l}
|
|
2184
|
+
|
|
2185
|
+
output[global_idx] = value;
|
|
2186
|
+
}`}else{if(y)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let x=a.kernelShape.length,R=a.pads.length,C="";return h?C=`
|
|
2187
|
+
if (xIndices[j] >= uniforms.x_shape[j]) {
|
|
2188
|
+
pad++;
|
|
2189
|
+
isPad = true;
|
|
2190
|
+
break;
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
if (!isPad) {
|
|
2194
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2195
|
+
${o}
|
|
2196
|
+
}`:C=`
|
|
2197
|
+
}
|
|
2198
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2199
|
+
${o}
|
|
2200
|
+
`,`
|
|
2201
|
+
${e.registerUniforms(c).declareVariables(t,v)}
|
|
2202
|
+
|
|
2203
|
+
${e.mainStart()}
|
|
2204
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2205
|
+
let indices = ${v.offsetToIndices("global_idx")};
|
|
2206
|
+
var xIndices = ${v.offsetToIndices("global_idx")};
|
|
2207
|
+
|
|
2208
|
+
var offsets: array<u32, ${x}>;
|
|
2209
|
+
|
|
2210
|
+
var value = ${w}(${u});
|
|
2211
|
+
var pad = 0;
|
|
2212
|
+
var isPad = false;
|
|
2213
|
+
|
|
2214
|
+
for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {
|
|
2215
|
+
var offset = i;
|
|
2216
|
+
for (var j = 0u; j < ${x-1}u; j++) {
|
|
2217
|
+
offsets[j] = offset / ${H("uniforms.kernelStrides","j",x)};
|
|
2218
|
+
offset -= offsets[j] * ${H("uniforms.kernelStrides","j",x)};
|
|
2219
|
+
}
|
|
2220
|
+
offsets[${x-1}] = offset;
|
|
2221
|
+
|
|
2222
|
+
isPad = false;
|
|
2223
|
+
for (var j = ${r-x}u; j < ${r}u; j++) {
|
|
2224
|
+
xIndices[j] = indices[j] * ${H("uniforms.strides",`j - ${r-x}u`,x)}
|
|
2225
|
+
+ offsets[j - ${r-x}u] - ${H("uniforms.pads","j - 2u",R)};
|
|
2226
|
+
${C}
|
|
2227
|
+
}
|
|
2228
|
+
${l}
|
|
2229
|
+
|
|
2230
|
+
output[global_idx] = value;
|
|
2231
|
+
}`}},ia=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,jd=e=>`${ia(e)};${e.countIncludePad}`,Kd=e=>`${ia(e)};${e.storageOrder};${e.dilations}`,na=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),aa=(e,t,r,i)=>{let[a,o]=ta(t,i,r),l=U("x",t.dataType,t.dims.length),u=l.type.value,c="value += x_val;",h="";a.countIncludePad?h+=`value /= ${u}(uniforms.kernelSize);`:h+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[p,m,y,w,v]=ra(o,a);p.push(...D(t.dims,o));let x=["rank"];return{name:e,shaderCache:{hint:`${i.cacheKey};${y};${w};${v}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(q.size(o)/64)},programUniforms:p}),getShaderSource:R=>sa(R,l,t.dims.length,o.length,a,c,h,0,m,y,w,v)}},Qd=e=>{let t=e.count_include_pad!==0,r=na(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let i={countIncludePad:t,...r,cacheKey:""};return{...i,cacheKey:jd(i)}},Xd=(e,t)=>{ki(e.inputs),e.compute(aa("AveragePool",e.inputs[0],!1,t))},oa={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Zd=e=>{let t=e.format;return{format:t,...oa,cacheKey:t}},Jd=(e,t)=>{ki(e.inputs),e.compute(aa("GlobalAveragePool",e.inputs[0],!0,t))},la=(e,t,r,i)=>{let[a,o]=ta(t,i,r),l=`
|
|
2232
|
+
value = max(x_val, value);
|
|
2233
|
+
`,u="",c=U("x",t.dataType,t.dims.length),h=["rank"],[p,m,y,w,v]=ra(o,a);return p.push(...D(t.dims,o)),{name:e,shaderCache:{hint:`${i.cacheKey};${y};${w};${v}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(q.size(o)/64)},programUniforms:p}),getShaderSource:x=>sa(x,c,t.dims.length,o.length,a,l,u,t.dataType===10?-65504:-1e5,m,y,w,v)}},Yd=(e,t)=>{ki(e.inputs),e.compute(la("MaxPool",e.inputs[0],!1,t))},ec=e=>{let t=e.storage_order,r=e.dilations,i=na(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(i.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let a={storageOrder:t,dilations:r,...i,cacheKey:""};return{...a,cacheKey:Kd(a)}},tc=e=>{let t=e.format;return{format:t,...oa,cacheKey:t}},rc=(e,t)=>{ki(e.inputs),e.compute(la("GlobalMaxPool",e.inputs[0],!0,t))}}),sc,ic,nc,ac,zm=T(()=>{Ee(),xe(),k(),he(),sc=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,i)=>r===e[2].dims[i]).reduce((r,i)=>r&&i,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((a,o)=>o===t.axis||a===e[0].dims[o]).reduce((a,o)=>a&&o,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],i=e[1].dims[t.axis];if(t.blockSize<Math.ceil(r/i)||t.blockSize>Math.ceil(r/(i-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},ic=(e,t)=>{let r=q.normalizeAxis(t.axis,e[0].dims.length),i=e[0].dataType,a=i===3,o=e[0].dims,l=e[1].dataType,u=q.size(o),c=i===3||i===2,h=c?[Math.ceil(q.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,m=e.length>2?e[2]:void 0,y=m?c?[Math.ceil(q.size(m.dims)/4)]:m.dims:void 0,w=p.length===0||p.length===1&&p[0]===1,v=w===!1&&p.length===1,x=F(u),R=w&&(!c||x===4),C=R?x:1,$=R&&!c?x:1,I=U("input",c?12:i,h.length,$),M=U("scale",l,p.length),L=m?U("zero_point",c?12:i,y.length):void 0,V=te("output",l,o.length,C),W=[I,M];L&&W.push(L);let X=[h,p];m&&X.push(y);let se=[{type:12,data:u/C},{type:12,data:r},{type:12,data:t.blockSize},...D(...X,o)],ge=Be=>{let Te=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
2234
|
+
${Be.registerUniforms(Te).declareVariables(...W,V)}
|
|
2235
|
+
${Be.mainStart()}
|
|
2236
|
+
${Be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2237
|
+
let output_indices = ${V.offsetToIndices("global_idx")};
|
|
2238
|
+
|
|
2239
|
+
// Set input x
|
|
2240
|
+
${c?`
|
|
2241
|
+
let input = ${I.getByOffset("global_idx / 4")};
|
|
2242
|
+
let x_vec = ${a?"unpack4xI8(input)":"unpack4xU8(input)"};
|
|
2243
|
+
let x_value = ${C===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${I.getByOffset("global_idx")};`};
|
|
2244
|
+
|
|
2245
|
+
// Set scale input
|
|
2246
|
+
${w?`let scale_value= ${M.getByOffset("0")}`:v?`
|
|
2247
|
+
let scale_index = ${V.indicesGet("output_indices","uniforms.axis")};
|
|
2248
|
+
let scale_value= ${M.getByOffset("scale_index")};`:`
|
|
2249
|
+
var scale_indices: ${M.type.indices} = output_indices;
|
|
2250
|
+
let index = ${M.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size;
|
|
2251
|
+
${M.indicesSet("scale_indices","uniforms.axis","index")};
|
|
2252
|
+
let scale_value= ${M.getByIndices("scale_indices")};`};
|
|
2253
|
+
|
|
2254
|
+
// Set zero-point input
|
|
2255
|
+
${L?w?c?`
|
|
2256
|
+
let zero_point_input = ${L.getByOffset("0")};
|
|
2257
|
+
let zero_point_vec = ${a?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2258
|
+
let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${L.getByOffset("0")}`:v?c?`
|
|
2259
|
+
let zero_point_index = ${V.indicesGet("output_indices","uniforms.axis")};
|
|
2260
|
+
let zero_point_input = ${L.getByOffset("zero_point_index / 4")};
|
|
2261
|
+
let zero_point_vec = ${a?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2262
|
+
let zero_point_value = zero_point_vec[zero_point_index % 4]`:`
|
|
2263
|
+
let zero_point_index = ${V.indicesGet("output_indices","uniforms.axis")};
|
|
2264
|
+
let zero_point_value = ${L.getByOffset("zero_point_index")};`:c?`
|
|
2265
|
+
let zero_point_offset = ${M.indicesToOffset("scale_indices")};
|
|
2266
|
+
let zero_point_input = ${L.getByOffset("zero_point_offset / 4")};
|
|
2267
|
+
let zero_point_vec = ${a?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2268
|
+
let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${L.getByIndices("scale_indices")};`:`let zero_point_value = ${c?a?"i32":"u32":I.type.value}(0);`};
|
|
2269
|
+
// Compute and write output
|
|
2270
|
+
${V.setByOffset("global_idx",`${V.type.value}(x_value - zero_point_value) * scale_value`)};
|
|
2271
|
+
}`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:L?["rank","rank","rank"]:["rank","rank"]},getShaderSource:ge,getRunData:()=>({outputs:[{dims:o,dataType:l}],dispatchGroup:{x:Math.ceil(u/C/64),y:1,z:1},programUniforms:se})}},nc=(e,t)=>{sc(e.inputs,t),e.compute(ic(e.inputs,t))},ac=e=>_({axis:e.axis,blockSize:e.blockSize})}),oc,lc,uc,Dm=T(()=>{wt(),Ee(),he(),oc=(e,t,r)=>{let i=e===t,a=e<t&&r<0,o=e>t&&r>0;if(i||a||o)throw new Error("Range these inputs' contents are invalid.")},lc=(e,t,r,i)=>{let a=Math.abs(Math.ceil((t-e)/r)),o=[a],l=a,u=[{type:12,data:l},{type:i,data:e},{type:i,data:r},...D(o)],c=h=>{let p=te("output",i,o.length),m=p.type.value,y=[{name:"outputSize",type:"u32"},{name:"start",type:m},{name:"delta",type:m}];return`
|
|
2272
|
+
${h.registerUniforms(y).declareVariables(p)}
|
|
2273
|
+
${h.mainStart()}
|
|
2274
|
+
${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2275
|
+
output[global_idx] = uniforms.start + ${m}(global_idx) * uniforms.delta;
|
|
2276
|
+
}`};return{name:"Range",shaderCache:{hint:`${i}`},getShaderSource:c,getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u})}},uc=e=>{let t=0,r=0,i=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],i=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],i=e.inputs[2].getFloat32Array()[0]),de.webgpu.validateInputContent&&oc(t,r,i),e.compute(lc(t,r,i,e.inputs[0].dataType),{inputs:[]})}}),dc,cc,hc,pc,Lm=T(()=>{Ee(),xe(),k(),he(),dc=(e,t,r,i)=>{if(e!=="none"&&i!=="i32"&&i!=="u32"&&i!=="f32")throw new Error(`Input ${i} is not supported with reduction ${e}.`);let a=`{
|
|
2277
|
+
var oldValue = 0;
|
|
2278
|
+
loop {
|
|
2279
|
+
let newValueF32 =`,o=`;
|
|
2280
|
+
let newValue = bitcast<i32>(newValueF32);
|
|
2281
|
+
let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue);
|
|
2282
|
+
if res.exchanged {
|
|
2283
|
+
break;
|
|
2284
|
+
}
|
|
2285
|
+
oldValue = res.old_value;
|
|
2286
|
+
}
|
|
2287
|
+
}`;switch(e){case"none":return`${t}=${r};`;case"add":return i==="i32"||i==="u32"?`atomicAdd(&${t}, bitcast<${i}>(${r}));`:`
|
|
2288
|
+
${a}bitcast<${i}>(oldValue) + (${r})${o}`;case"max":return i==="i32"||i==="u32"?`atomicMax(&${t}, bitcast<${i}>(${r}));`:`
|
|
2289
|
+
${a}max(bitcast<f32>(oldValue), (${r}))${o}`;case"min":return i==="i32"||i==="u32"?`atomicMin(&${t}, bitcast<${i}>(${r}));`:`${a}min(bitcast<${i}>(oldValue), (${r}))${o}`;case"mul":return`${a}(bitcast<${i}>(oldValue) * (${r}))${o}`;default:throw new Error(`Reduction ${e} is not supported.`)}},cc=(e,t)=>{let r=e[0].dims,i=e[1].dims,a=r,o=1,l=Math.ceil(q.sizeToDimension(i,i.length-1)/o),u=i[i.length-1],c=q.sizeFromDimension(r,u),h=[{type:12,data:l},{type:12,data:u},{type:12,data:c},...D(e[1].dims,e[2].dims,a)],p=m=>{let y=U("indices",e[1].dataType,e[1].dims.length),w=U("updates",e[2].dataType,e[2].dims.length,o),v=t.reduction!=="none"&&t.reduction!==""?tt("output",e[0].dataType,a.length):te("output",e[0].dataType,a.length,o);return`
|
|
2290
|
+
${m.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(y,w,v)}
|
|
2291
|
+
${m.mainStart()}
|
|
2292
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2293
|
+
var data_offset = 0u;
|
|
2294
|
+
let indices_start = uniforms.last_index_dimension * global_idx;
|
|
2295
|
+
let indices_end = indices_start + uniforms.last_index_dimension;
|
|
2296
|
+
for (var i = indices_start; i < indices_end; i++) {
|
|
2297
|
+
var index = i32(indices[i].x);
|
|
2298
|
+
${e[0].dims.length===1?`
|
|
2299
|
+
let element_count_dim = uniforms.output_strides;
|
|
2300
|
+
let dim_value = uniforms.output_shape;`:`
|
|
2301
|
+
let element_count_dim = uniforms.output_strides[i - indices_start];
|
|
2302
|
+
let dim_value = uniforms.output_shape[i - indices_start];`}
|
|
2303
|
+
if (index >= 0) {
|
|
2304
|
+
if (index >= i32(dim_value)) {
|
|
2305
|
+
index = i32(dim_value - 1);
|
|
2306
|
+
}
|
|
2307
|
+
} else {
|
|
2308
|
+
if (index < -i32(dim_value)) {
|
|
2309
|
+
index = 0;
|
|
2310
|
+
} else {
|
|
2311
|
+
index += i32(dim_value);
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
data_offset += u32((u32(index) * element_count_dim));
|
|
2315
|
+
}
|
|
2316
|
+
|
|
2317
|
+
for (var i = 0u; i < uniforms.num_updates_elements; i++) {
|
|
2318
|
+
let value = updates[uniforms.num_updates_elements * global_idx + i];
|
|
2319
|
+
${dc(t.reduction,"output[data_offset + i]","value",v.type.value)}
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
}`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:h}),getShaderSource:p}},hc=e=>_({reduction:e.reduction}),pc=(e,t)=>{e.compute(cc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),mc,fc,gc,ua,yc,wc,vc,bc,_c,Sc,$c,xc,da,Tc,Cc,Ec,kc,Mc,Rc,Ic,Bm=T(()=>{Ee(),xe(),k(),he(),mc=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and
|
|
2323
|
+
one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},fc=(e,t,r)=>{t.every(a=>a>=0&&a<r||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")}));let i=new Array(r).fill(1);return t.forEach((a,o)=>i[a]=e[o]),i},gc=(e,t,r,i,a,o)=>{let[l,u,c]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(l>0&&e.length>l&&e[l].dims.length>0)e[l].getFloat32Array().forEach(p=>o.push(p));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&e.length>u&&e[u].dims.length===1&&e[u].dims[0]>0){if(e[u].getFloat32Array().forEach(p=>i.push(p)),i.length!==0&&i.length!==h&&r>=18&&i.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");mc(i,t),t.axes.length>0&&fc(i,t.axes,h).forEach((p,m)=>i[m]=p)}if(c>0&&e.length>c&&e[c].dims.length===1&&e[c].dims[0]>0&&(e[c].getBigInt64Array().forEach(p=>a.push(Number(p))),a.length!==0&&a.length!==h&&r>=18&&a.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(i.length!==0&&i.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(a.length!==0&&a.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof i<"u"&&typeof a<"u"&&i.length>0&&a.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},ua=(e,t,r,i)=>`
|
|
2324
|
+
// The whole part and the fractional part are calculated separately due to inaccuracy of floating
|
|
2325
|
+
// point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
|
|
2326
|
+
// offset-by-one error later in floor().
|
|
2327
|
+
let big = (${e}) * (${t});
|
|
2328
|
+
let whole = ${i}(big / (${r}));
|
|
2329
|
+
let fract = ${i}(big % (${r})) / ${i}(${r});
|
|
2330
|
+
return whole + fract;
|
|
2331
|
+
`,yc=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,
|
|
2332
|
+
lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`
|
|
2333
|
+
if (xScale < 1.0 || floor(xScale) != xScale) {
|
|
2334
|
+
return ${t}(xResized) / ${t}(xScale);
|
|
2335
|
+
} else {
|
|
2336
|
+
${ua("xResized","lengthOriginal","lengthResized",t)}
|
|
2337
|
+
}
|
|
2338
|
+
`;case"pytorch_half_pixel":return`if (lengthResized > 1) {
|
|
2339
|
+
return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;
|
|
2340
|
+
} else {
|
|
2341
|
+
return 0.0;
|
|
2342
|
+
}`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {
|
|
2343
|
+
return 0.0;
|
|
2344
|
+
} else {
|
|
2345
|
+
${ua("xResized","lengthOriginal - 1","lengthResized - 1",t)}
|
|
2346
|
+
}`;case"tf_crop_and_resize":return`if (lengthResized > 1) {
|
|
2347
|
+
return ${t}(roiStart) * ${t}(lengthOriginal - 1) +
|
|
2348
|
+
(${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /
|
|
2349
|
+
${t}(lengthResized - 1);
|
|
2350
|
+
} else {
|
|
2351
|
+
return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);
|
|
2352
|
+
}`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);
|
|
2353
|
+
const adjustment = ${t}(lengthResized) / outputWidth;
|
|
2354
|
+
const center = ${t}(lengthOriginal) / 2;
|
|
2355
|
+
const offset = center * (1 - adjustment);
|
|
2356
|
+
return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",wc=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",vc=(e,t,r)=>{let i=new Array(r).fill(0).concat(new Array(r).fill(1)),a=e.length===0?i:e.slice();return t.length>0?(t.forEach((o,l)=>{i[o]=a[l],i[l+r]=a[t.length+l]}),i):a},bc=(e,t,r,i)=>{let a=[];if(r.length>0)if(i.length>0){if(e.forEach(o=>a.push(o)),Math.max(...i)>e.length)throw new Error("axes is out of bound");i.forEach((o,l)=>a[o]=r[l])}else r.forEach(o=>a.push(o));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");a=e.map((o,l)=>Math.round(o*t[l]))}return a},_c=(e,t,r)=>{let i=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(o=>t[o]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(o=>t[o]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let a=e.slice();return r.axes.length>0?(r.axes.forEach(o=>t[o]=i),r.axes.forEach(o=>a[o]=Math.round(e[o]*t[o]))):(t.fill(i,0,t.length),a.forEach((o,l)=>a[l]=Math.round(o*t[l]))),a},Sc=(e,t,r,i,a)=>`
|
|
2357
|
+
fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {
|
|
2358
|
+
var original_indices: array<${e.type.value}, ${r.length}>;
|
|
2359
|
+
for (var i:u32 = 0; i < ${r.length}; i++) {
|
|
2360
|
+
var output_index = ${e.indicesGet("output_indices","i")};
|
|
2361
|
+
var scale = ${H("uniforms.scales","i",i)};
|
|
2362
|
+
var roi_low = ${H("uniforms.roi","i",a)};
|
|
2363
|
+
var roi_hi = ${H("uniforms.roi",`i + ${t.length}`,a)};
|
|
2364
|
+
if (scale == 1.0) {
|
|
2365
|
+
original_indices[i] = ${e.type.value}(output_index);
|
|
2366
|
+
} else {
|
|
2367
|
+
var input_shape_i = ${H("uniforms.input_shape","i",t.length)};
|
|
2368
|
+
var output_shape_i = ${H("uniforms.output_shape","i",r.length)};
|
|
2369
|
+
original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
|
|
2370
|
+
input_shape_i, roi_low, roi_hi);
|
|
2371
|
+
}
|
|
2372
|
+
}
|
|
2373
|
+
return original_indices;
|
|
2374
|
+
}`,$c=(e,t,r,i,a,o,l)=>`
|
|
2375
|
+
fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
|
|
2376
|
+
var input_indices: ${e.type.indices};
|
|
2377
|
+
for (var i:u32 = 0; i < ${i.length}; i++) {
|
|
2378
|
+
var output_index = ${t.indicesGet("output_indices","i")};
|
|
2379
|
+
var input_index: u32;
|
|
2380
|
+
var scale = ${H("uniforms.scales","i",a)};
|
|
2381
|
+
if (scale == 1.0) {
|
|
2382
|
+
input_index = output_index;
|
|
2383
|
+
} else {
|
|
2384
|
+
var roi_low = ${H("uniforms.roi","i",o)};
|
|
2385
|
+
var roi_hi = ${H("uniforms.roi",`i + ${r.length}`,o)};
|
|
2386
|
+
var input_shape_i = ${H("uniforms.input_shape","i",r.length)};
|
|
2387
|
+
var output_shape_i = ${H("uniforms.output_shape","i",i.length)};
|
|
2388
|
+
var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
|
|
2389
|
+
input_shape_i, roi_low, roi_hi);
|
|
2390
|
+
if (!${l} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {
|
|
2391
|
+
if (original_idx < 0) {
|
|
2392
|
+
input_index = 0;
|
|
2393
|
+
} else if (original_idx > ${t.type.value}(input_shape_i - 1)) {
|
|
2394
|
+
input_index = input_shape_i - 1;
|
|
2395
|
+
} else {
|
|
2396
|
+
input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));
|
|
2397
|
+
}
|
|
2398
|
+
} else {
|
|
2399
|
+
input_index = u32(original_idx);
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
${e.indicesSet("input_indices","i","input_index")}
|
|
2403
|
+
}
|
|
2404
|
+
return input_indices;
|
|
2405
|
+
}`,xc=(e,t)=>`
|
|
2406
|
+
fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {
|
|
2407
|
+
for (var i:u32 = 0; i < ${t.length}; i++) {
|
|
2408
|
+
var input_index = ${e.indicesGet("input_indices","i")};
|
|
2409
|
+
if (input_index < 0 || input_index >= ${H("uniforms.input_shape","i",t.length)}) {
|
|
2410
|
+
return false;
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
return true;
|
|
2414
|
+
}`,da=(e,t,r,i)=>e.rank>i?`
|
|
2415
|
+
${e.indicesSet("input_indices",t,"channel")};
|
|
2416
|
+
${e.indicesSet("input_indices",r,"batch")};
|
|
2417
|
+
`:"",Tc=(e,t,r,i,a)=>{let[o,l,u,c]=r.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return`
|
|
2418
|
+
fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} {
|
|
2419
|
+
var input_indices: ${e.type.indices};
|
|
2420
|
+
${e.indicesSet("input_indices",l,`max(0, min(row, ${r[l]} - 1))`)};
|
|
2421
|
+
${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)};
|
|
2422
|
+
${da(e,c,o,2)}
|
|
2423
|
+
return ${e.getByIndices("input_indices")};
|
|
2424
|
+
}
|
|
2425
|
+
|
|
2426
|
+
fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} {
|
|
2427
|
+
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
|
|
2428
|
+
var row:${h} = originalIndices[${l}];
|
|
2429
|
+
var col:${h} = originalIndices[${u}];
|
|
2430
|
+
${i?`if (row < 0 || row > (${r[l]} - 1) || col < 0 || col > (${r[u]} - 1)) {
|
|
2431
|
+
return ${a};
|
|
2432
|
+
}`:""};
|
|
2433
|
+
row = max(0, min(row, ${r[l]} - 1));
|
|
2434
|
+
col = max(0, min(col, ${r[u]} - 1));
|
|
2435
|
+
var row1: u32 = u32(row);
|
|
2436
|
+
var col1: u32 = u32(col);
|
|
2437
|
+
var row2: u32 = u32(row + 1);
|
|
2438
|
+
var col2: u32 = u32(col + 1);
|
|
2439
|
+
var channel: u32 = ${r.length>2?`u32(originalIndices[${c}])`:"0"};
|
|
2440
|
+
var batch: u32 = ${r.length>2?`u32(originalIndices[${o}])`:"0"};
|
|
2441
|
+
var x11: ${h} = getInputValue(batch, channel, row1, col1);
|
|
2442
|
+
var x12: ${h} = getInputValue(batch, channel, row1, col2);
|
|
2443
|
+
var x21: ${h} = getInputValue(batch, channel, row2, col1);
|
|
2444
|
+
var x22: ${h} = getInputValue(batch, channel, row2, col2);
|
|
2445
|
+
var dx1: ${h} = abs(row - ${h}(row1));
|
|
2446
|
+
var dx2: ${h} = abs(${h}(row2) - row);
|
|
2447
|
+
var dy1: ${h} = abs(col - ${h}(col1));
|
|
2448
|
+
var dy2: ${h} = abs(${h}(col2) - col);
|
|
2449
|
+
if (row1 == row2) {
|
|
2450
|
+
dx1 = 0.5;
|
|
2451
|
+
dx2 = 0.5;
|
|
2452
|
+
}
|
|
2453
|
+
if (col1 == col2) {
|
|
2454
|
+
dy1 = 0.5;
|
|
2455
|
+
dy2 = 0.5;
|
|
2456
|
+
}
|
|
2457
|
+
return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);
|
|
2458
|
+
}`},Cc=(e,t,r,i,a,o,l,u,c,h)=>{let p=r.length===2,[m,y]=p?[0,1]:[2,3],w=e.type.value,v=x=>{let R=x===m?"row":"col";return`
|
|
2459
|
+
fn ${R}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${w} {
|
|
2460
|
+
var output_index = ${t.indicesGet("output_indices",x)};
|
|
2461
|
+
var originalIdx: ${w} = getOriginalCoordinateFromResizedCoordinate(output_index, ${a[x]},
|
|
2462
|
+
${i[x]}, ${r[x]}, ${o[x]}, ${o[x]} + ${r.length});
|
|
2463
|
+
var fractOriginalIdx: ${w} = originalIdx - floor(originalIdx);
|
|
2464
|
+
var coefs = getCubicInterpolationCoefs(fractOriginalIdx);
|
|
2465
|
+
|
|
2466
|
+
if (${u} && (originalIdx < 0 || originalIdx > (${r[x]} - 1))) {
|
|
2467
|
+
return ${c};
|
|
2468
|
+
}
|
|
2469
|
+
var data: array<${w}, 4> = array<${w}, 4>(0.0, 0.0, 0.0, 0.0);
|
|
2470
|
+
for (var i: i32 = -1; i < 3; i++) {
|
|
2471
|
+
var ${R}: ${w} = originalIdx + ${w}(i);
|
|
2472
|
+
if (${R} < 0 || ${R} >= ${r[x]}) {
|
|
2473
|
+
${h?`coefs[i + 1] = 0.0;
|
|
2474
|
+
continue;`:u?`return ${c};`:`${R} = max(0, min(${R}, ${r[x]} - 1));`};
|
|
2475
|
+
}
|
|
2476
|
+
var input_indices_copy: ${e.type.indices} = input_indices;
|
|
2477
|
+
${e.indicesSet("input_indices_copy",x,`u32(${R})`)};
|
|
2478
|
+
data[i + 1] = ${x===m?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};
|
|
2479
|
+
}
|
|
2480
|
+
return cubicInterpolation1D(data, coefs);
|
|
2481
|
+
}`};return`
|
|
2482
|
+
${v(m)};
|
|
2483
|
+
${v(y)};
|
|
2484
|
+
fn getCubicInterpolationCoefs(s: ${w}) -> array<${w}, 4> {
|
|
2485
|
+
var absS = abs(s);
|
|
2486
|
+
var coeffs: array<${w}, 4> = array<${w}, 4>(0.0, 0.0, 0.0, 0.0);
|
|
2487
|
+
var oneMinusAbsS: ${w} = 1.0 - absS;
|
|
2488
|
+
var twoMinusAbsS: ${w} = 2.0 - absS;
|
|
2489
|
+
var onePlusAbsS: ${w} = 1.0 + absS;
|
|
2490
|
+
coeffs[0] = ((${l} * onePlusAbsS - 5 * ${l}) * onePlusAbsS + 8 * ${l}) * onePlusAbsS - 4 * ${l};
|
|
2491
|
+
coeffs[1] = ((${l} + 2) * absS - (${l} + 3)) * absS * absS + 1;
|
|
2492
|
+
coeffs[2] = ((${l} + 2) * oneMinusAbsS - (${l} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;
|
|
2493
|
+
coeffs[3] = ((${l} * twoMinusAbsS - 5 * ${l}) * twoMinusAbsS + 8 * ${l}) * twoMinusAbsS - 4 * ${l};
|
|
2494
|
+
return coeffs;
|
|
2495
|
+
}
|
|
2496
|
+
|
|
2497
|
+
fn cubicInterpolation1D(x: array<${w}, 4>, coefs: array<${w}, 4>) -> ${w} {
|
|
2498
|
+
var coefsSum: ${w} = coefs[0] + coefs[1] + coefs[2] + coefs[3];
|
|
2499
|
+
return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2502
|
+
fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${w} {
|
|
2503
|
+
var input_indices: ${e.type.indices} = output_indices;
|
|
2504
|
+
return colCubicInterpolation(input_indices, output_indices);
|
|
2505
|
+
}
|
|
2506
|
+
`},Ec=(e,t,r,i,a)=>{let[o,l,u,c,h]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return`
|
|
2507
|
+
fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} {
|
|
2508
|
+
var input_indices: ${e.type.indices};
|
|
2509
|
+
${e.indicesSet("input_indices",l,`max(0, min(depth, ${r[l]} - 1))`)};
|
|
2510
|
+
${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)};
|
|
2511
|
+
${e.indicesSet("input_indices",c,`max(0, min(width, ${r[c]} - 1))`)};
|
|
2512
|
+
${da(e,h,o,3)}
|
|
2513
|
+
return ${e.getByIndices("input_indices")};
|
|
2514
|
+
}
|
|
2515
|
+
|
|
2516
|
+
fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} {
|
|
2517
|
+
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
|
|
2518
|
+
var depth:${p} = originalIndices[${l}];
|
|
2519
|
+
var height:${p} = originalIndices[${u}];
|
|
2520
|
+
var width:${p} = originalIndices[${c}];
|
|
2521
|
+
${i?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[c]} - 1)) {
|
|
2522
|
+
return ${a};
|
|
2523
|
+
}`:""};
|
|
2524
|
+
|
|
2525
|
+
depth = max(0, min(depth, ${r[l]} - 1));
|
|
2526
|
+
height = max(0, min(height, ${r[u]} - 1));
|
|
2527
|
+
width = max(0, min(width, ${r[c]} - 1));
|
|
2528
|
+
var depth1: u32 = u32(depth);
|
|
2529
|
+
var height1: u32 = u32(height);
|
|
2530
|
+
var width1: u32 = u32(width);
|
|
2531
|
+
var depth2: u32 = u32(depth + 1);
|
|
2532
|
+
var height2: u32 = u32(height + 1);
|
|
2533
|
+
var width2: u32 = u32(width + 1);
|
|
2534
|
+
var channel: u32 = ${r.length>3?`u32(originalIndices[${h}])`:"0"};
|
|
2535
|
+
var batch: u32 = ${r.length>3?`u32(originalIndices[${o}])`:"0"};
|
|
2536
|
+
|
|
2537
|
+
var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1);
|
|
2538
|
+
var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2);
|
|
2539
|
+
var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1);
|
|
2540
|
+
var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2);
|
|
2541
|
+
var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1);
|
|
2542
|
+
var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2);
|
|
2543
|
+
var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1);
|
|
2544
|
+
var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2);
|
|
2545
|
+
var dx1: ${p} = abs(depth - ${p}(depth1));
|
|
2546
|
+
var dx2: ${p} = abs(${p}(depth2) - depth);
|
|
2547
|
+
var dy1: ${p} = abs(height - ${p}(height1));
|
|
2548
|
+
var dy2: ${p} = abs(${p}(height2) - height);
|
|
2549
|
+
var dz1: ${p} = abs(width - ${p}(width1));
|
|
2550
|
+
var dz2: ${p} = abs(${p}(width2) - width);
|
|
2551
|
+
if (depth1 == depth2) {
|
|
2552
|
+
dx1 = 0.5;
|
|
2553
|
+
dx2 = 0.5;
|
|
2554
|
+
}
|
|
2555
|
+
if (height1 == height2) {
|
|
2556
|
+
dy1 = 0.5;
|
|
2557
|
+
dy2 = 0.5;
|
|
2558
|
+
}
|
|
2559
|
+
if (width1 == width2) {
|
|
2560
|
+
dz1 = 0.5;
|
|
2561
|
+
dz2 = 0.5;
|
|
2562
|
+
}
|
|
2563
|
+
return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +
|
|
2564
|
+
x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);
|
|
2565
|
+
}`},kc=(e,t,r,i,a,o)=>{let l=e.dims,u=vc(o,t.axes,l.length),c=bc(l,i,a,t.axes),h=i.slice();i.length===0&&(h=l.map(($,I)=>$===0?1:c[I]/$),t.keepAspectRatioPolicy!=="stretch"&&(c=_c(l,h,t)));let p=te("output",e.dataType,c.length),m=U("input",e.dataType,l.length),y=q.size(c),w=l.length===c.length&&l.every(($,I)=>$===c[I]),v=t.coordinateTransformMode==="tf_crop_and_resize",x=t.extrapolationValue,R=m.type.value,C=$=>`
|
|
2566
|
+
${w?"":`
|
|
2567
|
+
${yc(t.coordinateTransformMode,R)};
|
|
2568
|
+
${(()=>{switch(t.mode){case"nearest":return`
|
|
2569
|
+
${xc(m,l)};
|
|
2570
|
+
${wc(t.nearestMode,r,R)};
|
|
2571
|
+
${$c(m,p,l,c,h.length,u.length,v)};
|
|
2572
|
+
`;case"linear":return`
|
|
2573
|
+
${Sc(p,l,c,h.length,u.length)};
|
|
2574
|
+
${(()=>{if(l.length===2||l.length===4)return`${Tc(m,p,l,v,x)}`;if(l.length===3||l.length===5)return`${Ec(m,p,l,v,x)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};
|
|
2575
|
+
`;case"cubic":return`
|
|
2576
|
+
${(()=>{if(l.length===2||l.length===4)return`${Cc(m,p,l,c,h,u,t.cubicCoeffA,v,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};
|
|
2577
|
+
`;default:throw Error("Invalid resize mode")}})()};
|
|
2578
|
+
`}
|
|
2579
|
+
${$.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",u.length).declareVariables(m,p)}
|
|
2580
|
+
${$.mainStart()}
|
|
2581
|
+
${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2582
|
+
${w?"output[global_idx] = input[global_idx];":`
|
|
2583
|
+
let output_indices = ${p.offsetToIndices("global_idx")};
|
|
2584
|
+
var input_indices: ${m.type.indices};
|
|
2585
|
+
${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);
|
|
2586
|
+
if (checkInputIndices(input_indices)) {
|
|
2587
|
+
output[global_idx] = ${m.getByIndices("input_indices")};
|
|
2588
|
+
} else {
|
|
2589
|
+
output[global_idx] = ${t.extrapolationValue};
|
|
2590
|
+
}`;case"linear":return`output[global_idx] = ${l.length===2||l.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};
|
|
2591
|
+
`}
|
|
2592
|
+
}`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${h.length>0?t.mode==="cubic"?h:h.length:""}|${a.length>0?a:""}|${u.length>0?u:""}|${w}|${t.mode==="nearest"?l.length:l}`,inputDependencies:["rank"]},getShaderSource:C,getRunData:()=>({outputs:[{dims:c,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},{type:1,data:h},{type:1,data:u},...D(l,c)]})}},Mc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Rc=(e,t)=>{let r=[],i=[],a=[],o=Mc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");gc(e.inputs,t,o,r,i,a),e.compute(kc(e.inputs[0],t,o,r,i,a),{inputs:[0]})},Ic=e=>{let t=e.antialias,r=e.axes,i=e.coordinateTransformMode,a=e.cubicCoeffA,o=e.excludeOutside!==0,l=e.extrapolationValue,u=e.keepAspectRatioPolicy,c=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return _({antialias:t,axes:r,coordinateTransformMode:i,cubicCoeffA:a,excludeOutside:o,extrapolationValue:l,keepAspectRatioPolicy:u,mode:c,nearestMode:h})}}),Ac,Pc,Oc,Um=T(()=>{Ee(),xe(),he(),Ac=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],i=e[2];if(t.dataType!==r.dataType||t.dataType!==i.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let a=t.dims[t.dims.length-1],o=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==a)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==o)throw new Error("Skip must have the same sequence length as input");if(i.dims.length!==1)throw new Error("Gamma must be 1D");if(i.dims[i.dims.length-1]!==a)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let l=e[3];if(l.dims.length!==1)throw new Error("Beta must be 1D");if(l.dims[l.dims.length-1]!==a)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let l=e[4];if(l.dims.length!==1)throw new Error("Bias must be 1D");if(l.dims[l.dims.length-1]!==a)throw new Error("Bias must have the same hidden size as input")}},Pc=(e,t,r,i)=>{let a=t.simplified,o=e[0].dims,l=q.size(o),u=o,c=l,h=o.slice(-1)[0],p=i?o.slice(0,-1).concat(1):[],m=!a&&e.length>3,y=e.length>4,w=i&&r>1,v=i&&r>2,x=r>3,R=64,C=F(h),$=[{type:12,data:c},{type:12,data:C},{type:12,data:h},{type:1,data:t.epsilon}],I=L=>{let V=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],W=[U("x",e[0].dataType,e[0].dims,C),U("skip",e[1].dataType,e[1].dims,C),U("gamma",e[2].dataType,e[2].dims,C)];m&&W.push(U("beta",e[3].dataType,e[3].dims,C)),y&&W.push(U("bias",e[4].dataType,e[4].dims,C)),W.push(te("output",e[0].dataType,u,C)),w&&W.push(te("mean_output",1,p)),v&&W.push(te("inv_std_output",1,p)),x&&W.push(te("input_skip_bias_sum",e[0].dataType,u,C));let X=N(e[0].dataType),se=N(1,C);return`
|
|
2593
|
+
|
|
2594
|
+
${L.registerUniforms(V).declareVariables(...W)}
|
|
2595
|
+
var<workgroup> sum_shared : array<${se}, ${R}>;
|
|
2596
|
+
var<workgroup> sum_squared_shared : array<${se}, ${R}>;
|
|
2597
|
+
|
|
2598
|
+
${L.mainStart([R,1,1])}
|
|
2599
|
+
let ix = local_id.x;
|
|
2600
|
+
let iy = global_id.x / ${R};
|
|
2601
|
+
|
|
2602
|
+
let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;
|
|
2603
|
+
var stride = hidden_size_vectorized / ${R};
|
|
2604
|
+
let offset = ix * stride + iy * hidden_size_vectorized;
|
|
2605
|
+
let offset1d = stride * ix;
|
|
2606
|
+
if (ix == ${R-1}) {
|
|
2607
|
+
stride = hidden_size_vectorized - stride * ix;
|
|
2608
|
+
}
|
|
2609
|
+
for (var i: u32 = 0; i < stride; i++) {
|
|
2610
|
+
let skip_value = skip[offset + i];
|
|
2611
|
+
let bias_value = ${y?"bias[offset1d + i]":X+"(0.0)"};
|
|
2612
|
+
let input_value = x[offset + i];
|
|
2613
|
+
let value = input_value + skip_value + bias_value;
|
|
2614
|
+
${x?"input_skip_bias_sum[offset + i] = value;":""}
|
|
2615
|
+
output[offset + i] = value;
|
|
2616
|
+
let f32_value = ${Y(X,C,"value")};
|
|
2617
|
+
sum_shared[ix] += f32_value;
|
|
2618
|
+
sum_squared_shared[ix] += f32_value * f32_value;
|
|
2619
|
+
}
|
|
2620
|
+
workgroupBarrier();
|
|
2621
|
+
|
|
2622
|
+
var reduce_size : u32 = ${R};
|
|
2623
|
+
for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {
|
|
2624
|
+
reduce_size = curr_size + (reduce_size & 1);
|
|
2625
|
+
if (ix < curr_size) {
|
|
2626
|
+
sum_shared[ix] += sum_shared[ix + reduce_size];
|
|
2627
|
+
sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];
|
|
2628
|
+
}
|
|
2629
|
+
workgroupBarrier();
|
|
2630
|
+
}
|
|
2631
|
+
|
|
2632
|
+
let sum = sum_shared[0];
|
|
2633
|
+
let square_sum = sum_squared_shared[0];
|
|
2634
|
+
let mean = ${Q("sum",C)} / f32(uniforms.hidden_size);
|
|
2635
|
+
let inv_std_dev = inverseSqrt(${Q("square_sum",C)} / f32(uniforms.hidden_size) ${a?"":"- mean * mean"} + uniforms.epsilon);
|
|
2636
|
+
${w?"mean_output[global_idx] = mean;":""}
|
|
2637
|
+
${v?"inv_std_output[global_idx] = inv_std_dev;":""}
|
|
2638
|
+
|
|
2639
|
+
for (var i: u32 = 0; i < stride; i++) {
|
|
2640
|
+
output[offset + i] = (output[offset + i] ${a?"":`- ${X}(mean)`}) *
|
|
2641
|
+
${X}(inv_std_dev) * gamma[offset1d + i]
|
|
2642
|
+
${m?"+ beta[offset1d + i]":""};
|
|
2643
|
+
}
|
|
2644
|
+
}`},M=[{dims:u,dataType:e[0].dataType}];return r>1&&M.push({dims:p,dataType:1}),r>2&&M.push({dims:p,dataType:1}),r>3&&M.push({dims:o,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${C};${w};${v};${x}`,inputDependencies:e.map((L,V)=>"type")},getShaderSource:I,getRunData:()=>({outputs:M,dispatchGroup:{x:Math.ceil(c/h)},programUniforms:$})}},Oc=(e,t)=>{Ac(e.inputs);let r=[0];e.outputCount>1&&r.push(-3),e.outputCount>2&&r.push(-3),e.outputCount>3&&r.push(3),e.compute(Pc(e.inputs,t,e.outputCount,!1),{outputs:r})}}),zc,Mi,Dc,ca,Lc,Bc,Uc,Fc,Fm=T(()=>{Ee(),xe(),k(),he(),zc=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,i)=>{if(e[i+1].dataType!==6&&e[i+1].dataType!==7)throw new Error(`Input ${i} must be an array of int32 or int64`)})},Mi=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(i=>r.push(Number(i)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(i=>r.push(Number(i)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Dc=(e,t)=>{if(e.length>1){let r=Mi(e,1),i=Mi(e,2),a=Mi(e,3);return a.length===0&&(a=[...Array(e[0].dims.length).keys()]),_({starts:r,ends:i,axes:a})}else return t},ca=(e,t,r,i,a)=>{let o=e;return e<0&&(o+=r[i[t]]),a[t]<0?Math.max(0,Math.min(o,r[i[t]]-1)):Math.max(0,Math.min(o,r[i[t]]))},Lc=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
|
|
2645
|
+
var input_indices: ${e.type.indices};
|
|
2646
|
+
var carry = 0u;
|
|
2647
|
+
for (var i = ${r.length-1}; i >= 0; i--) {
|
|
2648
|
+
let input_shape_i = ${H("uniforms.input_shape","i",r.length)};
|
|
2649
|
+
let steps_i = ${H("uniforms.steps","i",r.length)};
|
|
2650
|
+
let signs_i = ${H("uniforms.signs","i",r.length)};
|
|
2651
|
+
let starts_i = ${H("uniforms.starts","i",r.length)};
|
|
2652
|
+
var output_index = ${t.indicesGet("output_indices","i")};
|
|
2653
|
+
var input_index = output_index * steps_i + starts_i + carry;
|
|
2654
|
+
carry = input_index / input_shape_i;
|
|
2655
|
+
input_index = input_index % input_shape_i;
|
|
2656
|
+
if (signs_i < 0) {
|
|
2657
|
+
input_index = input_shape_i - input_index - 1u + starts_i;
|
|
2658
|
+
}
|
|
2659
|
+
${e.indicesSet("input_indices","i","input_index")};
|
|
2660
|
+
}
|
|
2661
|
+
return input_indices;
|
|
2662
|
+
}`,Bc=(e,t)=>{let r=e[0].dims,i=q.size(r),a=t.axes.length>0?q.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],o=Mi(e,4);o.forEach(C=>C!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(a.length).fill(1));let l=t.starts.map((C,$)=>ca(C,$,r,a,o)),u=t.ends.map((C,$)=>ca(C,$,r,a,o));if(a.length!==l.length||a.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(a.length!==r.length)for(let C=0;C<r.length;++C)a.includes(C)||(l.splice(C,0,0),u.splice(C,0,r[C]),o.splice(C,0,1));let c=o.map(C=>Math.sign(C));o.forEach((C,$,I)=>{if(C<0){let M=(u[$]-l[$])/C,L=l[$],V=L+M*o[$];l[$]=V,u[$]=L,I[$]=-C}});let h=r.slice(0);a.forEach((C,$)=>{h[C]=Math.ceil((u[C]-l[C])/o[C])});let p={dims:h,dataType:e[0].dataType},m=te("output",e[0].dataType,h.length),y=U("input",e[0].dataType,e[0].dims.length),w=q.size(h),v=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:l.length},{name:"signs",type:"i32",length:c.length},{name:"steps",type:"u32",length:o.length}],x=[{type:12,data:w},{type:12,data:l},{type:6,data:c},{type:12,data:o},...D(e[0].dims,h)],R=C=>`
|
|
2663
|
+
${C.registerUniforms(v).declareVariables(y,m)}
|
|
2664
|
+
${Lc(y,m,r)}
|
|
2665
|
+
${C.mainStart()}
|
|
2666
|
+
${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2667
|
+
let output_indices = ${m.offsetToIndices("global_idx")};
|
|
2668
|
+
let input_indices = calculateInputIndices(output_indices);
|
|
2669
|
+
${m.setByOffset("global_idx",y.getByIndices("input_indices"))}
|
|
2670
|
+
}`;return{name:"Slice",shaderCache:{hint:`${c.length}_${l.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:R,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:x})}},Uc=(e,t)=>{zc(e.inputs,t);let r=Dc(e.inputs,t);e.compute(Bc(e.inputs,r),{inputs:[0]})},Fc=e=>{let t=e.starts,r=e.ends,i=e.axes;return _({starts:t,ends:r,axes:i})}}),Nc,Vc,Gc,Wc,Nm=T(()=>{Ee(),xe(),k(),Le(),he(),Nc=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Vc=(e,t)=>{let r=e.inputs[0],i=r.dims,a=q.size(i),o=i.length,l=q.normalizeAxis(t.axis,o),u=l<i.length-1,c,h=[];u?(h=Array.from({length:o},(W,X)=>X),h[l]=o-1,h[o-1]=l,c=e.compute(it(r,h),{inputs:[r],outputs:[-1]})[0]):c=r;let p=c.dims,m=p[o-1],y=a/m,w=F(m),v=m/w,x=64;y===1&&(x=256);let R=(W,X)=>X===4?`max(max(${W}.x, ${W}.y), max(${W}.z, ${W}.w))`:X===2?`max(${W}.x, ${W}.y)`:X===3?`max(max(${W}.x, ${W}.y), ${W}.z)`:W,C=U("x",c.dataType,c.dims,w),$=te("result",c.dataType,c.dims,w),I=C.type.value,M=N(c.dataType)==="f32"?`var threadMax = ${I}(-3.4028234663852886e+38f);`:`var threadMax = ${I}(-65504.0h);`,L=W=>`
|
|
2671
|
+
var<workgroup> rowMaxShared : ${I};
|
|
2672
|
+
var<workgroup> rowSumShared : ${I};
|
|
2673
|
+
var<workgroup> threadShared : array<${I}, ${x}>;
|
|
2674
|
+
|
|
2675
|
+
fn getValue(row: i32, col: i32, row_stride: i32) -> ${I} {
|
|
2676
|
+
let index = row * row_stride + col;
|
|
2677
|
+
return x[index];
|
|
2678
|
+
}
|
|
2679
|
+
|
|
2680
|
+
fn setValue(row: i32, col: i32, row_stride: i32, value: ${I}) {
|
|
2681
|
+
let index = row * row_stride + col;
|
|
2682
|
+
result[index] = value;
|
|
2683
|
+
}
|
|
2684
|
+
${W.registerUniform("packedCols","i32").declareVariables(C,$)}
|
|
2685
|
+
${W.mainStart(x)}
|
|
2686
|
+
let gindex = i32(global_idx);
|
|
2687
|
+
let lindex = i32(local_idx);
|
|
2688
|
+
const wg = ${x};
|
|
2689
|
+
let row = gindex / wg;
|
|
2690
|
+
let cols = uniforms.packedCols;
|
|
2691
|
+
let row_stride : i32 = uniforms.packedCols;
|
|
2692
|
+
|
|
2693
|
+
// find the rows max
|
|
2694
|
+
${M}
|
|
2695
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2696
|
+
let value = getValue(row, col, row_stride);
|
|
2697
|
+
threadMax = max(threadMax, value);
|
|
2698
|
+
}
|
|
2699
|
+
if (lindex < cols) {
|
|
2700
|
+
threadShared[lindex] = threadMax;
|
|
2701
|
+
}
|
|
2702
|
+
workgroupBarrier();
|
|
2703
|
+
|
|
2704
|
+
var reduceSize = min(cols, wg);
|
|
2705
|
+
for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {
|
|
2706
|
+
reduceSize = currSize + (reduceSize & 1);
|
|
2707
|
+
if (lindex < currSize) {
|
|
2708
|
+
threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);
|
|
2709
|
+
}
|
|
2710
|
+
workgroupBarrier();
|
|
2711
|
+
}
|
|
2712
|
+
if (lindex == 0) {
|
|
2713
|
+
rowMaxShared = ${I}(${R("threadShared[0]",w)});
|
|
2714
|
+
}
|
|
2715
|
+
workgroupBarrier();
|
|
2716
|
+
|
|
2717
|
+
// find the rows sum
|
|
2718
|
+
var threadSum = ${I}(0.0);
|
|
2719
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2720
|
+
let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);
|
|
2721
|
+
threadSum += subExp;
|
|
2722
|
+
}
|
|
2723
|
+
threadShared[lindex] = threadSum;
|
|
2724
|
+
workgroupBarrier();
|
|
2725
|
+
|
|
2726
|
+
for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {
|
|
2727
|
+
if (lindex < currSize) {
|
|
2728
|
+
threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];
|
|
2729
|
+
}
|
|
2730
|
+
workgroupBarrier();
|
|
2731
|
+
}
|
|
2732
|
+
if (lindex == 0) {
|
|
2733
|
+
rowSumShared = ${I}(${Q("threadShared[0]",w)});
|
|
2734
|
+
}
|
|
2735
|
+
workgroupBarrier();
|
|
2736
|
+
|
|
2737
|
+
// calculate final value for each element in the row
|
|
2738
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2739
|
+
var value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;
|
|
2740
|
+
// max operation protects against NaN since all values should be >=0
|
|
2741
|
+
value = max(value, ${I}(0.0));
|
|
2742
|
+
setValue(row, col, row_stride, value);
|
|
2743
|
+
}
|
|
2744
|
+
}`,V=e.compute({name:"Softmax",shaderCache:{hint:`${w};${x}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:c.dataType}],dispatchGroup:{x:y},programUniforms:[{type:6,data:v}]}),getShaderSource:L},{inputs:[c],outputs:[u?-1:0]})[0];u&&e.compute(it(V,h),{inputs:[V]})},Gc=(e,t)=>{Nc(e.inputs),Vc(e,t)},Wc=e=>_({axis:e.axis})}),ha,qc,Hc,jc,Kc,Vm=T(()=>{Ee(),xe(),he(),ha=e=>Array.from(e.getBigInt64Array(),Number),qc=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(ha(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Hc=(e,t)=>{let r=[];for(let i=0;i<e.length;++i)r.push(e[i]*t[i]);return r},jc=(e,t)=>{let r=e[0].dims,i=t??ha(e[1]),a=Hc(r,i),o=q.size(a),l=e[0].dataType,u=U("input",l,r.length),c=te("output",l,a.length),h=p=>`
|
|
2745
|
+
const inputShape = ${u.indices(...r)};
|
|
2746
|
+
${p.registerUniform("output_size","u32").declareVariables(u,c)}
|
|
2747
|
+
${p.mainStart()}
|
|
2748
|
+
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2749
|
+
let output_indices = ${c.offsetToIndices("global_idx")};
|
|
2750
|
+
var input_indices: ${u.type.indices};
|
|
2751
|
+
for (var i = 0; i < ${r.length}; i++) {
|
|
2752
|
+
let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")};
|
|
2753
|
+
let input_dim_value = ${c.indicesGet("output_indices","i")} % input_dim_i;
|
|
2754
|
+
|
|
2755
|
+
${u.indicesSet("input_indices","i","input_dim_value")}
|
|
2756
|
+
}
|
|
2757
|
+
${c.setByOffset("global_idx",u.getByIndices("input_indices"))}
|
|
2758
|
+
}`;return{name:"Tile",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...D(e[0].dims,a)]}),getShaderSource:h}},Kc=e=>{qc(e.inputs),e.compute(jc(e.inputs),{inputs:[0]})}}),Qc,Xc,Zc,Gm=T(()=>{Ee(),xe(),he(),Qc=(e,t,r,i,a)=>{let o=te("output_data",a,r.length,4),l=U("a_data",t[1].dataType,t[1].dims.length,4),u=U("b_data",t[2].dataType,t[2].dims.length,4),c=U("c_data",t[0].dataType,t[0].dims.length,4),h,p=(m,y,w)=>`select(${y}, ${m}, ${w})`;if(!i)h=o.setByOffset("global_idx",p(l.getByOffset("global_idx"),u.getByOffset("global_idx"),c.getByOffset("global_idx")));else{let m=(y,w,v="")=>{let x=`a_data[index_a${w}][component_a${w}]`,R=`b_data[index_b${w}][component_b${w}]`,C=`bool(c_data[index_c${w}] & (0xffu << (component_c${w} * 8)))`;return`
|
|
2759
|
+
let output_indices${w} = ${o.offsetToIndices(`global_idx * 4u + ${w}u`)};
|
|
2760
|
+
let offset_a${w} = ${l.broadcastedIndicesToOffset(`output_indices${w}`,o)};
|
|
2761
|
+
let offset_b${w} = ${u.broadcastedIndicesToOffset(`output_indices${w}`,o)};
|
|
2762
|
+
let offset_c${w} = ${c.broadcastedIndicesToOffset(`output_indices${w}`,o)};
|
|
2763
|
+
let index_a${w} = offset_a${w} / 4u;
|
|
2764
|
+
let index_b${w} = offset_b${w} / 4u;
|
|
2765
|
+
let index_c${w} = offset_c${w} / 4u;
|
|
2766
|
+
let component_a${w} = offset_a${w} % 4u;
|
|
2767
|
+
let component_b${w} = offset_b${w} % 4u;
|
|
2768
|
+
let component_c${w} = offset_c${w} % 4u;
|
|
2769
|
+
${y}[${w}] = ${v}(${p(x,R,C)});
|
|
2770
|
+
`};a===9?h=`
|
|
2771
|
+
var data = vec4<u32>(0);
|
|
2772
|
+
${m("data",0,"u32")}
|
|
2773
|
+
${m("data",1,"u32")}
|
|
2774
|
+
${m("data",2,"u32")}
|
|
2775
|
+
${m("data",3,"u32")}
|
|
2776
|
+
output_data[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:h=`
|
|
2777
|
+
${m("output_data[global_idx]",0)}
|
|
2778
|
+
${m("output_data[global_idx]",1)}
|
|
2779
|
+
${m("output_data[global_idx]",2)}
|
|
2780
|
+
${m("output_data[global_idx]",3)}
|
|
2781
|
+
`}return`
|
|
2782
|
+
${e.registerUniform("vec_size","u32").declareVariables(c,l,u,o)}
|
|
2783
|
+
${e.mainStart()}
|
|
2784
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
2785
|
+
${h}
|
|
2786
|
+
}`},Xc=e=>{let t=e[1].dims,r=e[2].dims,i=e[0].dims,a=e[1].dataType,o=!(q.areEqual(t,r)&&q.areEqual(r,i)),l=t,u=q.size(t);if(o){let h=lr.calcShape(lr.calcShape(t,r,!1),i,!1);if(!h)throw new Error("Can't perform where op on the given tensors");l=h,u=q.size(l)}let c=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>Qc(h,e,l,o,a),getRunData:()=>({outputs:[{dims:l,dataType:a}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:c},...D(i,t,r,l)]})}},Zc=e=>{e.compute(Xc(e.inputs))}}),Jc,Wm=T(()=>{im(),kn(),nm(),am(),om(),lm(),um(),mm(),gm(),ym(),wm(),vm(),bm(),_m(),Sm(),$m(),xm(),Tm(),Cm(),Em(),km(),Mm(),Rm(),Im(),Am(),dd(),Pm(),Om(),zm(),Dm(),Lm(),Tn(),Bm(),bd(),Um(),Fm(),Nm(),yd(),Vm(),Le(),An(),Gm(),Jc=new Map([["Abs",[Ao]],["Acos",[Po]],["Acosh",[Oo]],["Add",[_l]],["ArgMax",[yo,En]],["ArgMin",[go,En]],["Asin",[zo]],["Asinh",[Do]],["Atan",[Lo]],["Atanh",[Bo]],["Attention",[$o]],["AveragePool",[Xd,Qd]],["BatchNormalization",[Eo]],["BiasAdd",[Ro]],["BiasSplitGelu",[wl]],["Cast",[Fo,Uo]],["Ceil",[Go]],["Clip",[Vo]],["Concat",[zl,Dl]],["Conv",[qn,Gn]],["ConvTranspose",[uu,au]],["Cos",[Wo]],["Cosh",[qo]],["CumSum",[cu,hu]],["DepthToSpace",[gu,yu]],["DequantizeLinear",[nc,ac]],["Div",[Sl]],["Einsum",[$u,xu]],["Elu",[Ho,$i]],["Equal",[$l]],["Erf",[jo]],["Exp",[Ko]],["Expand",[ku]],["FastGelu",[Ru]],["Floor",[Qo]],["FusedConv",[qn,Gn]],["Gather",[Ou,Pu]],["GatherElements",[qu,Wu]],["GatherBlockQuantized",[Fu,Nu]],["GatherND",[Du,Lu]],["Gelu",[Xo]],["Gemm",[Qu,Ku]],["GlobalAveragePool",[Jd,Zd]],["GlobalMaxPool",[rc,tc]],["Greater",[El]],["GreaterOrEqual",[Ml]],["GridSample",[id,nd]],["GroupQueryAttention",[xd]],["HardSigmoid",[il,sl]],["InstanceNormalization",[Ed]],["LayerNormalization",[Rd]],["LeakyRelu",[Zo,$i]],["Less",[kl]],["LessOrEqual",[Rl]],["Log",[hl]],["MatMul",[Ad]],["MatMulNBits",[Dd,Ld]],["MaxPool",[Yd,ec]],["Mul",[xl]],["MultiHeadAttention",[ud,od]],["Neg",[Yo]],["Not",[Jo]],["Pad",[Hd]],["Pow",[Tl]],["QuickGelu",[fl,$i]],["Range",[uc]],["Reciprocal",[el]],["ReduceMin",[co]],["ReduceMean",[no]],["ReduceMax",[uo]],["ReduceSum",[po]],["ReduceProd",[ho]],["ReduceL1",[ao]],["ReduceL2",[oo]],["ReduceLogSum",[fo]],["ReduceLogSumExp",[lo]],["ReduceSumSquare",[mo]],["Relu",[tl]],["Resize",[Rc,Ic]],["RotaryEmbedding",[vd]],["ScatterND",[pc,hc]],["Sigmoid",[rl]],["Sin",[nl]],["Sinh",[al]],["Slice",[Uc,Fc]],["SkipLayerNormalization",[Oc]],["Split",[fd,gd]],["Sqrt",[ol]],["Softmax",[Gc,Wc]],["Sub",[Cl]],["Tan",[ll]],["Tanh",[ul]],["ThresholdedRelu",[cl,$i]],["Tile",[Kc]],["Transpose",[Wt,bi]],["Where",[Zc]]])}),Yc,qm=T(()=>{wt(),Vt(),he(),Yc=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,i,a){bt(e.programInfo.name);let o=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let h of t)u.push({binding:u.length,resource:{buffer:h.buffer}});for(let h of r)u.push({binding:u.length,resource:{buffer:h.buffer}});a&&u.push({binding:u.length,resource:a});let c=o.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let h={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:c,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}l.setPipeline(e.computePipeline),l.setBindGroup(0,c),l.dispatchWorkgroups(...i),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),yt(e.programInfo.name)}dispose(){}build(e,t){bt(e.name);let r=this.backend.device,i=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(h=>{r.features.has(h.feature)&&i.push(`enable ${h.extension};`)});let a=De(t,this.backend.device.limits),o=e.getShaderSource(a),l=`${i.join(`
|
|
2787
|
+
`)}
|
|
2788
|
+
${a.additionalImplementations}
|
|
2789
|
+
${o}`,u=r.createShaderModule({code:l,label:e.name});Fe("verbose",()=>`[WebGPU] ${e.name} shader code: ${l}`);let c=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return yt(e.name),{programInfo:e,computePipeline:c,uniformVariablesInfo:a.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,a=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=a&&r<=a&&i<=a)return[t,r,i];let o=t*r*i,l=Math.ceil(Math.sqrt(o));if(l>a){if(l=Math.ceil(Math.cbrt(o)),l>a)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[l,l,l]}else return[l,l,1]}}}),eh={};K(eh,{WebGpuBackend:()=>ih});var th,rh,sh,ih,Hm=T(()=>{wt(),Ee(),Vt(),kr(),$n(),Wm(),qm(),th=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let i=0;i<e.length;++i){let a=e[i].dataType;switch(t[i]){case"none":{r.push("");break}case"type":{r.push(`${a}`);break}case"rank":{let o=e[i].dims.length;r.push(`${a};${o}`);break}case"dims":{let o=e[i].dims.join(",");r.push(`${a};${o}`);break}default:throw new Error(`unsupported input dependency: ${t[i]}`)}}return r.join("|")},rh=(e,t,r)=>{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+r+`:${th(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},sh=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},ih=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let r=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r},a=o=>t.features.has(o)&&r.push(o)&&!0;a("chromium-experimental-timestamp-query-inside-passes")||a("timestamp-query"),a("shader-f16"),a("subgroups"),this.device=await t.requestDevice(i),this.adapterInfo=new sh(t.info||await t.requestAdapterInfo()),this.gpuDataManager=Gi(this),this.programManager=new Yc(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,vs(e.logLevel,!!e.debug),this.device.onuncapturederror=o=>{o.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${o.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&this.env?.webgpu&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;bt(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let i=0;i<t.length/2;i++){let a=r[i],o=a.kernelId,l=this.kernels.get(o),u=l.kernelType,c=l.kernelName,h=a.programName,p=a.inputTensorViews,m=a.outputTensorViews,y=t[i*2],w=t[i*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=y);let v=Number(y-this.queryTimeBase),x=Number(w-this.queryTimeBase);if(!Number.isSafeInteger(v)||!Number.isSafeInteger(x))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:p.map(R=>({dims:R.dims,dataType:Bt(R.dataType)})),outputsMetadata:m.map(R=>({dims:R.dims,dataType:Bt(R.dataType)})),kernelId:o,kernelType:u,kernelName:c,programName:h,startTime:v,endTime:x});else{let R="";p.forEach(($,I)=>{R+=`input[${I}]: [${$.dims}] | ${Bt($.dataType)}, `});let C="";m.forEach(($,I)=>{C+=`output[${I}]: [${$.dims}] | ${Bt($.dataType)}, `}),console.log(`[profiling] kernel "${o}|${u}|${c}|${h}" ${R}${C}start time: ${v} ns, execution time: ${x-v} ns`)}ar("GPU",`${h}::${y}::${w}`)}e.unmap(),this.pendingQueries.delete(e)}),yt()}run(e,t,r,i,a,o){bt(e.name);let l=[];for(let $=0;$<t.length;++$){let I=t[$].data;if(I===0)continue;let M=this.gpuDataManager.get(I);if(!M)throw new Error(`no GPU data for input: ${I}`);l.push(M)}let{outputs:u,dispatchGroup:c,programUniforms:h}=e.getRunData(t),p=r.length===0?u.map(($,I)=>I):r;if(p.length!==u.length)throw new Error(`Output size ${p.length} must be equal to ${u.length}.`);let m=[],y=[];for(let $=0;$<u.length;++$){if(!Number.isInteger(p[$])||p[$]<-3||p[$]>=o)throw new Error(`Invalid output index: ${p[$]}`);if(p[$]===-3)continue;let I=p[$]===-1,M=p[$]===-2,L=I||M?a(u[$].dataType,u[$].dims):i(p[$],u[$].dataType,u[$].dims);if(m.push(L),L.data===0)continue;let V=this.gpuDataManager.get(L.data);if(!V)throw new Error(`no GPU data for output: ${L.data}`);if(I&&this.temporaryData.push(V),M){let W=this.kernelPersistentData.get(this.currentKernelId);W||(W=[],this.kernelPersistentData.set(this.currentKernelId,W)),W.push(V)}y.push(V)}if(l.length!==t.length||y.length!==m.length){if(y.length===0)return yt(e.name),m;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let w;if(h){let $=0,I=[];h.forEach(W=>{let X=typeof W.data=="number"?[W.data]:W.data;if(X.length===0)return;let se=W.type===10?2:4,ge,Be;W.type===10?(Be=X.length>4?16:X.length>2?8:X.length*se,ge=X.length>4?16:se*X.length):(Be=X.length<=2?X.length*se:16,ge=16),$=Math.ceil($/Be)*Be,I.push($);let Te=W.type===10?8:4;$+=X.length>4?Math.ceil(X.length/Te)*ge:X.length*se});let M=16;$=Math.ceil($/M)*M;let L=new ArrayBuffer($);h.forEach((W,X)=>{let se=I[X],ge=typeof W.data=="number"?[W.data]:W.data;if(W.type===6)new Int32Array(L,se,ge.length).set(ge);else if(W.type===12)new Uint32Array(L,se,ge.length).set(ge);else if(W.type===10)new Uint16Array(L,se,ge.length).set(ge);else if(W.type===1)new Float32Array(L,se,ge.length).set(ge);else throw new Error(`Unsupported uniform type: ${Bt(W.type)}`)});let V=this.gpuDataManager.create($,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(V.buffer,0,L,0,$),this.gpuDataManager.release(V.id),w={offset:0,size:$,buffer:V.buffer}}let v=this.programManager.normalizeDispatchGroupSize(c),x=v[1]===1&&v[2]===1,R=rh(e,t,x),C=this.programManager.getArtifact(R);if(C||(C=this.programManager.build(e,v),this.programManager.setArtifact(R,C),Fe("info",()=>`[artifact] key: ${R}, programName: ${e.name}`)),h&&C.uniformVariablesInfo){if(h.length!==C.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${C.uniformVariablesInfo.length}, got ${h.length} in program "${C.programInfo.name}".`);for(let $=0;$<h.length;$++){let I=h[$],M=I.type,L=typeof I.data=="number"?1:I.data.length,[V,W]=C.uniformVariablesInfo[$];if(M!==V||L!==W)throw new Error(`Uniform variable ${$} mismatch: expect type ${V} with size ${W}, got type ${M} with size ${L} in program "${C.programInfo.name}".`)}}if(Fe("info",()=>`[ProgramManager] run "${e.name}" (key=${R}) with ${v[0]}x${v[1]}x${v[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let $={kernelId:this.currentKernelId,programName:C.programInfo.name,inputTensorViews:t,outputTensorViews:m};this.pendingKernels.push($),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push($)}return this.programManager.run(C,l,y,v,w),yt(e.name),m}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,r,i){let a=Jc.get(e);if(!a)throw new Error(`kernel not implemented: ${e}`);let o={kernelType:e,kernelName:i,kernelEntry:a[0],attributes:[a[1],r]};this.kernels.set(t,o)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let a=i.kernelType,o=i.kernelName,l=i.kernelEntry,u=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${a}] ${o}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),Fe("info",()=>`[WebGPU] Start to run kernel "[${a}] ${o}"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope("validation"),l(t,u[1]),0}catch(h){return r.push(Promise.resolve(`[WebGPU] Kernel "[${a}] ${o}" failed. ${h}`)),1}finally{c&&r.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${a}] ${o}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,i){let a=this.sessionExternalDataMapping.get(e);a||(a=new Map,this.sessionExternalDataMapping.set(e,a));let o=a.get(t),l=this.gpuDataManager.registerExternalBuffer(r,i,o);return a.set(t,[l,r]),l}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,r){return async()=>{let i=await yi(this,e,t);return ur(i.buffer,r)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Fe("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Fe("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Fe("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let i=0;i<r;i++){let a=this.getComputePassEncoder(),o=e[i];this.writeTimestamp(this.pendingDispatchNumber*2),a.setPipeline(o.computePipeline),a.setBindGroup(0,o.bindGroup),a.dispatchWorkgroups(...o.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(t[i]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),nh={};K(nh,{init:()=>oh});var rn,ah,oh,jm=T(()=>{Ee(),Vt(),xe(),gi(),rn=class Yh{constructor(t,r,i,a){this.module=t,this.dataType=r,this.data=i,this.dims=a}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=q.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=q.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=q.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=q.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(q.size(t)!==q.size(this.dims))throw new Error("Invalid new shape");return new Yh(this.module,this.dataType,this.data,t)}},ah=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,a=r/e.PTR_SIZE,o=i===4?"i32":"i64";this.opKernelContext=Number(e.getValue(i*a++,o));let l=Number(e.getValue(i*a++,o));this.outputCount=Number(e.getValue(i*a++,o)),this.customDataOffset=Number(e.getValue(i*a++,"*")),this.customDataSize=Number(e.getValue(i*a++,o));let u=[];for(let c=0;c<l;c++){let h=Number(e.getValue(i*a++,o)),p=Number(e.getValue(i*a++,"*")),m=Number(e.getValue(i*a++,o)),y=[];for(let w=0;w<m;w++)y.push(Number(e.getValue(i*a++,o)));u.push(new rn(e,h,p,y))}this.inputs=u}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let r=t?.inputs?.map(l=>typeof l=="number"?this.inputs[l]:l)??this.inputs,i=t?.outputs??[],a=(l,u,c)=>new rn(this.module,u,this.output(l,c),c),o=(l,u)=>{let c=Ut(l,u);if(!c)throw new Error(`Unsupported data type: ${l}`);let h=c>0?this.backend.gpuDataManager.create(c).id:0;return new rn(this.module,l,h,u)};return this.backend.run(e,r,i,a,o,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let i=this.module.PTR_SIZE,a=i===4?"i32":"i64",o=this.module.stackAlloc((1+t.length)*i);this.module.setValue(o,t.length,a);for(let l=0;l<t.length;l++)this.module.setValue(o+i*(l+1),t[l],a);return this.module._JsepOutput(this.opKernelContext,e,o)}catch(i){throw new Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${i}`)}finally{this.module.stackRestore(r)}}},oh=async(e,t,r,i)=>{let a=t.jsepInit;if(!a)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let o=(Hm(),ae(eh)).WebGpuBackend,l=new o;await l.initialize(r,i),a("webgpu",[l,u=>l.alloc(Number(u)),u=>l.free(u),(u,c,h,p=!1)=>{if(p)Fe("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(u)}, dst=${Number(c)}, size=${Number(h)}`),l.memcpy(Number(u),Number(c));else{Fe("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(u)}, gpuDataId=${Number(c)}, size=${Number(h)}`);let m=t.HEAPU8.subarray(Number(u>>>0),Number(u>>>0)+Number(h));l.upload(Number(c),m)}},async(u,c,h)=>{Fe("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${u}, dataOffset=${c}, size=${h}`),await l.download(Number(u),()=>t.HEAPU8.subarray(Number(c)>>>0,Number(c+h)>>>0))},(u,c,h)=>l.createKernel(u,Number(c),h,t.UTF8ToString(t._JsepGetNodeName(Number(c)))),u=>l.releaseKernel(u),(u,c,h,p)=>{Fe("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${h}, kernel=${u}, contextDataOffset=${c}`);let m=new ah(t,l,Number(c));return l.computeKernel(Number(u),m,p)},()=>l.captureBegin(),()=>l.captureEnd(),()=>l.replay()])}else{let o=new fi(r);a("webnn",[o,()=>o.reserveTensorId(),l=>o.releaseTensorId(l),async(l,u,c,h,p)=>o.ensureTensor(l,u,c,h,p),(l,u)=>{o.uploadTensor(l,u)},async(l,u)=>o.downloadTensor(l,u),(l,u)=>o.registerMLContext(l,u),!!r.trace])}}}),lh,pa,ma,Pr,uh,fa,sn,ga,ya,wa,va,ba,_a,dh=T(()=>{wt(),_n(),Sn(),Ee(),Dt(),Qr(),ui(),lh=(e,t)=>{Me()._OrtInit(e,t)!==0&&$e("Can't initialize onnxruntime.")},pa=async e=>{lh(e.wasm.numThreads,Zr(e.logLevel))},ma=async(e,t)=>{Me().asyncInit?.();let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!r)throw new 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 new Error("WebNN is not supported in current environment");{let i=(jm(),ae(nh)).init;t==="webgpu"&&await i("webgpu",Me(),e,r),t==="webnn"&&await i("webnn",Me(),e)}},Pr=new Map,uh=e=>{let t=Me(),r=t.stackSave();try{let i=t.PTR_SIZE,a=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,a,a+i)!==0&&$e("Can't get session input/output count.");let o=i===4?"i32":"i64";return[Number(t.getValue(a,o)),Number(t.getValue(a+i,o))]}finally{t.stackRestore(r)}},fa=(e,t)=>{let r=Me(),i=r.stackSave(),a=0;try{let o=r.PTR_SIZE,l=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(e,t,l,l+o)!==0&&$e("Can't get session input/output metadata.");let u=Number(r.getValue(l,"*"));a=Number(r.getValue(l+o,"*"));let c=r.HEAP32[a/4];if(c===0)return[u,0];let h=r.HEAPU32[a/4+1],p=[];for(let m=0;m<h;m++){let y=Number(r.getValue(a+8+m*o,"*"));p.push(y!==0?r.UTF8ToString(y):Number(r.getValue(a+8+(m+h)*o,"*")))}return[u,c,p]}finally{r.stackRestore(i),a!==0&&r._OrtFree(a)}},sn=e=>{let t=Me(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},ga=async(e,t)=>{let r,i,a=Me();Array.isArray(e)?[r,i]=e:e.buffer===a.HEAPU8.buffer?[r,i]=[e.byteOffset,e.byteLength]:[r,i]=sn(e);let o=0,l=0,u=0,c=[],h=[],p=[];try{if([l,c]=await li(t),t?.externalData&&a.mountExternalData){let M=[];for(let L of t.externalData){let V=typeof L=="string"?L:L.path;M.push(es(typeof L=="string"?L:L.data).then(W=>{a.mountExternalData(V,W)}))}await Promise.all(M)}for(let M of t?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(a.shouldTransferToMLTensor=!1,typeof M!="string"){let L=M,V=L?.context,W=L?.gpuDevice,X=L?.deviceType,se=L?.powerPreference;V?a.currentContext=V:W?a.currentContext=await a.webnnCreateMLContext(W):a.currentContext=await a.webnnCreateMLContext({deviceType:X,powerPreference:se})}else a.currentContext=await a.webnnCreateMLContext();break}o=await a._OrtCreateSession(r,i,l),a.webgpuOnCreateSession?.(o),o===0&&$e("Can't create a session."),a.jsepOnCreateSession?.(),a.currentContext&&(a.webnnRegisterMLContext(o,a.currentContext),a.currentContext=void 0,a.shouldTransferToMLTensor=!0);let[m,y]=uh(o),w=!!t?.enableGraphCapture,v=[],x=[],R=[],C=[],$=[];for(let M=0;M<m;M++){let[L,V,W]=fa(o,M);L===0&&$e("Can't get an input name."),h.push(L);let X=a.UTF8ToString(L);v.push(X),R.push(V===0?{name:X,isTensor:!1}:{name:X,isTensor:!0,type:Bt(V),shape:W})}for(let M=0;M<y;M++){let[L,V,W]=fa(o,M+m);L===0&&$e("Can't get an output name."),p.push(L);let X=a.UTF8ToString(L);x.push(X),C.push(V===0?{name:X,isTensor:!1}:{name:X,isTensor:!0,type:Bt(V),shape:W});{if(w&&t?.preferredOutputLocation===void 0){$.push("gpu-buffer");continue}let se=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[X]??"cpu",ge=a.webnnIsGraphOutput;if(se==="cpu"&&ge&&ge(o,X)){$.push("ml-tensor-cpu-output");continue}if(se!=="cpu"&&se!=="cpu-pinned"&&se!=="gpu-buffer"&&se!=="ml-tensor")throw new Error(`Not supported preferred output location: ${se}.`);if(w&&se!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${se}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);$.push(se)}}let I=null;return $.some(M=>M==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(u=a._OrtCreateBinding(o),u===0&&$e("Can't create IO binding."),I={handle:u,outputPreferredLocations:$,outputPreferredLocationsEncoded:$.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>gs(M))}),Pr.set(o,[o,h,p,I,w,!1]),[o,v,x,R,C]}catch(m){throw h.forEach(y=>a._OrtFree(y)),p.forEach(y=>a._OrtFree(y)),u!==0&&a._OrtReleaseBinding(u)!==0&&$e("Can't release IO binding."),o!==0&&a._OrtReleaseSession(o)!==0&&$e("Can't release session."),m}finally{a._free(r),l!==0&&a._OrtReleaseSessionOptions(l)!==0&&$e("Can't release session options."),c.forEach(m=>a._free(m)),a.unmountExternalData?.()}},ya=e=>{let t=Me(),r=Pr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,a,o,l,u]=r;l&&(u&&t._OrtClearBoundOutputs(l.handle)!==0&&$e("Can't clear bound outputs."),t._OrtReleaseBinding(l.handle)!==0&&$e("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),a.forEach(c=>t._OrtFree(c)),o.forEach(c=>t._OrtFree(c)),t._OrtReleaseSession(i)!==0&&$e("Can't release session."),Pr.delete(e)},wa=async(e,t,r,i,a,o,l=!1)=>{if(!e){t.push(0);return}let u=Me(),c=u.PTR_SIZE,h=e[0],p=e[1],m=e[3],y=m,w,v;if(h==="string"&&(m==="gpu-buffer"||m==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(l&&m!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(m==="gpu-buffer"){let C=e[2].gpuBuffer;v=Ut(Lt(h),p);{let $=u.jsepRegisterBuffer;if(!$)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');w=$(i,o,C,v)}}else if(m==="ml-tensor"){let C=e[2].mlTensor;v=Ut(Lt(h),p);let $=u.webnnRegisterMLTensor;if(!$)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');w=$(i,C,Lt(h),p)}else{let C=e[2];if(Array.isArray(C)){v=c*C.length,w=u._malloc(v),r.push(w);for(let $=0;$<C.length;$++){if(typeof C[$]!="string")throw new TypeError(`tensor data at index ${$} is not a string`);u.setValue(w+$*c,lt(C[$],r),"*")}}else{let $=u.webnnIsGraphInput,I=u.webnnIsGraphOutput;if(h!=="string"&&$&&I){let M=u.UTF8ToString(a);if($(i,M)||I(i,M)){let L=Lt(h);v=Ut(L,p),y="ml-tensor";let V=u.webnnCreateTemporaryTensor,W=u.webnnUploadTensor;if(!V||!W)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let X=await V(i,L,p);W(X,new Uint8Array(C.buffer,C.byteOffset,C.byteLength)),w=X}else v=C.byteLength,w=u._malloc(v),r.push(w),u.HEAPU8.set(new Uint8Array(C.buffer,C.byteOffset,v),w)}else v=C.byteLength,w=u._malloc(v),r.push(w),u.HEAPU8.set(new Uint8Array(C.buffer,C.byteOffset,v),w)}}let x=u.stackSave(),R=u.stackAlloc(4*p.length);try{p.forEach(($,I)=>u.setValue(R+I*c,$,c===4?"i32":"i64"));let C=u._OrtCreateTensor(Lt(h),w,v,R,p.length,gs(y));C===0&&$e(`Can't create tensor for input/output. session=${i}, index=${o}.`),t.push(C)}finally{u.stackRestore(x)}},va=async(e,t,r,i,a,o)=>{let l=Me(),u=l.PTR_SIZE,c=Pr.get(e);if(!c)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=c[0],p=c[1],m=c[2],y=c[3],w=c[4],v=c[5],x=t.length,R=i.length,C=0,$=[],I=[],M=[],L=[],V=[],W=l.stackSave(),X=l.stackAlloc(x*u),se=l.stackAlloc(x*u),ge=l.stackAlloc(R*u),Be=l.stackAlloc(R*u);try{[C,$]=si(o),Et("wasm prepareInputOutputTensor");for(let ue=0;ue<x;ue++)await wa(r[ue],I,L,e,p[t[ue]],t[ue],w);for(let ue=0;ue<R;ue++)await wa(a[ue],M,L,e,m[i[ue]],x+i[ue],w);kt("wasm prepareInputOutputTensor");for(let ue=0;ue<x;ue++)l.setValue(X+ue*u,I[ue],"*"),l.setValue(se+ue*u,p[t[ue]],"*");for(let ue=0;ue<R;ue++)l.setValue(ge+ue*u,M[ue],"*"),l.setValue(Be+ue*u,m[i[ue]],"*");if(y&&!v){let{handle:ue,outputPreferredLocations:Se,outputPreferredLocationsEncoded:Oe}=y;if(p.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${p.length}).`);Et("wasm bindInputsOutputs");for(let Ue=0;Ue<x;Ue++){let Ae=t[Ue];await l._OrtBindInput(ue,p[Ae],I[Ue])!==0&&$e(`Can't bind input[${Ue}] for session=${e}.`)}for(let Ue=0;Ue<R;Ue++){let Ae=i[Ue];a[Ue]?.[3]?(V.push(M[Ue]),l._OrtBindOutput(ue,m[Ae],M[Ue],0)!==0&&$e(`Can't bind pre-allocated output[${Ue}] for session=${e}.`)):l._OrtBindOutput(ue,m[Ae],0,Oe[Ae])!==0&&$e(`Can't bind output[${Ue}] to ${Se[Ue]} for session=${e}.`)}kt("wasm bindInputsOutputs"),Pr.set(e,[h,p,m,y,w,!0])}l.jsepOnRunStart?.(h),l.webnnOnRunStart?.(h);let Te;y?Te=await l._OrtRunWithBinding(h,y.handle,R,ge,C):Te=await l._OrtRun(h,se,X,x,Be,R,ge,C),Te!==0&&$e("failed to call OrtRun().");let ke=[],Ge=[];Et("wasm ProcessOutputTensor");for(let ue=0;ue<R;ue++){let Se=Number(l.getValue(ge+ue*u,"*"));if(Se===M[ue]||V.includes(M[ue])){ke.push(a[ue]),Se!==M[ue]&&l._OrtReleaseTensor(Se)!==0&&$e("Can't release tensor.");continue}let Oe=l.stackSave(),Ue=l.stackAlloc(4*u),Ae=!1,Ne,ee=0;try{l._OrtGetTensorData(Se,Ue,Ue+u,Ue+2*u,Ue+3*u)!==0&&$e(`Can't access output tensor data on index ${ue}.`);let Ie=u===4?"i32":"i64",Ce=Number(l.getValue(Ue,Ie));ee=l.getValue(Ue+u,"*");let _e=l.getValue(Ue+u*2,"*"),xt=Number(l.getValue(Ue+u*3,Ie)),Ft=[];for(let Ze=0;Ze<xt;Ze++)Ft.push(Number(l.getValue(_e+Ze*u,Ie)));l._OrtFree(_e)!==0&&$e("Can't free memory for tensor dims.");let pt=Ft.reduce((Ze,mt)=>Ze*mt,1);Ne=Bt(Ce);let Nt=y?.outputPreferredLocations[i[ue]];if(Ne==="string"){if(Nt==="gpu-buffer"||Nt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ze=[];for(let mt=0;mt<pt;mt++){let br=l.getValue(ee+mt*u,"*"),Jm=l.getValue(ee+(mt+1)*u,"*"),Ym=mt===pt-1?void 0:Jm-br;Ze.push(l.UTF8ToString(br,Ym))}ke.push([Ne,Ft,Ze,"cpu"])}else if(Nt==="gpu-buffer"&&pt>0){let Ze=l.jsepGetBuffer;if(!Ze)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let mt=Ze(ee),br=Ut(Ce,pt);if(br===void 0||!Jr(Ne))throw new Error(`Unsupported data type: ${Ne}`);Ae=!0,ke.push([Ne,Ft,{gpuBuffer:mt,download:l.jsepCreateDownloader(mt,br,Ne),dispose:()=>{l._OrtReleaseTensor(Se)!==0&&$e("Can't release tensor.")}},"gpu-buffer"])}else if(Nt==="ml-tensor"&&pt>0){let Ze=l.webnnEnsureTensor,mt=l.webnnIsGraphInputOutputTypeSupported;if(!Ze||!mt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ut(Ce,pt)===void 0||!Yr(Ne))throw new Error(`Unsupported data type: ${Ne}`);if(!mt(e,Ne,!1))throw new Error(`preferredLocation "ml-tensor" for ${Ne} output is not supported by current WebNN Context.`);let br=await Ze(e,ee,Ce,Ft,!1);Ae=!0,ke.push([Ne,Ft,{mlTensor:br,download:l.webnnCreateMLTensorDownloader(ee,Ne),dispose:()=>{l.webnnReleaseTensorId(ee),l._OrtReleaseTensor(Se)}},"ml-tensor"])}else if(Nt==="ml-tensor-cpu-output"&&pt>0){let Ze=l.webnnCreateMLTensorDownloader(ee,Ne)(),mt=ke.length;Ae=!0,Ge.push((async()=>{let br=[mt,await Ze];return l.webnnReleaseTensorId(ee),l._OrtReleaseTensor(Se),br})()),ke.push([Ne,Ft,[],"cpu"])}else{let Ze=Xr(Ne),mt=new Ze(pt);new Uint8Array(mt.buffer,mt.byteOffset,mt.byteLength).set(l.HEAPU8.subarray(ee,ee+mt.byteLength)),ke.push([Ne,Ft,mt,"cpu"])}}finally{l.stackRestore(Oe),Ne==="string"&&ee&&l._free(ee),Ae||l._OrtReleaseTensor(Se)}}y&&!w&&(l._OrtClearBoundOutputs(y.handle)!==0&&$e("Can't clear bound outputs."),Pr.set(e,[h,p,m,y,w,!1]));for(let[ue,Se]of await Promise.all(Ge))ke[ue][2]=Se;return kt("wasm ProcessOutputTensor"),ke}finally{l.webnnOnRunEnd?.(h),l.stackRestore(W),I.forEach(Te=>l._OrtReleaseTensor(Te)),M.forEach(Te=>l._OrtReleaseTensor(Te)),L.forEach(Te=>l._free(Te)),C!==0&&l._OrtReleaseRunOptions(C),$.forEach(Te=>l._free(Te))}},ba=e=>{let t=Me(),r=Pr.get(e);if(!r)throw new Error("invalid session id");let i=r[0],a=t._OrtEndProfiling(i);a===0&&$e("Can't get an profile file name."),t._OrtFree(a)},_a=e=>{let t=[];for(let r of e){let i=r[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),Or,Ht,Os,Ri,Ii,nn,Sa,an,hs,ps,ch,hh,ph,mh,fh,gh,yh,wh,vh=T(()=>{wt(),dh(),Dt(),qr(),Or=()=>!!de.wasm.proxy&&typeof document<"u",Os=!1,Ri=!1,Ii=!1,an=new Map,hs=(e,t)=>{let r=an.get(e);r?r.push(t):an.set(e,[t])},ps=()=>{if(Os||!Ri||Ii||!Ht)throw new Error("worker not ready")},ch=e=>{switch(e.data.type){case"init-wasm":Os=!1,e.data.err?(Ii=!0,Sa[1](e.data.err)):(Ri=!0,Sa[0]()),nn&&(URL.revokeObjectURL(nn),nn=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=an.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},hh=async()=>{if(!Ri){if(Os)throw new Error("multiple calls to 'initWasm()' detected.");if(Ii)throw new Error("previous call to 'initWasm()' failed.");if(Os=!0,Or())return new Promise((e,t)=>{Ht?.terminate(),Js().then(([r,i])=>{try{Ht=i,Ht.onerror=o=>t(o),Ht.onmessage=ch,Sa=[e,t];let a={type:"init-wasm",in:de};if(!a.in.wasm.wasmPaths&&r){let o=Nr();o&&(a.in.wasm.wasmPaths=o)}Ht.postMessage(a),nn=r}catch(a){t(a)}},t)});try{await Kr(de.wasm),await pa(de),Ri=!0}catch(e){throw Ii=!0,e}finally{Os=!1}}},ph=async e=>{if(Or())return ps(),new Promise((t,r)=>{hs("init-ep",[t,r]);let i={type:"init-ep",in:{epName:e,env:de}};Ht.postMessage(i)});await ma(de,e)},mh=async e=>Or()?(ps(),new Promise((t,r)=>{hs("copy-from",[t,r]);let i={type:"copy-from",in:{buffer:e}};Ht.postMessage(i,[e.buffer])})):sn(e),fh=async(e,t)=>{if(Or()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ps(),new Promise((r,i)=>{hs("create",[r,i]);let a={type:"create",in:{model:e,options:{...t}}},o=[];e instanceof Uint8Array&&o.push(e.buffer),Ht.postMessage(a,o)})}else return ga(e,t)},gh=async e=>{if(Or())return ps(),new Promise((t,r)=>{hs("release",[t,r]);let i={type:"release",in:e};Ht.postMessage(i)});ya(e)},yh=async(e,t,r,i,a,o)=>{if(Or()){if(r.some(l=>l[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(a.some(l=>l))throw new Error("pre-allocated output tensor is not supported for proxy.");return ps(),new Promise((l,u)=>{hs("run",[l,u]);let c=r,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:c,outputIndices:i,options:o}};Ht.postMessage(h,_a(c))})}else return va(e,t,r,i,a,o)},wh=async e=>{if(Or())return ps(),new Promise((t,r)=>{hs("end-profiling",[t,r]);let i={type:"end-profiling",in:e};Ht.postMessage(i)});ba(e)}}),$a,bh,_h,Km=T(()=>{wt(),vh(),Ee(),Br(),ui(),$a=(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 new Error(`invalid data location: ${e.location} for ${t()}`)}},bh=e=>{switch(e[3]){case"cpu":return new ot(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Jr(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:i,dispose:a}=e[2];return ot.fromGpuBuffer(r,{dataType:t,dims:e[1],download:i,dispose:a})}case"ml-tensor":{let t=e[0];if(!Yr(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:i,dispose:a}=e[2];return ot.fromMLTensor(r,{dataType:t,dims:e[1],download:i,dispose:a})}default:throw new Error(`invalid data location: ${e[3]}`)}},_h=class{async fetchModelAndCopyToWasmMemory(e){return mh(await es(e))}async loadModel(e,t){bt();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await fh(r,t),yt()}async dispose(){return gh(this.sessionId)}async run(e,t,r){bt();let i=[],a=[];Object.entries(e).forEach(m=>{let y=m[0],w=m[1],v=this.inputNames.indexOf(y);if(v===-1)throw new Error(`invalid input '${y}'`);i.push(w),a.push(v)});let o=[],l=[];Object.entries(t).forEach(m=>{let y=m[0],w=m[1],v=this.outputNames.indexOf(y);if(v===-1)throw new Error(`invalid output '${y}'`);o.push(w),l.push(v)});let u=i.map((m,y)=>$a(m,()=>`input "${this.inputNames[a[y]]}"`)),c=o.map((m,y)=>m?$a(m,()=>`output "${this.outputNames[l[y]]}"`):null),h=await yh(this.sessionId,a,u,l,c,r),p={};for(let m=0;m<h.length;m++)p[this.outputNames[l[m]]]=o[m]??bh(h[m]);return yt(),p}startProfiling(){}endProfiling(){wh(this.sessionId)}}}),Sh={};K(Sh,{OnnxruntimeWebAssemblyBackend:()=>Ta,initializeFlags:()=>xa,wasmBackend:()=>$h});var xa,Ta,$h,Qm=T(()=>{wt(),vh(),Km(),xa=()=>{(typeof de.wasm.initTimeout!="number"||de.wasm.initTimeout<0)&&(de.wasm.initTimeout=0);let e=de.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.`),de.wasm.simd=!1),typeof de.wasm.proxy!="boolean"&&(de.wasm.proxy=!1),typeof de.wasm.trace!="boolean"&&(de.wasm.trace=!1),typeof de.wasm.numThreads!="number"||!Number.isInteger(de.wasm.numThreads)||de.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)de.wasm.numThreads=1;else{let t=typeof navigator>"u"?O("node:os").cpus().length:navigator.hardwareConcurrency;de.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Ta=class{async init(e){xa(),await hh(),await ph(e)}async createInferenceSessionHandler(e,t){let r=new _h;return await r.loadModel(e,t),r}},$h=new Ta}),xh={};K(xh,{InferenceSession:()=>Lr,TRACE:()=>ar,TRACE_EVENT_BEGIN:()=>Et,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>bt,TRACE_FUNC_END:()=>yt,Tensor:()=>ot,default:()=>Zm,env:()=>de,registerBackend:()=>re}),wt(),wt(),wt();var Xm="1.26.0",Zm=Ws;{let e=(Qm(),ae(Sh)).wasmBackend;re("webgpu",e,5),re("webnn",e,5),re("cpu",e,10),re("wasm",e,10)}return Object.defineProperty(de.versions,"web",{value:Xm,enumerable:!0}),ae(xh)})();/**
|
|
2790
|
+
* @license
|
|
2791
|
+
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
2792
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2793
|
+
* you may not use this file except in compliance with the License.
|
|
2794
|
+
* You may obtain a copy of the License at
|
|
2795
|
+
*
|
|
2796
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2797
|
+
*
|
|
2798
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2799
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2800
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2801
|
+
* See the License for the specific language governing permissions and
|
|
2802
|
+
* limitations under the License.
|
|
2803
|
+
* =============================================================================
|
|
2804
|
+
*//**
|
|
2805
|
+
* @license
|
|
2806
|
+
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
2807
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2808
|
+
* you may not use this file except in compliance with the License.
|
|
2809
|
+
* You may obtain a copy of the License at
|
|
2810
|
+
*
|
|
2811
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2812
|
+
*
|
|
2813
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2814
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2815
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2816
|
+
* See the License for the specific language governing permissions and
|
|
2817
|
+
* limitations under the License.
|
|
2818
|
+
* =============================================================================
|
|
2819
|
+
*//**
|
|
2820
|
+
* @license
|
|
2821
|
+
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
2822
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2823
|
+
* you may not use this file except in compliance with the License.
|
|
2824
|
+
* You may obtain a copy of the License at
|
|
2825
|
+
*
|
|
2826
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2827
|
+
*
|
|
2828
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2829
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2830
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2831
|
+
* See the License for the specific language governing permissions and
|
|
2832
|
+
* limitations under the License.
|
|
2833
|
+
* =============================================================================
|
|
2834
|
+
*/S.exports=n})(ka)),ka.exports}var ms={},Ma={},Ih;function rf(){return Ih||(Ih=1,Object.defineProperty(Ma,"__esModule",{value:!0})),Ma}var Di={},Ah;function sf(){if(Ah)return Di;Ah=1;var S;Object.defineProperty(Di,"__esModule",{value:!0}),Di.SileroLegacy=void 0;const s=Ds();class n{constructor(g,E,A,O,T){this.ortInstance=g,this._session=E,this._h=A,this._c=O,this._sr=T,this.reset_state=()=>{const K=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",K,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",K,[2,1,64])},this.process=async K=>{const ae={input:new this.ortInstance.Tensor("float32",K,[1,K.length]),h:this._h,c:this._c,sr:this._sr},J=await this._session.run(ae);this._h=J.hn,this._c=J.cn;const[ie]=J.output?.data;return{notSpeech:1-ie,isSpeech:ie}},this.release=async()=>{await this._session.release(),this._h.dispose(),this._c.dispose(),this._sr.dispose()}}}return Di.SileroLegacy=n,S=n,n.new=async(d,g)=>{s.log.debug("initializing vad");const E=await g(),A=await d.InferenceSession.create(E),O=new d.Tensor("int64",[16000n]),T=Array(128).fill(0),K=new d.Tensor("float32",T,[2,1,64]),G=new d.Tensor("float32",T,[2,1,64]);return s.log.debug("vad is initialized"),new S(d,A,K,G,O)},Di}var Li={},Ph;function nf(){if(Ph)return Li;Ph=1;var S;Object.defineProperty(Li,"__esModule",{value:!0}),Li.SileroV5=void 0;const s=Ds();function n(g){const E=Array(256).fill(0);return new g.Tensor("float32",E,[2,1,128])}class d{constructor(E,A,O,T){this._session=E,this._state=A,this._sr=O,this.ortInstance=T,this.reset_state=()=>{this._state=n(this.ortInstance)},this.process=async K=>{const ae={input:new this.ortInstance.Tensor("float32",K,[1,K.length]),state:this._state,sr:this._sr},J=await this._session.run(ae);if(!J.stateN)throw new Error("No state from model");if(this._state=J.stateN,!J.output?.data)throw new Error("No output from model");const ie=J.output.data[0];if(typeof ie!="number")throw new Error("Weird output data");return{notSpeech:1-ie,isSpeech:ie}},this.release=async()=>{await this._session.release(),this._state.dispose(),this._sr.dispose()}}}return Li.SileroV5=d,S=d,d.new=async(g,E)=>{s.log.debug("Loading VAD...");const A=await E(),O=await g.InferenceSession.create(A),T=new g.Tensor("int64",[16000n]),K=n(g);return s.log.debug("...finished loading VAD"),new S(O,K,T,g)},Li}var Oh;function ep(){return Oh||(Oh=1,(function(S){var s=ms&&ms.__createBinding||(Object.create?(function(E,A,O,T){T===void 0&&(T=O);var K=Object.getOwnPropertyDescriptor(A,O);(!K||("get"in K?!A.__esModule:K.writable||K.configurable))&&(K={enumerable:!0,get:function(){return A[O]}}),Object.defineProperty(E,T,K)}):(function(E,A,O,T){T===void 0&&(T=O),E[T]=A[O]})),n=ms&&ms.__exportStar||function(E,A){for(var O in E)O!=="default"&&!Object.prototype.hasOwnProperty.call(A,O)&&s(A,E,O)};Object.defineProperty(S,"__esModule",{value:!0}),S.SileroV5=S.SileroLegacy=void 0,n(rf(),S);var d=sf();Object.defineProperty(S,"SileroLegacy",{enumerable:!0,get:function(){return d.SileroLegacy}});var g=nf();Object.defineProperty(S,"SileroV5",{enumerable:!0,get:function(){return g.SileroV5}})})(ms)),ms}var Bi={},zh;function tp(){if(zh)return Bi;zh=1,Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.Resampler=void 0;const S=Ds();class s{constructor(d){this.options=d,this.process=g=>{const E=[];for(const A of g)for(this.inputBuffer.push(A);this.hasEnoughDataForFrame();){const O=this.generateOutputFrame();E.push(O)}return E},d.nativeSampleRate<16e3&&S.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(d){for(const g of d)for(this.inputBuffer.push(g);this.hasEnoughDataForFrame();)yield this.generateOutputFrame()}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){const d=new Float32Array(this.options.targetFrameSize);let g=0,E=0;for(;g<this.options.targetFrameSize;){let A=0,O=0;for(;E<Math.min(this.inputBuffer.length,(g+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const T=this.inputBuffer[E];T!==void 0&&(A+=T,O++),E++}d[g]=A/O,g++}return this.inputBuffer=this.inputBuffer.slice(E),d}}return Bi.Resampler=s,Bi}var Dh;function af(){return Dh||(Dh=1,(function(S){var s=Sr&&Sr.__createBinding||(Object.create?(function(J,ie,re,ne){ne===void 0&&(ne=re);var fe=Object.getOwnPropertyDescriptor(ie,re);(!fe||("get"in fe?!ie.__esModule:fe.writable||fe.configurable))&&(fe={enumerable:!0,get:function(){return ie[re]}}),Object.defineProperty(J,ne,fe)}):(function(J,ie,re,ne){ne===void 0&&(ne=re),J[ne]=ie[re]})),n=Sr&&Sr.__setModuleDefault||(Object.create?(function(J,ie){Object.defineProperty(J,"default",{enumerable:!0,value:ie})}):function(J,ie){J.default=ie}),d=Sr&&Sr.__importStar||function(J){if(J&&J.__esModule)return J;var ie={};if(J!=null)for(var re in J)re!=="default"&&Object.prototype.hasOwnProperty.call(J,re)&&s(ie,J,re);return n(ie,J),ie};Object.defineProperty(S,"__esModule",{value:!0}),S.NonRealTimeVAD=S.defaultNonRealTimeVADOptions=void 0;const g=d(tf()),E=Zh(),A=Ga(),O=Wa(),T=cn(),K=ep(),G=tp();S.defaultNonRealTimeVADOptions={...O.defaultFrameProcessorOptions,modelURL:E.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:A.defaultModelFetcher};class ae{static async new(ie={}){const re={...S.defaultNonRealTimeVADOptions,...ie};(0,O.validateOptions)(re),re.ortConfig!==void 0&&re.ortConfig(g);const ne=()=>re.modelFetcher(re.modelURL),fe=await K.SileroLegacy.new(g,ne),Re=new O.FrameProcessor(fe.process,fe.reset_state,{positiveSpeechThreshold:re.positiveSpeechThreshold,negativeSpeechThreshold:re.negativeSpeechThreshold,redemptionMs:re.redemptionMs,preSpeechPadMs:re.preSpeechPadMs,minSpeechMs:re.minSpeechMs,submitUserSpeechOnPause:re.submitUserSpeechOnPause},1536/16);return Re.resume(),new this(ne,g,re,Re)}constructor(ie,re,ne,fe){this.modelFetcher=ie,this.ort=re,this.options=ne,this.frameProcessor=fe,this.frameSamples=1536}async*run(ie,re){const ne={nativeSampleRate:re,targetSampleRate:16e3,targetFrameSize:this.frameSamples},fe=new G.Resampler(ne);let Re=0,Pe=0,ce=0;for await(const ye of fe.stream(ie)){const me=[];await this.frameProcessor.process(ye,We=>{me.push(We)});for(const We of me)switch(We.msg){case T.Message.SpeechStart:Re=ce*this.frameSamples/16;break;case T.Message.SpeechEnd:Pe=(ce+1)*this.frameSamples/16,yield{audio:We.audio,start:Re,end:Pe};break}ce++}const le=[];this.frameProcessor.endSegment(ye=>{le.push(ye)});for(const ye of le)switch(ye.msg){case T.Message.SpeechEnd:yield{audio:ye.audio,start:Re,end:ce*this.frameSamples/16}}}}S.NonRealTimeVAD=ae})(Sr)),Sr}var ir={},Lh;function of(){if(Lh)return ir;Lh=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.audioFileToArray=ir.encodeWAV=ir.arrayBufferToBase64=ir.minFramesForTargetMS=void 0;function S(O,T,K=16e3){return Math.ceil(O*K/1e3/T)}ir.minFramesForTargetMS=S;function s(O){const T=new Uint8Array(O),K=T.byteLength,G=new Array(K);for(let ae=0;ae<K;ae++){const J=T[ae];if(J===void 0)break;G[ae]=String.fromCharCode(J)}return btoa(G.join(""))}ir.arrayBufferToBase64=s;function n(O,T=3,K=16e3,G=1,ae=32){const J=ae/8,ie=G*J,re=new ArrayBuffer(44+O.length*J),ne=new DataView(re);return E(ne,0,"RIFF"),ne.setUint32(4,36+O.length*J,!0),E(ne,8,"WAVE"),E(ne,12,"fmt "),ne.setUint32(16,16,!0),ne.setUint16(20,T,!0),ne.setUint16(22,G,!0),ne.setUint32(24,K,!0),ne.setUint32(28,K*ie,!0),ne.setUint16(32,ie,!0),ne.setUint16(34,ae,!0),E(ne,36,"data"),ne.setUint32(40,O.length*J,!0),T===1?g(ne,44,O):d(ne,44,O),re}ir.encodeWAV=n;function d(O,T,K){for(let G=0;G<K.length;G++,T+=4)O.setFloat32(T,K[G],!0)}function g(O,T,K){for(let G=0;G<K.length;G++,T+=2){const ae=Math.max(-1,Math.min(1,K[G]));O.setInt16(T,ae<0?ae*32768:ae*32767,!0)}}function E(O,T,K){for(let G=0;G<K.length;G++)O.setUint8(T+G,K.charCodeAt(G))}async function A(O){const T=new OfflineAudioContext(1,1,44100),K=new FileReader;let G=null;if(await new Promise(ie=>{K.addEventListener("loadend",()=>{const re=K.result;T.decodeAudioData(re,ne=>{G=ne,T.startRendering().then(()=>{console.log("Rendering completed successfully"),ie()}).catch(fe=>{console.error("Rendering failed: ",fe)})},ne=>{console.log("Error with decoding audio data: ",ne)})}),K.readAsArrayBuffer(O)}),G===null)throw Error("some shit");const ae=G,J=new Float32Array(ae.length);for(let ie=0;ie<ae.length;ie++)for(let re=0;re<ae.numberOfChannels;re++){const ne=ae.getChannelData(re)[ie],fe=J[ie];if(ne===void 0||fe===void 0)throw new Error("sample or out[i] is undefined");J[ie]=fe+ne}return{audio:J,sampleRate:ae.sampleRate}}return ir.audioFileToArray=A,ir}var $r={},Ra={exports:{}};/*!
|
|
2835
|
+
* ONNX Runtime Web v1.26.0
|
|
2836
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2837
|
+
* Licensed under the MIT License.
|
|
2838
|
+
*/var Bh;function lf(){return Bh||(Bh=1,(function(S,s){var n=(()=>{var d=Object.defineProperty,g=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,A=Object.prototype.hasOwnProperty,O=(f=>typeof jt<"u"?jt:typeof Proxy<"u"?new Proxy(f,{get:(_,k)=>(typeof jt<"u"?jt:_)[k]}):f)(function(f){if(typeof jt<"u")return jt.apply(this,arguments);throw Error('Dynamic require of "'+f+'" is not supported')}),T=(f,_)=>()=>(f&&(_=f(f=0)),_),K=(f,_)=>{for(var k in _)d(f,k,{get:_[k],enumerable:!0})},G=(f,_,k,z)=>{if(_&&typeof _=="object"||typeof _=="function")for(let P of E(_))!A.call(f,P)&&P!==k&&d(f,P,{get:()=>_[P],enumerable:!(z=g(_,P))||z.enumerable});return f},ae=f=>G(d({},"__esModule",{value:!0}),f),J,ie,re,ne,fe,Re=T(()=>{J=new Map,ie=[],re=(f,_,k)=>{if(_&&typeof _.init=="function"&&typeof _.createInferenceSessionHandler=="function"){let z=J.get(f);if(z===void 0)J.set(f,{backend:_,priority:k});else{if(z.priority>k)return;if(z.priority===k&&z.backend!==_)throw new Error(`cannot register backend "${f}" using priority ${k}`)}if(k>=0){let P=ie.indexOf(f);P!==-1&&ie.splice(P,1);for(let N=0;N<ie.length;N++)if(J.get(ie[N]).priority<=k){ie.splice(N,0,f);return}ie.push(f)}return}throw new TypeError("not a valid backend")},ne=async f=>{let _=J.get(f);if(!_)return"backend not found.";if(_.initialized)return _.backend;if(_.aborted)return _.error;{let k=!!_.initPromise;try{return k||(_.initPromise=_.backend.init(f)),await _.initPromise,_.initialized=!0,_.backend}catch(z){return k||(_.error=`${z}`,_.aborted=!0),_.error}finally{delete _.initPromise}}},fe=async f=>{let _=f.executionProviders||[],k=_.map(F=>typeof F=="string"?F:F.name),z=k.length===0?ie:k,P,N=[],B=new Set;for(let F of z){let Z=await ne(F);typeof Z=="string"?N.push({name:F,err:Z}):(P||(P=Z),P===Z&&B.add(F))}if(!P)throw new Error(`no available backend found. ERR: ${N.map(F=>`[${F.name}] ${F.err}`).join(", ")}`);for(let{name:F,err:Z}of N)k.includes(F)&&console.warn(`removing requested execution provider "${F}" from session options because it is not available: ${Z}`);let D=_.filter(F=>B.has(typeof F=="string"?F:F.name));return[P,new Proxy(f,{get:(F,Z)=>Z==="executionProviders"?D:Reflect.get(F,Z)})]}}),Pe=T(()=>{Re()}),ce,le=T(()=>{ce="1.26.0"}),ye,me,We=T(()=>{le(),ye="warning",me={wasm:{},webgl:{},webgpu:{},versions:{common:ce},set logLevel(f){if(f!==void 0){if(typeof f!="string"||["verbose","info","warning","error","fatal"].indexOf(f)===-1)throw new Error(`Unsupported logging level: ${f}`);ye=f}},get logLevel(){return ye}},Object.defineProperty(me,"logLevel",{enumerable:!0})}),de,st=T(()=>{We(),de=me}),qe,dt,Qe=T(()=>{qe=(f,_)=>{let k=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);k.width=f.dims[3],k.height=f.dims[2];let z=k.getContext("2d");if(z!=null){let P,N;_?.tensorLayout!==void 0&&_.tensorLayout==="NHWC"?(P=f.dims[2],N=f.dims[3]):(P=f.dims[3],N=f.dims[2]);let B=_?.format!==void 0?_.format:"RGB",D=_?.norm,F,Z;D===void 0||D.mean===void 0?F=[255,255,255,255]:typeof D.mean=="number"?F=[D.mean,D.mean,D.mean,D.mean]:(F=[D.mean[0],D.mean[1],D.mean[2],0],D.mean[3]!==void 0&&(F[3]=D.mean[3])),D===void 0||D.bias===void 0?Z=[0,0,0,0]:typeof D.bias=="number"?Z=[D.bias,D.bias,D.bias,D.bias]:(Z=[D.bias[0],D.bias[1],D.bias[2],0],D.bias[3]!==void 0&&(Z[3]=D.bias[3]));let Y=N*P,Q=0,H=Y,ve=Y*2,U=-1;B==="RGBA"?(Q=0,H=Y,ve=Y*2,U=Y*3):B==="RGB"?(Q=0,H=Y,ve=Y*2):B==="RBG"&&(Q=0,ve=Y,H=Y*2);for(let te=0;te<N;te++)for(let tt=0;tt<P;tt++){let ze=(f.data[Q++]-Z[0])*F[0],be=(f.data[H++]-Z[1])*F[1],De=(f.data[ve++]-Z[2])*F[2],he=U===-1?255:(f.data[U++]-Z[3])*F[3];z.fillStyle="rgba("+ze+","+be+","+De+","+he+")",z.fillRect(tt,te,1,1)}if("toDataURL"in k)return k.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},dt=(f,_)=>{let k=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),z;if(k!=null){let P,N,B;_?.tensorLayout!==void 0&&_.tensorLayout==="NHWC"?(P=f.dims[2],N=f.dims[1],B=f.dims[3]):(P=f.dims[3],N=f.dims[2],B=f.dims[1]);let D=_!==void 0&&_.format!==void 0?_.format:"RGB",F=_?.norm,Z,Y;F===void 0||F.mean===void 0?Z=[255,255,255,255]:typeof F.mean=="number"?Z=[F.mean,F.mean,F.mean,F.mean]:(Z=[F.mean[0],F.mean[1],F.mean[2],255],F.mean[3]!==void 0&&(Z[3]=F.mean[3])),F===void 0||F.bias===void 0?Y=[0,0,0,0]:typeof F.bias=="number"?Y=[F.bias,F.bias,F.bias,F.bias]:(Y=[F.bias[0],F.bias[1],F.bias[2],0],F.bias[3]!==void 0&&(Y[3]=F.bias[3]));let Q=N*P;if(_!==void 0&&(_.format!==void 0&&B===4&&_.format!=="RGBA"||B===3&&_.format!=="RGB"&&_.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let H=4,ve=0,U=1,te=2,tt=3,ze=0,be=Q,De=Q*2,he=-1;D==="RGBA"?(ze=0,be=Q,De=Q*2,he=Q*3):D==="RGB"?(ze=0,be=Q,De=Q*2):D==="RBG"&&(ze=0,De=Q,be=Q*2),z=k.createImageData(P,N);for(let _t=0;_t<N*P;ve+=H,U+=H,te+=H,tt+=H,_t++)z.data[ve]=(f.data[ze++]-Y[0])*Z[0],z.data[U]=(f.data[be++]-Y[1])*Z[1],z.data[te]=(f.data[De++]-Y[2])*Z[2],z.data[tt]=he===-1?255:(f.data[he++]-Y[3])*Z[3]}else throw new Error("Can not access image data");return z}}),ut,at,Kt,Ct,je,Ve,et=T(()=>{zr(),ut=(f,_)=>{if(f===void 0)throw new Error("Image buffer must be defined");if(_.height===void 0||_.width===void 0)throw new Error("Image height and width must be defined");if(_.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:k,width:z}=_,P=_.norm??{mean:255,bias:0},N,B;typeof P.mean=="number"?N=[P.mean,P.mean,P.mean,P.mean]:N=[P.mean[0],P.mean[1],P.mean[2],P.mean[3]??255],typeof P.bias=="number"?B=[P.bias,P.bias,P.bias,P.bias]:B=[P.bias[0],P.bias[1],P.bias[2],P.bias[3]??0];let D=_.format!==void 0?_.format:"RGBA",F=_.tensorFormat!==void 0&&_.tensorFormat!==void 0?_.tensorFormat:"RGB",Z=k*z,Y=F==="RGBA"?new Float32Array(Z*4):new Float32Array(Z*3),Q=4,H=0,ve=1,U=2,te=3,tt=0,ze=Z,be=Z*2,De=-1;D==="RGB"&&(Q=3,H=0,ve=1,U=2,te=-1),F==="RGBA"?De=Z*3:F==="RBG"?(tt=0,be=Z,ze=Z*2):F==="BGR"&&(be=0,ze=Z,tt=Z*2);for(let he=0;he<Z;he++,H+=Q,U+=Q,ve+=Q,te+=Q)Y[tt++]=(f[H]+B[0])/N[0],Y[ze++]=(f[ve]+B[1])/N[1],Y[be++]=(f[U]+B[2])/N[2],De!==-1&&te!==-1&&(Y[De++]=(f[te]+B[3])/N[3]);return F==="RGBA"?new Je("float32",Y,[1,4,k,z]):new Je("float32",Y,[1,3,k,z])},at=async(f,_)=>{let k=typeof HTMLImageElement<"u"&&f instanceof HTMLImageElement,z=typeof ImageData<"u"&&f instanceof ImageData,P=typeof ImageBitmap<"u"&&f instanceof ImageBitmap,N=typeof f=="string",B,D=_??{},F=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},Z=Y=>typeof HTMLCanvasElement<"u"&&Y instanceof HTMLCanvasElement||Y instanceof OffscreenCanvas?Y.getContext("2d"):null;if(k){let Y=F();Y.width=f.width,Y.height=f.height;let Q=Z(Y);if(Q!=null){let H=f.height,ve=f.width;if(_!==void 0&&_.resizedHeight!==void 0&&_.resizedWidth!==void 0&&(H=_.resizedHeight,ve=_.resizedWidth),_!==void 0){if(D=_,_.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");D.tensorFormat="RGBA",D.height=H,D.width=ve}else D.tensorFormat="RGBA",D.height=H,D.width=ve;Q.drawImage(f,0,0),B=Q.getImageData(0,0,ve,H).data}else throw new Error("Can not access image data")}else if(z){let Y,Q;if(_!==void 0&&_.resizedWidth!==void 0&&_.resizedHeight!==void 0?(Y=_.resizedHeight,Q=_.resizedWidth):(Y=f.height,Q=f.width),_!==void 0&&(D=_),D.format="RGBA",D.height=Y,D.width=Q,_!==void 0){let H=F();H.width=Q,H.height=Y;let ve=Z(H);if(ve!=null)ve.putImageData(f,0,0),B=ve.getImageData(0,0,Q,Y).data;else throw new Error("Can not access image data")}else B=f.data}else if(P){if(_===void 0)throw new Error("Please provide image config with format for Imagebitmap");let Y=F();Y.width=f.width,Y.height=f.height;let Q=Z(Y);if(Q!=null){let H=f.height,ve=f.width;return Q.drawImage(f,0,0,ve,H),B=Q.getImageData(0,0,ve,H).data,D.height=H,D.width=ve,ut(B,D)}else throw new Error("Can not access image data")}else{if(N)return new Promise((Y,Q)=>{let H=F(),ve=Z(H);if(!f||!ve)return Q();let U=new Image;U.crossOrigin="Anonymous",U.src=f,U.onload=()=>{H.width=U.width,H.height=U.height,ve.drawImage(U,0,0,H.width,H.height);let te=ve.getImageData(0,0,H.width,H.height);D.height=H.height,D.width=H.width,Y(ut(te.data,D))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(B!==void 0)return ut(B,D);throw new Error("Input data provided is not supported - aborted tensor creation")},Kt=(f,_)=>{let{width:k,height:z,download:P,dispose:N}=_,B=[1,z,k,4];return new Je({location:"texture",type:"float32",texture:f,dims:B,download:P,dispose:N})},Ct=(f,_)=>{let{dataType:k,dims:z,download:P,dispose:N}=_;return new Je({location:"gpu-buffer",type:k??"float32",gpuBuffer:f,dims:z,download:P,dispose:N})},je=(f,_)=>{let{dataType:k,dims:z,download:P,dispose:N}=_;return new Je({location:"ml-tensor",type:k??"float32",mlTensor:f,dims:z,download:P,dispose:N})},Ve=(f,_,k)=>new Je({location:"cpu-pinned",type:f,data:_,dims:k??[_.length]})}),Xe,Rt,mr,Bs,hn=T(()=>{Xe=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Rt=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),mr=!1,Bs=()=>{if(!mr){mr=!0;let f=typeof BigInt64Array<"u"&&BigInt64Array.from,_=typeof BigUint64Array<"u"&&BigUint64Array.from,k=globalThis.Float16Array,z=typeof k<"u"&&k.from;f&&(Xe.set("int64",BigInt64Array),Rt.set(BigInt64Array,"int64")),_&&(Xe.set("uint64",BigUint64Array),Rt.set(BigUint64Array,"uint64")),z?(Xe.set("float16",k),Rt.set(k,"float16")):Xe.set("float16",Uint16Array)}}}),Us,Fs,pn=T(()=>{zr(),Us=f=>{let _=1;for(let k=0;k<f.length;k++){let z=f[k];if(typeof z!="number"||!Number.isSafeInteger(z))throw new TypeError(`dims[${k}] must be an integer, got: ${z}`);if(z<0)throw new RangeError(`dims[${k}] must be a non-negative integer, got: ${z}`);_*=z}return _},Fs=(f,_)=>{switch(f.location){case"cpu":return new Je(f.type,f.data,_);case"cpu-pinned":return new Je({location:"cpu-pinned",data:f.data,type:f.type,dims:_});case"texture":return new Je({location:"texture",texture:f.texture,type:f.type,dims:_});case"gpu-buffer":return new Je({location:"gpu-buffer",gpuBuffer:f.gpuBuffer,type:f.type,dims:_});case"ml-tensor":return new Je({location:"ml-tensor",mlTensor:f.mlTensor,type:f.type,dims:_});default:throw new Error(`tensorReshape: tensor location ${f.location} is not supported`)}}}),Je,zr=T(()=>{Qe(),et(),hn(),pn(),Je=class{constructor(f,_,k){Bs();let z,P;if(typeof f=="object"&&"location"in f)switch(this.dataLocation=f.location,z=f.type,P=f.dims,f.location){case"cpu-pinned":{let B=Xe.get(z);if(!B)throw new TypeError(`unsupported type "${z}" to create tensor from pinned buffer`);if(!(f.data instanceof B))throw new TypeError(`buffer should be of type ${B.name}`);this.cpuData=f.data;break}case"texture":{if(z!=="float32")throw new TypeError(`unsupported type "${z}" to create tensor from texture`);this.gpuTextureData=f.texture,this.downloader=f.download,this.disposer=f.dispose;break}case"gpu-buffer":{if(z!=="float32"&&z!=="float16"&&z!=="int32"&&z!=="int64"&&z!=="uint32"&&z!=="uint8"&&z!=="bool"&&z!=="uint4"&&z!=="int4")throw new TypeError(`unsupported type "${z}" to create tensor from gpu buffer`);this.gpuBufferData=f.gpuBuffer,this.downloader=f.download,this.disposer=f.dispose;break}case"ml-tensor":{if(z!=="float32"&&z!=="float16"&&z!=="int32"&&z!=="int64"&&z!=="uint32"&&z!=="uint64"&&z!=="int8"&&z!=="uint8"&&z!=="bool"&&z!=="uint4"&&z!=="int4")throw new TypeError(`unsupported type "${z}" to create tensor from MLTensor`);this.mlTensorData=f.mlTensor,this.downloader=f.download,this.disposer=f.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let B,D;if(typeof f=="string")if(z=f,D=k,f==="string"){if(!Array.isArray(_))throw new TypeError("A string tensor's data must be a string array.");B=_}else{let F=Xe.get(f);if(F===void 0)throw new TypeError(`Unsupported tensor type: ${f}.`);if(Array.isArray(_)){if(f==="float16"&&F===Uint16Array||f==="uint4"||f==="int4")throw new TypeError(`Creating a ${f} tensor from number array is not supported. Please use ${F.name} as data.`);f==="uint64"||f==="int64"?B=F.from(_,BigInt):B=F.from(_)}else if(_ instanceof F)B=_;else if(_ instanceof Uint8ClampedArray)if(f==="uint8")B=Uint8Array.from(_);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(f==="float16"&&_ instanceof Uint16Array&&F!==Uint16Array)B=new globalThis.Float16Array(_.buffer,_.byteOffset,_.length);else throw new TypeError(`A ${z} tensor's data must be type of ${F}`)}else if(D=_,Array.isArray(f)){if(f.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let F=typeof f[0];if(F==="string")z="string",B=f;else if(F==="boolean")z="bool",B=Uint8Array.from(f);else throw new TypeError(`Invalid element type of data array: ${F}.`)}else if(f instanceof Uint8ClampedArray)z="uint8",B=Uint8Array.from(f);else{let F=Rt.get(f.constructor);if(F===void 0)throw new TypeError(`Unsupported type for tensor data: ${f.constructor}.`);z=F,B=f}if(D===void 0)D=[B.length];else if(!Array.isArray(D))throw new TypeError("A tensor's dims must be a number array");P=D,this.cpuData=B,this.dataLocation="cpu"}let N=Us(P);if(this.cpuData&&N!==this.cpuData.length&&!((z==="uint4"||z==="int4")&&Math.ceil(N/2)===this.cpuData.length))throw new Error(`Tensor's size(${N}) does not match data length(${this.cpuData.length}).`);this.type=z,this.dims=P,this.size=N}static async fromImage(f,_){return at(f,_)}static fromTexture(f,_){return Kt(f,_)}static fromGpuBuffer(f,_){return Ct(f,_)}static fromMLTensor(f,_){return je(f,_)}static fromPinnedBuffer(f,_,k){return Ve(f,_,k)}toDataURL(f){return qe(this,f)}toImageData(f){return dt(this,f)}get data(){if(this.ensureValid(),!this.cpuData)throw new 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 new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(f){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 new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let _=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=_,f&&this.disposer&&(this.disposer(),this.disposer=void 0),_}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(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 new Error("The tensor is disposed.")}reshape(f){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Fs(this,f)}}}),ot,Ns=T(()=>{zr(),ot=Je}),ar,Dr,bt,yt,Et,kt,Vs=T(()=>{We(),ar=(f,_)=>{(typeof me.trace>"u"?!me.wasm.trace:!me.trace)||console.timeStamp(`${f}::ORT::${_}`)},Dr=(f,_)=>{let k=new Error().stack?.split(/\r\n|\r|\n/g)||[],z=!1;for(let P=0;P<k.length;P++){if(z&&!k[P].includes("TRACE_FUNC")){let N=`FUNC_${f}::${k[P].trim().split(" ")[1]}`;_&&(N+=`::${_}`),ar("CPU",N);return}k[P].includes("TRACE_FUNC")&&(z=!0)}},bt=f=>{(typeof me.trace>"u"?!me.wasm.trace:!me.trace)||Dr("BEGIN",f)},yt=f=>{(typeof me.trace>"u"?!me.wasm.trace:!me.trace)||Dr("END",f)},Et=f=>{(typeof me.trace>"u"?!me.wasm.trace:!me.trace)||console.time(`ORT::${f}`)},kt=f=>{(typeof me.trace>"u"?!me.wasm.trace:!me.trace)||console.timeEnd(`ORT::${f}`)}}),Gs,mn=T(()=>{Re(),Ns(),Vs(),Gs=class rp{constructor(_){this.handler=_}async run(_,k,z){bt(),Et("InferenceSession.run");let P={},N={};if(typeof _!="object"||_===null||_ instanceof ot||Array.isArray(_))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let B=!0;if(typeof k=="object"){if(k===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(k instanceof ot)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(k)){if(k.length===0)throw new TypeError("'fetches' cannot be an empty array.");B=!1;for(let Z of k){if(typeof Z!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(Z)===-1)throw new RangeError(`'fetches' contains invalid output name: ${Z}.`);P[Z]=null}if(typeof z=="object"&&z!==null)N=z;else if(typeof z<"u")throw new TypeError("'options' must be an object.")}else{let Z=!1,Y=Object.getOwnPropertyNames(k);for(let Q of this.outputNames)if(Y.indexOf(Q)!==-1){let H=k[Q];(H===null||H instanceof ot)&&(Z=!0,B=!1,P[Q]=H)}if(Z){if(typeof z=="object"&&z!==null)N=z;else if(typeof z<"u")throw new TypeError("'options' must be an object.")}else N=k}}else if(typeof k<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let Z of this.inputNames)if(typeof _[Z]>"u")throw new Error(`input '${Z}' is missing in 'feeds'.`);if(B)for(let Z of this.outputNames)P[Z]=null;let D=await this.handler.run(_,P,N),F={};for(let Z in D)if(Object.hasOwnProperty.call(D,Z)){let Y=D[Z];Y instanceof ot?F[Z]=Y:F[Z]=new ot(Y.type,Y.data,Y.dims)}return kt("InferenceSession.run"),yt(),F}async release(){return this.handler.dispose()}static async create(_,k,z,P){bt(),Et("InferenceSession.create");let N,B={};if(typeof _=="string"){if(N=_,typeof k=="object"&&k!==null)B=k;else if(typeof k<"u")throw new TypeError("'options' must be an object.")}else if(_ instanceof Uint8Array){if(N=_,typeof k=="object"&&k!==null)B=k;else if(typeof k<"u")throw new TypeError("'options' must be an object.")}else if(_ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&_ instanceof SharedArrayBuffer){let Y=_,Q=0,H=_.byteLength;if(typeof k=="object"&&k!==null)B=k;else if(typeof k=="number"){if(Q=k,!Number.isSafeInteger(Q))throw new RangeError("'byteOffset' must be an integer.");if(Q<0||Q>=Y.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${Y.byteLength}).`);if(H=_.byteLength-Q,typeof z=="number"){if(H=z,!Number.isSafeInteger(H))throw new RangeError("'byteLength' must be an integer.");if(H<=0||Q+H>Y.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${Y.byteLength-Q}].`);if(typeof P=="object"&&P!==null)B=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(typeof z<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof k<"u")throw new TypeError("'options' must be an object.");N=new Uint8Array(Y,Q,H)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[D,F]=await fe(B),Z=await D.createInferenceSessionHandler(N,F);return kt("InferenceSession.create"),yt(),new rp(Z)}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}}}),Lr,fn=T(()=>{mn(),Lr=Gs}),gn=T(()=>{}),yn=T(()=>{}),wn=T(()=>{}),vn=T(()=>{}),Ws={};K(Ws,{InferenceSession:()=>Lr,TRACE:()=>ar,TRACE_EVENT_BEGIN:()=>Et,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>bt,TRACE_FUNC_END:()=>yt,Tensor:()=>ot,env:()=>de,registerBackend:()=>re});var wt=T(()=>{Pe(),st(),fn(),Ns(),gn(),yn(),Vs(),wn(),vn()}),Br=T(()=>{}),qs={};K(qs,{default:()=>Hs});var Ur,Fr,Hs,bn=T(()=>{ci(),Dt(),qr(),Ur="ort-wasm-proxy-worker",Fr=globalThis.self?.name===Ur,Fr&&(self.onmessage=f=>{let{type:_,in:k}=f.data;try{switch(_){case"init-wasm":Kr(k.wasm).then(()=>{ys(k).then(()=>{postMessage({type:_})},z=>{postMessage({type:_,err:z})})},z=>{postMessage({type:_,err:z})});break;case"init-ep":{let{epName:z,env:P}=k;ws(P,z).then(()=>{postMessage({type:_})},N=>{postMessage({type:_,err:N})});break}case"copy-from":{let{buffer:z}=k,P=Fe(z);postMessage({type:_,out:P});break}case"create":{let{model:z,options:P}=k;Vt(z,P).then(N=>{postMessage({type:_,out:N})},N=>{postMessage({type:_,err:N})});break}case"release":_s(k),postMessage({type:_});break;case"run":{let{sessionId:z,inputIndices:P,inputs:N,outputIndices:B,options:D}=k;q(z,P,N,B,new Array(B.length).fill(null),D).then(F=>{F.some(Z=>Z[3]!=="cpu")?postMessage({type:_,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:_,out:F},Ss([...N,...F]))},F=>{postMessage({type:_,err:F})});break}case"end-profiling":Er(k),postMessage({type:_});break;default:}}catch(z){postMessage({type:_,err:z})}}),Hs=Fr?null:f=>new Worker(f??Ye,{type:"classic",name:Ur})}),js,Ks,Ye,Nr,fr,Qs,Xs,Vr,Zs,Gr,Js,Wr,Ys,qr=T(()=>{Br(),js=typeof location>"u"?void 0:location.origin,Ks=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,Ye=Ks(),Nr=()=>{if(Ye&&!Ye.startsWith("blob:"))return Ye.substring(0,Ye.lastIndexOf("/")+1)},fr=(f,_)=>{try{let k=_??Ye;return(k?new URL(f,k):new URL(f)).origin===js}catch{return!1}},Qs=(f,_)=>{let k=_??Ye;try{return(k?new URL(f,k):new URL(f)).href}catch{return}},Xs=(f,_)=>`${_??"./"}${f}`,Vr=async f=>{let _=await(await fetch(f,{credentials:"same-origin"})).blob();return URL.createObjectURL(_)},Zs=async f=>(await import(f)).default,Gr=(bn(),ae(qs)).default,Js=async()=>{if(!Ye)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(fr(Ye))return[void 0,Gr()];let f=await Vr(Ye);return[f,Gr(f)]},Wr=void 0,Ys=async(f,_,k,z)=>{let P=Wr&&!(f||_);if(P)if(Ye)P=fr(Ye)||z&&!k;else if(z&&!k)P=!0;else throw new Error("cannot determine the script source URL.");if(P)return[void 0,Wr];{let N="ort-wasm-simd-threaded.mjs",B=f??Qs(N,_),D=k&&B&&!fr(B,_),F=D?await Vr(B):B??Xs(N,_);return[D?F:void 0,await Zs(F)]}}}),Hr,gr,Qt,jr,ei,ti,ri,Kr,Me,Dt=T(()=>{qr(),gr=!1,Qt=!1,jr=!1,ei=()=>{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}},ti=()=>{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}},ri=()=>{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}},Kr=async f=>{if(gr)return Promise.resolve();if(Qt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(jr)throw new Error("previous call to 'initializeWebAssembly()' failed.");Qt=!0;let _=f.initTimeout,k=f.numThreads;if(f.simd!==!1){if(f.simd==="relaxed"){if(!ri())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ti())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let z=ei();k>1&&!z&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+k+", 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."),f.numThreads=k=1);let P=f.wasmPaths,N=typeof P=="string"?P:void 0,B=P?.mjs,D=B?.href??B,F=P?.wasm,Z=F?.href??F,Y=f.wasmBinary,[Q,H]=await Ys(D,N,k>1,!!Y||!!Z),ve=!1,U=[];if(_>0&&U.push(new Promise(te=>{setTimeout(()=>{ve=!0,te()},_)})),U.push(new Promise((te,tt)=>{let ze={numThreads:k};if(Y)ze.wasmBinary=Y,ze.locateFile=be=>be;else if(Z||N)ze.locateFile=be=>Z??N+be;else if(D&&D.indexOf("blob:")!==0)ze.locateFile=be=>new URL(be,D).href;else if(Q){let be=Nr();be&&(ze.locateFile=De=>be+De)}H(ze).then(be=>{Qt=!1,gr=!0,Hr=be,te(),Q&&URL.revokeObjectURL(Q)},be=>{Qt=!1,jr=!0,tt(be)})})),await Promise.race(U),ve)throw new Error(`WebAssembly backend initializing failed due to timeout: ${_}ms`)},Me=()=>{if(gr&&Hr)return Hr;throw new Error("WebAssembly is not initialized yet.")}}),lt,yr,$e,Qr=T(()=>{Dt(),lt=(f,_)=>{let k=Me(),z=k.lengthBytesUTF8(f)+1,P=k._malloc(z);return k.stringToUTF8(f,P,z),_.push(P),P},yr=(f,_,k,z)=>{if(typeof f=="object"&&f!==null){if(k.has(f))throw new Error("Circular reference in options");k.add(f)}Object.entries(f).forEach(([P,N])=>{let B=_?_+P:P;if(typeof N=="object")yr(N,B+".",k,z);else if(typeof N=="string"||typeof N=="number")z(B,N.toString());else if(typeof N=="boolean")z(B,N?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof N}`)})},$e=f=>{let _=Me(),k=_.stackSave();try{let z=_.PTR_SIZE,P=_.stackAlloc(2*z);_._OrtGetLastError(P,P+z);let N=Number(_.getValue(P,z===4?"i32":"i64")),B=_.getValue(P+z,"*"),D=B?_.UTF8ToString(B):"";throw new Error(`${f} ERROR_CODE: ${N}, ERROR_MESSAGE: ${D}`)}finally{_.stackRestore(k)}}}),si,_n=T(()=>{Dt(),Qr(),si=f=>{let _=Me(),k=0,z=[],P=f||{};try{if(f?.logSeverityLevel===void 0)P.logSeverityLevel=2;else if(typeof f.logSeverityLevel!="number"||!Number.isInteger(f.logSeverityLevel)||f.logSeverityLevel<0||f.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${f.logSeverityLevel}`);if(f?.logVerbosityLevel===void 0)P.logVerbosityLevel=0;else if(typeof f.logVerbosityLevel!="number"||!Number.isInteger(f.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${f.logVerbosityLevel}`);f?.terminate===void 0&&(P.terminate=!1);let N=0;return f?.tag!==void 0&&(N=lt(f.tag,z)),k=_._OrtCreateRunOptions(P.logSeverityLevel,P.logVerbosityLevel,!!P.terminate,N),k===0&&$e("Can't create run options."),f?.extra!==void 0&&yr(f.extra,"",new WeakSet,(B,D)=>{let F=lt(B,z),Z=lt(D,z);_._OrtAddRunConfigEntry(k,F,Z)!==0&&$e(`Can't set a run config entry: ${B} - ${D}.`)}),[k,z]}catch(N){throw k!==0&&_._OrtReleaseRunOptions(k),z.forEach(B=>_._free(B)),N}}}),ii,ni,ai,It,oi,li,Sn=T(()=>{Dt(),Qr(),ii=f=>{switch(f){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${f}`)}},ni=f=>{switch(f){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${f}`)}},ai=f=>{f.extra||(f.extra={}),f.extra.session||(f.extra.session={});let _=f.extra.session;_.use_ort_model_bytes_directly||(_.use_ort_model_bytes_directly="1"),f.executionProviders&&f.executionProviders.some(k=>(typeof k=="string"?k:k.name)==="webgpu")&&(f.enableMemPattern=!1)},It=(f,_,k,z)=>{let P=lt(_,z),N=lt(k,z);Me()._OrtAddSessionConfigEntry(f,P,N)!==0&&$e(`Can't set a session config entry: ${_} - ${k}.`)},oi=async(f,_,k)=>{let z=_.executionProviders;for(let P of z){let N=typeof P=="string"?P:P.name,B=[];switch(N){case"webnn":if(N="WEBNN",It(f,"session.disable_quant_qdq","1",k),It(f,"session.disable_qdq_constant_folding","1",k),typeof P!="string"){let Q=P?.deviceType;Q&&It(f,"deviceType",Q,k)}break;case"webgpu":if(N="JS",typeof P!="string"){let Q=P;if(Q?.preferredLayout){if(Q.preferredLayout!=="NCHW"&&Q.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${Q.preferredLayout}`);It(f,"preferredLayout",Q.preferredLayout,k)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${N}`)}let D=lt(N,k),F=B.length,Z=0,Y=0;if(F>0){Z=Me()._malloc(F*Me().PTR_SIZE),k.push(Z),Y=Me()._malloc(F*Me().PTR_SIZE),k.push(Y);for(let Q=0;Q<F;Q++)Me().setValue(Z+Q*Me().PTR_SIZE,B[Q][0],"*"),Me().setValue(Y+Q*Me().PTR_SIZE,B[Q][1],"*")}await Me()._OrtAppendExecutionProvider(f,D,Z,Y,F)!==0&&$e(`Can't append execution provider: ${N}.`)}},li=async f=>{let _=Me(),k=0,z=[],P=f||{};ai(P);try{let N=ii(P.graphOptimizationLevel??"all"),B=ni(P.executionMode??"sequential"),D=typeof P.logId=="string"?lt(P.logId,z):0,F=P.logSeverityLevel??2;if(!Number.isInteger(F)||F<0||F>4)throw new Error(`log severity level is not valid: ${F}`);let Z=P.logVerbosityLevel??0;if(!Number.isInteger(Z)||Z<0||Z>4)throw new Error(`log verbosity level is not valid: ${Z}`);let Y=typeof P.optimizedModelFilePath=="string"?lt(P.optimizedModelFilePath,z):0;if(k=_._OrtCreateSessionOptions(N,!!P.enableCpuMemArena,!!P.enableMemPattern,B,!!P.enableProfiling,0,D,F,Z,Y),k===0&&$e("Can't create session options."),P.executionProviders&&await oi(k,P,z),P.enableGraphCapture!==void 0){if(typeof P.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${P.enableGraphCapture}`);It(k,"enableGraphCapture",P.enableGraphCapture.toString(),z)}if(P.freeDimensionOverrides)for(let[Q,H]of Object.entries(P.freeDimensionOverrides)){if(typeof Q!="string")throw new Error(`free dimension override name must be a string: ${Q}`);if(typeof H!="number"||!Number.isInteger(H)||H<0)throw new Error(`free dimension override value must be a non-negative integer: ${H}`);let ve=lt(Q,z);_._OrtAddFreeDimensionOverride(k,ve,H)!==0&&$e(`Can't set a free dimension override: ${Q} - ${H}.`)}return P.extra!==void 0&&yr(P.extra,"",new WeakSet,(Q,H)=>{It(k,Q,H,z)}),[k,z]}catch(N){throw k!==0&&_._OrtReleaseSessionOptions(k)!==0&&$e("Can't release session options."),z.forEach(B=>_._free(B)),N}}}),Lt,Bt,Ut,Xr,Zr,Jr,Yr,gs,Ee=T(()=>{Lt=f=>{switch(f){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 new Error(`unsupported data type: ${f}`)}},Bt=f=>{switch(f){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 new Error(`unsupported data type: ${f}`)}},Ut=(f,_)=>{let k=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][f],z=typeof _=="number"?_:_.reduce((P,N)=>P*N,1);return k>0?Math.ceil(z*k):void 0},Xr=f=>{switch(f){case"float16":return typeof Float16Array<"u"&&Float16Array.from?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 new Error(`unsupported type: ${f}`)}},Zr=f=>{switch(f){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${f}`)}},Jr=f=>f==="float32"||f==="float16"||f==="int32"||f==="int64"||f==="uint32"||f==="uint8"||f==="bool"||f==="uint4"||f==="int4",Yr=f=>f==="float32"||f==="float16"||f==="int32"||f==="int64"||f==="uint32"||f==="uint64"||f==="int8"||f==="uint8"||f==="bool"||f==="uint4"||f==="int4",gs=f=>{switch(f){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 new Error(`unsupported data location: ${f}`)}}}),es,ui=T(()=>{Br(),es=async f=>{if(typeof f=="string"){let _=await fetch(f);if(!_.ok)throw new Error(`failed to load external data file: ${f}`);let k=_.headers.get("Content-Length"),z=k?parseInt(k,10):0;if(z<1073741824)return new Uint8Array(await _.arrayBuffer());{if(!_.body)throw new Error(`failed to load external data file: ${f}, no response body.`);let P=_.body.getReader(),N;try{N=new ArrayBuffer(z)}catch(D){if(D instanceof RangeError){let F=Math.ceil(z/65536);N=new WebAssembly.Memory({initial:F,maximum:F}).buffer}else throw D}let B=0;for(;;){let{done:D,value:F}=await P.read();if(D)break;let Z=F.byteLength;new Uint8Array(N,B,Z).set(F),B+=Z}return new Uint8Array(N,0,z)}}else return f instanceof Blob?new Uint8Array(await f.arrayBuffer()):f instanceof Uint8Array?f:new Uint8Array(f)}}),di,ys,ws,or,vs,bs,Fe,Vt,_s,lr,q,Er,Ss,ci=T(()=>{wt(),_n(),Sn(),Ee(),Dt(),Qr(),ui(),di=(f,_)=>{Me()._OrtInit(f,_)!==0&&$e("Can't initialize onnxruntime.")},ys=async f=>{di(f.wasm.numThreads,Zr(f.logLevel))},ws=async(f,_)=>{Me().asyncInit?.();let k=f.webgpu.adapter;if(_==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(k){if(typeof k.limits!="object"||typeof k.features!="object"||typeof k.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let z=f.webgpu.powerPreference;if(z!==void 0&&z!=="low-power"&&z!=="high-performance")throw new Error(`Invalid powerPreference setting: "${z}"`);let P=f.webgpu.forceFallbackAdapter;if(P!==void 0&&typeof P!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${P}"`);if(k=await navigator.gpu.requestAdapter({powerPreference:z,forceFallbackAdapter:P}),!k)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(_==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},or=new Map,vs=f=>{let _=Me(),k=_.stackSave();try{let z=_.PTR_SIZE,P=_.stackAlloc(2*z);_._OrtGetInputOutputCount(f,P,P+z)!==0&&$e("Can't get session input/output count.");let N=z===4?"i32":"i64";return[Number(_.getValue(P,N)),Number(_.getValue(P+z,N))]}finally{_.stackRestore(k)}},bs=(f,_)=>{let k=Me(),z=k.stackSave(),P=0;try{let N=k.PTR_SIZE,B=k.stackAlloc(2*N);k._OrtGetInputOutputMetadata(f,_,B,B+N)!==0&&$e("Can't get session input/output metadata.");let D=Number(k.getValue(B,"*"));P=Number(k.getValue(B+N,"*"));let F=k.HEAP32[P/4];if(F===0)return[D,0];let Z=k.HEAPU32[P/4+1],Y=[];for(let Q=0;Q<Z;Q++){let H=Number(k.getValue(P+8+Q*N,"*"));Y.push(H!==0?k.UTF8ToString(H):Number(k.getValue(P+8+(Q+Z)*N,"*")))}return[D,F,Y]}finally{k.stackRestore(z),P!==0&&k._OrtFree(P)}},Fe=f=>{let _=Me(),k=_._malloc(f.byteLength);if(k===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${f.byteLength}.`);return _.HEAPU8.set(f,k),[k,f.byteLength]},Vt=async(f,_)=>{let k,z,P=Me();Array.isArray(f)?[k,z]=f:f.buffer===P.HEAPU8.buffer?[k,z]=[f.byteOffset,f.byteLength]:[k,z]=Fe(f);let N=0,B=0,D=[],F=[],Z=[];try{if([B,D]=await li(_),_?.externalData&&P.mountExternalData){let be=[];for(let De of _.externalData){let he=typeof De=="string"?De:De.path;be.push(es(typeof De=="string"?De:De.data).then(_t=>{P.mountExternalData(he,_t)}))}await Promise.all(be)}for(let be of _?.executionProviders??[])if((typeof be=="string"?be:be.name)==="webnn"){if(P.shouldTransferToMLTensor=!1,typeof be!="string"){let De=be,he=De?.context,_t=De?.gpuDevice,St=De?.deviceType,cr=De?.powerPreference;he?P.currentContext=he:_t?P.currentContext=await P.webnnCreateMLContext(_t):P.currentContext=await P.webnnCreateMLContext({deviceType:St,powerPreference:cr})}else P.currentContext=await P.webnnCreateMLContext();break}N=await P._OrtCreateSession(k,z,B),P.webgpuOnCreateSession?.(N),N===0&&$e("Can't create a session."),P.jsepOnCreateSession?.(),P.currentContext&&(P.webnnRegisterMLContext(N,P.currentContext),P.currentContext=void 0,P.shouldTransferToMLTensor=!0);let[Y,Q]=vs(N),H=!!_?.enableGraphCapture,ve=[],U=[],te=[],tt=[],ze=[];for(let be=0;be<Y;be++){let[De,he,_t]=bs(N,be);De===0&&$e("Can't get an input name."),F.push(De);let St=P.UTF8ToString(De);ve.push(St),te.push(he===0?{name:St,isTensor:!1}:{name:St,isTensor:!0,type:Bt(he),shape:_t})}for(let be=0;be<Q;be++){let[De,he,_t]=bs(N,be+Y);De===0&&$e("Can't get an output name."),Z.push(De);let St=P.UTF8ToString(De);U.push(St),tt.push(he===0?{name:St,isTensor:!1}:{name:St,isTensor:!0,type:Bt(he),shape:_t})}return or.set(N,[N,F,Z,null,H,!1]),[N,ve,U,te,tt]}catch(Y){throw F.forEach(Q=>P._OrtFree(Q)),Z.forEach(Q=>P._OrtFree(Q)),N!==0&&P._OrtReleaseSession(N)!==0&&$e("Can't release session."),Y}finally{P._free(k),B!==0&&P._OrtReleaseSessionOptions(B)!==0&&$e("Can't release session options."),D.forEach(Y=>P._free(Y)),P.unmountExternalData?.()}},_s=f=>{let _=Me(),k=or.get(f);if(!k)throw new Error(`cannot release session. invalid session id: ${f}`);let[z,P,N,B,D]=k;B&&(D&&_._OrtClearBoundOutputs(B.handle)!==0&&$e("Can't clear bound outputs."),_._OrtReleaseBinding(B.handle)!==0&&$e("Can't release IO binding.")),_.jsepOnReleaseSession?.(f),_.webnnOnReleaseSession?.(f),_.webgpuOnReleaseSession?.(f),P.forEach(F=>_._OrtFree(F)),N.forEach(F=>_._OrtFree(F)),_._OrtReleaseSession(z)!==0&&$e("Can't release session."),or.delete(f)},lr=async(f,_,k,z,P,N,B=!1)=>{if(!f){_.push(0);return}let D=Me(),F=D.PTR_SIZE,Z=f[0],Y=f[1],Q=f[3],H=Q,ve,U;if(Z==="string"&&(Q==="gpu-buffer"||Q==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(B&&Q!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${N} when enableGraphCapture is true.`);if(Q==="gpu-buffer"){let ze=f[2].gpuBuffer;U=Ut(Lt(Z),Y);{let be=D.jsepRegisterBuffer;if(!be)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');ve=be(z,N,ze,U)}}else if(Q==="ml-tensor"){let ze=f[2].mlTensor;U=Ut(Lt(Z),Y);let be=D.webnnRegisterMLTensor;if(!be)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');ve=be(z,ze,Lt(Z),Y)}else{let ze=f[2];if(Array.isArray(ze)){U=F*ze.length,ve=D._malloc(U),k.push(ve);for(let be=0;be<ze.length;be++){if(typeof ze[be]!="string")throw new TypeError(`tensor data at index ${be} is not a string`);D.setValue(ve+be*F,lt(ze[be],k),"*")}}else{let be=D.webnnIsGraphInput,De=D.webnnIsGraphOutput;if(Z!=="string"&&be&&De){let he=D.UTF8ToString(P);if(be(z,he)||De(z,he)){let _t=Lt(Z);U=Ut(_t,Y),H="ml-tensor";let St=D.webnnCreateTemporaryTensor,cr=D.webnnUploadTensor;if(!St||!cr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Ir=await St(z,_t,Y);cr(Ir,new Uint8Array(ze.buffer,ze.byteOffset,ze.byteLength)),ve=Ir}else U=ze.byteLength,ve=D._malloc(U),k.push(ve),D.HEAPU8.set(new Uint8Array(ze.buffer,ze.byteOffset,U),ve)}else U=ze.byteLength,ve=D._malloc(U),k.push(ve),D.HEAPU8.set(new Uint8Array(ze.buffer,ze.byteOffset,U),ve)}}let te=D.stackSave(),tt=D.stackAlloc(4*Y.length);try{Y.forEach((be,De)=>D.setValue(tt+De*F,be,F===4?"i32":"i64"));let ze=D._OrtCreateTensor(Lt(Z),ve,U,tt,Y.length,gs(H));ze===0&&$e(`Can't create tensor for input/output. session=${z}, index=${N}.`),_.push(ze)}finally{D.stackRestore(te)}},q=async(f,_,k,z,P,N)=>{let B=Me(),D=B.PTR_SIZE,F=or.get(f);if(!F)throw new Error(`cannot run inference. invalid session id: ${f}`);let Z=F[0],Y=F[1],Q=F[2],H=F[3],ve=F[4];F[5];let U=_.length,te=z.length,tt=0,ze=[],be=[],De=[],he=[],_t=[],St=B.stackSave(),cr=B.stackAlloc(U*D),Ir=B.stackAlloc(U*D),As=B.stackAlloc(te*D),vi=B.stackAlloc(te*D);try{[tt,ze]=si(N),Et("wasm prepareInputOutputTensor");for(let Le=0;Le<U;Le++)await lr(k[Le],be,he,f,Y[_[Le]],_[Le],ve);for(let Le=0;Le<te;Le++)await lr(P[Le],De,he,f,Q[z[Le]],U+z[Le],ve);kt("wasm prepareInputOutputTensor");for(let Le=0;Le<U;Le++)B.setValue(cr+Le*D,be[Le],"*"),B.setValue(Ir+Le*D,Y[_[Le]],"*");for(let Le=0;Le<te;Le++)B.setValue(As+Le*D,De[Le],"*"),B.setValue(vi+Le*D,Q[z[Le]],"*");B.jsepOnRunStart?.(Z),B.webnnOnRunStart?.(Z);let it;it=await B._OrtRun(Z,Ir,cr,U,vi,te,As,tt),it!==0&&$e("failed to call OrtRun().");let Wt=[],bi=[];Et("wasm ProcessOutputTensor");for(let Le=0;Le<te;Le++){let Gt=Number(B.getValue(As+Le*D,"*"));if(Gt===De[Le]||_t.includes(De[Le])){Wt.push(P[Le]),Gt!==De[Le]&&B._OrtReleaseTensor(Gt)!==0&&$e("Can't release tensor.");continue}let Wi=B.stackSave(),Jt=B.stackAlloc(4*D),is=!1,ct,Mt=0;try{B._OrtGetTensorData(Gt,Jt,Jt+D,Jt+2*D,Jt+3*D)!==0&&$e(`Can't access output tensor data on index ${Le}.`);let Ps=D===4?"i32":"i64",ns=Number(B.getValue(Jt,Ps));Mt=B.getValue(Jt+D,"*");let _i=B.getValue(Jt+D*2,"*"),qi=Number(B.getValue(Jt+D*3,Ps)),vt=[];for(let ht=0;ht<qi;ht++)vt.push(Number(B.getValue(_i+ht*D,Ps)));B._OrtFree(_i)!==0&&$e("Can't free memory for tensor dims.");let Yt=vt.reduce((ht,nt)=>ht*nt,1);ct=Bt(ns);let Ar=H?.outputPreferredLocations[z[Le]];if(ct==="string"){if(Ar==="gpu-buffer"||Ar==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ht=[];for(let nt=0;nt<Yt;nt++){let qt=B.getValue(Mt+nt*D,"*"),Hi=B.getValue(Mt+(nt+1)*D,"*"),ji=nt===Yt-1?void 0:Hi-qt;ht.push(B.UTF8ToString(qt,ji))}Wt.push([ct,vt,ht,"cpu"])}else if(Ar==="gpu-buffer"&&Yt>0){let ht=B.jsepGetBuffer;if(!ht)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let nt=ht(Mt),qt=Ut(ns,Yt);if(qt===void 0||!Jr(ct))throw new Error(`Unsupported data type: ${ct}`);is=!0,Wt.push([ct,vt,{gpuBuffer:nt,download:B.jsepCreateDownloader(nt,qt,ct),dispose:()=>{B._OrtReleaseTensor(Gt)!==0&&$e("Can't release tensor.")}},"gpu-buffer"])}else if(Ar==="ml-tensor"&&Yt>0){let ht=B.webnnEnsureTensor,nt=B.webnnIsGraphInputOutputTypeSupported;if(!ht||!nt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ut(ns,Yt)===void 0||!Yr(ct))throw new Error(`Unsupported data type: ${ct}`);if(!nt(f,ct,!1))throw new Error(`preferredLocation "ml-tensor" for ${ct} output is not supported by current WebNN Context.`);let qt=await ht(f,Mt,ns,vt,!1);is=!0,Wt.push([ct,vt,{mlTensor:qt,download:B.webnnCreateMLTensorDownloader(Mt,ct),dispose:()=>{B.webnnReleaseTensorId(Mt),B._OrtReleaseTensor(Gt)}},"ml-tensor"])}else if(Ar==="ml-tensor-cpu-output"&&Yt>0){let ht=B.webnnCreateMLTensorDownloader(Mt,ct)(),nt=Wt.length;is=!0,bi.push((async()=>{let qt=[nt,await ht];return B.webnnReleaseTensorId(Mt),B._OrtReleaseTensor(Gt),qt})()),Wt.push([ct,vt,[],"cpu"])}else{let ht=Xr(ct),nt=new ht(Yt);new Uint8Array(nt.buffer,nt.byteOffset,nt.byteLength).set(B.HEAPU8.subarray(Mt,Mt+nt.byteLength)),Wt.push([ct,vt,nt,"cpu"])}}finally{B.stackRestore(Wi),ct==="string"&&Mt&&B._free(Mt),is||B._OrtReleaseTensor(Gt)}}H&&!ve&&(B._OrtClearBoundOutputs(H.handle)!==0&&$e("Can't clear bound outputs."),or.set(f,[Z,Y,Q,H,ve,!1]));for(let[Le,Gt]of await Promise.all(bi))Wt[Le][2]=Gt;return kt("wasm ProcessOutputTensor"),Wt}finally{B.webnnOnRunEnd?.(Z),B.stackRestore(St),be.forEach(it=>B._OrtReleaseTensor(it)),De.forEach(it=>B._OrtReleaseTensor(it)),he.forEach(it=>B._free(it)),tt!==0&&B._OrtReleaseRunOptions(tt),ze.forEach(it=>B._free(it))}},Er=f=>{let _=Me(),k=or.get(f);if(!k)throw new Error("invalid session id");let z=k[0],P=_._OrtEndProfiling(z);P===0&&$e("Can't get an profile file name."),_._OrtFree(P)},Ss=f=>{let _=[];for(let k of f){let z=k[2];!Array.isArray(z)&&"buffer"in z&&_.push(z.buffer)}return _}}),Xt,xe,ur,kr,wr,Mr,ts,rs,Zt,dr,$s,xs,Ts,hi,pi,Vi,Rr,mi,fi=T(()=>{wt(),ci(),Dt(),qr(),Xt=()=>!!de.wasm.proxy&&typeof document<"u",ur=!1,kr=!1,wr=!1,rs=new Map,Zt=(f,_)=>{let k=rs.get(f);k?k.push(_):rs.set(f,[_])},dr=()=>{if(ur||!kr||wr||!xe)throw new Error("worker not ready")},$s=f=>{switch(f.data.type){case"init-wasm":ur=!1,f.data.err?(wr=!0,ts[1](f.data.err)):(kr=!0,ts[0]()),Mr&&(URL.revokeObjectURL(Mr),Mr=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let _=rs.get(f.data.type);f.data.err?_.shift()[1](f.data.err):_.shift()[0](f.data.out);break}}},xs=async()=>{if(!kr){if(ur)throw new Error("multiple calls to 'initWasm()' detected.");if(wr)throw new Error("previous call to 'initWasm()' failed.");if(ur=!0,Xt())return new Promise((f,_)=>{xe?.terminate(),Js().then(([k,z])=>{try{xe=z,xe.onerror=N=>_(N),xe.onmessage=$s,ts=[f,_];let P={type:"init-wasm",in:de};if(!P.in.wasm.wasmPaths&&k){let N=Nr();N&&(P.in.wasm.wasmPaths=N)}xe.postMessage(P),Mr=k}catch(P){_(P)}},_)});try{await Kr(de.wasm),await ys(de),kr=!0}catch(f){throw wr=!0,f}finally{ur=!1}}},Ts=async f=>{if(Xt())return dr(),new Promise((_,k)=>{Zt("init-ep",[_,k]);let z={type:"init-ep",in:{epName:f,env:de}};xe.postMessage(z)});await ws(de,f)},hi=async f=>Xt()?(dr(),new Promise((_,k)=>{Zt("copy-from",[_,k]);let z={type:"copy-from",in:{buffer:f}};xe.postMessage(z,[f.buffer])})):Fe(f),pi=async(f,_)=>{if(Xt()){if(_?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return dr(),new Promise((k,z)=>{Zt("create",[k,z]);let P={type:"create",in:{model:f,options:{..._}}},N=[];f instanceof Uint8Array&&N.push(f.buffer),xe.postMessage(P,N)})}else return Vt(f,_)},Vi=async f=>{if(Xt())return dr(),new Promise((_,k)=>{Zt("release",[_,k]);let z={type:"release",in:f};xe.postMessage(z)});_s(f)},Rr=async(f,_,k,z,P,N)=>{if(Xt()){if(k.some(B=>B[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(P.some(B=>B))throw new Error("pre-allocated output tensor is not supported for proxy.");return dr(),new Promise((B,D)=>{Zt("run",[B,D]);let F=k,Z={type:"run",in:{sessionId:f,inputIndices:_,inputs:F,outputIndices:z,options:N}};xe.postMessage(Z,Ss(F))})}else return q(f,_,k,z,P,N)},mi=async f=>{if(Xt())return dr(),new Promise((_,k)=>{Zt("end-profiling",[_,k]);let z={type:"end-profiling",in:f};xe.postMessage(z)});Er(f)}}),gi,Cs,Es,ks=T(()=>{wt(),fi(),Ee(),Br(),ui(),gi=(f,_)=>{switch(f.location){case"cpu":return[f.type,f.dims,f.data,"cpu"];case"gpu-buffer":return[f.type,f.dims,{gpuBuffer:f.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[f.type,f.dims,{mlTensor:f.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${f.location} for ${_()}`)}},Cs=f=>{switch(f[3]){case"cpu":return new ot(f[0],f[2],f[1]);case"gpu-buffer":{let _=f[0];if(!Jr(_))throw new Error(`not supported data type: ${_} for deserializing GPU tensor`);let{gpuBuffer:k,download:z,dispose:P}=f[2];return ot.fromGpuBuffer(k,{dataType:_,dims:f[1],download:z,dispose:P})}case"ml-tensor":{let _=f[0];if(!Yr(_))throw new Error(`not supported data type: ${_} for deserializing MLTensor tensor`);let{mlTensor:k,download:z,dispose:P}=f[2];return ot.fromMLTensor(k,{dataType:_,dims:f[1],download:z,dispose:P})}default:throw new Error(`invalid data location: ${f[3]}`)}},Es=class{async fetchModelAndCopyToWasmMemory(f){return hi(await es(f))}async loadModel(f,_){bt();let k;typeof f=="string"?k=await this.fetchModelAndCopyToWasmMemory(f):k=f,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await pi(k,_),yt()}async dispose(){return Vi(this.sessionId)}async run(f,_,k){bt();let z=[],P=[];Object.entries(f).forEach(Q=>{let H=Q[0],ve=Q[1],U=this.inputNames.indexOf(H);if(U===-1)throw new Error(`invalid input '${H}'`);z.push(ve),P.push(U)});let N=[],B=[];Object.entries(_).forEach(Q=>{let H=Q[0],ve=Q[1],U=this.outputNames.indexOf(H);if(U===-1)throw new Error(`invalid output '${H}'`);N.push(ve),B.push(U)});let D=z.map((Q,H)=>gi(Q,()=>`input "${this.inputNames[P[H]]}"`)),F=N.map((Q,H)=>Q?gi(Q,()=>`output "${this.outputNames[B[H]]}"`):null),Z=await Rr(this.sessionId,P,D,B,F,k),Y={};for(let Q=0;Q<Z.length;Q++)Y[this.outputNames[B[Q]]]=N[Q]??Cs(Z[Q]);return yt(),Y}startProfiling(){}endProfiling(){mi(this.sessionId)}}}),ss={};K(ss,{OnnxruntimeWebAssemblyBackend:()=>Rs,initializeFlags:()=>Ms,wasmBackend:()=>Is});var Ms,Rs,Is,yi=T(()=>{wt(),fi(),ks(),Ms=()=>{(typeof de.wasm.initTimeout!="number"||de.wasm.initTimeout<0)&&(de.wasm.initTimeout=0);let f=de.wasm.simd;if(typeof f!="boolean"&&f!==void 0&&f!=="fixed"&&f!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${f}". Reset it to \`false\` and ignore SIMD feature checking.`),de.wasm.simd=!1),typeof de.wasm.proxy!="boolean"&&(de.wasm.proxy=!1),typeof de.wasm.trace!="boolean"&&(de.wasm.trace=!1),typeof de.wasm.numThreads!="number"||!Number.isInteger(de.wasm.numThreads)||de.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)de.wasm.numThreads=1;else{let _=typeof navigator>"u"?O("node:os").cpus().length:navigator.hardwareConcurrency;de.wasm.numThreads=Math.min(4,Math.ceil((_||1)/2))}},Rs=class{async init(f){Ms(),await xs(),await Ts(f)}async createInferenceSessionHandler(f,_){let k=new Es;return await k.loadModel(f,_),k}},Is=new Rs}),wi={};K(wi,{InferenceSession:()=>Lr,TRACE:()=>ar,TRACE_EVENT_BEGIN:()=>Et,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>bt,TRACE_FUNC_END:()=>yt,Tensor:()=>ot,default:()=>$n,env:()=>de,registerBackend:()=>re}),wt(),wt(),wt();var Gi="1.26.0",$n=Ws;{let f=(yi(),ae(ss)).wasmBackend;re("cpu",f,10),re("wasm",f,10)}return Object.defineProperty(de.versions,"web",{value:Gi,enumerable:!0}),ae(wi)})();S.exports=n})(Ra)),Ra.exports}var Uh;function uf(){return Uh||(Uh=1,(function(S){var s=$r&&$r.__createBinding||(Object.create?(function(ce,le,ye,me){me===void 0&&(me=ye);var We=Object.getOwnPropertyDescriptor(le,ye);(!We||("get"in We?!le.__esModule:We.writable||We.configurable))&&(We={enumerable:!0,get:function(){return le[ye]}}),Object.defineProperty(ce,me,We)}):(function(ce,le,ye,me){me===void 0&&(me=ye),ce[me]=le[ye]})),n=$r&&$r.__setModuleDefault||(Object.create?(function(ce,le){Object.defineProperty(ce,"default",{enumerable:!0,value:le})}):function(ce,le){ce.default=le}),d=$r&&$r.__importStar||function(ce){if(ce&&ce.__esModule)return ce;var le={};if(ce!=null)for(var ye in ce)ye!=="default"&&Object.prototype.hasOwnProperty.call(ce,ye)&&s(le,ce,ye);return n(le,ce),le};Object.defineProperty(S,"__esModule",{value:!0}),S.MicVAD=S.getDefaultRealTimeVADOptions=S.ort=S.DEFAULT_MODEL=void 0;const g=d(lf()),E=Ga(),A=Wa(),O=Ds(),T=cn(),K=ep(),G=tp();S.DEFAULT_MODEL="legacy",S.ort=g;const ae="vad.worklet.bundle.min.js",J="silero_vad_v5.onnx",ie="silero_vad_legacy.onnx",re=ce=>({...A.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{O.log.debug("VAD misfire")},onSpeechStart:()=>{O.log.debug("Detected speech start")},onSpeechEnd:()=>{O.log.debug("Detected speech end")},onSpeechRealStart:()=>{O.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:ce,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async le=>{le.getTracks().forEach(ye=>{ye.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:le=>{le.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});S.getDefaultRealTimeVADOptions=re;const ne=ce=>"audioWorklet"in ce&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function fe(ce,le,ye,me,We){await ye.audioWorklet.addModule(ce),le.processorOptions={...le.processorOptions??{},frameSamples:me};const de=new AudioWorkletNode(ye,"vad-helper-worklet",le);return de.port.onmessage=async st=>{const qe=st.data;if(!(typeof qe=="object"&&qe&&"message"in qe)){console.error("Invalid message event",qe);return}switch(qe.message){case T.Message.AudioFrame:{if(!("data"in qe&&qe.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const dt=new Float32Array(qe.data);await We(dt);break}}},de}async function Re(ce,le,ye){const me=new G.Resampler({nativeSampleRate:ce.sampleRate,targetSampleRate:16e3,targetFrameSize:le});O.log.debug("using script processor");const de=ce.createScriptProcessor(4096,1,1);let st=!1;return de.onaudioprocess=async qe=>{if(!st){st=!0;try{const dt=qe.inputBuffer.getChannelData(0);qe.outputBuffer.getChannelData(0).fill(0);const ut=me.process(dt);for(const at of ut)await ye(at)}catch(dt){console.error("Error processing audio:",dt)}finally{st=!1}}},de.connect(ce.destination),de}class Pe{constructor(le,ye,me,We,de=!1,st=null,qe=null,dt=null,Qe=null,ut=null,at=null,Kt="uninitialized",Ct=!1){this.options=le,this.frameProcessor=ye,this.model=me,this.frameSamples=We,this.listening=de,this.errored=st,this._stream=qe,this._audioContext=dt,this._vadNode=Qe,this._mediaStreamAudioSourceNode=ut,this._audioProcessorAdapterType=at,this.initializationState=Kt,this.ownsAudioContext=Ct,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=je=>{this.initializationState="errored",this.errored=je},this.start=async()=>{switch(this.initializationState){case"uninitialized":{O.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(je){throw je instanceof Error?this.setErrored(je.message):this.setErrored(String(je)),je}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?ne(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await fe(this.options.baseAssetPath+ae,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await Re(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),O.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{O.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:je,audioContext:Ve,vadNode:et}=this.getAudioInstances();this._stream=await this.options.resumeStream(je);const Xe=new MediaStreamAudioSourceNode(Ve,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Xe,Xe.connect(et);break}case"destroyed":{O.log.warn("start called after destroyed");break}case"errored":{O.log.error("start called after errored");break}default:{O.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:je,mediaStreamAudioSourceNode:Ve}=this.getAudioInstances();await this.options.pauseStream(je),Ve.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{O.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:je}=this.getAudioInstances();je instanceof AudioWorkletNode&&je.port.postMessage(T.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await this._audioContext?.close()},this.setOptions=je=>{this.frameProcessor.setOptions(je)},this.processFrame=async je=>{await this.frameProcessor.process(je,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=je=>{switch(je.msg){case T.Message.FrameProcessed:this.options.onFrameProcessed(je.probs,je.frame);break;case T.Message.SpeechStart:this.options.onSpeechStart();break;case T.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case T.Message.VADMisfire:this.options.onVADMisfire();break;case T.Message.SpeechEnd:this.options.onSpeechEnd(je.audio);break}}}static async new(le={}){const ye={...(0,S.getDefaultRealTimeVADOptions)(le.model??S.DEFAULT_MODEL),...le};(0,A.validateOptions)(ye),S.ort.env.wasm.wasmPaths=ye.onnxWASMBasePath,ye.ortConfig!==void 0&&ye.ortConfig(S.ort);const me=ye.model==="v5"?J:ie,We=ye.baseAssetPath+me,de=ye.model==="v5"?K.SileroV5.new:K.SileroLegacy.new;let st;try{st=await de(S.ort,()=>(0,E.defaultModelFetcher)(We))}catch(at){throw console.error(`Encountered an error while loading model file ${We}`),at}const qe=ye.model==="v5"?512:1536,dt=qe/16,Qe=new A.FrameProcessor(st.process,st.reset_state,{positiveSpeechThreshold:ye.positiveSpeechThreshold,negativeSpeechThreshold:ye.negativeSpeechThreshold,redemptionMs:ye.redemptionMs,preSpeechPadMs:ye.preSpeechPadMs,minSpeechMs:ye.minSpeechMs,submitUserSpeechOnPause:ye.submitUserSpeechOnPause},dt),ut=new Pe(ye,Qe,st,qe);if(ye.startOnLoad)try{await ut.start()}catch(at){throw console.error("Error starting micVad",at),at}return ut}}S.MicVAD=Pe})($r)),$r}var Fh;function Nh(){return Fh||(Fh=1,(function(S){Object.defineProperty(S,"__esModule",{value:!0}),S.getDefaultRealTimeVADOptions=S.MicVAD=S.DEFAULT_MODEL=S.utils=S.NonRealTimeVAD=S.Message=S.FrameProcessor=S.defaultModelFetcher=S.baseAssetPath=void 0;var s=Zh();Object.defineProperty(S,"baseAssetPath",{enumerable:!0,get:function(){return s.baseAssetPath}});var n=Ga();Object.defineProperty(S,"defaultModelFetcher",{enumerable:!0,get:function(){return n.defaultModelFetcher}});var d=Wa();Object.defineProperty(S,"FrameProcessor",{enumerable:!0,get:function(){return d.FrameProcessor}});var g=cn();Object.defineProperty(S,"Message",{enumerable:!0,get:function(){return g.Message}});var E=af();Object.defineProperty(S,"NonRealTimeVAD",{enumerable:!0,get:function(){return E.NonRealTimeVAD}});const A=of();S.utils={audioFileToArray:A.audioFileToArray,minFramesForTargetMS:A.minFramesForTargetMS,arrayBufferToBase64:A.arrayBufferToBase64,encodeWAV:A.encodeWAV};var O=uf();Object.defineProperty(S,"DEFAULT_MODEL",{enumerable:!0,get:function(){return O.DEFAULT_MODEL}}),Object.defineProperty(S,"MicVAD",{enumerable:!0,get:function(){return O.MicVAD}}),Object.defineProperty(S,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return O.getDefaultRealTimeVADOptions}})})(Ea)),Ea}var Vh;function df(){return Vh||(Vh=1,(function(S){Object.defineProperty(S,"__esModule",{value:!0}),S.useMicVAD=S.getDefaultReactRealTimeVADOptions=S.utils=void 0;const s=Nh(),n=Ke;var d=Nh();Object.defineProperty(S,"utils",{enumerable:!0,get:function(){return d.utils}});const g={userSpeakingThreshold:.6},E=T=>({...(0,s.getDefaultRealTimeVADOptions)(T),...g});S.getDefaultReactRealTimeVADOptions=E;function A(T){const K=T.model??s.DEFAULT_MODEL,G={...(0,S.getDefaultReactRealTimeVADOptions)(K),...T},ae={userSpeakingThreshold:G.userSpeakingThreshold},J={positiveSpeechThreshold:G.positiveSpeechThreshold,negativeSpeechThreshold:G.negativeSpeechThreshold,redemptionMs:G.redemptionMs,preSpeechPadMs:G.preSpeechPadMs,minSpeechMs:G.minSpeechMs,submitUserSpeechOnPause:G.submitUserSpeechOnPause,onFrameProcessed:G.onFrameProcessed,onVADMisfire:G.onVADMisfire,onSpeechStart:G.onSpeechStart,onSpeechEnd:G.onSpeechEnd,onSpeechRealStart:G.onSpeechRealStart,baseAssetPath:G.baseAssetPath,onnxWASMBasePath:G.onnxWASMBasePath,model:G.model,workletOptions:G.workletOptions,getStream:G.getStream,pauseStream:G.pauseStream,resumeStream:G.resumeStream,startOnLoad:G.startOnLoad,processorType:G.processorType};return G.ortConfig&&(J.ortConfig=G.ortConfig),G.audioContext&&(J.audioContext=G.audioContext),[ae,J]}function O(T){const[K,G]=A(T),ae=T.model??s.DEFAULT_MODEL,[J,ie]=(0,n.useState)(!1),[re,ne]=(0,n.useState)(!0),[fe,Re]=(0,n.useState)(!1),[Pe,ce]=(0,n.useState)(!1),[le,ye]=(0,n.useState)(null),me=(0,n.useRef)(G.onFrameProcessed),We=(0,n.useRef)(G.onSpeechEnd),de=(0,n.useRef)(G.onSpeechStart),st=(0,n.useRef)(G.onSpeechRealStart),qe=(0,n.useRef)(G.onVADMisfire),dt=(0,n.useRef)(G.getStream);(0,n.useEffect)(()=>{me.current=G.onFrameProcessed,We.current=G.onSpeechEnd,de.current=G.onSpeechStart,st.current=G.onSpeechRealStart,qe.current=G.onVADMisfire},[G.onFrameProcessed,G.onSpeechEnd,G.onSpeechStart,G.onSpeechRealStart,G.onVADMisfire]),(0,n.useEffect)(()=>{dt.current=G.getStream},[G.getStream]);const Qe=G.getStream.toString();(0,n.useEffect)(()=>{let Ct=null,je=!1;return(async()=>{try{ne(!0),Re(!1);const et={...G,onFrameProcessed:(Xe,Rt)=>{const mr=Xe.isSpeech>K.userSpeakingThreshold;ie(mr),me.current(Xe,Rt)},onSpeechEnd:Xe=>{We.current(Xe)},onSpeechStart:()=>{de.current()},onSpeechRealStart:()=>{st.current()},onVADMisfire:()=>{qe.current()},getStream:()=>dt.current()};if(Ct=await s.MicVAD.new(et),je){await Ct.destroy();return}ye(Ct),G.startOnLoad&&(await Ct.start(),ce(!0)),ne(!1)}catch(et){ne(!1),et instanceof Error?Re(et.message):Re(String(et))}})().catch(()=>{}),function(){je=!0,Ct&&Ct.destroy(),!re&&!fe&&ce(!1)}},[Qe,ae]);const ut=(0,n.useCallback)(async()=>{!re&&!fe&&(await le?.pause(),ce(!1))},[re,fe,le]),at=(0,n.useCallback)(async()=>{!re&&!fe&&(await le?.start(),ce(!0))},[re,fe,le]),Kt=(0,n.useCallback)(async()=>{Pe?await ut():await at()},[Pe,ut,at]);return{listening:Pe,errored:fe,loading:re,userSpeaking:J,pause:ut,start:at,toggle:Kt}}S.useMicVAD=O})(Ca)),Ca}var cf=df(),sp=Ds();sp.log.debug=()=>{};sp.log.warn=()=>{};const Gh={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1,channelCount:1};typeof window<"u"&&(window.addEventListener("unhandledrejection",S=>{S.reason&&S.reason.message&&S.reason.message.includes("MicVAD has null stream")&&S.preventDefault()}),window.addEventListener("error",S=>{S.message&&(S.message.includes("Cannot read properties of null (reading 'state')")||S.message.includes("Cannot read properties of undefined (reading 'S')"))&&S.preventDefault()}));const hf=16e3,ip=512,np=1e3,pf=300,mf=ip/hf*1e3,ff=Math.ceil(np/mf);function Ia(S){const s=new ArrayBuffer(S.length*2),n=new DataView(s);for(let d=0;d<S.length;d++){const g=Math.max(-1,Math.min(1,S[d]));n.setInt16(d*2,g<0?g*32768:g*32767,!0)}return new Uint8Array(s)}function Aa(S){if(!S.length)return new Float32Array(0);if(S.length===1)return S[0];const s=S.reduce((g,E)=>g+E.length,0),n=new Float32Array(s);let d=0;for(const g of S)n.set(g,d),d+=g.length;return n}function gf(S={}){const{onAudioChunk:s,onAudioEnd:n,onSpeechStart:d,onSpeechEnd:g,onVADMisfire:E,onError:A,enabled:O=!0,preloadStream:T=!0}=S,{sendAudioChunk:K,endAudioStream:G}=zt.useRqmiiAgentContext(),[ae,J]=Ke.useState(!1),[ie,re]=Ke.useState(null),ne=Ke.useRef(null),fe=Ke.useRef(!1),Re=Ke.useRef(null),Pe=Ke.useRef([]),ce=Ke.useRef(!1),le=Ke.useRef([]),ye=s??K;Ke.useEffect(()=>{!O||!T||typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||navigator.mediaDevices.getUserMedia({audio:Gh}).then(Ve=>{ne.current=Ve,re(null)}).catch(Ve=>{re("permission_denied"),A?.(Ve)})},[O,A,T]);const me=Ke.useCallback(async()=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone APIs are unavailable in this browser");if(ne.current&&ne.current.getTracks()[0]?.readyState==="live")return ne.current;const Ve=await navigator.mediaDevices.getUserMedia({audio:Gh});return ne.current=Ve,re(null),Ve},[]),We=Ke.useCallback(async Ve=>{Ve.getTracks().forEach(et=>{et.enabled=!1})},[]),de=Ke.useCallback(async()=>ne.current&&ne.current.getTracks()[0]?.readyState==="live"?(ne.current.getTracks().forEach(Ve=>{Ve.enabled=!0}),ne.current):me(),[me]);Ke.useCallback(()=>{const Ve=Pe.current;return Pe.current=[],Aa(Ve)},[]);const st=Ke.useCallback(()=>{le.current=[];const Ve=Pe.current;Pe.current=[];for(const et of Ve)ye(Ia(et));ce.current=!0},[ye]),qe=Ke.useCallback(()=>{ce.current=!1;const Ve=le.current;if(le.current=[],Ve.length>0){const et=Aa(Ve);ye(Ia(et))}},[ye]),dt=Ke.useCallback(()=>{ne.current&&(ne.current.getTracks().forEach(Ve=>Ve.stop()),ne.current=null)},[]);if(!O)return{isListening:!1,isLoading:!1,isErrored:!1,isSpeaking:!1,micError:null,toggle:async()=>!1,prepare:async()=>null,start:async()=>!1,stop:async()=>!1,pause:async()=>{},userSpeaking:!1};const Qe=cf.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:np,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:ip}},baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.30/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.1/dist/",ortConfig:Ve=>{Ve.env.wasm.numThreads=1,Ve.env.logLevel="error"},getStream:me,pauseStream:We,resumeStream:de,onFrameProcessed:(Ve,et)=>{if(et&&(Pe.current.push(new Float32Array(et)),Pe.current.length>ff&&Pe.current.shift(),ce.current)){const Xe=le.current;if(Xe.push(new Float32Array(et)),Xe.length>=3){const Rt=Aa(Xe);Xe.length=0,ye(Ia(Rt))}}},onSpeechStart:()=>{fe.current||(Re.current&&(clearTimeout(Re.current),Re.current=null),J(!0),d?.(),st())},onSpeechEnd:()=>{Re.current=setTimeout(()=>{J(!1),qe(),n?n():G(),fe.current=!0,setTimeout(()=>{fe.current=!1},300),g?.()},pf)},onVADMisfire:()=>{Re.current&&(clearTimeout(Re.current),Re.current=null),J(!1),qe(),E?.()}}),ut=Ke.useCallback(async()=>!O||Qe.loading||Qe.errored?!1:(Qe.listening&&(Re.current&&(clearTimeout(Re.current),Re.current=null),J(!1),qe(),await Qe.pause()),!0),[O,qe,Qe]),at=Ke.useCallback(async()=>{try{await Qe.start()}catch(Ve){const et=Ve instanceof Error?Ve.message:String(Ve);if(et.includes("null stream")||et.includes("audio context")||et.includes("processor adapter"))await new Promise(Xe=>setTimeout(Xe,100)),await Qe.start();else throw Ve}},[Qe]),Kt=Ke.useCallback(async()=>!O||Qe.loading||Qe.errored?!1:(Qe.listening?(Re.current&&(clearTimeout(Re.current),Re.current=null),J(!1),qe(),await Qe.pause()):await at(),!0),[O,qe,at]),Ct=Ke.useCallback(async()=>O?me():null,[O,me]),je=Ke.useCallback(async()=>!O||Qe.loading||Qe.errored?!1:(Qe.listening||await at(),!0),[O,at]);return Ke.useEffect(()=>()=>{Re.current&&clearTimeout(Re.current),qe(),dt()},[dt,qe]),{isListening:Qe.listening,isLoading:Qe.loading,isErrored:!!Qe.errored,isSpeaking:ae,micError:ie,toggle:Kt,prepare:Ct,start:je,stop:ut,pause:Qe.pause,userSpeaking:Qe.userSpeaking}}function yf(S,s,n=[]){const{events:d}=zt.useRqmiiAgentContext();Ke.useEffect(()=>d.on(S,s),[S,s,d,...n])}var Pa={exports:{}},Wh;function wf(){return Wh||(Wh=1,(function(S){const s={};s.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},s.localCName=s.generateIdentifier(),s.splitLines=function(n){return n.trim().split(`
|
|
2839
|
+
`).map(d=>d.trim())},s.splitSections=function(n){return n.split(`
|
|
2840
|
+
m=`).map((g,E)=>(E>0?"m="+g:g).trim()+`\r
|
|
2841
|
+
`)},s.getDescription=function(n){const d=s.splitSections(n);return d&&d[0]},s.getMediaSections=function(n){const d=s.splitSections(n);return d.shift(),d},s.matchPrefix=function(n,d){return s.splitLines(n).filter(g=>g.indexOf(d)===0)},s.parseCandidate=function(n){let d;n.indexOf("a=candidate:")===0?d=n.substring(12).split(" "):d=n.substring(10).split(" ");const g={foundation:d[0],component:{1:"rtp",2:"rtcp"}[d[1]]||d[1],protocol:d[2].toLowerCase(),priority:parseInt(d[3],10),ip:d[4],address:d[4],port:parseInt(d[5],10),type:d[7]};for(let E=8;E<d.length;E+=2)switch(d[E]){case"raddr":g.relatedAddress=d[E+1];break;case"rport":g.relatedPort=parseInt(d[E+1],10);break;case"tcptype":g.tcpType=d[E+1];break;case"ufrag":g.ufrag=d[E+1],g.usernameFragment=d[E+1];break;default:g[d[E]]===void 0&&(g[d[E]]=d[E+1]);break}return g},s.writeCandidate=function(n){const d=[];d.push(n.foundation);const g=n.component;g==="rtp"?d.push(1):g==="rtcp"?d.push(2):d.push(g),d.push(n.protocol.toUpperCase()),d.push(n.priority),d.push(n.address||n.ip),d.push(n.port);const E=n.type;return d.push("typ"),d.push(E),E!=="host"&&n.relatedAddress&&n.relatedPort!==void 0&&(d.push("raddr"),d.push(n.relatedAddress),d.push("rport"),d.push(n.relatedPort)),n.tcpType&&n.protocol.toLowerCase()==="tcp"&&(d.push("tcptype"),d.push(n.tcpType)),(n.usernameFragment||n.ufrag)&&(d.push("ufrag"),d.push(n.usernameFragment||n.ufrag)),"candidate:"+d.join(" ")},s.parseIceOptions=function(n){return n.substring(14).split(" ")},s.parseRtpMap=function(n){let d=n.substring(9).split(" ");const g={payloadType:parseInt(d.shift(),10)};return d=d[0].split("/"),g.name=d[0],g.clockRate=parseInt(d[1],10),g.channels=d.length===3?parseInt(d[2],10):1,g.numChannels=g.channels,g},s.writeRtpMap=function(n){let d=n.payloadType;n.preferredPayloadType!==void 0&&(d=n.preferredPayloadType);const g=n.channels||n.numChannels||1;return"a=rtpmap:"+d+" "+n.name+"/"+n.clockRate+(g!==1?"/"+g:"")+`\r
|
|
2842
|
+
`},s.parseExtmap=function(n){const d=n.substring(9).split(" ");return{id:parseInt(d[0],10),direction:d[0].indexOf("/")>0?d[0].split("/")[1]:"sendrecv",uri:d[1],attributes:d.slice(2).join(" ")}},s.writeExtmap=function(n){return"a=extmap:"+(n.id||n.preferredId)+(n.direction&&n.direction!=="sendrecv"?"/"+n.direction:"")+" "+n.uri+(n.attributes?" "+n.attributes:"")+`\r
|
|
2843
|
+
`},s.parseFmtp=function(n){const d={};let g;const E=n.substring(n.indexOf(" ")+1).split(";");for(let A=0;A<E.length;A++)g=E[A].trim().split("="),d[g[0].trim()]=g[1];return d},s.writeFmtp=function(n){let d="",g=n.payloadType;if(n.preferredPayloadType!==void 0&&(g=n.preferredPayloadType),n.parameters&&Object.keys(n.parameters).length){const E=[];Object.keys(n.parameters).forEach(A=>{n.parameters[A]!==void 0?E.push(A+"="+n.parameters[A]):E.push(A)}),d+="a=fmtp:"+g+" "+E.join(";")+`\r
|
|
2844
|
+
`}return d},s.parseRtcpFb=function(n){const d=n.substring(n.indexOf(" ")+1).split(" ");return{type:d.shift(),parameter:d.join(" ")}},s.writeRtcpFb=function(n){let d="",g=n.payloadType;return n.preferredPayloadType!==void 0&&(g=n.preferredPayloadType),n.rtcpFeedback&&n.rtcpFeedback.length&&n.rtcpFeedback.forEach(E=>{d+="a=rtcp-fb:"+g+" "+E.type+(E.parameter&&E.parameter.length?" "+E.parameter:"")+`\r
|
|
2845
|
+
`}),d},s.parseSsrcMedia=function(n){const d=n.indexOf(" "),g={ssrc:parseInt(n.substring(7,d),10)},E=n.indexOf(":",d);return E>-1?(g.attribute=n.substring(d+1,E),g.value=n.substring(E+1)):g.attribute=n.substring(d+1),g},s.parseSsrcGroup=function(n){const d=n.substring(13).split(" ");return{semantics:d.shift(),ssrcs:d.map(g=>parseInt(g,10))}},s.getMid=function(n){const d=s.matchPrefix(n,"a=mid:")[0];if(d)return d.substring(6)},s.parseFingerprint=function(n){const d=n.substring(14).split(" ");return{algorithm:d[0].toLowerCase(),value:d[1].toUpperCase()}},s.getDtlsParameters=function(n,d){return{role:"auto",fingerprints:s.matchPrefix(n+d,"a=fingerprint:").map(s.parseFingerprint)}},s.writeDtlsParameters=function(n,d){let g="a=setup:"+d+`\r
|
|
2846
|
+
`;return n.fingerprints.forEach(E=>{g+="a=fingerprint:"+E.algorithm+" "+E.value+`\r
|
|
2847
|
+
`}),g},s.parseCryptoLine=function(n){const d=n.substring(9).split(" ");return{tag:parseInt(d[0],10),cryptoSuite:d[1],keyParams:d[2],sessionParams:d.slice(3)}},s.writeCryptoLine=function(n){return"a=crypto:"+n.tag+" "+n.cryptoSuite+" "+(typeof n.keyParams=="object"?s.writeCryptoKeyParams(n.keyParams):n.keyParams)+(n.sessionParams?" "+n.sessionParams.join(" "):"")+`\r
|
|
2848
|
+
`},s.parseCryptoKeyParams=function(n){if(n.indexOf("inline:")!==0)return null;const d=n.substring(7).split("|");return{keyMethod:"inline",keySalt:d[0],lifeTime:d[1],mkiValue:d[2]?d[2].split(":")[0]:void 0,mkiLength:d[2]?d[2].split(":")[1]:void 0}},s.writeCryptoKeyParams=function(n){return n.keyMethod+":"+n.keySalt+(n.lifeTime?"|"+n.lifeTime:"")+(n.mkiValue&&n.mkiLength?"|"+n.mkiValue+":"+n.mkiLength:"")},s.getCryptoParameters=function(n,d){return s.matchPrefix(n+d,"a=crypto:").map(s.parseCryptoLine)},s.getIceParameters=function(n,d){const g=s.matchPrefix(n+d,"a=ice-ufrag:")[0],E=s.matchPrefix(n+d,"a=ice-pwd:")[0];return g&&E?{usernameFragment:g.substring(12),password:E.substring(10)}:null},s.writeIceParameters=function(n){let d="a=ice-ufrag:"+n.usernameFragment+`\r
|
|
2849
|
+
a=ice-pwd:`+n.password+`\r
|
|
2850
|
+
`;return n.iceLite&&(d+=`a=ice-lite\r
|
|
2851
|
+
`),d},s.parseRtpParameters=function(n){const d={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},E=s.splitLines(n)[0].split(" ");d.profile=E[2];for(let O=3;O<E.length;O++){const T=E[O],K=s.matchPrefix(n,"a=rtpmap:"+T+" ")[0];if(K){const G=s.parseRtpMap(K),ae=s.matchPrefix(n,"a=fmtp:"+T+" ");switch(G.parameters=ae.length?s.parseFmtp(ae[0]):{},G.rtcpFeedback=s.matchPrefix(n,"a=rtcp-fb:"+T+" ").map(s.parseRtcpFb),d.codecs.push(G),G.name.toUpperCase()){case"RED":case"ULPFEC":d.fecMechanisms.push(G.name.toUpperCase());break}}}s.matchPrefix(n,"a=extmap:").forEach(O=>{d.headerExtensions.push(s.parseExtmap(O))});const A=s.matchPrefix(n,"a=rtcp-fb:* ").map(s.parseRtcpFb);return d.codecs.forEach(O=>{A.forEach(T=>{O.rtcpFeedback.find(G=>G.type===T.type&&G.parameter===T.parameter)||O.rtcpFeedback.push(T)})}),d},s.writeRtpDescription=function(n,d){let g="";g+="m="+n+" ",g+=d.codecs.length>0?"9":"0",g+=" "+(d.profile||"UDP/TLS/RTP/SAVPF")+" ",g+=d.codecs.map(A=>A.preferredPayloadType!==void 0?A.preferredPayloadType:A.payloadType).join(" ")+`\r
|
|
2852
|
+
`,g+=`c=IN IP4 0.0.0.0\r
|
|
2853
|
+
`,g+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
2854
|
+
`,d.codecs.forEach(A=>{g+=s.writeRtpMap(A),g+=s.writeFmtp(A),g+=s.writeRtcpFb(A)});let E=0;return d.codecs.forEach(A=>{A.maxptime>E&&(E=A.maxptime)}),E>0&&(g+="a=maxptime:"+E+`\r
|
|
2855
|
+
`),d.headerExtensions&&d.headerExtensions.forEach(A=>{g+=s.writeExtmap(A)}),g},s.parseRtpEncodingParameters=function(n){const d=[],g=s.parseRtpParameters(n),E=g.fecMechanisms.indexOf("RED")!==-1,A=g.fecMechanisms.indexOf("ULPFEC")!==-1,O=s.matchPrefix(n,"a=ssrc:").map(J=>s.parseSsrcMedia(J)).filter(J=>J.attribute==="cname"),T=O.length>0&&O[0].ssrc;let K;const G=s.matchPrefix(n,"a=ssrc-group:FID").map(J=>J.substring(17).split(" ").map(re=>parseInt(re,10)));G.length>0&&G[0].length>1&&G[0][0]===T&&(K=G[0][1]),g.codecs.forEach(J=>{if(J.name.toUpperCase()==="RTX"&&J.parameters.apt){let ie={ssrc:T,codecPayloadType:parseInt(J.parameters.apt,10)};T&&K&&(ie.rtx={ssrc:K}),d.push(ie),E&&(ie=JSON.parse(JSON.stringify(ie)),ie.fec={ssrc:T,mechanism:A?"red+ulpfec":"red"},d.push(ie))}}),d.length===0&&T&&d.push({ssrc:T});let ae=s.matchPrefix(n,"b=");return ae.length&&(ae[0].indexOf("b=TIAS:")===0?ae=parseInt(ae[0].substring(7),10):ae[0].indexOf("b=AS:")===0?ae=parseInt(ae[0].substring(5),10)*1e3*.95-2e3*8:ae=void 0,d.forEach(J=>{J.maxBitrate=ae})),d},s.parseRtcpParameters=function(n){const d={},g=s.matchPrefix(n,"a=ssrc:").map(O=>s.parseSsrcMedia(O)).filter(O=>O.attribute==="cname")[0];g&&(d.cname=g.value,d.ssrc=g.ssrc);const E=s.matchPrefix(n,"a=rtcp-rsize");d.reducedSize=E.length>0,d.compound=E.length===0;const A=s.matchPrefix(n,"a=rtcp-mux");return d.mux=A.length>0,d},s.writeRtcpParameters=function(n){let d="";return n.reducedSize&&(d+=`a=rtcp-rsize\r
|
|
2856
|
+
`),n.mux&&(d+=`a=rtcp-mux\r
|
|
2857
|
+
`),n.ssrc!==void 0&&n.cname&&(d+="a=ssrc:"+n.ssrc+" cname:"+n.cname+`\r
|
|
2858
|
+
`),d},s.parseMsid=function(n){let d;const g=s.matchPrefix(n,"a=msid:");if(g.length===1)return d=g[0].substring(7).split(" "),{stream:d[0],track:d[1]};const E=s.matchPrefix(n,"a=ssrc:").map(A=>s.parseSsrcMedia(A)).filter(A=>A.attribute==="msid");if(E.length>0)return d=E[0].value.split(" "),{stream:d[0],track:d[1]}},s.parseSctpDescription=function(n){const d=s.parseMLine(n),g=s.matchPrefix(n,"a=max-message-size:");let E;g.length>0&&(E=parseInt(g[0].substring(19),10)),isNaN(E)&&(E=65536);const A=s.matchPrefix(n,"a=sctp-port:");if(A.length>0)return{port:parseInt(A[0].substring(12),10),protocol:d.fmt,maxMessageSize:E};const O=s.matchPrefix(n,"a=sctpmap:");if(O.length>0){const T=O[0].substring(10).split(" ");return{port:parseInt(T[0],10),protocol:T[1],maxMessageSize:E}}},s.writeSctpDescription=function(n,d){let g=[];return n.protocol!=="DTLS/SCTP"?g=["m="+n.kind+" 9 "+n.protocol+" "+d.protocol+`\r
|
|
2859
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
2860
|
+
`,"a=sctp-port:"+d.port+`\r
|
|
2861
|
+
`]:g=["m="+n.kind+" 9 "+n.protocol+" "+d.port+`\r
|
|
2862
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
2863
|
+
`,"a=sctpmap:"+d.port+" "+d.protocol+` 65535\r
|
|
2864
|
+
`],d.maxMessageSize!==void 0&&g.push("a=max-message-size:"+d.maxMessageSize+`\r
|
|
2865
|
+
`),g.join("")},s.generateSessionId=function(){return Math.random().toString().substr(2,22)},s.writeSessionBoilerplate=function(n,d,g){let E;const A=d!==void 0?d:2;return n?E=n:E=s.generateSessionId(),`v=0\r
|
|
2866
|
+
o=`+(g||"thisisadapterortc")+" "+E+" "+A+` IN IP4 127.0.0.1\r
|
|
2867
|
+
s=-\r
|
|
2868
|
+
t=0 0\r
|
|
2869
|
+
`},s.getDirection=function(n,d){const g=s.splitLines(n);for(let E=0;E<g.length;E++)switch(g[E]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return g[E].substring(2)}return d?s.getDirection(d):"sendrecv"},s.getKind=function(n){return s.splitLines(n)[0].split(" ")[0].substring(2)},s.isRejected=function(n){return n.split(" ",2)[1]==="0"},s.parseMLine=function(n){const g=s.splitLines(n)[0].substring(2).split(" ");return{kind:g[0],port:parseInt(g[1],10),protocol:g[2],fmt:g.slice(3).join(" ")}},s.parseOLine=function(n){const g=s.matchPrefix(n,"o=")[0].substring(2).split(" ");return{username:g[0],sessionId:g[1],sessionVersion:parseInt(g[2],10),netType:g[3],addressType:g[4],address:g[5]}},s.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;const d=s.splitLines(n);for(let g=0;g<d.length;g++)if(d[g].length<2||d[g].charAt(1)!=="=")return!1;return!0},S.exports=s})(Pa)),Pa.exports}var qh=wf(),nr,gt,un={d:(S,s)=>{for(var n in s)un.o(s,n)&&!un.o(S,n)&&Object.defineProperty(S,n,{enumerable:!0,get:s[n]})},o:(S,s)=>Object.prototype.hasOwnProperty.call(S,s)},pe={};un.d(pe,{Dz:()=>Vp,g$:()=>cp,Lt:()=>up,Q9:()=>dp,qf:()=>Ua,hV:()=>jp,z$:()=>cg,J0:()=>Na,De:()=>Bf,$C:()=>fs,al:()=>bp,_W:()=>_p,Gv:()=>zp,m:()=>Dp,tz:()=>vp,Nu:()=>qp,zg:()=>Xp,vp:()=>Np,vU:()=>j,wF:()=>Rp,rv:()=>Gp,Nh:()=>Wp,ss:()=>Qp,qW:()=>Lp,QL:()=>Op,cf:()=>Jp,eM:()=>Mp,Yd:()=>b,Tk:()=>we,iM:()=>ap,qy:()=>Cr,ce:()=>kf,sK:()=>oe,Ok:()=>rt,q5:()=>Hp,g:()=>dg,xl:()=>Ep,I:()=>kp,bx:()=>Fa,dD:()=>Up,Ib:()=>Ni,Az:()=>ft,Iw:()=>pr,qY:()=>Ba,db:()=>lp,mR:()=>Fi,Tn:()=>La,rV:()=>Ip,gh:()=>$p,Mi:()=>xp,j:()=>Tp,YB:()=>Cp,Yt:()=>Pp,i5:()=>Ap,x_:()=>Tr,Am:()=>Va,eR:()=>hp,r8:()=>Sp,u3:()=>Zp,vd:()=>mp,iV:()=>gp,jZ:()=>fp,SW:()=>wp,ZH:()=>yp,Ni:()=>Yp,lh:()=>pp,ZP:()=>Fp,bq:()=>op,$f:()=>em,eu:()=>Bp,Ax:()=>Pf,Mc:()=>Af});class b{static GetStackTrace(){const s=new Error;let n="No Stack Available for this browser";return s.stack&&(n=s.stack.toString().replace(/Error/g,"")),n}static SetLoggerVerbosity(s){this.verboseLogLevel!=null&&(this.verboseLogLevel=s)}static Log(s,n,d){if(d>this.verboseLogLevel)return;const g=`Level: Log
|
|
2870
|
+
Msg: ${n}
|
|
2871
|
+
Caller: ${s}`;console.log(g)}static Info(s,n,d){if(d>this.verboseLogLevel)return;const g=`Level: Info
|
|
2872
|
+
Msg: ${n}`;console.info(g)}static Error(s,n){const d=`Level: Error
|
|
2873
|
+
Msg: ${n}
|
|
2874
|
+
Caller: ${s}`;console.error(d)}static Warning(s,n){const d=`Level: Warning
|
|
2875
|
+
Caller: ${s}
|
|
2876
|
+
Msg: ${n}`;console.warn(d)}}b.verboseLogLevel=5,(function(S){S.LIST_STREAMERS="listStreamers",S.SUBSCRIBE="subscribe",S.UNSUBSCRIBE="unsubscribe",S.ICE_CANDIDATE="iceCandidate",S.OFFER="offer",S.ANSWER="answer",S.DATACHANNELREQUEST="dataChannelRequest",S.SFURECVDATACHANNELREADY="peerDataChannelsReady",S.PONG="pong"})(nr||(nr={}));class Cr{sendFilter(s,n){return n}payload(){return b.Log(b.GetStackTrace(),`Sending =>
|
|
2877
|
+
`+JSON.stringify(this,this.sendFilter,4),6),JSON.stringify(this,this.sendFilter)}}class vf extends Cr{constructor(){super(),this.type=nr.LIST_STREAMERS}}class bf extends Cr{constructor(s){super(),this.type=nr.SUBSCRIBE,this.streamerId=s}}class _f extends Cr{constructor(){super(),this.type=nr.UNSUBSCRIBE}}class Sf extends Cr{constructor(s){super(),this.type=nr.PONG,this.time=s}}class $f extends Cr{constructor(s,n){super(),this.type=nr.OFFER,this.minBitrate=0,this.maxBitrate=0,s&&(this.type=s.type,this.sdp=s.sdp,this.minBitrate=n.minBitrateBps,this.maxBitrate=n.maxBitrateBps)}sendFilter(s,n){if(s!="minBitrate"&&s!="maxBitrate"||!(n<=0))return n}}class xf extends Cr{constructor(s,n){super(),this.type=nr.ANSWER,this.minBitrate=0,this.maxBitrate=0,s&&(this.type=s.type,this.sdp=s.sdp,this.minBitrate=n.minBitrateBps,this.maxBitrate=n.maxBitrateBps)}sendFilter(s,n){if(s!="minBitrate"&&s!="maxBitrate"||!(n<=0))return n}}class Tf extends Cr{constructor(){super(),this.type=nr.DATACHANNELREQUEST}}class Cf extends Cr{constructor(){super(),this.type=nr.SFURECVDATACHANNELREADY}}class Ef{constructor(s){this.type=nr.ICE_CANDIDATE,this.candidate=s}payload(){return b.Log(b.GetStackTrace(),`Sending =>
|
|
2878
|
+
`+JSON.stringify(this,void 0,4),6),JSON.stringify(this)}}(function(S){S.CONFIG="config",S.STREAMER_LIST="streamerList",S.STREAMER_ID_CHANGED="streamerIDChanged",S.PLAYER_COUNT="playerCount",S.OFFER="offer",S.ANSWER="answer",S.ICE_CANDIDATE="iceCandidate",S.PEER_DATA_CHANNELS="peerDataChannels",S.PING="ping",S.WARNING="warning"})(gt||(gt={}));class ap{}class kf extends ap{}class La{constructor(){this.FromUEMessageHandlers=new Map}addMessageHandler(s,n){this.FromUEMessageHandlers.set(s,n)}handleMessage(s,n){this.FromUEMessageHandlers.has(s)?this.FromUEMessageHandlers.get(s)(n):b.Error(b.GetStackTrace(),`Message type of ${s} does not have a message handler registered on the frontend - ignoring message.`)}static setupDefaultHandlers(s){s.signallingProtocol.addMessageHandler(gt.PING,(n=>{const d=new Sf(new Date().getTime()).payload();b.Log(b.GetStackTrace(),gt.PING+": "+n,6),s.webSocket.send(d)})),s.signallingProtocol.addMessageHandler(gt.CONFIG,(n=>{b.Log(b.GetStackTrace(),gt.CONFIG,6);const d=JSON.parse(n);s.onConfig(d)})),s.signallingProtocol.addMessageHandler(gt.STREAMER_LIST,(n=>{b.Log(b.GetStackTrace(),gt.STREAMER_LIST,6);const d=JSON.parse(n);s.onStreamerList(d)})),s.signallingProtocol.addMessageHandler(gt.STREAMER_ID_CHANGED,(n=>{b.Log(b.GetStackTrace(),gt.STREAMER_ID_CHANGED,6);const d=JSON.parse(n);s.onStreamerIDChanged(d)})),s.signallingProtocol.addMessageHandler(gt.PLAYER_COUNT,(n=>{b.Log(b.GetStackTrace(),gt.PLAYER_COUNT,6);const d=JSON.parse(n);b.Log(b.GetStackTrace(),"Player Count: "+d.count,6),s.onPlayerCount(d)})),s.signallingProtocol.addMessageHandler(gt.ANSWER,(n=>{b.Log(b.GetStackTrace(),gt.ANSWER,6);const d=JSON.parse(n);s.onWebRtcAnswer(d)})),s.signallingProtocol.addMessageHandler(gt.OFFER,(n=>{b.Log(b.GetStackTrace(),gt.OFFER,6);const d=JSON.parse(n);s.onWebRtcOffer(d)})),s.signallingProtocol.addMessageHandler(gt.ICE_CANDIDATE,(n=>{b.Log(b.GetStackTrace(),gt.ICE_CANDIDATE,6);const d=JSON.parse(n);s.onIceCandidate(d.candidate)})),s.signallingProtocol.addMessageHandler(gt.WARNING,(n=>{b.Warning(b.GetStackTrace(),`Warning received: ${n}`)})),s.signallingProtocol.addMessageHandler(gt.PEER_DATA_CHANNELS,(n=>{b.Log(b.GetStackTrace(),gt.PEER_DATA_CHANNELS,6);const d=JSON.parse(n);s.onWebRtcPeerDataChannels(d)}))}}class op{constructor(){this.WS_OPEN_STATE=1,this.onOpen=new EventTarget,this.onClose=new EventTarget,this.signallingProtocol=new La,La.setupDefaultHandlers(this)}connect(s){b.Log(b.GetStackTrace(),s,6);try{return this.webSocket=new WebSocket(s),this.webSocket.onopen=n=>this.handleOnOpen(n),this.webSocket.onerror=()=>this.handleOnError(),this.webSocket.onclose=n=>this.handleOnClose(n),this.webSocket.onmessage=n=>this.handleOnMessage(n),this.webSocket.onmessagebinary=n=>this.handleOnMessageBinary(n),!0}catch(n){return b.Error(n,n),!1}}handleOnMessageBinary(s){s&&s.data&&s.data.text().then((n=>{const d=new MessageEvent("messageFromBinary",{data:n});this.handleOnMessage(d)})).catch((n=>{b.Error(b.GetStackTrace(),`Failed to parse binary blob from websocket, reason: ${n}`)}))}handleOnMessage(s){if(s.data&&s.data instanceof Blob)return void this.handleOnMessageBinary(s);const n=JSON.parse(s.data);b.Log(b.GetStackTrace(),`received =>
|
|
2879
|
+
`+JSON.stringify(JSON.parse(s.data),void 0,4),6),this.signallingProtocol.handleMessage(n.type,s.data)}handleOnOpen(s){b.Log(b.GetStackTrace(),"Connected to the signalling server via WebSocket",6),this.onOpen.dispatchEvent(new Event("open"))}handleOnError(){b.Error(b.GetStackTrace(),"WebSocket error")}handleOnClose(s){b.Log(b.GetStackTrace(),"Disconnected to the signalling server via WebSocket: "+JSON.stringify(s.code)+" - "+s.reason),this.onClose.dispatchEvent(new CustomEvent("close",{detail:s}))}requestStreamerList(){const s=new vf;this.webSocket.send(s.payload())}sendSubscribe(s){const n=new bf(s);this.webSocket.send(n.payload())}sendUnsubscribe(){const s=new _f;this.webSocket.send(s.payload())}sendWebRtcOffer(s,n){const d=new $f(s,n);this.webSocket.send(d.payload())}sendWebRtcAnswer(s,n){const d=new xf(s,n);this.webSocket.send(d.payload())}sendWebRtcDatachannelRequest(){const s=new Tf;this.webSocket.send(s.payload())}sendSFURecvDataChannelReady(){const s=new Cf;this.webSocket.send(s.payload())}sendIceCandidate(s){if(b.Log(b.GetStackTrace(),"Sending Ice Candidate"),this.webSocket&&this.webSocket.readyState===this.WS_OPEN_STATE){const n=new Ef(s);this.webSocket.send(n.payload())}}close(){var s;(s=this.webSocket)===null||s===void 0||s.close()}onConfig(s){}onStreamerList(s){}onStreamerIDChanged(s){}onIceCandidate(s){}onWebRtcAnswer(s){}onWebRtcOffer(s){}onWebRtcPeerDataChannels(s){}onPlayerCount(s){}}class Mf{constructor(s){this.videoElementProvider=s,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(s){if(b.Log(b.GetStackTrace(),"handleOnTrack "+JSON.stringify(s.streams),6),s.track.id=="probator")return;const n=this.videoElementProvider.getVideoElement();if(s.track&&b.Log(b.GetStackTrace(),"Got track - "+s.track.kind+" id="+s.track.id+" readyState="+s.track.readyState,6),s.track.kind!="audio")return s.track.kind=="video"&&n.srcObject!==s.streams[0]?(n.srcObject=s.streams[0],void b.Log(b.GetStackTrace(),"Set video source from video track ontrack.")):void 0;this.CreateAudioTrack(s.streams[0])}CreateAudioTrack(s){const n=this.videoElementProvider.getVideoElement();n.srcObject!=s&&n.srcObject&&n.srcObject!==s&&(this.audioElement.srcObject=s,b.Log(b.GetStackTrace(),"Created new audio element to play separate audio stream."))}}class Rf{constructor(s){this.freezeFrameHeight=0,this.freezeFrameWidth=0,this.rootDiv=s,this.rootElement=document.createElement("div"),this.rootElement.id="freezeFrame",this.rootElement.style.display="none",this.rootElement.style.pointerEvents="none",this.rootElement.style.position="absolute",this.rootElement.style.zIndex="20",this.imageElement=document.createElement("img"),this.imageElement.style.position="absolute",this.rootElement.appendChild(this.imageElement),this.rootDiv.appendChild(this.rootElement)}setElementForShow(){this.rootElement.style.display="block"}setElementForHide(){this.rootElement.style.display="none"}updateImageElementSource(s){const n=btoa(s.reduce(((d,g)=>d+String.fromCharCode(g)),""));this.imageElement.src="data:image/jpeg;base64,"+n}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(this.freezeFrameWidth!==0&&this.freezeFrameHeight!==0){let s=0,n=0,d=0,g=0;const E=this.rootDiv.clientWidth/this.rootDiv.clientHeight,A=this.freezeFrameWidth/this.freezeFrameHeight;E<A?(s=this.rootDiv.clientWidth,n=Math.floor(this.rootDiv.clientWidth/A),d=Math.floor(.5*(this.rootDiv.clientHeight-n)),g=0):(s=Math.floor(this.rootDiv.clientHeight*A),n=this.rootDiv.clientHeight,d=0,g=Math.floor(.5*(this.rootDiv.clientWidth-s))),this.rootElement.style.width=this.rootDiv.offsetWidth+"px",this.rootElement.style.height=this.rootDiv.offsetHeight+"px",this.rootElement.style.left="0px",this.rootElement.style.top="0px",this.imageElement.style.width=s+"px",this.imageElement.style.height=n+"px",this.imageElement.style.left=g+"px",this.imageElement.style.top=d+"px"}}}class If{constructor(s){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Rf(s)}showFreezeFrame(){this.valid&&this.freezeFrame.setElementForShow()}hideFreezeFrame(){this.valid=!1,this.freezeFrame.setElementForHide()}updateFreezeFrameAndShow(s,n){this.freezeFrame.updateImageElementSource(s),this.freezeFrame.imageElement.onload=()=>{this.freezeFrame.setDimensionsFromElementAndResize(),n()}}processFreezeFrameMessage(s,n){this.receiving||(this.receiving=!0,this.valid=!1,this.size=0,this.jpeg=void 0),this.size=new DataView(s.slice(1,5).buffer).getInt32(0,!0);const d=s.slice(5);if(this.jpeg){const g=new Uint8Array(this.jpeg.length+d.length);g.set(this.jpeg,0),g.set(d,this.jpeg.length),this.jpeg=g}else this.jpeg=d,this.receiving=!0,b.Log(b.GetStackTrace(),`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`,6);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,b.Log(b.GetStackTrace(),`received complete freeze frame ${this.size}`,6),this.updateFreezeFrameAndShow(this.jpeg,n)):this.jpeg.length>this.size&&(b.Error(b.GetStackTrace(),`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class Ni{constructor(s,n,d,g,E=(()=>{})){this.onChange=E,this.onChangeEmit=()=>{},this.id=s,this.description=d,this.label=n,this.value=g}set label(s){this._label=s,this.onChangeEmit(this._value)}get label(){return this._label}get value(){return this._value}set value(s){this._value=s,this.onChange(this._value,this),this.onChangeEmit(this._value)}}class ft extends Ni{constructor(s,n,d,g,E,A=(()=>{})){super(s,n,d,g,A);const O=new URLSearchParams(window.location.search);if(E&&O.has(this.id)){const T=this.getUrlParamFlag();this.flag=T}else this.flag=g;this.useUrlParams=E}getUrlParamFlag(){const s=new URLSearchParams(window.location.search);return!!s.has(this.id)&&s.get(this.id)!=="false"&&s.get(this.id)!=="False"}updateURLParams(){if(this.useUrlParams){const s=new URLSearchParams(window.location.search);this.flag===!0?s.set(this.id,"true"):s.set(this.id,"false"),window.history.replaceState({},"",s.toString()!==""?`${location.pathname}?${s}`:`${location.pathname}`)}}enable(){this.flag=!0}get flag(){return!!this.value}set flag(s){this.value=s}}class pr extends Ni{constructor(s,n,d,g,E,A,O,T=(()=>{})){super(s,n,d,A,T),this._min=g,this._max=E;const K=new URLSearchParams(window.location.search);if(O&&K.has(this.id)){const G=Number.parseFloat(K.get(this.id));this.number=Number.isNaN(G)?A:G}else this.number=A;this.useUrlParams=O}updateURLParams(){if(this.useUrlParams){const s=new URLSearchParams(window.location.search);s.set(this.id,this.number.toString()),window.history.replaceState({},"",s.toString()!==""?`${location.pathname}?${s}`:`${location.pathname}`)}}set number(s){this.value=this.clamp(s)}get number(){return this.value}clamp(s){return this._min==null&&this._max==null?s:this._min==null?Math.min(this._max,s):this._max==null?Math.max(this._min,s):Math.max(Math.min(this._max,s),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(s){this.onChange=s}}class lp extends Ni{constructor(s,n,d,g,E,A=(()=>{})){super(s,n,d,g,A);const O=new URLSearchParams(window.location.search);if(E&&O.has(this.id)){const T=this.getUrlParamText();this.text=T}else this.text=g;this.useUrlParams=E}getUrlParamText(){var s;const n=new URLSearchParams(window.location.search);return n.has(this.id)&&(s=n.get(this.id))!==null&&s!==void 0?s:""}updateURLParams(){if(this.useUrlParams){const s=new URLSearchParams(window.location.search);s.set(this.id,this.text),window.history.replaceState({},"",s.toString()!==""?`${location.pathname}?${s}`:`${location.pathname}`)}}get text(){return this.value}set text(s){this.value=s}}class Ba extends Ni{constructor(s,n,d,g,E,A,O=(()=>{})){super(s,n,d,g,O),this.options=E;const T=new URLSearchParams(window.location.search),K=A&&T.has(this.id)?this.getUrlParamText():g;this.selected=K,this.useUrlParams=A}getUrlParamText(){var s;const n=new URLSearchParams(window.location.search);return n.has(this.id)&&(s=n.get(this.id))!==null&&s!==void 0?s:""}updateURLParams(){if(this.useUrlParams){const s=new URLSearchParams(window.location.search);s.set(this.id,this.selected),window.history.replaceState({},"",s.toString()!==""?`${location.pathname}?${s}`:`${location.pathname}`)}}addOnChangedListener(s){this.onChange=s}get options(){return this._options}set options(s){this._options=s,this.onChangeEmit(this.selected)}get selected(){return this.value}set selected(s){let n=this.options.filter((d=>d.indexOf(s)!==-1));n.length?this.value=n[0]:(n=this.options.filter((d=>d.indexOf(s.split(" ")[0])!==-1)),n.length&&(this.value=n[0]))}}class up extends Event{constructor(s){super("afkWarningActivate"),this.data=s}}class Ua extends Event{constructor(s){super("afkWarningUpdate"),this.data=s}}class dp extends Event{constructor(){super("afkWarningDeactivate")}}class cp extends Event{constructor(){super("afkTimedOut")}}class hp extends Event{constructor(s){super("videoEncoderAvgQP"),this.data=s}}class pp extends Event{constructor(){super("webRtcSdp")}}class mp extends Event{constructor(){super("webRtcAutoConnect")}}class fp extends Event{constructor(){super("webRtcConnecting")}}class gp extends Event{constructor(){super("webRtcConnected")}}class yp extends Event{constructor(){super("webRtcFailed")}}class wp extends Event{constructor(s){super("webRtcDisconnected"),this.data=s}}class vp extends Event{constructor(s){super("dataChannelOpen"),this.data=s}}class bp extends Event{constructor(s){super("dataChannelClose"),this.data=s}}class _p extends Event{constructor(s){super("dataChannelError"),this.data=s}}class Sp extends Event{constructor(){super("videoInitialized")}}class $p extends Event{constructor(){super("streamLoading")}}class xp extends Event{constructor(){super("streamConnect")}}class Tp extends Event{constructor(){super("streamDisconnect")}}class Cp extends Event{constructor(){super("streamReconnect")}}class Ep extends Event{constructor(s){super("playStreamError"),this.data=s}}class kp extends Event{constructor(){super("playStream")}}class Fa extends Event{constructor(s){super("playStreamRejected"),this.data=s}}class Mp extends Event{constructor(s){super("loadFreezeFrame"),this.data=s}}class Rp extends Event{constructor(){super("hideFreezeFrame")}}class Ip extends Event{constructor(s){super("statsReceived"),this.data=s}}class Ap extends Event{constructor(s){super("streamerListMessage"),this.data=s}}class Pp extends Event{constructor(s){super("StreamerIDChangedMessage"),this.data=s}}class Op extends Event{constructor(s){super("latencyTestResult"),this.data=s}}class zp extends Event{constructor(s){super("dataChannelLatencyTestResponse"),this.data=s}}class Dp extends Event{constructor(s){super("dataChannelLatencyTestResult"),this.data=s}}class Lp extends Event{constructor(s){super("initialSettings"),this.data=s}}class Fi extends Event{constructor(s){super("settingsChanged"),this.data=s}}class Af extends Event{constructor(){super("xrSessionStarted")}}class Pf extends Event{constructor(){super("xrSessionEnded")}}class Bp extends Event{constructor(s){super("xrFrame"),this.data=s}}class Up extends Event{constructor(s){super("playerCount"),this.data=s}}class Fp extends Event{constructor(){super("webRtcTCPRelayDetected")}}class Np extends EventTarget{dispatchEvent(s){return super.dispatchEvent(s)}addEventListener(s,n){super.addEventListener(s,n)}removeEventListener(s,n){super.removeEventListener(s,n)}}class j{}j.AutoConnect="AutoConnect",j.AutoPlayVideo="AutoPlayVideo",j.AFKDetection="TimeoutIfIdle",j.BrowserSendOffer="OfferToReceive",j.HoveringMouseMode="HoveringMouse",j.ForceMonoAudio="ForceMonoAudio",j.ForceTURN="ForceTURN",j.FakeMouseWithTouches="FakeMouseWithTouches",j.IsQualityController="ControlsQuality",j.MatchViewportResolution="MatchViewportRes",j.StartVideoMuted="StartVideoMuted",j.SuppressBrowserKeys="SuppressBrowserKeys",j.UseMic="UseMic",j.KeyboardInput="KeyboardInput",j.MouseInput="MouseInput",j.TouchInput="TouchInput",j.GamepadInput="GamepadInput",j.XRControllerInput="XRControllerInput",j.WaitForStreamer="WaitForStreamer",j.HideUI="HideUI";const Of=S=>Object.getOwnPropertyNames(j).some((s=>j[s]===S));class oe{}oe.AFKTimeoutSecs="AFKTimeout",oe.AFKCountdownSecs="AFKCountdown",oe.MinQP="MinQP",oe.MaxQP="MaxQP",oe.WebRTCFPS="WebRTCFPS",oe.WebRTCMinBitrate="WebRTCMinBitrate",oe.WebRTCMaxBitrate="WebRTCMaxBitrate",oe.MaxReconnectAttempts="MaxReconnectAttempts",oe.StreamerAutoJoinInterval="StreamerAutoJoinInterval";const zf=S=>Object.getOwnPropertyNames(oe).some((s=>oe[s]===S));class Tr{}Tr.SignallingServerUrl="ss";const Df=S=>Object.getOwnPropertyNames(Tr).some((s=>Tr[s]===S));class rt{}rt.PreferredCodec="PreferredCodec",rt.StreamerId="StreamerId";const Lf=S=>Object.getOwnPropertyNames(rt).some((s=>rt[s]===S));class Bf{constructor(s={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:n,useUrlParams:d}=s;this._useUrlParams=!!d,this.populateDefaultSettings(this._useUrlParams,n)}get useUrlParams(){return this._useUrlParams}populateDefaultSettings(s,n){this.textParameters.set(Tr.SignallingServerUrl,new lp(Tr.SignallingServerUrl,"Signalling url","Url of the signalling server",n&&n.hasOwnProperty(Tr.SignallingServerUrl)?n[Tr.SignallingServerUrl]:(location.protocol==="https:"?"wss://":"ws://")+window.location.hostname+(window.location.port==="80"||window.location.port===""?"":`:${window.location.port}`),s)),this.optionParameters.set(rt.StreamerId,new Ba(rt.StreamerId,"Streamer ID","The ID of the streamer to stream.",n&&n.hasOwnProperty(rt.StreamerId)?n[rt.StreamerId]:"",[],s)),this.optionParameters.set(rt.PreferredCodec,new Ba(rt.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation","H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",n&&n.hasOwnProperty(rt.PreferredCodec)?[n[rt.PreferredCodec]]:(function(){const d=[];if(!RTCRtpReceiver.getCapabilities)return d.push("Only available on Chrome"),d;const g=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((E=>{const A=E.mimeType.split("/")[1]+" "+(E.sdpFmtpLine||"");g.exec(A)!==null&&d.push(A)})),d})(),s)),this.flags.set(j.AutoConnect,new ft(j.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",!(!n||!n.hasOwnProperty(j.AutoConnect))&&n[j.AutoConnect],s)),this.flags.set(j.AutoPlayVideo,new ft(j.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!n||!n.hasOwnProperty(j.AutoPlayVideo)||n[j.AutoPlayVideo],s)),this.flags.set(j.BrowserSendOffer,new ft(j.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!n||!n.hasOwnProperty(j.BrowserSendOffer))&&n[j.BrowserSendOffer],s)),this.flags.set(j.UseMic,new ft(j.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!n||!n.hasOwnProperty(j.UseMic))&&n[j.UseMic],s)),this.flags.set(j.StartVideoMuted,new ft(j.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!n||!n.hasOwnProperty(j.StartVideoMuted))&&n[j.StartVideoMuted],s)),this.flags.set(j.SuppressBrowserKeys,new ft(j.SuppressBrowserKeys,"Suppress browser keys","Suppress certain browser keys that we use in UE, for example F5 to show shader complexity instead of refresh the page.",!n||!n.hasOwnProperty(j.SuppressBrowserKeys)||n[j.SuppressBrowserKeys],s)),this.flags.set(j.IsQualityController,new ft(j.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!n||!n.hasOwnProperty(j.IsQualityController)||n[j.IsQualityController],s)),this.flags.set(j.ForceMonoAudio,new ft(j.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!n||!n.hasOwnProperty(j.ForceMonoAudio))&&n[j.ForceMonoAudio],s)),this.flags.set(j.ForceTURN,new ft(j.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!n||!n.hasOwnProperty(j.ForceTURN))&&n[j.ForceTURN],s)),this.flags.set(j.AFKDetection,new ft(j.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!n||!n.hasOwnProperty(j.AFKDetection))&&n[j.AFKDetection],s)),this.flags.set(j.MatchViewportResolution,new ft(j.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",!(!n||!n.hasOwnProperty(j.MatchViewportResolution))&&n[j.MatchViewportResolution],s)),this.flags.set(j.HoveringMouseMode,new ft(j.HoveringMouseMode,"Control Scheme: Locked Mouse","Either locked mouse, where the pointer is consumed by the video and locked to it, or hovering mouse, where the mouse is not consumed.",!(!n||!n.hasOwnProperty(j.HoveringMouseMode))&&n[j.HoveringMouseMode],s,((d,g)=>{g.label=`Control Scheme: ${d?"Hovering":"Locked"} Mouse`}))),this.flags.set(j.FakeMouseWithTouches,new ft(j.FakeMouseWithTouches,"Fake mouse with touches","A single finger touch is converted into a mouse event. This allows a non-touch application to be controlled partially via a touch device.",!(!n||!n.hasOwnProperty(j.FakeMouseWithTouches))&&n[j.FakeMouseWithTouches],s)),this.flags.set(j.KeyboardInput,new ft(j.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!n||!n.hasOwnProperty(j.KeyboardInput)||n[j.KeyboardInput],s)),this.flags.set(j.MouseInput,new ft(j.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!n||!n.hasOwnProperty(j.MouseInput)||n[j.MouseInput],s)),this.flags.set(j.TouchInput,new ft(j.TouchInput,"Touch input","If enabled, send touch events to streamer",!n||!n.hasOwnProperty(j.TouchInput)||n[j.TouchInput],s)),this.flags.set(j.GamepadInput,new ft(j.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!n||!n.hasOwnProperty(j.GamepadInput)||n[j.GamepadInput],s)),this.flags.set(j.XRControllerInput,new ft(j.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!n||!n.hasOwnProperty(j.XRControllerInput)||n[j.XRControllerInput],s)),this.flags.set(j.WaitForStreamer,new ft(j.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!n||!n.hasOwnProperty(j.WaitForStreamer)||n[j.WaitForStreamer],s)),this.flags.set(j.HideUI,new ft(j.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!n||!n.hasOwnProperty(j.HideUI))&&n[j.HideUI],s)),this.numericParameters.set(oe.AFKTimeoutSecs,new pr(oe.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,n&&n.hasOwnProperty(oe.AFKTimeoutSecs)?n[oe.AFKTimeoutSecs]:120,s)),this.numericParameters.set(oe.AFKCountdownSecs,new pr(oe.AFKCountdownSecs,"AFK countdown","The time (in seconds) for a user to respond before the stream is ended after an AFK timeout.",10,null,10,s)),this.numericParameters.set(oe.MaxReconnectAttempts,new pr(oe.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,n&&n.hasOwnProperty(oe.MaxReconnectAttempts)?n[oe.MaxReconnectAttempts]:3,s)),this.numericParameters.set(oe.MinQP,new pr(oe.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,n&&n.hasOwnProperty(oe.MinQP)?n[oe.MinQP]:0,s)),this.numericParameters.set(oe.MaxQP,new pr(oe.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,n&&n.hasOwnProperty(oe.MaxQP)?n[oe.MaxQP]:51,s)),this.numericParameters.set(oe.WebRTCFPS,new pr(oe.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,n&&n.hasOwnProperty(oe.WebRTCFPS)?n[oe.WebRTCFPS]:60,s)),this.numericParameters.set(oe.WebRTCMinBitrate,new pr(oe.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,n&&n.hasOwnProperty(oe.WebRTCMinBitrate)?n[oe.WebRTCMinBitrate]:0,s)),this.numericParameters.set(oe.WebRTCMaxBitrate,new pr(oe.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,n&&n.hasOwnProperty(oe.WebRTCMaxBitrate)?n[oe.WebRTCMaxBitrate]:0,s)),this.numericParameters.set(oe.StreamerAutoJoinInterval,new pr(oe.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,n&&n.hasOwnProperty(oe.StreamerAutoJoinInterval)?n[oe.StreamerAutoJoinInterval]:3e3,s))}_addOnNumericSettingChangedListener(s,n){this.numericParameters.has(s)&&this.numericParameters.get(s).addOnChangedListener(n)}_addOnOptionSettingChangedListener(s,n){this.optionParameters.has(s)&&this.optionParameters.get(s).addOnChangedListener(n)}getNumericSettingValue(s){if(this.numericParameters.has(s))return this.numericParameters.get(s).number;throw new Error(`There is no numeric setting with the id of ${s}`)}getTextSettingValue(s){if(this.textParameters.has(s))return this.textParameters.get(s).value;throw new Error(`There is no numeric setting with the id of ${s}`)}setNumericSetting(s,n){if(!this.numericParameters.has(s))throw new Error(`There is no numeric setting with the id of ${s}`);this.numericParameters.get(s).number=n}_addOnSettingChangedListener(s,n){this.flags.has(s)&&(this.flags.get(s).onChange=n)}_addOnTextSettingChangedListener(s,n){this.textParameters.has(s)&&(this.textParameters.get(s).onChange=n)}getSettingOption(s){return this.optionParameters.get(s)}isFlagEnabled(s){return this.flags.get(s).flag}setFlagEnabled(s,n){this.flags.has(s)?this.flags.get(s).flag=n:b.Warning(b.GetStackTrace(),`Cannot toggle flag called ${s} - it does not exist in the Config.flags map.`)}setTextSetting(s,n){this.textParameters.has(s)?this.textParameters.get(s).text=n:b.Warning(b.GetStackTrace(),`Cannot set text setting called ${s} - it does not exist in the Config.textParameters map.`)}setOptionSettingOptions(s,n){this.optionParameters.has(s)?this.optionParameters.get(s).options=n:b.Warning(b.GetStackTrace(),`Cannot set text setting called ${s} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(s,n){if(this.optionParameters.has(s)){const d=this.optionParameters.get(s),g=d.options;g.includes(n)||(g.push(n),d.options=g),d.selected=n}else b.Warning(b.GetStackTrace(),`Cannot set text setting called ${s} - it does not exist in the Config.enumParameters map.`)}setFlagLabel(s,n){this.flags.has(s)?this.flags.get(s).label=n:b.Warning(b.GetStackTrace(),`Cannot set label for flag called ${s} - it does not exist in the Config.flags map.`)}setSettings(s){for(const n of Object.keys(s))Of(n)?this.setFlagEnabled(n,s[n]):zf(n)?this.setNumericSetting(n,s[n]):Df(n)?this.setTextSetting(n,s[n]):Lf(n)&&this.setOptionSettingValue(n,s[n])}getSettings(){const s={};for(const[n,d]of this.flags.entries())s[n]=d.flag;for(const[n,d]of this.numericParameters.entries())s[n]=d.number;for(const[n,d]of this.textParameters.entries())s[n]=d.text;for(const[n,d]of this.optionParameters.entries())s[n]=d.selected;return s}getFlags(){return Array.from(this.flags.values())}getTextSettings(){return Array.from(this.textParameters.values())}getNumericSettings(){return Array.from(this.numericParameters.values())}getOptionSettings(){return Array.from(this.optionParameters.values())}_registerOnChangeEvents(s){for(const n of this.flags.keys()){const d=this.flags.get(n);d&&(d.onChangeEmit=g=>s.dispatchEvent(new Fi({id:d.id,type:"flag",value:g,target:d})))}for(const n of this.numericParameters.keys()){const d=this.numericParameters.get(n);d&&(d.onChangeEmit=g=>s.dispatchEvent(new Fi({id:d.id,type:"number",value:g,target:d})))}for(const n of this.textParameters.keys()){const d=this.textParameters.get(n);d&&(d.onChangeEmit=g=>s.dispatchEvent(new Fi({id:d.id,type:"text",value:g,target:d})))}for(const n of this.optionParameters.keys()){const d=this.optionParameters.get(n);d&&(d.onChangeEmit=g=>s.dispatchEvent(new Fi({id:d.id,type:"option",value:g,target:d})))}}}var fs;(function(S){S[S.LockedMouse=0]="LockedMouse",S[S.HoveringMouse=1]="HoveringMouse"})(fs||(fs={}));class Vp{constructor(s,n,d){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=s,this.pixelStreaming=n,this.onDismissAfk=d,this.onAFKTimedOutCallback=()=>{console.log("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new dp))}startAfkWarningTimer(){this.config.getNumericSettingValue(oe.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(j.AFKDetection)?this.active=!0:this.active=!1,this.resetAfkWarningTimer()}stopAfkWarningTimer(){this.active=!1,this.countdownActive=!1,clearTimeout(this.warnTimer),clearInterval(this.countDownTimer)}pauseAfkWarningTimer(){this.active=!1}resetAfkWarningTimer(){this.active&&this.config.isFlagEnabled(j.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(oe.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new up({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(oe.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new Ua({countDown:this.countDown})),this.config.isFlagEnabled(j.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new cp),this.onAFKTimedOutCallback(),b.Log(b.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new Ua({countDown:this.countDown}))}),1e3)}}class Hh{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(s,n,d){this.peerConnection=s,this.label=n,this.datachannelOptions=d,d==null&&(this.datachannelOptions={},this.datachannelOptions.ordered=!0),this.dataChannel=this.peerConnection.createDataChannel(this.label,this.datachannelOptions),this.setupDataChannel()}setupDataChannel(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=s=>this.handleOnOpen(s),this.dataChannel.onclose=s=>this.handleOnClose(s),this.dataChannel.onmessage=s=>this.handleOnMessage(s),this.dataChannel.onerror=s=>this.handleOnError(s)}handleOnOpen(s){var n;b.Log(b.GetStackTrace(),`Data Channel (${this.label}) opened.`,7),this.onOpen((n=this.dataChannel)===null||n===void 0?void 0:n.label,s)}handleOnClose(s){var n;b.Log(b.GetStackTrace(),`Data Channel (${this.label}) closed.`,7),this.onClose((n=this.dataChannel)===null||n===void 0?void 0:n.label,s)}handleOnMessage(s){b.Log(b.GetStackTrace(),`Data Channel (${this.label}) message: ${s}`,8)}handleOnError(s){var n;b.Log(b.GetStackTrace(),`Data Channel (${this.label}) error: ${s}`,7),this.onError((n=this.dataChannel)===null||n===void 0?void 0:n.label,s)}onOpen(s,n){}onClose(s,n){}onError(s,n){}}class Gp{}class Wp{}class qp{}class Na{}class Hp{}class Uf{}class Ff{}class jp{constructor(){this.inboundVideoStats=new Wp,this.inboundAudioStats=new Gp,this.DataChannelStats=new qp,this.outBoundVideoStats=new Hp,this.sessionStats=new Uf,this.streamStats=new Ff,this.codecs=new Map}processStats(s){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,s.forEach((n=>{switch(n.type){case"candidate-pair":this.handleCandidatePair(n);break;case"certificate":case"media-source":case"media-playout":case"outbound-rtp":case"peer-connection":case"remote-inbound-rtp":break;case"codec":this.handleCodec(n);break;case"data-channel":this.handleDataChannel(n);break;case"inbound-rtp":this.handleInBoundRTP(n);break;case"local-candidate":this.handleLocalCandidate(n);break;case"remote-candidate":this.handleRemoteCandidate(n);break;case"remote-outbound-rtp":this.handleRemoteOutBound(n);break;case"track":this.handleTrack(n);break;case"transport":this.handleTransport(n);break;case"stream":this.handleStream(n);break;default:b.Error(b.GetStackTrace(),"unhandled Stat Type"),b.Log(b.GetStackTrace(),n)}}))}handleStream(s){this.streamStats=s}handleCandidatePair(s){this.candidatePairs.push(s)}handleDataChannel(s){this.DataChannelStats.bytesReceived=s.bytesReceived,this.DataChannelStats.bytesSent=s.bytesSent,this.DataChannelStats.dataChannelIdentifier=s.dataChannelIdentifier,this.DataChannelStats.id=s.id,this.DataChannelStats.label=s.label,this.DataChannelStats.messagesReceived=s.messagesReceived,this.DataChannelStats.messagesSent=s.messagesSent,this.DataChannelStats.protocol=s.protocol,this.DataChannelStats.state=s.state,this.DataChannelStats.timestamp=s.timestamp}handleLocalCandidate(s){const n=new Na;n.label="local-candidate",n.address=s.address,n.port=s.port,n.protocol=s.protocol,n.candidateType=s.candidateType,n.id=s.id,n.relayProtocol=s.relayProtocol,n.transportId=s.transportId,this.localCandidates.push(n)}handleRemoteCandidate(s){const n=new Na;n.label="remote-candidate",n.address=s.address,n.port=s.port,n.protocol=s.protocol,n.id=s.id,n.candidateType=s.candidateType,n.relayProtocol=s.relayProtocol,n.transportId=s.transportId,this.remoteCandidates.push(n)}handleInBoundRTP(s){switch(s.kind){case"video":this.inboundVideoStats=s,this.lastVideoStats!=null&&(this.inboundVideoStats.bitrate=8*(this.inboundVideoStats.bytesReceived-this.lastVideoStats.bytesReceived)/(this.inboundVideoStats.timestamp-this.lastVideoStats.timestamp),this.inboundVideoStats.bitrate=Math.floor(this.inboundVideoStats.bitrate)),this.lastVideoStats=Object.assign({},this.inboundVideoStats);break;case"audio":this.inboundAudioStats=s,this.lastAudioStats!=null&&(this.inboundAudioStats.bitrate=8*(this.inboundAudioStats.bytesReceived-this.lastAudioStats.bytesReceived)/(this.inboundAudioStats.timestamp-this.lastAudioStats.timestamp),this.inboundAudioStats.bitrate=Math.floor(this.inboundAudioStats.bitrate)),this.lastAudioStats=Object.assign({},this.inboundAudioStats);break;default:b.Log(b.GetStackTrace(),"Kind is not handled")}}handleRemoteOutBound(s){s.kind==="video"&&(this.outBoundVideoStats.bytesSent=s.bytesSent,this.outBoundVideoStats.id=s.id,this.outBoundVideoStats.localId=s.localId,this.outBoundVideoStats.packetsSent=s.packetsSent,this.outBoundVideoStats.remoteTimestamp=s.remoteTimestamp,this.outBoundVideoStats.timestamp=s.timestamp)}handleTrack(s){s.type!=="track"||s.trackIdentifier!=="video_label"&&s.kind!=="video"||(this.inboundVideoStats.framesDropped=s.framesDropped,this.inboundVideoStats.framesReceived=s.framesReceived,this.inboundVideoStats.frameHeight=s.frameHeight,this.inboundVideoStats.frameWidth=s.frameWidth)}handleTransport(s){this.transportStats=s}handleCodec(s){const n=s.id,d=`${s.mimeType.replace("video/","").replace("audio/","")}${s.sdpFmtpLine?` ${s.sdpFmtpLine}`:""}`;this.codecs.set(n,d)}handleSessionStatistics(s,n,d){const g=Date.now()-s;this.sessionStats.runTime=new Date(g).toISOString().substr(11,8).toString();const E=n===null?"Not sent yet":n?"true":"false";this.sessionStats.controlsStreamInput=E,this.sessionStats.videoEncoderAvgQP=d}isNumber(s){return typeof s=="number"&&isFinite(s)}getActiveCandidatePair(){return this.transportStats?this.candidatePairs.find((s=>s.id===this.transportStats.selectedCandidatePairId),null):this.candidatePairs.find((s=>s.selected),null)}}const jh=(Kh={parseRtpParameters:()=>qh.parseRtpParameters,splitSections:()=>qh.splitSections},Oa={},un.d(Oa,Kh),Oa);var Kh,Oa;class Kp{static isVideoTransciever(s){return this.canTransceiverReceiveVideo(s)||this.canTransceiverSendVideo(s)}static canTransceiverReceiveVideo(s){return!!s&&(s.direction==="sendrecv"||s.direction==="recvonly")&&s.receiver&&s.receiver.track&&s.receiver.track.kind==="video"}static canTransceiverSendVideo(s){return!!s&&(s.direction==="sendrecv"||s.direction==="sendonly")&&s.sender&&s.sender.track&&s.sender.track.kind==="video"}static isAudioTransciever(s){return this.canTransceiverReceiveAudio(s)||this.canTransceiverSendAudio(s)}static canTransceiverReceiveAudio(s){return!!s&&(s.direction==="sendrecv"||s.direction==="recvonly")&&s.receiver&&s.receiver.track&&s.receiver.track.kind==="audio"}static canTransceiverSendAudio(s){return!!s&&(s.direction==="sendrecv"||s.direction==="sendonly")&&s.sender&&s.sender.track&&s.sender.track.kind==="audio"}}var zs,we,za=function(S,s,n,d){return new(n||(n=Promise))((function(g,E){function A(K){try{T(d.next(K))}catch(G){E(G)}}function O(K){try{T(d.throw(K))}catch(G){E(G)}}function T(K){var G;K.done?g(K.value):(G=K.value,G instanceof n?G:new n((function(ae){ae(G)}))).then(A,O)}T((d=d.apply(S,[])).next())}))};class Nf{constructor(s,n,d){this.config=n,this.createPeerConnection(s,d)}createPeerConnection(s,n){this.config.isFlagEnabled(j.ForceTURN)&&(s.iceTransportPolicy="relay",b.Log(b.GetStackTrace(),"Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(s),this.peerConnection.onsignalingstatechange=d=>this.handleSignalStateChange(d),this.peerConnection.oniceconnectionstatechange=d=>this.handleIceConnectionStateChange(d),this.peerConnection.onicegatheringstatechange=d=>this.handleIceGatheringStateChange(d),this.peerConnection.ontrack=d=>this.handleOnTrack(d),this.peerConnection.onicecandidate=d=>this.handleIceCandidate(d),this.peerConnection.ondatachannel=d=>this.handleDataChannel(d),this.aggregatedStats=new jp,this.preferredCodec=n,this.updateCodecSelection=!0}createOffer(s,n){return za(this,void 0,void 0,(function*(){b.Log(b.GetStackTrace(),"Create Offer",6);const d=location.hostname==="localhost"||location.hostname==="127.0.0.1",g=location.protocol==="https:";let E=n.isFlagEnabled(j.UseMic);!E||d||g||(E=!1,b.Error(b.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),b.Error(b.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(E).finally((()=>{var A;(A=this.peerConnection)===null||A===void 0||A.createOffer(s).then((O=>{var T;this.showTextOverlayConnecting(),O.sdp=this.mungeSDP(O.sdp,E),(T=this.peerConnection)===null||T===void 0||T.setLocalDescription(O),this.onSendWebRTCOffer(O)})).catch((()=>{this.showTextOverlaySetupFailure()}))}))}))}receiveOffer(s,n){var d;return za(this,void 0,void 0,(function*(){b.Log(b.GetStackTrace(),"Receive Offer",6),(d=this.peerConnection)===null||d===void 0||d.setRemoteDescription(s).then((()=>{const g=location.hostname==="localhost"||location.hostname==="127.0.0.1",E=location.protocol==="https:";let A=n.isFlagEnabled(j.UseMic);!A||g||E||(A=!1,b.Error(b.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),b.Error(b.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(rt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(s)),this.setupTransceiversAsync(A).finally((()=>{var O;(O=this.peerConnection)===null||O===void 0||O.createAnswer().then((T=>{var K;return T.sdp=this.mungeSDP(T.sdp,A),(K=this.peerConnection)===null||K===void 0?void 0:K.setLocalDescription(T)})).then((()=>{var T;this.onSendWebRTCAnswer((T=this.peerConnection)===null||T===void 0?void 0:T.currentLocalDescription)})).catch((()=>{b.Error(b.GetStackTrace(),"createAnswer() failed")}))}))}))}))}receiveAnswer(s){var n;(n=this.peerConnection)===null||n===void 0||n.setRemoteDescription(s),this.config.setOptionSettingOptions(rt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(s))}generateStats(){var s;(s=this.peerConnection)===null||s===void 0||s.getStats(null).then((n=>{this.aggregatedStats.processStats(n),this.onVideoStats(this.aggregatedStats),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId&&this.config.setOptionSettingValue(rt.PreferredCodec,this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId))}))}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(s,n){let d=s.replace(/(a=fmtp:\d+ .*level-asymmetry-allowed=.*)\r\n/gm,`$1;x-google-start-bitrate=10000;x-google-max-bitrate=100000\r
|
|
2880
|
+
`),g="maxaveragebitrate=510000;";return n&&(g+="sprop-maxcapturerate=48000;"),g+=this.config.isFlagEnabled(j.ForceMonoAudio)?"stereo=0;":"stereo=1;",g+="useinbandfec=1",d=d.replace("useinbandfec=1",g),d}handleOnIce(s){var n;b.Log(b.GetStackTrace(),"peerconnection handleOnIce",6),this.config.isFlagEnabled(j.ForceTURN)&&s.candidate.indexOf("relay")<0?b.Info(b.GetStackTrace(),`Dropping candidate because it was not TURN relay. | Type= ${s.type} | Protocol= ${s.protocol} | Address=${s.address} | Port=${s.port} |`,6):(n=this.peerConnection)===null||n===void 0||n.addIceCandidate(s)}handleSignalStateChange(s){b.Log(b.GetStackTrace(),"signaling state change: "+s,6)}handleIceConnectionStateChange(s){b.Log(b.GetStackTrace(),"ice connection state change: "+s,6),this.onIceConnectionStateChange(s)}handleIceGatheringStateChange(s){b.Log(b.GetStackTrace(),"ice gathering state change: "+JSON.stringify(s),6)}handleOnTrack(s){this.onTrack(s)}handleIceCandidate(s){this.onPeerIceCandidate(s)}handleDataChannel(s){this.onDataChannel(s)}onTrack(s){}onIceConnectionStateChange(s){}onPeerIceCandidate(s){}onDataChannel(s){}fuzzyIntersectUEAndBrowserCodecs(s){const n=new Array,d=this.parseAvailableCodecs(s),g=this.config.getSettingOption(rt.PreferredCodec).options;for(const E of d)if(g.includes(E))n.push(E);else{const A=E.split(" ")[0];for(const O of g)if(O.includes(A)){n.push(O);break}}return n}setupTransceiversAsync(s){var n,d,g,E,A,O,T,K,G,ae,J,ie;return za(this,void 0,void 0,(function*(){let re=!1;for(const fe of(d=(n=this.peerConnection)===null||n===void 0?void 0:n.getTransceivers())!==null&&d!==void 0?d:[])if(fe&&fe.receiver&&fe.receiver.track&&fe.receiver.track.kind==="video"){re=!0;break}if(re||(g=this.peerConnection)===null||g===void 0||g.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&this.preferredCodec!=""){for(const fe of(A=(E=this.peerConnection)===null||E===void 0?void 0:E.getTransceivers())!==null&&A!==void 0?A:[])if(fe&&fe.receiver&&fe.receiver.track&&fe.receiver.track.kind==="video"&&fe.setCodecPreferences){const Re=this.preferredCodec.split(" "),Pe={mimeType:"video/"+Re[0],clockRate:9e4,sdpFmtpLine:Re[1]?Re[1]:""},ce=[Pe];RTCRtpReceiver.getCapabilities("video").codecs.forEach((le=>{(le.mimeType!=Pe.mimeType||le?.sdpFmtpLine!=Pe?.sdpFmtpLine)&&ce.push(le)}));for(const le of ce)le?.sdpFmtpLine!==void 0&&le.sdpFmtpLine!==""||delete le.sdpFmtpLine;fe.setCodecPreferences(ce)}}let ne=!1;for(const fe of(T=(O=this.peerConnection)===null||O===void 0?void 0:O.getTransceivers())!==null&&T!==void 0?T:[])if(fe&&fe.receiver&&fe.receiver.track&&fe.receiver.track.kind==="audio"){ne=!0;break}if(s){const fe={video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}},Re=yield navigator.mediaDevices.getUserMedia(fe);if(Re)if(ne){for(const Pe of(ae=(G=this.peerConnection)===null||G===void 0?void 0:G.getTransceivers())!==null&&ae!==void 0?ae:[])if(Kp.canTransceiverReceiveAudio(Pe))for(const ce of Re.getTracks())ce.kind&&ce.kind=="audio"&&(Pe.sender.replaceTrack(ce),Pe.direction="sendrecv")}else for(const Pe of Re.getTracks())Pe.kind&&Pe.kind=="audio"&&((J=this.peerConnection)===null||J===void 0||J.addTransceiver(Pe,{direction:"sendrecv"}));else ne||(ie=this.peerConnection)===null||ie===void 0||ie.addTransceiver("audio",{direction:"recvonly"})}else ne||(K=this.peerConnection)===null||K===void 0||K.addTransceiver("audio",{direction:"recvonly"})}))}onVideoStats(s){}onSendWebRTCOffer(s){}onSendWebRTCAnswer(s){}showTextOverlayConnecting(){}showTextOverlaySetupFailure(){}parseAvailableCodecs(s){if(!RTCRtpReceiver.getCapabilities)return["Only available on Chrome"];const n=[],d=(0,jh.splitSections)(s.sdp);return d.shift(),d.forEach((g=>{const{codecs:E}=(0,jh.parseRtpParameters)(g),A=/(VP\d|H26\d|AV1).*/;E.forEach((O=>{const T=O.name+" "+Object.keys(O.parameters||{}).map((K=>K+"="+O.parameters[K])).join(";");if(A.exec(T)!==null){O.name=="VP9"&&(O.parameters={"profile-id":"0"});const K=O.name+" "+Object.keys(O.parameters||{}).map((G=>G+"="+O.parameters[G])).join(";");n.push(K)}}))})),n}}class Qp{constructor(){this.PixelStreamingSettings=new Vf,this.EncoderSettings=new Xp,this.WebRTCSettings=new Zp}ueCompatible(){this.WebRTCSettings.MaxFPS!=null&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class Vf{}class Xp{}class Zp{}class Jp{constructor(){this.ReceiptTimeMs=null,this.TransmissionTimeMs=null,this.PreCaptureTimeMs=null,this.PostCaptureTimeMs=null,this.PreEncodeTimeMs=null,this.PostEncodeTimeMs=null,this.EncodeMs=null,this.CaptureToSendMs=null,this.testStartTimeMs=0,this.browserReceiptTimeMs=0,this.latencyExcludingDecode=0,this.testDuration=0,this.networkLatency=0,this.browserSendLatency=0,this.frameDisplayDeltaTimeMs=0,this.endToEndLatency=0,this.encodeLatency=0}setFrameDisplayDeltaTime(s){this.frameDisplayDeltaTimeMs==0&&(this.frameDisplayDeltaTimeMs=Math.round(s))}processFields(){this.EncodeMs!=null||this.PreEncodeTimeMs==null&&this.PostEncodeTimeMs==null||(b.Log(b.GetStackTrace(),`Setting Encode Ms
|
|
2881
|
+
${this.PostEncodeTimeMs}
|
|
2882
|
+
${this.PreEncodeTimeMs}`,6),this.EncodeMs=this.PostEncodeTimeMs-this.PreEncodeTimeMs),this.CaptureToSendMs!=null||this.PreCaptureTimeMs==null&&this.PostCaptureTimeMs==null||(b.Log(b.GetStackTrace(),`Setting CaptureToSendMs Ms
|
|
2883
|
+
${this.PostCaptureTimeMs}
|
|
2884
|
+
${this.PreCaptureTimeMs}`,6),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class Da{static setExtensionFromBytes(s,n){n.receiving||(n.mimetype="",n.extension="",n.receiving=!0,n.valid=!1,n.chunks=0,n.data=[],n.timestampStart=new Date().getTime(),b.Log(b.GetStackTrace(),"Received first chunk of file",6));const d=new TextDecoder("utf-16").decode(s.slice(1));b.Log(b.GetStackTrace(),d,6),n.extension=d}static setMimeTypeFromBytes(s,n){n.receiving||(n.mimetype="",n.extension="",n.receiving=!0,n.valid=!1,n.chunks=0,n.data=[],n.timestampStart=new Date().getTime(),b.Log(b.GetStackTrace(),"Received first chunk of file",6));const d=new TextDecoder("utf-16").decode(s.slice(1));b.Log(b.GetStackTrace(),d,6),n.mimetype=d}static setContentsFromBytes(s,n){if(!n.receiving)return;n.chunks=Math.ceil(new DataView(s.slice(1,5).buffer).getInt32(0,!0)/16379);const d=s.slice(5);if(n.data.push(d),b.Log(b.GetStackTrace(),`Received file chunk: ${n.data.length}/${n.chunks}`,6),n.data.length===n.chunks){n.receiving=!1,n.valid=!0,b.Log(b.GetStackTrace(),"Received complete file",6);const g=new Date().getTime()-n.timestampStart,E=Math.round(16384*n.chunks/g);b.Log(b.GetStackTrace(),`Average transfer bitrate: ${E}kb/s over ${g/1e3} seconds`,6);const A=new Blob(n.data,{type:n.mimetype}),O=document.createElement("a");O.setAttribute("href",URL.createObjectURL(A)),O.setAttribute("download",`transfer.${n.extension}`),document.body.append(O),O.remove()}else n.data.length>n.chunks&&(n.receiving=!1,b.Error(b.GetStackTrace(),`Received bigger file than advertised: ${n.data.length}/${n.chunks}`))}}class Gf{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}}class Tt{}Tt.mainButton=0,Tt.auxiliaryButton=1,Tt.secondaryButton=2,Tt.fourthButton=3,Tt.fifthButton=4;class Pt{}Pt.primaryButton=1,Pt.secondaryButton=2,Pt.auxiliaryButton=4,Pt.fourthButton=8,Pt.fifthButton=16;class Ls{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(s){this.unregisterCallbacks.push(s)}unregisterAll(){for(const s of this.unregisterCallbacks)s();this.unregisterCallbacks=[]}}class Wf{constructor(s,n,d){this.touchEventListenerTracker=new Ls,this.toStreamerMessagesProvider=s,this.videoElementProvider=n,this.coordinateConverter=d;const g=O=>this.onTouchStart(O),E=O=>this.onTouchEnd(O),A=O=>this.onTouchMove(O);document.addEventListener("touchstart",g,{passive:!1}),document.addEventListener("touchend",E,{passive:!1}),document.addEventListener("touchmove",A,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",g))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchend",E))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",A)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}setVideoElementParentClientRect(s){this.videoElementParentClientRect=s}onTouchStart(s){if(this.videoElementProvider.isVideoReady()&&s.target===this.videoElementProvider.getVideoElement()){if(this.fakeTouchFinger==null){const n=s.changedTouches[0];this.fakeTouchFinger=new qf(n.identifier,n.clientX-this.videoElementParentClientRect.left,n.clientY-this.videoElementParentClientRect.top);const d=this.videoElementProvider.getVideoParentElement(),g=new MouseEvent("mouseenter",n);d.dispatchEvent(g);const E=this.coordinateConverter.normalizeAndQuantizeUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([Tt.mainButton,E.x,E.y])}s.preventDefault()}}onTouchEnd(s){if(!this.videoElementProvider.isVideoReady()||this.fakeTouchFinger==null)return;const n=this.videoElementProvider.getVideoParentElement(),d=this.toStreamerMessagesProvider.toStreamerHandlers;for(let g=0;g<s.changedTouches.length;g++){const E=s.changedTouches[g];if(E.identifier===this.fakeTouchFinger.id){const A=E.clientX-this.videoElementParentClientRect.left,O=E.clientY-this.videoElementParentClientRect.top,T=this.coordinateConverter.normalizeAndQuantizeUnsigned(A,O);d.get("MouseUp")([Tt.mainButton,T.x,T.y]);const K=new MouseEvent("mouseleave",E);n.dispatchEvent(K),this.fakeTouchFinger=null;break}}s.preventDefault()}onTouchMove(s){if(!this.videoElementProvider.isVideoReady()||this.fakeTouchFinger==null)return;const n=this.toStreamerMessagesProvider.toStreamerHandlers;for(let d=0;d<s.touches.length;d++){const g=s.touches[d];if(g.identifier===this.fakeTouchFinger.id){const E=g.clientX-this.videoElementParentClientRect.left,A=g.clientY-this.videoElementParentClientRect.top,O=this.coordinateConverter.normalizeAndQuantizeUnsigned(E,A),T=this.coordinateConverter.normalizeAndQuantizeSigned(E-this.fakeTouchFinger.x,A-this.fakeTouchFinger.y);n.get("MouseMove")([O.x,O.y,T.x,T.y]),this.fakeTouchFinger.x=E,this.fakeTouchFinger.y=A;break}}s.preventDefault()}}class qf{constructor(s,n,d){this.id=s,this.x=n,this.y=d}}class Ot{}Ot.backSpace=8,Ot.shift=16,Ot.control=17,Ot.alt=18,Ot.rightShift=253,Ot.rightControl=254,Ot.rightAlt=255;class Hf{constructor(s,n,d){this.keyboardEventListenerTracker=new Ls,this.CodeToKeyCode={Escape:27,Digit0:48,Digit1:49,Digit2:50,Digit3:51,Digit4:52,Digit5:53,Digit6:54,Digit7:55,Digit8:56,Digit9:57,Minus:173,Equal:187,Backspace:8,Tab:9,KeyQ:81,KeyW:87,KeyE:69,KeyR:82,KeyT:84,KeyY:89,KeyU:85,KeyI:73,KeyO:79,KeyP:80,BracketLeft:219,BracketRight:221,Enter:13,ControlLeft:17,KeyA:65,KeyS:83,KeyD:68,KeyF:70,KeyG:71,KeyH:72,KeyJ:74,KeyK:75,KeyL:76,Semicolon:186,Quote:222,Backquote:192,ShiftLeft:16,Backslash:220,KeyZ:90,KeyX:88,KeyC:67,KeyV:86,KeyB:66,KeyN:78,KeyM:77,Comma:188,Period:190,Slash:191,ShiftRight:253,AltLeft:18,Space:32,CapsLock:20,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,Pause:19,ScrollLock:145,NumpadDivide:111,NumpadMultiply:106,NumpadSubtract:109,NumpadAdd:107,NumpadDecimal:110,Numpad9:105,Numpad8:104,Numpad7:103,Numpad6:102,Numpad5:101,Numpad4:100,Numpad3:99,Numpad2:98,Numpad1:97,Numpad0:96,NumLock:144,ControlRight:254,AltRight:255,Home:36,End:35,ArrowUp:38,ArrowLeft:37,ArrowRight:39,ArrowDown:40,PageUp:33,PageDown:34,Insert:45,Delete:46,ContextMenu:93},this.toStreamerMessagesProvider=s,this.config=n,this.activeKeysProvider=d}registerKeyBoardEvents(){const s=E=>this.handleOnCompositionEnd(E),n=E=>this.handleOnKeyDown(E),d=E=>this.handleOnKeyUp(E),g=E=>this.handleOnKeyPress(E);document.addEventListener("compositionend",s),document.addEventListener("keydown",n),document.addEventListener("keyup",d),document.addEventListener("keypress",g),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("compositionend",s))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keydown",n))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keyup",d))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keypress",g)))}unregisterKeyBoardEvents(){this.keyboardEventListenerTracker.unregisterAll()}handleOnKeyDown(s){const n=this.getKeycode(s);n&&n!==229&&(b.Log(b.GetStackTrace(),`key down ${n}, repeat = ${s.repeat}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyDown")([this.getKeycode(s),s.repeat?1:0]),this.activeKeysProvider.getActiveKeys().push(n),n===Ot.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:Ot.backSpace})),this.config.isFlagEnabled(j.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&s.preventDefault())}handleOnKeyUp(s){const n=this.getKeycode(s);n&&(b.Log(b.GetStackTrace(),`key up ${n}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyUp")([n]),this.config.isFlagEnabled(j.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&s.preventDefault())}handleOnKeyPress(s){if(!("charCode"in s))return void b.Warning(b.GetStackTrace(),"KeyboardEvent.charCode is deprecated in this browser, cannot send key press.");const n=s.charCode;b.Log(b.GetStackTrace(),`key press ${n}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyPress")([n])}handleOnCompositionEnd(s){s.data&&s.data.length&&s.data.split("").forEach((n=>{this.handleOnKeyDown(new KeyboardEvent("keydown",{keyCode:n.toUpperCase().charCodeAt(0),charCode:n.charCodeAt(0)})),this.handleOnKeyPress(new KeyboardEvent("keypress",{keyCode:n.toUpperCase().charCodeAt(0),charCode:n.charCodeAt(0)})),this.handleOnKeyUp(new KeyboardEvent("keyup",{keyCode:n.toUpperCase().charCodeAt(0),charCode:n.charCodeAt(0)}))}))}getKeycode(s){if(!("keyCode"in s)){const n=s;return n.code in this.CodeToKeyCode?this.CodeToKeyCode[n.code]:(b.Warning(b.GetStackTrace(),`Keyboard code of ${n.code} is not supported in our mapping, ignoring this key.`),null)}return s.keyCode===Ot.shift&&s.code==="ShiftRight"?Ot.rightShift:s.keyCode===Ot.control&&s.code==="ControlRight"?Ot.rightControl:s.keyCode===Ot.alt&&s.code==="AltRight"?Ot.rightAlt:s.keyCode}isKeyCodeBrowserKey(s){return s>=112&&s<=123||s===9}}class jf{constructor(s,n,d){this.x=0,this.y=0,this.updateMouseMovePositionEvent=E=>{this.updateMouseMovePosition(E)},this.mouseEventListenerTracker=new Ls,this.videoElementProvider=s,this.mouseController=n,this.activeKeysProvider=d;const g=this.videoElementProvider.getVideoParentElement();this.x=g.getBoundingClientRect().width/2,this.y=g.getBoundingClientRect().height/2,this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y)}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}lockStateChange(){const s=this.videoElementProvider.getVideoParentElement(),n=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers;if(document.pointerLockElement===s||document.mozPointerLockElement===s)b.Log(b.GetStackTrace(),"Pointer locked",6),document.addEventListener("mousemove",this.updateMouseMovePositionEvent,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1)));else{b.Log(b.GetStackTrace(),"The pointer lock status is now unlocked",6),document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1);let d=this.activeKeysProvider.getActiveKeys();const g=new Set(d),E=[];g.forEach((A=>{})),E.forEach((A=>{n.get("KeyUp")([A])})),d=[]}}updateMouseMovePosition(s){if(!this.videoElementProvider.isVideoReady())return;const n=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers,d=this.videoElementProvider.getVideoParentElement().clientWidth,g=this.videoElementProvider.getVideoParentElement().clientHeight;this.x+=s.movementX,this.y+=s.movementY,this.x>d&&(this.x-=d),this.y>g&&(this.y-=g),this.x<0&&(this.x=d+this.x),this.y<0&&(this.y=g-this.y),this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y);const E=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(s.movementX,s.movementY);n.get("MouseMove")([this.coord.x,this.coord.y,E.x,E.y])}handleMouseDown(s){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([s.button,this.coord.x,this.coord.y])}handleMouseUp(s){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([s.button,this.coord.x,this.coord.y])}handleMouseWheel(s){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([s.wheelDelta,this.coord.x,this.coord.y])}handleMouseDouble(s){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([s.button,this.coord.x,this.coord.y])}handlePressMouseButtons(s){this.videoElementProvider.isVideoReady()&&this.mouseController.pressMouseButtons(s.buttons,this.x,this.y)}handleReleaseMouseButtons(s){this.videoElementProvider.isVideoReady()&&this.mouseController.releaseMouseButtons(s.buttons,this.x,this.y)}}class Kf{constructor(s){this.mouseController=s}unregisterMouseEvents(){}updateMouseMovePosition(s){if(!this.mouseController.videoElementProvider.isVideoReady())return;b.Log(b.GetStackTrace(),"MouseMove",6);const n=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(s.offsetX,s.offsetY),d=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(s.movementX,s.movementY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseMove")([n.x,n.y,d.x,d.y]),s.preventDefault()}handleMouseDown(s){if(!this.mouseController.videoElementProvider.isVideoReady())return;b.Log(b.GetStackTrace(),"onMouse Down",6);const n=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(s.offsetX,s.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([s.button,n.x,n.y]),s.preventDefault()}handleMouseUp(s){if(!this.mouseController.videoElementProvider.isVideoReady())return;b.Log(b.GetStackTrace(),"onMouse Up",6);const n=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(s.offsetX,s.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([s.button,n.x,n.y]),s.preventDefault()}handleContextMenu(s){this.mouseController.videoElementProvider.isVideoReady()&&s.preventDefault()}handleMouseWheel(s){if(!this.mouseController.videoElementProvider.isVideoReady())return;const n=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(s.offsetX,s.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([s.wheelDelta,n.x,n.y]),s.preventDefault()}handleMouseDouble(s){if(!this.mouseController.videoElementProvider.isVideoReady())return;const n=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(s.offsetX,s.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([s.button,n.x,n.y])}handlePressMouseButtons(s){this.mouseController.videoElementProvider.isVideoReady()&&(b.Log(b.GetStackTrace(),"onMouse press",6),this.mouseController.pressMouseButtons(s.buttons,s.offsetX,s.offsetY))}handleReleaseMouseButtons(s){this.mouseController.videoElementProvider.isVideoReady()&&(b.Log(b.GetStackTrace(),"onMouse release",6),this.mouseController.releaseMouseButtons(s.buttons,s.offsetX,s.offsetY))}}class Qf{constructor(s,n,d,g){this.mouseEventListenerTracker=new Ls,this.toStreamerMessagesProvider=s,this.coordinateConverter=d,this.videoElementProvider=n,this.activeKeysProvider=g,this.registerMouseEnterAndLeaveEvents()}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}registerLockedMouseEvents(s){const n=this.videoElementProvider.getVideoParentElement(),d=new jf(this.videoElementProvider,s,this.activeKeysProvider);if(n.requestPointerLock=n.requestPointerLock||n.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,n.requestPointerLock){const K=()=>{n.requestPointerLock()};n.addEventListener("click",K),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("click",K)))}const g=()=>d.lockStateChange();document.addEventListener("pointerlockchange",g,!1),document.addEventListener("mozpointerlockchange",g,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("pointerlockchange",g,!1))),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mozpointerlockchange",g,!1)));const E=K=>d.handleMouseDown(K),A=K=>d.handleMouseUp(K),O=K=>d.handleMouseWheel(K),T=K=>d.handleMouseDouble(K);n.addEventListener("mousedown",E),n.addEventListener("mouseup",A),n.addEventListener("wheel",O),n.addEventListener("dblclick",T),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousedown",E))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mouseup",A))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("wheel",O))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("dblclick",T))),this.mouseEventListenerTracker.addUnregisterCallback((()=>d.unregisterMouseEvents())),this.mouseEventListenerTracker.addUnregisterCallback((()=>{!document.exitPointerLock||document.pointerLockElement!==n&&document.mozPointerLockElement!==n||document.exitPointerLock()}))}registerHoveringMouseEvents(s){const n=this.videoElementProvider.getVideoParentElement(),d=new Kf(s),g=G=>d.updateMouseMovePosition(G),E=G=>d.handleMouseDown(G),A=G=>d.handleMouseUp(G),O=G=>d.handleContextMenu(G),T=G=>d.handleMouseWheel(G),K=G=>d.handleMouseDouble(G);n.addEventListener("mousemove",g),n.addEventListener("mousedown",E),n.addEventListener("mouseup",A),n.addEventListener("contextmenu",O),n.addEventListener("wheel",T),n.addEventListener("dblclick",K),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousemove",g))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousedown",E))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mouseup",A))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("contextmenu",O))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("wheel",T))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("dblclick",K))),this.mouseEventListenerTracker.addUnregisterCallback((()=>d.unregisterMouseEvents()))}registerMouseEnterAndLeaveEvents(){const s=this.videoElementProvider.getVideoParentElement(),n=g=>{this.videoElementProvider.isVideoReady()&&(b.Log(b.GetStackTrace(),"Mouse Entered",6),this.sendMouseEnter(),this.pressMouseButtons(g.buttons,g.x,g.y))},d=g=>{this.videoElementProvider.isVideoReady()&&(b.Log(b.GetStackTrace(),"Mouse Left",6),this.sendMouseLeave(),this.releaseMouseButtons(g.buttons,g.x,g.y))};s.addEventListener("mouseenter",n),s.addEventListener("mouseleave",d),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mouseenter",n))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mouseleave",d)))}releaseMouseButtons(s,n,d){const g=this.coordinateConverter.normalizeAndQuantizeUnsigned(n,d);s&Pt.primaryButton&&this.sendMouseUp(Tt.mainButton,g.x,g.y),s&Pt.secondaryButton&&this.sendMouseUp(Tt.secondaryButton,g.x,g.y),s&Pt.auxiliaryButton&&this.sendMouseUp(Tt.auxiliaryButton,g.x,g.y),s&Pt.fourthButton&&this.sendMouseUp(Tt.fourthButton,g.x,g.y),s&Pt.fifthButton&&this.sendMouseUp(Tt.fifthButton,g.x,g.y)}pressMouseButtons(s,n,d){if(!this.videoElementProvider.isVideoReady())return;const g=this.coordinateConverter.normalizeAndQuantizeUnsigned(n,d);s&Pt.primaryButton&&this.sendMouseDown(Tt.mainButton,g.x,g.y),s&Pt.secondaryButton&&this.sendMouseDown(Tt.secondaryButton,g.x,g.y),s&Pt.auxiliaryButton&&this.sendMouseDown(Tt.auxiliaryButton,g.x,g.y),s&Pt.fourthButton&&this.sendMouseDown(Tt.fourthButton,g.x,g.y),s&Pt.fifthButton&&this.sendMouseDown(Tt.fifthButton,g.x,g.y)}sendMouseEnter(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseEnter")()}sendMouseLeave(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseLeave")()}sendMouseDown(s,n,d){this.videoElementProvider.isVideoReady()&&(b.Log(b.GetStackTrace(),`mouse button ${s} down at (${n}, ${d})`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([s,n,d]))}sendMouseUp(s,n,d){if(!this.videoElementProvider.isVideoReady())return;b.Log(b.GetStackTrace(),`mouse button ${s} up at (${n}, ${d})`,6);const g=this.coordinateConverter.normalizeAndQuantizeUnsigned(n,d);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([s,g.x,g.y])}}class Xf{constructor(s,n,d){this.fingers=[9,8,7,6,5,4,3,2,1,0],this.fingerIds=new Map,this.maxByteValue=255,this.touchEventListenerTracker=new Ls,this.toStreamerMessagesProvider=s,this.videoElementProvider=n,this.coordinateConverter=d,this.videoElementParent=n.getVideoElement();const g=T=>this.onTouchStart(T),E=T=>this.onTouchEnd(T),A=T=>this.onTouchMove(T);this.videoElementParent.addEventListener("touchstart",g),this.videoElementParent.addEventListener("touchend",E),this.videoElementParent.addEventListener("touchmove",A),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",g))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchend",E))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchmove",A))),b.Log(b.GetStackTrace(),"Touch Events Registered",6);const O=T=>{T.preventDefault()};document.addEventListener("touchmove",O),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",O)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}rememberTouch(s){const n=this.fingers.pop();n===void 0&&b.Log(b.GetStackTrace(),"exhausted touch identifiers",6),this.fingerIds.set(s.identifier,n)}forgetTouch(s){this.fingers.push(this.fingerIds.get(s.identifier)),this.fingers.sort((function(n,d){return d-n})),this.fingerIds.delete(s.identifier)}onTouchStart(s){if(this.videoElementProvider.isVideoReady()){for(let n=0;n<s.changedTouches.length;n++)this.rememberTouch(s.changedTouches[n]);b.Log(b.GetStackTrace(),"touch start",6),this.emitTouchData("TouchStart",s.changedTouches),s.preventDefault()}}onTouchEnd(s){if(this.videoElementProvider.isVideoReady()){b.Log(b.GetStackTrace(),"touch end",6),this.emitTouchData("TouchEnd",s.changedTouches);for(let n=0;n<s.changedTouches.length;n++)this.forgetTouch(s.changedTouches[n]);s.preventDefault()}}onTouchMove(s){this.videoElementProvider.isVideoReady()&&(b.Log(b.GetStackTrace(),"touch move",6),this.emitTouchData("TouchMove",s.touches),s.preventDefault())}emitTouchData(s,n){if(!this.videoElementProvider.isVideoReady())return;const d=this.videoElementProvider.getVideoParentElement().getBoundingClientRect(),g=this.toStreamerMessagesProvider.toStreamerHandlers;for(let E=0;E<n.length;E++){const O=n[E],T=O.clientX-d.left,K=O.clientY-d.top;b.Log(b.GetStackTrace(),`F${this.fingerIds.get(O.identifier)}=(${T}, ${K})`,6);const G=this.coordinateConverter.normalizeAndQuantizeUnsigned(T,K);switch(s){case"TouchStart":g.get("TouchStart")([1,G.x,G.y,this.fingerIds.get(O.identifier),this.maxByteValue*(O.force>0?O.force:1),G.inRange?1:0]);break;case"TouchEnd":g.get("TouchEnd")([1,G.x,G.y,this.fingerIds.get(O.identifier),this.maxByteValue*O.force,G.inRange?1:0]);break;case"TouchMove":g.get("TouchMove")([1,G.x,G.y,this.fingerIds.get(O.identifier),this.maxByteValue*(O.force>0?O.force:1),G.inRange?1:0])}}}}class Zf{constructor(s){this.gamePadEventListenerTracker=new Ls,this.toStreamerMessagesProvider=s,this.requestAnimationFrame=(window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.requestAnimationFrame).bind(window);const n=window;if(window.addEventListener("beforeunload",(d=>this.onBeforeUnload(d))),"GamepadEvent"in n){const d=E=>this.gamePadConnectHandler(E),g=E=>this.gamePadDisconnectHandler(E);window.addEventListener("gamepadconnected",d),window.addEventListener("gamepaddisconnected",g),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepadconnected",d))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepaddisconnected",g)))}else if("WebKitGamepadEvent"in n){const d=E=>this.gamePadConnectHandler(E),g=E=>this.gamePadDisconnectHandler(E);window.addEventListener("webkitgamepadconnected",d),window.addEventListener("webkitgamepaddisconnected",g),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepadconnected",d))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepaddisconnected",g)))}if(this.controllers=[],navigator.getGamepads)for(const d of navigator.getGamepads())d&&this.gamePadConnectHandler(new GamepadEvent("gamepadconnected",{gamepad:d}))}unregisterGamePadEvents(){this.gamePadEventListenerTracker.unregisterAll();for(const s of this.controllers)s.id!==void 0&&this.onGamepadDisconnected(s.id);this.controllers=[],this.onGamepadConnected=()=>{},this.onGamepadDisconnected=()=>{}}gamePadConnectHandler(s){b.Log(b.GetStackTrace(),"Gamepad connect handler",6);const n=s.gamepad,d={currentState:n,prevState:n,id:void 0};this.controllers.push(d),this.controllers[n.index].currentState=n,this.controllers[n.index].prevState=n,b.Log(b.GetStackTrace(),"gamepad: "+n.id+" connected",6),window.requestAnimationFrame((()=>this.updateStatus())),this.onGamepadConnected()}gamePadDisconnectHandler(s){b.Log(b.GetStackTrace(),"Gamepad disconnect handler",6),b.Log(b.GetStackTrace(),"gamepad: "+s.gamepad.id+" disconnected",6);const n=this.controllers[s.gamepad.index];delete this.controllers[s.gamepad.index],this.controllers=this.controllers.filter((d=>d!==void 0)),this.onGamepadDisconnected(n.id)}scanGamePads(){const s=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[];for(let n=0;n<s.length;n++)s[n]&&s[n].index in this.controllers&&(this.controllers[s[n].index].currentState=s[n])}updateStatus(){this.scanGamePads();const s=this.toStreamerMessagesProvider.toStreamerHandlers;for(const n of this.controllers){const d=n.id===void 0?this.controllers.indexOf(n):n.id,g=n.currentState;for(let E=0;E<n.currentState.buttons.length;E++){const A=n.currentState.buttons[E],O=n.prevState.buttons[E];A.pressed?E==zs.LeftTrigger?s.get("GamepadAnalog")([d,5,A.value]):E==zs.RightTrigger?s.get("GamepadAnalog")([d,6,A.value]):s.get("GamepadButtonPressed")([d,E,O.pressed?1:0]):!A.pressed&&O.pressed&&(E==zs.LeftTrigger?s.get("GamepadAnalog")([d,5,0]):E==zs.RightTrigger?s.get("GamepadAnalog")([d,6,0]):s.get("GamepadButtonReleased")([d,E,0]))}for(let E=0;E<g.axes.length;E+=2){const A=parseFloat(g.axes[E].toFixed(4)),O=-parseFloat(g.axes[E+1].toFixed(4));s.get("GamepadAnalog")([d,E+1,A]),s.get("GamepadAnalog")([d,E+2,O])}this.controllers[d].prevState=g}this.controllers.length>0&&this.requestAnimationFrame((()=>this.updateStatus()))}onGamepadResponseReceived(s){for(const n of this.controllers)if(n.id===void 0){n.id=s;break}}onGamepadConnected(){}onGamepadDisconnected(s){}onBeforeUnload(s){for(const n of this.controllers)this.onGamepadDisconnected(n.id)}}(function(S){S[S.RightClusterBottomButton=0]="RightClusterBottomButton",S[S.RightClusterRightButton=1]="RightClusterRightButton",S[S.RightClusterLeftButton=2]="RightClusterLeftButton",S[S.RightClusterTopButton=3]="RightClusterTopButton",S[S.LeftShoulder=4]="LeftShoulder",S[S.RightShoulder=5]="RightShoulder",S[S.LeftTrigger=6]="LeftTrigger",S[S.RightTrigger=7]="RightTrigger",S[S.SelectOrBack=8]="SelectOrBack",S[S.StartOrForward=9]="StartOrForward",S[S.LeftAnalogPress=10]="LeftAnalogPress",S[S.RightAnalogPress=11]="RightAnalogPress",S[S.LeftClusterTopButton=12]="LeftClusterTopButton",S[S.LeftClusterBottomButton=13]="LeftClusterBottomButton",S[S.LeftClusterLeftButton=14]="LeftClusterLeftButton",S[S.LeftClusterRightButton=15]="LeftClusterRightButton",S[S.CentreButton=16]="CentreButton",S[S.LeftStickHorizontal=0]="LeftStickHorizontal",S[S.LeftStickVertical=1]="LeftStickVertical",S[S.RightStickHorizontal=2]="RightStickHorizontal",S[S.RightStickVertical=3]="RightStickVertical"})(zs||(zs={}));class Jf{constructor(s,n,d){this.activeKeys=new Yf,this.toStreamerMessagesProvider=s,this.videoElementProvider=n,this.coordinateConverter=d}registerKeyBoard(s){b.Log(b.GetStackTrace(),"Register Keyboard Events",7);const n=new Hf(this.toStreamerMessagesProvider,s,this.activeKeys);return n.registerKeyBoardEvents(),n}registerMouse(s){b.Log(b.GetStackTrace(),"Register Mouse Events",7);const n=new Qf(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys);switch(s){case fs.LockedMouse:n.registerLockedMouseEvents(n);break;case fs.HoveringMouse:n.registerHoveringMouseEvents(n);break;default:b.Info(b.GetStackTrace(),"unknown Control Scheme Type Defaulting to Locked Mouse Events"),n.registerLockedMouseEvents(n)}return n}registerTouch(s,n){if(b.Log(b.GetStackTrace(),"Registering Touch",6),s){const d=new Wf(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return d.setVideoElementParentClientRect(n),d}return new Xf(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return b.Log(b.GetStackTrace(),"Register Game Pad",7),new Zf(this.toStreamerMessagesProvider)}}class Yf{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class eg{constructor(s,n){this.lastTimeResized=new Date().getTime(),this.videoElement=document.createElement("video"),this.config=n,this.videoElement.id="streamingVideo",this.videoElement.disablePictureInPicture=!0,this.videoElement.playsInline=!0,this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.pointerEvents="all",s.appendChild(this.videoElement),this.onResizePlayerCallback=()=>{console.log("Resolution changed, restyling player, did you forget to override this function?")},this.onMatchViewportResolutionCallback=()=>{console.log("Resolution changed and match viewport resolution is turned on, did you forget to override this function?")},this.videoElement.onclick=()=>{this.audioElement!=null&&this.audioElement.paused&&this.audioElement.play(),this.videoElement.paused&&this.videoElement.play()},this.videoElement.onloadedmetadata=()=>{this.onVideoInitialized()},window.addEventListener("resize",(()=>this.resizePlayerStyle()),!0),window.addEventListener("orientationchange",(()=>this.onOrientationChange()))}setAudioElement(s){this.audioElement=s}play(){return this.videoElement.muted=this.config.isFlagEnabled(j.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(j.AutoPlayVideo),this.videoElement.play()}isPaused(){return this.videoElement.paused}isVideoReady(){return this.videoElement.readyState!==void 0&&this.videoElement.readyState>0}hasVideoSource(){return this.videoElement.srcObject!==void 0&&this.videoElement.srcObject!==null}getVideoElement(){return this.videoElement}getVideoParentElement(){return this.videoElement.parentElement}setVideoEnabled(s){this.videoElement.srcObject.getTracks().forEach((n=>n.enabled=s))}onVideoInitialized(){}onOrientationChange(){clearTimeout(this.orientationChangeTimeout),this.orientationChangeTimeout=window.setTimeout((()=>{this.resizePlayerStyle()}),500)}resizePlayerStyle(){const s=this.getVideoParentElement();s&&(this.updateVideoStreamSize(),s.classList.contains("fixed-size")||this.resizePlayerStyleToFillParentElement(),this.onResizePlayerCallback())}resizePlayerStyleToFillParentElement(){this.getVideoParentElement().setAttribute("style","top: 0px; left: 0px; width: 100%; height: 100%; cursor: default;")}updateVideoStreamSize(){if(this.config.isFlagEnabled(j.MatchViewportResolution))if(new Date().getTime()-this.lastTimeResized>300){const s=this.getVideoParentElement();if(!s)return;this.onMatchViewportResolutionCallback(s.clientWidth,s.clientHeight),this.lastTimeResized=new Date().getTime()}else b.Log(b.GetStackTrace(),"Resizing too often - skipping",6),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout((()=>this.updateVideoStreamSize()),100)}}class tg{constructor(){this.toStreamerHandlers=new Map,this.fromStreamerHandlers=new Map,this.toStreamerMessages=new Map,this.fromStreamerMessages=new Map}populateDefaultProtocol(){this.toStreamerMessages.set("IFrameRequest",{id:0,structure:[]}),this.toStreamerMessages.set("RequestQualityControl",{id:1,structure:[]}),this.toStreamerMessages.set("FpsRequest",{id:2,structure:[]}),this.toStreamerMessages.set("AverageBitrateRequest",{id:3,structure:[]}),this.toStreamerMessages.set("StartStreaming",{id:4,structure:[]}),this.toStreamerMessages.set("StopStreaming",{id:5,structure:[]}),this.toStreamerMessages.set("LatencyTest",{id:6,structure:["string"]}),this.toStreamerMessages.set("RequestInitialSettings",{id:7,structure:[]}),this.toStreamerMessages.set("TestEcho",{id:8,structure:[]}),this.toStreamerMessages.set("DataChannelLatencyTest",{id:9,structure:[]}),this.toStreamerMessages.set("UIInteraction",{id:50,structure:["string"]}),this.toStreamerMessages.set("Command",{id:51,structure:["string"]}),this.toStreamerMessages.set("KeyDown",{id:60,structure:["uint8","uint8"]}),this.toStreamerMessages.set("KeyUp",{id:61,structure:["uint8"]}),this.toStreamerMessages.set("KeyPress",{id:62,structure:["uint16"]}),this.toStreamerMessages.set("MouseEnter",{id:70,structure:[]}),this.toStreamerMessages.set("MouseLeave",{id:71,structure:[]}),this.toStreamerMessages.set("MouseDown",{id:72,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseUp",{id:73,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseMove",{id:74,structure:["uint16","uint16","int16","int16"]}),this.toStreamerMessages.set("MouseWheel",{id:75,structure:["int16","uint16","uint16"]}),this.toStreamerMessages.set("MouseDouble",{id:76,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("TouchStart",{id:80,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchEnd",{id:81,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchMove",{id:82,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadConnected",{id:93,structure:[]}),this.toStreamerMessages.set("GamepadButtonPressed",{id:90,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadButtonReleased",{id:91,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadAnalog",{id:92,structure:["uint8","uint8","double"]}),this.toStreamerMessages.set("GamepadDisconnected",{id:94,structure:["uint8"]}),this.fromStreamerMessages.set(0,"QualityControlOwnership"),this.fromStreamerMessages.set(1,"Response"),this.fromStreamerMessages.set(2,"Command"),this.fromStreamerMessages.set(3,"FreezeFrame"),this.fromStreamerMessages.set(4,"UnfreezeFrame"),this.fromStreamerMessages.set(5,"VideoEncoderAvgQP"),this.fromStreamerMessages.set(6,"LatencyTest"),this.fromStreamerMessages.set(7,"InitialSettings"),this.fromStreamerMessages.set(8,"FileExtension"),this.fromStreamerMessages.set(9,"FileMimeType"),this.fromStreamerMessages.set(10,"FileContents"),this.fromStreamerMessages.set(11,"TestEcho"),this.fromStreamerMessages.set(12,"InputControlOwnership"),this.fromStreamerMessages.set(13,"GamepadResponse"),this.fromStreamerMessages.set(14,"DataChannelLatencyTest"),this.fromStreamerMessages.set(255,"Protocol")}registerMessageHandler(s,n,d){switch(s){case we.ToStreamer:this.toStreamerHandlers.set(n,d);break;case we.FromStreamer:this.fromStreamerHandlers.set(n,d);break;default:b.Log(b.GetStackTrace(),`Unknown message direction ${s}`)}}}(function(S){S[S.ToStreamer=0]="ToStreamer",S[S.FromStreamer=1]="FromStreamer"})(we||(we={}));class rg{constructor(){this.responseEventListeners=new Map}addResponseEventListener(s,n){this.responseEventListeners.set(s,n)}removeResponseEventListener(s){this.responseEventListeners.delete(s)}onResponse(s){b.Log(b.GetStackTrace(),"DataChannelReceiveMessageType.Response",6);const n=new TextDecoder("utf-16").decode(s.slice(1));b.Log(b.GetStackTrace(),n,6),this.responseEventListeners.forEach((d=>{d(n)}))}}class sg{constructor(s,n){this.dataChannelSender=s,this.toStreamerMessagesMapProvider=n}sendMessageToStreamer(s,n){n===void 0&&(n=[]);const d=this.toStreamerMessagesMapProvider.toStreamerMessages.get(s);if(d===void 0)return void b.Error(b.GetStackTrace(),`Attempted to send a message to the streamer with message type: ${s}, but the frontend hasn't been configured to send such a message. Check you've added the message type in your cpp`);if(d.structure&&n&&d.structure.length!==n.length)return void b.Error(b.GetStackTrace(),`Provided message data doesn't match expected layout. Expected [ ${d.structure.map((T=>{switch(T){case"uint8":case"uint16":case"int16":case"float":case"double":return"number";case"string":return"string"}})).toString()} ] but received [ ${n.map((T=>typeof T)).toString()} ]`);let g=0;const E=new TextEncoder;n.forEach(((T,K)=>{switch(d.structure[K]){case"uint8":g+=1;break;case"uint16":case"int16":g+=2;break;case"float":g+=4;break;case"double":g+=8;break;case"string":g+=2,g+=2*E.encode(T).length}}));const A=new DataView(new ArrayBuffer(g+1));A.setUint8(0,d.id);let O=1;n.forEach(((T,K)=>{switch(d.structure[K]){case"uint8":A.setUint8(O,T),O+=1;break;case"uint16":A.setUint16(O,T,!0),O+=2;break;case"int16":A.setInt16(O,T,!0),O+=2;break;case"float":A.setFloat32(O,T,!0),O+=4;break;case"double":A.setFloat64(O,T,!0),O+=8;break;case"string":A.setUint16(O,T.length,!0),O+=2;for(let G=0;G<T.length;G++)A.setUint16(O,T.charCodeAt(G),!0),O+=2}})),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(A.buffer):b.Info(b.GetStackTrace(),`Data channel cannot send yet, skipping sending message: ${s} - ${new Uint8Array(A.buffer)}`)}}class ig{constructor(s){this.sendMessageController=s}SendRequestQualityControl(){this.sendMessageController.sendMessageToStreamer("RequestQualityControl")}SendMaxFpsRequest(){this.sendMessageController.sendMessageToStreamer("FpsRequest")}SendAverageBitrateRequest(){this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest")}SendStartStreaming(){this.sendMessageController.sendMessageToStreamer("StartStreaming")}SendStopStreaming(){this.sendMessageController.sendMessageToStreamer("StopStreaming")}SendRequestInitialSettings(){this.sendMessageController.sendMessageToStreamer("RequestInitialSettings")}}class ng{constructor(s){this.dataChannelProvider=s}canSend(){return this.dataChannelProvider.getDataChannelInstance().dataChannel!==void 0&&this.dataChannelProvider.getDataChannelInstance().dataChannel.readyState=="open"}sendData(s){const n=this.dataChannelProvider.getDataChannelInstance();n.dataChannel.readyState=="open"?(n.dataChannel.send(s),b.Log(b.GetStackTrace(),`Message Sent: ${new Uint8Array(s)}`,6),this.resetAfkWarningTimerOnDataSend()):b.Error(b.GetStackTrace(),`Message Failed: ${new Uint8Array(s)}`)}resetAfkWarningTimerOnDataSend(){}}class ag{constructor(s){this.videoElementProvider=s,this.normalizeAndQuantizeUnsignedFunc=()=>{throw new Error("Normalize and quantize unsigned, method not implemented.")},this.normalizeAndQuantizeSignedFunc=()=>{throw new Error("Normalize and unquantize signed, method not implemented.")},this.denormalizeAndUnquantizeUnsignedFunc=()=>{throw new Error("Denormalize and unquantize unsigned, method not implemented.")}}normalizeAndQuantizeUnsigned(s,n){return this.normalizeAndQuantizeUnsignedFunc(s,n)}unquantizeAndDenormalizeUnsigned(s,n){return this.denormalizeAndUnquantizeUnsignedFunc(s,n)}normalizeAndQuantizeSigned(s,n){return this.normalizeAndQuantizeSignedFunc(s,n)}setupNormalizeAndQuantize(){if(this.videoElementParent=this.videoElementProvider.getVideoParentElement(),this.videoElement=this.videoElementProvider.getVideoElement(),this.videoElementParent&&this.videoElement){const s=this.videoElementParent.clientWidth||1,n=this.videoElementParent.clientHeight||1,d=this.videoElement.videoWidth||1,g=n/s,E=(this.videoElement.videoHeight||1)/d;g>E?(b.Log(b.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio > videoAspectRatio",6),this.ratio=g/E,this.normalizeAndQuantizeUnsignedFunc=(A,O)=>this.normalizeAndQuantizeUnsignedPlayerBigger(A,O),this.normalizeAndQuantizeSignedFunc=(A,O)=>this.normalizeAndQuantizeSignedPlayerBigger(A,O),this.denormalizeAndUnquantizeUnsignedFunc=(A,O)=>this.denormalizeAndUnquantizeUnsignedPlayerBigger(A,O)):(b.Log(b.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio <= videoAspectRatio",6),this.ratio=E/g,this.normalizeAndQuantizeUnsignedFunc=(A,O)=>this.normalizeAndQuantizeUnsignedPlayerSmaller(A,O),this.normalizeAndQuantizeSignedFunc=(A,O)=>this.normalizeAndQuantizeSignedPlayerSmaller(A,O),this.denormalizeAndUnquantizeUnsignedFunc=(A,O)=>this.denormalizeAndUnquantizeUnsignedPlayerSmaller(A,O))}}normalizeAndQuantizeUnsignedPlayerBigger(s,n){const d=s/this.videoElementParent.clientWidth,g=this.ratio*(n/this.videoElementParent.clientHeight-.5)+.5;return d<0||d>1||g<0||g>1?new on(!1,65535,65535):new on(!0,65536*d,65536*g)}denormalizeAndUnquantizeUnsignedPlayerBigger(s,n){const d=s/65536,g=(n/65536-.5)/this.ratio+.5;return new Va(d*this.videoElementParent.clientWidth,g*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerBigger(s,n){const d=s/(.5*this.videoElementParent.clientWidth),g=this.ratio*n/(.5*this.videoElementParent.clientHeight);return new Qh(32767*d,32767*g)}normalizeAndQuantizeUnsignedPlayerSmaller(s,n){const d=this.ratio*(s/this.videoElementParent.clientWidth-.5)+.5,g=n/this.videoElementParent.clientHeight;return d<0||d>1||g<0||g>1?new on(!1,65535,65535):new on(!0,65536*d,65536*g)}denormalizeAndUnquantizeUnsignedPlayerSmaller(s,n){const d=(s/65536-.5)/this.ratio+.5,g=n/65536;return new Va(d*this.videoElementParent.clientWidth,g*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerSmaller(s,n){const d=this.ratio*s/(.5*this.videoElementParent.clientWidth),g=n/(.5*this.videoElementParent.clientHeight);return new Qh(32767*d,32767*g)}}class on{constructor(s,n,d){this.inRange=s,this.x=n,this.y=d}}class Va{constructor(s,n){this.x=s,this.y=n}}class Qh{constructor(s,n){this.x=s,this.y=n}}class Yp{constructor(s,n){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=s,this.pixelStreaming=n,this.responseController=new rg,this.file=new Gf,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new Vp(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new If(this.pixelStreaming.videoElementParent),this.videoPlayer=new eg(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(d,g)=>{const E={"Resolution.Width":d,"Resolution.Height":g};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(E)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new Mf(this.videoPlayer),this.coordinateConverter=new ag(this.videoPlayer),this.sendrecvDataChannelController=new Hh,this.recvDataChannelController=new Hh,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new ng(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new tg,this.webSocketController=new op,this.webSocketController.onConfig=d=>this.handleOnConfigMessage(d),this.webSocketController.onStreamerList=d=>this.handleStreamerListMessage(d),this.webSocketController.onStreamerIDChanged=d=>this.handleStreamerIDChangedMessage(d),this.webSocketController.onPlayerCount=d=>{this.pixelStreaming._onPlayerCount(d.count)},this.webSocketController.onOpen.addEventListener("open",(()=>{this.config.isFlagEnabled(j.BrowserSendOffer)||this.webSocketController.requestStreamerList()})),this.webSocketController.onClose.addEventListener("close",(d=>{const g=this.shouldReconnect&&d.detail.code!=1001&&this.config.getNumericSettingValue(oe.MaxReconnectAttempts)>0,E=this.disconnectMessage?this.disconnectMessage:d.detail.reason;this.pixelStreaming._onDisconnect(E,!g&&!this.isReconnecting),this.afkController.stopAfkWarningTimer(),this.statsTimerHandle&&this.statsTimerHandle!==void 0&&window.clearInterval(this.statsTimerHandle),this.setVideoEncoderAvgQP(0),this.setTouchInputEnabled(!1),this.setMouseInputEnabled(!1),this.setKeyboardInputEnabled(!1),this.setGamePadInputEnabled(!1),g&&setTimeout((()=>{this.isReconnecting=!0,this.reconnectAttempt++,this.tryReconnect(d.detail.reason)}),2e3)})),this.sendMessageController=new sg(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new ig(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new Jf(this.streamMessageController,this.videoPlayer,this.coordinateConverter),this.isUsingSFU=!1,this.isQualityController=!1,this.preferredCodec="",this.shouldReconnect=!0,this.isReconnecting=!1,this.reconnectAttempt=0,this.config._addOnOptionSettingChangedListener(rt.StreamerId,(d=>{d!==""&&(this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=d,this.webSocketController.sendSubscribe(d))})),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>{let d=this.config.getTextSettingValue(Tr.SignallingServerUrl);return this.config.isFlagEnabled(j.BrowserSendOffer)&&(d+="?"+j.BrowserSendOffer+"=true"),d}}requestUnquantizedAndDenormalizeUnsigned(s,n){return this.coordinateConverter.unquantizeAndDenormalizeUnsigned(s,n)}handleOnMessage(s){const n=new Uint8Array(s.data);b.Log(b.GetStackTrace(),"Message incoming:"+n,6);const d=this.streamMessageController.fromStreamerMessages.get(n[0]);this.streamMessageController.fromStreamerHandlers.get(d)(s.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(we.FromStreamer,"QualityControlOwnership",(s=>this.onQualityControlOwnership(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"Response",(s=>this.responseController.onResponse(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"Command",(s=>{this.onCommand(s)})),this.streamMessageController.registerMessageHandler(we.FromStreamer,"FreezeFrame",(s=>this.onFreezeFrameMessage(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"UnfreezeFrame",(()=>this.invalidateFreezeFrameAndEnableVideo())),this.streamMessageController.registerMessageHandler(we.FromStreamer,"VideoEncoderAvgQP",(s=>this.handleVideoEncoderAvgQP(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"LatencyTest",(s=>this.handleLatencyTestResult(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"DataChannelLatencyTest",(s=>this.handleDataChannelLatencyTestResponse(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"InitialSettings",(s=>this.handleInitialSettings(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"FileExtension",(s=>this.onFileExtension(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"FileMimeType",(s=>this.onFileMimeType(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"FileContents",(s=>this.onFileContents(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(we.FromStreamer,"InputControlOwnership",(s=>this.onInputControlOwnership(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"GamepadResponse",(s=>this.onGamepadResponse(s))),this.streamMessageController.registerMessageHandler(we.FromStreamer,"Protocol",(s=>this.onProtocolMessage(s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"IFrameRequest",(()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest"))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"RequestQualityControl",(()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl"))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"FpsRequest",(()=>this.sendMessageController.sendMessageToStreamer("FpsRequest"))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"AverageBitrateRequest",(()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest"))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"StartStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StartStreaming"))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"StopStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StopStreaming"))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"LatencyTest",(s=>this.sendMessageController.sendMessageToStreamer("LatencyTest",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"RequestInitialSettings",(()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings"))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(we.ToStreamer,"UIInteraction",(s=>this.sendMessageController.sendMessageToStreamer("UIInteraction",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"Command",(s=>this.sendMessageController.sendMessageToStreamer("Command",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"TextboxEntry",(s=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"KeyDown",(s=>this.sendMessageController.sendMessageToStreamer("KeyDown",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"KeyUp",(s=>this.sendMessageController.sendMessageToStreamer("KeyUp",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"KeyPress",(s=>this.sendMessageController.sendMessageToStreamer("KeyPress",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"MouseEnter",(s=>this.sendMessageController.sendMessageToStreamer("MouseEnter",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"MouseLeave",(s=>this.sendMessageController.sendMessageToStreamer("MouseLeave",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"MouseDown",(s=>this.sendMessageController.sendMessageToStreamer("MouseDown",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"MouseUp",(s=>this.sendMessageController.sendMessageToStreamer("MouseUp",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"MouseMove",(s=>this.sendMessageController.sendMessageToStreamer("MouseMove",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"MouseWheel",(s=>this.sendMessageController.sendMessageToStreamer("MouseWheel",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"MouseDouble",(s=>this.sendMessageController.sendMessageToStreamer("MouseDouble",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"TouchStart",(s=>this.sendMessageController.sendMessageToStreamer("TouchStart",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"TouchEnd",(s=>this.sendMessageController.sendMessageToStreamer("TouchEnd",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"TouchMove",(s=>this.sendMessageController.sendMessageToStreamer("TouchMove",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"GamepadConnected",(()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected"))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"GamepadButtonPressed",(s=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"GamepadButtonReleased",(s=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"GamepadAnalog",(s=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"GamepadDisconnected",(s=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"XREyeViews",(s=>this.sendMessageController.sendMessageToStreamer("XREyeViews",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"XRHMDTransform",(s=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"XRControllerTransform",(s=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"XRSystem",(s=>this.sendMessageController.sendMessageToStreamer("XRSystem",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"XRButtonTouched",(s=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"XRButtonTouchReleased",(s=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"XRButtonPressed",(s=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"XRButtonReleased",(s=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",s))),this.streamMessageController.registerMessageHandler(we.ToStreamer,"XRAnalog",(s=>this.sendMessageController.sendMessageToStreamer("XRAnalog",s)))}onCommand(s){b.Log(b.GetStackTrace(),"DataChannelReceiveMessageType.Command",6);const n=new TextDecoder("utf-16").decode(s.slice(1));b.Log(b.GetStackTrace(),"Data Channel Command: "+n,6);const d=JSON.parse(n);d.command==="onScreenKeyboard"&&this.pixelStreaming._activateOnScreenKeyboard(d)}onProtocolMessage(s){try{const n=new TextDecoder("utf-16").decode(s.slice(1)),d=JSON.parse(n);Object.prototype.hasOwnProperty.call(d,"Direction")||b.Error(b.GetStackTrace(),"Malformed protocol received. Ensure the protocol message contains a direction");const g=d.Direction;delete d.Direction,b.Log(b.GetStackTrace(),`Received new ${g==we.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(d).forEach((E=>{const A=d[E];switch(g){case we.ToStreamer:if(!Object.prototype.hasOwnProperty.call(A,"id"))return void b.Error(b.GetStackTrace(),`ToStreamer->${E} protocol definition was malformed as it didn't contain at least an id
|
|
2885
|
+
|
|
2886
|
+
Definition was: ${JSON.stringify(A,null,2)}`);if(E==="UIInteraction"||E==="Command"||E==="LatencyTest")return;this.streamMessageController.toStreamerHandlers.get(E)?this.streamMessageController.toStreamerMessages.set(E,A):b.Error(b.GetStackTrace(),`There was no registered handler for "${E}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${E}", myHandler)`);break;case we.FromStreamer:if(!Object.prototype.hasOwnProperty.call(A,"id"))return void b.Error(b.GetStackTrace(),`FromStreamer->${E} protocol definition was malformed as it didn't contain at least an id
|
|
2887
|
+
|
|
2888
|
+
Definition was: ${JSON.stringify(A,null,2)}`);this.streamMessageController.fromStreamerHandlers.get(E)?this.streamMessageController.fromStreamerMessages.set(A.id,E):b.Error(b.GetStackTrace(),`There was no registered handler for "${A}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${E}", myHandler)`);break;default:b.Error(b.GetStackTrace(),`Unknown direction: ${g}`)}})),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(n){b.Log(b.GetStackTrace(),n)}}onInputControlOwnership(s){const n=new Uint8Array(s);b.Log(b.GetStackTrace(),"DataChannelReceiveMessageType.InputControlOwnership",6);const d=new Boolean(n[1]).valueOf();b.Log(b.GetStackTrace(),`Received input controller message - will your input control the stream: ${d}`),this.pixelStreaming._onInputControlOwnership(d)}onGamepadResponse(s){const n=new TextDecoder("utf-16").decode(s.slice(1)),d=JSON.parse(n);this.gamePadController.onGamepadResponseReceived(d.controllerId)}onAfkTriggered(){this.afkController.onAfkClick(),this.videoPlayer.isPaused()&&this.videoPlayer.hasVideoSource()&&this.playStream()}setAfkEnabled(s){s?this.onAfkTriggered():this.afkController.stopAfkWarningTimer()}tryReconnect(s){this.webSocketController?(this.isReconnecting=!0,this.webSocketController.webSocket&&this.webSocketController.webSocket.readyState!=WebSocket.CLOSED?(this.closeSignalingServer(`${s} Restarting stream...`),setTimeout((()=>{this.tryReconnect(s)}),3e3)):(this.pixelStreaming._onWebRtcAutoConnect(),this.connectToSignallingServer())):b.Log(b.GetStackTrace(),"The Web Socket Controller does not exist so this will not work right now.")}loadFreezeFrameOrShowPlayOverlay(){this.pixelStreaming.dispatchEvent(new Mp({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),this.shouldShowPlayOverlay===!0?(b.Log(b.GetStackTrace(),"showing play overlay"),this.resizePlayerStyle()):(b.Log(b.GetStackTrace(),"showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout((()=>{this.videoPlayer.setVideoEnabled(!1)}),this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(s){b.Log(b.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6);const n=new Uint8Array(s);this.freezeFrameController.processFreezeFrameMessage(n,(()=>this.loadFreezeFrameOrShowPlayOverlay()))}invalidateFreezeFrameAndEnableVideo(){b.Log(b.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6),setTimeout((()=>{this.pixelStreaming.dispatchEvent(new Rp),this.freezeFrameController.hideFreezeFrame()}),this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(s){const n=new Uint8Array(s);Da.setExtensionFromBytes(n,this.file)}onFileMimeType(s){const n=new Uint8Array(s);Da.setMimeTypeFromBytes(n,this.file)}onFileContents(s){const n=new Uint8Array(s);Da.setContentsFromBytes(n,this.file)}playStream(){if(!this.videoPlayer.getVideoElement()){const s="Could not play video stream because the video player was not initialized correctly.";return this.pixelStreaming.dispatchEvent(new Ep({message:s})),b.Error(b.GetStackTrace(),s),void this.closeSignalingServer("Stream not initialized correctly")}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(j.TouchInput)),this.pixelStreaming.dispatchEvent(new kp),this.streamController.audioElement.srcObject){const s=this.config.isFlagEnabled(j.StartVideoMuted);this.streamController.audioElement.muted=s,s?this.playVideo():this.streamController.audioElement.play().then((()=>{this.playVideo()})).catch((n=>{b.Log(b.GetStackTrace(),n),b.Log(b.GetStackTrace(),"Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new Fa({reason:n}))}))}else this.playVideo();this.shouldShowPlayOverlay=!1,this.freezeFrameController.showFreezeFrame()}else b.Warning(b.GetStackTrace(),"Cannot play stream, the video element has no srcObject to play.")}playVideo(){this.videoPlayer.play().catch((s=>{this.streamController.audioElement.srcObject&&this.streamController.audioElement.pause(),b.Log(b.GetStackTrace(),s),b.Log(b.GetStackTrace(),"Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new Fa({reason:s}))}))}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(j.AutoPlayVideo)&&this.playStream(),this.resizePlayerStyle()}connectToSignallingServer(){this.locallyClosed=!1,this.shouldReconnect=!0,this.disconnectMessage=null;const s=this.signallingUrlBuilder();this.webSocketController.connect(s)}startSession(s){if(this.peerConfig=s,this.config.isFlagEnabled(j.ForceTURN)&&!this.checkTurnServerAvailability(s))return b.Info(b.GetStackTrace(),"No turn server was found in the Peer Connection Options. TURN cannot be forced, closing connection. Please use STUN instead"),void this.closeSignalingServer("TURN cannot be forced, closing connection. Please use STUN instead.");this.peerConnectionController=new Nf(this.peerConfig,this.config,this.preferredCodec),this.peerConnectionController.onVideoStats=d=>this.handleVideoStats(d),this.peerConnectionController.onSendWebRTCOffer=d=>this.handleSendWebRTCOffer(d),this.peerConnectionController.onSendWebRTCAnswer=d=>this.handleSendWebRTCAnswer(d),this.peerConnectionController.onPeerIceCandidate=d=>this.handleSendIceCandidate(d),this.peerConnectionController.onDataChannel=d=>this.handleDataChannel(d),this.peerConnectionController.showTextOverlayConnecting=()=>this.pixelStreaming._onWebRtcConnecting(),this.peerConnectionController.showTextOverlaySetupFailure=()=>this.pixelStreaming._onWebRtcFailed();let n=!1;this.peerConnectionController.onIceConnectionStateChange=()=>{!n&&["connected","completed"].includes(this.peerConnectionController.peerConnection.iceConnectionState)&&(this.pixelStreaming._onWebRtcConnected(),n=!0)},this.peerConnectionController.onTrack=d=>this.streamController.handleOnTrack(d),this.config.isFlagEnabled(j.BrowserSendOffer)&&(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"cirrus",this.datachannelOptions),this.sendrecvDataChannelController.handleOnMessage=d=>this.handleOnMessage(d),this.peerConnectionController.createOffer(this.sdpConstraints,this.config))}checkTurnServerAvailability(s){if(!s.iceServers)return b.Info(b.GetStackTrace(),"A turn sever was not found"),!1;for(const n of s.iceServers)for(const d of n.urls)if(d.includes("turn"))return b.Log(b.GetStackTrace(),`A turn sever was found at ${d}`),!0;return b.Info(b.GetStackTrace(),"A turn sever was not found"),!1}handleOnConfigMessage(s){this.resizePlayerStyle(),this.startSession(s.peerConnectionOptions),this.webSocketController.onWebRtcAnswer=n=>this.handleWebRtcAnswer(n),this.webSocketController.onWebRtcOffer=n=>this.handleWebRtcOffer(n),this.webSocketController.onWebRtcPeerDataChannels=n=>this.handleWebRtcSFUPeerDatachannels(n),this.webSocketController.onIceCandidate=n=>this.handleIceCandidate(n)}handleStreamerListMessage(s){b.Log(b.GetStackTrace(),`Got streamer list ${s.ids}`,6);let n=null;var d=this.config.getSettingOption(rt.StreamerId);d.selected.toString().trim()&&(n=d.selected);const g=[...s.ids];g.unshift(""),this.config.setOptionSettingOptions(rt.StreamerId,g);let E=null;const A=this.config.isFlagEnabled(j.WaitForStreamer),O=this.config.getNumericSettingValue(oe.MaxReconnectAttempts),T=this.config.getNumericSettingValue(oe.StreamerAutoJoinInterval),K=this.config.useUrlParams,G=new URLSearchParams(window.location.search);K&&G.has(rt.StreamerId)?n=G.get(rt.StreamerId):this.subscribedStream&&(n=this.subscribedStream),n&&s.ids.includes(n)?E=n:n&&A||s.ids.length!=1||(E=s.ids[0]),E?(this.isReconnecting=!1,this.reconnectAttempt=0,this.config.setOptionSettingValue(rt.StreamerId,E)):A&&(this.reconnectAttempt<O?(this.isReconnecting=!0,this.reconnectAttempt++,setTimeout((()=>{this.webSocketController.requestStreamerList()}),T)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.shouldReconnect=!1)),this.pixelStreaming.dispatchEvent(new Ap({messageStreamerList:s,autoSelectedStreamerId:E,wantedStreamerId:n}))}handleStreamerIDChangedMessage(s){const n=s.newID;var d=this.config.getSettingOption(rt.StreamerId),g=d.onChange;d.onChange=()=>{};for(var E=d.options,A=0;A<E.length;++A)if(E[A]==this.subscribedStream){E[A]=n;break}d.options=E,d.selected=n,d.onChange=g,this.subscribedStream=s.newID,this.pixelStreaming.dispatchEvent(new Pp({newID:n}))}handleWebRtcAnswer(s){b.Log(b.GetStackTrace(),`Got answer sdp ${s.sdp}`,6);const n={sdp:s.sdp,type:"answer"};this.peerConnectionController.receiveAnswer(n),this.handlePostWebrtcNegotiation()}handleWebRtcOffer(s){b.Log(b.GetStackTrace(),`Got offer sdp ${s.sdp}`,6),this.isUsingSFU=!!s.sfu&&s.sfu,this.isUsingSFU&&(this.peerConnectionController.preferredCodec="");const n={sdp:s.sdp,type:"offer"};this.peerConnectionController.receiveOffer(n,this.config),this.handlePostWebrtcNegotiation()}handleWebRtcSFUPeerDatachannels(s){const n={ordered:!0,negotiated:!0,id:s.sendStreamId},d=s.sendStreamId!=s.recvStreamId;if(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,d?"send-datachannel":"datachannel",n),d){const g={ordered:!0,negotiated:!0,id:s.recvStreamId};this.recvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"recv-datachannel",g),this.recvDataChannelController.handleOnOpen=()=>this.webSocketController.sendSFURecvDataChannelReady(),this.recvDataChannelController.handleOnMessage=E=>this.handleOnMessage(E)}else this.sendrecvDataChannelController.handleOnMessage=g=>this.handleOnMessage(g)}handlePostWebrtcNegotiation(){this.afkController.startAfkWarningTimer(),this.pixelStreaming._onWebRtcSdp(),this.statsTimerHandle&&this.statsTimerHandle!==void 0&&window.clearInterval(this.statsTimerHandle),this.statsTimerHandle=window.setInterval((()=>this.getStats()),1e3),this.setMouseInputEnabled(this.config.isFlagEnabled(j.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(j.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(j.GamepadInput))}handleIceCandidate(s){b.Log(b.GetStackTrace(),"Web RTC Controller: onWebRtcIce",6);const n=new RTCIceCandidate(s);this.peerConnectionController.handleOnIce(n)}handleSendIceCandidate(s){b.Log(b.GetStackTrace(),"OnIceCandidate",6),s.candidate&&s.candidate.candidate&&this.webSocketController.sendIceCandidate(s.candidate)}handleDataChannel(s){b.Log(b.GetStackTrace(),"Data channel created for us by browser as we are a receiving peer.",6),this.sendrecvDataChannelController.dataChannel=s.channel,this.sendrecvDataChannelController.setupDataChannel(),this.sendrecvDataChannelController.handleOnMessage=n=>this.handleOnMessage(n)}handleSendWebRTCOffer(s){b.Log(b.GetStackTrace(),"Sending the offer to the Server",6);const n={minBitrateBps:1e3*this.config.getNumericSettingValue(oe.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(oe.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcOffer(s,n)}handleSendWebRTCAnswer(s){b.Log(b.GetStackTrace(),"Sending the answer to the Server",6);const n={minBitrateBps:1e3*this.config.getNumericSettingValue(oe.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(oe.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcAnswer(s,n),this.isUsingSFU&&this.webSocketController.sendWebRtcDatachannelRequest()}setUpMouseAndFreezeFrame(){this.videoElementParentClientRect=this.videoPlayer.getVideoParentElement().getBoundingClientRect(),this.coordinateConverter.setupNormalizeAndQuantize(),this.freezeFrameController.freezeFrame.resize()}closeSignalingServer(s){var n;this.locallyClosed=!0,this.shouldReconnect=!1,this.disconnectMessage=s,(n=this.webSocketController)===null||n===void 0||n.close()}closePeerConnection(){var s;(s=this.peerConnectionController)===null||s===void 0||s.close()}close(){this.closeSignalingServer(""),this.closePeerConnection()}getStats(){this.peerConnectionController.generateStats()}sendLatencyTest(){this.latencyStartTime=Date.now(),this.streamMessageController.toStreamerHandlers.get("LatencyTest")([JSON.stringify({StartTime:this.latencyStartTime})])}sendDataChannelLatencyTest(s){this.streamMessageController.toStreamerHandlers.get("DataChannelLatencyTest")([JSON.stringify(s)])}sendEncoderMinQP(s){b.Log(b.GetStackTrace(),`MinQP=${s}
|
|
2889
|
+
`,6),s!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQP":s})])}sendEncoderMaxQP(s){b.Log(b.GetStackTrace(),`MaxQP=${s}
|
|
2890
|
+
`,6),s!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQP":s})])}sendWebRTCMinBitrate(s){b.Log(b.GetStackTrace(),`WebRTC Min Bitrate=${s}`,6),s!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MinBitrate":s})])}sendWebRTCMaxBitrate(s){b.Log(b.GetStackTrace(),`WebRTC Max Bitrate=${s}`,6),s!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxBitrate":s})])}sendWebRTCFps(s){b.Log(b.GetStackTrace(),`WebRTC FPS=${s}`,6),s!=null&&(this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.Fps":s})]),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxFps":s})]))}sendShowFps(){b.Log(b.GetStackTrace(),"---- Sending show stat to UE ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"stat.fps":""})])}sendIframeRequest(){b.Log(b.GetStackTrace(),"---- Sending Request for an IFrame ----",6),this.streamMessageController.toStreamerHandlers.get("IFrameRequest")()}emitUIInteraction(s){b.Log(b.GetStackTrace(),"---- Sending custom UIInteraction message ----",6),this.streamMessageController.toStreamerHandlers.get("UIInteraction")([JSON.stringify(s)])}emitCommand(s){b.Log(b.GetStackTrace(),"---- Sending custom Command message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(s)])}emitConsoleCommand(s){b.Log(b.GetStackTrace(),"---- Sending custom Command:ConsoleCommand message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({ConsoleCommand:s})])}sendRequestQualityControlOwnership(){b.Log(b.GetStackTrace(),"---- Sending Request to Control Quality ----",6),this.toStreamerMessagesController.SendRequestQualityControl()}handleLatencyTestResult(s){b.Log(b.GetStackTrace(),"DataChannelReceiveMessageType.latencyTest",6);const n=new TextDecoder("utf-16").decode(s.slice(1)),d=new Jp;Object.assign(d,JSON.parse(n)),d.processFields(),d.testStartTimeMs=this.latencyStartTime,d.browserReceiptTimeMs=Date.now(),d.latencyExcludingDecode=~~(d.browserReceiptTimeMs-d.testStartTimeMs),d.testDuration=~~(d.TransmissionTimeMs-d.ReceiptTimeMs),d.networkLatency=~~(d.latencyExcludingDecode-d.testDuration),d.frameDisplayDeltaTimeMs&&d.browserReceiptTimeMs&&(d.endToEndLatency=(d.frameDisplayDeltaTimeMs,d.networkLatency,~~+d.CaptureToSendMs)),this.pixelStreaming._onLatencyTestResult(d)}handleDataChannelLatencyTestResponse(s){b.Log(b.GetStackTrace(),"DataChannelReceiveMessageType.dataChannelLatencyResponse",6);const n=new TextDecoder("utf-16").decode(s.slice(1)),d=JSON.parse(n);this.pixelStreaming._onDataChannelLatencyTestResponse(d)}handleInitialSettings(s){b.Log(b.GetStackTrace(),"DataChannelReceiveMessageType.InitialSettings",6);const n=new TextDecoder("utf-16").decode(s.slice(1)),d=JSON.parse(n),g=new Qp;d.Encoder&&(g.EncoderSettings=d.Encoder),d.WebRTC&&(g.WebRTCSettings=d.WebRTC),d.PixelStreaming&&(g.PixelStreamingSettings=d.PixelStreaming),d.ConfigOptions&&d.ConfigOptions.DefaultToHover!==void 0&&this.config.setFlagEnabled(j.HoveringMouseMode,!!d.ConfigOptions.DefaultToHover),g.ueCompatible(),b.Log(b.GetStackTrace(),n,6),this.pixelStreaming._onInitialSettings(g)}handleVideoEncoderAvgQP(s){b.Log(b.GetStackTrace(),"DataChannelReceiveMessageType.VideoEncoderAvgQP",6);const n=Number(new TextDecoder("utf-16").decode(s.slice(1)));this.setVideoEncoderAvgQP(n)}handleVideoInitialized(){this.pixelStreaming._onVideoInitialized(),this.autoPlayVideoOrSetUpPlayOverlay(),this.resizePlayerStyle(),this.videoPlayer.updateVideoStreamSize()}onQualityControlOwnership(s){const n=new Uint8Array(s);b.Log(b.GetStackTrace(),"DataChannelReceiveMessageType.QualityControlOwnership",6),this.isQualityController=new Boolean(n[1]).valueOf(),b.Log(b.GetStackTrace(),`Received quality controller message, will control quality: ${this.isQualityController}`),this.pixelStreaming._onQualityControlOwnership(this.isQualityController)}handleVideoStats(s){this.pixelStreaming._onVideoStats(s)}resizePlayerStyle(){this.videoPlayer.resizePlayerStyle()}setPreferredCodec(s){this.preferredCodec=s,this.peerConnectionController&&(this.peerConnectionController.preferredCodec=s,this.peerConnectionController.updateCodecSelection=!1)}setVideoEncoderAvgQP(s){this.videoAvgQp=s,this.pixelStreaming._onVideoEncoderAvgQP(this.videoAvgQp)}setKeyboardInputEnabled(s){var n;(n=this.keyboardController)===null||n===void 0||n.unregisterKeyBoardEvents(),s&&(this.keyboardController=this.inputClassesFactory.registerKeyBoard(this.config))}setMouseInputEnabled(s){var n;if((n=this.mouseController)===null||n===void 0||n.unregisterMouseEvents(),s){const d=this.config.isFlagEnabled(j.HoveringMouseMode)?fs.HoveringMouse:fs.LockedMouse;this.mouseController=this.inputClassesFactory.registerMouse(d)}}setTouchInputEnabled(s){var n;(n=this.touchController)===null||n===void 0||n.unregisterTouchEvents(),s&&(this.touchController=this.inputClassesFactory.registerTouch(this.config.isFlagEnabled(j.FakeMouseWithTouches),this.videoElementParentClientRect))}setGamePadInputEnabled(s){var n;(n=this.gamePadController)===null||n===void 0||n.unregisterGamePadEvents(),s&&(this.gamePadController=this.inputClassesFactory.registerGamePad(),this.gamePadController.onGamepadConnected=()=>{this.streamMessageController.toStreamerHandlers.get("GamepadConnected")()},this.gamePadController.onGamepadDisconnected=d=>{this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([d])})}registerDataChannelEventEmitters(s){s.onOpen=(n,d)=>this.pixelStreaming.dispatchEvent(new vp({label:n,event:d})),s.onClose=(n,d)=>this.pixelStreaming.dispatchEvent(new bp({label:n,event:d})),s.onError=(n,d)=>this.pixelStreaming.dispatchEvent(new _p({label:n,event:d}))}registerMessageHandler(s,n,d){n===we.FromStreamer&&d===void 0&&b.Warning(b.GetStackTrace(),`Unable to register handler for ${s} as no handler was passed`),this.streamMessageController.registerMessageHandler(n,s,(g=>d===void 0&&n===we.ToStreamer?this.sendMessageController.sendMessageToStreamer(s,g):d(g)))}}class dn{constructor(s){this.toStreamerMessagesProvider=s,this.controllers=[]}static deepCopyGamepad(s){return JSON.parse(JSON.stringify({buttons:s.buttons.map((n=>JSON.parse(JSON.stringify({pressed:n.pressed,touched:n.touched,value:n.value})))),axes:s.axes}))}updateStatus(s,n,d){if(s.gamepad){const g=n.getPose(s.gripSpace,d);if(!g)return;let E=0;s.profiles.includes("htc-vive")?E=1:s.profiles.includes("oculus-touch")&&(E=2),this.toStreamerMessagesProvider.toStreamerHandlers.get("XRSystem")([E]);let A=2;switch(s.handedness){case"left":A=0;break;case"right":A=1}const O=g.transform.matrix,T=[];for(let J=0;J<16;J++)T[J]=new Float32Array([O[J]])[0];this.toStreamerMessagesProvider.toStreamerHandlers.get("XRControllerTransform")([T[0],T[4],T[8],T[12],T[1],T[5],T[9],T[13],T[2],T[6],T[10],T[14],T[3],T[7],T[11],T[15],A]),this.controllers[A]===void 0&&(this.controllers[A]={prevState:void 0,currentState:void 0,id:void 0},this.controllers[A].prevState=dn.deepCopyGamepad(s.gamepad)),this.controllers[A].currentState=dn.deepCopyGamepad(s.gamepad);const K=this.controllers[A],G=K.currentState,ae=K.prevState;for(let J=0;J<G.buttons.length;J++){const ie=G.buttons[J],re=ae.buttons[J];if(ie.pressed){let ne=re.pressed?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonPressed")([A,J,ne])}else re.pressed&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonReleased")([A,J,0]);if(ie.touched){let ne=re.touched?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouched")([A,J,ne])}else re.touched&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouchReleased")([A,J,0])}for(let J=0;J<G.axes.length;J++){let ie=G.axes[J];ie!=ae.axes[J]&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRAnalog")([A,J,ie])}this.controllers[A].prevState=G}}}class em{constructor(s){this.xrViewerPose=null,this.videoTexture=null,this.prevVideoWidth=0,this.prevVideoHeight=0,this.leftView=null,this.rightView=null,this.xrSession=null,this.webRtcController=s,this.xrGamepadController=new dn(this.webRtcController.streamMessageController),this.onSessionEnded=new EventTarget,this.onSessionStarted=new EventTarget,this.onFrame=new EventTarget}xrClicked(){if(this.xrSession)this.xrSession.end();else{if(!navigator.xr)return void b.Error(b.GetStackTrace(),"This browser does not support XR.");navigator.xr.requestSession("immersive-vr",{optionalFeatures:[]}).then((s=>{this.onXrSessionStarted(s)}))}}onXrSessionEnded(){b.Log(b.GetStackTrace(),"XR Session ended"),this.xrSession=null,this.onSessionEnded.dispatchEvent(new Event("xrSessionEnded"))}initGL(){if(this.gl)return;const s=document.createElement("canvas");this.gl=s.getContext("webgl2",{xrCompatible:!0}),this.gl.clearColor(0,0,0,1)}initShaders(){const s=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(s,`
|
|
2891
|
+
attribute vec2 a_position;
|
|
2892
|
+
attribute vec2 a_texCoord;
|
|
2893
|
+
|
|
2894
|
+
// varyings
|
|
2895
|
+
varying vec2 v_texCoord;
|
|
2896
|
+
|
|
2897
|
+
void main() {
|
|
2898
|
+
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
2899
|
+
// pass the texCoord to the fragment shader
|
|
2900
|
+
// The GPU will interpolate this value between points.
|
|
2901
|
+
v_texCoord = a_texCoord;
|
|
2902
|
+
}
|
|
2903
|
+
`),this.gl.compileShader(s);const n=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(n,`
|
|
2904
|
+
precision mediump float;
|
|
2905
|
+
|
|
2906
|
+
// our texture
|
|
2907
|
+
uniform sampler2D u_image;
|
|
2908
|
+
|
|
2909
|
+
// the texCoords passed in from the vertex shader.
|
|
2910
|
+
varying vec2 v_texCoord;
|
|
2911
|
+
|
|
2912
|
+
void main() {
|
|
2913
|
+
gl_FragColor = texture2D(u_image, v_texCoord);
|
|
2914
|
+
}
|
|
2915
|
+
`),this.gl.compileShader(n);const d=this.gl.createProgram();this.gl.attachShader(d,s),this.gl.attachShader(d,n),this.gl.linkProgram(d),this.gl.useProgram(d),this.positionLocation=this.gl.getAttribLocation(d,"a_position"),this.texcoordLocation=this.gl.getAttribLocation(d,"a_texCoord")}updateVideoTexture(){this.videoTexture||(this.videoTexture=this.gl.createTexture(),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR));let s=this.webRtcController.videoPlayer.getVideoElement().videoHeight,n=this.webRtcController.videoPlayer.getVideoElement().videoWidth;this.prevVideoHeight!=s||this.prevVideoWidth!=n?this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,n,s,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()):this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,0,0,n,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()),this.prevVideoHeight=s,this.prevVideoWidth=n}initBuffers(){this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.positionLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-1,1,1,1,-1,-1,-1,-1,1,1,1,-1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.positionLocation,2,this.gl.FLOAT,!1,0,0),this.texcoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texcoordBuffer),this.gl.enableVertexAttribArray(this.texcoordLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.texcoordLocation,2,this.gl.FLOAT,!1,0,0)}onXrSessionStarted(s){b.Log(b.GetStackTrace(),"XR Session started"),this.xrSession=s,this.xrSession.addEventListener("end",(()=>{this.onXrSessionEnded()})),this.initGL(),this.initShaders(),this.initBuffers(),s.requestReferenceSpace("local").then((n=>{if(this.xrRefSpace=n,this.xrSession.updateRenderState({baseLayer:new XRWebGLLayer(this.xrSession,this.gl)}),this.xrSession.supportedFrameRates)for(let d of this.xrSession.supportedFrameRates)d==90&&s.updateTargetFrameRate(90);this.xrSession.requestAnimationFrame(this.onXrFrame.bind(this))})),this.onSessionStarted.dispatchEvent(new Event("xrSessionStarted"))}sendXRDataToUE(){if(this.leftView==null||this.rightView==null)return;const s=this.leftView.transform.matrix,n=this.leftView.projectionMatrix,d=this.rightView.transform.matrix,g=this.rightView.projectionMatrix;this.webRtcController.streamMessageController.toStreamerHandlers.get("XREyeViews")([s[0],s[4],s[8],s[12],s[1],s[5],s[9],s[13],s[2],s[6],s[10],s[14],s[3],s[7],s[11],s[15],n[0],n[4],n[8],n[12],n[1],n[5],n[9],n[13],n[2],n[6],n[10],n[14],n[3],n[7],n[11],n[15],d[0],d[4],d[8],d[12],d[1],d[5],d[9],d[13],d[2],d[6],d[10],d[14],d[3],d[7],d[11],d[15],g[0],g[4],g[8],g[12],g[1],g[5],g[9],g[13],g[2],g[6],g[10],g[14],g[3],g[7],g[11],g[15]])}onXrFrame(s,n){if(this.xrViewerPose=n.getViewerPose(this.xrRefSpace),this.xrViewerPose){if(this.updateViews(),this.leftView==null||this.rightView==null)return;this.sendXRDataToUE(),this.updateVideoTexture(),this.render()}this.webRtcController.config.isFlagEnabled(j.XRControllerInput)&&this.xrSession.inputSources.forEach(((d,g,E)=>{this.xrGamepadController.updateStatus(d,n,this.xrRefSpace)}),this),this.xrSession.requestAnimationFrame(((d,g)=>this.onXrFrame(d,g))),this.onFrame.dispatchEvent(new Bp({time:s,frame:n}))}updateViews(){if(this.xrViewerPose)for(const s of this.xrViewerPose.views)s.eye==="left"?this.leftView=s:s.eye==="right"&&(this.rightView=s)}render(){if(!this.gl)return;const s=this.xrSession.renderState.baseLayer;this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,s.framebuffer),this.gl.viewport(0,0,s.framebufferWidth,s.framebufferHeight),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}static isSessionSupported(s){return location.protocol!=="https:"&&b.Info(null,"WebXR requires https, if you want WebXR use https."),navigator.xr?navigator.xr.isSessionSupported(s):new Promise((()=>!1))}}class og{constructor(s){this.editTextButton=null,this.hiddenInput=null,"ontouchstart"in document.documentElement&&this.createOnScreenKeyboardHelpers(s)}unquantizeAndDenormalizeUnsigned(s,n){return null}createOnScreenKeyboardHelpers(s){this.hiddenInput||(this.hiddenInput=document.createElement("input"),this.hiddenInput.id="hiddenInput",this.hiddenInput.maxLength=0,this.hiddenInput.style.position="absolute",this.hiddenInput.style.left="-10%",this.hiddenInput.style.width="0px",this.hiddenInput.style.opacity="0",s.appendChild(this.hiddenInput)),this.editTextButton||(this.editTextButton=document.createElement("button"),this.editTextButton.id="editTextButton",this.editTextButton.innerHTML="edit text",s.appendChild(this.editTextButton),this.editTextButton.style.display="none",this.editTextButton.addEventListener("touchend",(n=>{this.hiddenInput.focus(),n.preventDefault()})))}showOnScreenKeyboard(s){if(s.showOnScreenKeyboard){this.editTextButton.style.display="default";const n=this.unquantizeAndDenormalizeUnsigned(s.x,s.y);this.editTextButton.style.top=n.y.toString()+"px",this.editTextButton.style.left=(n.x-40).toString()+"px"}else this.editTextButton.style.display="none",this.hiddenInput.blur()}}class lg{constructor(s){this.seq=s.Seq,this.playerSentTimestamp=Date.now(),this.requestFillerSize=s.Filler?s.Filler.length:0}update(s){this.playerReceivedTimestamp=Date.now(),this.streamerReceivedTimestamp=s.ReceivedTimestamp,this.streamerSentTimestamp=s.SentTimestamp,this.responseFillerSize=s.Filler?s.Filler.length:0}}class ug{constructor(s,n){this.sink=s,this.callback=n,this.records=new Map,this.seq=0}start(s){return!this.isRunning()&&(this.startTime=Date.now(),this.records.clear(),this.interval=setInterval((()=>{Date.now()-this.startTime>=s.duration?this.stop():this.sendRequest(s.requestSize,s.responseSize)}).bind(this),Math.floor(1e3/s.rps)),!0)}stop(){this.interval&&(clearInterval(this.interval),this.interval=void 0,this.callback(this.produceResult()))}produceResult(){const s=new Map(this.records);return{records:s,dataChannelRtt:Math.ceil(Array.from(this.records.values()).reduce(((n,d)=>n+(d.playerReceivedTimestamp-d.playerSentTimestamp)),0)/this.records.size),playerToStreamerTime:Math.ceil(Array.from(this.records.values()).reduce(((n,d)=>n+(d.streamerReceivedTimestamp-d.playerSentTimestamp)),0)/this.records.size),streamerToPlayerTime:Math.ceil(Array.from(this.records.values()).reduce(((n,d)=>n+(d.playerReceivedTimestamp-d.streamerSentTimestamp)),0)/this.records.size),exportLatencyAsCSV:()=>{let n=`Timestamp;RTT;PlayerToStreamer;StreamerToPlayer;
|
|
2916
|
+
`;return s.forEach((d=>{n+=d.playerSentTimestamp+";",n+=d.playerReceivedTimestamp-d.playerSentTimestamp+";",n+=d.streamerReceivedTimestamp-d.playerSentTimestamp+";",n+=d.playerReceivedTimestamp-d.streamerSentTimestamp+";",n+=`
|
|
2917
|
+
`})),n}}}isRunning(){return!!this.interval}receive(s){if(!this.isRunning())return;if(!s)return void b.Error(b.GetStackTrace(),"Undefined response from server");let n=this.records.get(s.Seq);n&&n.update(s)}sendRequest(s,n){let d=this.createRequest(s,n),g=new lg(d);this.records.set(g.seq,g),this.sink(d)}createRequest(s,n){return{Seq:this.seq++,FillResponseSize:n,Filler:s?"A".repeat(s):""}}}class dg{constructor(s,n){this.allowConsoleCommands=!1,this.config=s,n?.videoElementParent&&(this._videoElementParent=n.videoElementParent),this._eventEmitter=new Np,this.configureSettings(),this.setWebRtcPlayerController(new Yp(this.config,this)),this.onScreenKeyboardHelper=new og(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(d,g)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(d,g),this._activateOnScreenKeyboard=d=>this.onScreenKeyboardHelper.showOnScreenKeyboard(d),this._webXrController=new em(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",(d=>{this._eventEmitter.addEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}))}get videoElementParent(){return this._videoElementParent||(this._videoElementParent=document.createElement("div"),this._videoElementParent.id="videoElementParent"),this._videoElementParent}configureSettings(){this.config._addOnSettingChangedListener(j.IsQualityController,(s=>{s!==!0||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(j.AFKDetection,(s=>{this._webRtcController.setAfkEnabled(s)})),this.config._addOnSettingChangedListener(j.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(j.HoveringMouseMode,(s=>{this.config.setFlagLabel(j.HoveringMouseMode,`Control Scheme: ${s?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(j.MouseInput))})),this.config._addOnSettingChangedListener(j.KeyboardInput,(s=>{this._webRtcController.setKeyboardInputEnabled(s)})),this.config._addOnSettingChangedListener(j.MouseInput,(s=>{this._webRtcController.setMouseInputEnabled(s)})),this.config._addOnSettingChangedListener(j.FakeMouseWithTouches,(s=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(j.TouchInput))})),this.config._addOnSettingChangedListener(j.TouchInput,(s=>{this._webRtcController.setTouchInputEnabled(s)})),this.config._addOnSettingChangedListener(j.GamepadInput,(s=>{this._webRtcController.setGamePadInputEnabled(s)})),this.config._addOnNumericSettingChangedListener(oe.MinQP,(s=>{b.Log(b.GetStackTrace(),"-------- Sending MinQP --------",7),this._webRtcController.sendEncoderMinQP(s),b.Log(b.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(oe.MaxQP,(s=>{b.Log(b.GetStackTrace(),"-------- Sending encoder settings --------",7),this._webRtcController.sendEncoderMaxQP(s),b.Log(b.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(oe.WebRTCMinBitrate,(s=>{b.Log(b.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMinBitrate(1e3*s),b.Log(b.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(oe.WebRTCMaxBitrate,(s=>{b.Log(b.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMaxBitrate(1e3*s),b.Log(b.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(oe.WebRTCFPS,(s=>{b.Log(b.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCFps(s),b.Log(b.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnOptionSettingChangedListener(rt.PreferredCodec,(s=>{this._webRtcController&&this._webRtcController.setPreferredCodec(s)})),this.config._registerOnChangeEvents(this._eventEmitter)}_activateOnScreenKeyboard(s){throw new Error("Method not implemented.")}_onInputControlOwnership(s){this._inputController=s}setWebRtcPlayerController(s){this._webRtcController=s,this._webRtcController.setPreferredCodec(this.config.getSettingOption(rt.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new xp),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Cp),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Tp),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(j.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(s=!1){if(!this.config.isFlagEnabled("UseMic"))return s?(this.config.setFlagEnabled("UseMic",!0),void this.reconnect()):void b.Warning(b.GetStackTrace(),"Trying to unmute mic, but PixelStreaming was initialized with no microphone track. Call with forceEnable == true to re-connect with a mic track.");this.setMicrophoneMuted(!1)}muteMicrophone(){this.config.isFlagEnabled("UseMic")?this.setMicrophoneMuted(!0):b.Info(b.GetStackTrace(),"Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(s){var n,d,g,E;for(const A of(E=(g=(d=(n=this._webRtcController)===null||n===void 0?void 0:n.peerConnectionController)===null||d===void 0?void 0:d.peerConnection)===null||g===void 0?void 0:g.getTransceivers())!==null&&E!==void 0?E:[])Kp.canTransceiverSendAudio(A)&&(A.sender.track.enabled=!s)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new mp)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new pp)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new $p)}_onDisconnect(s,n){this._eventEmitter.dispatchEvent(new wp({eventString:s,allowClickToReconnect:n}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new fp)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new gp)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new yp)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new Sp),this._videoStartTime=Date.now()}_onLatencyTestResult(s){this._eventEmitter.dispatchEvent(new Op({latencyTimings:s}))}_onDataChannelLatencyTestResponse(s){this._eventEmitter.dispatchEvent(new zp({response:s}))}_onVideoStats(s){this._videoStartTime&&this._videoStartTime!==void 0||(this._videoStartTime=Date.now()),s.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new Ip({aggregatedStats:s}))}_onVideoEncoderAvgQP(s){this._eventEmitter.dispatchEvent(new hp({avgQP:s}))}_onInitialSettings(s){var n;this._eventEmitter.dispatchEvent(new Lp({settings:s})),s.PixelStreamingSettings&&(this.allowConsoleCommands=(n=s.PixelStreamingSettings.AllowPixelStreamingCommands)!==null&&n!==void 0&&n,this.allowConsoleCommands===!1&&b.Info(b.GetStackTrace(),"-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const d=this.config.useUrlParams,g=new URLSearchParams(window.location.search);b.Info(b.GetStackTrace(),`using URL parameters ${d}`),s.EncoderSettings&&(this.config.setNumericSetting(oe.MinQP,d&&g.has(oe.MinQP)?Number.parseFloat(g.get(oe.MinQP)):s.EncoderSettings.MinQP),this.config.setNumericSetting(oe.MaxQP,d&&g.has(oe.MaxQP)?Number.parseFloat(g.get(oe.MaxQP)):s.EncoderSettings.MaxQP)),s.WebRTCSettings&&(this.config.setNumericSetting(oe.WebRTCMinBitrate,d&&g.has(oe.WebRTCMinBitrate)?Number.parseFloat(g.get(oe.WebRTCMinBitrate)):s.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(oe.WebRTCMaxBitrate,d&&g.has(oe.WebRTCMaxBitrate)?Number.parseFloat(g.get(oe.WebRTCMaxBitrate)):s.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(oe.WebRTCFPS,d&&g.has(oe.WebRTCFPS)?Number.parseFloat(g.get(oe.WebRTCFPS)):s.WebRTCSettings.FPS))}_onQualityControlOwnership(s){this.config.setFlagEnabled(j.IsQualityController,s)}_onPlayerCount(s){this._eventEmitter.dispatchEvent(new Up({count:s}))}_setupWebRtcTCPRelayDetection(s){let n=s.data.aggregatedStats.getActiveCandidatePair();if(n!=null){let d=s.data.aggregatedStats.localCandidates.find((g=>g.id==n.localCandidateId),null);d!=null&&d.candidateType=="relay"&&d.relayProtocol=="tcp"&&this._eventEmitter.dispatchEvent(new Fp),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(s){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new ug(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(n=>{this._eventEmitter.dispatchEvent(new Dp({result:n}))})),this.addEventListener("dataChannelLatencyTestResponse",(({data:{response:n}})=>{this._dataChannelLatencyTestController.receive(n)}))),this._dataChannelLatencyTestController.start(s))}requestShowFps(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendShowFps(),!0)}requestIframe(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendIframeRequest(),!0)}emitUIInteraction(s){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.emitUIInteraction(s),!0)}emitCommand(s){return!(!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in s||(this._webRtcController.emitCommand(s),0))}emitConsoleCommand(s){return!(!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()||(this._webRtcController.emitConsoleCommand(s),0))}addResponseEventListener(s,n){this._webRtcController.responseController.addResponseEventListener(s,n)}removeResponseEventListener(s){this._webRtcController.responseController.removeResponseEventListener(s)}dispatchEvent(s){return this._eventEmitter.dispatchEvent(s)}addEventListener(s,n){this._eventEmitter.addEventListener(s,n)}removeEventListener(s,n){this._eventEmitter.removeEventListener(s,n)}toggleXR(){this.webXrController.xrClicked()}setSignallingUrlBuilder(s){this._webRtcController.signallingUrlBuilder=s}get webSocketController(){return this._webRtcController.webSocketController}get webXrController(){return this._webXrController}registerMessageHandler(s,n,d){n!==we.FromStreamer||d!==void 0?n===we.ToStreamer&&d===void 0?this._webRtcController.streamMessageController.registerMessageHandler(n,s,(g=>this._webRtcController.sendMessageController.sendMessageToStreamer(s,g))):this._webRtcController.streamMessageController.registerMessageHandler(n,s,(g=>d(g))):b.Warning(b.GetStackTrace(),`Unable to register an undefined handler for ${s}`)}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}}class cg{}pe.Dz;pe.g$;pe.Lt;pe.Q9;pe.qf;pe.hV;pe.z$;pe.J0;var hg=pe.De;pe.$C;pe.al;pe._W;pe.Gv;pe.m;pe.tz;pe.Nu;pe.zg;pe.vp;pe.vU;pe.wF;pe.rv;pe.Nh;pe.ss;pe.qW;pe.QL;pe.cf;pe.eM;pe.Yd;pe.Tk;pe.iM;pe.qy;pe.ce;pe.sK;pe.Ok;pe.q5;var pg=pe.g;pe.xl;pe.I;pe.bx;pe.dD;pe.Ib;pe.Az;pe.Iw;pe.qY;pe.db;pe.mR;pe.Tn;pe.rV;pe.gh;pe.Mi;pe.j;pe.YB;pe.Yt;pe.i5;pe.x_;pe.Am;pe.eR;pe.r8;pe.u3;pe.vd;pe.iV;pe.jZ;pe.SW;pe.ZH;pe.Ni;pe.lh;pe.ZP;pe.bq;pe.$f;pe.eu;pe.Ax;pe.Mc;const tm=({signallingUrl:S,autoConnect:s=!0,width:n,height:d,onConnecting:g,onLoading:E,onConnected:A,onDisconnected:O,onError:T,muted:K=!1})=>{const G=Ke.useRef(null),ae=Ke.useRef(null),J=Ke.useRef(!1),[ie,re]=Ke.useState(!1),[ne,fe]=Ke.useState(!1),[Re,Pe]=Ke.useState(null);return Ke.useEffect(()=>{if(!(!G.current||!S)){g&&g(),process.env.NODE_ENV==="development"&&console.log("Initializing Epic Pixel Streaming with URL:",S),"mediaDevices"in navigator||Object.defineProperty(navigator,"mediaDevices",{value:{}}),navigator.mediaDevices.getUserMedia||(navigator.mediaDevices.getUserMedia=function(){return Promise.reject(new Error("getUserMedia is not supported"))});try{const ce=new hg({useUrlParams:!1,initialSettings:{ss:S,AutoConnect:s,AutoPlayVideo:!0,StartVideoMuted:K,UseMic:!1,HoveringMouse:!1,FakeMouseWithTouches:!0,TouchInput:!1,MouseInput:!1,KeyboardInput:!1,WaitForStreamer:!0}}),le=new pg(ce,{videoElementParent:G.current});le.addEventListener("webRtcConnected",()=>{J.current=!0,re(!0),fe(!1),Pe(null),A?.()}),le.addEventListener("webRtcDisconnected",()=>{J.current=!1,re(!1),O?.()}),le.addEventListener("streamLoading",()=>{fe(!0),E?.()}),le.addEventListener("playStreamError",()=>{Pe("Failed to play stream"),fe(!1),T?.("Failed to play stream")}),le.addEventListener("playStream",()=>{fe(!1),J.current||(J.current=!0,re(!0),A?.())}),le.addEventListener("videoInitialized",()=>{fe(!1)}),ae.current=le}catch(ce){process.env.NODE_ENV==="development"&&console.error("Failed to initialize Pixel Streaming:",ce),Pe("Failed to initialize streaming: "+ce.message),fe(!1),T?.(ce.message)}return()=>{if(ae.current){try{const ce=ae.current;ce._webSocketController&&ce._webSocketController.close(),ae.current.disconnect()}catch(ce){process.env.NODE_ENV==="development"&&console.error("Error during cleanup:",ce)}ae.current=null}}}},[S,s,g,E,A,O,T]),Ke.useEffect(()=>{if(ae.current)try{const le=ae.current._webRtcController?.videoPlayer;if(!le)return;let ye=!1;if(le.audioElement){const We=le.audioElement.srcObject;if(We){const de=We.getAudioTracks();de.length>0&&(de.forEach(st=>{st.enabled=!K}),ye=!0)}}const me=le.getVideoElement();if(me&&me.srcObject&&me.srcObject instanceof MediaStream){const de=me.srcObject.getAudioTracks();de.length>0&&(de.forEach(st=>{st.enabled=!K}),ye=!0)}!ye&&me&&(me.muted=K)}catch(ce){process.env.NODE_ENV==="development"&&console.error("Error controlling audio:",ce)}},[K]),xr.jsxs("div",{className:"pixel-streaming-container",style:{width:n||"100%",height:d||"100%",position:"relative",display:"flex",flexDirection:"column",touchAction:"none",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},children:[xr.jsx("div",{ref:G,className:"player-container",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"hidden",touchAction:"none"}}),ne&&xr.jsxs("div",{className:"loading-overlay",children:[xr.jsx("div",{className:"loading-spinner"}),xr.jsx("div",{className:"loading-text",children:"Connecting to stream..."})]}),!ie&&!ne&&Re&&xr.jsx("div",{className:"connection-overlay",children:xr.jsx("div",{className:"error-message",children:Re})})]})};function rm({className:S,style:s,autoConnect:n=!0,muted:d=!1,onConnected:g,onDisconnected:E,onError:A}){const{streamingUrl:O,setCloudStreamState:T}=Xh();if(!O)return null;const K=()=>{T(zt.CLOUD_STREAM_STATE.CONNECTING)},G=()=>{T(zt.CLOUD_STREAM_STATE.LOADING)},ae=()=>{T(zt.CLOUD_STREAM_STATE.CONNECTED),g?.()},J=()=>{T(zt.CLOUD_STREAM_STATE.DISCONNECTED),E?.()},ie=re=>{T(zt.CLOUD_STREAM_STATE.ERROR,re),A?.(re)};return xr.jsx("div",{className:S,style:s,children:xr.jsx(tm,{signallingUrl:O,autoConnect:n,muted:d,onConnecting:K,onLoading:G,onConnected:ae,onDisconnected:J,onError:ie})})}const mg=Object.freeze(Object.defineProperty({__proto__:null,RqmiiCloudAvatarPlayer:rm},Symbol.toStringTag,{value:"Module"}));exports.EpicPixelStreamingPlayer=tm;exports.RqmiiCloudAvatarPlayer=rm;exports.RqmiiCloudAvatarPlayer$1=mg;exports.useRqmiiAvatar=Xh;exports.useRqmiiEvents=yf;exports.useRqmiiVAD=gf;exports.useRqmiiVoice=ef;
|
|
2918
|
+
//# sourceMappingURL=RqmiiCloudAvatarPlayer-CmovoCKk.cjs.map
|