@rqmii_immersive/agent-react-sdk 5.0.4 → 5.0.5
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/{RqmiiCloudAvatarPlayer-CS7A0FHP.js → RqmiiCloudAvatarPlayer-CzYyyu9R.js} +2968 -2915
- package/dist/RqmiiCloudAvatarPlayer-CzYyyu9R.js.map +1 -0
- package/dist/{RqmiiCloudAvatarPlayer-_YWFwrMm.cjs → RqmiiCloudAvatarPlayer-DGywLDgp.cjs} +335 -335
- package/dist/RqmiiCloudAvatarPlayer-DGywLDgp.cjs.map +1 -0
- package/dist/agent-react-sdk.css +1 -1
- package/dist/core/constants.d.ts +2 -0
- package/dist/core/constants.d.ts.map +1 -1
- package/dist/core/managers/session.d.ts +5 -0
- package/dist/core/managers/session.d.ts.map +1 -1
- package/dist/hooks/use-rqmii-connection.d.ts.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +43 -47
- package/dist/index.js.map +1 -1
- package/dist/provider/RqmiiAgentProvider.d.ts.map +1 -1
- package/dist/provider/socket-handlers.d.ts.map +1 -1
- package/dist/provider/use-manager-lifecycle.d.ts +5 -0
- package/dist/provider/use-manager-lifecycle.d.ts.map +1 -1
- package/dist/types/index.d.ts +30 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-content.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-text-and-voice.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-text.d.ts.map +1 -1
- package/dist/ui/chat/primitives.d.ts +9 -1
- package/dist/ui/chat/primitives.d.ts.map +1 -1
- package/dist/ui/chat/utils.d.ts +3 -0
- package/dist/ui/chat/utils.d.ts.map +1 -1
- package/dist/ui/languages/translations/af.d.ts.map +1 -1
- package/dist/ui/languages/translations/ar.d.ts.map +1 -1
- package/dist/ui/languages/translations/az.d.ts.map +1 -1
- package/dist/ui/languages/translations/be.d.ts.map +1 -1
- package/dist/ui/languages/translations/bg.d.ts.map +1 -1
- package/dist/ui/languages/translations/bn.d.ts.map +1 -1
- package/dist/ui/languages/translations/bs.d.ts.map +1 -1
- package/dist/ui/languages/translations/ca.d.ts.map +1 -1
- package/dist/ui/languages/translations/cs.d.ts.map +1 -1
- package/dist/ui/languages/translations/cy.d.ts.map +1 -1
- package/dist/ui/languages/translations/da.d.ts.map +1 -1
- package/dist/ui/languages/translations/de.d.ts.map +1 -1
- package/dist/ui/languages/translations/el.d.ts.map +1 -1
- package/dist/ui/languages/translations/en.d.ts.map +1 -1
- package/dist/ui/languages/translations/es.d.ts.map +1 -1
- package/dist/ui/languages/translations/et.d.ts.map +1 -1
- package/dist/ui/languages/translations/eu.d.ts.map +1 -1
- package/dist/ui/languages/translations/fa.d.ts.map +1 -1
- package/dist/ui/languages/translations/fi.d.ts.map +1 -1
- package/dist/ui/languages/translations/fr.d.ts.map +1 -1
- package/dist/ui/languages/translations/gl.d.ts.map +1 -1
- package/dist/ui/languages/translations/gu.d.ts.map +1 -1
- package/dist/ui/languages/translations/hi.d.ts.map +1 -1
- package/dist/ui/languages/translations/hr.d.ts.map +1 -1
- package/dist/ui/languages/translations/hu.d.ts.map +1 -1
- package/dist/ui/languages/translations/id.d.ts.map +1 -1
- package/dist/ui/languages/translations/it.d.ts.map +1 -1
- package/dist/ui/languages/translations/ja.d.ts.map +1 -1
- package/dist/ui/languages/translations/kk.d.ts.map +1 -1
- package/dist/ui/languages/translations/kn.d.ts.map +1 -1
- package/dist/ui/languages/translations/ko.d.ts.map +1 -1
- package/dist/ui/languages/translations/lt.d.ts.map +1 -1
- package/dist/ui/languages/translations/lv.d.ts.map +1 -1
- package/dist/ui/languages/translations/mk.d.ts.map +1 -1
- package/dist/ui/languages/translations/ml.d.ts.map +1 -1
- package/dist/ui/languages/translations/mr.d.ts.map +1 -1
- package/dist/ui/languages/translations/ms.d.ts.map +1 -1
- package/dist/ui/languages/translations/nl.d.ts.map +1 -1
- package/dist/ui/languages/translations/no.d.ts.map +1 -1
- package/dist/ui/languages/translations/pa.d.ts.map +1 -1
- package/dist/ui/languages/translations/pl.d.ts.map +1 -1
- package/dist/ui/languages/translations/pt.d.ts.map +1 -1
- package/dist/ui/languages/translations/ro.d.ts.map +1 -1
- package/dist/ui/languages/translations/ru.d.ts.map +1 -1
- package/dist/ui/languages/translations/sk.d.ts.map +1 -1
- package/dist/ui/languages/translations/sl.d.ts.map +1 -1
- package/dist/ui/languages/translations/sq.d.ts.map +1 -1
- package/dist/ui/languages/translations/sr.d.ts.map +1 -1
- package/dist/ui/languages/translations/sv.d.ts.map +1 -1
- package/dist/ui/languages/translations/sw.d.ts.map +1 -1
- package/dist/ui/languages/translations/ta.d.ts.map +1 -1
- package/dist/ui/languages/translations/te.d.ts.map +1 -1
- package/dist/ui/languages/translations/th.d.ts.map +1 -1
- package/dist/ui/languages/translations/tl.d.ts.map +1 -1
- package/dist/ui/languages/translations/tr.d.ts.map +1 -1
- package/dist/ui/languages/translations/uk.d.ts.map +1 -1
- package/dist/ui/languages/translations/ur.d.ts.map +1 -1
- package/dist/ui/languages/translations/vi.d.ts.map +1 -1
- package/dist/ui/languages/translations/zh.d.ts.map +1 -1
- package/dist/ui/languages/types.d.ts +8 -0
- package/dist/ui/languages/types.d.ts.map +1 -1
- package/dist/ui.cjs +21 -21
- package/dist/ui.cjs.map +1 -1
- package/dist/ui.js +1655 -1104
- package/dist/ui.js.map +1 -1
- package/package.json +1 -1
- package/dist/RqmiiCloudAvatarPlayer-CS7A0FHP.js.map +0 -1
- package/dist/RqmiiCloudAvatarPlayer-_YWFwrMm.cjs.map +0 -1
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
"use strict";const oe=require("react"),Jt=require("react/jsx-runtime"),di={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},_r={CONNECT:"connect",DISCONNECT:"disconnect",CONNECT_ERROR:"connect_error",SESSION_READY:"session_ready",SESSION_JOINED:"session_joined",SESSION_TERMINATED:"session_terminated",USER_MESSAGE:"user_message",AUDIO_CHUNK:"audio_chunk",AUDIO_END:"audio_end",INTERRUPT:"interrupt",CHANGE_SESSION_LANGUAGE:"change_session_language",LANGUAGE_CHANGED:"language_changed",CLIENT_READY:"client_ready",CLIENT_TOOL_REQUEST:"client_tool_request",CLIENT_TOOL_RESULT:"client_tool_result",CLEAR_SESSION_HISTORY:"clear_session_history",TRANSCRIPT:"transcript",PARTIAL_TRANSCRIPT:"partial_transcript",AGENT_RESPONSE_CHUNK:"agent_response_chunk",AGENT_RESPONSE:"agent_response",AGENT_AUDIO_CHUNK:"agent_audio_chunk",AGENT_AUDIO_COMPLETE:"agent_audio_complete",AVATAR_SPEAKING:"avatar_speaking",AVATAR_SPEAKING_DONE:"avatar_speaking_done",INTERRUPTED:"interrupted",ERROR:"error",AUTH_ERROR:"auth_error",SESSION_EXPIRED:"session_expired",CREDITS_EXHAUSTED:"credits_exhausted",SESSION_STATE_CHANGED:"session:state_changed",AUDIO_PLAYBACK_COMPLETE:"audio:playback_complete"},ft={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",FAILED:"failed",ENDED:"ended"},Zt={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},Bs={IDLE:"idle",USER_SPEAKING:"user_speaking",AGENT_THINKING:"agent_thinking",AGENT_SPEAKING:"agent_speaking",TOOL_EXECUTING:"tool_executing",TERMINATING:"terminating",TERMINATED:"terminated"},Gp={encoding:"16bitInt",channels:1,sampleRate:16e3},po={connectionState:ft.IDLE,isConnected:!1,isSessionReady:!1,error:null,isAudioPlaying:!1,isAvatarSpeaking:!1,sessionState:Bs.IDLE,cloudStream:{state:Zt.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[],creditExhausted:!1,creditError:null,agentConfig:null};function hp(d,r){switch(r.type){case"SET_CONNECTION_STATE":return{...d,connectionState:r.payload,isConnected:r.payload===ft.CONNECTED};case"SET_ERROR":return{...d,error:r.payload};case"SET_CLOUD_STREAM_STATE":return{...d,cloudStream:r.payload};case"SET_SESSION_STATE":return{...d,sessionState:r.payload};case"UPDATE_SESSION":return{...d,session:{...d.session,...r.payload}};case"ADD_MESSAGE":return{...d,messages:[...d.messages,r.payload]};case"SET_AUDIO_PLAYING":return{...d,isAudioPlaying:r.payload};case"SET_AVATAR_SPEAKING":return{...d,isAvatarSpeaking:r.payload};case"SET_CREDIT_EXHAUSTED":return{...d,creditExhausted:r.payload.exhausted,creditError:r.payload.error};case"SET_TRANSCRIPT":return{...d,transcript:r.payload};case"SET_PARTIAL_TRANSCRIPT":return{...d,partialTranscript:r.payload};case"SET_MESSAGES":return{...d,messages:r.payload};case"SET_SESSION_READY":return{...d,isSessionReady:r.payload};case"SET_AGENT_CONFIG":return{...d,agentConfig:r.payload};case"HARD_RESET":return po;case"REPLACE_STATE":return r.payload;default:return d}}function cg(d){return{isSessionTerminated:d===Bs.TERMINATED,isSessionTerminating:d===Bs.TERMINATING,isAgentThinking:d===Bs.AGENT_THINKING,isAgentSpeaking:d===Bs.AGENT_SPEAKING,isToolExecuting:d===Bs.TOOL_EXECUTING}}function hg(){const d=new Map;return{addChunk(r,s){const a=r||`request-${Date.now()}`,_=`${d.get(a)||""}${s||""}`;return d.set(a,_),{id:a,text:_}},consume(r,s=""){const a=r||`request-${Date.now()}`,f=d.get(a)||s||"";return d.delete(a),{id:a,text:f}},clear(){d.clear()}}}function pg(){try{const d=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof d=="string"&&d.trim()?d.trim():void 0}catch{return}}async function Ii(d){if(!d?.ok){let r=`HTTP ${d.status}`;try{const f=await d.json();r=f?.detail||f?.message||r}catch{}const s=new Error(r);throw s.status=d.status,s}return d.json()}function fg({restUrl:d,log:r,withCredentials:s}){function a(){if(!d)throw new Error("Missing restUrl in RqmiiAgentProvider")}async function f({apiKey:b,publicChatId:U,agentId:z,userId:re,language:K="en",timezone:se,config:J}={}){a();const Y={...b?{api_key:b}:{},...U?{public_chat_id:U}:{},...z?{agent_id:z}:{},...re?{user_id:re}:{},language:K,...se?{timezone:se}:{},...J?{config:J}:{}};r("initializeSession — POST /sessions/init",Y);const H=await fetch(`${d}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y),...s?{credentials:"include"}:{}}),ne=await Ii(H);if(!ne?.session_id||!ne?.session_token)throw new Error("Invalid initialize session response");return ne}async function _({uniqueId:b}){a(),r("joinDesktopSession — POST /sessions/join",{uniqueId:b});const U=await fetch(`${d}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:b}),...s?{credentials:"include"}:{}}),z=await Ii(U);if(!z?.session_id||!z?.session_token)throw new Error("Invalid join session response");return z}async function C(b){a(),r("fetchAgentConfig — GET /agent/{publicChatId}",{publicChatId:b});const U=await fetch(`${d}/agent/${encodeURIComponent(b)}`,{method:"GET",headers:{"Content-Type":"application/json"},...s?{credentials:"include"}:{}});return Ii(U)}async function R({sessionId:b,rating:U,feedback:z,endedBy:re}){if(a(),!b)throw new Error("sessionId is required");const K={...typeof U=="number"?{rating:U}:{},...z?{feedback:z}:{},...re?{ended_by:re}:{}};r("submitFeedback — PATCH /conversations/{sessionId}/feedback",{sessionId:b,payload:K});const se=await fetch(`${d}/conversations/${encodeURIComponent(b)}/feedback`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(K),...s?{credentials:"include"}:{}});return Ii(se)}return{initializeSession:f,joinDesktopSession:_,fetchAgentConfig:C,submitFeedback:R}}const Or=Object.create(null);Or.open="0";Or.close="1";Or.ping="2";Or.pong="3";Or.message="4";Or.upgrade="5";Or.noop="6";const Di=Object.create(null);Object.keys(Or).forEach(d=>{Di[Or[d]]=d});const fo={type:"error",data:"parser error"},qp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Wp=typeof ArrayBuffer=="function",Hp=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d&&d.buffer instanceof ArrayBuffer,xo=({type:d,data:r},s,a)=>qp&&r instanceof Blob?s?a(r):pp(r,a):Wp&&(r instanceof ArrayBuffer||Hp(r))?s?a(r):pp(new Blob([r]),a):a(Or[d]+(r||"")),pp=(d,r)=>{const s=new FileReader;return s.onload=function(){const a=s.result.split(",")[1];r("b"+(a||""))},s.readAsDataURL(d)};function fp(d){return d instanceof Uint8Array?d:d instanceof ArrayBuffer?new Uint8Array(d):new Uint8Array(d.buffer,d.byteOffset,d.byteLength)}let Ya;function mg(d,r){if(qp&&d.data instanceof Blob)return d.data.arrayBuffer().then(fp).then(r);if(Wp&&(d.data instanceof ArrayBuffer||Hp(d.data)))return r(fp(d.data));xo(d,!1,s=>{Ya||(Ya=new TextEncoder),r(Ya.encode(s))})}const mp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oi=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let d=0;d<mp.length;d++)oi[mp.charCodeAt(d)]=d;const gg=d=>{let r=d.length*.75,s=d.length,a,f=0,_,C,R,b;d[d.length-1]==="="&&(r--,d[d.length-2]==="="&&r--);const U=new ArrayBuffer(r),z=new Uint8Array(U);for(a=0;a<s;a+=4)_=oi[d.charCodeAt(a)],C=oi[d.charCodeAt(a+1)],R=oi[d.charCodeAt(a+2)],b=oi[d.charCodeAt(a+3)],z[f++]=_<<2|C>>4,z[f++]=(C&15)<<4|R>>2,z[f++]=(R&3)<<6|b&63;return U},yg=typeof ArrayBuffer=="function",Co=(d,r)=>{if(typeof d!="string")return{type:"message",data:Kp(d,r)};const s=d.charAt(0);return s==="b"?{type:"message",data:wg(d.substring(1),r)}:Di[s]?d.length>1?{type:Di[s],data:d.substring(1)}:{type:Di[s]}:fo},wg=(d,r)=>{if(yg){const s=gg(d);return Kp(s,r)}else return{base64:!0,data:d}},Kp=(d,r)=>{switch(r){case"blob":return d instanceof Blob?d:new Blob([d]);case"arraybuffer":default:return d instanceof ArrayBuffer?d:d.buffer}},jp="",vg=(d,r)=>{const s=d.length,a=new Array(s);let f=0;d.forEach((_,C)=>{xo(_,!1,R=>{a[C]=R,++f===s&&r(a.join(jp))})})},_g=(d,r)=>{const s=d.split(jp),a=[];for(let f=0;f<s.length;f++){const _=Co(s[f],r);if(a.push(_),_.type==="error")break}return a};function bg(){return new TransformStream({transform(d,r){mg(d,s=>{const a=s.length;let f;if(a<126)f=new Uint8Array(1),new DataView(f.buffer).setUint8(0,a);else if(a<65536){f=new Uint8Array(3);const _=new DataView(f.buffer);_.setUint8(0,126),_.setUint16(1,a)}else{f=new Uint8Array(9);const _=new DataView(f.buffer);_.setUint8(0,127),_.setBigUint64(1,BigInt(a))}d.data&&typeof d.data!="string"&&(f[0]|=128),r.enqueue(f),r.enqueue(s)})}})}let Ja;function Mi(d){return d.reduce((r,s)=>r+s.length,0)}function Pi(d,r){if(d[0].length===r)return d.shift();const s=new Uint8Array(r);let a=0;for(let f=0;f<r;f++)s[f]=d[0][a++],a===d[0].length&&(d.shift(),a=0);return d.length&&a<d[0].length&&(d[0]=d[0].slice(a)),s}function Sg(d,r){Ja||(Ja=new TextDecoder);const s=[];let a=0,f=-1,_=!1;return new TransformStream({transform(C,R){for(s.push(C);;){if(a===0){if(Mi(s)<1)break;const b=Pi(s,1);_=(b[0]&128)===128,f=b[0]&127,f<126?a=3:f===126?a=1:a=2}else if(a===1){if(Mi(s)<2)break;const b=Pi(s,2);f=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(Mi(s)<8)break;const b=Pi(s,8),U=new DataView(b.buffer,b.byteOffset,b.length),z=U.getUint32(0);if(z>Math.pow(2,21)-1){R.enqueue(fo);break}f=z*Math.pow(2,32)+U.getUint32(4),a=3}else{if(Mi(s)<f)break;const b=Pi(s,f);R.enqueue(Co(_?b:Ja.decode(b),r)),a=0}if(f===0||f>d){R.enqueue(fo);break}}}})}const Qp=4;function $t(d){if(d)return Tg(d)}function Tg(d){for(var r in $t.prototype)d[r]=$t.prototype[r];return d}$t.prototype.on=$t.prototype.addEventListener=function(d,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+d]=this._callbacks["$"+d]||[]).push(r),this};$t.prototype.once=function(d,r){function s(){this.off(d,s),r.apply(this,arguments)}return s.fn=r,this.on(d,s),this};$t.prototype.off=$t.prototype.removeListener=$t.prototype.removeAllListeners=$t.prototype.removeEventListener=function(d,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var s=this._callbacks["$"+d];if(!s)return this;if(arguments.length==1)return delete this._callbacks["$"+d],this;for(var a,f=0;f<s.length;f++)if(a=s[f],a===r||a.fn===r){s.splice(f,1);break}return s.length===0&&delete this._callbacks["$"+d],this};$t.prototype.emit=function(d){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),s=this._callbacks["$"+d],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if(s){s=s.slice(0);for(var a=0,f=s.length;a<f;++a)s[a].apply(this,r)}return this};$t.prototype.emitReserved=$t.prototype.emit;$t.prototype.listeners=function(d){return this._callbacks=this._callbacks||{},this._callbacks["$"+d]||[]};$t.prototype.hasListeners=function(d){return!!this.listeners(d).length};const Vi=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,s)=>s(r,0),lr=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Eg="arraybuffer";function Xp(d,...r){return r.reduce((s,a)=>(d.hasOwnProperty(a)&&(s[a]=d[a]),s),{})}const $g=lr.setTimeout,xg=lr.clearTimeout;function Gi(d,r){r.useNativeTimers?(d.setTimeoutFn=$g.bind(lr),d.clearTimeoutFn=xg.bind(lr)):(d.setTimeoutFn=lr.setTimeout.bind(lr),d.clearTimeoutFn=lr.clearTimeout.bind(lr))}const Cg=1.33;function kg(d){return typeof d=="string"?Rg(d):Math.ceil((d.byteLength||d.size)*Cg)}function Rg(d){let r=0,s=0;for(let a=0,f=d.length;a<f;a++)r=d.charCodeAt(a),r<128?s+=1:r<2048?s+=2:r<55296||r>=57344?s+=3:(a++,s+=4);return s}function Yp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ag(d){let r="";for(let s in d)d.hasOwnProperty(s)&&(r.length&&(r+="&"),r+=encodeURIComponent(s)+"="+encodeURIComponent(d[s]));return r}function Ig(d){let r={},s=d.split("&");for(let a=0,f=s.length;a<f;a++){let _=s[a].split("=");r[decodeURIComponent(_[0])]=decodeURIComponent(_[1])}return r}class Mg extends Error{constructor(r,s,a){super(r),this.description=s,this.context=a,this.type="TransportError"}}class ko extends $t{constructor(r){super(),this.writable=!1,Gi(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,s,a){return super.emitReserved("error",new Mg(r,s,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(r){this.readyState==="open"&&this.write(r)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(r){const s=Co(r,this.socket.binaryType);this.onPacket(s)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,s={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(s)}_hostname(){const r=this.opts.hostname;return r.indexOf(":")===-1?r:"["+r+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(r){const s=Ag(r);return s.length?"?"+s:""}}class Pg extends ko{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const s=()=>{this.readyState="paused",r()};if(this._polling||!this.writable){let a=0;this._polling&&(a++,this.once("pollComplete",function(){--a||s()})),this.writable||(a++,this.once("drain",function(){--a||s()}))}else s()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){const s=a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)};_g(r,this.socket.binaryType).forEach(s),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const r=()=>{this.write([{type:"close"}])};this.readyState==="open"?r():this.once("open",r)}write(r){this.writable=!1,vg(r,s=>{this.doWrite(s,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",s=this.query||{};return this.opts.timestampRequests!==!1&&(s[this.opts.timestampParam]=Yp()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(r,s)}}let Jp=!1;try{Jp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Og=Jp;function Dg(){}class zg extends Pg{constructor(r){if(super(r),typeof location<"u"){const s=location.protocol==="https:";let a=location.port;a||(a=s?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||a!==r.port}}doWrite(r,s){const a=this.request({method:"POST",data:r});a.on("success",s),a.on("error",(f,_)=>{this.onError("xhr post error",f,_)})}doPoll(){const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(s,a)=>{this.onError("xhr poll error",s,a)}),this.pollXhr=r}}class Pr extends $t{constructor(r,s,a){super(),this.createRequest=r,Gi(this,a),this._opts=a,this._method=a.method||"GET",this._uri=s,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var r;const s=Xp(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this._opts.xd;const a=this._xhr=this.createRequest(s);try{a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let f in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(f)&&a.setRequestHeader(f,this._opts.extraHeaders[f])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(r=this._opts.cookieJar)===null||r===void 0||r.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var f;a.readyState===3&&((f=this._opts.cookieJar)===null||f===void 0||f.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},a.send(this._data)}catch(f){this.setTimeoutFn(()=>{this._onError(f)},0);return}typeof document<"u"&&(this._index=Pr.requestsCount++,Pr.requests[this._index]=this)}_onError(r){this.emitReserved("error",r,this._xhr),this._cleanup(!0)}_cleanup(r){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Dg,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Pr.requests[this._index],this._xhr=null}}_onLoad(){const r=this._xhr.responseText;r!==null&&(this.emitReserved("data",r),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Pr.requestsCount=0;Pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",gp);else if(typeof addEventListener=="function"){const d="onpagehide"in lr?"pagehide":"unload";addEventListener(d,gp,!1)}}function gp(){for(let d in Pr.requests)Pr.requests.hasOwnProperty(d)&&Pr.requests[d].abort()}const Lg=(function(){const d=Zp({xdomain:!1});return d&&d.responseType!==null})();class Bg extends zg{constructor(r){super(r);const s=r&&r.forceBase64;this.supportsBinary=Lg&&!s}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Pr(Zp,this.uri(),r)}}function Zp(d){const r=d.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||Og))return new XMLHttpRequest}catch{}if(!r)try{return new lr[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ef=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Ng extends ko{get name(){return"websocket"}doOpen(){const r=this.uri(),s=this.opts.protocols,a=ef?{}:Xp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(r,s,a)}catch(f){return this.emitReserved("error",f)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=r=>this.onClose({description:"websocket connection closed",context:r}),this.ws.onmessage=r=>this.onData(r.data),this.ws.onerror=r=>this.onError("websocket error",r)}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],f=s===r.length-1;xo(a,this.supportsBinary,_=>{try{this.doWrite(a,_)}catch{}f&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const r=this.opts.secure?"wss":"ws",s=this.query||{};return this.opts.timestampRequests&&(s[this.opts.timestampParam]=Yp()),this.supportsBinary||(s.b64=1),this.createUri(r,s)}}const Za=lr.WebSocket||lr.MozWebSocket;class Ug extends Ng{createSocket(r,s,a){return ef?new Za(r,s,a):s?new Za(r,s):new Za(r)}doWrite(r,s){this.ws.send(s)}}class Fg extends ko{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(r){return this.emitReserved("error",r)}this._transport.closed.then(()=>{this.onClose()}).catch(r=>{this.onError("webtransport error",r)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(r=>{const s=Sg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(s).getReader(),f=bg();f.readable.pipeTo(r.writable),this._writer=f.writable.getWriter();const _=()=>{a.read().then(({done:R,value:b})=>{R||(this.onPacket(b),_())}).catch(R=>{})};_();const C={type:"open"};this.query.sid&&(C.data=`{"sid":"${this.query.sid}"}`),this._writer.write(C).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],f=s===r.length-1;this._writer.write(a).then(()=>{f&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const Vg={websocket:Ug,webtransport:Fg,polling:Bg},Gg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,qg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mo(d){if(d.length>8e3)throw"URI too long";const r=d,s=d.indexOf("["),a=d.indexOf("]");s!=-1&&a!=-1&&(d=d.substring(0,s)+d.substring(s,a).replace(/:/g,";")+d.substring(a,d.length));let f=Gg.exec(d||""),_={},C=14;for(;C--;)_[qg[C]]=f[C]||"";return s!=-1&&a!=-1&&(_.source=r,_.host=_.host.substring(1,_.host.length-1).replace(/;/g,":"),_.authority=_.authority.replace("[","").replace("]","").replace(/;/g,":"),_.ipv6uri=!0),_.pathNames=Wg(_,_.path),_.queryKey=Hg(_,_.query),_}function Wg(d,r){const s=/\/{2,9}/g,a=r.replace(s,"/").split("/");return(r.slice(0,1)=="/"||r.length===0)&&a.splice(0,1),r.slice(-1)=="/"&&a.splice(a.length-1,1),a}function Hg(d,r){const s={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,_){f&&(s[f]=_)}),s}const go=typeof addEventListener=="function"&&typeof removeEventListener=="function",zi=[];go&&addEventListener("offline",()=>{zi.forEach(d=>d())},!1);class as extends $t{constructor(r,s){if(super(),this.binaryType=Eg,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(s=r,r=null),r){const a=mo(r);s.hostname=a.host,s.secure=a.protocol==="https"||a.protocol==="wss",s.port=a.port,a.query&&(s.query=a.query)}else s.host&&(s.hostname=mo(s.host).host);Gi(this,s),this.secure=s.secure!=null?s.secure:typeof location<"u"&&location.protocol==="https:",s.hostname&&!s.port&&(s.port=this.secure?"443":"80"),this.hostname=s.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=s.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},s.transports.forEach(a=>{const f=a.prototype.name;this.transports.push(f),this._transportsByName[f]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},s),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ig(this.opts.query)),go&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},zi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const s=Object.assign({},this.opts.query);s.EIO=Qp,s.transport=r,this.id&&(s.sid=this.id);const a=Object.assign({},this.opts,{query:s,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[r]);return new this._transportsByName[r](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const r=this.opts.rememberUpgrade&&as.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const s=this.createTransport(r);s.open(),this.setTransport(s)}setTransport(r){this.transport&&this.transport.removeAllListeners(),this.transport=r,r.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",s=>this._onClose("transport close",s))}onOpen(){this.readyState="open",as.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",r),this.emitReserved("heartbeat"),r.type){case"open":this.onHandshake(JSON.parse(r.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const s=new Error("server error");s.code=r.data,this._onError(s);break;case"message":this.emitReserved("data",r.data),this.emitReserved("message",r.data);break}}onHandshake(r){this.emitReserved("handshake",r),this.id=r.sid,this.transport.query.sid=r.sid,this._pingInterval=r.pingInterval,this._pingTimeout=r.pingTimeout,this._maxPayload=r.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const r=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+r,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},r),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const r=this._getWritablePackets();this.transport.send(r),this._prevBufferLen=r.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let s=1;for(let a=0;a<this.writeBuffer.length;a++){const f=this.writeBuffer[a].data;if(f&&(s+=kg(f)),a>0&&s>this._maxPayload)return this.writeBuffer.slice(0,a);s+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(this._pingTimeoutTime=0,Vi(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,s,a){return this._sendPacket("message",r,s,a),this}send(r,s,a){return this._sendPacket("message",r,s,a),this}_sendPacket(r,s,a,f){if(typeof s=="function"&&(f=s,s=void 0),typeof a=="function"&&(f=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;const _={type:r,data:s,options:a};this.emitReserved("packetCreate",_),this.writeBuffer.push(_),f&&this.once("flush",f),this.flush()}close(){const r=()=>{this._onClose("forced close"),this.transport.close()},s=()=>{this.off("upgrade",s),this.off("upgradeError",s),r()},a=()=>{this.once("upgrade",s),this.once("upgradeError",s)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():r()}):this.upgrading?a():r()),this}_onError(r){if(as.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",r),this._onClose("transport error",r)}_onClose(r,s){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),go&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=zi.indexOf(this._offlineEventListener);a!==-1&&zi.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,s),this.writeBuffer=[],this._prevBufferLen=0}}}as.protocol=Qp;class Kg extends as{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let r=0;r<this._upgrades.length;r++)this._probe(this._upgrades[r])}_probe(r){let s=this.createTransport(r),a=!1;as.priorWebsocketSuccess=!1;const f=()=>{a||(s.send([{type:"ping",data:"probe"}]),s.once("packet",re=>{if(!a)if(re.type==="pong"&&re.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;as.priorWebsocketSuccess=s.name==="websocket",this.transport.pause(()=>{a||this.readyState!=="closed"&&(z(),this.setTransport(s),s.send([{type:"upgrade"}]),this.emitReserved("upgrade",s),s=null,this.upgrading=!1,this.flush())})}else{const K=new Error("probe error");K.transport=s.name,this.emitReserved("upgradeError",K)}}))};function _(){a||(a=!0,z(),s.close(),s=null)}const C=re=>{const K=new Error("probe error: "+re);K.transport=s.name,_(),this.emitReserved("upgradeError",K)};function R(){C("transport closed")}function b(){C("socket closed")}function U(re){s&&re.name!==s.name&&_()}const z=()=>{s.removeListener("open",f),s.removeListener("error",C),s.removeListener("close",R),this.off("close",b),this.off("upgrading",U)};s.once("open",f),s.once("error",C),s.once("close",R),this.once("close",b),this.once("upgrading",U),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{a||s.open()},200):s.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const s=[];for(let a=0;a<r.length;a++)~this.transports.indexOf(r[a])&&s.push(r[a]);return s}}let jg=class extends Kg{constructor(r,s={}){const a=typeof r=="object"?r:s;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(f=>Vg[f]).filter(f=>!!f)),super(r,a)}};function Qg(d,r="",s){let a=d;s=s||typeof location<"u"&&location,d==null&&(d=s.protocol+"//"+s.host),typeof d=="string"&&(d.charAt(0)==="/"&&(d.charAt(1)==="/"?d=s.protocol+d:d=s.host+d),/^(https?|wss?):\/\//.test(d)||(typeof s<"u"?d=s.protocol+"//"+d:d="https://"+d),a=mo(d)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";const _=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+_+":"+a.port+r,a.href=a.protocol+"://"+_+(s&&s.port===a.port?"":":"+a.port),a}const Xg=typeof ArrayBuffer=="function",Yg=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d.buffer instanceof ArrayBuffer,tf=Object.prototype.toString,Jg=typeof Blob=="function"||typeof Blob<"u"&&tf.call(Blob)==="[object BlobConstructor]",Zg=typeof File=="function"||typeof File<"u"&&tf.call(File)==="[object FileConstructor]";function Ro(d){return Xg&&(d instanceof ArrayBuffer||Yg(d))||Jg&&d instanceof Blob||Zg&&d instanceof File}function Li(d,r){if(!d||typeof d!="object")return!1;if(Array.isArray(d)){for(let s=0,a=d.length;s<a;s++)if(Li(d[s]))return!0;return!1}if(Ro(d))return!0;if(d.toJSON&&typeof d.toJSON=="function"&&arguments.length===1)return Li(d.toJSON(),!0);for(const s in d)if(Object.prototype.hasOwnProperty.call(d,s)&&Li(d[s]))return!0;return!1}function ey(d){const r=[],s=d.data,a=d;return a.data=yo(s,r),a.attachments=r.length,{packet:a,buffers:r}}function yo(d,r){if(!d)return d;if(Ro(d)){const s={_placeholder:!0,num:r.length};return r.push(d),s}else if(Array.isArray(d)){const s=new Array(d.length);for(let a=0;a<d.length;a++)s[a]=yo(d[a],r);return s}else if(typeof d=="object"&&!(d instanceof Date)){const s={};for(const a in d)Object.prototype.hasOwnProperty.call(d,a)&&(s[a]=yo(d[a],r));return s}return d}function ty(d,r){return d.data=wo(d.data,r),delete d.attachments,d}function wo(d,r){if(!d)return d;if(d&&d._placeholder===!0){if(typeof d.num=="number"&&d.num>=0&&d.num<r.length)return r[d.num];throw new Error("illegal attachments")}else if(Array.isArray(d))for(let s=0;s<d.length;s++)d[s]=wo(d[s],r);else if(typeof d=="object")for(const s in d)Object.prototype.hasOwnProperty.call(d,s)&&(d[s]=wo(d[s],r));return d}const ry=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Ye;(function(d){d[d.CONNECT=0]="CONNECT",d[d.DISCONNECT=1]="DISCONNECT",d[d.EVENT=2]="EVENT",d[d.ACK=3]="ACK",d[d.CONNECT_ERROR=4]="CONNECT_ERROR",d[d.BINARY_EVENT=5]="BINARY_EVENT",d[d.BINARY_ACK=6]="BINARY_ACK"})(Ye||(Ye={}));class sy{constructor(r){this.replacer=r}encode(r){return(r.type===Ye.EVENT||r.type===Ye.ACK)&&Li(r)?this.encodeAsBinary({type:r.type===Ye.EVENT?Ye.BINARY_EVENT:Ye.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let s=""+r.type;return(r.type===Ye.BINARY_EVENT||r.type===Ye.BINARY_ACK)&&(s+=r.attachments+"-"),r.nsp&&r.nsp!=="/"&&(s+=r.nsp+","),r.id!=null&&(s+=r.id),r.data!=null&&(s+=JSON.stringify(r.data,this.replacer)),s}encodeAsBinary(r){const s=ey(r),a=this.encodeAsString(s.packet),f=s.buffers;return f.unshift(a),f}}class Ao extends $t{constructor(r){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof r=="function"?{reviver:r}:r)}add(r){let s;if(typeof r=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");s=this.decodeString(r);const a=s.type===Ye.BINARY_EVENT;a||s.type===Ye.BINARY_ACK?(s.type=a?Ye.EVENT:Ye.ACK,this.reconstructor=new ny(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(Ro(r)||r.base64)if(this.reconstructor)s=this.reconstructor.takeBinaryData(r),s&&(this.reconstructor=null,super.emitReserved("decoded",s));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+r)}decodeString(r){let s=0;const a={type:Number(r.charAt(0))};if(Ye[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===Ye.BINARY_EVENT||a.type===Ye.BINARY_ACK){const _=s+1;for(;r.charAt(++s)!=="-"&&s!=r.length;);const C=r.substring(_,s);if(C!=Number(C)||r.charAt(s)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!iy(R)||R<0)throw new Error("Illegal attachments");if(R>this.opts.maxAttachments)throw new Error("too many attachments");a.attachments=R}if(r.charAt(s+1)==="/"){const _=s+1;for(;++s&&!(r.charAt(s)===","||s===r.length););a.nsp=r.substring(_,s)}else a.nsp="/";const f=r.charAt(s+1);if(f!==""&&Number(f)==f){const _=s+1;for(;++s;){const C=r.charAt(s);if(C==null||Number(C)!=C){--s;break}if(s===r.length)break}a.id=Number(r.substring(_,s+1))}if(r.charAt(++s)){const _=this.tryParse(r.substr(s));if(Ao.isPayloadValid(a.type,_))a.data=_;else throw new Error("invalid payload")}return a}tryParse(r){try{return JSON.parse(r,this.opts.reviver)}catch{return!1}}static isPayloadValid(r,s){switch(r){case Ye.CONNECT:return yp(s);case Ye.DISCONNECT:return s===void 0;case Ye.CONNECT_ERROR:return typeof s=="string"||yp(s);case Ye.EVENT:case Ye.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&ry.indexOf(s[0])===-1);case Ye.ACK:case Ye.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ny{constructor(r){this.packet=r,this.buffers=[],this.reconPack=r}takeBinaryData(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){const s=ty(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const iy=Number.isInteger||function(d){return typeof d=="number"&&isFinite(d)&&Math.floor(d)===d};function yp(d){return Object.prototype.toString.call(d)==="[object Object]"}const ay=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ao,Encoder:sy,get PacketType(){return Ye}},Symbol.toStringTag,{value:"Module"}));function br(d,r,s){return d.on(r,s),function(){d.off(r,s)}}const oy=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class rf extends $t{constructor(r,s,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=r,this.nsp=s,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const r=this.io;this.subs=[br(r,"open",this.onopen.bind(this)),br(r,"packet",this.onpacket.bind(this)),br(r,"error",this.onerror.bind(this)),br(r,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...s){var a,f,_;if(oy.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(s.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(s),this;const C={type:Ye.EVENT,data:s};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){const z=this.ids++,re=s.pop();this._registerAckCallback(z,re),C.id=z}const R=(f=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||f===void 0?void 0:f.writable,b=this.connected&&!(!((_=this.io.engine)===null||_===void 0)&&_._hasPingExpired());return this.flags.volatile&&!R||(b?(this.notifyOutgoingListeners(C),this.packet(C)):this.sendBuffer.push(C)),this.flags={},this}_registerAckCallback(r,s){var a;const f=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(f===void 0){this.acks[r]=s;return}const _=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let R=0;R<this.sendBuffer.length;R++)this.sendBuffer[R].id===r&&this.sendBuffer.splice(R,1);s.call(this,new Error("operation has timed out"))},f),C=(...R)=>{this.io.clearTimeoutFn(_),s.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...s){return new Promise((a,f)=>{const _=(C,R)=>C?f(C):a(R);_.withError=!0,s.push(_),this.emit(r,...s)})}_addToQueue(r){let s;typeof r[r.length-1]=="function"&&(s=r.pop());const a={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((f,..._)=>(this._queue[0],f!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),s&&s(f)):(this._queue.shift(),s&&s(null,..._)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(r=!1){if(!this.connected||this._queue.length===0)return;const s=this._queue[0];s.pending&&!r||(s.pending=!0,s.tryCount++,this.flags=s.flags,this.emit.apply(this,s.args))}packet(r){r.nsp=this.nsp,this.io._packet(r)}onopen(){typeof this.auth=="function"?this.auth(r=>{this._sendConnectPacket(r)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(r){this.packet({type:Ye.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},r):r})}onerror(r){this.connected||this.emitReserved("connect_error",r)}onclose(r,s){this.connected=!1,delete this.id,this.emitReserved("disconnect",r,s),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(r=>{if(!this.sendBuffer.some(a=>String(a.id)===r)){const a=this.acks[r];delete this.acks[r],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(r){if(r.nsp===this.nsp)switch(r.type){case Ye.CONNECT:r.data&&r.data.sid?this.onconnect(r.data.sid,r.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ye.EVENT:case Ye.BINARY_EVENT:this.onevent(r);break;case Ye.ACK:case Ye.BINARY_ACK:this.onack(r);break;case Ye.DISCONNECT:this.ondisconnect();break;case Ye.CONNECT_ERROR:this.destroy();const a=new Error(r.data.message);a.data=r.data.data,this.emitReserved("connect_error",a);break}}onevent(r){const s=r.data||[];r.id!=null&&s.push(this.ack(r.id)),this.connected?this.emitEvent(s):this.receiveBuffer.push(Object.freeze(s))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const s=this._anyListeners.slice();for(const a of s)a.apply(this,r)}super.emit.apply(this,r),this._pid&&r.length&&typeof r[r.length-1]=="string"&&(this._lastOffset=r[r.length-1])}ack(r){const s=this;let a=!1;return function(...f){a||(a=!0,s.packet({type:Ye.ACK,id:r,data:f}))}}onack(r){const s=this.acks[r.id];typeof s=="function"&&(delete this.acks[r.id],s.withError&&r.data.unshift(null),s.apply(this,r.data))}onconnect(r,s){this.id=r,this.recovered=s&&this._pid===s,this._pid=s,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(r=>this.emitEvent(r)),this.receiveBuffer=[],this.sendBuffer.forEach(r=>{this.notifyOutgoingListeners(r),this.packet(r)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(r=>r()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Ye.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const s=this._anyListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const s=this._anyOutgoingListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const s=this._anyOutgoingListeners.slice();for(const a of s)a.apply(this,r.data)}}}function un(d){d=d||{},this.ms=d.min||100,this.max=d.max||1e4,this.factor=d.factor||2,this.jitter=d.jitter>0&&d.jitter<=1?d.jitter:0,this.attempts=0}un.prototype.duration=function(){var d=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),s=Math.floor(r*this.jitter*d);d=(Math.floor(r*10)&1)==0?d-s:d+s}return Math.min(d,this.max)|0};un.prototype.reset=function(){this.attempts=0};un.prototype.setMin=function(d){this.ms=d};un.prototype.setMax=function(d){this.max=d};un.prototype.setJitter=function(d){this.jitter=d};class vo extends $t{constructor(r,s){var a;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(s=r,r=void 0),s=s||{},s.path=s.path||"/socket.io",this.opts=s,Gi(this,s),this.reconnection(s.reconnection!==!1),this.reconnectionAttempts(s.reconnectionAttempts||1/0),this.reconnectionDelay(s.reconnectionDelay||1e3),this.reconnectionDelayMax(s.reconnectionDelayMax||5e3),this.randomizationFactor((a=s.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new un({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(s.timeout==null?2e4:s.timeout),this._readyState="closed",this.uri=r;const f=s.parser||ay;this.encoder=new f.Encoder,this.decoder=new f.Decoder,this._autoConnect=s.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(r){return arguments.length?(this._reconnection=!!r,r||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(r){return r===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=r,this)}reconnectionDelay(r){var s;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(s=this.backoff)===null||s===void 0||s.setMin(r),this)}randomizationFactor(r){var s;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(s=this.backoff)===null||s===void 0||s.setJitter(r),this)}reconnectionDelayMax(r){var s;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(s=this.backoff)===null||s===void 0||s.setMax(r),this)}timeout(r){return arguments.length?(this._timeout=r,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(r){if(~this._readyState.indexOf("open"))return this;this.engine=new jg(this.uri,this.opts);const s=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const f=br(s,"open",function(){a.onopen(),r&&r()}),_=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=br(s,"error",_);if(this._timeout!==!1){const R=this._timeout,b=this.setTimeoutFn(()=>{f(),_(new Error("timeout")),s.close()},R);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(f),this.subs.push(C),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(br(r,"ping",this.onping.bind(this)),br(r,"data",this.ondata.bind(this)),br(r,"error",this.onerror.bind(this)),br(r,"close",this.onclose.bind(this)),br(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(s){this.onclose("parse error",s)}}ondecoded(r){Vi(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){this.emitReserved("error",r)}socket(r,s){let a=this.nsps[r];return a?this._autoConnect&&!a.active&&a.connect():(a=new rf(this,r,s),this.nsps[r]=a),a}_destroy(r){const s=Object.keys(this.nsps);for(const a of s)if(this.nsps[a].active)return;this._close()}_packet(r){const s=this.encoder.encode(r);for(let a=0;a<s.length;a++)this.engine.write(s[a],r.options)}cleanup(){this.subs.forEach(r=>r()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(r,s){var a;this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,s),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const r=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const s=this.backoff.duration();this._reconnecting=!0;const a=this.setTimeoutFn(()=>{r.skipReconnect||(this.emitReserved("reconnect_attempt",r.backoff.attempts),!r.skipReconnect&&r.open(f=>{f?(r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",f)):r.onreconnect()}))},s);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){const r=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",r)}}const Zn={};function Bi(d,r){typeof d=="object"&&(r=d,d=void 0),r=r||{};const s=Qg(d,r.path||"/socket.io"),a=s.source,f=s.id,_=s.path,C=Zn[f]&&_ in Zn[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let b;return R?b=new vo(a,r):(Zn[f]||(Zn[f]=new vo(a,r)),b=Zn[f]),s.query&&!r.query&&(r.query=s.queryKey),b.socket(s.path,r)}Object.assign(Bi,{Manager:vo,Socket:rf,io:Bi,connect:Bi});function ly({wsUrl:d,log:r}){let s=null;function a({authPayload:C,queryToken:R}){const b=Bi(d,{transports:["polling"],timeout:2e4,reconnection:!1,auth:C,query:R?{token:R}:void 0});return s=b,b}function f(){if(s){try{s.removeAllListeners(),s.connected?s.disconnect():s.close()}catch{}s=null}}function _(){return s}return{connectSocketRaw:a,cleanupSocket:f,getSocket:_}}const uy=d=>{if(window.audioCtx=d,d.state!=="suspended")return;const r=document.body,s=["touchstart","touchend","mousedown","keydown"];s.forEach(_=>r.addEventListener(_,a,!1));function a(){d.resume().then(f)}function f(){s.forEach(_=>r.removeEventListener(_,a))}};function Ot(d){this.init(d)}Ot.prototype.init=function(d){var r={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},r,d),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};Ot.prototype.getMaxValue=function(){var d={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ot.prototype.getTypedArray=function(){var d={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ot.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),uy(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Ot.prototype.resetState=function(){this.playingStartTime=-1,this.lastGotTimestamp=0,this.samples=new Float32Array,this.timeout=void 0,this.flag_request_stop=!1,this.startTime=0};Ot.prototype.isTypedArray=function(d){return d.byteLength&&d.buffer&&d.buffer.constructor==ArrayBuffer};Ot.prototype.feed=function(d){if(this.isTypedArray(d)){d=this.getFormatedValue(d);var r=new Float32Array(this.samples.length+d.length);r.set(this.samples,0),r.set(d,this.samples.length),this.samples=r,this.timeout||this.flush()}};Ot.prototype.getFormatedValue=function(r){var r=new this.typedArray(r.buffer),s=new Float32Array(r.length),a;for(a=0;a<r.length;a++)s[a]=r[a]/this.maxValue;return s};Ot.prototype.volume=function(d){this.gainNode.gain.value=d};Ot.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Ot.prototype.getTimestamp=function(d){if(this.playingStartTime>=0){if(!d)return this.audioCtx.currentTime-this.playingStartTime;const r=this.lastGotTimestamp;return this.lastGotTimestamp+=d/1e3,r}return 0};Ot.prototype.setRequestStop=function(){this.flag_request_stop=!0};Ot.prototype.setOnEnd=function(d){this.onEnd=d};Ot.prototype.interrupt=function(d){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};Ot.prototype.ensuredSetTimeout=(function(){let d;return function(r,s){d=performance.now();const a=f=>{f-d>=s?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Ot.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Ot.prototype.flush=function(){if(this.samples.length){var d=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,s=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,f,_,C,R;for(f=0;f<this.option.channels;f++)for(a=s.getChannelData(f),_=f,R=50,C=0;C<r;C++)a[C]=this.samples[_],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),_+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,d.buffer=s,d.connect(this.gainNode),d.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=d,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=s.duration,this.flag_request_stop)this.flag_request_stop=!1,d.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const b=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,b-50)}}};function dy(d,r){const s=new Ot(d),a=s.destroy.bind(s);let f=!1;return s.destroy=()=>{if(!f){f=!0;try{a()}catch{}}},s.setOnEnd(()=>{f||r()}),s._isDestroyed=()=>f,s}function cy({enableAudio:d,pcmOptions:r,log:s,onPlaybackComplete:a}){let f=null,_=null;function C(){if(!d||f)return f;const H={...Gp,...r||{}};return f=dy(H,()=>{a()}),f}function R(){if(f){try{f.interrupt?.(),f.destroy?.()}catch{}f=null}}function b(H){const ne=C();if(ne)try{ne.feed(H)}catch(ve){s("feedAudio: player.feed() failed",ve),a()}}function U(){if(!f){a();return}try{f.setRequestStop(),f.playingBufferNode||f.scheduledBufferNode||a()}catch(H){s("requestStop: setRequestStop() failed",H),a()}}function z(){R()}function re(){if(f)try{const H=f.audioCtx;H?.state==="running"&&H.suspend()}catch(H){s("pauseAudioPlayback: audioCtx.suspend() failed",H)}}async function K(){const H=C();if(H)try{const ne=H.audioCtx;ne?.state==="suspended"&&await ne.resume()}catch(ne){s("resumeAudioPlayback: audioCtx.resume() failed",ne)}}function se(H){_=H||null}function J(){return _}function Y(){return f?f._isDestroyed?.()??!0:!0}return{ensurePcmPlayer:C,destroyPcmPlayer:R,feedAudio:b,requestStop:U,interruptPlayback:z,pauseAudioPlayback:re,resumeAudioPlayback:K,attachAudioElement:se,getAudioElement:J,isDestroyed:Y}}function hy(d){const{wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:_,withCredentials:C,onPlaybackComplete:R}=d,b=oe.useCallback((...K)=>{_&&console.log("[RqmiiSDK]",...K)},[_]),U=oe.useRef(null),z=oe.useRef(null),re=oe.useRef(null);return U.current||(U.current=ly({wsUrl:r,log:b})),z.current||(z.current=cy({enableAudio:a,pcmOptions:f,log:b,onPlaybackComplete:R})),re.current||(re.current=fg({restUrl:s,log:b,withCredentials:C})),oe.useEffect(()=>()=>{U.current?.cleanupSocket(),z.current?.destroyPcmPlayer()},[]),{socketMgrRef:U,audioMgrRef:z,sessionMgrRef:re,log:b}}function eo(d){return String(d||"").toLowerCase().replaceAll("-","_")}function py(d){if(!d)return null;if(d instanceof Uint8Array)return d;if(d instanceof ArrayBuffer)return new Uint8Array(d);if(typeof d=="object"&&d!==null){const r=d;if(r.buffer instanceof ArrayBuffer){const s=d,a=Number.isInteger(s.byteOffset)?s.byteOffset:0,f=Number.isInteger(s.byteLength)?s.byteLength:s.buffer.byteLength-a;return new Uint8Array(s.buffer,a,f)}if(r.type==="Buffer"&&Array.isArray(r.data))return new Uint8Array(r.data)}try{return new Uint8Array(d)}catch{return null}}function fy(d){const{socket:r,dispatch:s,stateRef:a,sessionIdRef:f,sessionAgentTypeRef:_,interruptedRef:C,manualDisconnectRef:R,chunkAccumulatorRef:b,clientToolsRef:U,audioMgrRef:z,enableAudio:re,cbRefs:K,eventsEmitter:se}=d,J=_r,Y=z.current;r.on(J.DISCONNECT,H=>{if(s({type:"SET_CONNECTION_STATE",payload:ft.IDLE}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onDisconnect?.(H),H==="io server disconnect"||H==="io client disconnect"||R.current){s({type:"SET_CONNECTION_STATE",payload:ft.ENDED});return}s({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),s({type:"SET_ERROR",payload:"Connection lost"})}),r.on(J.SESSION_READY,H=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null}),H?.agentType&&s({type:"UPDATE_SESSION",payload:{agentType:eo(H.agentType)}})}),r.on(J.SESSION_JOINED,()=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null})}),r.on(J.SESSION_TERMINATED,()=>{Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onSessionTerminated?.(),r.disconnect()}),r.on(J.TRANSCRIPT,H=>{const ne=H||null;s({type:"SET_TRANSCRIPT",payload:ne}),ne?.is_final&&ne?.text?.trim()&&(s({type:"ADD_MESSAGE",payload:{id:`transcript-${Date.now()}`,role:"user",text:ne.text.trim(),timestamp:new Date().toISOString()}}),s({type:"SET_PARTIAL_TRANSCRIPT",payload:null})),se.emit("transcript",ne??void 0),se.emit("partial_transcript",void 0)}),r.on(J.PARTIAL_TRANSCRIPT,H=>{const ne=typeof H=="string"?H:H?.text;if(typeof ne=="string"&&ne.length===0)return;const ve=H||null;s({type:"SET_PARTIAL_TRANSCRIPT",payload:ve}),se.emit("partial_transcript",ve??void 0)}),r.on(J.AGENT_RESPONSE_CHUNK,H=>{const{id:ne,text:ve}=b.current.addChunk(H?.requestId,H?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==ne),{id:ne,role:"assistant",text:ve,streaming:!0,timestamp:new Date().toISOString()}]})}),r.on(J.AGENT_RESPONSE,H=>{const{id:ne,text:ve}=b.current.consume(H?.requestId,H?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==ne),{id:ne,role:"assistant",text:ve,streaming:!1,timestamp:new Date().toISOString()}]})}),r.on(J.AVATAR_SPEAKING,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!0})}),r.on(J.AVATAR_SPEAKING_DONE,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!1})}),r.on(J.AGENT_AUDIO_CHUNK,H=>{if(!re||C.current)return;const ne=eo(_.current);if(ne==="cloud_avatar"||ne==="desktop_avatar"||ne==="text")return;const ve=py(H?.audio);ve&&(Y.feedAudio(ve),s({type:"SET_AUDIO_PLAYING",payload:!0}))}),r.on(J.AGENT_AUDIO_COMPLETE,()=>{if(!re)return;const H=eo(_.current);H==="cloud_avatar"||H==="desktop_avatar"||H==="text"||Y.requestStop()}),r.on(J.INTERRUPTED,()=>{const H=!Y.isDestroyed();C.current=!1,Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),H&&r.connected&&r.emit(J.AUDIO_PLAYBACK_COMPLETE,{session_id:f.current})}),r.on(J.AUTH_ERROR,H=>{s({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),s({type:"SET_ERROR",payload:H?.message||"Authentication error"})}),r.on(J.ERROR,H=>{const ne=H?.code;if(!(ne==="TTS_ERROR"||ne==="STT_ERROR"||ne==="LLM_ERROR")){if(ne==="INSUFFICIENT_CREDITS"){s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:H?.message||"Insufficient credits to process this request."}}),K.current.onError?.(H);return}s({type:"SET_ERROR",payload:H?.message||H?.detail||"Server error"}),K.current.onError?.(H)}}),r.on(J.SESSION_EXPIRED,H=>{s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onSessionExpired?.(H)}),r.on(J.CREDITS_EXHAUSTED,()=>{s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:"This project has run out of credits."}}),s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),R.current=!0;try{r.disconnect()}catch{}}),r.on(J.SESSION_STATE_CHANGED,H=>{H?.state&&s({type:"SET_SESSION_STATE",payload:H.state})}),r.on(J.LANGUAGE_CHANGED,H=>{const ne=H?.language;ne&&se.emit("language_changed",{language:ne})}),r.on(J.CLIENT_TOOL_REQUEST,H=>{const ne=H?.executionId,ve=H?.toolName,de=H?.parameters??{},ce=H?.waitForResponse!==!1;if(!ve)return;const pe=U.current[ve];if(!pe)return;const he={minimize:()=>se.emit("minimize_chat"),maximize:()=>se.emit("maximize_chat")};ce&&ne?pe(de,he).then(Ve=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:ne,result:Ve})}).catch(Ve=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:ne,result:{error:Ve instanceof Error?Ve.message:String(Ve)}})}):pe(de,he).catch(()=>{})})}class sf{listeners=new Map;on(r,s){return this.listeners.has(r)||this.listeners.set(r,new Set),this.listeners.get(r).add(s),()=>this.off(r,s)}once(r,s){const a=((...f)=>{this.off(r,a),s(...f)});return this.on(r,a)}off(r,s){this.listeners.get(r)?.delete(s)}emit(r,s){const a=this.listeners.get(r);if(a)for(const f of a)try{f(s)}catch{}}removeAllListeners(){this.listeners.clear()}}const nf=oe.createContext(null);function af({children:d,wsUrl:r,restUrl:s,enableAudio:a=!0,pcmOptions:f,debug:_=!1,heartbeatIntervalSeconds:C=15,withCredentials:R=!1,onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re}){const[K,se]=oe.useReducer(hp,po),J=oe.useRef(K),Y=oe.useCallback(xe=>{J.current=hp(J.current,xe),se(xe)},[]),H=oe.useRef(!1),ne=oe.useRef(hg()),ve=oe.useRef(null),de=oe.useRef(po.session.agentType),ce=oe.useRef(!1),pe=oe.useRef(new sf),he=oe.useRef({}),Ve=oe.useRef({onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re});oe.useEffect(()=>{Ve.current={onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re}},[b,U,z,re]),oe.useEffect(()=>{de.current=K.session.agentType},[K.session.agentType]),oe.useEffect(()=>{ve.current=K.session.sessionId},[K.session.sessionId]);const fe=oe.useCallback(()=>{Y({type:"SET_AUDIO_PLAYING",payload:!1});const xe=Je.current?.getSocket();xe?.connected&&xe.emit(_r.AUDIO_PLAYBACK_COMPLETE,{session_id:ve.current})},[]),{socketMgrRef:Je,audioMgrRef:qe,sessionMgrRef:ot}=hy({wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:_,withCredentials:R,onPlaybackComplete:fe}),Ze=oe.useCallback(xe=>{fy({socket:xe,dispatch:Y,stateRef:J,sessionIdRef:ve,sessionAgentTypeRef:de,interruptedRef:ce,manualDisconnectRef:H,chunkAccumulatorRef:ne,clientToolsRef:he,audioMgrRef:{current:qe.current},enableAudio:a,cbRefs:Ve,eventsEmitter:pe.current})},[a]),it=oe.useCallback(({authPayload:xe,queryToken:Qe})=>new Promise((Nt,nr)=>{Je.current?.cleanupSocket();const It=Je.current.connectSocketRaw({authPayload:xe,queryToken:Qe});Ze(It),It.once("connect",()=>{Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTED}),Y({type:"SET_ERROR",payload:null}),Nt(It)}),It.once("connect_error",Yr=>{Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Yr?.message||"Connection error"}),nr(Yr)})}),[Ze]),tt=oe.useCallback(({keepManualDisconnect:xe=!1}={})=>{H.current=!0,ce.current=!1,ne.current.clear(),qe.current.destroyPcmPlayer(),Je.current.cleanupSocket(),xe||(H.current=!1),Y({type:"HARD_RESET"})},[]),Wt=oe.useCallback(async({apiKey:xe,publicChatId:Qe,agentId:Nt,userId:nr,language:It="en",clientTools:Yr,config:hn}={})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!xe&&!Qe&&!Nt)throw new Error("Provide one of apiKey, publicChatId, or agentId");tt(),he.current=Yr??{},Y({type:"SET_CONNECTION_STATE",payload:ft.INITIALIZING}),Y({type:"SET_ERROR",payload:null});const ls=pg();let ct;try{ct=await ot.current.initializeSession({apiKey:xe,publicChatId:Qe,agentId:Nt,userId:nr,language:It,timezone:ls,config:hn})}catch($r){const Lt=$r;throw Lt.status===401||Lt.status===403?(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Authentication failed"})):Lt.status===402?(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:Lt.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED})):Lt.status===429?(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Too many requests. Please try again later."})):(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Failed to initialize session"})),$r}const Ut=ct;Y({type:"UPDATE_SESSION",payload:{sessionId:Ut.session_id,agentType:Ut.streaming_url?di.CLOUD_AVATAR:K.session.agentType,streamingUrl:Ut.streaming_url||null,uniqueId:Ut.unique_id||null}}),Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Ut.streaming_url?Zt.CONNECTING:Zt.IDLE,error:null}}),H.current=!0;try{await it({authPayload:{token:Ut.session_token},queryToken:Ut.session_token}),H.current=!1}catch($r){throw H.current=!1,$r}return ct},[it,tt,r,K.session.agentType]),xt=oe.useCallback(async({uniqueId:xe})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!xe)throw new Error("uniqueId is required");tt(),Y({type:"SET_CONNECTION_STATE",payload:ft.INITIALIZING}),Y({type:"SET_ERROR",payload:null});let Qe;try{Qe=await ot.current.joinDesktopSession({uniqueId:xe})}catch(nr){const It=nr;throw(It.status===401||It.status===403)&&(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Authentication failed"})),It.status===402&&(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:It.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED})),It.status===429&&(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Too many requests. Please try again later."})),nr}const Nt=Qe;Y({type:"UPDATE_SESSION",payload:{sessionId:Nt.session_id,uniqueId:xe,role:"user",agentType:di.DESKTOP_AVATAR}}),Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Zt.IDLE,error:null}}),H.current=!0;try{await it({authPayload:{token:Nt.session_token},queryToken:Nt.session_token}),H.current=!1}catch(nr){throw H.current=!1,nr}return Qe},[it,tt,r]),je=oe.useCallback(()=>tt({keepManualDisconnect:!0}),[tt]),We=oe.useCallback(async()=>{const xe=Je.current?.getSocket();return xe&&K.isConnected&&(xe.emit("end_session"),await new Promise(Qe=>setTimeout(Qe,150))),je(),{success:!0}},[je,K.isConnected]),st=oe.useCallback(()=>{const xe=Je.current?.getSocket();xe?.connected?xe.emit("end_session"):(Y({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),Y({type:"SET_SESSION_READY",payload:!1}))},[]),ze=oe.useCallback((xe,Qe={})=>{const Nt=Je.current?.getSocket();return!Nt||!K.isConnected?!1:(Nt.emit(xe,Qe),!0)},[K.isConnected]),At=oe.useCallback(xe=>!xe||!String(xe).trim()?!1:(Y({type:"ADD_MESSAGE",payload:{id:`user-${Date.now()}`,role:"user",text:String(xe),timestamp:new Date().toISOString()}}),ze(_r.USER_MESSAGE,{message:String(xe)})),[ze]),sr=oe.useCallback((xe,Qe)=>{!Qe||!String(Qe).trim()||Y({type:"ADD_MESSAGE",payload:{id:`${xe}-${Date.now()}`,role:xe,text:String(Qe),timestamp:new Date().toISOString()}})},[]),Hr=oe.useCallback(xe=>!xe||!String(xe).trim()?!1:ze(_r.USER_MESSAGE,{message:String(xe)}),[ze]),Us=oe.useCallback(xe=>ze(_r.AUDIO_CHUNK,{audio:xe}),[ze]),Kr=oe.useCallback(()=>ze(_r.AUDIO_END,{}),[ze]),jr=oe.useCallback(()=>(ce.current=!0,qe.current.interruptPlayback(),Y({type:"SET_AUDIO_PLAYING",payload:!1}),ze(_r.INTERRUPT,{})),[ze]),Fs=oe.useCallback(()=>ze(_r.CLEAR_SESSION_HISTORY,{}),[ze]),rt=oe.useCallback(xe=>xe?ze(_r.CHANGE_SESSION_LANGUAGE,{language:xe}):!1,[ze]),Tr=oe.useCallback((xe={})=>ze(_r.CLIENT_READY,xe),[ze]),lt=oe.useCallback(()=>{ne.current.clear(),Y({type:"SET_MESSAGES",payload:[]})},[]),Qr=oe.useCallback(()=>qe.current.resumeAudioPlayback(),[]),er=oe.useCallback(()=>qe.current.pauseAudioPlayback(),[]),Er=oe.useCallback(xe=>qe.current.attachAudioElement(xe),[]),gt=oe.useCallback((xe,Qe=null)=>{Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:xe,error:Qe?String(Qe):null}})},[]),yt=oe.useCallback(async xe=>{if(!s)throw new Error("Missing restUrl in RqmiiAgentProvider");try{const Qe=await ot.current.fetchAgentConfig(xe);return Y({type:"SET_AGENT_CONFIG",payload:Qe}),Qe}catch(Qe){throw Y({type:"SET_AGENT_CONFIG",payload:null}),Qe}},[s]),Ct=oe.useCallback(xe=>{he.current={...he.current,...xe}},[]),kt=oe.useCallback(xe=>{const Qe=xe.sessionId||ve.current;return Qe?ot.current.submitFeedback({sessionId:Qe,rating:xe.rating,feedback:xe.feedback,endedBy:xe.endedBy}):Promise.reject(new Error("No session id available for feedback"))},[]),Xr=oe.useMemo(()=>cg(K.sessionState),[K.sessionState]),os=oe.useMemo(()=>({...K,...Xr,initializeSession:Wt,joinDesktopSession:xt,disconnect:je,terminateSession:We,endSession:st,emit:ze,sendTextMessage:At,addLocalMessage:sr,emitUserMessage:Hr,sendAudioChunk:Us,endAudioStream:Kr,interrupt:jr,clearSessionHistory:Fs,changeSessionLanguage:rt,signalClientReady:Tr,clearMessages:lt,resumeAudioPlayback:Qr,pauseAudioPlayback:er,attachAudioElement:Er,fetchAgentConfig:yt,submitFeedback:kt,setCloudStreamState:gt,registerClientTools:Ct,events:pe.current,audioElement:qe.current?.getAudioElement()??null,socket:Je.current?.getSocket()??null}),[K,Xr,Wt,xt,je,We,st,ze,At,sr,Hr,Us,Kr,jr,Fs,rt,Tr,lt,Qr,er,Er,gt,Ct,kt]);return Jt.jsx(nf.Provider,{value:os,children:d})}function dn(){const d=oe.useContext(nf);if(!d)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return d}function of(){const d=dn();return{connectionState:d.connectionState,isConnected:d.isConnected,isSessionReady:d.isSessionReady,error:d.error,session:d.session,creditExhausted:d.creditExhausted,creditError:d.creditError,sessionState:d.sessionState,isSessionTerminated:d.isSessionTerminated,isSessionTerminating:d.isSessionTerminating,isAgentThinking:d.isAgentThinking,isAgentSpeaking:d.isAgentSpeaking,isToolExecuting:d.isToolExecuting,agentConfig:d.agentConfig,initializeSession:d.initializeSession,joinDesktopSession:d.joinDesktopSession,disconnect:d.disconnect,terminateSession:d.terminateSession,endSession:d.endSession,interrupt:d.interrupt,clearSessionHistory:d.clearSessionHistory,changeSessionLanguage:d.changeSessionLanguage,signalClientReady:d.signalClientReady,fetchAgentConfig:d.fetchAgentConfig,submitFeedback:d.submitFeedback,registerClientTools:d.registerClientTools,events:d.events}}function my(){const d=dn();return{messages:d.messages,sendTextMessage:d.sendTextMessage,addLocalMessage:d.addLocalMessage,emitUserMessage:d.emitUserMessage,clearMessages:d.clearMessages}}function gy(){const d=dn();return{sendAudioChunk:d.sendAudioChunk,endAudioStream:d.endAudioStream,isAudioPlaying:d.isAudioPlaying,transcript:d.transcript,partialTranscript:d.partialTranscript,interrupt:d.interrupt,resumeAudioPlayback:d.resumeAudioPlayback,pauseAudioPlayback:d.pauseAudioPlayback,attachAudioElement:d.attachAudioElement}}function lf(){const d=dn(),r=d.cloudStream?.state||Zt.IDLE;return{streamingUrl:d.session.streamingUrl,isAvatarSpeaking:d.isAvatarSpeaking,speakingSource:"avatar_events",isCloudAvatar:d.session.agentType===di.CLOUD_AVATAR,isDesktopAvatar:d.session.agentType===di.DESKTOP_AVATAR,cloudStreamState:r,cloudStreamError:d.cloudStream?.error||null,isCloudStreamConnected:r===Zt.CONNECTED,isCloudStreamLoading:r===Zt.CONNECTING||r===Zt.LOADING,setCloudStreamState:d.setCloudStreamState}}var to={},ro={},ei={},wp;function uf(){if(wp)return ei;wp=1,Object.defineProperty(ei,"__esModule",{value:!0}),ei.baseAssetPath=void 0;const r=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let s="/";return r&&(s=r.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),ei.baseAssetPath=s,ei}var ti={},vp;function Io(){if(vp)return ti;vp=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.defaultModelFetcher=void 0;const d=r=>fetch(r).then(s=>s.arrayBuffer());return ti.defaultModelFetcher=d,ti}var Fr={},ri={},_p;function ci(){if(_p)return ri;_p=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.log=void 0;const d=r=>s=>{console.log(`VAD | ${r} >`,s)};return ri.log={error:d("error"),debug:d("debug"),warn:d("warn")},ri}var si={},bp;function qi(){if(bp)return si;bp=1,Object.defineProperty(si,"__esModule",{value:!0}),si.Message=void 0;var d;return(function(r){r.AudioFrame="AUDIO_FRAME",r.SpeechStart="SPEECH_START",r.VADMisfire="VAD_MISFIRE",r.SpeechEnd="SPEECH_END",r.SpeechStop="SPEECH_STOP",r.SpeechRealStart="SPEECH_REAL_START",r.FrameProcessed="FRAME_PROCESSED"})(d||(si.Message=d={})),si}var Sp;function Mo(){if(Sp)return Fr;Sp=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.FrameProcessor=Fr.validateOptions=Fr.defaultFrameProcessorOptions=void 0;const d=ci(),r=qi();Fr.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function s(C){(C.positiveSpeechThreshold<0||C.positiveSpeechThreshold>1)&&d.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(C.negativeSpeechThreshold<0||C.negativeSpeechThreshold>C.positiveSpeechThreshold)&&d.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),C.preSpeechPadMs<0&&d.log.error("preSpeechPadMs should be positive"),C.redemptionMs<0&&d.log.error("redemptionMs should be positive"),C.minSpeechMs<0&&d.log.error("minSpeechMs should be positive")}Fr.validateOptions=s;const a=C=>{const R=C.reduce((U,z)=>(U.push(U.at(-1)+z.length),U),[0]),b=new Float32Array(R.at(-1));return C.forEach((U,z)=>{const re=R[z];b.set(U,re)}),b};function f(C,R){const b=Math.floor(C.redemptionMs/R),U=Math.floor(C.preSpeechPadMs/R),z=Math.floor(C.minSpeechMs/R);return{redemptionFrames:b,preSpeechPadFrames:U,minSpeechFrames:z}}class _{constructor(R,b,U,z){this.modelProcessFunc=R,this.modelResetFunc=b,this.options=U,this.msPerFrame=z,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=J=>{this.options={...this.options,...J};const{redemptionFrames:Y,preSpeechPadFrames:H,minSpeechFrames:ne}=f(this.options,this.msPerFrame);this.redemptionFrames=Y,this.preSpeechPadFrames=H,this.minSpeechFrames=ne},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=J=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(J):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=J=>{const Y=this.audioBuffer;this.audioBuffer=[];const H=this.speaking;if(this.reset(),H)if(Y.reduce((ve,de)=>de.isSpeech?ve+1:ve,0)>=this.minSpeechFrames){const ve=a(Y.map(de=>de.frame));J({msg:r.Message.SpeechEnd,audio:ve})}else J({msg:r.Message.VADMisfire});return{}},this.process=async(J,Y)=>{if(!this.active)return;const H=await this.modelProcessFunc(J),ne=H.isSpeech>=this.options.positiveSpeechThreshold;if(Y({probs:H,msg:r.Message.FrameProcessed,frame:J}),this.audioBuffer.push({frame:J,isSpeech:ne}),ne&&(this.speechFrameCount++,this.redemptionCounter=0),ne&&!this.speaking&&(this.speaking=!0,Y({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,Y({msg:r.Message.SpeechRealStart})),H.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const ve=this.audioBuffer;if(this.audioBuffer=[],ve.reduce((ce,pe)=>pe.isSpeech?ce+1:ce,0)>=this.minSpeechFrames){const ce=a(ve.map(pe=>pe.frame));Y({msg:r.Message.SpeechEnd,audio:ce})}else Y({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:re,preSpeechPadFrames:K,minSpeechFrames:se}=f(this.options,this.msPerFrame);this.redemptionFrames=re,this.preSpeechPadFrames=K,this.minSpeechFrames=se,this.reset()}}return Fr.FrameProcessor=_,Fr}var Vr={};function ur(d){throw new Error('Could not dynamically require "'+d+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var so={exports:{}};/*!
|
|
1
|
+
"use strict";const ae=require("react"),Jt=require("react/jsx-runtime"),ci={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},br={CONNECT:"connect",DISCONNECT:"disconnect",CONNECT_ERROR:"connect_error",SESSION_READY:"session_ready",SESSION_JOINED:"session_joined",SESSION_TERMINATED:"session_terminated",USER_MESSAGE:"user_message",AUDIO_CHUNK:"audio_chunk",AUDIO_END:"audio_end",INTERRUPT:"interrupt",CHANGE_SESSION_LANGUAGE:"change_session_language",LANGUAGE_CHANGED:"language_changed",CLIENT_READY:"client_ready",CLIENT_TOOL_REQUEST:"client_tool_request",CLIENT_TOOL_RESULT:"client_tool_result",CLEAR_SESSION_HISTORY:"clear_session_history",TRANSCRIPT:"transcript",PARTIAL_TRANSCRIPT:"partial_transcript",AGENT_RESPONSE_CHUNK:"agent_response_chunk",AGENT_RESPONSE:"agent_response",AGENT_AUDIO_CHUNK:"agent_audio_chunk",AGENT_AUDIO_COMPLETE:"agent_audio_complete",AVATAR_SPEAKING:"avatar_speaking",AVATAR_SPEAKING_DONE:"avatar_speaking_done",INTERRUPTED:"interrupted",ERROR:"error",AUTH_ERROR:"auth_error",SESSION_EXPIRED:"session_expired",CREDITS_EXHAUSTED:"credits_exhausted",SESSION_STATE_CHANGED:"session:state_changed",AUDIO_PLAYBACK_COMPLETE:"audio:playback_complete",MESSAGE_RATE_LIMITED:"message_rate_limited",SHOW_LEAD_CAPTURE_FORM:"show_lead_capture_form"},pt={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",FAILED:"failed",ENDED:"ended"},Zt={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},Ns={IDLE:"idle",USER_SPEAKING:"user_speaking",AGENT_THINKING:"agent_thinking",AGENT_SPEAKING:"agent_speaking",TOOL_EXECUTING:"tool_executing",TERMINATING:"terminating",TERMINATED:"terminated"},Gp={encoding:"16bitInt",channels:1,sampleRate:16e3},po={connectionState:pt.IDLE,isConnected:!1,isSessionReady:!1,error:null,isAudioPlaying:!1,isAvatarSpeaking:!1,sessionState:Ns.IDLE,cloudStream:{state:Zt.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[],creditExhausted:!1,creditError:null,agentConfig:null};function hp(d,r){switch(r.type){case"SET_CONNECTION_STATE":return{...d,connectionState:r.payload,isConnected:r.payload===pt.CONNECTED};case"SET_ERROR":return{...d,error:r.payload};case"SET_CLOUD_STREAM_STATE":return{...d,cloudStream:r.payload};case"SET_SESSION_STATE":return{...d,sessionState:r.payload};case"UPDATE_SESSION":return{...d,session:{...d.session,...r.payload}};case"ADD_MESSAGE":return{...d,messages:[...d.messages,r.payload]};case"SET_AUDIO_PLAYING":return{...d,isAudioPlaying:r.payload};case"SET_AVATAR_SPEAKING":return{...d,isAvatarSpeaking:r.payload};case"SET_CREDIT_EXHAUSTED":return{...d,creditExhausted:r.payload.exhausted,creditError:r.payload.error};case"SET_TRANSCRIPT":return{...d,transcript:r.payload};case"SET_PARTIAL_TRANSCRIPT":return{...d,partialTranscript:r.payload};case"SET_MESSAGES":return{...d,messages:r.payload};case"SET_SESSION_READY":return{...d,isSessionReady:r.payload};case"SET_AGENT_CONFIG":return{...d,agentConfig:r.payload};case"HARD_RESET":return po;case"REPLACE_STATE":return r.payload;default:return d}}function cg(d){return{isSessionTerminated:d===Ns.TERMINATED,isSessionTerminating:d===Ns.TERMINATING,isAgentThinking:d===Ns.AGENT_THINKING,isAgentSpeaking:d===Ns.AGENT_SPEAKING,isToolExecuting:d===Ns.TOOL_EXECUTING}}function hg(){const d=new Map;return{addChunk(r,s){const a=r||`request-${Date.now()}`,_=`${d.get(a)||""}${s||""}`;return d.set(a,_),{id:a,text:_}},consume(r,s=""){const a=r||`request-${Date.now()}`,f=d.get(a)||s||"";return d.delete(a),{id:a,text:f}},clear(){d.clear()}}}function pg(){try{const d=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof d=="string"&&d.trim()?d.trim():void 0}catch{return}}async function Zn(d){if(!d?.ok){let r=`HTTP ${d.status}`;try{const f=await d.json();r=f?.detail||f?.message||r}catch{}const s=new Error(r);throw s.status=d.status,s}return d.json()}function fg({restUrl:d,log:r,withCredentials:s}){function a(){if(!d)throw new Error("Missing restUrl in RqmiiAgentProvider")}async function f({apiKey:N,publicChatId:z,agentId:te,userId:j,language:se="en",timezone:J,config:Y}={}){a();const W={...N?{api_key:N}:{},...z?{public_chat_id:z}:{},...te?{agent_id:te}:{},...j?{user_id:j}:{},language:se,...J?{timezone:J}:{},...Y?{config:Y}:{}};r("initializeSession — POST /sessions/init",W);const ne=await fetch(`${d}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W),...s?{credentials:"include"}:{}}),fe=await Zn(ne);if(!fe?.session_id||!fe?.session_token)throw new Error("Invalid initialize session response");return fe}async function _({uniqueId:N}){a(),r("joinDesktopSession — POST /sessions/join",{uniqueId:N});const z=await fetch(`${d}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:N}),...s?{credentials:"include"}:{}}),te=await Zn(z);if(!te?.session_id||!te?.session_token)throw new Error("Invalid join session response");return te}async function C(N){a(),r("fetchAgentConfig — GET /agent/{publicChatId}",{publicChatId:N});const z=await fetch(`${d}/agent/${encodeURIComponent(N)}`,{method:"GET",headers:{"Content-Type":"application/json"},...s?{credentials:"include"}:{}});return Zn(z)}async function R({sessionId:N,rating:z,feedback:te,endedBy:j}){if(a(),!N)throw new Error("sessionId is required");const se={...typeof z=="number"?{rating:z}:{},...te?{feedback:te}:{},...j?{ended_by:j}:{}};r("submitFeedback — PATCH /conversations/{sessionId}/feedback",{sessionId:N,payload:se});const J=await fetch(`${d}/conversations/${encodeURIComponent(N)}/feedback`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(se),...s?{credentials:"include"}:{}});return Zn(J)}async function S({agentId:N,sessionId:z,collectedData:te}){if(a(),!N)throw new Error("agentId is required");if(!z)throw new Error("sessionId is required");r("submitLead — POST /public/agent/{agentId}/lead-capture/leads",{agentId:N,sessionId:z});const j=await fetch(`${d}/public/agent/${encodeURIComponent(N)}/lead-capture/leads`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:z,collected_data:te}),...s?{credentials:"include"}:{}});return Zn(j)}return{initializeSession:f,joinDesktopSession:_,fetchAgentConfig:C,submitFeedback:R,submitLead:S}}const Dr=Object.create(null);Dr.open="0";Dr.close="1";Dr.ping="2";Dr.pong="3";Dr.message="4";Dr.upgrade="5";Dr.noop="6";const Di=Object.create(null);Object.keys(Dr).forEach(d=>{Di[Dr[d]]=d});const fo={type:"error",data:"parser error"},qp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Wp=typeof ArrayBuffer=="function",Hp=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d&&d.buffer instanceof ArrayBuffer,xo=({type:d,data:r},s,a)=>qp&&r instanceof Blob?s?a(r):pp(r,a):Wp&&(r instanceof ArrayBuffer||Hp(r))?s?a(r):pp(new Blob([r]),a):a(Dr[d]+(r||"")),pp=(d,r)=>{const s=new FileReader;return s.onload=function(){const a=s.result.split(",")[1];r("b"+(a||""))},s.readAsDataURL(d)};function fp(d){return d instanceof Uint8Array?d:d instanceof ArrayBuffer?new Uint8Array(d):new Uint8Array(d.buffer,d.byteOffset,d.byteLength)}let Ya;function mg(d,r){if(qp&&d.data instanceof Blob)return d.data.arrayBuffer().then(fp).then(r);if(Wp&&(d.data instanceof ArrayBuffer||Hp(d.data)))return r(fp(d.data));xo(d,!1,s=>{Ya||(Ya=new TextEncoder),r(Ya.encode(s))})}const mp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",li=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let d=0;d<mp.length;d++)li[mp.charCodeAt(d)]=d;const gg=d=>{let r=d.length*.75,s=d.length,a,f=0,_,C,R,S;d[d.length-1]==="="&&(r--,d[d.length-2]==="="&&r--);const N=new ArrayBuffer(r),z=new Uint8Array(N);for(a=0;a<s;a+=4)_=li[d.charCodeAt(a)],C=li[d.charCodeAt(a+1)],R=li[d.charCodeAt(a+2)],S=li[d.charCodeAt(a+3)],z[f++]=_<<2|C>>4,z[f++]=(C&15)<<4|R>>2,z[f++]=(R&3)<<6|S&63;return N},yg=typeof ArrayBuffer=="function",Co=(d,r)=>{if(typeof d!="string")return{type:"message",data:jp(d,r)};const s=d.charAt(0);return s==="b"?{type:"message",data:wg(d.substring(1),r)}:Di[s]?d.length>1?{type:Di[s],data:d.substring(1)}:{type:Di[s]}:fo},wg=(d,r)=>{if(yg){const s=gg(d);return jp(s,r)}else return{base64:!0,data:d}},jp=(d,r)=>{switch(r){case"blob":return d instanceof Blob?d:new Blob([d]);case"arraybuffer":default:return d instanceof ArrayBuffer?d:d.buffer}},Kp="",vg=(d,r)=>{const s=d.length,a=new Array(s);let f=0;d.forEach((_,C)=>{xo(_,!1,R=>{a[C]=R,++f===s&&r(a.join(Kp))})})},_g=(d,r)=>{const s=d.split(Kp),a=[];for(let f=0;f<s.length;f++){const _=Co(s[f],r);if(a.push(_),_.type==="error")break}return a};function bg(){return new TransformStream({transform(d,r){mg(d,s=>{const a=s.length;let f;if(a<126)f=new Uint8Array(1),new DataView(f.buffer).setUint8(0,a);else if(a<65536){f=new Uint8Array(3);const _=new DataView(f.buffer);_.setUint8(0,126),_.setUint16(1,a)}else{f=new Uint8Array(9);const _=new DataView(f.buffer);_.setUint8(0,127),_.setBigUint64(1,BigInt(a))}d.data&&typeof d.data!="string"&&(f[0]|=128),r.enqueue(f),r.enqueue(s)})}})}let Ja;function Mi(d){return d.reduce((r,s)=>r+s.length,0)}function Pi(d,r){if(d[0].length===r)return d.shift();const s=new Uint8Array(r);let a=0;for(let f=0;f<r;f++)s[f]=d[0][a++],a===d[0].length&&(d.shift(),a=0);return d.length&&a<d[0].length&&(d[0]=d[0].slice(a)),s}function Sg(d,r){Ja||(Ja=new TextDecoder);const s=[];let a=0,f=-1,_=!1;return new TransformStream({transform(C,R){for(s.push(C);;){if(a===0){if(Mi(s)<1)break;const S=Pi(s,1);_=(S[0]&128)===128,f=S[0]&127,f<126?a=3:f===126?a=1:a=2}else if(a===1){if(Mi(s)<2)break;const S=Pi(s,2);f=new DataView(S.buffer,S.byteOffset,S.length).getUint16(0),a=3}else if(a===2){if(Mi(s)<8)break;const S=Pi(s,8),N=new DataView(S.buffer,S.byteOffset,S.length),z=N.getUint32(0);if(z>Math.pow(2,21)-1){R.enqueue(fo);break}f=z*Math.pow(2,32)+N.getUint32(4),a=3}else{if(Mi(s)<f)break;const S=Pi(s,f);R.enqueue(Co(_?S:Ja.decode(S),r)),a=0}if(f===0||f>d){R.enqueue(fo);break}}}})}const Qp=4;function $t(d){if(d)return Tg(d)}function Tg(d){for(var r in $t.prototype)d[r]=$t.prototype[r];return d}$t.prototype.on=$t.prototype.addEventListener=function(d,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+d]=this._callbacks["$"+d]||[]).push(r),this};$t.prototype.once=function(d,r){function s(){this.off(d,s),r.apply(this,arguments)}return s.fn=r,this.on(d,s),this};$t.prototype.off=$t.prototype.removeListener=$t.prototype.removeAllListeners=$t.prototype.removeEventListener=function(d,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var s=this._callbacks["$"+d];if(!s)return this;if(arguments.length==1)return delete this._callbacks["$"+d],this;for(var a,f=0;f<s.length;f++)if(a=s[f],a===r||a.fn===r){s.splice(f,1);break}return s.length===0&&delete this._callbacks["$"+d],this};$t.prototype.emit=function(d){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),s=this._callbacks["$"+d],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if(s){s=s.slice(0);for(var a=0,f=s.length;a<f;++a)s[a].apply(this,r)}return this};$t.prototype.emitReserved=$t.prototype.emit;$t.prototype.listeners=function(d){return this._callbacks=this._callbacks||{},this._callbacks["$"+d]||[]};$t.prototype.hasListeners=function(d){return!!this.listeners(d).length};const Vi=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,s)=>s(r,0),ur=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Eg="arraybuffer";function Xp(d,...r){return r.reduce((s,a)=>(d.hasOwnProperty(a)&&(s[a]=d[a]),s),{})}const $g=ur.setTimeout,xg=ur.clearTimeout;function Gi(d,r){r.useNativeTimers?(d.setTimeoutFn=$g.bind(ur),d.clearTimeoutFn=xg.bind(ur)):(d.setTimeoutFn=ur.setTimeout.bind(ur),d.clearTimeoutFn=ur.clearTimeout.bind(ur))}const Cg=1.33;function kg(d){return typeof d=="string"?Rg(d):Math.ceil((d.byteLength||d.size)*Cg)}function Rg(d){let r=0,s=0;for(let a=0,f=d.length;a<f;a++)r=d.charCodeAt(a),r<128?s+=1:r<2048?s+=2:r<55296||r>=57344?s+=3:(a++,s+=4);return s}function Yp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ag(d){let r="";for(let s in d)d.hasOwnProperty(s)&&(r.length&&(r+="&"),r+=encodeURIComponent(s)+"="+encodeURIComponent(d[s]));return r}function Ig(d){let r={},s=d.split("&");for(let a=0,f=s.length;a<f;a++){let _=s[a].split("=");r[decodeURIComponent(_[0])]=decodeURIComponent(_[1])}return r}class Mg extends Error{constructor(r,s,a){super(r),this.description=s,this.context=a,this.type="TransportError"}}class ko extends $t{constructor(r){super(),this.writable=!1,Gi(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,s,a){return super.emitReserved("error",new Mg(r,s,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(r){this.readyState==="open"&&this.write(r)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(r){const s=Co(r,this.socket.binaryType);this.onPacket(s)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,s={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(s)}_hostname(){const r=this.opts.hostname;return r.indexOf(":")===-1?r:"["+r+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(r){const s=Ag(r);return s.length?"?"+s:""}}class Pg extends ko{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const s=()=>{this.readyState="paused",r()};if(this._polling||!this.writable){let a=0;this._polling&&(a++,this.once("pollComplete",function(){--a||s()})),this.writable||(a++,this.once("drain",function(){--a||s()}))}else s()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){const s=a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)};_g(r,this.socket.binaryType).forEach(s),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const r=()=>{this.write([{type:"close"}])};this.readyState==="open"?r():this.once("open",r)}write(r){this.writable=!1,vg(r,s=>{this.doWrite(s,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",s=this.query||{};return this.opts.timestampRequests!==!1&&(s[this.opts.timestampParam]=Yp()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(r,s)}}let Jp=!1;try{Jp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Og=Jp;function Dg(){}class zg extends Pg{constructor(r){if(super(r),typeof location<"u"){const s=location.protocol==="https:";let a=location.port;a||(a=s?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||a!==r.port}}doWrite(r,s){const a=this.request({method:"POST",data:r});a.on("success",s),a.on("error",(f,_)=>{this.onError("xhr post error",f,_)})}doPoll(){const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(s,a)=>{this.onError("xhr poll error",s,a)}),this.pollXhr=r}}class Or extends $t{constructor(r,s,a){super(),this.createRequest=r,Gi(this,a),this._opts=a,this._method=a.method||"GET",this._uri=s,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var r;const s=Xp(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this._opts.xd;const a=this._xhr=this.createRequest(s);try{a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let f in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(f)&&a.setRequestHeader(f,this._opts.extraHeaders[f])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(r=this._opts.cookieJar)===null||r===void 0||r.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var f;a.readyState===3&&((f=this._opts.cookieJar)===null||f===void 0||f.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},a.send(this._data)}catch(f){this.setTimeoutFn(()=>{this._onError(f)},0);return}typeof document<"u"&&(this._index=Or.requestsCount++,Or.requests[this._index]=this)}_onError(r){this.emitReserved("error",r,this._xhr),this._cleanup(!0)}_cleanup(r){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Dg,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Or.requests[this._index],this._xhr=null}}_onLoad(){const r=this._xhr.responseText;r!==null&&(this.emitReserved("data",r),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Or.requestsCount=0;Or.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",gp);else if(typeof addEventListener=="function"){const d="onpagehide"in ur?"pagehide":"unload";addEventListener(d,gp,!1)}}function gp(){for(let d in Or.requests)Or.requests.hasOwnProperty(d)&&Or.requests[d].abort()}const Lg=(function(){const d=Zp({xdomain:!1});return d&&d.responseType!==null})();class Bg extends zg{constructor(r){super(r);const s=r&&r.forceBase64;this.supportsBinary=Lg&&!s}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Or(Zp,this.uri(),r)}}function Zp(d){const r=d.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||Og))return new XMLHttpRequest}catch{}if(!r)try{return new ur[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ef=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Ng extends ko{get name(){return"websocket"}doOpen(){const r=this.uri(),s=this.opts.protocols,a=ef?{}:Xp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(r,s,a)}catch(f){return this.emitReserved("error",f)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=r=>this.onClose({description:"websocket connection closed",context:r}),this.ws.onmessage=r=>this.onData(r.data),this.ws.onerror=r=>this.onError("websocket error",r)}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],f=s===r.length-1;xo(a,this.supportsBinary,_=>{try{this.doWrite(a,_)}catch{}f&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const r=this.opts.secure?"wss":"ws",s=this.query||{};return this.opts.timestampRequests&&(s[this.opts.timestampParam]=Yp()),this.supportsBinary||(s.b64=1),this.createUri(r,s)}}const Za=ur.WebSocket||ur.MozWebSocket;class Ug extends Ng{createSocket(r,s,a){return ef?new Za(r,s,a):s?new Za(r,s):new Za(r)}doWrite(r,s){this.ws.send(s)}}class Fg extends ko{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(r){return this.emitReserved("error",r)}this._transport.closed.then(()=>{this.onClose()}).catch(r=>{this.onError("webtransport error",r)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(r=>{const s=Sg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(s).getReader(),f=bg();f.readable.pipeTo(r.writable),this._writer=f.writable.getWriter();const _=()=>{a.read().then(({done:R,value:S})=>{R||(this.onPacket(S),_())}).catch(R=>{})};_();const C={type:"open"};this.query.sid&&(C.data=`{"sid":"${this.query.sid}"}`),this._writer.write(C).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],f=s===r.length-1;this._writer.write(a).then(()=>{f&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const Vg={websocket:Ug,webtransport:Fg,polling:Bg},Gg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,qg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mo(d){if(d.length>8e3)throw"URI too long";const r=d,s=d.indexOf("["),a=d.indexOf("]");s!=-1&&a!=-1&&(d=d.substring(0,s)+d.substring(s,a).replace(/:/g,";")+d.substring(a,d.length));let f=Gg.exec(d||""),_={},C=14;for(;C--;)_[qg[C]]=f[C]||"";return s!=-1&&a!=-1&&(_.source=r,_.host=_.host.substring(1,_.host.length-1).replace(/;/g,":"),_.authority=_.authority.replace("[","").replace("]","").replace(/;/g,":"),_.ipv6uri=!0),_.pathNames=Wg(_,_.path),_.queryKey=Hg(_,_.query),_}function Wg(d,r){const s=/\/{2,9}/g,a=r.replace(s,"/").split("/");return(r.slice(0,1)=="/"||r.length===0)&&a.splice(0,1),r.slice(-1)=="/"&&a.splice(a.length-1,1),a}function Hg(d,r){const s={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,_){f&&(s[f]=_)}),s}const go=typeof addEventListener=="function"&&typeof removeEventListener=="function",zi=[];go&&addEventListener("offline",()=>{zi.forEach(d=>d())},!1);class ds extends $t{constructor(r,s){if(super(),this.binaryType=Eg,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(s=r,r=null),r){const a=mo(r);s.hostname=a.host,s.secure=a.protocol==="https"||a.protocol==="wss",s.port=a.port,a.query&&(s.query=a.query)}else s.host&&(s.hostname=mo(s.host).host);Gi(this,s),this.secure=s.secure!=null?s.secure:typeof location<"u"&&location.protocol==="https:",s.hostname&&!s.port&&(s.port=this.secure?"443":"80"),this.hostname=s.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=s.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},s.transports.forEach(a=>{const f=a.prototype.name;this.transports.push(f),this._transportsByName[f]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},s),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ig(this.opts.query)),go&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},zi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const s=Object.assign({},this.opts.query);s.EIO=Qp,s.transport=r,this.id&&(s.sid=this.id);const a=Object.assign({},this.opts,{query:s,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[r]);return new this._transportsByName[r](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const r=this.opts.rememberUpgrade&&ds.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const s=this.createTransport(r);s.open(),this.setTransport(s)}setTransport(r){this.transport&&this.transport.removeAllListeners(),this.transport=r,r.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",s=>this._onClose("transport close",s))}onOpen(){this.readyState="open",ds.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",r),this.emitReserved("heartbeat"),r.type){case"open":this.onHandshake(JSON.parse(r.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const s=new Error("server error");s.code=r.data,this._onError(s);break;case"message":this.emitReserved("data",r.data),this.emitReserved("message",r.data);break}}onHandshake(r){this.emitReserved("handshake",r),this.id=r.sid,this.transport.query.sid=r.sid,this._pingInterval=r.pingInterval,this._pingTimeout=r.pingTimeout,this._maxPayload=r.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const r=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+r,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},r),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const r=this._getWritablePackets();this.transport.send(r),this._prevBufferLen=r.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let s=1;for(let a=0;a<this.writeBuffer.length;a++){const f=this.writeBuffer[a].data;if(f&&(s+=kg(f)),a>0&&s>this._maxPayload)return this.writeBuffer.slice(0,a);s+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(this._pingTimeoutTime=0,Vi(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,s,a){return this._sendPacket("message",r,s,a),this}send(r,s,a){return this._sendPacket("message",r,s,a),this}_sendPacket(r,s,a,f){if(typeof s=="function"&&(f=s,s=void 0),typeof a=="function"&&(f=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;const _={type:r,data:s,options:a};this.emitReserved("packetCreate",_),this.writeBuffer.push(_),f&&this.once("flush",f),this.flush()}close(){const r=()=>{this._onClose("forced close"),this.transport.close()},s=()=>{this.off("upgrade",s),this.off("upgradeError",s),r()},a=()=>{this.once("upgrade",s),this.once("upgradeError",s)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():r()}):this.upgrading?a():r()),this}_onError(r){if(ds.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",r),this._onClose("transport error",r)}_onClose(r,s){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),go&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=zi.indexOf(this._offlineEventListener);a!==-1&&zi.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,s),this.writeBuffer=[],this._prevBufferLen=0}}}ds.protocol=Qp;class jg extends ds{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let r=0;r<this._upgrades.length;r++)this._probe(this._upgrades[r])}_probe(r){let s=this.createTransport(r),a=!1;ds.priorWebsocketSuccess=!1;const f=()=>{a||(s.send([{type:"ping",data:"probe"}]),s.once("packet",te=>{if(!a)if(te.type==="pong"&&te.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;ds.priorWebsocketSuccess=s.name==="websocket",this.transport.pause(()=>{a||this.readyState!=="closed"&&(z(),this.setTransport(s),s.send([{type:"upgrade"}]),this.emitReserved("upgrade",s),s=null,this.upgrading=!1,this.flush())})}else{const j=new Error("probe error");j.transport=s.name,this.emitReserved("upgradeError",j)}}))};function _(){a||(a=!0,z(),s.close(),s=null)}const C=te=>{const j=new Error("probe error: "+te);j.transport=s.name,_(),this.emitReserved("upgradeError",j)};function R(){C("transport closed")}function S(){C("socket closed")}function N(te){s&&te.name!==s.name&&_()}const z=()=>{s.removeListener("open",f),s.removeListener("error",C),s.removeListener("close",R),this.off("close",S),this.off("upgrading",N)};s.once("open",f),s.once("error",C),s.once("close",R),this.once("close",S),this.once("upgrading",N),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{a||s.open()},200):s.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const s=[];for(let a=0;a<r.length;a++)~this.transports.indexOf(r[a])&&s.push(r[a]);return s}}let Kg=class extends jg{constructor(r,s={}){const a=typeof r=="object"?r:s;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(f=>Vg[f]).filter(f=>!!f)),super(r,a)}};function Qg(d,r="",s){let a=d;s=s||typeof location<"u"&&location,d==null&&(d=s.protocol+"//"+s.host),typeof d=="string"&&(d.charAt(0)==="/"&&(d.charAt(1)==="/"?d=s.protocol+d:d=s.host+d),/^(https?|wss?):\/\//.test(d)||(typeof s<"u"?d=s.protocol+"//"+d:d="https://"+d),a=mo(d)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";const _=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+_+":"+a.port+r,a.href=a.protocol+"://"+_+(s&&s.port===a.port?"":":"+a.port),a}const Xg=typeof ArrayBuffer=="function",Yg=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d.buffer instanceof ArrayBuffer,tf=Object.prototype.toString,Jg=typeof Blob=="function"||typeof Blob<"u"&&tf.call(Blob)==="[object BlobConstructor]",Zg=typeof File=="function"||typeof File<"u"&&tf.call(File)==="[object FileConstructor]";function Ro(d){return Xg&&(d instanceof ArrayBuffer||Yg(d))||Jg&&d instanceof Blob||Zg&&d instanceof File}function Li(d,r){if(!d||typeof d!="object")return!1;if(Array.isArray(d)){for(let s=0,a=d.length;s<a;s++)if(Li(d[s]))return!0;return!1}if(Ro(d))return!0;if(d.toJSON&&typeof d.toJSON=="function"&&arguments.length===1)return Li(d.toJSON(),!0);for(const s in d)if(Object.prototype.hasOwnProperty.call(d,s)&&Li(d[s]))return!0;return!1}function ey(d){const r=[],s=d.data,a=d;return a.data=yo(s,r),a.attachments=r.length,{packet:a,buffers:r}}function yo(d,r){if(!d)return d;if(Ro(d)){const s={_placeholder:!0,num:r.length};return r.push(d),s}else if(Array.isArray(d)){const s=new Array(d.length);for(let a=0;a<d.length;a++)s[a]=yo(d[a],r);return s}else if(typeof d=="object"&&!(d instanceof Date)){const s={};for(const a in d)Object.prototype.hasOwnProperty.call(d,a)&&(s[a]=yo(d[a],r));return s}return d}function ty(d,r){return d.data=wo(d.data,r),delete d.attachments,d}function wo(d,r){if(!d)return d;if(d&&d._placeholder===!0){if(typeof d.num=="number"&&d.num>=0&&d.num<r.length)return r[d.num];throw new Error("illegal attachments")}else if(Array.isArray(d))for(let s=0;s<d.length;s++)d[s]=wo(d[s],r);else if(typeof d=="object")for(const s in d)Object.prototype.hasOwnProperty.call(d,s)&&(d[s]=wo(d[s],r));return d}const ry=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Xe;(function(d){d[d.CONNECT=0]="CONNECT",d[d.DISCONNECT=1]="DISCONNECT",d[d.EVENT=2]="EVENT",d[d.ACK=3]="ACK",d[d.CONNECT_ERROR=4]="CONNECT_ERROR",d[d.BINARY_EVENT=5]="BINARY_EVENT",d[d.BINARY_ACK=6]="BINARY_ACK"})(Xe||(Xe={}));class sy{constructor(r){this.replacer=r}encode(r){return(r.type===Xe.EVENT||r.type===Xe.ACK)&&Li(r)?this.encodeAsBinary({type:r.type===Xe.EVENT?Xe.BINARY_EVENT:Xe.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let s=""+r.type;return(r.type===Xe.BINARY_EVENT||r.type===Xe.BINARY_ACK)&&(s+=r.attachments+"-"),r.nsp&&r.nsp!=="/"&&(s+=r.nsp+","),r.id!=null&&(s+=r.id),r.data!=null&&(s+=JSON.stringify(r.data,this.replacer)),s}encodeAsBinary(r){const s=ey(r),a=this.encodeAsString(s.packet),f=s.buffers;return f.unshift(a),f}}class Ao extends $t{constructor(r){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof r=="function"?{reviver:r}:r)}add(r){let s;if(typeof r=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");s=this.decodeString(r);const a=s.type===Xe.BINARY_EVENT;a||s.type===Xe.BINARY_ACK?(s.type=a?Xe.EVENT:Xe.ACK,this.reconstructor=new ny(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(Ro(r)||r.base64)if(this.reconstructor)s=this.reconstructor.takeBinaryData(r),s&&(this.reconstructor=null,super.emitReserved("decoded",s));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+r)}decodeString(r){let s=0;const a={type:Number(r.charAt(0))};if(Xe[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===Xe.BINARY_EVENT||a.type===Xe.BINARY_ACK){const _=s+1;for(;r.charAt(++s)!=="-"&&s!=r.length;);const C=r.substring(_,s);if(C!=Number(C)||r.charAt(s)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!iy(R)||R<0)throw new Error("Illegal attachments");if(R>this.opts.maxAttachments)throw new Error("too many attachments");a.attachments=R}if(r.charAt(s+1)==="/"){const _=s+1;for(;++s&&!(r.charAt(s)===","||s===r.length););a.nsp=r.substring(_,s)}else a.nsp="/";const f=r.charAt(s+1);if(f!==""&&Number(f)==f){const _=s+1;for(;++s;){const C=r.charAt(s);if(C==null||Number(C)!=C){--s;break}if(s===r.length)break}a.id=Number(r.substring(_,s+1))}if(r.charAt(++s)){const _=this.tryParse(r.substr(s));if(Ao.isPayloadValid(a.type,_))a.data=_;else throw new Error("invalid payload")}return a}tryParse(r){try{return JSON.parse(r,this.opts.reviver)}catch{return!1}}static isPayloadValid(r,s){switch(r){case Xe.CONNECT:return yp(s);case Xe.DISCONNECT:return s===void 0;case Xe.CONNECT_ERROR:return typeof s=="string"||yp(s);case Xe.EVENT:case Xe.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&ry.indexOf(s[0])===-1);case Xe.ACK:case Xe.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ny{constructor(r){this.packet=r,this.buffers=[],this.reconPack=r}takeBinaryData(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){const s=ty(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const iy=Number.isInteger||function(d){return typeof d=="number"&&isFinite(d)&&Math.floor(d)===d};function yp(d){return Object.prototype.toString.call(d)==="[object Object]"}const ay=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ao,Encoder:sy,get PacketType(){return Xe}},Symbol.toStringTag,{value:"Module"}));function Sr(d,r,s){return d.on(r,s),function(){d.off(r,s)}}const oy=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class rf extends $t{constructor(r,s,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=r,this.nsp=s,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const r=this.io;this.subs=[Sr(r,"open",this.onopen.bind(this)),Sr(r,"packet",this.onpacket.bind(this)),Sr(r,"error",this.onerror.bind(this)),Sr(r,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...s){var a,f,_;if(oy.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(s.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(s),this;const C={type:Xe.EVENT,data:s};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){const z=this.ids++,te=s.pop();this._registerAckCallback(z,te),C.id=z}const R=(f=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||f===void 0?void 0:f.writable,S=this.connected&&!(!((_=this.io.engine)===null||_===void 0)&&_._hasPingExpired());return this.flags.volatile&&!R||(S?(this.notifyOutgoingListeners(C),this.packet(C)):this.sendBuffer.push(C)),this.flags={},this}_registerAckCallback(r,s){var a;const f=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(f===void 0){this.acks[r]=s;return}const _=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let R=0;R<this.sendBuffer.length;R++)this.sendBuffer[R].id===r&&this.sendBuffer.splice(R,1);s.call(this,new Error("operation has timed out"))},f),C=(...R)=>{this.io.clearTimeoutFn(_),s.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...s){return new Promise((a,f)=>{const _=(C,R)=>C?f(C):a(R);_.withError=!0,s.push(_),this.emit(r,...s)})}_addToQueue(r){let s;typeof r[r.length-1]=="function"&&(s=r.pop());const a={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((f,..._)=>(this._queue[0],f!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),s&&s(f)):(this._queue.shift(),s&&s(null,..._)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(r=!1){if(!this.connected||this._queue.length===0)return;const s=this._queue[0];s.pending&&!r||(s.pending=!0,s.tryCount++,this.flags=s.flags,this.emit.apply(this,s.args))}packet(r){r.nsp=this.nsp,this.io._packet(r)}onopen(){typeof this.auth=="function"?this.auth(r=>{this._sendConnectPacket(r)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(r){this.packet({type:Xe.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},r):r})}onerror(r){this.connected||this.emitReserved("connect_error",r)}onclose(r,s){this.connected=!1,delete this.id,this.emitReserved("disconnect",r,s),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(r=>{if(!this.sendBuffer.some(a=>String(a.id)===r)){const a=this.acks[r];delete this.acks[r],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(r){if(r.nsp===this.nsp)switch(r.type){case Xe.CONNECT:r.data&&r.data.sid?this.onconnect(r.data.sid,r.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Xe.EVENT:case Xe.BINARY_EVENT:this.onevent(r);break;case Xe.ACK:case Xe.BINARY_ACK:this.onack(r);break;case Xe.DISCONNECT:this.ondisconnect();break;case Xe.CONNECT_ERROR:this.destroy();const a=new Error(r.data.message);a.data=r.data.data,this.emitReserved("connect_error",a);break}}onevent(r){const s=r.data||[];r.id!=null&&s.push(this.ack(r.id)),this.connected?this.emitEvent(s):this.receiveBuffer.push(Object.freeze(s))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const s=this._anyListeners.slice();for(const a of s)a.apply(this,r)}super.emit.apply(this,r),this._pid&&r.length&&typeof r[r.length-1]=="string"&&(this._lastOffset=r[r.length-1])}ack(r){const s=this;let a=!1;return function(...f){a||(a=!0,s.packet({type:Xe.ACK,id:r,data:f}))}}onack(r){const s=this.acks[r.id];typeof s=="function"&&(delete this.acks[r.id],s.withError&&r.data.unshift(null),s.apply(this,r.data))}onconnect(r,s){this.id=r,this.recovered=s&&this._pid===s,this._pid=s,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(r=>this.emitEvent(r)),this.receiveBuffer=[],this.sendBuffer.forEach(r=>{this.notifyOutgoingListeners(r),this.packet(r)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(r=>r()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Xe.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const s=this._anyListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const s=this._anyOutgoingListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const s=this._anyOutgoingListeners.slice();for(const a of s)a.apply(this,r.data)}}}function hn(d){d=d||{},this.ms=d.min||100,this.max=d.max||1e4,this.factor=d.factor||2,this.jitter=d.jitter>0&&d.jitter<=1?d.jitter:0,this.attempts=0}hn.prototype.duration=function(){var d=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),s=Math.floor(r*this.jitter*d);d=(Math.floor(r*10)&1)==0?d-s:d+s}return Math.min(d,this.max)|0};hn.prototype.reset=function(){this.attempts=0};hn.prototype.setMin=function(d){this.ms=d};hn.prototype.setMax=function(d){this.max=d};hn.prototype.setJitter=function(d){this.jitter=d};class vo extends $t{constructor(r,s){var a;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(s=r,r=void 0),s=s||{},s.path=s.path||"/socket.io",this.opts=s,Gi(this,s),this.reconnection(s.reconnection!==!1),this.reconnectionAttempts(s.reconnectionAttempts||1/0),this.reconnectionDelay(s.reconnectionDelay||1e3),this.reconnectionDelayMax(s.reconnectionDelayMax||5e3),this.randomizationFactor((a=s.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new hn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(s.timeout==null?2e4:s.timeout),this._readyState="closed",this.uri=r;const f=s.parser||ay;this.encoder=new f.Encoder,this.decoder=new f.Decoder,this._autoConnect=s.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(r){return arguments.length?(this._reconnection=!!r,r||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(r){return r===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=r,this)}reconnectionDelay(r){var s;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(s=this.backoff)===null||s===void 0||s.setMin(r),this)}randomizationFactor(r){var s;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(s=this.backoff)===null||s===void 0||s.setJitter(r),this)}reconnectionDelayMax(r){var s;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(s=this.backoff)===null||s===void 0||s.setMax(r),this)}timeout(r){return arguments.length?(this._timeout=r,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(r){if(~this._readyState.indexOf("open"))return this;this.engine=new Kg(this.uri,this.opts);const s=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const f=Sr(s,"open",function(){a.onopen(),r&&r()}),_=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=Sr(s,"error",_);if(this._timeout!==!1){const R=this._timeout,S=this.setTimeoutFn(()=>{f(),_(new Error("timeout")),s.close()},R);this.opts.autoUnref&&S.unref(),this.subs.push(()=>{this.clearTimeoutFn(S)})}return this.subs.push(f),this.subs.push(C),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(Sr(r,"ping",this.onping.bind(this)),Sr(r,"data",this.ondata.bind(this)),Sr(r,"error",this.onerror.bind(this)),Sr(r,"close",this.onclose.bind(this)),Sr(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(s){this.onclose("parse error",s)}}ondecoded(r){Vi(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){this.emitReserved("error",r)}socket(r,s){let a=this.nsps[r];return a?this._autoConnect&&!a.active&&a.connect():(a=new rf(this,r,s),this.nsps[r]=a),a}_destroy(r){const s=Object.keys(this.nsps);for(const a of s)if(this.nsps[a].active)return;this._close()}_packet(r){const s=this.encoder.encode(r);for(let a=0;a<s.length;a++)this.engine.write(s[a],r.options)}cleanup(){this.subs.forEach(r=>r()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(r,s){var a;this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,s),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const r=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const s=this.backoff.duration();this._reconnecting=!0;const a=this.setTimeoutFn(()=>{r.skipReconnect||(this.emitReserved("reconnect_attempt",r.backoff.attempts),!r.skipReconnect&&r.open(f=>{f?(r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",f)):r.onreconnect()}))},s);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){const r=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",r)}}const ei={};function Bi(d,r){typeof d=="object"&&(r=d,d=void 0),r=r||{};const s=Qg(d,r.path||"/socket.io"),a=s.source,f=s.id,_=s.path,C=ei[f]&&_ in ei[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let S;return R?S=new vo(a,r):(ei[f]||(ei[f]=new vo(a,r)),S=ei[f]),s.query&&!r.query&&(r.query=s.queryKey),S.socket(s.path,r)}Object.assign(Bi,{Manager:vo,Socket:rf,io:Bi,connect:Bi});function ly({wsUrl:d,log:r}){let s=null;function a({authPayload:C,queryToken:R}){const S=Bi(d,{transports:["polling"],timeout:2e4,reconnection:!1,auth:C,query:R?{token:R}:void 0});return s=S,S}function f(){if(s){try{s.removeAllListeners(),s.connected?s.disconnect():s.close()}catch{}s=null}}function _(){return s}return{connectSocketRaw:a,cleanupSocket:f,getSocket:_}}const uy=d=>{if(window.audioCtx=d,d.state!=="suspended")return;const r=document.body,s=["touchstart","touchend","mousedown","keydown"];s.forEach(_=>r.addEventListener(_,a,!1));function a(){d.resume().then(f)}function f(){s.forEach(_=>r.removeEventListener(_,a))}};function Ot(d){this.init(d)}Ot.prototype.init=function(d){var r={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},r,d),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};Ot.prototype.getMaxValue=function(){var d={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ot.prototype.getTypedArray=function(){var d={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ot.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),uy(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Ot.prototype.resetState=function(){this.playingStartTime=-1,this.lastGotTimestamp=0,this.samples=new Float32Array,this.timeout=void 0,this.flag_request_stop=!1,this.startTime=0};Ot.prototype.isTypedArray=function(d){return d.byteLength&&d.buffer&&d.buffer.constructor==ArrayBuffer};Ot.prototype.feed=function(d){if(this.isTypedArray(d)){d=this.getFormatedValue(d);var r=new Float32Array(this.samples.length+d.length);r.set(this.samples,0),r.set(d,this.samples.length),this.samples=r,this.timeout||this.flush()}};Ot.prototype.getFormatedValue=function(r){var r=new this.typedArray(r.buffer),s=new Float32Array(r.length),a;for(a=0;a<r.length;a++)s[a]=r[a]/this.maxValue;return s};Ot.prototype.volume=function(d){this.gainNode.gain.value=d};Ot.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Ot.prototype.getTimestamp=function(d){if(this.playingStartTime>=0){if(!d)return this.audioCtx.currentTime-this.playingStartTime;const r=this.lastGotTimestamp;return this.lastGotTimestamp+=d/1e3,r}return 0};Ot.prototype.setRequestStop=function(){this.flag_request_stop=!0};Ot.prototype.setOnEnd=function(d){this.onEnd=d};Ot.prototype.interrupt=function(d){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};Ot.prototype.ensuredSetTimeout=(function(){let d;return function(r,s){d=performance.now();const a=f=>{f-d>=s?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Ot.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Ot.prototype.flush=function(){if(this.samples.length){var d=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,s=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,f,_,C,R;for(f=0;f<this.option.channels;f++)for(a=s.getChannelData(f),_=f,R=50,C=0;C<r;C++)a[C]=this.samples[_],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),_+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,d.buffer=s,d.connect(this.gainNode),d.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=d,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=s.duration,this.flag_request_stop)this.flag_request_stop=!1,d.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const S=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,S-50)}}};function dy(d,r){const s=new Ot(d),a=s.destroy.bind(s);let f=!1;return s.destroy=()=>{if(!f){f=!0;try{a()}catch{}}},s.setOnEnd(()=>{f||r()}),s._isDestroyed=()=>f,s}function cy({enableAudio:d,pcmOptions:r,log:s,onPlaybackComplete:a}){let f=null,_=null;function C(){if(!d||f)return f;const W={...Gp,...r||{}};return f=dy(W,()=>{a()}),f}function R(){if(f){try{f.interrupt?.(),f.destroy?.()}catch{}f=null}}function S(W){const ne=C();if(ne)try{ne.feed(W)}catch(fe){s("feedAudio: player.feed() failed",fe),a()}}function N(){if(!f){a();return}try{f.setRequestStop(),f.playingBufferNode||f.scheduledBufferNode||a()}catch(W){s("requestStop: setRequestStop() failed",W),a()}}function z(){R()}function te(){if(f)try{const W=f.audioCtx;W?.state==="running"&&W.suspend()}catch(W){s("pauseAudioPlayback: audioCtx.suspend() failed",W)}}async function j(){const W=C();if(W)try{const ne=W.audioCtx;ne?.state==="suspended"&&await ne.resume()}catch(ne){s("resumeAudioPlayback: audioCtx.resume() failed",ne)}}function se(W){_=W||null}function J(){return _}function Y(){return f?f._isDestroyed?.()??!0:!0}return{ensurePcmPlayer:C,destroyPcmPlayer:R,feedAudio:S,requestStop:N,interruptPlayback:z,pauseAudioPlayback:te,resumeAudioPlayback:j,attachAudioElement:se,getAudioElement:J,isDestroyed:Y}}function hy(d){const{wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:_,withCredentials:C,onPlaybackComplete:R}=d,S=ae.useCallback((...j)=>{_&&console.log("[RqmiiSDK]",...j)},[_]),N=ae.useRef(null),z=ae.useRef(null),te=ae.useRef(null);return N.current||(N.current=ly({wsUrl:r,log:S})),z.current||(z.current=cy({enableAudio:a,pcmOptions:f,log:S,onPlaybackComplete:R})),te.current||(te.current=fg({restUrl:s,log:S,withCredentials:C})),ae.useEffect(()=>()=>{N.current?.cleanupSocket(),z.current?.destroyPcmPlayer()},[]),{socketMgrRef:N,audioMgrRef:z,sessionMgrRef:te,log:S}}function eo(d){return String(d||"").toLowerCase().replaceAll("-","_")}function py(d){if(!d)return null;if(d instanceof Uint8Array)return d;if(d instanceof ArrayBuffer)return new Uint8Array(d);if(typeof d=="object"&&d!==null){const r=d;if(r.buffer instanceof ArrayBuffer){const s=d,a=Number.isInteger(s.byteOffset)?s.byteOffset:0,f=Number.isInteger(s.byteLength)?s.byteLength:s.buffer.byteLength-a;return new Uint8Array(s.buffer,a,f)}if(r.type==="Buffer"&&Array.isArray(r.data))return new Uint8Array(r.data)}try{return new Uint8Array(d)}catch{return null}}function fy(d){const{socket:r,dispatch:s,stateRef:a,sessionIdRef:f,sessionAgentTypeRef:_,interruptedRef:C,manualDisconnectRef:R,chunkAccumulatorRef:S,clientToolsRef:N,audioMgrRef:z,enableAudio:te,cbRefs:j,eventsEmitter:se}=d,J=br,Y=z.current;r.on(J.DISCONNECT,W=>{if(s({type:"SET_CONNECTION_STATE",payload:pt.IDLE}),s({type:"SET_SESSION_READY",payload:!1}),j.current.onDisconnect?.(W),W==="io server disconnect"||W==="io client disconnect"||R.current){s({type:"SET_CONNECTION_STATE",payload:pt.ENDED});return}s({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),s({type:"SET_ERROR",payload:"Connection lost"})}),r.on(J.SESSION_READY,W=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null}),W?.agentType&&s({type:"UPDATE_SESSION",payload:{agentType:eo(W.agentType)}})}),r.on(J.SESSION_JOINED,()=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null})}),r.on(J.SESSION_TERMINATED,()=>{Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),s({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),j.current.onSessionTerminated?.(),r.disconnect()}),r.on(J.TRANSCRIPT,W=>{const ne=W||null;s({type:"SET_TRANSCRIPT",payload:ne}),ne?.is_final&&ne?.text?.trim()&&(s({type:"ADD_MESSAGE",payload:{id:`transcript-${Date.now()}`,role:"user",text:ne.text.trim(),timestamp:new Date().toISOString()}}),s({type:"SET_PARTIAL_TRANSCRIPT",payload:null})),se.emit("transcript",ne??void 0),se.emit("partial_transcript",void 0)}),r.on(J.PARTIAL_TRANSCRIPT,W=>{const ne=typeof W=="string"?W:W?.text;if(typeof ne=="string"&&ne.length===0)return;const fe=W||null;s({type:"SET_PARTIAL_TRANSCRIPT",payload:fe}),se.emit("partial_transcript",fe??void 0)}),r.on(J.AGENT_RESPONSE_CHUNK,W=>{const{id:ne,text:fe}=S.current.addChunk(W?.requestId,W?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==ne),{id:ne,role:"assistant",text:fe,streaming:!0,timestamp:new Date().toISOString()}]})}),r.on(J.AGENT_RESPONSE,W=>{const{id:ne,text:fe}=S.current.consume(W?.requestId,W?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==ne),{id:ne,role:"assistant",text:fe,streaming:!1,timestamp:new Date().toISOString()}]})}),r.on(J.AVATAR_SPEAKING,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!0})}),r.on(J.AVATAR_SPEAKING_DONE,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!1})}),r.on(J.AGENT_AUDIO_CHUNK,W=>{if(!te||C.current)return;const ne=eo(_.current);if(ne==="cloud_avatar"||ne==="desktop_avatar"||ne==="text")return;const fe=py(W?.audio);fe&&(Y.feedAudio(fe),s({type:"SET_AUDIO_PLAYING",payload:!0}))}),r.on(J.AGENT_AUDIO_COMPLETE,()=>{if(!te)return;const W=eo(_.current);W==="cloud_avatar"||W==="desktop_avatar"||W==="text"||Y.requestStop()}),r.on(J.INTERRUPTED,()=>{const W=!Y.isDestroyed();C.current=!1,Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),W&&r.connected&&r.emit(J.AUDIO_PLAYBACK_COMPLETE,{session_id:f.current})}),r.on(J.AUTH_ERROR,W=>{s({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),s({type:"SET_ERROR",payload:W?.message||"Authentication error"})}),r.on(J.ERROR,W=>{const ne=W?.code;if(!(ne==="TTS_ERROR"||ne==="STT_ERROR"||ne==="LLM_ERROR")){if(ne==="INSUFFICIENT_CREDITS"){s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:W?.message||"Insufficient credits to process this request."}}),j.current.onError?.(W);return}s({type:"SET_ERROR",payload:W?.message||W?.detail||"Server error"}),j.current.onError?.(W)}}),r.on(J.SESSION_EXPIRED,W=>{s({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),j.current.onSessionExpired?.(W)}),r.on(J.CREDITS_EXHAUSTED,()=>{s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:"This project has run out of credits."}}),s({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),R.current=!0;try{r.disconnect()}catch{}}),r.on(J.SESSION_STATE_CHANGED,W=>{W?.state&&s({type:"SET_SESSION_STATE",payload:W.state})}),r.on(J.LANGUAGE_CHANGED,W=>{const ne=W?.language;ne&&se.emit("language_changed",{language:ne})}),r.on(J.SHOW_LEAD_CAPTURE_FORM,W=>{const ne=Array.isArray(W?.fields)?W.fields:[],fe=W?.agentId;!fe||ne.length===0||s({type:"ADD_MESSAGE",payload:{id:`lead-form-${Date.now()}`,role:"lead_form",text:"",form:{agentId:fe,title:W?.title,fields:ne},timestamp:new Date().toISOString()}})}),r.on(J.MESSAGE_RATE_LIMITED,W=>{se.emit("message_rate_limited",W)}),r.on(J.CLIENT_TOOL_REQUEST,W=>{const ne=W?.executionId,fe=W?.toolName,de=W?.parameters??{},ce=W?.waitForResponse!==!1;if(!fe)return;const pe=N.current[fe];if(!pe)return;const he={minimize:()=>se.emit("minimize_chat"),maximize:()=>se.emit("maximize_chat")};ce&&ne?pe(de,he).then(Ve=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:ne,result:Ve})}).catch(Ve=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:ne,result:{error:Ve instanceof Error?Ve.message:String(Ve)}})}):pe(de,he).catch(()=>{})})}class sf{listeners=new Map;on(r,s){return this.listeners.has(r)||this.listeners.set(r,new Set),this.listeners.get(r).add(s),()=>this.off(r,s)}once(r,s){const a=((...f)=>{this.off(r,a),s(...f)});return this.on(r,a)}off(r,s){this.listeners.get(r)?.delete(s)}emit(r,s){const a=this.listeners.get(r);if(a)for(const f of a)try{f(s)}catch{}}removeAllListeners(){this.listeners.clear()}}const nf=ae.createContext(null);function af({children:d,wsUrl:r,restUrl:s,enableAudio:a=!0,pcmOptions:f,debug:_=!1,heartbeatIntervalSeconds:C=15,withCredentials:R=!1,onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te}){const[j,se]=ae.useReducer(hp,po),J=ae.useRef(j),Y=ae.useCallback(be=>{J.current=hp(J.current,be),se(be)},[]),W=ae.useRef(!1),ne=ae.useRef(hg()),fe=ae.useRef(null),de=ae.useRef(po.session.agentType),ce=ae.useRef(!1),pe=ae.useRef(new sf),he=ae.useRef({}),Ve=ae.useRef({onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te});ae.useEffect(()=>{Ve.current={onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te}},[S,N,z,te]),ae.useEffect(()=>{de.current=j.session.agentType},[j.session.agentType]),ae.useEffect(()=>{fe.current=j.session.sessionId},[j.session.sessionId]);const me=ae.useCallback(()=>{Y({type:"SET_AUDIO_PLAYING",payload:!1});const be=Ye.current?.getSocket();be?.connected&&be.emit(br.AUDIO_PLAYBACK_COMPLETE,{session_id:fe.current})},[]),{socketMgrRef:Ye,audioMgrRef:qe,sessionMgrRef:it}=hy({wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:_,withCredentials:R,onPlaybackComplete:me}),Je=ae.useCallback(be=>{fy({socket:be,dispatch:Y,stateRef:J,sessionIdRef:fe,sessionAgentTypeRef:de,interruptedRef:ce,manualDisconnectRef:W,chunkAccumulatorRef:ne,clientToolsRef:he,audioMgrRef:{current:qe.current},enableAudio:a,cbRefs:Ve,eventsEmitter:pe.current})},[a]),at=ae.useCallback(({authPayload:be,queryToken:Ze})=>new Promise((Bt,nr)=>{Ye.current?.cleanupSocket();const It=Ye.current.connectSocketRaw({authPayload:be,queryToken:Ze});Je(It),It.once("connect",()=>{Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTED}),Y({type:"SET_ERROR",payload:null}),Bt(It)}),It.once("connect_error",xr=>{Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:xr?.message||"Connection error"}),nr(xr)})}),[Je]),tt=ae.useCallback(({keepManualDisconnect:be=!1}={})=>{W.current=!0,ce.current=!1,ne.current.clear(),qe.current.destroyPcmPlayer(),Ye.current.cleanupSocket(),be||(W.current=!1),Y({type:"HARD_RESET"})},[]),qt=ae.useCallback(async({apiKey:be,publicChatId:Ze,agentId:Bt,userId:nr,language:It="en",clientTools:xr,config:yt}={})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!be&&!Ze&&!Bt)throw new Error("Provide one of apiKey, publicChatId, or agentId");tt(),he.current=xr??{},Y({type:"SET_CONNECTION_STATE",payload:pt.INITIALIZING}),Y({type:"SET_ERROR",payload:null});const Lr=pg();let Br;try{Br=await it.current.initializeSession({apiKey:be,publicChatId:Ze,agentId:Bt,userId:nr,language:It,timezone:Lr,config:yt})}catch(ir){const Wt=ir;throw Wt.status===401||Wt.status===403?(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Wt.message||"Authentication failed"})):Wt.status===402?(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:Wt.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED})):Wt.status===429?(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Wt.message||"Too many requests. Please try again later."})):(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Wt.message||"Failed to initialize session"})),ir}const Nt=Br;Y({type:"UPDATE_SESSION",payload:{sessionId:Nt.session_id,agentType:Nt.streaming_url?ci.CLOUD_AVATAR:j.session.agentType,streamingUrl:Nt.streaming_url||null,uniqueId:Nt.unique_id||null}}),Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Nt.streaming_url?Zt.CONNECTING:Zt.IDLE,error:null}}),W.current=!0;try{await at({authPayload:{token:Nt.session_token},queryToken:Nt.session_token}),W.current=!1}catch(ir){throw W.current=!1,ir}return Br},[at,tt,r,j.session.agentType]),xt=ae.useCallback(async({uniqueId:be})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!be)throw new Error("uniqueId is required");tt(),Y({type:"SET_CONNECTION_STATE",payload:pt.INITIALIZING}),Y({type:"SET_ERROR",payload:null});let Ze;try{Ze=await it.current.joinDesktopSession({uniqueId:be})}catch(nr){const It=nr;throw(It.status===401||It.status===403)&&(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Authentication failed"})),It.status===402&&(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:It.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED})),It.status===429&&(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Too many requests. Please try again later."})),nr}const Bt=Ze;Y({type:"UPDATE_SESSION",payload:{sessionId:Bt.session_id,uniqueId:be,role:"user",agentType:ci.DESKTOP_AVATAR}}),Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Zt.IDLE,error:null}}),W.current=!0;try{await at({authPayload:{token:Bt.session_token},queryToken:Bt.session_token}),W.current=!1}catch(nr){throw W.current=!1,nr}return Ze},[at,tt,r]),Ke=ae.useCallback(()=>tt({keepManualDisconnect:!0}),[tt]),We=ae.useCallback(async()=>{const be=Ye.current?.getSocket();return be&&j.isConnected&&(be.emit("end_session"),await new Promise(Ze=>setTimeout(Ze,150))),Ke(),{success:!0}},[Ke,j.isConnected]),st=ae.useCallback(()=>{const be=Ye.current?.getSocket();be?.connected?be.emit("end_session"):(Y({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),Y({type:"SET_SESSION_READY",payload:!1}))},[]),ze=ae.useCallback((be,Ze={})=>{const Bt=Ye.current?.getSocket();return!Bt||!j.isConnected?!1:(Bt.emit(be,Ze),!0)},[j.isConnected]),Rt=ae.useCallback(be=>!be||!String(be).trim()?!1:(Y({type:"ADD_MESSAGE",payload:{id:`user-${Date.now()}`,role:"user",text:String(be),timestamp:new Date().toISOString()}}),ze(br.USER_MESSAGE,{message:String(be)})),[ze]),sr=ae.useCallback((be,Ze)=>{!Ze||!String(Ze).trim()||Y({type:"ADD_MESSAGE",payload:{id:`${be}-${Date.now()}`,role:be,text:String(Ze),timestamp:new Date().toISOString()}})},[]),Xr=ae.useCallback(be=>!be||!String(be).trim()?!1:ze(br.USER_MESSAGE,{message:String(be)}),[ze]),Vs=ae.useCallback(be=>ze(br.AUDIO_CHUNK,{audio:be}),[ze]),Yr=ae.useCallback(()=>ze(br.AUDIO_END,{}),[ze]),Jr=ae.useCallback(()=>(ce.current=!0,qe.current.interruptPlayback(),Y({type:"SET_AUDIO_PLAYING",payload:!1}),ze(br.INTERRUPT,{})),[ze]),Gs=ae.useCallback(()=>ze(br.CLEAR_SESSION_HISTORY,{}),[ze]),rt=ae.useCallback(be=>be?ze(br.CHANGE_SESSION_LANGUAGE,{language:be}):!1,[ze]),Er=ae.useCallback((be={})=>ze(br.CLIENT_READY,be),[ze]),lt=ae.useCallback(()=>{ne.current.clear(),Y({type:"SET_MESSAGES",payload:[]})},[]),Zr=ae.useCallback(be=>{Y({type:"SET_MESSAGES",payload:be})},[]),er=ae.useCallback(()=>qe.current.resumeAudioPlayback(),[]),$r=ae.useCallback(()=>qe.current.pauseAudioPlayback(),[]),gt=ae.useCallback(be=>qe.current.attachAudioElement(be),[]),ft=ae.useCallback((be,Ze=null)=>{Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:be,error:Ze?String(Ze):null}})},[]),At=ae.useCallback(async be=>{if(!s)throw new Error("Missing restUrl in RqmiiAgentProvider");try{const Ze=await it.current.fetchAgentConfig(be);return Y({type:"SET_AGENT_CONFIG",payload:Ze}),Ze}catch(Ze){throw Y({type:"SET_AGENT_CONFIG",payload:null}),Ze}},[s]),Ct=ae.useCallback(be=>{he.current={...he.current,...be}},[]),es=ae.useCallback(be=>{const Ze=be.sessionId||fe.current;return Ze?it.current.submitFeedback({sessionId:Ze,rating:be.rating,feedback:be.feedback,endedBy:be.endedBy}):Promise.reject(new Error("No session id available for feedback"))},[]),ts=ae.useCallback(be=>{const Ze=be.sessionId||fe.current;return Ze?it.current.submitLead({agentId:be.agentId,sessionId:Ze,collectedData:be.collectedData}):Promise.reject(new Error("No session id available for lead capture"))},[]),qs=ae.useMemo(()=>cg(j.sessionState),[j.sessionState]),zr=ae.useMemo(()=>({...j,...qs,initializeSession:qt,joinDesktopSession:xt,disconnect:Ke,terminateSession:We,endSession:st,emit:ze,sendTextMessage:Rt,addLocalMessage:sr,emitUserMessage:Xr,sendAudioChunk:Vs,endAudioStream:Yr,interrupt:Jr,clearSessionHistory:Gs,changeSessionLanguage:rt,signalClientReady:Er,clearMessages:lt,setMessages:Zr,resumeAudioPlayback:er,pauseAudioPlayback:$r,attachAudioElement:gt,fetchAgentConfig:At,submitFeedback:es,submitLead:ts,setCloudStreamState:ft,registerClientTools:Ct,events:pe.current,audioElement:qe.current?.getAudioElement()??null,socket:Ye.current?.getSocket()??null}),[j,qs,qt,xt,Ke,We,st,ze,Rt,sr,Xr,Vs,Yr,Jr,Gs,rt,Er,lt,Zr,er,$r,gt,ft,Ct,es,ts]);return Jt.jsx(nf.Provider,{value:zr,children:d})}function Fs(){const d=ae.useContext(nf);if(!d)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return d}function of(){const d=Fs();return{connectionState:d.connectionState,isConnected:d.isConnected,isSessionReady:d.isSessionReady,error:d.error,session:d.session,creditExhausted:d.creditExhausted,creditError:d.creditError,sessionState:d.sessionState,isSessionTerminated:d.isSessionTerminated,isSessionTerminating:d.isSessionTerminating,isAgentThinking:d.isAgentThinking,isAgentSpeaking:d.isAgentSpeaking,isToolExecuting:d.isToolExecuting,agentConfig:d.agentConfig,initializeSession:d.initializeSession,joinDesktopSession:d.joinDesktopSession,disconnect:d.disconnect,terminateSession:d.terminateSession,endSession:d.endSession,interrupt:d.interrupt,clearSessionHistory:d.clearSessionHistory,changeSessionLanguage:d.changeSessionLanguage,signalClientReady:d.signalClientReady,fetchAgentConfig:d.fetchAgentConfig,submitFeedback:d.submitFeedback,registerClientTools:d.registerClientTools,events:d.events}}function my(){const d=Fs();return{messages:d.messages,sendTextMessage:d.sendTextMessage,addLocalMessage:d.addLocalMessage,emitUserMessage:d.emitUserMessage,clearMessages:d.clearMessages}}function gy(){const d=Fs();return{sendAudioChunk:d.sendAudioChunk,endAudioStream:d.endAudioStream,isAudioPlaying:d.isAudioPlaying,transcript:d.transcript,partialTranscript:d.partialTranscript,interrupt:d.interrupt,resumeAudioPlayback:d.resumeAudioPlayback,pauseAudioPlayback:d.pauseAudioPlayback,attachAudioElement:d.attachAudioElement}}function lf(){const d=Fs(),r=d.cloudStream?.state||Zt.IDLE;return{streamingUrl:d.session.streamingUrl,isAvatarSpeaking:d.isAvatarSpeaking,speakingSource:"avatar_events",isCloudAvatar:d.session.agentType===ci.CLOUD_AVATAR,isDesktopAvatar:d.session.agentType===ci.DESKTOP_AVATAR,cloudStreamState:r,cloudStreamError:d.cloudStream?.error||null,isCloudStreamConnected:r===Zt.CONNECTED,isCloudStreamLoading:r===Zt.CONNECTING||r===Zt.LOADING,setCloudStreamState:d.setCloudStreamState}}var to={},ro={},ti={},wp;function uf(){if(wp)return ti;wp=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.baseAssetPath=void 0;const r=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let s="/";return r&&(s=r.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),ti.baseAssetPath=s,ti}var ri={},vp;function Io(){if(vp)return ri;vp=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.defaultModelFetcher=void 0;const d=r=>fetch(r).then(s=>s.arrayBuffer());return ri.defaultModelFetcher=d,ri}var Wr={},si={},_p;function hi(){if(_p)return si;_p=1,Object.defineProperty(si,"__esModule",{value:!0}),si.log=void 0;const d=r=>s=>{console.log(`VAD | ${r} >`,s)};return si.log={error:d("error"),debug:d("debug"),warn:d("warn")},si}var ni={},bp;function qi(){if(bp)return ni;bp=1,Object.defineProperty(ni,"__esModule",{value:!0}),ni.Message=void 0;var d;return(function(r){r.AudioFrame="AUDIO_FRAME",r.SpeechStart="SPEECH_START",r.VADMisfire="VAD_MISFIRE",r.SpeechEnd="SPEECH_END",r.SpeechStop="SPEECH_STOP",r.SpeechRealStart="SPEECH_REAL_START",r.FrameProcessed="FRAME_PROCESSED"})(d||(ni.Message=d={})),ni}var Sp;function Mo(){if(Sp)return Wr;Sp=1,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.FrameProcessor=Wr.validateOptions=Wr.defaultFrameProcessorOptions=void 0;const d=hi(),r=qi();Wr.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function s(C){(C.positiveSpeechThreshold<0||C.positiveSpeechThreshold>1)&&d.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(C.negativeSpeechThreshold<0||C.negativeSpeechThreshold>C.positiveSpeechThreshold)&&d.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),C.preSpeechPadMs<0&&d.log.error("preSpeechPadMs should be positive"),C.redemptionMs<0&&d.log.error("redemptionMs should be positive"),C.minSpeechMs<0&&d.log.error("minSpeechMs should be positive")}Wr.validateOptions=s;const a=C=>{const R=C.reduce((N,z)=>(N.push(N.at(-1)+z.length),N),[0]),S=new Float32Array(R.at(-1));return C.forEach((N,z)=>{const te=R[z];S.set(N,te)}),S};function f(C,R){const S=Math.floor(C.redemptionMs/R),N=Math.floor(C.preSpeechPadMs/R),z=Math.floor(C.minSpeechMs/R);return{redemptionFrames:S,preSpeechPadFrames:N,minSpeechFrames:z}}class _{constructor(R,S,N,z){this.modelProcessFunc=R,this.modelResetFunc=S,this.options=N,this.msPerFrame=z,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=J=>{this.options={...this.options,...J};const{redemptionFrames:Y,preSpeechPadFrames:W,minSpeechFrames:ne}=f(this.options,this.msPerFrame);this.redemptionFrames=Y,this.preSpeechPadFrames=W,this.minSpeechFrames=ne},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=J=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(J):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=J=>{const Y=this.audioBuffer;this.audioBuffer=[];const W=this.speaking;if(this.reset(),W)if(Y.reduce((fe,de)=>de.isSpeech?fe+1:fe,0)>=this.minSpeechFrames){const fe=a(Y.map(de=>de.frame));J({msg:r.Message.SpeechEnd,audio:fe})}else J({msg:r.Message.VADMisfire});return{}},this.process=async(J,Y)=>{if(!this.active)return;const W=await this.modelProcessFunc(J),ne=W.isSpeech>=this.options.positiveSpeechThreshold;if(Y({probs:W,msg:r.Message.FrameProcessed,frame:J}),this.audioBuffer.push({frame:J,isSpeech:ne}),ne&&(this.speechFrameCount++,this.redemptionCounter=0),ne&&!this.speaking&&(this.speaking=!0,Y({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,Y({msg:r.Message.SpeechRealStart})),W.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const fe=this.audioBuffer;if(this.audioBuffer=[],fe.reduce((ce,pe)=>pe.isSpeech?ce+1:ce,0)>=this.minSpeechFrames){const ce=a(fe.map(pe=>pe.frame));Y({msg:r.Message.SpeechEnd,audio:ce})}else Y({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:te,preSpeechPadFrames:j,minSpeechFrames:se}=f(this.options,this.msPerFrame);this.redemptionFrames=te,this.preSpeechPadFrames=j,this.minSpeechFrames=se,this.reset()}}return Wr.FrameProcessor=_,Wr}var Hr={};function dr(d){throw new Error('Could not dynamically require "'+d+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var so={exports:{}};/*!
|
|
2
2
|
* ONNX Runtime Web v1.26.0
|
|
3
3
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
4
4
|
* Licensed under the MIT License.
|
|
5
|
-
*/var Tp;function yy(){return Tp||(Tp=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,_=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(e=>typeof ur<"u"?ur:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof ur<"u"?ur:t)[n]}):e)(function(e){if(typeof ur<"u")return ur.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),b=(e,t)=>()=>(e&&(t=e(e=0)),t),U=(e,t)=>{for(var n in t)a(e,n,{get:t[n],enumerable:!0})},z=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _(t))!C.call(e,o)&&o!==n&&a(e,o,{get:()=>t[o],enumerable:!(i=f(t,o))||i.enumerable});return e},re=e=>z(a({},"__esModule",{value:!0}),e),K,se,J,Y,H,ne=b(()=>{K=new Map,se=[],J=(e,t,n)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=K.get(e);if(i===void 0)K.set(e,{backend:t,priority:n});else{if(i.priority>n)return;if(i.priority===n&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let o=se.indexOf(e);o!==-1&&se.splice(o,1);for(let l=0;l<se.length;l++)if(K.get(se[l]).priority<=n){se.splice(l,0,e);return}se.push(e)}return}throw new TypeError("not a valid backend")},Y=async e=>{let t=K.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return n||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},H=async e=>{let t=e.executionProviders||[],n=t.map(h=>typeof h=="string"?h:h.name),i=n.length===0?se:n,o,l=[],u=new Set;for(let h of i){let p=await Y(h);typeof p=="string"?l.push({name:h,err:p}):(o||(o=p),o===p&&u.add(h))}if(!o)throw new Error(`no available backend found. ERR: ${l.map(h=>`[${h.name}] ${h.err}`).join(", ")}`);for(let{name:h,err:p}of l)n.includes(h)&&console.warn(`removing requested execution provider "${h}" from session options because it is not available: ${p}`);let c=t.filter(h=>u.has(typeof h=="string"?h:h.name));return[o,new Proxy(e,{get:(h,p)=>p==="executionProviders"?c:Reflect.get(h,p)})]}}),ve=b(()=>{ne()}),de,ce=b(()=>{de="1.26.0"}),pe,he,Ve=b(()=>{ce(),pe="warning",he={wasm:{},webgl:{},webgpu:{},versions:{common:de},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}`);pe=e}},get logLevel(){return pe}},Object.defineProperty(he,"logLevel",{enumerable:!0})}),fe,Je=b(()=>{Ve(),fe=he}),qe,ot,Ze=b(()=>{qe=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let i=n.getContext("2d");if(i!=null){let o,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[3]):(o=e.dims[3],l=e.dims[2]);let u=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],0],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=l*o,g=0,w=m,v=m*2,S=-1;u==="RGBA"?(g=0,w=m,v=m*2,S=m*3):u==="RGB"?(g=0,w=m,v=m*2):u==="RBG"&&(g=0,v=m,w=m*2);for(let x=0;x<l;x++)for(let M=0;M<o;M++){let k=(e.data[g++]-p[0])*h[0],$=(e.data[w++]-p[1])*h[1],P=(e.data[v++]-p[2])*h[2],I=S===-1?255:(e.data[S++]-p[3])*h[3];i.fillStyle="rgba("+k+","+$+","+P+","+I+")",i.fillRect(M,x,1,1)}if("toDataURL"in n)return n.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},ot=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(n!=null){let o,l,u;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[1],u=e.dims[3]):(o=e.dims[3],l=e.dims[2],u=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",h=t?.norm,p,m;h===void 0||h.mean===void 0?p=[255,255,255,255]:typeof h.mean=="number"?p=[h.mean,h.mean,h.mean,h.mean]:(p=[h.mean[0],h.mean[1],h.mean[2],255],h.mean[3]!==void 0&&(p[3]=h.mean[3])),h===void 0||h.bias===void 0?m=[0,0,0,0]:typeof h.bias=="number"?m=[h.bias,h.bias,h.bias,h.bias]:(m=[h.bias[0],h.bias[1],h.bias[2],0],h.bias[3]!==void 0&&(m[3]=h.bias[3]));let g=l*o;if(t!==void 0&&(t.format!==void 0&&u===4&&t.format!=="RGBA"||u===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let w=4,v=0,S=1,x=2,M=3,k=0,$=g,P=g*2,I=-1;c==="RGBA"?(k=0,$=g,P=g*2,I=g*3):c==="RGB"?(k=0,$=g,P=g*2):c==="RBG"&&(k=0,P=g,$=g*2),i=n.createImageData(o,l);for(let B=0;B<l*o;v+=w,S+=w,x+=w,M+=w,B++)i.data[v]=(e.data[k++]-m[0])*p[0],i.data[S]=(e.data[$++]-m[1])*p[1],i.data[x]=(e.data[P++]-m[2])*p[2],i.data[M]=I===-1?255:(e.data[I++]-m[3])*p[3]}else throw new Error("Can not access image data");return i}}),it,tt,Wt,xt,je,We,st=b(()=>{Tr(),it=(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:n,width:i}=t,o=t.norm??{mean:255,bias:0},l,u;typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:l=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?u=[o.bias,o.bias,o.bias,o.bias]:u=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let c=t.format!==void 0?t.format:"RGBA",h=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=n*i,m=h==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),g=4,w=0,v=1,S=2,x=3,M=0,k=p,$=p*2,P=-1;c==="RGB"&&(g=3,w=0,v=1,S=2,x=-1),h==="RGBA"?P=p*3:h==="RBG"?(M=0,$=p,k=p*2):h==="BGR"&&($=0,k=p,M=p*2);for(let I=0;I<p;I++,w+=g,S+=g,v+=g,x+=g)m[M++]=(e[w]+u[0])/l[0],m[k++]=(e[v]+u[1])/l[1],m[$++]=(e[S]+u[2])/l[2],P!==-1&&x!==-1&&(m[P++]=(e[x]+u[3])/l[3]);return h==="RGBA"?new rt("float32",m,[1,4,n,i]):new rt("float32",m,[1,3,n,i])},tt=async(e,t)=>{let n=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,l=typeof e=="string",u,c=t??{},h=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=m=>typeof HTMLCanvasElement<"u"&&m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext("2d"):null;if(n){let m=h();m.width=e.width,m.height=e.height;let g=p(m);if(g!=null){let w=e.height,v=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(w=t.resizedHeight,v=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=w,c.width=v}else c.tensorFormat="RGBA",c.height=w,c.width=v;g.drawImage(e,0,0),u=g.getImageData(0,0,v,w).data}else throw new Error("Can not access image data")}else if(i){let m,g;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(m=t.resizedHeight,g=t.resizedWidth):(m=e.height,g=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=m,c.width=g,t!==void 0){let w=h();w.width=g,w.height=m;let v=p(w);if(v!=null)v.putImageData(e,0,0),u=v.getImageData(0,0,g,m).data;else throw new Error("Can not access image data")}else u=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let m=h();m.width=e.width,m.height=e.height;let g=p(m);if(g!=null){let w=e.height,v=e.width;return g.drawImage(e,0,0,v,w),u=g.getImageData(0,0,v,w).data,c.height=w,c.width=v,it(u,c)}else throw new Error("Can not access image data")}else{if(l)return new Promise((m,g)=>{let w=h(),v=p(w);if(!e||!v)return g();let S=new Image;S.crossOrigin="Anonymous",S.src=e,S.onload=()=>{w.width=S.width,w.height=S.height,v.drawImage(S,0,0,w.width,w.height);let x=v.getImageData(0,0,w.width,w.height);c.height=w.height,c.width=w.width,m(it(x.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return it(u,c);throw new Error("Input data provided is not supported - aborted tensor creation")},Wt=(e,t)=>{let{width:n,height:i,download:o,dispose:l}=t,u=[1,i,n,4];return new rt({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:l})},xt=(e,t)=>{let{dataType:n,dims:i,download:o,dispose:l}=t;return new rt({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:i,download:o,dispose:l})},je=(e,t)=>{let{dataType:n,dims:i,download:o,dispose:l}=t;return new rt({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:i,download:o,dispose:l})},We=(e,t,n)=>new rt({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})}),ze,At,sr,Hr,Us=b(()=>{ze=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),At=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),sr=!1,Hr=()=>{if(!sr){sr=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;e&&(ze.set("int64",BigInt64Array),At.set(BigInt64Array,"int64")),t&&(ze.set("uint64",BigUint64Array),At.set(BigUint64Array,"uint64")),i?(ze.set("float16",n),At.set(n,"float16")):ze.set("float16",Uint16Array)}}}),Kr,jr,Fs=b(()=>{Tr(),Kr=e=>{let t=1;for(let n=0;n<e.length;n++){let i=e[n];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${n}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${i}`);t*=i}return t},jr=(e,t)=>{switch(e.location){case"cpu":return new rt(e.type,e.data,t);case"cpu-pinned":return new rt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new rt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new rt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new rt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),rt,Tr=b(()=>{Ze(),st(),Us(),Fs(),rt=class{constructor(e,t,n){Hr();let i,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,o=e.dims,e.location){case"cpu-pinned":{let u=ze.get(i);if(!u)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof u))throw new TypeError(`buffer should be of type ${u.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 u,c;if(typeof e=="string")if(i=e,c=n,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");u=t}else{let h=ze.get(e);if(h===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&h===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${h.name} as data.`);e==="uint64"||e==="int64"?u=h.from(t,BigInt):u=h.from(t)}else if(t instanceof h)u=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")u=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&h!==Uint16Array)u=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${h}`)}else if(c=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let h=typeof e[0];if(h==="string")i="string",u=e;else if(h==="boolean")i="bool",u=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${h}.`)}else if(e instanceof Uint8ClampedArray)i="uint8",u=Uint8Array.from(e);else{let h=At.get(e.constructor);if(h===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=h,u=e}if(c===void 0)c=[u.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");o=c,this.cpuData=u,this.dataLocation="cpu"}let l=Kr(o);if(this.cpuData&&l!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(l/2)===this.cpuData.length))throw new Error(`Tensor's size(${l}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=o,this.size=l}static async fromImage(e,t){return tt(e,t)}static fromTexture(e,t){return Wt(e,t)}static fromGpuBuffer(e,t){return xt(e,t)}static fromMLTensor(e,t){return je(e,t)}static fromPinnedBuffer(e,t,n){return We(e,t,n)}toDataURL(e){return qe(this,e)}toImageData(e){return ot(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 jr(this,e)}}}),lt,Qr=b(()=>{Tr(),lt=rt}),er,Er,gt,yt,Ct,kt,Xr=b(()=>{Ve(),er=(e,t)=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeStamp(`${e}::ORT::${t}`)},Er=(e,t)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let o=0;o<n.length;o++){if(i&&!n[o].includes("TRACE_FUNC")){let l=`FUNC_${e}::${n[o].trim().split(" ")[1]}`;t&&(l+=`::${t}`),er("CPU",l);return}n[o].includes("TRACE_FUNC")&&(i=!0)}},gt=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||Er("BEGIN",e)},yt=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||Er("END",e)},Ct=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.time(`ORT::${e}`)},kt=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeEnd(`ORT::${e}`)}}),os,xe=b(()=>{ne(),Qr(),Xr(),os=class df{constructor(t){this.handler=t}async run(t,n,i){gt(),Ct("InferenceSession.run");let o={},l={};if(typeof t!="object"||t===null||t instanceof lt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let u=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof lt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");u=!1;for(let p of n){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);o[p]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,m=Object.getOwnPropertyNames(n);for(let g of this.outputNames)if(m.indexOf(g)!==-1){let w=n[g];(w===null||w instanceof lt)&&(p=!0,u=!1,o[g]=w)}if(p){if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else l=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(u)for(let p of this.outputNames)o[p]=null;let c=await this.handler.run(t,o,l),h={};for(let p in c)if(Object.hasOwnProperty.call(c,p)){let m=c[p];m instanceof lt?h[p]=m:h[p]=new lt(m.type,m.data,m.dims)}return kt("InferenceSession.run"),yt(),h}async release(){return this.handler.dispose()}static async create(t,n,i,o){gt(),Ct("InferenceSession.create");let l,u={};if(typeof t=="string"){if(l=t,typeof n=="object"&&n!==null)u=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(l=t,typeof n=="object"&&n!==null)u=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let m=t,g=0,w=t.byteLength;if(typeof n=="object"&&n!==null)u=n;else if(typeof n=="number"){if(g=n,!Number.isSafeInteger(g))throw new RangeError("'byteOffset' must be an integer.");if(g<0||g>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(w=t.byteLength-g,typeof i=="number"){if(w=i,!Number.isSafeInteger(w))throw new RangeError("'byteLength' must be an integer.");if(w<=0||g+w>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-g}].`);if(typeof o=="object"&&o!==null)u=o;else if(typeof o<"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 n<"u")throw new TypeError("'options' must be an object.");l=new Uint8Array(m,g,w)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,h]=await H(u),p=await c.createInferenceSessionHandler(l,h);return kt("InferenceSession.create"),yt(),new df(p)}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}}}),Qe,Nt=b(()=>{xe(),Qe=os}),nr=b(()=>{}),It=b(()=>{}),Yr=b(()=>{}),hn=b(()=>{}),ls={};U(ls,{InferenceSession:()=>Qe,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>Ct,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>yt,Tensor:()=>lt,env:()=>fe,registerBackend:()=>J});var ct=b(()=>{ve(),Je(),Nt(),Qr(),nr(),It(),Xr(),Yr(),hn()}),Ut=b(()=>{}),$r={};U($r,{default:()=>pn});var Lt,us,pn,Wi=b(()=>{Yh(),Ht(),fs(),Lt="ort-wasm-proxy-worker",us=globalThis.self?.name===Lt,us&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":ys(n.wasm).then(()=>{Ba(n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:o}=n;Na(o,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=n,o=ki(i);postMessage({type:t,out:o});break}case"create":{let{model:i,options:o}=n;Fa(i,o).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":Va(n),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:o,inputs:l,outputIndices:u,options:c}=n;qa(i,o,l,u,new Array(u.length).fill(null),c).then(h=>{h.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:h},Ha([...l,...h]))},h=>{postMessage({type:t,err:h})});break}case"end-profiling":Wa(n),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),pn=us?null:e=>new Worker(e??at,{type:"classic",name:Lt})}),fn,mn,at,ds,Dr,gn,yn,cs,wn,hs,vn,ps,_n,fs=b(()=>{Ut(),fn=typeof location>"u"?void 0:location.origin,mn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,at=mn(),ds=()=>{if(at&&!at.startsWith("blob:"))return at.substring(0,at.lastIndexOf("/")+1)},Dr=(e,t)=>{try{let n=t??at;return(n?new URL(e,n):new URL(e)).origin===fn}catch{return!1}},gn=(e,t)=>{let n=t??at;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},yn=(e,t)=>`${t??"./"}${e}`,cs=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},wn=async e=>(await import(e)).default,hs=(Wi(),re($r)).default,vn=async()=>{if(!at)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Dr(at))return[void 0,hs()];let e=await cs(at);return[e,hs(e)]},ps=void 0,_n=async(e,t,n,i)=>{let o=ps&&!(e||t);if(o)if(at)o=Dr(at)||i&&!n;else if(i&&!n)o=!0;else throw new Error("cannot determine the script source URL.");if(o)return[void 0,ps];{let l="ort-wasm-simd-threaded.jsep.mjs",u=e??gn(l,t),c=n&&u&&!Dr(u,t),h=c?await cs(u):u??yn(l,t);return[c?h:void 0,await wn(h)]}}}),ms,zr,dr,gs,bn,Sn,Tn,ys,Pe,Ht=b(()=>{fs(),zr=!1,dr=!1,gs=!1,bn=()=>{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}},Sn=()=>{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}},Tn=()=>{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}},ys=async e=>{if(zr)return Promise.resolve();if(dr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(gs)throw new Error("previous call to 'initializeWebAssembly()' failed.");dr=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Tn())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Sn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=bn();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=n=1);let o=e.wasmPaths,l=typeof o=="string"?o:void 0,u=o?.mjs,c=u?.href??u,h=o?.wasm,p=h?.href??h,m=e.wasmBinary,[g,w]=await _n(c,l,n>1,!!m||!!p),v=!1,S=[];if(t>0&&S.push(new Promise(x=>{setTimeout(()=>{v=!0,x()},t)})),S.push(new Promise((x,M)=>{let k={numThreads:n};if(m)k.wasmBinary=m,k.locateFile=$=>$;else if(p||l)k.locateFile=$=>p??l+$;else if(c&&c.indexOf("blob:")!==0)k.locateFile=$=>new URL($,c).href;else if(g){let $=ds();$&&(k.locateFile=P=>$+P)}w(k).then($=>{dr=!1,zr=!0,ms=$,x(),g&&URL.revokeObjectURL(g)},$=>{dr=!1,gs=!0,M($)})})),await Promise.race(S),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Pe=()=>{if(zr&&ms)return ms;throw new Error("WebAssembly is not initialized yet.")}}),mt,Lr,Ce,ws=b(()=>{Ht(),mt=(e,t)=>{let n=Pe(),i=n.lengthBytesUTF8(e)+1,o=n._malloc(i);return n.stringToUTF8(e,o,i),t.push(o),o},Lr=(e,t,n,i)=>{if(typeof e=="object"&&e!==null){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach(([o,l])=>{let u=t?t+o:o;if(typeof l=="object")Lr(l,u+".",n,i);else if(typeof l=="string"||typeof l=="number")i(u,l.toString());else if(typeof l=="boolean")i(u,l?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof l}`)})},Ce=e=>{let t=Pe(),n=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetLastError(o,o+i);let l=Number(t.getValue(o,i===4?"i32":"i64")),u=t.getValue(o+i,"*"),c=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(n)}}}),En,Hi=b(()=>{Ht(),ws(),En=e=>{let t=Pe(),n=0,i=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.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)o.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&&(o.terminate=!1);let l=0;return e?.tag!==void 0&&(l=mt(e.tag,i)),n=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,l),n===0&&Ce("Can't create run options."),e?.extra!==void 0&&Lr(e.extra,"",new WeakSet,(u,c)=>{let h=mt(u,i),p=mt(c,i);t._OrtAddRunConfigEntry(n,h,p)!==0&&Ce(`Can't set a run config entry: ${u} - ${c}.`)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseRunOptions(n),i.forEach(u=>t._free(u)),l}}}),$n,xn,Cn,Ft,kn,Rn,Ki=b(()=>{Ht(),ws(),$n=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}`)}},xn=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Cn=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(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(e.enableMemPattern=!1)},Ft=(e,t,n,i)=>{let o=mt(t,i),l=mt(n,i);Pe()._OrtAddSessionConfigEntry(e,o,l)!==0&&Ce(`Can't set a session config entry: ${t} - ${n}.`)},kn=async(e,t,n)=>{let i=t.executionProviders;for(let o of i){let l=typeof o=="string"?o:o.name,u=[];switch(l){case"webnn":if(l="WEBNN",Ft(e,"session.disable_quant_qdq","1",n),Ft(e,"session.disable_qdq_constant_folding","1",n),typeof o!="string"){let g=o?.deviceType;g&&Ft(e,"deviceType",g,n)}break;case"webgpu":if(l="JS",typeof o!="string"){let g=o;if(g?.preferredLayout){if(g.preferredLayout!=="NCHW"&&g.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${g.preferredLayout}`);Ft(e,"preferredLayout",g.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let c=mt(l,n),h=u.length,p=0,m=0;if(h>0){p=Pe()._malloc(h*Pe().PTR_SIZE),n.push(p),m=Pe()._malloc(h*Pe().PTR_SIZE),n.push(m);for(let g=0;g<h;g++)Pe().setValue(p+g*Pe().PTR_SIZE,u[g][0],"*"),Pe().setValue(m+g*Pe().PTR_SIZE,u[g][1],"*")}await Pe()._OrtAppendExecutionProvider(e,c,p,m,h)!==0&&Ce(`Can't append execution provider: ${l}.`)}},Rn=async e=>{let t=Pe(),n=0,i=[],o=e||{};Cn(o);try{let l=$n(o.graphOptimizationLevel??"all"),u=xn(o.executionMode??"sequential"),c=typeof o.logId=="string"?mt(o.logId,i):0,h=o.logSeverityLevel??2;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log severity level is not valid: ${h}`);let p=o.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let m=typeof o.optimizedModelFilePath=="string"?mt(o.optimizedModelFilePath,i):0;if(n=t._OrtCreateSessionOptions(l,!!o.enableCpuMemArena,!!o.enableMemPattern,u,!!o.enableProfiling,0,c,h,p,m),n===0&&Ce("Can't create session options."),o.executionProviders&&await kn(n,o,i),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);Ft(n,"enableGraphCapture",o.enableGraphCapture.toString(),i)}if(o.freeDimensionOverrides)for(let[g,w]of Object.entries(o.freeDimensionOverrides)){if(typeof g!="string")throw new Error(`free dimension override name must be a string: ${g}`);if(typeof w!="number"||!Number.isInteger(w)||w<0)throw new Error(`free dimension override value must be a non-negative integer: ${w}`);let v=mt(g,i);t._OrtAddFreeDimensionOverride(n,v,w)!==0&&Ce(`Can't set a free dimension override: ${g} - ${w}.`)}return o.extra!==void 0&&Lr(o.extra,"",new WeakSet,(g,w)=>{Ft(n,g,w,i)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&Ce("Can't release session options."),i.forEach(u=>t._free(u)),l}}}),Kt,jt,Qt,vs,_s,bs,Ss,Vs,Ie=b(()=>{Kt=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}`)}},jt=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}`)}},Qt=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i=typeof t=="number"?t:t.reduce((o,l)=>o*l,1);return n>0?Math.ceil(i*n):void 0},vs=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}`)}},_s=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}`)}},bs=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ss=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Vs=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}`)}}}),Ts,An=b(()=>{Ut(),Ts=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 n=t.headers.get("Content-Length"),i=n?parseInt(n,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 o=t.body.getReader(),l;try{l=new ArrayBuffer(i)}catch(c){if(c instanceof RangeError){let h=Math.ceil(i/65536);l=new WebAssembly.Memory({initial:h,maximum:h}).buffer}else throw c}let u=0;for(;;){let{done:c,value:h}=await o.read();if(c)break;let p=h.byteLength;new Uint8Array(l,u,p).set(h),u+=p}return new Uint8Array(l,0,i)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),In,Gs,qs,xr,Ws,Hs,He,tr=b(()=>{Ie(),In=["V","I","W","E","F"],Gs=(e,t)=>{console.log(`[${In[e]},${new Date().toISOString()}]${t}`)},Ws=(e,t)=>{qs=e,xr=t},Hs=(e,t)=>{let n=_s(e),i=_s(qs);n>=i&&Gs(n,typeof t=="function"?t():t)},He=(...e)=>{xr&&Hs(...e)}}),Ks,Cr,j,Jr,js,Mn,cr,ke=b(()=>{Ks=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Cr=class{static calcShape(e,t,n=!1){let i=e.length,o=t.length;if(i===0)return t;if(o===0)return e;let l=Math.max(e.length,t.length),u=new Array(l);if(n){if(i<2||o<2)return;let c=Ks.calcMatMulShape([e[i-2],e[i-1]],[t[o-2],t[o-1]]);if(c===void 0)return;[u[l-2],u[l-1]]=c}for(let c=n?3:1;c<=l;c++){let h=i-c<0?1:e[i-c],p=o-c<0?1:t[o-c];if(h!==p&&h>1&&p>1)return;let m=Math.max(h,p);if(h&&p)u[l-c]=Math.max(h,p);else{if(m>1)return;u[l-c]=0}}return u}static isValidBroadcast(e,t){let n=e.length,i=t.length;if(n>i)return!1;for(let o=1;o<=n;o++)if(e[n-o]!==1&&e[n-o]!==t[i-o])return!1;return!0}},j=class Ni{static size(t){return Ni.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,n=4){let i=t.length;if(i===0)return[];let o=new Array(i),l=i-1;for(;l>=0;){if(t[l]%n===0){o[l]=t[l]/n;break}if(n%t[l]!==0)throw new Error("cannot convert shape");o[l]=1,n/=t[l],l--}for(l--;l>=0;l--)o[l]=t[l];return o}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Ni.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Ni.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,i){let o=1;for(let l=n;l<i;l++){if(t[l]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");o*=Number(t[l])}return o}static computeStrides(t){let n=t.length;if(n===0)return[];if(n===1)return[1];let i=new Array(n);i[n-1]=1,i[n-2]=t[n-1];for(let o=n-3;o>=0;--o)i[o]=i[o+1]*t[o+1];return i}static normalizeAxis(t,n){if(t<-n&&t>=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(i=>this.normalizeAxis(i,n??t.length))}static sortBasedOnPerm(t,n){return n?n.map(i=>t[i]):t.slice().reverse()}static padShape(t,n){let i=t.length;return t.map((o,l)=>o+n[l]+n[l+i])}static areEqual(t,n){return t.length!==n.length?!1:t.every((i,o)=>i===n[o])}},Jr=class li{static adjustPoolAttributes(t,n,i,o,l,u){if(!t&&i.length!==n.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let c=0;c<n.length-2;c++)c>=i.length?i.push(n[c+2]):i[c]=n[c+2];for(let c=0;c<i.length;c++)if(c<o.length){if(o[c]<0)throw new Error("strides should be greater than or equal to 1")}else o.push(1);for(let c=0;c<i.length;c++)if(c<l.length){if(l[c]<0)throw new Error("dilations should be greater than or equal to 1")}else l.push(1);for(let c=0;c<i.length*2;c++)if(c<u.length){if(u[c]<0)throw new Error("pad should be greater than or equal to 1")}else u.push(0);for(let c=0;c<i.length;c++){if(i[c]<=0)throw new Error("kernel shapes need to be greater than 0");if(u[c]>=i[c]||u[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,o,l,u,c){if(c){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let h=0;h<t.length-2;h++)li.adjustPadAndReturnShape(t[h+(u?1:2)],n[h],i[h],o[h],l,h,h+t.length-2,c)}}static computePoolOutputShape(t,n,i,o,l,u,c){if(n.length<=0)throw new Error("input shape must be of size greater than 0");let h=[n[0],n[1]];return li.computeShapeHelper(t,n,h,i,o,l,u,c),h}static computeConvOutputShape(t,n,i,o,l,u,c){if(t.length<=0||n.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let h=[t[0],n[0]];return li.computeShapeHelper(!1,t,h,i,o,l,u,c),h}static computeShapeHelper(t,n,i,o,l,u,c,h){if(t)for(let p=0;p<n.length-2;p++)i.push(1);else for(let p=0;p<n.length-2;p++)i.push(li.adjustPadAndReturnShape(n[p+2],o[p],l[p],u[p],c,p,p+n.length-2,h))}static adjustPadAndReturnShape(t,n,i,o,l,u,c,h){let p=i*(o-1)+1;if(h&&h!=="NOTSET")switch(h){case"VALID":return l[u]=0,l[c]=0,Math.floor((t-p)/n+1);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let m=((t+n-1)/n-1)*n+o-t;return l[u]=Math.floor(h==="SAME_LOWER"?(m+1)/2:m/2),l[c]=m-l[u],Math.floor((t+m-o)/n+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((t+l[u]+l[c]-p)/n+1)}},js=class{static getShapeOfGemmResult(e,t,n,i,o){if(e.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let l,u,c;t?(l=e[1],u=e[0]):(l=e[0],u=e[1]);let h=-1;if(i?(c=n[0],h=1):(c=n[1],h=0),n[h]!==u)throw new Error("dimension mismatch");if(l<=0||c<=0||u<=0)throw new Error("invalid shape specified");if(o&&!Cr.isValidBroadcast(o,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,u]}},Mn=-34028234663852886e22,cr=34028234663852886e22}),kr,Zr=b(()=>{Ie(),kr=(e,t)=>new(vs(t))(e)}),Br,es,Es,$s,hr,Rr,Qs,Xs,Ys,Pn,On,pi=b(()=>{Ie(),tr(),Br=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),es=(e,t)=>{if(t==="int32")return e;let n=Br.get(t);if(!n)throw new Error(`WebNN backend does not support data type: ${t}`);let i=n/8;if(e.byteLength%i!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${i}.`);let o=e.byteLength/i,l=new(vs(t))(e.buffer,e.byteOffset,o);switch(t){case"int64":case"uint64":{let u=new Int32Array(o);for(let c=0;c<o;c++){let h=l[c];if(h>2147483647n||h<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");u[c]=Number(h)}return new Uint8Array(u.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(c=>c>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let u=Int32Array.from(l,Number);return new Uint8Array(u.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Es=(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 n=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case"int64":{let o=BigInt64Array.from(i,BigInt);return new Uint8Array(o.buffer)}case"uint64":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let o=BigUint64Array.from(i,BigInt);return new Uint8Array(o.buffer)}case"int8":{if(i.some(l=>l<-128||l>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let o=Int8Array.from(i,Number);return new Uint8Array(o.buffer)}case"uint8":{if(i.some(o=>o<0||o>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(l=>l<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let o=Uint32Array.from(i,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},$s=1,hr=()=>$s++,Rr=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Qs=(e,t)=>{let n=Br.get(e);if(!n)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,o)=>i*o)*n/8):0},Xs=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:i,dataType:o,shape:l,fallbackDataType:u}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=i,this.dataType=o,this.tensorShape=l,this.fallbackDataType=u}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Qs(this.dataType,this.tensorShape)}destroy(){He("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Es(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return n.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((i,o)=>i===n[o])}setIsDataConverted(e){this.isDataConverted=e}},Ys=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,i){let o=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),u;if(!l?.input.dataTypes.includes(t)){if(u=Rr.get(t),!u||l?.input.dataTypes.includes(u))throw new Error(`WebNN backend does not support data type: ${t}`);He("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${u}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(o,t,n))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==Qs(t,n))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 c=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,c,!0,!0,u),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=es(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 He("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?Es(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()}},Pn=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=hr();return this.tensorTrackersById.set(e,new Ys(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,i,o){He("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${i}, copyOld: ${o}}`);let l=this.tensorTrackersById.get(t);if(!l)throw new Error("Tensor not found.");return l.ensureTensor(e,n,i,o)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");n.upload(t)}async download(e,t){He("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,i){let o=this.getMLContext(e),l=hr(),u=new Xs({sessionId:e,context:o,tensor:t,dataType:n,shape:i});return this.tensorTrackersById.set(l,new Ys(this,u)),this.externalTensors.add(u),l}async getCachedTensor(e,t,n,i,o,l,u){let c=this.getMLContext(e);for(let[p,m]of this.freeTensors.entries())if(m.canReuseTensor(c,t,n)){He("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${n}`);let g=this.freeTensors.splice(p,1)[0];return g.sessionId=e,g}He("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${n}}`);let h=await c.createTensor({dataType:u??t,shape:n,dimensions:n,usage:i,writable:o,readable:l});return new Xs({sessionId:e,context:c,tensor:h,dataType:t,shape:n,fallbackDataType:u})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},On=(...e)=>new Pn(...e)}),ts,Dn,zn,Ln=b(()=>{Ie(),Ht(),Zr(),pi(),tr(),ts=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Dn=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),i=Object.keys(t).sort();return n.length===i.length&&n.every((o,l)=>o===i[l]&&e[o]===t[o])},zn=class{constructor(e){this.tensorManager=On(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,Ws(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){He("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){He("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let n of t)He("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${n}}`),this.tensorManager.releaseTensorId(n);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let n=this.mlContextCache.findIndex(i=>i.gpuDevice===e);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:i}),i}}else if(e===void 0){let n=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let t=this.mlContextCache.findIndex(n=>Dn(n.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:n}),n}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let i=this.mlContextCache.findIndex(o=>o.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){He("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,i,o){let l=ts.get(n);if(!l)throw new Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,l,i,o)}async createTemporaryTensor(e,t,n){He("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let i=ts.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,i,n,!1);let l=this.temporarySessionTensorIds.get(e);return l?l.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,t){if(!Pe().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");He("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return kr(n,t)}}registerMLTensor(e,t,n,i){let o=ts.get(n);if(!o)throw new Error(`Unsupported ONNX data type: ${n}`);let l=this.tensorManager.registerTensor(e,t,o,i);return He("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${i}} -> {tensorId: ${l}}`),l}registerMLConstant(e,t,n,i,o,l,u=!1){if(!l)throw new Error("External mounted files are not available.");let c=e;e.startsWith("./")&&(c=e.substring(2));let h=l.get(c);if(!h)throw new Error(`File with name ${c} not found in preloaded files.`);if(t+n>h.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=h.slice(t,t+n).buffer,m;switch(o.dataType){case"float32":m=new Float32Array(p);break;case"float16":m=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(p):new Uint16Array(p);break;case"int32":m=new Int32Array(p);break;case"uint32":m=new Uint32Array(p);break;case"int64":if(u){let g=es(new Uint8Array(p),"int64");m=new Int32Array(g.buffer),o.dataType="int32"}else m=new BigInt64Array(p);break;case"uint64":m=new BigUint64Array(p);break;case"int8":m=new Int8Array(p);break;case"int4":case"uint4":case"uint8":m=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return He("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${u?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),i.constant(o,m)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let i=ts.get(Kt(t)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:n?!!o?.input.dataTypes.includes(i):!!o?.output.dataTypes.includes(i)}flush(){}}}),Js=b(()=>{}),Zs,en,xs,tn,rn,sn,Bn,Nn,fi,ji=b(()=>{tr(),Js(),Zs=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]]),en=[],xs=e=>Math.ceil(Number(e)/16)*16,tn=e=>{for(let t=0;t<en.length;t++){let n=en[t];if(e<=n)return n}return Math.ceil(e/16)*16},rn=1,sn=()=>rn++,Bn=async(e,t,n,i)=>{let o=xs(n),l=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let u=e.getCommandEncoder();e.endComputePass(),u.copyBufferToBuffer(t,0,l,0,o),e.flush(),await l.mapAsync(GPUMapMode.READ);let c=l.getMappedRange();if(i){let h=i();return h.set(new Uint8Array(c,0,n)),h}else return new Uint8Array(c.slice(0,n))}finally{l.destroy()}},Nn=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 Zs)en.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,i=t.byteOffset,o=t.byteLength,l=xs(o),u=this.storageCache.get(e);if(!u)throw new Error("gpu data for uploading does not exist");if(Number(u.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${u.originalSize}, data size=${o}`);let c=this.backend.device.createBuffer({mappedAtCreation:!0,size:l,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),h=c.getMappedRange();new Uint8Array(h).set(new Uint8Array(n,i,o)),c.unmap();let p=this.backend.device.createCommandEncoder();p.copyBufferToBuffer(c,0,u.gpuData.buffer,0,l),this.backend.device.queue.submit([p.finish()]),c.destroy(),He("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)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(n.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=xs(n.originalSize),l=this.backend.getCommandEncoder();this.backend.endComputePass(),l.copyBufferToBuffer(n.gpuData.buffer,0,i.gpuData.buffer,0,o)}registerExternalBuffer(e,t,n){let i;if(n){if(i=n[0],e===n[1])return He("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=
|
|
7
|
-
let dim${
|
|
8
|
-
let rest${
|
|
9
|
-
indices[${
|
|
10
|
-
current = rest${
|
|
5
|
+
*/var Tp;function yy(){return Tp||(Tp=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,_=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(e=>typeof dr<"u"?dr:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof dr<"u"?dr:t)[n]}):e)(function(e){if(typeof dr<"u")return dr.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),S=(e,t)=>()=>(e&&(t=e(e=0)),t),N=(e,t)=>{for(var n in t)a(e,n,{get:t[n],enumerable:!0})},z=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _(t))!C.call(e,o)&&o!==n&&a(e,o,{get:()=>t[o],enumerable:!(i=f(t,o))||i.enumerable});return e},te=e=>z(a({},"__esModule",{value:!0}),e),j,se,J,Y,W,ne=S(()=>{j=new Map,se=[],J=(e,t,n)=>{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:n});else{if(i.priority>n)return;if(i.priority===n&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let o=se.indexOf(e);o!==-1&&se.splice(o,1);for(let l=0;l<se.length;l++)if(j.get(se[l]).priority<=n){se.splice(l,0,e);return}se.push(e)}return}throw new TypeError("not a valid backend")},Y=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 n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return n||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},W=async e=>{let t=e.executionProviders||[],n=t.map(h=>typeof h=="string"?h:h.name),i=n.length===0?se:n,o,l=[],u=new Set;for(let h of i){let p=await Y(h);typeof p=="string"?l.push({name:h,err:p}):(o||(o=p),o===p&&u.add(h))}if(!o)throw new Error(`no available backend found. ERR: ${l.map(h=>`[${h.name}] ${h.err}`).join(", ")}`);for(let{name:h,err:p}of l)n.includes(h)&&console.warn(`removing requested execution provider "${h}" from session options because it is not available: ${p}`);let c=t.filter(h=>u.has(typeof h=="string"?h:h.name));return[o,new Proxy(e,{get:(h,p)=>p==="executionProviders"?c:Reflect.get(h,p)})]}}),fe=S(()=>{ne()}),de,ce=S(()=>{de="1.26.0"}),pe,he,Ve=S(()=>{ce(),pe="warning",he={wasm:{},webgl:{},webgpu:{},versions:{common:de},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}`);pe=e}},get logLevel(){return pe}},Object.defineProperty(he,"logLevel",{enumerable:!0})}),me,Ye=S(()=>{Ve(),me=he}),qe,it,Je=S(()=>{qe=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let i=n.getContext("2d");if(i!=null){let o,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[3]):(o=e.dims[3],l=e.dims[2]);let u=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],0],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=l*o,g=0,w=m,v=m*2,b=-1;u==="RGBA"?(g=0,w=m,v=m*2,b=m*3):u==="RGB"?(g=0,w=m,v=m*2):u==="RBG"&&(g=0,v=m,w=m*2);for(let x=0;x<l;x++)for(let M=0;M<o;M++){let k=(e.data[g++]-p[0])*h[0],$=(e.data[w++]-p[1])*h[1],P=(e.data[v++]-p[2])*h[2],I=b===-1?255:(e.data[b++]-p[3])*h[3];i.fillStyle="rgba("+k+","+$+","+P+","+I+")",i.fillRect(M,x,1,1)}if("toDataURL"in n)return n.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},it=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(n!=null){let o,l,u;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[1],u=e.dims[3]):(o=e.dims[3],l=e.dims[2],u=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",h=t?.norm,p,m;h===void 0||h.mean===void 0?p=[255,255,255,255]:typeof h.mean=="number"?p=[h.mean,h.mean,h.mean,h.mean]:(p=[h.mean[0],h.mean[1],h.mean[2],255],h.mean[3]!==void 0&&(p[3]=h.mean[3])),h===void 0||h.bias===void 0?m=[0,0,0,0]:typeof h.bias=="number"?m=[h.bias,h.bias,h.bias,h.bias]:(m=[h.bias[0],h.bias[1],h.bias[2],0],h.bias[3]!==void 0&&(m[3]=h.bias[3]));let g=l*o;if(t!==void 0&&(t.format!==void 0&&u===4&&t.format!=="RGBA"||u===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let w=4,v=0,b=1,x=2,M=3,k=0,$=g,P=g*2,I=-1;c==="RGBA"?(k=0,$=g,P=g*2,I=g*3):c==="RGB"?(k=0,$=g,P=g*2):c==="RBG"&&(k=0,P=g,$=g*2),i=n.createImageData(o,l);for(let B=0;B<l*o;v+=w,b+=w,x+=w,M+=w,B++)i.data[v]=(e.data[k++]-m[0])*p[0],i.data[b]=(e.data[$++]-m[1])*p[1],i.data[x]=(e.data[P++]-m[2])*p[2],i.data[M]=I===-1?255:(e.data[I++]-m[3])*p[3]}else throw new Error("Can not access image data");return i}}),at,tt,qt,xt,Ke,We,st=S(()=>{Er(),at=(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:n,width:i}=t,o=t.norm??{mean:255,bias:0},l,u;typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:l=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?u=[o.bias,o.bias,o.bias,o.bias]:u=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let c=t.format!==void 0?t.format:"RGBA",h=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=n*i,m=h==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),g=4,w=0,v=1,b=2,x=3,M=0,k=p,$=p*2,P=-1;c==="RGB"&&(g=3,w=0,v=1,b=2,x=-1),h==="RGBA"?P=p*3:h==="RBG"?(M=0,$=p,k=p*2):h==="BGR"&&($=0,k=p,M=p*2);for(let I=0;I<p;I++,w+=g,b+=g,v+=g,x+=g)m[M++]=(e[w]+u[0])/l[0],m[k++]=(e[v]+u[1])/l[1],m[$++]=(e[b]+u[2])/l[2],P!==-1&&x!==-1&&(m[P++]=(e[x]+u[3])/l[3]);return h==="RGBA"?new rt("float32",m,[1,4,n,i]):new rt("float32",m,[1,3,n,i])},tt=async(e,t)=>{let n=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,l=typeof e=="string",u,c=t??{},h=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=m=>typeof HTMLCanvasElement<"u"&&m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext("2d"):null;if(n){let m=h();m.width=e.width,m.height=e.height;let g=p(m);if(g!=null){let w=e.height,v=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(w=t.resizedHeight,v=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=w,c.width=v}else c.tensorFormat="RGBA",c.height=w,c.width=v;g.drawImage(e,0,0),u=g.getImageData(0,0,v,w).data}else throw new Error("Can not access image data")}else if(i){let m,g;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(m=t.resizedHeight,g=t.resizedWidth):(m=e.height,g=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=m,c.width=g,t!==void 0){let w=h();w.width=g,w.height=m;let v=p(w);if(v!=null)v.putImageData(e,0,0),u=v.getImageData(0,0,g,m).data;else throw new Error("Can not access image data")}else u=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let m=h();m.width=e.width,m.height=e.height;let g=p(m);if(g!=null){let w=e.height,v=e.width;return g.drawImage(e,0,0,v,w),u=g.getImageData(0,0,v,w).data,c.height=w,c.width=v,at(u,c)}else throw new Error("Can not access image data")}else{if(l)return new Promise((m,g)=>{let w=h(),v=p(w);if(!e||!v)return g();let b=new Image;b.crossOrigin="Anonymous",b.src=e,b.onload=()=>{w.width=b.width,w.height=b.height,v.drawImage(b,0,0,w.width,w.height);let x=v.getImageData(0,0,w.width,w.height);c.height=w.height,c.width=w.width,m(at(x.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return at(u,c);throw new Error("Input data provided is not supported - aborted tensor creation")},qt=(e,t)=>{let{width:n,height:i,download:o,dispose:l}=t,u=[1,i,n,4];return new rt({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:l})},xt=(e,t)=>{let{dataType:n,dims:i,download:o,dispose:l}=t;return new rt({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:i,download:o,dispose:l})},Ke=(e,t)=>{let{dataType:n,dims:i,download:o,dispose:l}=t;return new rt({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:i,download:o,dispose:l})},We=(e,t,n)=>new rt({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})}),ze,Rt,sr,Xr,Vs=S(()=>{ze=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"]]),sr=!1,Xr=()=>{if(!sr){sr=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;e&&(ze.set("int64",BigInt64Array),Rt.set(BigInt64Array,"int64")),t&&(ze.set("uint64",BigUint64Array),Rt.set(BigUint64Array,"uint64")),i?(ze.set("float16",n),Rt.set(n,"float16")):ze.set("float16",Uint16Array)}}}),Yr,Jr,Gs=S(()=>{Er(),Yr=e=>{let t=1;for(let n=0;n<e.length;n++){let i=e[n];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${n}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${i}`);t*=i}return t},Jr=(e,t)=>{switch(e.location){case"cpu":return new rt(e.type,e.data,t);case"cpu-pinned":return new rt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new rt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new rt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new rt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),rt,Er=S(()=>{Je(),st(),Vs(),Gs(),rt=class{constructor(e,t,n){Xr();let i,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,o=e.dims,e.location){case"cpu-pinned":{let u=ze.get(i);if(!u)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof u))throw new TypeError(`buffer should be of type ${u.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 u,c;if(typeof e=="string")if(i=e,c=n,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");u=t}else{let h=ze.get(e);if(h===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&h===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${h.name} as data.`);e==="uint64"||e==="int64"?u=h.from(t,BigInt):u=h.from(t)}else if(t instanceof h)u=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")u=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&h!==Uint16Array)u=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${h}`)}else if(c=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let h=typeof e[0];if(h==="string")i="string",u=e;else if(h==="boolean")i="bool",u=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${h}.`)}else if(e instanceof Uint8ClampedArray)i="uint8",u=Uint8Array.from(e);else{let h=Rt.get(e.constructor);if(h===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=h,u=e}if(c===void 0)c=[u.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");o=c,this.cpuData=u,this.dataLocation="cpu"}let l=Yr(o);if(this.cpuData&&l!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(l/2)===this.cpuData.length))throw new Error(`Tensor's size(${l}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=o,this.size=l}static async fromImage(e,t){return tt(e,t)}static fromTexture(e,t){return qt(e,t)}static fromGpuBuffer(e,t){return xt(e,t)}static fromMLTensor(e,t){return Ke(e,t)}static fromPinnedBuffer(e,t,n){return We(e,t,n)}toDataURL(e){return qe(this,e)}toImageData(e){return it(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 Jr(this,e)}}}),lt,Zr=S(()=>{Er(),lt=rt}),er,$r,gt,ft,At,Ct,es=S(()=>{Ve(),er=(e,t)=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeStamp(`${e}::ORT::${t}`)},$r=(e,t)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let o=0;o<n.length;o++){if(i&&!n[o].includes("TRACE_FUNC")){let l=`FUNC_${e}::${n[o].trim().split(" ")[1]}`;t&&(l+=`::${t}`),er("CPU",l);return}n[o].includes("TRACE_FUNC")&&(i=!0)}},gt=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||$r("BEGIN",e)},ft=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||$r("END",e)},At=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.time(`ORT::${e}`)},Ct=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeEnd(`ORT::${e}`)}}),ts,qs=S(()=>{ne(),Zr(),es(),ts=class df{constructor(t){this.handler=t}async run(t,n,i){gt(),At("InferenceSession.run");let o={},l={};if(typeof t!="object"||t===null||t instanceof lt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let u=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof lt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");u=!1;for(let p of n){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);o[p]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,m=Object.getOwnPropertyNames(n);for(let g of this.outputNames)if(m.indexOf(g)!==-1){let w=n[g];(w===null||w instanceof lt)&&(p=!0,u=!1,o[g]=w)}if(p){if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else l=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(u)for(let p of this.outputNames)o[p]=null;let c=await this.handler.run(t,o,l),h={};for(let p in c)if(Object.hasOwnProperty.call(c,p)){let m=c[p];m instanceof lt?h[p]=m:h[p]=new lt(m.type,m.data,m.dims)}return Ct("InferenceSession.run"),ft(),h}async release(){return this.handler.dispose()}static async create(t,n,i,o){gt(),At("InferenceSession.create");let l,u={};if(typeof t=="string"){if(l=t,typeof n=="object"&&n!==null)u=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(l=t,typeof n=="object"&&n!==null)u=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let m=t,g=0,w=t.byteLength;if(typeof n=="object"&&n!==null)u=n;else if(typeof n=="number"){if(g=n,!Number.isSafeInteger(g))throw new RangeError("'byteOffset' must be an integer.");if(g<0||g>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(w=t.byteLength-g,typeof i=="number"){if(w=i,!Number.isSafeInteger(w))throw new RangeError("'byteLength' must be an integer.");if(w<=0||g+w>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-g}].`);if(typeof o=="object"&&o!==null)u=o;else if(typeof o<"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 n<"u")throw new TypeError("'options' must be an object.");l=new Uint8Array(m,g,w)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,h]=await W(u),p=await c.createInferenceSessionHandler(l,h);return Ct("InferenceSession.create"),ft(),new df(p)}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}}}),zr,be=S(()=>{qs(),zr=ts}),Ze=S(()=>{}),Bt=S(()=>{}),nr=S(()=>{}),It=S(()=>{}),xr={};N(xr,{InferenceSession:()=>zr,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>At,TRACE_EVENT_END:()=>Ct,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>ft,Tensor:()=>lt,env:()=>me,registerBackend:()=>J});var yt=S(()=>{fe(),Ye(),be(),Zr(),Ze(),Bt(),es(),nr(),It()}),Lr=S(()=>{}),Br={};N(Br,{default:()=>Wt});var Nt,ir,Wt,Wi=S(()=>{Yh(),Ht(),ms(),Nt="ort-wasm-proxy-worker",ir=globalThis.self?.name===Nt,ir&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":ws(n.wasm).then(()=>{Ba(n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:o}=n;Na(o,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=n,o=Ri(i);postMessage({type:t,out:o});break}case"create":{let{model:i,options:o}=n;Fa(i,o).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":Va(n),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:o,inputs:l,outputIndices:u,options:c}=n;qa(i,o,l,u,new Array(u.length).fill(null),c).then(h=>{h.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:h},Ha([...l,...h]))},h=>{postMessage({type:t,err:h})});break}case"end-profiling":Wa(n),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),Wt=ir?null:e=>new Worker(e??ot,{type:"classic",name:Nt})}),fn,mn,ot,cs,Nr,gn,yn,hs,wn,ps,vn,fs,_n,ms=S(()=>{Lr(),fn=typeof location>"u"?void 0:location.origin,mn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,ot=mn(),cs=()=>{if(ot&&!ot.startsWith("blob:"))return ot.substring(0,ot.lastIndexOf("/")+1)},Nr=(e,t)=>{try{let n=t??ot;return(n?new URL(e,n):new URL(e)).origin===fn}catch{return!1}},gn=(e,t)=>{let n=t??ot;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},yn=(e,t)=>`${t??"./"}${e}`,hs=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},wn=async e=>(await import(e)).default,ps=(Wi(),te(Br)).default,vn=async()=>{if(!ot)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Nr(ot))return[void 0,ps()];let e=await hs(ot);return[e,ps(e)]},fs=void 0,_n=async(e,t,n,i)=>{let o=fs&&!(e||t);if(o)if(ot)o=Nr(ot)||i&&!n;else if(i&&!n)o=!0;else throw new Error("cannot determine the script source URL.");if(o)return[void 0,fs];{let l="ort-wasm-simd-threaded.jsep.mjs",u=e??gn(l,t),c=n&&u&&!Nr(u,t),h=c?await hs(u):u??yn(l,t);return[c?h:void 0,await wn(h)]}}}),gs,Ur,cr,ys,bn,Sn,Tn,ws,Pe,Ht=S(()=>{ms(),Ur=!1,cr=!1,ys=!1,bn=()=>{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}},Sn=()=>{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}},Tn=()=>{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}},ws=async e=>{if(Ur)return Promise.resolve();if(cr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ys)throw new Error("previous call to 'initializeWebAssembly()' failed.");cr=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Tn())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Sn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=bn();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=n=1);let o=e.wasmPaths,l=typeof o=="string"?o:void 0,u=o?.mjs,c=u?.href??u,h=o?.wasm,p=h?.href??h,m=e.wasmBinary,[g,w]=await _n(c,l,n>1,!!m||!!p),v=!1,b=[];if(t>0&&b.push(new Promise(x=>{setTimeout(()=>{v=!0,x()},t)})),b.push(new Promise((x,M)=>{let k={numThreads:n};if(m)k.wasmBinary=m,k.locateFile=$=>$;else if(p||l)k.locateFile=$=>p??l+$;else if(c&&c.indexOf("blob:")!==0)k.locateFile=$=>new URL($,c).href;else if(g){let $=cs();$&&(k.locateFile=P=>$+P)}w(k).then($=>{cr=!1,Ur=!0,gs=$,x(),g&&URL.revokeObjectURL(g)},$=>{cr=!1,ys=!0,M($)})})),await Promise.race(b),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Pe=()=>{if(Ur&&gs)return gs;throw new Error("WebAssembly is not initialized yet.")}}),mt,Fr,Ce,vs=S(()=>{Ht(),mt=(e,t)=>{let n=Pe(),i=n.lengthBytesUTF8(e)+1,o=n._malloc(i);return n.stringToUTF8(e,o,i),t.push(o),o},Fr=(e,t,n,i)=>{if(typeof e=="object"&&e!==null){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach(([o,l])=>{let u=t?t+o:o;if(typeof l=="object")Fr(l,u+".",n,i);else if(typeof l=="string"||typeof l=="number")i(u,l.toString());else if(typeof l=="boolean")i(u,l?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof l}`)})},Ce=e=>{let t=Pe(),n=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetLastError(o,o+i);let l=Number(t.getValue(o,i===4?"i32":"i64")),u=t.getValue(o+i,"*"),c=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(n)}}}),En,Hi=S(()=>{Ht(),vs(),En=e=>{let t=Pe(),n=0,i=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.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)o.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&&(o.terminate=!1);let l=0;return e?.tag!==void 0&&(l=mt(e.tag,i)),n=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,l),n===0&&Ce("Can't create run options."),e?.extra!==void 0&&Fr(e.extra,"",new WeakSet,(u,c)=>{let h=mt(u,i),p=mt(c,i);t._OrtAddRunConfigEntry(n,h,p)!==0&&Ce(`Can't set a run config entry: ${u} - ${c}.`)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseRunOptions(n),i.forEach(u=>t._free(u)),l}}}),$n,xn,Cn,Ut,kn,Rn,ji=S(()=>{Ht(),vs(),$n=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}`)}},xn=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Cn=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(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(e.enableMemPattern=!1)},Ut=(e,t,n,i)=>{let o=mt(t,i),l=mt(n,i);Pe()._OrtAddSessionConfigEntry(e,o,l)!==0&&Ce(`Can't set a session config entry: ${t} - ${n}.`)},kn=async(e,t,n)=>{let i=t.executionProviders;for(let o of i){let l=typeof o=="string"?o:o.name,u=[];switch(l){case"webnn":if(l="WEBNN",Ut(e,"session.disable_quant_qdq","1",n),Ut(e,"session.disable_qdq_constant_folding","1",n),typeof o!="string"){let g=o?.deviceType;g&&Ut(e,"deviceType",g,n)}break;case"webgpu":if(l="JS",typeof o!="string"){let g=o;if(g?.preferredLayout){if(g.preferredLayout!=="NCHW"&&g.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${g.preferredLayout}`);Ut(e,"preferredLayout",g.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let c=mt(l,n),h=u.length,p=0,m=0;if(h>0){p=Pe()._malloc(h*Pe().PTR_SIZE),n.push(p),m=Pe()._malloc(h*Pe().PTR_SIZE),n.push(m);for(let g=0;g<h;g++)Pe().setValue(p+g*Pe().PTR_SIZE,u[g][0],"*"),Pe().setValue(m+g*Pe().PTR_SIZE,u[g][1],"*")}await Pe()._OrtAppendExecutionProvider(e,c,p,m,h)!==0&&Ce(`Can't append execution provider: ${l}.`)}},Rn=async e=>{let t=Pe(),n=0,i=[],o=e||{};Cn(o);try{let l=$n(o.graphOptimizationLevel??"all"),u=xn(o.executionMode??"sequential"),c=typeof o.logId=="string"?mt(o.logId,i):0,h=o.logSeverityLevel??2;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log severity level is not valid: ${h}`);let p=o.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let m=typeof o.optimizedModelFilePath=="string"?mt(o.optimizedModelFilePath,i):0;if(n=t._OrtCreateSessionOptions(l,!!o.enableCpuMemArena,!!o.enableMemPattern,u,!!o.enableProfiling,0,c,h,p,m),n===0&&Ce("Can't create session options."),o.executionProviders&&await kn(n,o,i),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);Ut(n,"enableGraphCapture",o.enableGraphCapture.toString(),i)}if(o.freeDimensionOverrides)for(let[g,w]of Object.entries(o.freeDimensionOverrides)){if(typeof g!="string")throw new Error(`free dimension override name must be a string: ${g}`);if(typeof w!="number"||!Number.isInteger(w)||w<0)throw new Error(`free dimension override value must be a non-negative integer: ${w}`);let v=mt(g,i);t._OrtAddFreeDimensionOverride(n,v,w)!==0&&Ce(`Can't set a free dimension override: ${g} - ${w}.`)}return o.extra!==void 0&&Fr(o.extra,"",new WeakSet,(g,w)=>{Ut(n,g,w,i)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&Ce("Can't release session options."),i.forEach(u=>t._free(u)),l}}}),jt,Kt,Qt,_s,bs,Ss,Ts,Ws,Ie=S(()=>{jt=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}`)}},Kt=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}`)}},Qt=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i=typeof t=="number"?t:t.reduce((o,l)=>o*l,1);return n>0?Math.ceil(i*n):void 0},_s=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}`)}},bs=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}`)}},Ss=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ts=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ws=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,An=S(()=>{Lr(),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 n=t.headers.get("Content-Length"),i=n?parseInt(n,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 o=t.body.getReader(),l;try{l=new ArrayBuffer(i)}catch(c){if(c instanceof RangeError){let h=Math.ceil(i/65536);l=new WebAssembly.Memory({initial:h,maximum:h}).buffer}else throw c}let u=0;for(;;){let{done:c,value:h}=await o.read();if(c)break;let p=h.byteLength;new Uint8Array(l,u,p).set(h),u+=p}return new Uint8Array(l,0,i)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),In,Hs,js,Cr,Ks,Qs,He,tr=S(()=>{Ie(),In=["V","I","W","E","F"],Hs=(e,t)=>{console.log(`[${In[e]},${new Date().toISOString()}]${t}`)},Ks=(e,t)=>{js=e,Cr=t},Qs=(e,t)=>{let n=bs(e),i=bs(js);n>=i&&Hs(n,typeof t=="function"?t():t)},He=(...e)=>{Cr&&Qs(...e)}}),Xs,kr,K,rs,Ys,Mn,hr,ke=S(()=>{Xs=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},kr=class{static calcShape(e,t,n=!1){let i=e.length,o=t.length;if(i===0)return t;if(o===0)return e;let l=Math.max(e.length,t.length),u=new Array(l);if(n){if(i<2||o<2)return;let c=Xs.calcMatMulShape([e[i-2],e[i-1]],[t[o-2],t[o-1]]);if(c===void 0)return;[u[l-2],u[l-1]]=c}for(let c=n?3:1;c<=l;c++){let h=i-c<0?1:e[i-c],p=o-c<0?1:t[o-c];if(h!==p&&h>1&&p>1)return;let m=Math.max(h,p);if(h&&p)u[l-c]=Math.max(h,p);else{if(m>1)return;u[l-c]=0}}return u}static isValidBroadcast(e,t){let n=e.length,i=t.length;if(n>i)return!1;for(let o=1;o<=n;o++)if(e[n-o]!==1&&e[n-o]!==t[i-o])return!1;return!0}},K=class Ni{static size(t){return Ni.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,n=4){let i=t.length;if(i===0)return[];let o=new Array(i),l=i-1;for(;l>=0;){if(t[l]%n===0){o[l]=t[l]/n;break}if(n%t[l]!==0)throw new Error("cannot convert shape");o[l]=1,n/=t[l],l--}for(l--;l>=0;l--)o[l]=t[l];return o}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Ni.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Ni.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,i){let o=1;for(let l=n;l<i;l++){if(t[l]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");o*=Number(t[l])}return o}static computeStrides(t){let n=t.length;if(n===0)return[];if(n===1)return[1];let i=new Array(n);i[n-1]=1,i[n-2]=t[n-1];for(let o=n-3;o>=0;--o)i[o]=i[o+1]*t[o+1];return i}static normalizeAxis(t,n){if(t<-n&&t>=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(i=>this.normalizeAxis(i,n??t.length))}static sortBasedOnPerm(t,n){return n?n.map(i=>t[i]):t.slice().reverse()}static padShape(t,n){let i=t.length;return t.map((o,l)=>o+n[l]+n[l+i])}static areEqual(t,n){return t.length!==n.length?!1:t.every((i,o)=>i===n[o])}},rs=class ui{static adjustPoolAttributes(t,n,i,o,l,u){if(!t&&i.length!==n.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let c=0;c<n.length-2;c++)c>=i.length?i.push(n[c+2]):i[c]=n[c+2];for(let c=0;c<i.length;c++)if(c<o.length){if(o[c]<0)throw new Error("strides should be greater than or equal to 1")}else o.push(1);for(let c=0;c<i.length;c++)if(c<l.length){if(l[c]<0)throw new Error("dilations should be greater than or equal to 1")}else l.push(1);for(let c=0;c<i.length*2;c++)if(c<u.length){if(u[c]<0)throw new Error("pad should be greater than or equal to 1")}else u.push(0);for(let c=0;c<i.length;c++){if(i[c]<=0)throw new Error("kernel shapes need to be greater than 0");if(u[c]>=i[c]||u[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,o,l,u,c){if(c){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let h=0;h<t.length-2;h++)ui.adjustPadAndReturnShape(t[h+(u?1:2)],n[h],i[h],o[h],l,h,h+t.length-2,c)}}static computePoolOutputShape(t,n,i,o,l,u,c){if(n.length<=0)throw new Error("input shape must be of size greater than 0");let h=[n[0],n[1]];return ui.computeShapeHelper(t,n,h,i,o,l,u,c),h}static computeConvOutputShape(t,n,i,o,l,u,c){if(t.length<=0||n.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let h=[t[0],n[0]];return ui.computeShapeHelper(!1,t,h,i,o,l,u,c),h}static computeShapeHelper(t,n,i,o,l,u,c,h){if(t)for(let p=0;p<n.length-2;p++)i.push(1);else for(let p=0;p<n.length-2;p++)i.push(ui.adjustPadAndReturnShape(n[p+2],o[p],l[p],u[p],c,p,p+n.length-2,h))}static adjustPadAndReturnShape(t,n,i,o,l,u,c,h){let p=i*(o-1)+1;if(h&&h!=="NOTSET")switch(h){case"VALID":return l[u]=0,l[c]=0,Math.floor((t-p)/n+1);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let m=((t+n-1)/n-1)*n+o-t;return l[u]=Math.floor(h==="SAME_LOWER"?(m+1)/2:m/2),l[c]=m-l[u],Math.floor((t+m-o)/n+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((t+l[u]+l[c]-p)/n+1)}},Ys=class{static getShapeOfGemmResult(e,t,n,i,o){if(e.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let l,u,c;t?(l=e[1],u=e[0]):(l=e[0],u=e[1]);let h=-1;if(i?(c=n[0],h=1):(c=n[1],h=0),n[h]!==u)throw new Error("dimension mismatch");if(l<=0||c<=0||u<=0)throw new Error("invalid shape specified");if(o&&!kr.isValidBroadcast(o,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,u]}},Mn=-34028234663852886e22,hr=34028234663852886e22}),Rr,ss=S(()=>{Ie(),Rr=(e,t)=>new(_s(t))(e)}),Vr,ns,$s,xs,pr,Ar,Js,Zs,en,Pn,On,fi=S(()=>{Ie(),tr(),Vr=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),ns=(e,t)=>{if(t==="int32")return e;let n=Vr.get(t);if(!n)throw new Error(`WebNN backend does not support data type: ${t}`);let i=n/8;if(e.byteLength%i!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${i}.`);let o=e.byteLength/i,l=new(_s(t))(e.buffer,e.byteOffset,o);switch(t){case"int64":case"uint64":{let u=new Int32Array(o);for(let c=0;c<o;c++){let h=l[c];if(h>2147483647n||h<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");u[c]=Number(h)}return new Uint8Array(u.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(c=>c>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let u=Int32Array.from(l,Number);return new Uint8Array(u.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},$s=(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 n=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case"int64":{let o=BigInt64Array.from(i,BigInt);return new Uint8Array(o.buffer)}case"uint64":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let o=BigUint64Array.from(i,BigInt);return new Uint8Array(o.buffer)}case"int8":{if(i.some(l=>l<-128||l>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let o=Int8Array.from(i,Number);return new Uint8Array(o.buffer)}case"uint8":{if(i.some(o=>o<0||o>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(l=>l<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let o=Uint32Array.from(i,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},xs=1,pr=()=>xs++,Ar=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Js=(e,t)=>{let n=Vr.get(e);if(!n)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,o)=>i*o)*n/8):0},Zs=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:i,dataType:o,shape:l,fallbackDataType:u}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=i,this.dataType=o,this.tensorShape=l,this.fallbackDataType=u}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Js(this.dataType,this.tensorShape)}destroy(){He("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=$s(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return n.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((i,o)=>i===n[o])}setIsDataConverted(e){this.isDataConverted=e}},en=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,i){let o=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),u;if(!l?.input.dataTypes.includes(t)){if(u=Ar.get(t),!u||l?.input.dataTypes.includes(u))throw new Error(`WebNN backend does not support data type: ${t}`);He("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${u}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(o,t,n))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==Js(t,n))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 c=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,c,!0,!0,u),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=ns(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 He("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?$s(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()}},Pn=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=pr();return this.tensorTrackersById.set(e,new en(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,i,o){He("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${i}, copyOld: ${o}}`);let l=this.tensorTrackersById.get(t);if(!l)throw new Error("Tensor not found.");return l.ensureTensor(e,n,i,o)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");n.upload(t)}async download(e,t){He("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,i){let o=this.getMLContext(e),l=pr(),u=new Zs({sessionId:e,context:o,tensor:t,dataType:n,shape:i});return this.tensorTrackersById.set(l,new en(this,u)),this.externalTensors.add(u),l}async getCachedTensor(e,t,n,i,o,l,u){let c=this.getMLContext(e);for(let[p,m]of this.freeTensors.entries())if(m.canReuseTensor(c,t,n)){He("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${n}`);let g=this.freeTensors.splice(p,1)[0];return g.sessionId=e,g}He("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${n}}`);let h=await c.createTensor({dataType:u??t,shape:n,dimensions:n,usage:i,writable:o,readable:l});return new Zs({sessionId:e,context:c,tensor:h,dataType:t,shape:n,fallbackDataType:u})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},On=(...e)=>new Pn(...e)}),is,Dn,zn,Ln=S(()=>{Ie(),Ht(),ss(),fi(),tr(),is=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Dn=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),i=Object.keys(t).sort();return n.length===i.length&&n.every((o,l)=>o===i[l]&&e[o]===t[o])},zn=class{constructor(e){this.tensorManager=On(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,Ks(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){He("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){He("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let n of t)He("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${n}}`),this.tensorManager.releaseTensorId(n);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let n=this.mlContextCache.findIndex(i=>i.gpuDevice===e);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:i}),i}}else if(e===void 0){let n=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let t=this.mlContextCache.findIndex(n=>Dn(n.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:n}),n}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let i=this.mlContextCache.findIndex(o=>o.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){He("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,i,o){let l=is.get(n);if(!l)throw new Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,l,i,o)}async createTemporaryTensor(e,t,n){He("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let i=is.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,i,n,!1);let l=this.temporarySessionTensorIds.get(e);return l?l.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,t){if(!Pe().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");He("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return Rr(n,t)}}registerMLTensor(e,t,n,i){let o=is.get(n);if(!o)throw new Error(`Unsupported ONNX data type: ${n}`);let l=this.tensorManager.registerTensor(e,t,o,i);return He("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${i}} -> {tensorId: ${l}}`),l}registerMLConstant(e,t,n,i,o,l,u=!1){if(!l)throw new Error("External mounted files are not available.");let c=e;e.startsWith("./")&&(c=e.substring(2));let h=l.get(c);if(!h)throw new Error(`File with name ${c} not found in preloaded files.`);if(t+n>h.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=h.slice(t,t+n).buffer,m;switch(o.dataType){case"float32":m=new Float32Array(p);break;case"float16":m=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(p):new Uint16Array(p);break;case"int32":m=new Int32Array(p);break;case"uint32":m=new Uint32Array(p);break;case"int64":if(u){let g=ns(new Uint8Array(p),"int64");m=new Int32Array(g.buffer),o.dataType="int32"}else m=new BigInt64Array(p);break;case"uint64":m=new BigUint64Array(p);break;case"int8":m=new Int8Array(p);break;case"int4":case"uint4":case"uint8":m=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return He("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${u?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),i.constant(o,m)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let i=is.get(jt(t)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:n?!!o?.input.dataTypes.includes(i):!!o?.output.dataTypes.includes(i)}flush(){}}}),tn=S(()=>{}),rn,sn,Cs,nn,an,on,Bn,Nn,mi,Ki=S(()=>{tr(),tn(),rn=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]]),sn=[],Cs=e=>Math.ceil(Number(e)/16)*16,nn=e=>{for(let t=0;t<sn.length;t++){let n=sn[t];if(e<=n)return n}return Math.ceil(e/16)*16},an=1,on=()=>an++,Bn=async(e,t,n,i)=>{let o=Cs(n),l=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let u=e.getCommandEncoder();e.endComputePass(),u.copyBufferToBuffer(t,0,l,0,o),e.flush(),await l.mapAsync(GPUMapMode.READ);let c=l.getMappedRange();if(i){let h=i();return h.set(new Uint8Array(c,0,n)),h}else return new Uint8Array(c.slice(0,n))}finally{l.destroy()}},Nn=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 rn)sn.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,i=t.byteOffset,o=t.byteLength,l=Cs(o),u=this.storageCache.get(e);if(!u)throw new Error("gpu data for uploading does not exist");if(Number(u.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${u.originalSize}, data size=${o}`);let c=this.backend.device.createBuffer({mappedAtCreation:!0,size:l,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),h=c.getMappedRange();new Uint8Array(h).set(new Uint8Array(n,i,o)),c.unmap();let p=this.backend.device.createCommandEncoder();p.copyBufferToBuffer(c,0,u.gpuData.buffer,0,l),this.backend.device.queue.submit([p.finish()]),c.destroy(),He("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)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(n.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=Cs(n.originalSize),l=this.backend.getCommandEncoder();this.backend.endComputePass(),l.copyBufferToBuffer(n.gpuData.buffer,0,i.gpuData.buffer,0,o)}registerExternalBuffer(e,t,n){let i;if(n){if(i=n[0],e===n[1])return He("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=on();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:t}),He("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),He("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=nn(e),i,o=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,l=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||l){let c=(o?this.freeBuffers:this.freeUniformBuffers).get(n);c?c.length>0?i=c.pop():i=this.backend.device.createBuffer({size:n,usage:t}):i=this.backend.device.createBuffer({size:n,usage:t})}else i=this.backend.device.createBuffer({size:n,usage:t});let u={id:on(),type:0,buffer:i};return this.storageCache.set(u.id,{gpuData:u,originalSize:Number(e)}),He("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${u.id}`),u}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,n=this.storageCache.get(t);if(!n){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return He("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw new Error("data does not exist");await Bn(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=rn.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.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(n=>{n.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(He("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},mi=(...e)=>new Nn(...e)}),y,E,A=S(()=>{y=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=e=>new y(e)}),D,O,G,U,L,V,re,ie,Z,Q,Te,F,le,ut,Be,Ee,Ne,we=S(()=>{Ie(),ke(),D=64,O=(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}`)}},G=(e,t=1)=>{let n=O(e,t);return typeof n=="string"?n:n[0]},U=(e,t=1)=>{let n=O(e,t);return typeof n=="string"?n:n[1]},L=(...e)=>{let t=[];return e.forEach(n=>{n.length!==0&&t.push({type:12,data:n},{type:12,data:K.computeStrides(n)})}),t},V=e=>e%4===0?4:e%2===0?2:1,re=(e="f32",t,n="0")=>!t||t===1?`${e}(${n})`:`vec${t}<${e}>(${n})`,ie=(e,t,n)=>e==="f32"?n:t===1?`f32(${n})`:`vec${t}<f32>(${n})`,Z=(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,Q=(e,t,n,i)=>e.startsWith("uniforms.")&&n>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}]`:n>1?`${e}[${t}]`:e,Te=(e,t,n,i,o)=>{let l=typeof n=="number",u=l?n:n.length,c=[...new Array(u).keys()],h=u<2?"u32":u<=4?`vec${u}<u32>`:`array<u32, ${u}>`,p=O(t,o),m=typeof p=="string"?p:p[1],g=typeof p=="string"?p:p[0],w={indices:h,value:m,storage:g,tensor:t},v=oe=>typeof oe=="string"?oe:`${oe}u`,b={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},x=l?"uniforms.":"",M=`${x}${e}_shape`,k=`${x}${e}_strides`,$="";for(let oe=0;oe<u-1;oe++)$+=`
|
|
7
|
+
let dim${oe} = current / ${Q(k,oe,u)};
|
|
8
|
+
let rest${oe} = current % ${Q(k,oe,u)};
|
|
9
|
+
indices[${oe}] = dim${oe};
|
|
10
|
+
current = rest${oe};
|
|
11
11
|
`;$+=`indices[${u-1}] = current;`;let P=u<2?"":`
|
|
12
12
|
fn o2i_${e}(offset: u32) -> ${w.indices} {
|
|
13
13
|
var indices: ${w.indices};
|
|
14
14
|
var current = offset;
|
|
15
15
|
${$}
|
|
16
16
|
return indices;
|
|
17
|
-
}`,I=
|
|
17
|
+
}`,I=oe=>(b.offsetToIndices=!0,u<2?oe:`o2i_${e}(${oe})`),B=[];if(u>=2)for(let oe=u-1;oe>=0;oe--)B.push(`${Q(k,oe,u)} * (indices[${oe}])`);let q=u<2?"":`
|
|
18
18
|
fn i2o_${e}(indices: ${w.indices}) -> u32 {
|
|
19
19
|
return ${B.join("+")};
|
|
20
|
-
}`,
|
|
21
|
-
return ${
|
|
22
|
-
}`,`${Ae}(${
|
|
20
|
+
}`,H=oe=>(b.indicesToOffset=!0,u<2?oe:`i2o_${e}(${oe})`),ee=(...oe)=>u===0?"0u":`${w.indices}(${oe.map(v).join(",")})`,ue=(oe,Oe)=>u<2?`${oe}`:`${Q(oe,Oe,u)}`,_e=(oe,Oe,Ae)=>u<2?`${oe}=${Ae};`:`${Q(oe,Oe,u)}=${Ae};`,Fe={},Re=(oe,Oe)=>{b.broadcastedIndicesToOffset=!0;let Ae=`${Oe.name}broadcastedIndicesTo${e}Offset`;if(Ae in Fe)return`${Ae}(${oe})`;let $e=[];for(let Dt=u-1;Dt>=0;Dt--){let Xt=Oe.indicesGet("outputIndices",Dt+Oe.rank-u);$e.push(`${ue(k,Dt)} * (${Xt} % ${ue(M,Dt)})`)}return Fe[Ae]=`fn ${Ae}(outputIndices: ${Oe.type.indices}) -> u32 {
|
|
21
|
+
return ${$e.length>0?$e.join("+"):"0u"};
|
|
22
|
+
}`,`${Ae}(${oe})`},Me=(oe,Oe)=>(()=>{if(w.storage===w.value)return`${e}[${oe}]=${Oe};`;if(w.storage==="vec2<u32>"&&w.value==="i32")return`${e}[${oe}]=vec2<u32>(u32(${Oe}), select(0u, 0xFFFFFFFFu, ${Oe} < 0));`;if(w.storage==="vec2<u32>"&&w.value==="u32")return`${e}[${oe}]=vec2<u32>(u32(${Oe}), 0u);`;if(w.storage==="u32"&&w.value==="vec4<bool>")return`${e}[${oe}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${Oe}));`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),Qe=oe=>(()=>{if(w.storage===w.value)return`${e}[${oe}]`;if(w.storage==="vec2<u32>"&&w.value==="i32")return`i32(${e}[${oe}].x)`;if(w.storage==="vec2<u32>"&&w.value==="u32")return`u32(${e}[${oe}].x)`;if(w.storage==="u32"&&w.value==="vec4<bool>")return`vec4<bool>(bool(${e}[${oe}] & 0xFFu), bool(${e}[${oe}] & 0xFF00u), bool(${e}[${oe}] & 0xFF0000u), bool(${e}[${oe}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),ye=u<2?"":`
|
|
23
23
|
fn get_${e}ByIndices(indices: ${w.indices}) -> ${m} {
|
|
24
|
-
return ${
|
|
25
|
-
}
|
|
26
|
-
fn get_${e}(${
|
|
24
|
+
return ${Qe(`i2o_${e}(indices)`)};
|
|
25
|
+
}`,xe=u<2?"":(()=>{let oe=c.map(Ae=>`d${Ae}: u32`).join(", "),Oe=c.map(Ae=>`d${Ae}`).join(", ");return`
|
|
26
|
+
fn get_${e}(${oe}) -> ${m} {
|
|
27
27
|
return get_${e}ByIndices(${ee(Oe)});
|
|
28
|
-
}`})(),Le=(...
|
|
28
|
+
}`})(),Le=(...oe)=>{if(oe.length!==u)throw new Error(`indices length must be ${u}`);let Oe=oe.map(v).join(",");return u===0?Qe("0u"):u===1?Qe(Oe[0]):(b.get=!0,b.getByIndices=!0,b.indicesToOffset=!0,`get_${e}(${Oe})`)},Ge=oe=>u<2?Qe(oe):(b.getByIndices=!0,b.indicesToOffset=!0,`get_${e}ByIndices(${oe})`),De=u<2?"":`
|
|
29
29
|
fn set_${e}ByIndices(indices: ${w.indices}, value: ${m}) {
|
|
30
30
|
${Me(`i2o_${e}(indices)`,"value")}
|
|
31
|
-
}`,
|
|
32
|
-
fn set_${e}(${
|
|
31
|
+
}`,je=u<2?"":(()=>{let oe=c.map(Ae=>`d${Ae}: u32`).join(", "),Oe=c.map(Ae=>`d${Ae}`).join(", ");return`
|
|
32
|
+
fn set_${e}(${oe}, value: ${m}) {
|
|
33
33
|
set_${e}ByIndices(${ee(Oe)}, value);
|
|
34
|
-
}`})();return{impl:()=>{let
|
|
35
|
-
`)},type:w,offsetToIndices:I,indicesToOffset:
|
|
34
|
+
}`})();return{impl:()=>{let oe=[],Oe=!1;return b.offsetToIndices&&(oe.push(P),Oe=!0),b.indicesToOffset&&(oe.push(q),Oe=!0),b.broadcastedIndicesToOffset&&(Object.values(Fe).forEach(Ae=>oe.push(Ae)),Oe=!0),b.set&&(oe.push(je),Oe=!0),b.setByIndices&&(oe.push(De),Oe=!0),b.get&&(oe.push(xe),Oe=!0),b.getByIndices&&(oe.push(ye),Oe=!0),!l&&Oe&&oe.unshift(`const ${M} = ${w.indices}(${n.join(",")});`,`const ${k} = ${w.indices}(${K.computeStrides(n).join(",")});`),oe.join(`
|
|
35
|
+
`)},type:w,offsetToIndices:I,indicesToOffset:H,broadcastedIndicesToOffset:Re,indices:ee,indicesGet:ue,indicesSet:_e,set:(...oe)=>{if(oe.length!==u+1)throw new Error(`indices length must be ${u}`);let Oe=oe[u];if(typeof Oe!="string")throw new Error("value must be string");let Ae=oe.slice(0,u).map(v).join(",");return u===0?Me("0u",Oe):u===1?Me(Ae[0],Oe):(b.set=!0,b.setByIndices=!0,b.indicesToOffset=!0,`set_${e}(${Ae}, ${Oe})`)},setByOffset:Me,setByIndices:(oe,Oe)=>u<2?Me(oe,Oe):(b.setByIndices=!0,b.indicesToOffset=!0,`set_${e}ByIndices(${oe}, ${Oe});`),get:Le,getByOffset:Qe,getByIndices:Ge,usage:i,name:e,strides:k,shape:M,rank:u}},F=(e,t,n,i=1)=>Te(e,t,n,"input",i),le=(e,t,n,i=1)=>Te(e,t,n,"output",i),ut=(e,t,n)=>Te(e,t,n,"atomicOutput",1),Be=(e,t,n,i=1)=>Te(e,t,n,"internal",i),Ee=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=D){let t=typeof e=="number"?e:e[0],n=typeof e=="number"?1:e[1],i=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${n}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*n*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${n}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,l=o?`@builtin(global_invocation_id) global_id : vec3<u32>,
|
|
36
36
|
@builtin(workgroup_id) workgroup_id : vec3<u32>,
|
|
37
37
|
@builtin(local_invocation_index) local_idx : u32,
|
|
38
38
|
@builtin(local_invocation_id) local_id : vec3<u32>`:`@builtin(global_invocation_id) global_id : vec3<u32>,
|
|
@@ -50,46 +50,46 @@
|
|
|
50
50
|
struct Uniforms { ${e.join(", ")} };
|
|
51
51
|
@group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(`
|
|
52
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])}},Ne=(e,t)=>new
|
|
54
|
-
var a: ${n.type.indices};`;for(let l=0;l<t;++l)o+=`a[${e[l]}]=i[${l}];`;return o+="return a;}"},
|
|
55
|
-
${
|
|
56
|
-
${
|
|
57
|
-
${
|
|
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])}},Ne=(e,t)=>new Ee(e,t)}),kt,Mt,Ir,as,ln,Un,ct,ar,Fn,Ue=S(()=>{Ie(),ke(),A(),we(),kt=(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}`)},Mt=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),Ir=(e,t)=>K.sortBasedOnPerm(e,Mt(e.length,t)),as=(e,t,n,i)=>{let o=`fn perm(i: ${i.type.indices}) -> ${n.type.indices} {
|
|
54
|
+
var a: ${n.type.indices};`;for(let l=0;l<t;++l)o+=`a[${e[l]}]=i[${l}];`;return o+="return a;}"},ln=(e,t)=>{let n=[],i=[];for(let o=0;o<e.length;++o)e[o]!==1&&n.push(e[o]),e[t[o]]!==1&&i.push(t[o]);return{newShape:n,newPerm:i}},Un=(e,t)=>{let n=0;for(let i=0;i<e.length;++i)if(t[e[i]]!==1){if(e[i]<n)return!1;n=e[i]}return!0},ct=(e,t)=>{let n=e.dataType,i=e.dims.length,o=Mt(i,t),l=Ir(e.dims,o),u=e.dims,c=l,h=i<2||Un(o,e.dims),p;if(h)return p=b=>{let x=F("input",n,u,4),M=le("output",n,c,4);return`
|
|
55
|
+
${b.registerUniform("output_size","u32").declareVariables(x,M)}
|
|
56
|
+
${b.mainStart()}
|
|
57
|
+
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
58
58
|
output[global_idx] = input[global_idx];
|
|
59
|
-
}`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let
|
|
59
|
+
}`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let b=K.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(b/64/4)},programUniforms:[{type:12,data:Math.ceil(b/4)}]}},getShaderSource:p};let{newShape:m,newPerm:g}=ln(e.dims,o),w=K.areEqual(g,[2,3,1]),v=K.areEqual(g,[3,1,2]);if(m.length===2||w||v){u=w?[m[0],m[1]*m[2]]:v?[m[0]*m[1],m[2]]:m,c=[u[1],u[0]];let b=16;return p=x=>{let M=F("a",n,u.length),k=le("output",n,c.length);return`
|
|
60
60
|
${x.registerUniform("output_size","u32").declareVariables(M,k)}
|
|
61
|
-
var<workgroup> tile : array<array<${k.type.value}, ${
|
|
62
|
-
${x.mainStart([
|
|
63
|
-
let stride = (uniforms.output_shape[1] - 1) / ${
|
|
61
|
+
var<workgroup> tile : array<array<${k.type.value}, ${b+1}>, ${b}>;
|
|
62
|
+
${x.mainStart([b,b,1])}
|
|
63
|
+
let stride = (uniforms.output_shape[1] - 1) / ${b} + 1;
|
|
64
64
|
let workgroup_id_x = workgroup_index % stride;
|
|
65
65
|
let workgroup_id_y = workgroup_index / stride;
|
|
66
|
-
let input_col = workgroup_id_y * ${
|
|
67
|
-
let input_row = workgroup_id_x * ${
|
|
66
|
+
let input_col = workgroup_id_y * ${b}u + local_id.x;
|
|
67
|
+
let input_row = workgroup_id_x * ${b}u + local_id.y;
|
|
68
68
|
if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {
|
|
69
69
|
tile[local_id.y][local_id.x] = ${M.getByIndices(`${M.type.indices}(input_row, input_col)`)};
|
|
70
70
|
}
|
|
71
71
|
workgroupBarrier();
|
|
72
72
|
|
|
73
|
-
let output_col = workgroup_id_x * ${
|
|
74
|
-
let output_row = workgroup_id_y * ${
|
|
73
|
+
let output_col = workgroup_id_x * ${b}u + local_id.x;
|
|
74
|
+
let output_row = workgroup_id_y * ${b}u + local_id.y;
|
|
75
75
|
if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {
|
|
76
76
|
${k.setByIndices(`${k.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")}
|
|
77
77
|
}
|
|
78
|
-
}`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let x=
|
|
79
|
-
${
|
|
78
|
+
}`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let x=K.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c[1]/b),y:Math.ceil(c[0]/b)},programUniforms:[{type:12,data:x},...L(u,c)]}},getShaderSource:p}}return p=b=>{let x=F("a",n,u.length),M=le("output",n,c.length);return`
|
|
79
|
+
${b.registerUniform("output_size","u32").declareVariables(x,M)}
|
|
80
80
|
|
|
81
|
-
${
|
|
81
|
+
${as(o,i,x,M)}
|
|
82
82
|
|
|
83
|
-
${
|
|
84
|
-
${
|
|
83
|
+
${b.mainStart()}
|
|
84
|
+
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
85
85
|
|
|
86
86
|
let indices = ${M.offsetToIndices("global_idx")};
|
|
87
87
|
let aIndices = perm(indices);
|
|
88
88
|
|
|
89
89
|
${M.setByOffset("global_idx",x.getByIndices("aIndices"))}
|
|
90
|
-
}`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let
|
|
90
|
+
}`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let b=K.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:[{type:12,data:b},...L(u,c)]}},getShaderSource:p}},ar=(e,t)=>{kt(e.inputs,t.perm),e.compute(ct(e.inputs[0],t.perm))},Fn=e=>E({perm:e.perm})}),rr,gi,fr,ks,wt,Lt,un,Rs,Vn,yi,Et,mr,os,vt,ht,or,wi,vi,Po,Oo,Do,fm=S(()=>{Ie(),ke(),we(),Xi(),Ue(),rr={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"},gi={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"},fr={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},ks={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},wt=(e,t)=>{let n=[];for(let i=t-e;i<t;++i)n.push(i);return n},Lt=(e,t)=>{let n=[],i=e.length;for(let l=0;l<i;l++)t.indexOf(l)===-1&&n.push(e[l]);let o=t.map(l=>e[l]);return[n,o]},un=(e,t)=>{let n=e.length+t.length,i=[],o=0;for(let l=0;l<n;l++)t.indexOf(l)===-1?i.push(e[o++]):i.push(1);return i},Rs=(e,t)=>{for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0},Vn=(e,t)=>{let n=[];if(!Rs(e,t)){for(let i=0;i<t;++i)e.indexOf(i)===-1&&n.push(i);e.forEach(i=>n.push(i))}return n},yi=(e,t,n,i,o,l,u)=>{let c=n[0].dims,h=K.size(l),p=K.size(u),m=F("_A",n[0].dataType,c),g=le("output",o,l),w=64;h===1&&(w=256);let v=`
|
|
91
91
|
var<workgroup> aBestValues : array<f32, ${w}>;
|
|
92
|
-
`,
|
|
92
|
+
`,b=x=>`
|
|
93
93
|
${x.registerUniform("reduceSize","u32").declareVariables(m,g)}
|
|
94
94
|
${v}
|
|
95
95
|
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
@@ -100,7 +100,7 @@
|
|
|
100
100
|
let outputIndex = global_idx / ${w};
|
|
101
101
|
let offset = outputIndex * uniforms.reduceSize;
|
|
102
102
|
|
|
103
|
-
var bestValue = f32(${
|
|
103
|
+
var bestValue = f32(${fr[i]});
|
|
104
104
|
let Length = uniforms.reduceSize;
|
|
105
105
|
for (var k = local_idx; k < Length; k = k + ${w}) {
|
|
106
106
|
let candidate = f32(${m.getByOffset("offset + k")});
|
|
@@ -115,7 +115,7 @@
|
|
|
115
115
|
let interval = DIV_CEIL(reduceSize, 2u);
|
|
116
116
|
if (local_idx < currentSize) {
|
|
117
117
|
let candidate = aBestValues[local_idx + interval];
|
|
118
|
-
bestValue = ${
|
|
118
|
+
bestValue = ${gi[i]};
|
|
119
119
|
aBestValues[local_idx] = bestValue;
|
|
120
120
|
}
|
|
121
121
|
reduceSize = interval;
|
|
@@ -123,9 +123,9 @@
|
|
|
123
123
|
}
|
|
124
124
|
|
|
125
125
|
if (local_idx == 0u) {
|
|
126
|
-
${g.setByOffset("outputIndex",`${i==="mean"?`${g.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${g.type.storage}(${
|
|
126
|
+
${g.setByOffset("outputIndex",`${i==="mean"?`${g.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${g.type.storage}(${ks[i]})`}`)};
|
|
127
127
|
}
|
|
128
|
-
}`;return{name:e,shaderCache:{hint:`${t};${w}`,inputDependencies:["type"]},getShaderSource:
|
|
128
|
+
}`;return{name:e,shaderCache:{hint:`${t};${w}`,inputDependencies:["type"]},getShaderSource:b,getRunData:()=>({outputs:[{dims:l,dataType:o}],dispatchGroup:{x:h},programUniforms:[{type:12,data:p}]})}},Et=(e,t,n,i)=>{let o=e.inputs.length===1?n:Qi(e.inputs,n),l=o.axes;l.length===0&&!o.noopWithEmptyAxes&&(l=e.inputs[0].dims.map((v,b)=>b));let u=K.normalizeAxes(l,e.inputs[0].dims.length),c=u,h=e.inputs[0],p=Vn(c,e.inputs[0].dims.length);p.length>0&&(h=e.compute(ct(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],c=wt(c.length,h.dims.length));let[m,g]=Lt(h.dims,c),w=m;o.keepDims&&(w=un(m,u)),e.compute(yi(t,o.cacheKey,[h],i,e.inputs[0].dataType,w,g),{inputs:[h]})},mr=(e,t)=>{Et(e,"ReduceMeanShared",t,"mean")},os=(e,t)=>{Et(e,"ReduceL1Shared",t,"l1")},vt=(e,t)=>{Et(e,"ReduceL2Shared",t,"l2")},ht=(e,t)=>{Et(e,"ReduceLogSumExpShared",t,"logSumExp")},or=(e,t)=>{Et(e,"ReduceMaxShared",t,"max")},wi=(e,t)=>{Et(e,"ReduceMinShared",t,"min")},vi=(e,t)=>{Et(e,"ReduceProdShared",t,"prod")},Po=(e,t)=>{Et(e,"ReduceSumShared",t,"sum")},Oo=(e,t)=>{Et(e,"ReduceSumSquareShared",t,"sumSquare")},Do=(e,t)=>{Et(e,"ReduceLogSumShared",t,"logSum")}}),gr,zo,_i,Qi,yr,Lo,Bo,No,Uo,Fo,Vo,Go,qo,Wo,Ho,wr,jo,Ko,Qo,Xo,Yo,Jo,Zo,el,tl,rl,Xi=S(()=>{Ie(),ke(),A(),we(),fm(),gr=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.")},zo=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],_i=(e,t,n,i,o,l,u=!1,c=!1)=>{let h=[],p=n[0].dims,m=p.length,g=K.normalizeAxes(o,m),w=!c&&g.length===0;p.forEach((x,M)=>{w||g.indexOf(M)>=0?u&&h.push(1):h.push(x)});let v=h.length,b=K.size(h);return{name:e,shaderCache:t,getShaderSource:x=>{let M=[],k=F("_A",n[0].dataType,m),$=le("output",l,v),P=i(k,$,g),I=P[2];for(let B=0,q=0;B<m;B++)w||g.indexOf(B)>=0?(u&&q++,I=`for(var j${B}: u32 = 0; j${B} < ${p[B]}; j${B}++) {
|
|
129
129
|
${P[2].includes("last_index")?`let last_index = j${B};`:""}
|
|
130
130
|
${k.indicesSet("input_indices",B,`j${B}`)}
|
|
131
131
|
${I}
|
|
@@ -146,19 +146,19 @@
|
|
|
146
146
|
${P[3]}
|
|
147
147
|
${P.length===4?$.setByOffset("global_idx","value"):P.slice(4).join(`
|
|
148
148
|
`)}
|
|
149
|
-
}`},getRunData:()=>({outputs:[{dims:h,dataType:l}],dispatchGroup:{x:Math.ceil(
|
|
150
|
-
`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},Vo=(e,t)=>{
|
|
151
|
-
`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},qo=(e,t)=>{
|
|
149
|
+
}`},getRunData:()=>({outputs:[{dims:h,dataType:l}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:[{type:12,data:b},...L(p,h)]})}},Qi=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(i=>n.push(Number(i))),E({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},yr=(e,t,n,i)=>{let o=e.inputs,l=o.length===1?n:Qi(o,n);e.compute(_i(t,{hint:l.cacheKey,inputDependencies:["rank"]},[o[0]],l.noopWithEmptyAxes&&l.axes.length===0?zo:i,l.axes,o[0].dataType,l.keepDims,l.noopWithEmptyAxes),{inputs:[0]})},Lo=(e,t)=>{gr(e.inputs),yr(e,"ReduceLogSum",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},Bo=(e,t)=>{gr(e.inputs),yr(e,"ReduceL1",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},No=(e,t)=>{gr(e.inputs),yr(e,"ReduceL2",t,(n,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Uo=(e,t)=>{gr(e.inputs),yr(e,"ReduceLogSumExp",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},Fo=(e,t)=>{gr(e.inputs),yr(e,"ReduceMax",t,(n,i,o)=>{let l=[];for(let u=0;u<n.rank;u++)(o.indexOf(u)>=0||o.length===0)&&l.push(n.indicesSet("input_indices",u,0));return[`${l.join(`
|
|
150
|
+
`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},Vo=(e,t)=>{gr(e.inputs),yr(e,"ReduceMean",t,(n,i,o)=>{let l=1;for(let u=0;u<n.rank;u++)(o.indexOf(u)>=0||o.length===0)&&(l*=e.inputs[0].dims[u]);return["var sum = f32(0);","",`sum += f32(${n.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${l});`]})},Go=(e,t)=>{gr(e.inputs),yr(e,"ReduceMin",t,(n,i,o)=>{let l=[];for(let u=0;u<n.rank;u++)(o.indexOf(u)>=0||o.length===0)&&l.push(`input_indices[${u}] = 0;`);return[`${l.join(`
|
|
151
|
+
`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},qo=(e,t)=>{gr(e.inputs),yr(e,"ReduceProd",t,(n,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},Wo=(e,t)=>{gr(e.inputs),yr(e,"ReduceSum",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},Ho=(e,t)=>{gr(e.inputs),yr(e,"ReduceSumSquare",t,(n,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += t * t;`,""])},wr=(e,t,n)=>{if(t.length===0)return n;let i=1,o=1;for(let l=0;l<t.length;l++)t.indexOf(l)===-1?i*=e[l]:o*=e[l];return o<32&&i>1024},jo=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Vo(e,t):mr(e,t)},Ko=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bo(e,t):os(e,t)},Qo=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?No(e,t):vt(e,t)},Xo=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Uo(e,t):ht(e,t)},Yo=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fo(e,t):or(e,t)},Jo=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Go(e,t):wi(e,t)},Zo=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qo(e,t):vi(e,t)},el=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Wo(e,t):Po(e,t)},tl=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ho(e,t):Oo(e,t)},rl=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Lo(e,t):Do(e,t)}}),Yi,sl,nl,Ji,mm=S(()=>{Ie(),A(),Xi(),Yi=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.")},sl=(e,t)=>{Yi(e.inputs);let n=(i,o,l)=>{let u=[];for(let c=0;c<i.rank;c++)(l.indexOf(c)>=0||l.length===0)&&u.push(`input_indices[${c}] = 0;`);return[`${u.join(`
|
|
152
152
|
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
153
153
|
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {
|
|
154
154
|
value = ${i.getByIndices("input_indices")};
|
|
155
155
|
best_index = i32(last_index);
|
|
156
|
-
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(
|
|
156
|
+
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(_i("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},nl=(e,t)=>{Yi(e.inputs);let n=(i,o,l)=>{let u=[];for(let c=0;c<i.rank;c++)(l.indexOf(c)>=0||l.length===0)&&u.push(`input_indices[${c}] = 0;`);return[`${u.join(`
|
|
157
157
|
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
158
158
|
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {
|
|
159
159
|
value = ${i.getByIndices("input_indices")};
|
|
160
160
|
best_index = i32(last_index);
|
|
161
|
-
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(
|
|
161
|
+
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(_i("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},Ji=e=>E(e)}),il,bi,al,ol,ll,Gn,ul,dl,Zi=S(()=>{Ie(),ke(),tn(),we(),il=(e,t)=>{let n=e[0],i=e[1],o=e[2],l=e[3],u=e[4],c=e[5];if(u&&c)throw new Error("Attention cannot have both past and attention_bias");if(n.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let h=n.dims[0],p=n.dims[1],m=n.dims[2];if(o.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]!==m)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==i.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let g=o.dims[0]/3,w=g,v=w;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let P of t.qkvHiddenSizes)if(P%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");g=t.qkvHiddenSizes[0],w=t.qkvHiddenSizes[1],v=t.qkvHiddenSizes[2]}let b=p;if(g!==w)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==g+w+v)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let x=0;if(u){if(w!==v)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(u.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(u.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(u.dims[1]!==h)throw new Error('Input "past" second dimension must be batch_size');if(u.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(u.dims[4]!==w/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(x=u.dims[3])}let M=b+x,k=-1,$=0;if(l)throw new Error("Mask not supported");if(u)throw new Error("past is not supported");if(c){if(c.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(c.dims[0]!==h||c.dims[1]!==t.numHeads||c.dims[2]!==p||c.dims[3]!==M)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:h,sequenceLength:p,pastSequenceLength:x,kvSequenceLength:b,totalSequenceLength:M,maxSequenceLength:k,inputHiddenSize:m,hiddenSize:g,vHiddenSize:v,headSize:Math.floor(g/t.numHeads),vHeadSize:Math.floor(v/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:$,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},bi=(e,t,n)=>t&&e?`
|
|
162
162
|
let total_sequence_length_input = u32(${t.getByOffset("0")});
|
|
163
163
|
let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);
|
|
164
164
|
let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;
|
|
@@ -171,22 +171,22 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
171
171
|
`:`
|
|
172
172
|
${n?"let past_sequence_length = uniforms.past_sequence_length":""};
|
|
173
173
|
let present_sequence_length = total_sequence_length;
|
|
174
|
-
`,al=(e,t,n,i,o,l,u,c)=>{let h=V(u?1:l),p=64,m=l/h;m<p&&(p=32);let g=Math.ceil(l/h/p),w=[{type:12,data:t},{type:12,data:n},{type:12,data:i},{type:12,data:o},{type:12,data:m},{type:12,data:g}],v=G(e.dataType,h),
|
|
174
|
+
`,al=(e,t,n,i,o,l,u,c)=>{let h=V(u?1:l),p=64,m=l/h;m<p&&(p=32);let g=Math.ceil(l/h/p),w=[{type:12,data:t},{type:12,data:n},{type:12,data:i},{type:12,data:o},{type:12,data:m},{type:12,data:g}],v=G(e.dataType,h),b=U(1,h),x=["type"];u&&x.push("type"),c&&x.push("type");let M=k=>{let $=le("x",e.dataType,e.dims,h),P=[$],I=u?F("seq_lens",u.dataType,u.dims):void 0;I&&P.push(I);let B=c?F("total_sequence_length_input",c.dataType,c.dims):void 0;B&&P.push(B);let q=U(e.dataType),H=[{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
175
|
var<workgroup> thread_max: array<f32, ${p}>;
|
|
176
176
|
var<workgroup> thread_sum: array<f32, ${p}>;
|
|
177
|
-
${k.registerUniforms(
|
|
177
|
+
${k.registerUniforms(H).declareVariables(...P)}
|
|
178
178
|
${k.mainStart([p,1,1])}
|
|
179
179
|
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
180
180
|
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
181
181
|
let sequence_length = uniforms.sequence_length;
|
|
182
182
|
var total_sequence_length = uniforms.total_sequence_length;
|
|
183
|
-
${
|
|
183
|
+
${bi(I,B,!1)}
|
|
184
184
|
let local_offset = local_idx * uniforms.elements_per_thread;
|
|
185
185
|
let offset = (global_idx / ${p}) * uniforms.total_sequence_length + local_offset;
|
|
186
186
|
let seq_causal_length = ${u?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"};
|
|
187
|
-
var thread_max_vector = ${
|
|
187
|
+
var thread_max_vector = ${b}(-3.4028234663852886e+38f);
|
|
188
188
|
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
189
|
-
thread_max_vector = max(${
|
|
189
|
+
thread_max_vector = max(${b}(x[offset + i]), thread_max_vector);
|
|
190
190
|
}
|
|
191
191
|
thread_max[local_idx] = ${(()=>{switch(h){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: ${h}`)}})()};
|
|
192
192
|
workgroupBarrier();
|
|
@@ -196,9 +196,9 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
196
196
|
max_value = max(thread_max[i], max_value);
|
|
197
197
|
}
|
|
198
198
|
|
|
199
|
-
var sum_vector = ${
|
|
199
|
+
var sum_vector = ${b}(0);
|
|
200
200
|
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
201
|
-
sum_vector += exp(${
|
|
201
|
+
sum_vector += exp(${b}(x[offset + i]) - max_value);
|
|
202
202
|
}
|
|
203
203
|
thread_sum[local_idx] = ${(()=>{switch(h){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: ${h}`)}})()};
|
|
204
204
|
workgroupBarrier();
|
|
@@ -214,7 +214,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
214
214
|
}
|
|
215
215
|
} else {
|
|
216
216
|
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
217
|
-
var f32input = ${
|
|
217
|
+
var f32input = ${b}(x[offset + i]);
|
|
218
218
|
x[offset + i] = ${$.type.value}(exp(f32input - max_value) / sum);
|
|
219
219
|
}
|
|
220
220
|
}
|
|
@@ -222,23 +222,23 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
222
222
|
for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {
|
|
223
223
|
x[offset + total_seq_id] = ${$.type.value}(${q}(0));
|
|
224
224
|
}`:""};
|
|
225
|
-
}`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${p};${v};${h}`,inputDependencies:x},getShaderSource:M,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:t*n},programUniforms:w})}},ol=(e,t,n,i,o,l,u,c,h)=>{let p=u+l.kvSequenceLength,m=[l.batchSize,l.numHeads,l.sequenceLength,p],g=e>1&&i,w=l.kvNumHeads?l.kvNumHeads:l.numHeads,v=g?[l.batchSize,w,p,l.headSize]:void 0,
|
|
225
|
+
}`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${p};${v};${h}`,inputDependencies:x},getShaderSource:M,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:t*n},programUniforms:w})}},ol=(e,t,n,i,o,l,u,c,h)=>{let p=u+l.kvSequenceLength,m=[l.batchSize,l.numHeads,l.sequenceLength,p],g=e>1&&i,w=l.kvNumHeads?l.kvNumHeads:l.numHeads,v=g?[l.batchSize,w,p,l.headSize]:void 0,b=l.nReps?l.nReps:1,x=l.scale===0?1/Math.sqrt(l.headSize):l.scale,M=V(l.headSize),k=l.headSize/M,$=12,P={x:Math.ceil(p/$),y:Math.ceil(l.sequenceLength/$),z:l.batchSize*l.numHeads},I=[{type:12,data:l.sequenceLength},{type:12,data:k},{type:12,data:p},{type:12,data:l.numHeads},{type:12,data:l.headSize},{type:1,data:x},{type:12,data:u},{type:12,data:l.kvSequenceLength},{type:12,data:b}],B=g&&i&&K.size(i.dims)>0,q=["type","type"];B&&q.push("type"),o&&q.push("type"),c&&q.push("type"),h&&q.push("type");let H=[{dims:m,dataType:t.dataType,gpuDataType:0}];g&&H.push({dims:v,dataType:t.dataType,gpuDataType:0});let ee=ue=>{let _e=F("q",t.dataType,t.dims,M),Fe=F("key",n.dataType,n.dims,M),Re=[_e,Fe];if(B){let De=F("past_key",i.dataType,i.dims,M);Re.push(De)}o&&Re.push(F("attention_bias",o.dataType,o.dims));let Me=c?F("seq_lens",c.dataType,c.dims):void 0;Me&&Re.push(Me);let Qe=h?F("total_sequence_length_input",h.dataType,h.dims):void 0;Qe&&Re.push(Qe);let ye=le("output",t.dataType,m),xe=[ye];g&&xe.push(le("present_key",t.dataType,v,M));let Le=U(1,M),Ge=[{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
226
|
const TILE_SIZE = ${$}u;
|
|
227
227
|
|
|
228
228
|
var<workgroup> tileQ: array<${_e.type.storage}, ${$*$}>;
|
|
229
229
|
var<workgroup> tileK: array<${_e.type.storage}, ${$*$}>;
|
|
230
|
-
${ue.registerUniforms(Ge).declareVariables(...Re
|
|
230
|
+
${ue.registerUniforms(Ge).declareVariables(...Re,...xe)}
|
|
231
231
|
${ue.mainStart([$,$,1])}
|
|
232
232
|
// x holds the N and y holds the M
|
|
233
233
|
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
234
|
-
let kvHeadIdx = ${
|
|
235
|
-
let kv_num_heads = ${
|
|
234
|
+
let kvHeadIdx = ${b===1?"headIdx":"headIdx / uniforms.n_reps"};
|
|
235
|
+
let kv_num_heads = ${b===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
|
|
236
236
|
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
237
237
|
let m = workgroup_id.y * TILE_SIZE;
|
|
238
238
|
let n = workgroup_id.x * TILE_SIZE;
|
|
239
239
|
let sequence_length = uniforms.M;
|
|
240
240
|
var total_sequence_length = uniforms.N;
|
|
241
|
-
${
|
|
241
|
+
${bi(Me,Qe,!0)}
|
|
242
242
|
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;
|
|
243
243
|
let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
244
244
|
${B&&g?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};
|
|
@@ -277,12 +277,12 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
277
277
|
let headOffset = workgroup_id.z * uniforms.M * uniforms.N;
|
|
278
278
|
let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;
|
|
279
279
|
var sum: f32 = ${(()=>{switch(M){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: ${M}`)}})()};
|
|
280
|
-
output[outputIdx] = ${
|
|
280
|
+
output[outputIdx] = ${ye.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"};
|
|
281
281
|
}
|
|
282
|
-
}`};return{name:"AttentionProbs",shaderCache:{hint:`${M};${o!==void 0};${i!==void 0};${e}`,inputDependencies:q},getRunData:()=>({outputs:
|
|
282
|
+
}`};return{name:"AttentionProbs",shaderCache:{hint:`${M};${o!==void 0};${i!==void 0};${e}`,inputDependencies:q},getRunData:()=>({outputs:H,dispatchGroup:P,programUniforms:I}),getShaderSource:ee}},ll=(e,t,n,i,o,l,u=void 0,c=void 0)=>{let h=l+o.kvSequenceLength,p=o.nReps?o.nReps:1,m=o.vHiddenSize*p,g=e>1&&i,w=o.kvNumHeads?o.kvNumHeads:o.numHeads,v=g?[o.batchSize,w,h,o.headSize]:void 0,b=[o.batchSize,o.sequenceLength,m],x=12,M={x:Math.ceil(o.vHeadSize/x),y:Math.ceil(o.sequenceLength/x),z:o.batchSize*o.numHeads},k=[{type:12,data:o.sequenceLength},{type:12,data:h},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:m},{type:12,data:l},{type:12,data:o.kvSequenceLength},{type:12,data:p}],$=g&&i&&K.size(i.dims)>0,P=["type","type"];$&&P.push("type"),u&&P.push("type"),c&&P.push("type");let I=[{dims:b,dataType:t.dataType,gpuDataType:0}];g&&I.push({dims:v,dataType:t.dataType,gpuDataType:0});let B=q=>{let H=F("probs",t.dataType,t.dims),ee=F("v",n.dataType,n.dims),ue=[H,ee];$&&ue.push(F("past_value",i.dataType,i.dims));let _e=u?F("seq_lens",u.dataType,u.dims):void 0;u&&ue.push(_e);let Fe=c?F("total_sequence_length_input",c.dataType,c.dims):void 0;c&&ue.push(Fe);let Re=[le("output",t.dataType,b)];g&&Re.push(le("present_value",t.dataType,v));let Me=[{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
283
|
const TILE_SIZE = ${x}u;
|
|
284
|
-
var<workgroup> tileQ: array<${
|
|
285
|
-
var<workgroup> tileV: array<${
|
|
284
|
+
var<workgroup> tileQ: array<${H.type.value}, ${x*x}>;
|
|
285
|
+
var<workgroup> tileV: array<${H.type.value}, ${x*x}>;
|
|
286
286
|
${q.registerUniforms(Me).declareVariables(...ue,...Re)}
|
|
287
287
|
${q.mainStart([x,x,1])}
|
|
288
288
|
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
@@ -293,13 +293,13 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
293
293
|
let n = global_id.x;
|
|
294
294
|
let sequence_length = uniforms.M;
|
|
295
295
|
var total_sequence_length = uniforms.K;
|
|
296
|
-
${
|
|
296
|
+
${bi(_e,Fe,!0)}
|
|
297
297
|
let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
298
298
|
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch
|
|
299
299
|
${$&&g?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};
|
|
300
300
|
let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;
|
|
301
301
|
${g?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""}
|
|
302
|
-
var value = ${
|
|
302
|
+
var value = ${H.type.storage}(0);
|
|
303
303
|
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
304
304
|
if (m < uniforms.M && w + local_id.x < uniforms.K) {
|
|
305
305
|
tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];
|
|
@@ -334,13 +334,13 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
334
334
|
+ headIdx * uniforms.N + n;
|
|
335
335
|
output[outputIdx] = value;
|
|
336
336
|
}
|
|
337
|
-
}`};return{name:"AttentionScore",shaderCache:{hint:`${i!==void 0};${e}`,inputDependencies:P},getRunData:()=>({outputs:I,dispatchGroup:M,programUniforms:k}),getShaderSource:B}},Gn=(e,t,n,i,o,l,u,c,h,p,m=void 0,g=void 0)=>{let w=Math.min(e.outputCount,1+(u?1:0)+(c?1:0)),v=w>1?u:void 0,
|
|
337
|
+
}`};return{name:"AttentionScore",shaderCache:{hint:`${i!==void 0};${e}`,inputDependencies:P},getRunData:()=>({outputs:I,dispatchGroup:M,programUniforms:k}),getShaderSource:B}},Gn=(e,t,n,i,o,l,u,c,h,p,m=void 0,g=void 0)=>{let w=Math.min(e.outputCount,1+(u?1:0)+(c?1:0)),v=w>1?u:void 0,b=w>1?c:void 0,x=w>1?p.pastSequenceLength:0,M=x+p.kvSequenceLength,k=h&&K.size(h.dims)>0?h:void 0,$=[t,n];v&&K.size(v.dims)>0&&$.push(v),k&&$.push(k),m&&$.push(m),g&&$.push(g);let P=e.compute(ol(w,t,n,v,k,p,x,m,g),{inputs:$,outputs:w>1?[-1,1]:[-1]})[0];e.compute(al(P,p.batchSize,p.numHeads,x,p.sequenceLength,M,m,g),{inputs:m&&g?[P,m,g]:[P],outputs:[]});let I=[P,i];b&&K.size(b.dims)>0&&I.push(b),m&&I.push(m),g&&I.push(g),e.compute(ll(w,P,i,b,p,x,m,g),{inputs:I,outputs:w>1?[0,2]:[0]})},ul=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],i=t.sequenceLength,o=t.inputHiddenSize,l=t.headSize,u=12,c={x:Math.ceil(t.headSize/u),y:Math.ceil(t.sequenceLength/u),z:t.batchSize*t.numHeads},h=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:i},{type:12,data:o},{type:12,data:l},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=g=>{let w=le("output_q",h[0].dataType,n),v=le("output_k",h[0].dataType,n),b=le("output_v",h[0].dataType,n),x=F("input",h[0].dataType,h[0].dims),M=F("weight",h[1].dataType,h[1].dims),k=F("bias",h[2].dataType,h[2].dims),$=x.type.storage,P=[{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
338
|
const TILE_SIZE = ${u}u;
|
|
339
339
|
var<workgroup> tileInput: array<${$}, ${u*u}>;
|
|
340
340
|
var<workgroup> tileWeightQ: array<${$}, ${u*u}>;
|
|
341
341
|
var<workgroup> tileWeightK: array<${$}, ${u*u}>;
|
|
342
342
|
var<workgroup> tileWeightV: array<${$}, ${u*u}>;
|
|
343
|
-
${g.registerUniforms(P).declareVariables(x,M,k,w,v,
|
|
343
|
+
${g.registerUniforms(P).declareVariables(x,M,k,w,v,b)}
|
|
344
344
|
${g.mainStart([u,u,1])}
|
|
345
345
|
let batchIndex = workgroup_id.z / uniforms.num_heads;
|
|
346
346
|
let headNumber = workgroup_id.z % uniforms.num_heads;
|
|
@@ -389,24 +389,24 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
389
389
|
output_k[outputIdx] = valueK;
|
|
390
390
|
output_v[outputIdx] = valueV;
|
|
391
391
|
}
|
|
392
|
-
}`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:p}),getShaderSource:m},{inputs:h,outputs:[-1,-1,-1]})},dl=(e,t)=>{let n=il(e.inputs,t),[i,o,l]=ul(e,n);return Gn(e,i,o,l,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}}),cl,hl,pl,fl,gm=
|
|
392
|
+
}`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:p}),getShaderSource:m},{inputs:h,outputs:[-1,-1,-1]})},dl=(e,t)=>{let n=il(e.inputs,t),[i,o,l]=ul(e,n);return Gn(e,i,o,l,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}}),cl,hl,pl,fl,gm=S(()=>{yt(),Ie(),ke(),A(),we(),cl=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let n=(i,o,l)=>{let u=o.length;if(u!==i.length)throw new Error(`${l}: num dimensions != ${u}`);o.forEach((c,h)=>{if(c!==i[h])throw new Error(`${l}: dim[${h}] 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);n(e[1].dims,i,"Invalid input scale"),n(e[2].dims,i,"Invalid input B"),n(e[3].dims,i,"Invalid input mean"),n(e[4].dims,i,"Invalid input var")}else n(e[1].dims,[1],"Invalid input scale"),n(e[2].dims,[1],"Invalid input B"),n(e[3].dims,[1],"Invalid input mean"),n(e[4].dims,[1],"Invalid input var")},hl=(e,t)=>{let{epsilon:n,spatial:i,format:o}=t,l=e[0].dims,u=i?V(l[l.length-1]):1,c=o==="NHWC"&&l.length>1?u:1,h=K.size(l)/u,p=i,m=p?l.length:l,g=F("x",e[0].dataType,e[0].dims,u),w=F("scale",e[1].dataType,e[1].dims,c),v=F("bias",e[2].dataType,e[2].dims,c),b=F("inputMean",e[3].dataType,e[3].dims,c),x=F("inputVar",e[4].dataType,e[4].dims,c),M=le("y",e[0].dataType,m,u),k=()=>{let P="";if(i)P=`let cOffset = ${l.length===1?"0u":o==="NHWC"?`outputIndices[${l.length-1}] / ${u}`:"outputIndices[1]"};`;else if(o==="NCHW")P=`
|
|
393
393
|
${M.indicesSet("outputIndices","0","0")}
|
|
394
394
|
let cOffset = ${M.indicesToOffset("outputIndices")};`;else{P=`var cIndices = ${w.type.indices}(0);
|
|
395
395
|
cIndices[0] = outputIndices[${l.length-1}];`;for(let I=1;I<w.rank;I++)P+=`cIndices[${I}] = outputIndices[${I}];`;P+=`let cOffset = ${w.indicesToOffset("cIndices")};`}return P},$=P=>`
|
|
396
396
|
const epsilon = ${n};
|
|
397
|
-
${P.registerUniform("outputSize","u32").declareVariables(g,w,v,
|
|
397
|
+
${P.registerUniform("outputSize","u32").declareVariables(g,w,v,b,x,M)}
|
|
398
398
|
${P.mainStart()}
|
|
399
399
|
${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
400
400
|
var outputIndices = ${M.offsetToIndices(`global_idx * ${u}`)};
|
|
401
401
|
${k()}
|
|
402
402
|
let scale = ${w.getByOffset("cOffset")};
|
|
403
403
|
let bias = ${v.getByOffset("cOffset")};
|
|
404
|
-
let inputMean = ${
|
|
404
|
+
let inputMean = ${b.getByOffset("cOffset")};
|
|
405
405
|
let inputVar = ${x.getByOffset("cOffset")};
|
|
406
406
|
let x = ${g.getByOffset("global_idx")};
|
|
407
407
|
let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;
|
|
408
408
|
${M.setByOffset("global_idx","value")}
|
|
409
|
-
}`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${i}_${u}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:$,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p?[{type:12,data:h},...L(l)]:[{type:12,data:h}]})}},pl=e=>E(e),fl=(e,t)=>{let{inputs:n,outputCount:i}=e,o=pl({...t,outputCount:i});if(
|
|
409
|
+
}`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${i}_${u}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:$,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p?[{type:12,data:h},...L(l)]:[{type:12,data:h}]})}},pl=e=>E(e),fl=(e,t)=>{let{inputs:n,outputCount:i}=e,o=pl({...t,outputCount:i});if(me.webgpu.validateInputContent&&cl(n,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(hl(n,o))}}),ml,gl,yl,ym=S(()=>{ke(),we(),ml=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")},gl=e=>{let t=e[0].dims,n=e[0].dims[2],i=K.size(t)/4,o=e[0].dataType,l=F("input",o,t,4),u=F("bias",o,[n],4),c=F("residual",o,t,4),h=le("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:p=>`
|
|
410
410
|
const channels = ${n}u / 4;
|
|
411
411
|
${p.declareVariables(l,u,c,h)}
|
|
412
412
|
|
|
@@ -415,7 +415,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
415
415
|
let value = ${l.getByOffset("global_idx")}
|
|
416
416
|
+ ${u.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")};
|
|
417
417
|
${h.setByOffset("global_idx","value")}
|
|
418
|
-
}`}},yl=e=>{ml(e.inputs),e.compute(gl(e.inputs))}}),wl,et,vl,_l,bl,Sl,Tl,El,$l,xl,Cl,kl,Rl,Al,Il,Ml,qn,Pl,
|
|
418
|
+
}`}},yl=e=>{ml(e.inputs),e.compute(gl(e.inputs))}}),wl,et,vl,_l,bl,Sl,Tl,El,$l,xl,Cl,kl,Rl,Al,Il,Ml,qn,Pl,Si,Ol,Dl,zl,Ll,Bl,Nl,Ul,Fl,Vl,Gl,ql,Wl,Hl,jl,Kl,Ql,ea,Xl,ta,ra,Yl,Jl,Zl,eu,tu,ru,sa=S(()=>{Ie(),ke(),A(),we(),wl=(e,t,n,i,o,l,u)=>{let c=Math.ceil(t/4),h="";typeof o=="string"?h=`${o}(a)`:h=o("a");let p=F("inputData",n,[c],4),m=le("outputData",i,[c],4),g=[{name:"vec_size",type:"u32"}];return u&&g.push(...u),`
|
|
419
419
|
${e.registerUniforms(g).declareVariables(p,m)}
|
|
420
420
|
|
|
421
421
|
${l??""}
|
|
@@ -425,7 +425,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
425
425
|
|
|
426
426
|
let a = ${p.getByOffset("global_idx")};
|
|
427
427
|
${m.setByOffset("global_idx",h)}
|
|
428
|
-
}`},et=(e,t,n,i,o,l=e.dataType,u,c)=>{let h=[{type:12,data:Math.ceil(
|
|
428
|
+
}`},et=(e,t,n,i,o,l=e.dataType,u,c)=>{let h=[{type:12,data:Math.ceil(K.size(e.dims)/4)}];return u&&h.push(...u),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:p=>wl(p,K.size(e.dims),e.dataType,l,n,i,c),getRunData:p=>({outputs:[{dims:e.dims,dataType:l}],dispatchGroup:{x:Math.ceil(K.size(p[0].dims)/64/4)},programUniforms:h})}},vl=e=>{e.compute(et(e.inputs[0],"Abs","abs"))},_l=e=>{e.compute(et(e.inputs[0],"Acos","acos"))},bl=e=>{e.compute(et(e.inputs[0],"Acosh","acosh"))},Sl=e=>{e.compute(et(e.inputs[0],"Asin","asin"))},Tl=e=>{e.compute(et(e.inputs[0],"Asinh","asinh"))},El=e=>{e.compute(et(e.inputs[0],"Atan","atan"))},$l=e=>{e.compute(et(e.inputs[0],"Atanh","atanh"))},xl=e=>E(e),Cl=(e,t)=>{let n;switch(t.to){case 10:n="vec4<f16>";break;case 1:n="vec4<f32>";break;case 12:n="vec4<u32>";break;case 6:n="vec4<i32>";break;case 9:n="vec4<bool>";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(et(e.inputs[0],"Cast",n,void 0,t.cacheKey,t.to))},kl=e=>{let t,n,i=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=i?e[1].getFloat32Array()[0]:-34028234663852886e22,n=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=i?e[1].getUint16Array()[0]:64511,n=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return E({min:t,max:n})},Rl=(e,t)=>{let n=t||kl(e.inputs),i=U(e.inputs[0].dataType);e.compute(et(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${i}>(uniforms.min), vec4<${i}>(uniforms.max))`,void 0,n.cacheKey,void 0,[{type:e.inputs[0].dataType,data:n.min},{type:e.inputs[0].dataType,data:n.max}],[{name:"min",type:i},{name:"max",type:i}]),{inputs:[0]})},Al=e=>{e.compute(et(e.inputs[0],"Ceil","ceil"))},Il=e=>{e.compute(et(e.inputs[0],"Cos","cos"))},Ml=e=>{e.compute(et(e.inputs[0],"Cosh","cosh"))},qn=e=>E(e),Pl=(e,t)=>{let n=U(e.inputs[0].dataType);e.compute(et(e.inputs[0],"Elu",i=>`elu_vf32(${i})`,`
|
|
429
429
|
const elu_alpha_ = ${n}(${t.alpha});
|
|
430
430
|
|
|
431
431
|
fn elu_f32(a: ${n}) -> ${n} {
|
|
@@ -434,7 +434,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
434
434
|
|
|
435
435
|
fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> {
|
|
436
436
|
return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));
|
|
437
|
-
}`,t.cacheKey))},
|
|
437
|
+
}`,t.cacheKey))},Si=(e="f32")=>`
|
|
438
438
|
const r0: ${e} = 0.3275911;
|
|
439
439
|
const r1: ${e} = 0.254829592;
|
|
440
440
|
const r2: ${e} = -0.284496736;
|
|
@@ -446,7 +446,7 @@ fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {
|
|
|
446
446
|
let absv = abs(v);
|
|
447
447
|
let x = 1.0 / (1.0 + r0 * absv);
|
|
448
448
|
return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));
|
|
449
|
-
}`,Ol=e=>{let t=
|
|
449
|
+
}`,Ol=e=>{let t=U(e.inputs[0].dataType);e.compute(et(e.inputs[0],"Erf",n=>`erf_vf32(${n})`,Si(t)))},Dl=e=>{e.compute(et(e.inputs[0],"Exp","exp"))},zl=e=>{e.compute(et(e.inputs[0],"Floor","floor"))},Ll=e=>{let t=U(e.inputs[0].dataType);e.compute(et(e.inputs[0],"Gelu",n=>`0.5 * ${n} * (1.0 + erf_vf32(${n} * 0.7071067811865475))`,Si(t)))},Bl=(e,t)=>{let n=U(e.inputs[0].dataType);e.compute(et(e.inputs[0],"LeakyRelu",i=>`select(leaky_relu_alpha_ * ${i}, ${i}, ${i} >= vec4<${n}>(0.0))`,`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},Nl=e=>{e.compute(et(e.inputs[0],"Not",t=>`!${t}`))},Ul=e=>{e.compute(et(e.inputs[0],"Neg",t=>`-${t}`))},Fl=e=>{e.compute(et(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Vl=e=>{let t=U(e.inputs[0].dataType);e.compute(et(e.inputs[0],"Relu",n=>`select(vec4<${t}>(0.0), ${n}, ${n} > vec4<${t}>(0.0))`))},Gl=e=>{e.compute(et(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},ql=e=>E(e),Wl=(e,t)=>{let n=U(e.inputs[0].dataType);e.compute(et(e.inputs[0],"HardSigmoid",i=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${i} + vec4<${n}>(${t.beta})))`,void 0,t.cacheKey))},Hl=e=>{e.compute(et(e.inputs[0],"Sin","sin"))},jl=e=>{e.compute(et(e.inputs[0],"Sinh","sinh"))},Kl=e=>{e.compute(et(e.inputs[0],"Sqrt","sqrt"))},Ql=e=>{e.compute(et(e.inputs[0],"Tan","tan"))},ea=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Xl=e=>{e.compute(et(e.inputs[0],"Tanh",ea))},ta=(e="f32")=>`
|
|
450
450
|
const fast_gelu_a: ${e} = 0.5;
|
|
451
451
|
const fast_gelu_b: ${e} = 0.7978845608028654;
|
|
452
452
|
const fast_gelu_c: ${e} = 0.035677408136300125;
|
|
@@ -454,7 +454,7 @@ const fast_gelu_c: ${e} = 0.035677408136300125;
|
|
|
454
454
|
fn tanh_v(v: vec4<${e}>) -> vec4<${e}> {
|
|
455
455
|
return ${ea("v")};
|
|
456
456
|
}
|
|
457
|
-
`,ra=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Yl=e=>{let t=
|
|
457
|
+
`,ra=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Yl=e=>{let t=U(e.inputs[0].dataType);e.compute(et(e.inputs[0],"FastGelu",ra,ta(t),void 0,e.inputs[0].dataType))},Jl=(e,t)=>{let n=U(e.inputs[0].dataType);return e.compute(et(e.inputs[0],"ThresholdedRelu",i=>`select(vec4<${n}>(0.0), ${i}, ${i} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},Zl=e=>{e.compute(et(e.inputs[0],"Log","log"))},eu=(e,t)=>`
|
|
458
458
|
const alpha = vec4<${e}>(${t});
|
|
459
459
|
const one = ${e}(1.0);
|
|
460
460
|
const zero = ${e}(0.0);
|
|
@@ -471,13 +471,13 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
471
471
|
}
|
|
472
472
|
return x * x1;
|
|
473
473
|
}
|
|
474
|
-
`,tu=e=>`quick_gelu_impl(${e})`,ru=(e,t)=>{let n=
|
|
474
|
+
`,tu=e=>`quick_gelu_impl(${e})`,ru=(e,t)=>{let n=U(e.inputs[0].dataType);e.compute(et(e.inputs[0],"QuickGelu",tu,eu(n,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),su,nu,iu,wm=S(()=>{ke(),we(),sa(),su=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")},nu=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let n=F("input",e[0].dataType,e[0].dims,4),i=F("bias",e[0].dataType,[e[0].dims[2]],4),o=le("output",e[0].dataType,t,4),l=K.size(t)/4,u=G(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)}}),getShaderSource:c=>`
|
|
475
475
|
const M_SQRT2 = sqrt(2.0);
|
|
476
476
|
const halfChannels = ${e[0].dims[2]/4/2}u;
|
|
477
477
|
|
|
478
478
|
${c.declareVariables(n,i,o)}
|
|
479
479
|
|
|
480
|
-
${
|
|
480
|
+
${Si(u)}
|
|
481
481
|
|
|
482
482
|
${c.mainStart()}
|
|
483
483
|
${c.guardAgainstOutOfBoundsWorkgroupSizes(l)}
|
|
@@ -489,20 +489,20 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
489
489
|
let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);
|
|
490
490
|
|
|
491
491
|
${o.setByOffset("global_idx","valueLeft * geluRight")}
|
|
492
|
-
}`}},iu=e=>{su(e.inputs),e.compute(nu(e.inputs))}}),au,ou,
|
|
493
|
-
let outputIndices = ${
|
|
494
|
-
let offsetA = ${x.broadcastedIndicesToOffset("outputIndices",
|
|
495
|
-
let offsetB = ${M.broadcastedIndicesToOffset("outputIndices",
|
|
496
|
-
${
|
|
497
|
-
`}else k=
|
|
498
|
-
let outputIndices${I} = ${
|
|
499
|
-
let offsetA${I} = ${x.broadcastedIndicesToOffset(`outputIndices${I}`,
|
|
500
|
-
let offsetB${I} = ${M.broadcastedIndicesToOffset(`outputIndices${I}`,
|
|
492
|
+
}`}},iu=e=>{su(e.inputs),e.compute(nu(e.inputs))}}),au,ou,vr,lu,uu,du,cu,hu,pu,fu,mu,gu,yu,vm=S(()=>{Ie(),ke(),we(),au=(e,t,n,i,o,l,u,c,h,p,m,g)=>{let w,v;typeof c=="string"?w=v=($,P)=>`${c}((${$}),(${P}))`:typeof c=="function"?w=v=c:(w=c.scalar,v=c.vector);let b=le("outputData",m,i.length,4),x=F("aData",h,t.length,4),M=F("bData",p,n.length,4),k;if(o)if(l){let $=K.size(t)===1,P=K.size(n)===1,I=t.length>0&&t[t.length-1]%4===0,B=n.length>0&&n[n.length-1]%4===0;$||P?k=b.setByOffset("global_idx",v($?`${x.type.value}(${x.getByOffset("0")}.x)`:x.getByOffset("global_idx"),P?`${M.type.value}(${M.getByOffset("0")}.x)`:M.getByOffset("global_idx"))):k=`
|
|
493
|
+
let outputIndices = ${b.offsetToIndices("global_idx * 4u")};
|
|
494
|
+
let offsetA = ${x.broadcastedIndicesToOffset("outputIndices",b)};
|
|
495
|
+
let offsetB = ${M.broadcastedIndicesToOffset("outputIndices",b)};
|
|
496
|
+
${b.setByOffset("global_idx",v(u||I?x.getByOffset("offsetA / 4u"):`${x.type.value}(${x.getByOffset("offsetA / 4u")}[offsetA % 4u])`,u||B?M.getByOffset("offsetB / 4u"):`${M.type.value}(${M.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}
|
|
497
|
+
`}else k=b.setByOffset("global_idx",v(x.getByOffset("global_idx"),M.getByOffset("global_idx")));else{if(!l)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let $=(P,I,B="")=>{let q=`aData[indexA${I}][componentA${I}]`,H=`bData[indexB${I}][componentB${I}]`;return`
|
|
498
|
+
let outputIndices${I} = ${b.offsetToIndices(`global_idx * 4u + ${I}u`)};
|
|
499
|
+
let offsetA${I} = ${x.broadcastedIndicesToOffset(`outputIndices${I}`,b)};
|
|
500
|
+
let offsetB${I} = ${M.broadcastedIndicesToOffset(`outputIndices${I}`,b)};
|
|
501
501
|
let indexA${I} = offsetA${I} / 4u;
|
|
502
502
|
let indexB${I} = offsetB${I} / 4u;
|
|
503
503
|
let componentA${I} = offsetA${I} % 4u;
|
|
504
504
|
let componentB${I} = offsetB${I} % 4u;
|
|
505
|
-
${P}[${I}] = ${B}(${w(q,
|
|
505
|
+
${P}[${I}] = ${B}(${w(q,H)});
|
|
506
506
|
`};m===9?k=`
|
|
507
507
|
var data = vec4<u32>(0);
|
|
508
508
|
${$("data",0,"u32")}
|
|
@@ -515,14 +515,14 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
515
515
|
${$("outputData[global_idx]",2)}
|
|
516
516
|
${$("outputData[global_idx]",3)}
|
|
517
517
|
`}return`
|
|
518
|
-
${e.registerUniform("vec_size","u32").declareVariables(x,M,
|
|
518
|
+
${e.registerUniform("vec_size","u32").declareVariables(x,M,b)}
|
|
519
519
|
|
|
520
520
|
${g??""}
|
|
521
521
|
|
|
522
522
|
${e.mainStart()}
|
|
523
523
|
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
524
524
|
${k}
|
|
525
|
-
}`},ou=(e,t,n,i,o,l,u=n.dataType)=>{let c=n.dims.map(Number),h=i.dims.map(Number),p=!
|
|
525
|
+
}`},ou=(e,t,n,i,o,l,u=n.dataType)=>{let c=n.dims.map(Number),h=i.dims.map(Number),p=!K.areEqual(c,h),m=c,g=K.size(c),w=!1,v=!1,b=[p];if(p){let x=kr.calcShape(c,h,!1);if(!x)throw new Error("Can't perform binary op on the given tensors");m=x.slice(),g=K.size(m);let M=K.size(c)===1,k=K.size(h)===1,$=c.length>0&&c[c.length-1]%4===0,P=h.length>0&&h[h.length-1]%4===0;b.push(M),b.push(k),b.push($),b.push(P);let I=1;for(let B=1;B<m.length;B++){let q=c[c.length-B],H=h[h.length-B];if(q===H)I*=q;else break}I%4===0?(v=!0,w=!0):(M||k||$||P)&&(w=!0)}else w=!0;return b.push(w),{name:e,shaderCache:{hint:t+b.map(x=>x.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:x=>au(x,c,h,m,w,p,v,o,n.dataType,i.dataType,u,l),getRunData:()=>({outputs:[{dims:m,dataType:u}],dispatchGroup:{x:Math.ceil(g/64/4)},programUniforms:[{type:12,data:Math.ceil(K.size(m)/4)},...L(c,h,m)]})}},vr=(e,t,n,i,o,l)=>{e.compute(ou(t,o??"",e.inputs[0],e.inputs[1],n,i,l))},lu=e=>{vr(e,"Add",(t,n)=>`${t}+${n}`)},uu=e=>{vr(e,"Div",(t,n)=>`${t}/${n}`)},du=e=>{vr(e,"Equal",{scalar:(t,n)=>`u32(${t}==${n})`,vector:(t,n)=>`vec4<u32>(${t}==${n})`},void 0,void 0,9)},cu=e=>{vr(e,"Mul",(t,n)=>`${t}*${n}`)},hu=e=>{let t=F("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;vr(e,"Pow",{scalar:(n,i)=>`pow_custom(${n},${i})`,vector:(n,i)=>`pow_vector_custom(${n},${i})`},`
|
|
526
526
|
fn pow_custom(a : ${t}, b : ${t}) -> ${t} {
|
|
527
527
|
if (b == ${t}(0.0)) {
|
|
528
528
|
return ${t}(1.0);
|
|
@@ -535,7 +535,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
535
535
|
// TODO: implement vectorized pow
|
|
536
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
537
|
}
|
|
538
|
-
`)},pu=e=>{
|
|
538
|
+
`)},pu=e=>{vr(e,"Sub",(t,n)=>`${t}-${n}`)},fu=e=>{vr(e,"Greater",{scalar:(t,n)=>`u32(${t}>${n})`,vector:(t,n)=>`vec4<u32>(${t}>${n})`},void 0,void 0,9)},mu=e=>{vr(e,"Less",{scalar:(t,n)=>`u32(${t}<${n})`,vector:(t,n)=>`vec4<u32>(${t}<${n})`},void 0,void 0,9)},gu=e=>{vr(e,"GreaterOrEqual",{scalar:(t,n)=>`u32(${t}>=${n})`,vector:(t,n)=>`vec4<u32>(${t}>=${n})`},void 0,void 0,9)},yu=e=>{vr(e,"LessOrEqual",{scalar:(t,n)=>`u32(${t}<=${n})`,vector:(t,n)=>`vec4<u32>(${t}<=${n})`},void 0,void 0,9)}}),wu,vu,_u,bu,Su,Tu,_m=S(()=>{Ie(),ke(),A(),we(),wu=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let n=0,i=e[n],o=i.dataType,l=i.dims.length;e.forEach((u,c)=>{if(c!==n){if(u.dataType!==o)throw new Error("input tensors should be one type");if(u.dims.length!==l)throw new Error("input tensors should have the same shape");u.dims.forEach((h,p)=>{if(p!==t&&h!==i.dims[p])throw new Error("non concat dimensions must match")})}})},vu=(e,t)=>`
|
|
539
539
|
fn calculateInputIndex(index: u32) -> u32 {
|
|
540
540
|
let sizeInConcatAxis = array<u32, ${e}u>(${t});
|
|
541
541
|
for (var i: u32 = 0u; i < ${e}; i += 1u ) {
|
|
@@ -545,7 +545,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
545
545
|
}
|
|
546
546
|
return ${e}u;
|
|
547
547
|
}`,_u=(e,t)=>{let n=e.length,i=[];for(let o=0;o<n;++o){let l=t.setByOffset("global_idx",e[o].getByIndices("indices"));n===1?i.push(l):o===0?i.push(`if (inputIndex == ${o}u) { ${l} }`):o===n-1?i.push(`else { ${l} }`):i.push(`else if (inputIndex == ${o}) { ${l} }`)}return i.join(`
|
|
548
|
-
`)},bu=(e,t,n,i)=>{let o=
|
|
548
|
+
`)},bu=(e,t,n,i)=>{let o=K.size(n),l=new Array(e.length),u=new Array(e.length),c=0,h=[],p=[],m=[{type:12,data:o}];for(let x=0;x<e.length;++x)c+=e[x].dims[t],l[x]=c,p.push(e[x].dims.length),u[x]=F(`input${x}`,i,p[x]),h.push("rank"),m.push({type:12,data:l[x]});for(let x=0;x<e.length;++x)m.push(...L(e[x].dims));m.push(...L(n));let g=le("output",i,n.length),w=g.indicesGet("indices",t),v=Array.from(Array(l.length).keys()).map(x=>`uniforms.sizeInConcatAxis${x}`).join(","),b=x=>`
|
|
549
549
|
|
|
550
550
|
${(()=>{x.registerUniform("outputSize","u32");for(let M=0;M<e.length;M++)x.registerUniform(`sizeInConcatAxis${M}`,"u32");return x.declareVariables(...u,g)})()}
|
|
551
551
|
|
|
@@ -563,11 +563,11 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
563
563
|
}
|
|
564
564
|
|
|
565
565
|
${_u(u,g)}
|
|
566
|
-
}`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:
|
|
566
|
+
}`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:b}},Su=(e,t)=>{let n=e.inputs,i=n[0].dims,o=K.normalizeAxis(t.axis,i.length);wu(n,o);let l=i.slice();l[o]=n.reduce((c,h)=>c+(h.dims.length>o?h.dims[o]:0),0);let u=n.filter(c=>K.size(c.dims)>0);e.compute(bu(u,o,l,n[0].dataType),{inputs:u})},Tu=e=>E({axis:e.axis})}),As,Is,Ms,na,Ps=S(()=>{Ie(),ke(),As=(e,t,n="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}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value));
|
|
567
567
|
value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
|
|
568
|
-
`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},
|
|
568
|
+
`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Is=(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})},Ms=(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"})},na=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[n,i]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:i}}else if(t==="Clip"){let[n,i]=e?.activation_params||[Mn,hr];return{activation:t,clipMax:i,clipMin:n}}else if(t==="LeakyRelu"){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}}),Pt,Eu,ia=S(()=>{Pt=(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.`)}},Eu=e=>`
|
|
569
569
|
${e?"value = value + getBiasByOutputCoords(coords);":""}
|
|
570
|
-
`}),$u,bm=
|
|
570
|
+
`}),$u,bm=S(()=>{$u=e=>`
|
|
571
571
|
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
|
|
572
572
|
return dot(coords, vec4<i32>(
|
|
573
573
|
shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
|
|
@@ -576,17 +576,17 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
|
|
|
576
576
|
return dot(coords, vec4<i32>(
|
|
577
577
|
i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));
|
|
578
578
|
}
|
|
579
|
-
`}),Wn,aa,oa=
|
|
579
|
+
`}),Wn,aa,oa=S(()=>{Ie(),ke(),we(),Ps(),Wn=(e,t,n,i,o)=>{let l=i-n;return`
|
|
580
580
|
${Array.from({length:n}).map((u,c)=>`
|
|
581
581
|
if (${Q(t.shape,c,t.rank)} != 1) {
|
|
582
582
|
${t.indicesSet(e,c,Q(o,c+l,i))}
|
|
583
583
|
} else {
|
|
584
584
|
${t.indicesSet(e,c,0)}
|
|
585
585
|
}`).join("")}
|
|
586
|
-
`},aa=(e,t,n,i,o=!1,l)=>{let u=e[0].dims,c=e[1].dims,h=u[u.length-2],p=c[c.length-1],m=u[u.length-1],g=V(p),w=V(m),v=V(h),
|
|
587
|
-
let b_data${
|
|
588
|
-
values[${
|
|
589
|
-
`}return
|
|
586
|
+
`},aa=(e,t,n,i,o=!1,l)=>{let u=e[0].dims,c=e[1].dims,h=u[u.length-2],p=c[c.length-1],m=u[u.length-1],g=V(p),w=V(m),v=V(h),b=K.size(n)/g/v,x=e.length>2,M=i?i.slice(0,-2):n.slice(0,-2),k=[K.size(M),h,p],$=[{type:12,data:b},{type:12,data:h},{type:12,data:p},{type:12,data:m}];Is(t,$),$.push(...L(M,u,c)),x&&$.push(...L(e[2].dims)),$.push(...L(k));let P=I=>{let B=Be("batch_dims",e[0].dataType,M.length),q=F("a",e[0].dataType,u.length,w),H=F("b",e[1].dataType,c.length,g),ee=le("output",e[0].dataType,k.length,g),ue=G(ee.type.tensor),_e=As(t,ee.type.value,ue),Fe=[q,H],Re="";if(x){let ye=o?g:1;Fe.push(F("bias",e[2].dataType,e[2].dims.length,ye)),Re=`${o?`value += bias[col / ${ye}];`:`value += ${ee.type.value}(bias[row + i]);`}`}let Me=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ms(t,Me);let Qe=()=>{let ye=`var a_data: ${q.type.value};`;for(let xe=0;xe<w;xe++)ye+=`
|
|
587
|
+
let b_data${xe} = b[(b_offset + (k + ${xe}) * uniforms.N + col) / ${g}];`;for(let xe=0;xe<v;xe++){ye+=`a_data = a[(a_offset + (row + ${xe}) * uniforms.K + k) / ${w}];`;for(let Le=0;Le<w;Le++)ye+=`
|
|
588
|
+
values[${xe}] = fma(${H.type.value}(a_data${w===1?"":`[${Le}]`}), b_data${Le}, values[${xe}]);
|
|
589
|
+
`}return ye};return`
|
|
590
590
|
${I.registerUniforms(Me).registerInternalVariables(B).declareVariables(...Fe,ee)}
|
|
591
591
|
${I.mainStart()}
|
|
592
592
|
${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -604,14 +604,14 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
|
|
|
604
604
|
${q.indicesSet("a_indices",q.rank-1,0)}
|
|
605
605
|
let a_offset = ${q.indicesToOffset("a_indices")};
|
|
606
606
|
|
|
607
|
-
var b_indices: ${
|
|
608
|
-
${Wn("b_indices",
|
|
609
|
-
${
|
|
610
|
-
${
|
|
611
|
-
let b_offset = ${
|
|
607
|
+
var b_indices: ${H.type.indices};
|
|
608
|
+
${Wn("b_indices",H,H.rank-2,B.rank,"batch_indices")}
|
|
609
|
+
${H.indicesSet("b_indices",H.rank-2,0)}
|
|
610
|
+
${H.indicesSet("b_indices",H.rank-1,0)}
|
|
611
|
+
let b_offset = ${H.indicesToOffset("b_indices")};
|
|
612
612
|
var values: array<${ee.type.value}, ${v}>;
|
|
613
613
|
for (var k: u32 = 0u; k < uniforms.K; k = k + ${w}) {
|
|
614
|
-
${
|
|
614
|
+
${Qe()}
|
|
615
615
|
}
|
|
616
616
|
for (var i = 0u; i < ${v}u; i++) {
|
|
617
617
|
var value = values[i];
|
|
@@ -622,7 +622,7 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
|
|
|
622
622
|
${ee.setByOffset(`offset / ${g}`,"value")};
|
|
623
623
|
}
|
|
624
624
|
}
|
|
625
|
-
`};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${g};${w};${v};${o}`,inputDependencies:x?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(
|
|
625
|
+
`};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${g};${w};${v};${o}`,inputDependencies:x?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:$}),getShaderSource:P}}}),xu,Cu,la,ua,ku,da,Ru,Ti,ca=S(()=>{Ie(),ke(),we(),Ps(),oa(),ia(),xu=(e,t)=>e?`
|
|
626
626
|
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
627
627
|
kStart + inputRow,
|
|
628
628
|
globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});
|
|
@@ -720,7 +720,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
720
720
|
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
721
721
|
globalRowStart + inputRow,
|
|
722
722
|
kStart + inputCol${t?", batchIndices":""});
|
|
723
|
-
`,ku=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",da=(e,t,n="f32",i,o=!1,l=32,u=!1,c=32,h=!1)=>{let p=e[1]*t[1],m=e[0]*t[0],g=o?p:l,w=o?l:p;if(!(w%t[1]===0&&g%t[0]===0&&l%t[1]===0))throw new Error(`tileAHight ${w} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}, tileInner ${l} must be divisible by workgroupSize[1]${t[1]}`);let v=w/t[1],
|
|
723
|
+
`,ku=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",da=(e,t,n="f32",i,o=!1,l=32,u=!1,c=32,h=!1)=>{let p=e[1]*t[1],m=e[0]*t[0],g=o?p:l,w=o?l:p;if(!(w%t[1]===0&&g%t[0]===0&&l%t[1]===0))throw new Error(`tileAHight ${w} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}, tileInner ${l} must be divisible by workgroupSize[1]${t[1]}`);let v=w/t[1],b=g/t[0],x=l/t[1],M=h?`
|
|
724
724
|
let localRow = i32(localId.y);
|
|
725
725
|
let localCol = i32(localId.x);
|
|
726
726
|
let globalRowStart = i32(workgroupId.y) * ${p};
|
|
@@ -777,13 +777,13 @@ let globalCol = i32(globalId.x) * colPerThread;
|
|
|
777
777
|
let globalRowStart = i32(workgroupId.y) * ${p};
|
|
778
778
|
|
|
779
779
|
let tileRowA = i32(localId.y) * ${v};
|
|
780
|
-
let tileColA = i32(localId.x) * ${
|
|
780
|
+
let tileColA = i32(localId.x) * ${b};
|
|
781
781
|
let tileRowB = i32(localId.y) * ${x};
|
|
782
782
|
// Loop over shared dimension.
|
|
783
783
|
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
784
784
|
// Load one tile of A into local memory.
|
|
785
785
|
for (var innerRow = 0; innerRow < ${v}; innerRow = innerRow + 1) {
|
|
786
|
-
for (var innerCol = 0; innerCol < ${
|
|
786
|
+
for (var innerCol = 0; innerCol < ${b}; innerCol = innerCol + 1) {
|
|
787
787
|
let inputRow = tileRowA + innerRow;
|
|
788
788
|
let inputCol = tileColA + innerCol;
|
|
789
789
|
${ua(o,i)}
|
|
@@ -885,11 +885,11 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
885
885
|
${h.setByIndices("vec3<u32>(coords)","value")}
|
|
886
886
|
}
|
|
887
887
|
}
|
|
888
|
-
`},
|
|
889
|
-
${Me.registerUniforms(
|
|
890
|
-
${
|
|
891
|
-
${x?la(M,k
|
|
892
|
-
`};return{name:"MatMul",shaderCache:{hint:`${M};${t.activation};${x};${o}`,inputDependencies:_e},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:$[0],y:$[1],z:$[2]},programUniforms:ue}),getShaderSource:Re}}}),Au,Iu,Sm=
|
|
888
|
+
`},Ti=(e,t,n,i,o=!1,l)=>{let u=e[0].dims,c=e[1].dims,h=u.slice(0,-2),p=c.slice(0,-2),m=i?i.slice(0,-2):n.slice(0,-2),g=K.size(m),w=u[u.length-2],v=u[u.length-1],b=c[c.length-1],x=v%4===0&&b%4===0,M=w<=8?[4,1,1]:[4,4,1],k=[8,8,1],$=[Math.ceil(b/k[0]/M[0]),Math.ceil(w/k[1]/M[1]),Math.ceil(g/k[2]/M[2])],P=x?4:1,I=[...h,w,v/P],B=I.length,q=[...p,v,b/P],H=q.length,ee=[g,w,b/P],ue=[{type:6,data:w},{type:6,data:b},{type:6,data:v}];Is(t,ue),ue.push(...L(m,I,q));let _e=["rank","rank"],Fe=e.length>2;Fe&&(ue.push(...L(e[2].dims)),_e.push("rank")),ue.push(...L(ee));let Re=Me=>{let Qe=m.length,ye=Be("batchDims",e[0].dataType,Qe,1),xe=G(e[0].dataType),Le=F("a",e[0].dataType,B,P),Ge=F("b",e[1].dataType,H,P),De=le("result",e[0].dataType,ee.length,P),je=[Le,Ge];if(Fe){let Dt=o?P:1;je.push(F("bias",e[2].dataType,e[2].dims.length,Dt))}let oe=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ms(t,oe);let Oe=G(De.type.tensor),Ae=As(t,De.type.value,Oe),$e=Ru(P,Fe,Ae,[ye,Le,Ge,De],o);return`
|
|
889
|
+
${Me.registerUniforms(oe).registerInternalVariables(ye).declareVariables(...je,De)}
|
|
890
|
+
${$e}
|
|
891
|
+
${x?la(M,k,xe,ye):da(M,k,xe,ye)}
|
|
892
|
+
`};return{name:"MatMul",shaderCache:{hint:`${M};${t.activation};${x};${o}`,inputDependencies:_e},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:$[0],y:$[1],z:$[2]},programUniforms:ue}),getShaderSource:Re}}}),Au,Iu,Sm=S(()=>{Ie(),tr(),we(),Ps(),ia(),bm(),ca(),Au=(e,t,n,i,o=!1,l,u=4,c=4,h=4,p="f32")=>{let m=ue=>{switch(ue){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${ue} is not supported.`)}},g=ue=>{switch(ue){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 ${ue} is not supported.`)}},w=e?`
|
|
893
893
|
let coord = vec4<i32>(batch, xRow, xCol, xCh);
|
|
894
894
|
`:`
|
|
895
895
|
let coord = vec4<i32>(batch, xCh, xRow, xCol);
|
|
@@ -905,7 +905,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
905
905
|
row,
|
|
906
906
|
col / outWidth,
|
|
907
907
|
col % outWidth);
|
|
908
|
-
`,
|
|
908
|
+
`,b=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",x=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",M=e?"row":"col",k=e?"col":"row",$=`
|
|
909
909
|
let inChannels = i32(uniforms.w_shape[2]);
|
|
910
910
|
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
|
|
911
911
|
let outRow = ${M} / outWidth;
|
|
@@ -919,7 +919,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
919
919
|
var resData = ${Pt(u,p)}(0.0);
|
|
920
920
|
// The bounds checking is always needed since we use it to pad zero for
|
|
921
921
|
// the 'same' padding type.
|
|
922
|
-
if (xRow >= 0 && xRow < ${
|
|
922
|
+
if (xRow >= 0 && xRow < ${b} && xCol >= 0 && xCol < ${x}) {
|
|
923
923
|
${w}
|
|
924
924
|
let xIndex = getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape));
|
|
925
925
|
${m(u)}
|
|
@@ -948,12 +948,12 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
948
948
|
if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {
|
|
949
949
|
${g(c)}
|
|
950
950
|
}
|
|
951
|
-
return ${Pt(c,p)}(0.0);`,B=Pt(h,p),q=Pt(e?u:c,p),
|
|
951
|
+
return ${Pt(c,p)}(0.0);`,B=Pt(h,p),q=Pt(e?u:c,p),H=Pt(e?c:u,p),ee=As(l,B,p);return`
|
|
952
952
|
fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${q} {
|
|
953
953
|
${e?P:I}
|
|
954
954
|
}
|
|
955
955
|
|
|
956
|
-
fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${
|
|
956
|
+
fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${H} {
|
|
957
957
|
${e?I:P}
|
|
958
958
|
}
|
|
959
959
|
|
|
@@ -968,14 +968,14 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
968
968
|
${ee}
|
|
969
969
|
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
|
|
970
970
|
}
|
|
971
|
-
}`},Iu=(e,t,n,i,o,l,u,c,h)=>{let p=t.format==="NHWC",m=p?e[0].dims[3]:e[0].dims[1],g=n[0],w=p?n[2]:n[3],v=p?n[1]:n[2],
|
|
971
|
+
}`},Iu=(e,t,n,i,o,l,u,c,h)=>{let p=t.format==="NHWC",m=p?e[0].dims[3]:e[0].dims[1],g=n[0],w=p?n[2]:n[3],v=p?n[1]:n[2],b=p?n[3]:n[1],x=p&&(m%4===0||m%3===0)&&b%4===0,M=p?b:w*v,k=p?w*v:b,$=[8,8,1],P=i<=8?[4,1,1]:[4,4,1],I=[Math.ceil(M/$[0]/P[0]),Math.ceil(k/$[1]/P[1]),Math.ceil(g/$[2]/P[2])];He("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${I}`);let B=x?p&&m%4!==0?3:4:1,q=$[1]*P[1],H=$[0]*P[0],ee=Math.max($[0]*B,$[1]),ue=i%q===0,_e=o%H===0,Fe=l%ee===0,Re=x?[B,4,4]:[1,1,1],Me=[{type:6,data:i},{type:6,data:o},{type:6,data:l},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Is(t,Me),Me.push(...L(e[0].dims,e[1].dims));let Qe=["rank","rank"];u&&(Me.push(...L(e[2].dims)),Qe.push("rank")),Me.push(...L(n));let ye=xe=>{let Le=[{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}];Ms(t,Le);let Ge=x?4:1,De=G(e[0].dataType),je=`
|
|
972
972
|
fn setOutputAtIndex(flatIndex : i32, value : ${x?`vec4<${De}>`:De}) {
|
|
973
973
|
result[flatIndex] = ${x?`vec4<${De}>`:De}(value);
|
|
974
974
|
}
|
|
975
975
|
fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${x?`vec4<${De}>`:De}) {
|
|
976
976
|
let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));
|
|
977
977
|
setOutputAtIndex(flatIndex ${x?"/ 4":""}, value);
|
|
978
|
-
}`,
|
|
978
|
+
}`,oe=F("x",e[0].dataType,e[0].dims.length,B===3?1:B),Oe=F("w",e[1].dataType,e[1].dims.length,Ge),Ae=[oe,Oe],$e=le("result",e[0].dataType,n.length,Ge);if(u){let Dt=F("bias",e[2].dataType,e[2].dims.length,Ge);Ae.push(Dt),je+=`
|
|
979
979
|
fn getBiasByOutputCoords(coords : vec4<i32>) -> ${x?`vec4<${De}>`:De} {
|
|
980
980
|
return bias[coords.${p?"w":"y"}${x?"/ 4":""}];
|
|
981
981
|
}`}return`
|
|
@@ -983,13 +983,13 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
983
983
|
//struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>,
|
|
984
984
|
// outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>,
|
|
985
985
|
// dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };
|
|
986
|
-
${
|
|
987
|
-
${
|
|
986
|
+
${xe.registerUniforms(Le).declareVariables(...Ae,$e)}
|
|
987
|
+
${je}
|
|
988
988
|
${Au(p,ue,_e,Fe,u,t,Re[0],Re[1],Re[2],De)}
|
|
989
|
-
${x?la(P,$,De,void 0,!p,ee):da(P,$,De,void 0,!p,ee,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${B};${x};${ue};${_e};${Fe};${q};${
|
|
989
|
+
${x?la(P,$,De,void 0,!p,ee):da(P,$,De,void 0,!p,ee,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${B};${x};${ue};${_e};${Fe};${q};${H};${ee}`,inputDependencies:Qe},getRunData:()=>({outputs:[{dims:h?h(n):n,dataType:e[0].dataType}],dispatchGroup:{x:I[0],y:I[1],z:I[2]},programUniforms:Me}),getShaderSource:ye}}}),Mu,ha,Hn,Pu,pa,Ou,Du,zu,Tm=S(()=>{Ie(),tr(),ke(),we(),Ps(),ia(),Mu=e=>{let t=1;for(let n=0;n<e.length;n++)t*=e[n];return t},ha=e=>typeof e=="number"?[e,e,e]:e,Hn=(e,t)=>t<=1?e:e+(e-1)*(t-1),Pu=(e,t,n,i=1)=>{let o=Hn(t,i);return Math.floor((e[0]*(n-1)-n+o)/2)},pa=(e,t,n,i,o)=>{o==null&&(o=Pu(e,t[0],i[0]));let l=[0,0,0,n];for(let u=0;u<3;u++)e[u]+2*o>=t[u]&&(l[u]=Math.trunc((e[u]-t[u]+2*o)/i[u]+1));return l},Ou=(e,t,n,i,o,l,u,c,h,p)=>{let m,g,w,v;if(e==="VALID"&&(e=0),typeof e=="number"){m={top:e,bottom:e,left:e,right:e,front:e,back:e};let b=pa([t,n,i,1],[c,h,p],1,[o,l,u],e);g=b[0],w=b[1],v=b[2]}else if(Array.isArray(e)){if(!e.every((x,M,k)=>x===k[0]))throw Error(`Unsupported padding parameter: ${e}`);m={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let b=pa([t,n,i,1],[c,h,p],1,[o,l,u],e[0]);g=b[0],w=b[1],v=b[2]}else if(e==="SAME_UPPER"){g=Math.ceil(t/o),w=Math.ceil(n/l),v=Math.ceil(i/u);let b=(g-1)*o+c-t,x=(w-1)*l+h-n,M=(v-1)*u+p-i,k=Math.floor(b/2),$=b-k,P=Math.floor(x/2),I=x-P,B=Math.floor(M/2),q=M-B;m={top:P,bottom:I,left:B,right:q,front:k,back:$}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:m,outDepth:g,outHeight:w,outWidth:v}},Du=(e,t,n,i,o,l=!1,u="channelsLast")=>{let c,h,p,m,g;if(u==="channelsLast")[c,h,p,m,g]=e;else if(u==="channelsFirst")[c,g,h,p,m]=e;else throw new Error(`Unknown dataFormat ${u}`);let[w,,v,b,x]=t,[M,k,$]=ha(n),[P,I,B]=ha(i),q=Hn(v,P),H=Hn(b,I),ee=Hn(x,B),{padInfo:ue,outDepth:_e,outHeight:Fe,outWidth:Re}=Ou(o,h,p,m,M,k,$,q,H,ee),Me=l?w*g:w,Qe=[0,0,0,0,0];return u==="channelsFirst"?Qe=[c,Me,_e,Fe,Re]:u==="channelsLast"&&(Qe=[c,_e,Fe,Re,Me]),{batchSize:c,dataFormat:u,inDepth:h,inHeight:p,inWidth:m,inChannels:g,outDepth:_e,outHeight:Fe,outWidth:Re,outChannels:Me,padInfo:ue,strideDepth:M,strideHeight:k,strideWidth:$,filterDepth:v,filterHeight:b,filterWidth:x,effectiveFilterDepth:q,effectiveFilterHeight:H,effectiveFilterWidth:ee,dilationDepth:P,dilationHeight:I,dilationWidth:B,inShape:e,outShape:Qe,filterShape:t}},zu=(e,t,n,i,o,l)=>{let u=l==="channelsLast";u?e[0].dims[3]:e[0].dims[1];let c=[64,1,1],h={x:n.map((M,k)=>k)},p=[Math.ceil(Mu(h.x.map(M=>n[M]))/c[0]),1,1];He("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${p}`);let m=1,g=K.size(n),w=[{type:12,data:g},{type:12,data:i},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];Is(t,w),w.push(...L(e[0].dims,e[1].dims));let v=["rank","rank"],b=e.length===3;b&&(w.push(...L(e[2].dims)),v.push("rank")),w.push(...L(n));let x=M=>{let k=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:i.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Ms(t,k);let $=1,P=G(e[0].dataType),I=F("x",e[0].dataType,e[0].dims.length,m),B=F("W",e[1].dataType,e[1].dims.length,$),q=[I,B],H=le("result",e[0].dataType,n.length,$),ee="";if(b){let Fe=F("bias",e[2].dataType,e[2].dims.length,$);q.push(Fe),ee+=`
|
|
990
990
|
fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${P} {
|
|
991
991
|
return bias[${u?Q("coords",4,5):Q("coords",1,5)}];
|
|
992
|
-
}`}let ue=Pt(m,P),_e=
|
|
992
|
+
}`}let ue=Pt(m,P),_e=As(t,ue,P);return`
|
|
993
993
|
${ee}
|
|
994
994
|
fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
|
|
995
995
|
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
|
|
@@ -999,10 +999,10 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
999
999
|
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
|
|
1000
1000
|
return ${B.getByIndices("aIndices")};
|
|
1001
1001
|
}
|
|
1002
|
-
${M.registerUniforms(k).declareVariables(...q,
|
|
1002
|
+
${M.registerUniforms(k).declareVariables(...q,H)}
|
|
1003
1003
|
${M.mainStart()}
|
|
1004
1004
|
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1005
|
-
let coords = ${
|
|
1005
|
+
let coords = ${H.offsetToIndices("global_idx")};
|
|
1006
1006
|
let batch = ${Q("coords",0,I.rank)};
|
|
1007
1007
|
let d2 = ${u?Q("coords",I.rank-1,I.rank):Q("coords",1,I.rank)};
|
|
1008
1008
|
let xFRCCorner = vec3<u32>(${u?Q("coords",1,I.rank):Q("coords",2,I.rank)},
|
|
@@ -1091,10 +1091,10 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1091
1091
|
}
|
|
1092
1092
|
}
|
|
1093
1093
|
}
|
|
1094
|
-
${
|
|
1094
|
+
${b?"value = value + getBiasByOutputCoords(coords)":""};
|
|
1095
1095
|
${_e}
|
|
1096
1096
|
result[global_idx] = f32(value);
|
|
1097
|
-
}`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${u};${m};${
|
|
1097
|
+
}`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${u};${m};${b}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:p[0],y:p[1],z:p[2]},programUniforms:w}),getShaderSource:x}}}),Lu,Bu,Em=S(()=>{Ie(),ke(),we(),Ps(),Lu=(e,t,n,i)=>{let o=e.length>2,l=o?"value += b[output_channel];":"",u=e[0].dims,c=e[1].dims,h=t.format==="NHWC",p=h?n[3]:n[1],m=p/t.group,g=h&&m>=4?V(p):1,w=K.size(n)/g,v=[{type:12,data:w},{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:m}];Is(t,v),v.push(...L(u,[c[0],c[1],c[2],c[3]/g]));let b=o?["rank","rank","rank"]:["rank","rank"];v.push(...L([n[0],n[1],n[2],n[3]/g]));let x=M=>{let k=le("output",e[0].dataType,n.length,g),$=G(k.type.tensor),P=As(t,k.type.value,$),I=F("x",e[0].dataType,u.length),B=F("w",e[1].dataType,c.length,g),q=[I,B];o&&q.push(F("b",e[2].dataType,e[2].dims,g));let H=[{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"}];Ms(t,H);let ee=h?`
|
|
1098
1098
|
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {
|
|
1099
1099
|
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
|
|
1100
1100
|
|
|
@@ -1139,7 +1139,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1139
1139
|
}
|
|
1140
1140
|
}
|
|
1141
1141
|
`;return`
|
|
1142
|
-
${M.registerUniforms(
|
|
1142
|
+
${M.registerUniforms(H).declareVariables(...q,k)}
|
|
1143
1143
|
|
|
1144
1144
|
${M.mainStart()}
|
|
1145
1145
|
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1156,10 +1156,10 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1156
1156
|
${l}
|
|
1157
1157
|
${P}
|
|
1158
1158
|
${k.setByOffset("global_idx","value")}
|
|
1159
|
-
}`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${g}`,inputDependencies:
|
|
1160
|
-
${
|
|
1161
|
-
${
|
|
1162
|
-
${
|
|
1159
|
+
}`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${g}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:v}),getShaderSource:x}},Bu=(e,t,n,i)=>{let o=e.length>2,l=V(n[3]),u=V(n[2]),c=K.size(n)/l/u,h=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/l],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/l],m=[n[0],n[1],n[2],n[3]/l],g=[{type:12,data:c},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Is(t,g),g.push(...L(h,p,m));let w=(u-1)*t.strides[1]+p[1],v=b=>{let x=le("output",e[0].dataType,m.length,l),M=G(x.type.tensor),k=As(t,x.type.value,M),$=F("x",e[0].dataType,h.length,l),P=F("w",e[1].dataType,p.length,l),I=[$,P];o&&I.push(F("b",e[2].dataType,e[2].dims,l));let B=o?"value += b[output_channel];":"",q=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ms(t,q),`
|
|
1160
|
+
${b.registerUniforms(q).declareVariables(...I,x)}
|
|
1161
|
+
${b.mainStart()}
|
|
1162
|
+
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1163
1163
|
let width0 = uniforms.output_shape[3];
|
|
1164
1164
|
let output_channel = global_idx % width0;
|
|
1165
1165
|
var index1 = global_idx / width0;
|
|
@@ -1201,34 +1201,34 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1201
1201
|
${k}
|
|
1202
1202
|
${x.set("batch","row","col + i","output_channel","value")};
|
|
1203
1203
|
}
|
|
1204
|
-
}`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${l};${u};${w};${p[0]};${p[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:v}}}),Nu,
|
|
1204
|
+
}`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${l};${u};${w};${p[0]};${p[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:v}}}),Nu,Ei,Uu,$i,fa,ma,Fu,Vu,ga,$m=S(()=>{ke(),Sm(),Tm(),ca(),Em(),Ps(),oa(),Ue(),Nu=(e,t,n,i,o,l)=>{let u=e[0],c=e.slice(l?1:2,l?3:4),h=c.length,p=t[0],m=t.slice(2).map((w,v)=>w+(w-1)*(n[v]-1)),g=c.map((w,v)=>w+i[v]+i[v+h]).map((w,v)=>Math.floor((w-m[v]+o[v])/o[v]));return g.splice(0,0,u),g.splice(l?3:1,0,p),g},Ei=[2,3,1,0],Uu=(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 n=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[1]*t.group;if(n!==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 o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},$i=(e,t)=>{let n=e.kernelShape.slice();n.length<t[1].dims.length-2&&n.push(...Array(t[1].dims.length-2-n.length).fill(0));for(let l=2;l<t[1].dims.length;++l)n[l-2]===0&&(n[l-2]=t[1].dims[l]);let i=e.pads.slice();rs.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,n,i,e.format==="NHWC",e.autoPad);let o=Object.assign({},e);return Object.assign(o,{kernelShape:n,pads:i}),o},fa=e=>{let t=na(e),n=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,l=e.group,u=e.kernel_shape,c=e.pads,h=e.strides,p=e.w_is_const();return{autoPad:i,format:n,dilations:o,group:l,kernelShape:u,pads:c,strides:h,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},ma=(e,t,n,i)=>{let o=n.format==="NHWC",l=Nu(t[0].dims,t[1].dims,n.dilations,n.pads,n.strides,o);if(n.group!==1){let q=[t[0]];if(o){let H=e.kernelCustomData.wT??e.compute(ct(t[1],Ei),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=H),q.push(H)}else q.push(t[1]);t.length===3&&q.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===n.group&&t[1].dims[1]===1&&n.dilations[0]===1&&n.dilations[1]===1?e.compute(Bu(q,n,l,i),{inputs:q}):e.compute(Lu(q,n,l,i),{inputs:q});return}let u=t.length===3,c=t[0].dims[o?1:2],h=t[0].dims[o?2:3],p=t[0].dims[o?3:1],m=t[1].dims[2],g=t[1].dims[3],w=l[o?1:2],v=l[o?2:3],b=l[o?3:1],x=o&&m===c&&g===h&&n.pads[0]===0&&n.pads[1]===0;if(x||m===1&&g===1&&n.dilations[0]===1&&n.dilations[1]===1&&n.strides[0]===1&&n.strides[1]===1&&n.pads[0]===0&&n.pads[1]===0){let q=l[0],H,ee,ue,_e=[];if(o){let Me=e.kernelCustomData.wT??e.compute(ct(t[1],Ei),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Me),x){let Qe=c*h*p;H=t[0].reshape([1,q,Qe]),ee=Me.reshape([1,Qe,b]),ue=[1,q,b]}else H=t[0].reshape([q,c*h,p]),ee=Me.reshape([1,p,b]),ue=[q,w*v,b];_e.push(H),_e.push(ee)}else H=t[0].reshape([q,p,c*h]),ee=t[1].reshape([1,b,p]),ue=[q,b,w*v],_e.push(ee),_e.push(H);u&&_e.push(t[2]);let Fe=ue[2],Re=_e[0].dims[_e[0].dims.length-1];Fe<8&&Re<8?e.compute(aa(_e,n,l,ue,o,i),{inputs:_e}):e.compute(Ti(_e,n,l,ue,o,i),{inputs:_e});return}let M=!0,k=e.kernelCustomData.wT??e.compute(ct(t[1],Ei),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=k);let $=[t[0],k];u&&$.push(t[2]);let P=o?w*v:b,I=o?b:w*v,B=m*g*p;e.compute(Iu($,n,l,P,I,B,u,M,i),{inputs:$})},Fu=(e,t)=>{let n=t.format==="NHWC",i=[e.inputs[0].reshape(n?[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 o=[0,t.pads[0],0,t.pads[1]],l=[1].concat(t.strides),u=[1].concat(t.dilations),c=[1].concat(t.kernelShape),h=$i({...t,pads:o,strides:l,dilations:u,kernelShape:c},i);ma(e,i,h,p=>n?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Vu=(e,t,n)=>{let i=n.format==="NHWC"?"channelsLast":"channelsFirst",o=$i(n,t),l=n.autoPad==="NOTSET"?n.pads:n.autoPad,u=Du(t[0].dims,t[1].dims,n.strides,n.dilations,l,!1,i);e.compute(zu(t,o,u.outShape,[u.filterDepth,u.filterHeight,u.filterWidth],[u.padInfo.front,u.padInfo.top,u.padInfo.left],i))},ga=(e,t)=>{if(Uu(e.inputs,t),e.inputs[0].dims.length===3)Fu(e,t);else if(e.inputs[0].dims.length===5)Vu(e,e.inputs,t);else{let n=$i(t,e.inputs);ma(e,e.inputs,n)}}}),Gu,xm=S(()=>{Ie(),tr(),ke(),we(),Gu=(e,t,n)=>{let i=e.length>2,o=t.outputShape,l=t.format==="NHWC",u=t.group,c=e[1].dims,h=c[2]/u,p=c[3],m=l?V(h):1,g=l&&p===1&&h>=4,w=g?Math.floor(h/4)*4:Math.floor(h/m)*m,v=h-w,b=l?V(p):1,x=l?p===1?m:b:1,M=K.size(o)/b,k=[Math.ceil(M/64),1,1];He("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${k}`);let $=["rank","rank"],P=[t.strides[0],t.strides[1]],I=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],B=[t.dilations[0],t.dilations[1]],q=[I[0]+(t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)),I[1]+(t.dilations[1]<=1?0:(t.kernelShape[l?2:3]-1)*(t.dilations[1]-1))],H=[q[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),q[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],ee=[{type:12,data:M},{type:12,data:P},{type:12,data:I},{type:12,data:B},{type:12,data:q},{type:6,data:H},{type:12,data:w},{type:12,data:h},{type:12,data:p},...L(e[0].dims,e[1].dims)];i&&(ee.push(...L(e[2].dims)),$.push("rank")),ee.push(...L(o));let ue=_e=>{let Fe=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:P.length},{name:"filter_dims",type:"u32",length:I.length},{name:"dilations",type:"u32",length:I.length},{name:"effective_filter_dims",type:"u32",length:q.length},{name:"pads",type:"i32",length:H.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Re=G(e[0].dataType),Me=l?1:2,Qe=l?2:3,ye=l?3:1,xe=F("W",e[1].dataType,e[1].dims.length,x),Le=F("Dy",e[0].dataType,e[0].dims.length,m),Ge=[Le,xe];i&&Ge.push(F("bias",e[2].dataType,[o[ye]].length,b));let De=le("result",e[0].dataType,o.length,b),je=()=>{let Ae="";if(g)m===4?Ae+=`
|
|
1205
1205
|
let xValue = ${Le.getByOffset("x_offset")};
|
|
1206
|
-
let wValue = ${
|
|
1206
|
+
let wValue = ${xe.getByOffset("w_offset")};
|
|
1207
1207
|
dotProd = dotProd + dot(xValue, wValue);
|
|
1208
1208
|
x_offset += 1u;
|
|
1209
1209
|
w_offset += 1u;`:m===2?Ae+=`
|
|
1210
|
-
dotProd = dotProd + dot(vec4<${Re}>(${Le.getByOffset("x_offset")}, ${Le.getByOffset("x_offset + 1u")}), vec4<${Re}>(${
|
|
1210
|
+
dotProd = dotProd + dot(vec4<${Re}>(${Le.getByOffset("x_offset")}, ${Le.getByOffset("x_offset + 1u")}), vec4<${Re}>(${xe.getByOffset("w_offset")}, ${xe.getByOffset("w_offset + 1u")}));
|
|
1211
1211
|
x_offset += 2u;
|
|
1212
1212
|
w_offset += 2u;`:m===1&&(Ae+=`
|
|
1213
|
-
dotProd = dotProd + dot(vec4<${Re}>(${Le.getByOffset("x_offset")}, ${Le.getByOffset("x_offset + 1u")}, ${Le.getByOffset("x_offset + 2u")}, ${Le.getByOffset("x_offset + 3u")}), vec4<${Re}>(${
|
|
1213
|
+
dotProd = dotProd + dot(vec4<${Re}>(${Le.getByOffset("x_offset")}, ${Le.getByOffset("x_offset + 1u")}, ${Le.getByOffset("x_offset + 2u")}, ${Le.getByOffset("x_offset + 3u")}), vec4<${Re}>(${xe.getByOffset("w_offset")}, ${xe.getByOffset("w_offset + 1u")}, ${xe.getByOffset("w_offset + 2u")}, ${xe.getByOffset("w_offset + 3u")}));
|
|
1214
1214
|
x_offset += 4u;
|
|
1215
1215
|
w_offset += 4u;`);else if(Ae+=`
|
|
1216
1216
|
let xValue = ${l?Le.getByOffset(`${Le.indicesToOffset(`${Le.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${m}`):Le.get("batch","inputChannel","idyR","idyC")};
|
|
1217
1217
|
`,m===1)Ae+=`
|
|
1218
|
-
let w_offset = ${
|
|
1219
|
-
let wValue = ${
|
|
1220
|
-
dotProd = dotProd + xValue * wValue;`;else for(let
|
|
1221
|
-
let wValue${
|
|
1222
|
-
dotProd = dotProd + xValue[${
|
|
1223
|
-
+ ${Le.getByOffset(`x_offset + ${
|
|
1218
|
+
let w_offset = ${xe.indicesToOffset(`${xe.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};
|
|
1219
|
+
let wValue = ${xe.getByOffset(`w_offset / ${x}`)};
|
|
1220
|
+
dotProd = dotProd + xValue * wValue;`;else for(let $e=0;$e<m;$e++)Ae+=`
|
|
1221
|
+
let wValue${$e} = ${xe.getByOffset(`${xe.indicesToOffset(`${xe.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${$e}, wOutChannel)`)} / ${x}`)};
|
|
1222
|
+
dotProd = dotProd + xValue[${$e}] * wValue${$e};`;return Ae},oe=()=>{if(v===0)return"";if(!g)throw new Error(`packInputAs4 ${g} is not true.`);let Ae="";if(m===1){Ae+="dotProd = dotProd";for(let $e=0;$e<v;$e++)Ae+=`
|
|
1223
|
+
+ ${Le.getByOffset(`x_offset + ${$e}`)} * ${xe.getByOffset(`w_offset + ${$e}`)}`;Ae+=";"}else if(m===2){if(v!==2)throw new Error(`Invalid inputChannelsRemainder ${v}.`);Ae+=`
|
|
1224
1224
|
let xValue = ${Le.getByOffset("x_offset")};
|
|
1225
|
-
let wValue = ${
|
|
1225
|
+
let wValue = ${xe.getByOffset("w_offset")};
|
|
1226
1226
|
dotProd = dotProd + dot(xValue, wValue);`}return Ae},Oe=`
|
|
1227
|
-
let outputIndices = ${De.offsetToIndices(`global_idx * ${
|
|
1227
|
+
let outputIndices = ${De.offsetToIndices(`global_idx * ${b}`)};
|
|
1228
1228
|
let batch = ${De.indicesGet("outputIndices",0)};
|
|
1229
|
-
let d1 = ${De.indicesGet("outputIndices",
|
|
1229
|
+
let d1 = ${De.indicesGet("outputIndices",ye)};
|
|
1230
1230
|
let r = ${De.indicesGet("outputIndices",Me)};
|
|
1231
|
-
let c = ${De.indicesGet("outputIndices",
|
|
1231
|
+
let c = ${De.indicesGet("outputIndices",Qe)};
|
|
1232
1232
|
let dyCorner = vec2<i32>(i32(r), i32(c)) - uniforms.pads;
|
|
1233
1233
|
let dyRCorner = dyCorner.x;
|
|
1234
1234
|
let dyCCorner = dyCorner.y;
|
|
@@ -1264,7 +1264,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1264
1264
|
}
|
|
1265
1265
|
let dyC = (${Re}(dyCCorner) + ${Re}(wC)) / ${Re}(uniforms.strides.y);
|
|
1266
1266
|
let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;
|
|
1267
|
-
if (dyC < 0.0 || dyC >= ${Re}(uniforms.Dy_shape[${
|
|
1267
|
+
if (dyC < 0.0 || dyC >= ${Re}(uniforms.Dy_shape[${Qe}]) ||
|
|
1268
1268
|
fract(dyC) > 0.0 || wCPerm < 0) {
|
|
1269
1269
|
continue;
|
|
1270
1270
|
}
|
|
@@ -1272,42 +1272,42 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1272
1272
|
var inputChannel = groupId * uniforms.input_channels_per_group;
|
|
1273
1273
|
${g?`
|
|
1274
1274
|
var x_offset = ${Le.indicesToOffset(`${Le.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${m};
|
|
1275
|
-
var w_offset = ${
|
|
1275
|
+
var w_offset = ${xe.indicesToOffset(`${xe.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${x};
|
|
1276
1276
|
`:""}
|
|
1277
1277
|
for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${g?4:m}) {
|
|
1278
|
-
${
|
|
1278
|
+
${je()}
|
|
1279
1279
|
inputChannel = inputChannel + ${g?4:m};
|
|
1280
1280
|
}
|
|
1281
|
-
${
|
|
1281
|
+
${oe()}
|
|
1282
1282
|
wC = wC + uniforms.strides.y - 1;
|
|
1283
1283
|
}
|
|
1284
1284
|
wR = wR + uniforms.strides[0] - 1;
|
|
1285
1285
|
}
|
|
1286
|
-
let value = dotProd${i?` + bias[d1 / ${
|
|
1286
|
+
let value = dotProd${i?` + bias[d1 / ${b}]`:""};
|
|
1287
1287
|
${De.setByOffset("global_idx","value")};
|
|
1288
1288
|
`;return`
|
|
1289
1289
|
${_e.registerUniforms(Fe).declareVariables(...Ge,De)}
|
|
1290
1290
|
${_e.mainStart()}
|
|
1291
1291
|
${_e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};
|
|
1292
|
-
${Oe}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${m}${x}${
|
|
1292
|
+
${Oe}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${m}${x}${b}${g}${v}`,inputDependencies:$},getRunData:()=>({dispatchGroup:{x:k[0],y:k[1],z:k[2]},outputs:[{dims:n?n(o):o,dataType:e[0].dataType}],programUniforms:ee}),getShaderSource:ue}}}),qu,Wu,Hu,ya,ju,Ku,wa,Qu,Xu,Cm=S(()=>{xm(),Ps(),Ue(),qu=(e,t,n,i,o,l)=>(e-1)*t+n+(i-1)*o+1-l,Wu=(e,t,n,i,o)=>{let l=Math.floor(e/2);t==="SAME_UPPER"?(n[i]=l,n[o]=e-l):t==="SAME_LOWER"&&(n[i]=e-l,n[o]=l)},Hu=(e,t,n,i,o,l,u,c,h,p)=>{let m=e.length-2,g=p.length===0;h.length<m&&h.push(...Array(m-h.length).fill(0));let w=e[0],v=t[c?3:1]*o;for(let b=0,x=e.length-m-(c?1:0);b<m;++b,++x){let M=e[x],k=g?M*u[b]:p[b],$=qu(M,u[b],l[b],t[x],n[b],k);Wu($,i,l,b,b+m),g&&p.push(u[b]*(M-1)+h[b]+(t[x]-1)*n[b]+1-l[b]-l[b+m])}p.splice(0,0,w),p.splice(c?3:1,0,v)},ya=(e,t)=>{let n=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((g,w)=>g*w,1)===0){n.length=0;for(let g=2;g<t[1].dims.length;++g)n.push(t[1].dims[g])}let i=e.format==="NHWC";n.splice(0,0,t[1].dims[0]),n.splice(i?3:1,0,t[1].dims[1]);let o=e.pads.slice(),l=e.outputShape.slice(),u=e.outputPadding.slice(),c=t[0].dims,h=e.dilations.slice();if(h.reduce((g,w)=>g+w,0)===0){let g=t[0].dims.length-2;h=new Array(g).fill(1)}let p=e.strides.slice();if(p.reduce((g,w)=>g+w,0)===0){let g=t[0].dims.length-2;p=new Array(g).fill(1)}Hu(c,n,h,e.autoPad,e.group,o,p,i,u,l);let m=Object.assign({},e);return Object.assign(m,{kernelShape:n,pads:o,outputPadding:u,outputShape:l,dilations:h,strides:p}),m},ju=e=>{let t=na(e),n=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,l=e.group??1,u=e.kernelShape,c=e.pads,h=e.strides,p=e.wIsConst(),m=e.outputPadding,g=e.outputShape;return{autoPad:i,format:n,dilations:o,group:l,kernelShape:u,outputPadding:m,outputShape:g,pads:c,strides:h,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},Ku=(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 n=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[0];if(n!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let l=e[0].dims.length-2;if(t.dilations.reduce((u,c)=>u+c,0)>0&&t.dilations.length!==l)throw new Error(`dilations should be ${l}D`);if(t.strides.reduce((u,c)=>u+c,0)>0&&t.strides.length!==l)throw new Error(`strides should be ${l}D`);if(t.pads.reduce((u,c)=>u+c,0)>0&&t.pads.length!==l*2)throw new Error(`pads should be ${l*2}D`);if(t.outputPadding.length!==l&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${l}D`);if(t.kernelShape.reduce((u,c)=>u+c,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")},wa=(e,t,n,i)=>{let o=e.kernelCustomData.wT??e.compute(ct(t[1],[2,3,0,1]),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let l=[t[0],o];t.length===3&&l.push(t[2]),e.compute(Gu(l,n,i),{inputs:l})},Qu=(e,t)=>{let n=t.format==="NHWC",i=[e.inputs[0].reshape(n?[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 o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let l=t.dilations;(l.length===0||l[0]===0)&&(l=[1]);let u=t.strides;(u.length===0||u[0]===0)&&(u=[1]);let c=t.pads;c.length===0&&(c=[0,0]),c=[0,c[0],0,c[1]],u=[1].concat(u),l=[1].concat(l),o=[1].concat(o);let h=t.outputPadding;h=[0].concat(h);let p=ya({...t,pads:c,strides:u,dilations:l,kernelShape:o,outputPadding:h},i);wa(e,i,p,m=>n?[m[0],m[2],m[3]]:[m[0],m[1],m[3]])},Xu=(e,t)=>{if(Ku(e.inputs,t),e.inputs[0].dims.length===3)Qu(e,t);else{let n=ya(t,e.inputs);wa(e,e.inputs,n)}}}),Yu,Ju,Zu,km=S(()=>{Ie(),ke(),A(),we(),Yu=(e,t,n,i)=>{let o=K.size(t),l=t.length,u=F("input",e,l),c=le("output",e,l),h=n.dataType===6?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),p=K.normalizeAxis(h,l),m=g=>{let w=` i32(${u.indicesGet("inputIndices","uniforms.axis")}) `,v=Q("uniforms.input_shape","uniforms.axis",l),b=i.reverse?w+(i.exclusive?" + 1":""):"0",x=i.reverse?v:w+(i.exclusive?"":" + 1");return`
|
|
1293
1293
|
${g.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(u,c)}
|
|
1294
1294
|
${g.mainStart()}
|
|
1295
1295
|
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1296
1296
|
var inputIndices = ${c.offsetToIndices("global_idx")};
|
|
1297
1297
|
var sum = ${c.type.value}(0);
|
|
1298
|
-
let first : i32 = ${
|
|
1298
|
+
let first : i32 = ${b};
|
|
1299
1299
|
let last : i32 = ${x};
|
|
1300
1300
|
for (var i : i32 = first; i < last; i++) {
|
|
1301
1301
|
${u.indicesSet("inputIndices","uniforms.axis","u32(i)")};
|
|
1302
1302
|
sum = sum + ${u.getByIndices("inputIndices")};
|
|
1303
1303
|
}
|
|
1304
1304
|
${c.setByOffset("global_idx","sum")};
|
|
1305
|
-
}`};return{name:"CumSum",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:p},...L(t,t)]}),getShaderSource:m}},Ju=(e,t)=>{let n=e.inputs[0].dims,i=e.inputs[0].dataType,o=e.inputs[1];e.compute(Yu(i,n,o,t),{inputs:[0]})},Zu=e=>{let t=e.exclusive===1,n=e.reverse===1;return E({exclusive:t,reverse:n})}}),ed,td,rd,sd,nd,Rm=
|
|
1305
|
+
}`};return{name:"CumSum",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:p},...L(t,t)]}),getShaderSource:m}},Ju=(e,t)=>{let n=e.inputs[0].dims,i=e.inputs[0].dataType,o=e.inputs[1];e.compute(Yu(i,n,o,t),{inputs:[0]})},Zu=e=>{let t=e.exclusive===1,n=e.reverse===1;return E({exclusive:t,reverse:n})}}),ed,td,rd,sd,nd,Rm=S(()=>{Ie(),ke(),A(),we(),ed=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.")},td=(e,t,n,i)=>{let o=[];o.push(`fn perm(i: ${i.type.indices}) -> ${n.type.indices} {
|
|
1306
1306
|
var a: ${n.type.indices};`);for(let l=0;l<t;++l)o.push(n.indicesSet("a",e[l],`i[${l}]`));return o.push("return a;}"),o.join(`
|
|
1307
|
-
`)},rd=(e,t)=>{let n,i,o,l,u,c,h=t.format==="NHWC",p=t.blocksize,m=t.mode==="DCR";h?([n,i,o,l]=e.dims,u=m?[n,i,o,p,p,l/p**2]:[n,i,o,l/p**2,p,p],c=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,i,o,l]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],u=m?[n,p,p,l/p**2,i,o]:[n,l/p**2,p,p,i,o],c=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let g=e.reshape(u),w=g.dims.length,v=e.dataType,
|
|
1308
|
-
${k.registerUniform("output_size","u32").declareVariables(
|
|
1307
|
+
`)},rd=(e,t)=>{let n,i,o,l,u,c,h=t.format==="NHWC",p=t.blocksize,m=t.mode==="DCR";h?([n,i,o,l]=e.dims,u=m?[n,i,o,p,p,l/p**2]:[n,i,o,l/p**2,p,p],c=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,i,o,l]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],u=m?[n,p,p,l/p**2,i,o]:[n,l/p**2,p,p,i,o],c=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let g=e.reshape(u),w=g.dims.length,v=e.dataType,b=F("a",v,w),x=le("output",v,w),M=k=>`
|
|
1308
|
+
${k.registerUniform("output_size","u32").declareVariables(b,x)}
|
|
1309
1309
|
|
|
1310
|
-
${td(c,w,
|
|
1310
|
+
${td(c,w,b,x)}
|
|
1311
1311
|
|
|
1312
1312
|
${k.mainStart()}
|
|
1313
1313
|
${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1315,8 +1315,8 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1315
1315
|
let indices = ${x.offsetToIndices("global_idx")};
|
|
1316
1316
|
let aIndices = perm(indices);
|
|
1317
1317
|
|
|
1318
|
-
${x.setByOffset("global_idx",
|
|
1319
|
-
}`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:k=>{let $=h?[n,i*p,o*p,l/p**2]:[n,l/p**2,i*p,o*p],P=
|
|
1318
|
+
${x.setByOffset("global_idx",b.getByIndices("aIndices"))}
|
|
1319
|
+
}`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:k=>{let $=h?[n,i*p,o*p,l/p**2]:[n,l/p**2,i*p,o*p],P=K.size($),I=g.dims,B=K.sortBasedOnPerm(I,c);return{outputs:[{dims:$,dataType:k[0].dataType}],dispatchGroup:{x:Math.ceil(P/64)},programUniforms:[{type:12,data:P},...L(I,B)]}},getShaderSource:M}},sd=(e,t)=>{ed(e.inputs),e.compute(rd(e.inputs[0],t))},nd=e=>E({blocksize:e.blocksize,mode:e.mode,format:e.format})}),xi,jn,va,id,ad,od,ld,_a,ud,dd,cd,Am=S(()=>{Ie(),ke(),A(),we(),xi="[a-zA-Z]|\\.\\.\\.",jn="("+xi+")+",va="^"+jn+"$",id="("+jn+",)*"+jn,ad="^"+id+"$",od=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);n===void 0?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},ld=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,i]=t.includes("->")?t.split("->",2):[t,""];if(!n.match(RegExp(ad)))throw new Error("Invalid LHS term");if(n.split(",").forEach((o,l)=>{let u=e[l].dims.slice();if(!o.match(RegExp(va)))throw new Error("Invalid LHS term");let c=this.processTerm(o,!0,u,l);this.lhs.push(c)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([o,l])=>l.count===1||o==="...").map(([o])=>o).join("");else if(!i.match(RegExp(jn)))throw new Error("Invalid RHS");i.match(RegExp(xi,"g"))?.forEach(o=>{if(o==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let l=this.symbolToInfo.get(o);if(l===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(l.dimValue)}}),this.rhs=this.processTerm(i,!1,this.outputDims)}addSymbol(e,t,n){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(n)}else i={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,i)}processTerm(e,t,n,i=-1){let o=n.length,l=!1,u=[],c=0;if(!e.match(RegExp(va))&&!t&&e!=="")throw new Error("Invalid LHS term");let h=e.match(RegExp(xi,"g")),p=new od(i);return h?.forEach((m,g)=>{if(m==="..."){if(l)throw new Error("Only one ellipsis is allowed per input term");l=!0;let w=o-h.length+1;if(w<0)throw new Error("Ellipsis out of bounds");if(u=n.slice(c,c+w),this.hasEllipsis){if(this.ellipsisDims.length!==u.length||this.ellipsisDims.toString()!==u.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=u;else throw new Error("Ellipsis must be specified in the LHS");for(let v=0;v<u.length;v++){let b=String.fromCharCode(48+v);p.addSymbol(b,g+v),this.addSymbol(b,n[c++],i)}}else p.addSymbol(m,g+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(m,n[c++],i)}),p}},_a=e=>e+"_max",ud=(e,t,n,i)=>{let o=e.map(p=>p.length).map((p,m)=>F(`input${m}`,t,p)),l=K.size(i),u=le("output",t,i.length),c=[...n.symbolToInfo.keys()].filter(p=>!n.rhs.symbolToIndices.has(p)),h=p=>{let m=[],g="var prod = 1.0;",w="var sum = 0.0;",v="sum += prod;",b=[],x=[],M=[],k=[],$=n.symbolToInfo.size===n.rhs.symbolToIndices.size;n.symbolToInfo.forEach((I,B)=>{if(n.rhs.symbolToIndices.has(B)){let q=n.rhs.symbolToIndices.get(B)?.[0];q!==void 0&&n.lhs.forEach((H,ee)=>{if(I.inputIndices.includes(ee)){let ue=H.symbolToIndices.get(B);if(ue===void 0)throw new Error("Invalid symbol error");ue.forEach(_e=>{m.push(`${o[ee].indicesSet(`input${ee}Indices`,_e,u.indicesGet("outputIndices",q))}`)})}})}else n.lhs.forEach((q,H)=>{if(I.inputIndices.includes(H)){let ee=q.symbolToIndices.get(B);if(ee===void 0)throw new Error("Invalid symbol error");ee.forEach(ue=>{b.push(`${o[H].indicesSet(`input${H}Indices`,ue,`${B}`)}`)}),k.push(`prod *= ${o[H].getByIndices(`input${H}Indices`)};`)}}),x.push(`for(var ${B}: u32 = 0; ${B} < uniforms.${_a(B)}; ${B}++) {`),M.push("}")});let P=$?[...m,`let sum = ${o.map((I,B)=>I.getByIndices(`input${B}Indices`)).join(" * ")};`]:[...m,w,...x,...b,g,...k,v,...M];return`
|
|
1320
1320
|
${p.registerUniforms(c.map(I=>({name:`${_a(I)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,u)}
|
|
1321
1321
|
|
|
1322
1322
|
${p.mainStart()}
|
|
@@ -1327,13 +1327,13 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1327
1327
|
${P.join(`
|
|
1328
1328
|
`)};
|
|
1329
1329
|
${u.setByOffset("global_idx","sum")};
|
|
1330
|
-
}`};return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=c.filter(g=>n.symbolToInfo.has(g)).map(g=>({type:12,data:n.symbolToInfo.get(g)?.dimValue||0}));p.push({type:12,data:l});let m=e.map((g,w)=>[...L(g)]).reduce((g,w)=>g.concat(w),p);return m.push(...L(i)),{outputs:[{dims:i,dataType:t}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:m}},getShaderSource:h}},dd=(e,t)=>{let n=new ld(e.inputs,t.equation),i=n.outputDims,o=e.inputs.map((l,u)=>l.dims);e.compute(ud(o,e.inputs[0].dataType,n,i))},cd=e=>{let t=e.equation.replace(/\s+/g,"");return E({equation:t})}}),hd,ba,pd,fd,md,Im=
|
|
1330
|
+
}`};return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=c.filter(g=>n.symbolToInfo.has(g)).map(g=>({type:12,data:n.symbolToInfo.get(g)?.dimValue||0}));p.push({type:12,data:l});let m=e.map((g,w)=>[...L(g)]).reduce((g,w)=>g.concat(w),p);return m.push(...L(i)),{outputs:[{dims:i,dataType:t}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:m}},getShaderSource:h}},dd=(e,t)=>{let n=new ld(e.inputs,t.equation),i=n.outputDims,o=e.inputs.map((l,u)=>l.dims);e.compute(ud(o,e.inputs[0].dataType,n,i))},cd=e=>{let t=e.equation.replace(/\s+/g,"");return E({equation:t})}}),hd,ba,pd,fd,md,Im=S(()=>{Ie(),ke(),we(),hd=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=n.length<t.length?0:n.length-t.length,o=t.length<n.length?0:t.length-n.length;for(;i<n.length&&o<t.length;++i,++o)if(n[i]!==t[o]&&n[i]!==1&&t[o]!==1)throw new Error("Expand requires shape to be broadcastable to input")},ba=(e,t)=>{let n=e.length-t.length,i=[];for(let o=0;o<n;++o)i.push(e[o]);for(let o=0;o<t.length;++o)i.push(t[o]===1?e[o+n]:t[o]);return i},pd=(e,t)=>e.length>t.length?ba(e,t):ba(t,e),fd=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=pd(t,n),o=e[0].dataType,l=o===9||K.size(t)===1,u=o===9||t.length>0&&t[t.length-1]%4===0?4:1,c=l||i.length>0&&i[i.length-1]%4===0?4:1,h=Math.ceil(K.size(i)/c),p=g=>{let w=F("input",o,t.length,u),v=le("output",o,i.length,c),b;if(o===9){let x=(M,k,$="")=>`
|
|
1331
1331
|
let outputIndices${k} = ${v.offsetToIndices(`outputOffset + ${k}u`)};
|
|
1332
1332
|
let offset${k} = ${w.broadcastedIndicesToOffset(`outputIndices${k}`,v)};
|
|
1333
1333
|
let index${k} = offset${k} / 4u;
|
|
1334
1334
|
let component${k} = offset${k} % 4u;
|
|
1335
1335
|
${M}[${k}] = ${$}(${w.getByOffset(`index${k}`)}[component${k}]);
|
|
1336
|
-
`;
|
|
1336
|
+
`;b=`
|
|
1337
1337
|
let outputOffset = global_idx * ${c};
|
|
1338
1338
|
var data = vec4<u32>(0);
|
|
1339
1339
|
${x("data",0,"u32")}
|
|
@@ -1341,7 +1341,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1341
1341
|
${x("data",2,"u32")}
|
|
1342
1342
|
${x("data",3,"u32")}
|
|
1343
1343
|
${v.setByOffset("global_idx","data")}
|
|
1344
|
-
}`}else
|
|
1344
|
+
}`}else b=`
|
|
1345
1345
|
let outputIndices = ${v.offsetToIndices(`global_idx * ${c}`)};
|
|
1346
1346
|
let inputOffset = ${w.broadcastedIndicesToOffset("outputIndices",v)};
|
|
1347
1347
|
let data = ${v.type.value}(${w.getByOffset(`inputOffset / ${u}`)});
|
|
@@ -1350,13 +1350,13 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1350
1350
|
${g.registerUniform("vec_size","u32").declareVariables(w,v)}
|
|
1351
1351
|
${g.mainStart()}
|
|
1352
1352
|
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
1353
|
-
${
|
|
1353
|
+
${b}`},m=[{type:12,data:h},...L(t,i)];return{name:"Expand",shaderCache:{hint:`${i.length};${u}${c}`,inputDependencies:["rank"]},getShaderSource:p,getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:m})}},md=e=>{hd(e.inputs),e.compute(fd(e.inputs),{inputs:[0]})}}),gd,yd,Mm=S(()=>{Ie(),ke(),we(),sa(),gd=e=>{let t=e[0].dataType,n=K.size(e[0].dims),i=K.size(e[1].dims),o=i%4===0,l=u=>{let c=F("x",t,[1],4),h=F("bias",t,[1],4),p=le("y",t,[1],4),m=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],g=v=>`
|
|
1354
1354
|
let bias${v}_offset: u32 = (global_idx * 4 + ${v}) % uniforms.bias_size;
|
|
1355
1355
|
let bias${v} = ${h.getByOffset(`bias${v}_offset / 4`)}[bias${v}_offset % 4];`,w=o?`
|
|
1356
1356
|
let bias = ${h.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${g(0)}${g(1)}${g(2)}${g(3)}
|
|
1357
1357
|
let bias = ${c.type.value}(bias0, bias1, bias2, bias3);`;return`${u.registerUniforms(m).declareVariables(c,h,p)}
|
|
1358
1358
|
|
|
1359
|
-
${ta(
|
|
1359
|
+
${ta(U(t))}
|
|
1360
1360
|
|
|
1361
1361
|
${u.mainStart(D)}
|
|
1362
1362
|
${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}
|
|
@@ -1365,8 +1365,8 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1365
1365
|
${w}
|
|
1366
1366
|
let x_in = x + bias;
|
|
1367
1367
|
${p.setByOffset("global_idx",ra("x_in"))}
|
|
1368
|
-
}`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:l,getRunData:u=>({outputs:[{dims:u[0].dims,dataType:u[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:i}],dispatchGroup:{x:Math.ceil(n/D/4)}})}},yd=e=>{e.inputs.length<2||
|
|
1369
|
-
var idx${$} = ${
|
|
1368
|
+
}`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:l,getRunData:u=>({outputs:[{dims:u[0].dims,dataType:u[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:i}],dispatchGroup:{x:Math.ceil(n/D/4)}})}},yd=e=>{e.inputs.length<2||K.size(e.inputs[1].dims)===0?Yl(e):e.compute(gd(e.inputs))}}),wd,vd,_d,bd,Pm=S(()=>{Ie(),ke(),A(),we(),wd=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},vd=(e,t)=>{let n=e[0].dims,i=e[1].dims,o=n.length,l=K.normalizeAxis(t.axis,o),u=n.slice(0);u.splice(l,1,...i);let c=n[l],h=e[0].dataType===9?4:1,p=Math.ceil(K.size(u)/h),m=[{type:12,data:p},{type:6,data:c},{type:12,data:l},...L(e[0].dims,e[1].dims,u)],g=w=>{let v=F("data",e[0].dataType,e[0].dims.length,h),b=F("inputIndices",e[1].dataType,e[1].dims.length),x=le("output",e[0].dataType,u.length,h),M=$=>{let P=i.length,I=`var indicesIndices${$} = ${b.type.indices}(0);`;for(let B=0;B<P;B++)I+=`${P>1?`indicesIndices${$}[${B}]`:`indicesIndices${$}`} = ${u.length>1?`outputIndices${$}[uniforms.axis + ${B}]`:`outputIndices${$}`};`;I+=`
|
|
1369
|
+
var idx${$} = ${b.getByIndices(`indicesIndices${$}`)};
|
|
1370
1370
|
if (idx${$} < 0) {
|
|
1371
1371
|
idx${$} = idx${$} + uniforms.axisDimLimit;
|
|
1372
1372
|
}
|
|
@@ -1392,11 +1392,11 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1392
1392
|
let value = ${v.getByIndices("dataIndices")};
|
|
1393
1393
|
${x.setByOffset("global_idx","value")};
|
|
1394
1394
|
`;return`
|
|
1395
|
-
${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(v,
|
|
1395
|
+
${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(v,b,x)}
|
|
1396
1396
|
${w.mainStart()}
|
|
1397
1397
|
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1398
1398
|
${k}
|
|
1399
|
-
}`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:g}},_d=e=>E({axis:e.axis}),bd=(e,t)=>{let n=e.inputs;wd(n),e.compute(vd(e.inputs,t))}}),Sd,Td,Ed,Om=
|
|
1399
|
+
}`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:g}},_d=e=>E({axis:e.axis}),bd=(e,t)=>{let n=e.inputs;wd(n),e.compute(vd(e.inputs,t))}}),Sd,Td,Ed,Om=S(()=>{Ie(),ke(),we(),Sd=(e,t,n,i,o,l,u,c,h)=>{let p=[{type:12,data:l},{type:12,data:i},{type:12,data:o},{type:12,data:n},{type:12,data:u},{type:12,data:c},{type:12,data:h}],m=[l];p.push(...L(t.dims,m));let g=w=>{let v=F("indices_data",t.dataType,t.dims.length),b=le("input_slice_offsets_data",12,1,1),x=[v,b],M=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:n.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return`
|
|
1400
1400
|
${w.registerUniforms(M).declareVariables(...x)}
|
|
1401
1401
|
${w.mainStart()}
|
|
1402
1402
|
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1415,13 +1415,13 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1415
1415
|
}
|
|
1416
1416
|
|
|
1417
1417
|
input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset);
|
|
1418
|
-
}`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${n.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:m,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p}),getShaderSource:g},{inputs:[t],outputs:[-1]})[0]},Td=(e,t)=>{let n=e.inputs,i=n[0].dims,o=n[0].dataType,l=n[1].dims,u=l[l.length-1],c=
|
|
1419
|
-
${I.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(B,q,
|
|
1418
|
+
}`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${n.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:m,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p}),getShaderSource:g},{inputs:[t],outputs:[-1]})[0]},Td=(e,t)=>{let n=e.inputs,i=n[0].dims,o=n[0].dataType,l=n[1].dims,u=l[l.length-1],c=K.sizeToDimension(l,l.length-1),h=K.sizeFromDimension(i,t.batchDims+u),p=K.sizeToDimension(i,t.batchDims),m=K.sizeFromDimension(i,t.batchDims),g=c/p,w=new Array(u),v=h;for(let I=0;I<u;++I)w[u-1-I]=v,v*=i[t.batchDims+u-1-I];let b=Sd(e,n[1],w,t.batchDims,i,c,g,m,u),x=t.batchDims+u;if(x>i.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let M=l.slice(0,-1).concat(i.slice(x)),k=K.size(M),$=[{type:12,data:k},{type:12,data:h},...L(n[0].dims,b.dims,M)],P=I=>{let B=F("data",n[0].dataType,n[0].dims.length),q=F("slice_offsets",12,b.dims.length),H=le("output",n[0].dataType,M.length);return`
|
|
1419
|
+
${I.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(B,q,H)}
|
|
1420
1420
|
${I.mainStart()}
|
|
1421
1421
|
${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1422
1422
|
let slice_offset = slice_offsets[global_idx / uniforms.slice_size];
|
|
1423
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:M,dataType:o}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:$}),getShaderSource:P},{inputs:[n[0],
|
|
1424
|
+
}`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:M,dataType:o}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:$}),getShaderSource:P},{inputs:[n[0],b]})},Ed=e=>({batchDims:e.batch_dims,cacheKey:""})}),$d,xd,Cd,kd,Dm=S(()=>{Ie(),ke(),A(),we(),$d=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let n=K.normalizeAxis(t.quantizeAxis,e[0].dims.length),i=t.blockSize,o=e[0],l=e[2],u=e.length===4?e[3]:void 0;if(l.dims.length!==o.dims.length||!o.dims.map((c,h)=>h===n?Math.ceil(c/i)===l.dims[h]:c===l.dims[h]).reduce((c,h)=>c&&h,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(u){if(u.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(u.dims.length!==l.dims.length||!u.dims.map((c,h)=>c===l.dims[h]).reduce((c,h)=>c&&h,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},xd=(e,t)=>{let n=e[0].dims,i=e[1].dims,o=n.length,l=K.normalizeAxis(t.gatherAxis,o),u=K.normalizeAxis(t.quantizeAxis,o),c=n.slice(0);c.splice(l,1,...i);let h=K.size(c),p=e[2].dataType,m=e[0].dataType===22,g=[{type:12,data:h},{type:12,data:u},{type:12,data:l},{type:12,data:t.blockSize},...L(...e.map((v,b)=>v.dims),c)],w=v=>{let b=F("data",e[0].dataType,e[0].dims.length),x=F("inputIndices",e[1].dataType,e[1].dims.length),M=F("scales",e[2].dataType,e[2].dims.length),k=e.length>3?F("zeroPoint",e[3].dataType,e[3].dims.length):void 0,$=le("output",p,c.length),P=[b,x,M];k&&P.push(k);let I=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
1425
1425
|
${v.registerUniforms(I).declareVariables(...P,$)}
|
|
1426
1426
|
${v.mainStart()}
|
|
1427
1427
|
let output_indices = ${$.offsetToIndices("global_idx")};
|
|
@@ -1431,24 +1431,24 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1431
1431
|
let index = ${$.indicesGet("output_indices","uniforms.gather_axis + i")};
|
|
1432
1432
|
${x.indicesSet("indices_indices","i","index")};
|
|
1433
1433
|
}`:`indices_indices = ${$.indicesGet("output_indices","uniforms.gather_axis")};`};
|
|
1434
|
-
var data_indices = ${
|
|
1434
|
+
var data_indices = ${b.type.indices}(0);
|
|
1435
1435
|
for (var i: u32 = 0; i < uniforms.gather_axis; i++) {
|
|
1436
1436
|
let index = ${$.indicesGet("output_indices","i")};
|
|
1437
|
-
${
|
|
1437
|
+
${b.indicesSet("data_indices","i","index")};
|
|
1438
1438
|
}
|
|
1439
1439
|
var index_from_indices = ${x.getByIndices("indices_indices")};
|
|
1440
1440
|
if (index_from_indices < 0) {
|
|
1441
1441
|
index_from_indices += ${n[l]};
|
|
1442
1442
|
}
|
|
1443
|
-
${
|
|
1443
|
+
${b.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")};
|
|
1444
1444
|
for (var i = uniforms.gather_axis + 1; i < ${c.length}; i++) {
|
|
1445
1445
|
let index = ${$.indicesGet("output_indices",`i + ${i.length} - 1`)};
|
|
1446
|
-
${
|
|
1446
|
+
${b.indicesSet("data_indices","i","index")};
|
|
1447
1447
|
}
|
|
1448
|
-
let data_offset = ${
|
|
1448
|
+
let data_offset = ${b.indicesToOffset("data_indices")};
|
|
1449
1449
|
let data_index = data_offset % 8;
|
|
1450
1450
|
// Convert 4-bit packed data to 8-bit packed data.
|
|
1451
|
-
let packed_4bit_quantized_data = ${
|
|
1451
|
+
let packed_4bit_quantized_data = ${b.getByOffset("data_offset / 8")};
|
|
1452
1452
|
let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;
|
|
1453
1453
|
let quantized_data_vec = ${m?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data));
|
|
1454
1454
|
let quantized_data = quantized_data_vec[data_index / 2];
|
|
@@ -1464,10 +1464,10 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1464
1464
|
let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;
|
|
1465
1465
|
let zero_point_vec = ${m?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points));
|
|
1466
1466
|
let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};
|
|
1467
|
-
let dequantized_data = ${
|
|
1467
|
+
let dequantized_data = ${U(p)}(quantized_data - zero_point) * scale;
|
|
1468
1468
|
${$.setByOffset("global_idx","dequantized_data")};
|
|
1469
|
-
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((v,
|
|
1470
|
-
indices input tensors be of same rank.`)},Ad=(e,t)=>{let n=e[0].dims,i=e[0].dataType,o=n.length,l=e[1].dims,u=e[1].dataType,c=
|
|
1469
|
+
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((v,b)=>b!==1).map(v=>v.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(v,b)=>"rank")},getRunData:()=>({outputs:[{dims:c,dataType:p}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:g}),getShaderSource:w}},Cd=(e,t)=>{let n=e.inputs;$d(n,t),e.compute(xd(e.inputs,t))},kd=e=>E({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Rd,Ad,Id,Md,zm=S(()=>{Ie(),ke(),A(),we(),Rd=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.`)},Ad=(e,t)=>{let n=e[0].dims,i=e[0].dataType,o=n.length,l=e[1].dims,u=e[1].dataType,c=K.normalizeAxis(t.axis,o),h=n[c],p=l.slice(0),m=K.size(p),g=F("input",i,o),w=F("indicesInput",u,l.length),v=le("output",i,p.length),b=[{type:12,data:m},{type:6,data:h},{type:12,data:c}];return b.push(...L(n,l,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:b}),getShaderSource:x=>`
|
|
1471
1471
|
${x.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(g,w,v)}
|
|
1472
1472
|
${x.mainStart()}
|
|
1473
1473
|
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
@@ -1483,7 +1483,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1483
1483
|
let value = ${g.getByIndices("inputIndices")};
|
|
1484
1484
|
|
|
1485
1485
|
${v.setByOffset("global_idx","value")};
|
|
1486
|
-
}`}},Id=e=>E({axis:e.axis}),Md=(e,t)=>{let n=e.inputs;Rd(n),e.compute(Ad(e.inputs,t))}}),Pd,Od,Dd,zd,Lm=
|
|
1486
|
+
}`}},Id=e=>E({axis:e.axis}),Md=(e,t)=>{let n=e.inputs;Rd(n),e.compute(Ad(e.inputs,t))}}),Pd,Od,Dd,zd,Lm=S(()=>{Ie(),ke(),we(),Pd=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")},Od=(e,t)=>{let n=e[0].dims.slice(),i=e[1].dims.slice(),[o,l,u]=Ys.getShapeOfGemmResult(n,t.transA,i,t.transB,e.length===3?e[2].dims:void 0),c=[o,l];if(!c)throw new Error("Can't use gemm on the given tensors");let h=16,p=Math.ceil(l/h),m=Math.ceil(o/h);K.size(c);let g=[{type:12,data:p},{type:12,data:o},{type:12,data:l},{type:12,data:u},{type:1,data:t.alpha},{type:1,data:t.beta}],w=["type","type"];e.length===3&&(g.push(...L(e[2].dims)),w.push("rank")),g.push(...L(c));let v=b=>{let x=F("a",e[0].dataType,e[0].dims),M=F("b",e[1].dataType,e[1].dims),k=null,$=[x,M];e.length===3&&(k=F("c",e[2].dataType,e[2].dims.length),$.push(k));let P=le("output",e[0].dataType,c.length);$.push(P);let I=[{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"}],B="",q="";t.transA&&t.transB?(q=`
|
|
1487
1487
|
var col = tile_row_start + local_id.x;
|
|
1488
1488
|
var row = k_start + local_id.y;
|
|
1489
1489
|
if (col < uniforms.M && row < uniforms.K) {
|
|
@@ -1547,11 +1547,11 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1547
1547
|
} else {
|
|
1548
1548
|
tile_b[local_id.y][local_id.x] = ${M.type.value}(0);
|
|
1549
1549
|
}
|
|
1550
|
-
`,B="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let
|
|
1551
|
-
${
|
|
1550
|
+
`,B="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let H=t.alpha===1?"":"value *= uniforms.alpha;";return`
|
|
1551
|
+
${b.registerUniforms(I).declareVariables(...$)}
|
|
1552
1552
|
var<workgroup> tile_a: array<array<${x.type.storage}, ${h}>, ${h}>;
|
|
1553
1553
|
var<workgroup> tile_b: array<array<${M.type.storage}, ${h}>, ${h}>;
|
|
1554
|
-
${
|
|
1554
|
+
${b.mainStart([h,h,1])}
|
|
1555
1555
|
let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${h};
|
|
1556
1556
|
let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${h};
|
|
1557
1557
|
let num_tiles = (uniforms.K - 1) / ${h} + 1;
|
|
@@ -1568,14 +1568,14 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1568
1568
|
workgroupBarrier();
|
|
1569
1569
|
}
|
|
1570
1570
|
|
|
1571
|
-
${
|
|
1571
|
+
${H}
|
|
1572
1572
|
let m = tile_row_start + local_id.y;
|
|
1573
1573
|
let n = tile_col_start + local_id.x;
|
|
1574
1574
|
${k!=null?`let cOffset = ${k.broadcastedIndicesToOffset("vec2(m, n)",P)}; value += ${P.type.value}(uniforms.beta) * ${k.getByOffset("cOffset")};`:""}
|
|
1575
1575
|
if (m < uniforms.M && n < uniforms.N) {
|
|
1576
1576
|
output[m * uniforms.N + n] = value;
|
|
1577
1577
|
}
|
|
1578
|
-
}`};return{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:p*m},programUniforms:g}),getShaderSource:v}},Dd=e=>{let t=e.transA,n=e.transB,i=e.alpha,o=e.beta;return{transA:t,transB:n,alpha:i,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},zd=(e,t)=>{Pd(e.inputs),e.compute(Od(e.inputs,t))}}),
|
|
1578
|
+
}`};return{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:p*m},programUniforms:g}),getShaderSource:v}},Dd=e=>{let t=e.transA,n=e.transB,i=e.alpha,o=e.beta;return{transA:t,transB:n,alpha:i,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},zd=(e,t)=>{Pd(e.inputs),e.compute(Od(e.inputs,t))}}),Mr,Gr,Os,Ds,Ld,Bd,Nd,Ud,Fd,Vd,Gd,qd,Wd,Hd,Bm=S(()=>{Ie(),ke(),A(),we(),[Mr,Gr,Os,Ds]=[0,1,2,3],Ld=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")},Bd=`
|
|
1579
1579
|
fn gs_get_cubic_coeffs(x: f32) -> vec4<f32> {
|
|
1580
1580
|
let cubic_alpha = -0.75f;
|
|
1581
1581
|
let x_abs = abs(x);
|
|
@@ -1638,35 +1638,35 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1638
1638
|
fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4<f32>) -> ${t} {
|
|
1639
1639
|
var pixel = ${t}(0);
|
|
1640
1640
|
var indices = vec4<u32>(0);
|
|
1641
|
-
indices[${
|
|
1642
|
-
indices[${
|
|
1641
|
+
indices[${Mr}] = batch;
|
|
1642
|
+
indices[${Gr}] = channel;`+(()=>{switch(n.paddingMode){case"zeros":return`
|
|
1643
1643
|
if (r >= 0 && r < H && c >=0 && c < W) {
|
|
1644
|
-
indices[${
|
|
1645
|
-
indices[${
|
|
1644
|
+
indices[${Os}] = u32(r);
|
|
1645
|
+
indices[${Ds}] = u32(c);
|
|
1646
1646
|
} else {
|
|
1647
1647
|
return ${t}(0);
|
|
1648
1648
|
}
|
|
1649
1649
|
`;case"border":return`
|
|
1650
|
-
indices[${
|
|
1651
|
-
indices[${
|
|
1650
|
+
indices[${Os}] = u32(clamp(r, 0, H - 1));
|
|
1651
|
+
indices[${Ds}] = u32(clamp(c, 0, W - 1));
|
|
1652
1652
|
`;case"reflection":return`
|
|
1653
|
-
indices[${
|
|
1654
|
-
indices[${
|
|
1653
|
+
indices[${Os}] = gs_reflect(r, border[1], border[3]);
|
|
1654
|
+
indices[${Ds}] = gs_reflect(c, border[0], border[2]);
|
|
1655
1655
|
`;default:throw new Error(`padding mode ${n.paddingMode} is not supported`)}})()+`
|
|
1656
1656
|
return ${e.getByIndices("indices")};
|
|
1657
1657
|
}
|
|
1658
1658
|
`,Gd=(e,t,n)=>(()=>{switch(n.mode){case"nearest":return`
|
|
1659
|
-
let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${
|
|
1659
|
+
let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Mr}], indices[${Gr}], border);
|
|
1660
1660
|
`;case"bilinear":return`
|
|
1661
1661
|
let x1 = i32(floor(x));
|
|
1662
1662
|
let y1 = i32(floor(y));
|
|
1663
1663
|
let x2 = x1 + 1;
|
|
1664
1664
|
let y2 = y1 + 1;
|
|
1665
1665
|
|
|
1666
|
-
let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${
|
|
1667
|
-
let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${
|
|
1668
|
-
let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${
|
|
1669
|
-
let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${
|
|
1666
|
+
let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Mr}], indices[${Gr}], border);
|
|
1667
|
+
let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Mr}], indices[${Gr}], border);
|
|
1668
|
+
let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Mr}], indices[${Gr}], border);
|
|
1669
|
+
let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Mr}], indices[${Gr}], border);
|
|
1670
1670
|
|
|
1671
1671
|
let dx2 = ${t}(f32(x2) - x);
|
|
1672
1672
|
let dx1 = ${t}(x - f32(x1));
|
|
@@ -1679,14 +1679,14 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1679
1679
|
var p: mat4x4<${t}>;
|
|
1680
1680
|
for (var h = 0; h < 4; h++) {
|
|
1681
1681
|
for (var w = 0; w < 4; w++) {
|
|
1682
|
-
p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${
|
|
1682
|
+
p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Mr}], indices[${Gr}], border);
|
|
1683
1683
|
}
|
|
1684
1684
|
}
|
|
1685
1685
|
|
|
1686
1686
|
let dx = x - f32(x0 + 1);
|
|
1687
1687
|
let dy = y - f32(y0 + 1);
|
|
1688
1688
|
let result = gs_bicubic_interpolate(p, dx, dy);
|
|
1689
|
-
`;default:throw new Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,qd=(e,t)=>{let n=F("x",e[0].dataType,e[0].dims.length),i=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=F("grid",e[1].dataType,i.length,2),l=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(l=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[
|
|
1689
|
+
`;default:throw new Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,qd=(e,t)=>{let n=F("x",e[0].dataType,e[0].dims.length),i=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=F("grid",e[1].dataType,i.length,2),l=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(l=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Mr,Gr,Os,Ds]=[0,3,1,2]);let u=le("output",e[0].dataType,l.length),c=n.type.value,h=K.size(l),p=[{type:12,data:h},...L(e[0].dims,i,l)],m=g=>`
|
|
1690
1690
|
${g.registerUniform("output_size","u32").declareVariables(n,o,u)}
|
|
1691
1691
|
${Bd}
|
|
1692
1692
|
${Nd(c)}
|
|
@@ -1696,8 +1696,8 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1696
1696
|
|
|
1697
1697
|
${g.mainStart()}
|
|
1698
1698
|
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1699
|
-
let H_in = i32(uniforms.x_shape[${
|
|
1700
|
-
let W_in = i32(uniforms.x_shape[${
|
|
1699
|
+
let H_in = i32(uniforms.x_shape[${Os}]);
|
|
1700
|
+
let W_in = i32(uniforms.x_shape[${Ds}]);
|
|
1701
1701
|
|
|
1702
1702
|
${t.alignCorners===0?`
|
|
1703
1703
|
let x_min = -0.5;
|
|
@@ -1713,20 +1713,20 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1713
1713
|
let border = vec4<f32>(x_min, y_min, x_max, y_max);
|
|
1714
1714
|
|
|
1715
1715
|
let indices = ${u.offsetToIndices("global_idx")};
|
|
1716
|
-
var grid_indices = vec3<u32>(indices[${
|
|
1716
|
+
var grid_indices = vec3<u32>(indices[${Mr}], indices[${Os}], indices[${Ds}]);
|
|
1717
1717
|
let nxy = ${o.getByIndices("grid_indices")};
|
|
1718
1718
|
var x = gs_denormalize(f32(nxy[0]), W_in);
|
|
1719
1719
|
var y = gs_denormalize(f32(nxy[1]), H_in);
|
|
1720
1720
|
|
|
1721
1721
|
${Gd(u,c,t)}
|
|
1722
|
-
}`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:g=>{let w=
|
|
1723
|
-
${g.registerUniforms(x).declareVariables(v,
|
|
1722
|
+
}`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:g=>{let w=K.size(l);return{outputs:[{dims:l,dataType:g[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:p}},getShaderSource:m}},Wd=(e,t)=>{Ld(e.inputs),e.compute(qd(e.inputs,t))},Hd=e=>E({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Ft,jd,Kd,Sa,Qd,Kn,Xd,Yd=S(()=>{Ie(),ke(),A(),tn(),Zi(),we(),Ue(),Ft=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,jd=(e,t)=>{let n=e[0],i=Ft(e,1),o=Ft(e,2),l=Ft(e,3),u=Ft(e,4),c=Ft(e,5),h=Ft(e,6),p=Ft(e,7);if(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let m=n.dims[0],g=n.dims[1],w=n.dims.length===3?n.dims[2]:t.numHeads*n.dims[4],v=g,b=0,x=0,M=Math.floor(w/t.numHeads);if(h&&p&&K.size(h.dims)&&K.size(p.dims)){if(h.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(h.dims[0]!==m||h.dims[1]!==t.numHeads||h.dims[3]!==M)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[0]!==m||p.dims[1]!==t.numHeads||p.dims[3]!==M)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[2]!==p.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(p.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');b=h.dims[2],x=h.dims[2]}else if(h&&K.size(h.dims)||p&&K.size(p.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let k;if(i&&K.size(i.dims)>0){if(n.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(n.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]!==n.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');k=2,v=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==M)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');k=5,v=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==M)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');k=0,v=i.dims[2]}}else{if(n.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(n.dims[2]!==t.numHeads||n.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');k=3}if(l&&K.size(l.dims)>0){if(l.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 $=b+v,P=0;if(u&&K.size(u.dims)>0){P=8;let H=u.dims;throw H.length===1?H[0]===m?P=1:H[0]===3*m+2&&(P=3):H.length===2&&H[0]===m&&H[1]===$&&(P=5),P===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let I=!1,B=w;if(o&&K.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(v!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');B=o.dims[2]}else{if(v!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');B=o.dims[1]*o.dims[3],I=!0}}let q=!1;if(u&&K.size(u.dims)>0)throw new Error("Key padding mask is not supported");if(c&&K.size(c.dims)>0){if(c.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(c.dims[0]!==m||c.dims[1]!==t.numHeads||c.dims[2]!==g||c.dims[3]!==$)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:m,sequenceLength:g,pastSequenceLength:b,kvSequenceLength:v,totalSequenceLength:$,maxSequenceLength:x,inputHiddenSize:0,hiddenSize:w,vHiddenSize:B,headSize:M,vHeadSize:Math.floor(B/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:P,scale:t.scale,broadcastResPosBias:q,passPastInKv:I,qkvFormat:k}},Kd=e=>E({...e}),Sa=E({perm:[0,2,1,3]}),Qd=(e,t,n,i,o,l,u)=>{let c=[i,o,l],h=K.size(c),p=[{type:12,data:h},{type:12,data:u},{type:12,data:l}],m=g=>{let w=le("qkv_with_bias",t.dataType,c),v=F("qkv",t.dataType,c),b=F("bias",n.dataType,c),x=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`
|
|
1723
|
+
${g.registerUniforms(x).declareVariables(v,b,w)}
|
|
1724
1724
|
${g.mainStart()}
|
|
1725
1725
|
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1726
1726
|
let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
|
|
1727
1727
|
|
|
1728
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:c,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p}),getShaderSource:m},{inputs:[t,n],outputs:[-1]})[0]},
|
|
1729
|
+
}`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:c,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p}),getShaderSource:m},{inputs:[t,n],outputs:[-1]})[0]},Kn=(e,t,n,i,o,l,u,c)=>{let h=l;if(u&&K.size(u.dims)>0){if(i===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return h=Qd(e,l,u,t,i,n*o,c),h=h.reshape([t,i,n,o]),n===1||i===1?h:e.compute(ct(h,Sa.perm),{inputs:[h],outputs:[-1]})[0]}else return l.dims.length===3&&(h=l.reshape([t,i,n,o])),n===1||i===1?h:e.compute(ct(h,Sa.perm),{inputs:[h],outputs:[-1]})[0]},Xd=(e,t)=>{let n=jd(e.inputs,t),i=e.inputs[0],o=Ft(e.inputs,1),l=Ft(e.inputs,2),u=Ft(e.inputs,3),c=Ft(e.inputs,4),h=Ft(e.inputs,5),p=Ft(e.inputs,6),m=Ft(e.inputs,7);if(i.dims.length===5)throw new Error("Packed QKV is not implemented");if(o?.dims.length===5)throw new Error("Packed KV is not implemented");let g=o&&l&&o.dims.length===4&&l.dims.length===4,w=Kn(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,i,u,0);if(g)return Gn(e,w,o,l,c,void 0,p,m,h,n);if(!o||!l)throw new Error("key and value must be provided");let v=Kn(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,o,u,n.hiddenSize),b=Kn(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,l,u,2*n.hiddenSize);Gn(e,w,v,b,c,void 0,p,m,h,n)}}),Jd,Zd,ec,tc,Ta,rc,sc,nc=S(()=>{Ie(),ke(),A(),we(),Jd=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Zd=(e,t)=>{let n=[],i=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>n.push(Number(o))),i=n.length),E({numOutputs:i,axis:t.axis,splitSizes:n})},ec=e=>`
|
|
1730
1730
|
fn calculateOutputIndex(index: u32) -> u32 {
|
|
1731
1731
|
for (var i: u32 = 0u; i < ${e}u; i += 1u ) {
|
|
1732
1732
|
if (index < ${Q("uniforms.size_in_split_axis","i",e)}) {
|
|
@@ -1738,13 +1738,13 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1738
1738
|
fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) {
|
|
1739
1739
|
${n.join(`
|
|
1740
1740
|
`)}
|
|
1741
|
-
}`},Ta=(e,t)=>{let n=e[0].dims,i=
|
|
1742
|
-
${
|
|
1741
|
+
}`},Ta=(e,t)=>{let n=e[0].dims,i=K.size(n),o=e[0].dataType,l=K.normalizeAxis(t.axis,n.length),u=new Array(t.numOutputs),c=F("input",o,n.length),h=new Array(t.numOutputs),p=[],m=[],g=0,w=[{type:12,data:i}];for(let b=0;b<t.numOutputs;b++){g+=t.splitSizes[b],h[b]=g;let x=n.slice();x[l]=t.splitSizes[b],m.push(x),u[b]=le(`output${b}`,o,x.length),p.push({dims:m[b],dataType:e[0].dataType})}w.push({type:12,data:h},...L(n,...m));let v=b=>`
|
|
1742
|
+
${b.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",h.length).declareVariables(c,...u)}
|
|
1743
1743
|
${ec(h.length)}
|
|
1744
1744
|
${tc(u)}
|
|
1745
1745
|
|
|
1746
|
-
${
|
|
1747
|
-
${
|
|
1746
|
+
${b.mainStart()}
|
|
1747
|
+
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}
|
|
1748
1748
|
|
|
1749
1749
|
var indices = ${c.offsetToIndices("global_idx")};
|
|
1750
1750
|
var index = ${c.indicesGet("indices",l)};
|
|
@@ -1754,7 +1754,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1754
1754
|
${c.indicesSet("indices",l,"index")};
|
|
1755
1755
|
}
|
|
1756
1756
|
writeBufferData(output_number, indices, global_idx);
|
|
1757
|
-
}`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:v,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(i/64)},programUniforms:w})}},rc=(e,t)=>{Jd(e.inputs);let n=e.inputs.length===1?t:Zd(e.inputs,t);e.compute(Ta(e.inputs,n),{inputs:[0]})},sc=e=>{let t=e.axis,n=e.splitSizes,i=e.numOutputs<0?n.length:e.numOutputs;if(i!==n.length)throw new Error("numOutputs and splitSizes length must be equal");return E({axis:t,numOutputs:i,splitSizes:n})}}),ic,
|
|
1757
|
+
}`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:v,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(i/64)},programUniforms:w})}},rc=(e,t)=>{Jd(e.inputs);let n=e.inputs.length===1?t:Zd(e.inputs,t);e.compute(Ta(e.inputs,n),{inputs:[0]})},sc=e=>{let t=e.axis,n=e.splitSizes,i=e.numOutputs<0?n.length:e.numOutputs;if(i!==n.length)throw new Error("numOutputs and splitSizes length must be equal");return E({axis:t,numOutputs:i,splitSizes:n})}}),ic,Ci,ac,oc=S(()=>{Ie(),ke(),A(),we(),ic=(e,t)=>{let[n,i,o,l]=e,{numHeads:u,rotaryEmbeddingDim:c}=t;if(n.dims.length!==3&&n.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!K.areEqual(i.dims,[])&&!K.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(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(l.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${l.dims.length}`);if(!K.areEqual(o.dims,l.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(c>0&&u===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let h=n.dims[0],p=n.dims[n.dims.length-2],m=o.dims[0],g=K.sizeFromDimension(n.dims,1)/p,w=c===0?o.dims[1]*2:g/u;if(c>w)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(i.dims.length===2){if(h!==i.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${i.dims[0]}`);if(p!==i.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${i.dims[1]}`)}if(p>m)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported");if(w/2!==o.dims[1]&&c/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`)},Ci=(e,t)=>{let{interleaved:n,numHeads:i,rotaryEmbeddingDim:o,scale:l}=t,u=e[0].dims[0],c=K.sizeFromDimension(e[0].dims,1),h=e[0].dims[e[0].dims.length-2],p=c/h,m=e[2].dims[1],g=o===0?m*2:p/i,w=new Array(u,h,p/g,g-m),v=K.computeStrides(w),b=[{type:1,data:l},{type:12,data:w},{type:12,data:v},...e[0].dims.length===3?new Array({type:12,data:[c,p,g,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[c,g,h*g,1]}):[],...L(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],x=M=>{let k=F("input",e[0].dataType,e[0].dims.length),$=F("position_ids",e[1].dataType,e[1].dims.length),P=F("cos_cache",e[2].dataType,e[2].dims.length),I=F("sin_cache",e[3].dataType,e[3].dims.length),B=le("output",e[0].dataType,e[0].dims.length);return M.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:w.length},{name:"global_strides",type:"u32",length:v.length},{name:"input_output_strides",type:"u32",length:v.length}]),`
|
|
1758
1758
|
${M.declareVariables(k,$,P,I,B)}
|
|
1759
1759
|
|
|
1760
1760
|
${M.mainStart(D)}
|
|
@@ -1780,8 +1780,8 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1780
1780
|
let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
|
|
1781
1781
|
${B.setByOffset("k",k.getByOffset("k"))}
|
|
1782
1782
|
}
|
|
1783
|
-
}`};return{name:"RotaryEmbedding",shaderCache:{hint:E({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(
|
|
1784
|
-
${m.registerUniforms(
|
|
1783
|
+
}`};return{name:"RotaryEmbedding",shaderCache:{hint:E({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(K.size(w)/D)},programUniforms:b})}},ac=(e,t)=>{ic(e.inputs,t),e.compute(Ci(e.inputs,t))}}),lc,uc,Ea,dc,cc,Nm=S(()=>{A(),Ie(),Zi(),Yd(),nc(),Ue(),oc(),we(),lc=(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 n=e[0],i=e[1],o=e[2],l=e[3],u=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(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=n.dims[0],h=n.dims[1],p=n.dims.length===3?n.dims[2]:t.numHeads*n.dims[4],m=h,g=0,w=!i||i.dims.length===0,v=Math.floor(w?p/(t.numHeads+2*t.kvNumHeads):p/t.numHeads);w&&(p=v*t.numHeads);let b=l&&l.dims.length!==0,x=u&&u.dims.length!==0;if(b&&l.dims.length===4&&l.dims[0]===c&&l.dims[1]!==t.kvNumHeads&&l.dims[2]===t.kvNumHeads&&l.dims[3]===v)throw new Error("BSNH pastKey/pastValue is not supported");if(b&&x){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(u.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');g=l.dims[2]}else if(b||x)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let M=1;if(i&&i.dims.length>0){if(n.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(n.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(n.dims[2]%i.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');m=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==v)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');m=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==v)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');m=i.dims[2]}}else{if(n.dims.length!==3&&n.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(n.dims.length===5&&(n.dims[2]!==t.numHeads||n.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');M=3}let k=0,$=!1,P=t.kvNumHeads?v*t.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(m!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');P=o.dims[2]}else{if(m!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');P=o.dims[1]*o.dims[3],$=!0}}let I=e.length>4?e[5]:void 0;if(I){if(I.dims.length===0)throw new Error("seqlens_k must be at least 1D, got scalar.");let B=I.dims.reduce((q,H)=>q*H,1);if(B!==c)throw new Error(`seqlens_k must have batch_size (${c}) elements, got ${B}.`);for(let q=0;q<I.dims.length;q++)if(I.dims[q]!==1&&I.dims[q]!==c)throw new Error(`seqlens_k has unexpected shape. Each dimension must be 1 or batch_size (${c}), got dims[${q}] = ${I.dims[q]}.`)}return{batchSize:c,sequenceLength:h,pastSequenceLength:g,kvSequenceLength:m,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:P,headSize:v,vHeadSize:Math.floor(P/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:k,scale:t.scale,broadcastResPosBias:!1,passPastInKv:$,qkvFormat:M}},uc=E({perm:[0,2,1,3]}),Ea=(e,t,n)=>{let i=t,o=n.kvNumHeads;return t.dims.length===3&&n.kvSequenceLength!==0&&(i=t.reshape([n.batchSize,n.kvSequenceLength,o,n.headSize]),i=e.compute(ct(i,uc.perm),{inputs:[i],outputs:[-1]})[0]),i},dc=(e,t,n,i)=>{let o=7,l=["type","type"],u=[e*t],c=e*t,h=[{type:12,data:c},{type:12,data:t},{type:12,data:e}],p=m=>{let g=F("seq_lens",n.dataType,n.dims),w=F("total_seq_lens",i.dataType,i.dims),v=le("pos_ids",o,u),b=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return`
|
|
1784
|
+
${m.registerUniforms(b).declareVariables(g,w,v)}
|
|
1785
1785
|
${m.mainStart()}
|
|
1786
1786
|
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1787
1787
|
let total_sequence_length = u32(${w.getByOffset("0")});
|
|
@@ -1811,10 +1811,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1811
1811
|
${v.setByOffset("global_idx","seqlen")}
|
|
1812
1812
|
};
|
|
1813
1813
|
}
|
|
1814
|
-
`};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:h}),getShaderSource:p}},cc=(e,t)=>{let n=lc(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],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,l=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,u=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,c=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,h=e.inputs.length>4?e.inputs[5]:void 0,p=e.inputs.length>5?e.inputs[6]:void 0,m=n.kvNumHeads?n.kvNumHeads:n.numHeads,g=E({axis:2,numOutputs:3,splitSizes:[n.numHeads*n.headSize,m*n.headSize,m*n.headSize]}),[w,v,
|
|
1814
|
+
`};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:h}),getShaderSource:p}},cc=(e,t)=>{let n=lc(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],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,l=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,u=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,c=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,h=e.inputs.length>4?e.inputs[5]:void 0,p=e.inputs.length>5?e.inputs[6]:void 0,m=n.kvNumHeads?n.kvNumHeads:n.numHeads,g=E({axis:2,numOutputs:3,splitSizes:[n.numHeads*n.headSize,m*n.headSize,m*n.headSize]}),[w,v,b]=!o&&!l?e.compute(Ta([i],g),{inputs:[i],outputs:[-1,-1,-1]}):[i,o,l],x,M;if(t.doRotary){let I=e.compute(dc(n.batchSize,n.sequenceLength,h,p),{inputs:[h,p],outputs:[-1]})[0],B=e.inputs[7],q=e.inputs[8],H=E({interleaved:t.rotaryInterleaved!==0,numHeads:n.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),ee=[w,I,B,q],ue=[-1];x=e.compute(Ci(ee,H),{inputs:ee,outputs:ue})[0],ee.splice(0,1,v);let _e=E({interleaved:t.rotaryInterleaved!==0,numHeads:n.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});M=e.compute(Ci(ee,_e),{inputs:ee,outputs:ue})[0]}let k=Kn(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,t.doRotary?x:w,void 0,0),$=Ea(e,t.doRotary?M:v,n),P=Ea(e,b,n);Gn(e,k,$,P,void 0,void 0,u,c,void 0,n,h,p)}}),$a,hc,pc,fc,Um=S(()=>{Ie(),ke(),Ue(),we(),$a=(e,t,n,i,o,l,u,c)=>{let h=V(l),p=h===1?"f32":`vec${h}f`,m=h===1?"vec2f":`mat2x${h}f`,g=o*u,w=64;g===1&&(w=256);let v=[o,u,l/h],b=[o,u,2],x=["rank","type","type"],M=[];M.push(...L(v,b));let k=$=>{let P=F("x",t.dataType,3,h),I=F("scale",n.dataType,n.dims),B=F("bias",i.dataType,i.dims),q=le("output",1,3,2),H=[P,I,B,q];return`
|
|
1815
1815
|
var<workgroup> workgroup_shared : array<${m}, ${w}>;
|
|
1816
1816
|
const workgroup_size = ${w}u;
|
|
1817
|
-
${$.declareVariables(...
|
|
1817
|
+
${$.declareVariables(...H)}
|
|
1818
1818
|
${$.mainStart(w)}
|
|
1819
1819
|
let batch = workgroup_index / uniforms.x_shape[1];
|
|
1820
1820
|
let channel = workgroup_index % uniforms.x_shape[1];
|
|
@@ -1845,7 +1845,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1845
1845
|
let channel_shift = f32(bias[channel]) - sum_final * channel_scale;
|
|
1846
1846
|
output[workgroup_index] = vec2f(channel_scale, channel_shift);
|
|
1847
1847
|
}
|
|
1848
|
-
}`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${h};${c};${w}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:
|
|
1848
|
+
}`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${h};${c};${w}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:b,dataType:1}],dispatchGroup:{x:g},programUniforms:M}),getShaderSource:k},{inputs:[t,n,i],outputs:[-1]})[0]},hc=(e,t,n)=>{let i=t[0].dims,o=i,l=2,u=i[0],c=i[1],h=K.sizeFromDimension(i,l),p=V(h),m=K.size(o)/p,g=$a(e,t[0],t[1],t[2],u,h,c,n.epsilon),w=[u,c,h/p],v=[u,c],b=["type","none"],x=M=>{let k=F("x",t[0].dataType,w.length,p),$=F("scale_shift",1,v.length,2),P=le("output",t[0].dataType,w.length,p),I=[k,$,P];return`
|
|
1849
1849
|
${M.registerUniform("output_size","u32").declareVariables(...I)}
|
|
1850
1850
|
${M.mainStart()}
|
|
1851
1851
|
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1855,7 +1855,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1855
1855
|
let scale_shift = ${$.getByIndices("vec2<u32>(batch, channel)")};
|
|
1856
1856
|
let value = ${k.getByOffset("global_idx")} * ${P.type.value}(scale_shift.x) + ${P.type.value}(scale_shift.y);
|
|
1857
1857
|
${P.setByOffset("global_idx","value")};
|
|
1858
|
-
}`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${p}`,inputDependencies:
|
|
1858
|
+
}`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${p}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...L(w,v,w)]}),getShaderSource:x},{inputs:[t[0],g]})},pc=(e,t,n)=>{let i=t[0].dims,o=i,l=i[0],u=i[i.length-1],c=K.sizeFromDimension(i,1)/u,h=V(u),p=K.size(o)/h,m=[{type:12,data:c},{type:12,data:Math.floor(u/h)}],g=["type","type"],w=!1,v=[0,i.length-1];for(let k=0;k<i.length-2;k++)w=w||i[k+1]!==1,v.push(k+1);w=w&&i[i.length-1]!==1;let b=w?e.compute(ct(e.inputs[0],v),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:i.length},(k,$)=>i[v[$]])),x=$a(e,b,t[1],t[2],l,c,u,n.epsilon),M=k=>{let $=G(t[0].dataType),P=h===1?"vec2f":`mat${h}x2f`,I=H=>{let ee=H===0?"x":"y",ue=h===1?"f32":`vec${h}f`;switch(h){case 1:return`${$}(${ue}(scale.${ee}))`;case 2:return`vec2<${$}>(${ue}(scale[0].${ee}, scale[1].${ee}))`;case 4:return`vec4<${$}>(${ue}(scale[0].${ee}, scale[1].${ee}, scale[2].${ee}, scale[3].${ee}))`;default:throw new Error(`Not supported compoents ${h}`)}},B=F("input",t[0].dataType,t[0].dims,h),q=le("output",t[0].dataType,o,h);return`
|
|
1859
1859
|
@group(0) @binding(0) var<storage, read> input : array<${B.type.storage}>;
|
|
1860
1860
|
@group(0) @binding(1) var<storage, read> scale_input : array<${P}>;
|
|
1861
1861
|
@group(0) @binding(2) var<storage, read_write> output : array<${q.type.storage}>;
|
|
@@ -1869,46 +1869,46 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1869
1869
|
let scale_offset = current_image_number * uniforms.C + current_channel_number;
|
|
1870
1870
|
let scale = scale_input[scale_offset];
|
|
1871
1871
|
output[global_idx] = fma(input[global_idx], ${I(0)}, ${I(1)});
|
|
1872
|
-
}`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${h}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:M},{inputs:[t[0],x]})},fc=(e,t)=>{t.format==="NHWC"?pc(e,e.inputs,t):hc(e,e.inputs,t)}}),mc,gc,yc,Fm=
|
|
1872
|
+
}`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${h}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:M},{inputs:[t[0],x]})},fc=(e,t)=>{t.format==="NHWC"?pc(e,e.inputs,t):hc(e,e.inputs,t)}}),mc,gc,yc,Fm=S(()=>{Ie(),ke(),we(),mc=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},gc=(e,t,n)=>{let i=t.simplified,o=e[0].dims,l=e[1],u=!i&&e[2],c=o,h=K.normalizeAxis(t.axis,o.length),p=K.sizeToDimension(o,h),m=K.sizeFromDimension(o,h),g=K.size(l.dims),w=u?K.size(u.dims):0;if(g!==m||u&&w!==m)throw new Error(`Size of X.shape()[axis:] == ${m}.
|
|
1873
1873
|
Size of scale and bias (if provided) must match this.
|
|
1874
|
-
Got scale size of ${g} and bias size of ${w}`);let v=[];for(let B=0;B<o.length;++B)B<h?v.push(o[B]):v.push(1);let
|
|
1875
|
-
${B.registerUniforms(ee).declareVariables(...
|
|
1874
|
+
Got scale size of ${g} and bias size of ${w}`);let v=[];for(let B=0;B<o.length;++B)B<h?v.push(o[B]):v.push(1);let b=V(m),x=["type","type"],M=[{type:12,data:p},{type:1,data:m},{type:12,data:Math.floor(m/b)},{type:1,data:t.epsilon}];u&&x.push("type");let k=n>1,$=n>2,P=B=>{let q=G(e[0].dataType),H=[F("x",e[0].dataType,e[0].dims,b),F("scale",l.dataType,l.dims,b)];u&&H.push(F("bias",u.dataType,u.dims,b)),H.push(le("output",e[0].dataType,c,b)),k&&H.push(le("mean_data_output",1,v)),$&&H.push(le("inv_std_output",1,v));let ee=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`
|
|
1875
|
+
${B.registerUniforms(ee).declareVariables(...H)}
|
|
1876
1876
|
${B.mainStart()}
|
|
1877
1877
|
${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}
|
|
1878
1878
|
let offset = global_idx * uniforms.norm_size_vectorized;
|
|
1879
|
-
var mean_vector = ${
|
|
1880
|
-
var mean_square_vector = ${
|
|
1879
|
+
var mean_vector = ${re("f32",b)};
|
|
1880
|
+
var mean_square_vector = ${re("f32",b)};
|
|
1881
1881
|
|
|
1882
1882
|
for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {
|
|
1883
|
-
let value = ${ie(q,
|
|
1883
|
+
let value = ${ie(q,b,"x[h + offset]")};
|
|
1884
1884
|
mean_vector += value;
|
|
1885
1885
|
mean_square_vector += value * value;
|
|
1886
1886
|
}
|
|
1887
|
-
let mean = ${Z("mean_vector",
|
|
1888
|
-
let inv_std_dev = inverseSqrt(${Z("mean_square_vector",
|
|
1887
|
+
let mean = ${Z("mean_vector",b)} / uniforms.norm_size;
|
|
1888
|
+
let inv_std_dev = inverseSqrt(${Z("mean_square_vector",b)} / uniforms.norm_size ${i?"":"- mean * mean"} + uniforms.epsilon);
|
|
1889
1889
|
|
|
1890
1890
|
for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {
|
|
1891
|
-
let f32input = ${ie(q,
|
|
1892
|
-
let f32scale = ${ie(q,
|
|
1893
|
-
output[j + offset] = ${
|
|
1894
|
-
${u?`+ ${ie(q,
|
|
1891
|
+
let f32input = ${ie(q,b,"x[j + offset]")};
|
|
1892
|
+
let f32scale = ${ie(q,b,"scale[j]")};
|
|
1893
|
+
output[j + offset] = ${H[0].type.value}((f32input ${i?"":"- mean"}) * inv_std_dev * f32scale
|
|
1894
|
+
${u?`+ ${ie(q,b,"bias[j]")}`:""}
|
|
1895
1895
|
);
|
|
1896
1896
|
}
|
|
1897
1897
|
|
|
1898
1898
|
${k?"mean_data_output[global_idx] = mean":""};
|
|
1899
1899
|
${$?"inv_std_output[global_idx] = inv_std_dev":""};
|
|
1900
|
-
}`},I=[{dims:c,dataType:e[0].dataType}];return k&&I.push({dims:v,dataType:1}),$&&I.push({dims:v,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${
|
|
1901
|
-
// reuse a data (pass ${
|
|
1902
|
-
var input_offset${
|
|
1903
|
-
var a_data${
|
|
1904
|
-
for (var j${
|
|
1905
|
-
a_data${
|
|
1906
|
-
input_offset${
|
|
1900
|
+
}`},I=[{dims:c,dataType:e[0].dataType}];return k&&I.push({dims:v,dataType:1}),$&&I.push({dims:v,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${b};${n};${i}`,inputDependencies:x},getRunData:()=>({outputs:I,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:M}),getShaderSource:P}},yc=(e,t)=>{mc(e.inputs),e.compute(gc(e.inputs,t,e.outputCount))}}),wc,vc,Vm=S(()=>{ke(),oa(),ca(),wc=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.")},vc=e=>{wc(e.inputs);let t=kr.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let n=t[t.length-1],i=e.inputs[0].dims[e.inputs[0].dims.length-1];if(n<8&&i<8)e.compute(aa(e.inputs,{activation:""},t));else{let o=t[t.length-2],l=K.size(e.inputs[0].dims.slice(0,-2)),u=K.size(e.inputs[1].dims.slice(0,-2));if(l!==1&&o===1&&u===1){let c=e.inputs[0].reshape([1,l,i]),h=e.inputs[1].reshape([1,i,n]),p=[1,l,n],m=[c,h];e.compute(Ti(m,{activation:""},t,p),{inputs:m})}else e.compute(Ti(e.inputs,{activation:""},t))}}}),_c,bc,Sc,Tc,Ec,Gm=S(()=>{Ie(),ke(),A(),we(),_c=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let n=e[0],i=n.dims.length;if(n.dims[i-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),l=t.blockSize/8*t.bits,u=e[1];if(!K.areEqual(u.dims,[t.n,o,l]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let c=e[2].dims;if(K.size(c)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let h=e[3].dims,p=t.n*(t.bits===8?o:Math.floor((o*t.bits+7)/8));if(K.size(h)!==p)throw new Error("zeroPoints input size error.")}},bc=(e,t)=>{let n=e[0].dims,i=n.length,o=n[i-2],l=t.k,u=t.n,c=n.slice(0,i-2),h=K.size(c),p=e[1].dims[2]/4,m=e[0].dataType,g=V(t.k),w=V(p),v=V(u),b=c.concat([o,u]),x=o>1&&u/v%2===0?2:1,M=K.size(b)/v/x,k=64,$=[],P=[h,o,l/g],I=K.convertShape(e[1].dims).slice();I.splice(-1,1,p/w),$.push(...L(P)),$.push(...L(I)),$.push(...L(e[2].dims)),e.length===4&&$.push(...L(K.convertShape(e[3].dims)));let B=[h,o,u/v];$.push(...L(B));let q=H=>{let ee=P.length,ue=F("a",e[0].dataType,ee,g),_e=F("b",12,I.length,w),Fe=F("scales",e[2].dataType,e[2].dims.length),Re=[ue,_e,Fe],Me=e.length===4?F("zero_points",12,e[3].dims.length):void 0;Me&&Re.push(Me);let Qe=B.length,ye=le("output",e[0].dataType,Qe,v),xe=G(e[0].dataType),Le=(()=>{switch(g){case 1:return`array<${xe}, 8>`;case 2:return`mat4x2<${xe}>`;case 4:return`mat2x4<${xe}>`;default:throw new Error(`${g}-component is not supported.`)}})(),Ge=Math.floor(32/t.bits),De=Math.floor(Ge/8),je=()=>{let Ae="";for(let $e=0;$e<De;$e++){let Dt=$e*t.bits*4,Xt=Dt+t.bits;Ae+=`
|
|
1901
|
+
// reuse a data (pass ${$e})
|
|
1902
|
+
var input_offset${$e>0?$e:""} = ${$e===0?ue.indicesToOffset(`${ue.type.indices}(batch, row, word_offset)`):"input_offset"};
|
|
1903
|
+
var a_data${$e>0?$e:""}: ${Le};
|
|
1904
|
+
for (var j${$e>0?$e:""}: u32 = 0; j${$e>0?$e:""} < ${8/g}; j${$e>0?$e:""}++) {
|
|
1905
|
+
a_data${$e>0?$e:""}[j${$e>0?$e:""}] = ${ue.getByOffset(`input_offset${$e>0?$e:""}`)};
|
|
1906
|
+
input_offset${$e>0?$e:""}++;
|
|
1907
1907
|
}
|
|
1908
1908
|
`;for(let _t=0;_t<v*x;_t++)Ae+=`
|
|
1909
1909
|
b_value = ${w===1?`b${_t}_data`:`b${_t}_data[i]`};
|
|
1910
1910
|
${t.bits===2?`{
|
|
1911
|
-
let half_word = b_value >> ${
|
|
1911
|
+
let half_word = b_value >> ${$e*16}u;
|
|
1912
1912
|
let byte_lo = half_word & 0xFFu;
|
|
1913
1913
|
let byte_hi = (half_word >> 8u) & 0xFFu;
|
|
1914
1914
|
let spread_word = (byte_lo & 0xFu) | ((byte_lo >> 4u) << 8u) | ((byte_hi & 0xFu) << 16u) | ((byte_hi >> 4u) << 24u);
|
|
@@ -1916,10 +1916,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1916
1916
|
b_value_upper = unpack4xU8((spread_word >> 2u) & b_mask);
|
|
1917
1917
|
}`:`b_value_lower = unpack4xU8((b_value >> ${Dt}u) & b_mask);
|
|
1918
1918
|
b_value_upper = unpack4xU8((b_value >> ${Xt}u) & b_mask);`}
|
|
1919
|
-
b_quantized_values = ${Le}(${Array.from({length:4},(Yt,nt)=>`${
|
|
1919
|
+
b_quantized_values = ${Le}(${Array.from({length:4},(Yt,nt)=>`${xe}(b_value_lower[${nt}]), ${xe}(b_value_upper[${nt}])`).join(", ")});
|
|
1920
1920
|
b_dequantized_values = ${g===1?`${Le}(${Array.from({length:8},(Yt,nt)=>`(b_quantized_values[${nt}] - ${Me?`zero_point${_t}`:"zero_point"}) * scale${_t}`).join(", ")});`:`(b_quantized_values - ${Le}(${Array(8).fill(`${Me?`zero_point${_t}`:"zero_point"}`).join(",")})) * scale${_t};`};
|
|
1921
|
-
workgroup_shared[local_id.x * ${x} + ${Math.floor(_t/v)}]${v>1?`[${_t%v}]`:""} += ${Array.from({length:8/g},(Yt,nt)=>`${g===1?`a_data${
|
|
1922
|
-
`}return Ae},
|
|
1921
|
+
workgroup_shared[local_id.x * ${x} + ${Math.floor(_t/v)}]${v>1?`[${_t%v}]`:""} += ${Array.from({length:8/g},(Yt,nt)=>`${g===1?`a_data${$e>0?$e:""}[${nt}] * b_dequantized_values[${nt}]`:`dot(a_data${$e>0?$e:""}[${nt}], b_dequantized_values[${nt}])`}`).join(" + ")};
|
|
1922
|
+
`}return Ae},oe=()=>{let Ae=`
|
|
1923
1923
|
var col_index = col * ${v};
|
|
1924
1924
|
${Me?`
|
|
1925
1925
|
let zero_point_values_per_byte: u32 = ${Math.floor(8/t.bits)}u;
|
|
@@ -1931,18 +1931,18 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1931
1931
|
var zero_point_bits_offset: u32;
|
|
1932
1932
|
var zero_point_word: u32;`:`
|
|
1933
1933
|
// The default zero point is ${Math.pow(2,t.bits-1)} for unsigned ${t.bits}-bit quantization.
|
|
1934
|
-
let zero_point = ${
|
|
1935
|
-
`;for(let
|
|
1936
|
-
let scale${
|
|
1934
|
+
let zero_point = ${xe}(${Math.pow(2,t.bits-1).toFixed(1)});`}
|
|
1935
|
+
`;for(let $e=0;$e<v*x;$e++)Ae+=`
|
|
1936
|
+
let scale${$e} = ${Fe.getByOffset("col_index * nBlocksPerCol + block")};
|
|
1937
1937
|
${Me?`
|
|
1938
1938
|
zero_point_byte_count = col_index * zero_point_bytes_per_col + (block / zero_point_values_per_byte);
|
|
1939
1939
|
zero_point_word_index = zero_point_byte_count >> 0x2u;
|
|
1940
1940
|
zero_point_byte_offset = zero_point_byte_count & 0x3u;
|
|
1941
1941
|
zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_sub_offset * ${t.bits}u);
|
|
1942
1942
|
zero_point_word = ${Me.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
1943
|
-
let zero_point${
|
|
1944
|
-
col_index += 1;`;return Ae},Oe=()=>{let Ae=`col_index = col * ${v};`;for(let
|
|
1945
|
-
let b${
|
|
1943
|
+
let zero_point${$e} = ${xe}((zero_point_word) & ${t.bits===2?"0x3u":"0xFu"});`:""}
|
|
1944
|
+
col_index += 1;`;return Ae},Oe=()=>{let Ae=`col_index = col * ${v};`;for(let $e=0;$e<v*x;$e++)Ae+=`
|
|
1945
|
+
let b${$e}_data = ${_e.getByIndices(`${_e.type.indices}(col_index, block, word)`)};
|
|
1946
1946
|
col_index += 1;`;return Ae+=`
|
|
1947
1947
|
var b_value: u32;
|
|
1948
1948
|
let b_mask: u32 = ${t.bits===2?"0x03030303u":"0x0F0F0F0Fu"};
|
|
@@ -1950,10 +1950,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1950
1950
|
var b_value_upper: vec4<u32>;
|
|
1951
1951
|
var b_quantized_values: ${Le};
|
|
1952
1952
|
var b_dequantized_values: ${Le};`,Ae};return`
|
|
1953
|
-
var<workgroup> workgroup_shared: array<${
|
|
1954
|
-
${
|
|
1955
|
-
${
|
|
1956
|
-
let output_indices = ${
|
|
1953
|
+
var<workgroup> workgroup_shared: array<${ye.type.value}, ${x*k}>;
|
|
1954
|
+
${H.declareVariables(...Re,ye)}
|
|
1955
|
+
${H.mainStart([k,1,1])}
|
|
1956
|
+
let output_indices = ${ye.offsetToIndices(`(global_idx / ${k}) * ${x}`)};
|
|
1957
1957
|
let col = output_indices[2];
|
|
1958
1958
|
let row = output_indices[1];
|
|
1959
1959
|
let batch = output_indices[0];
|
|
@@ -1962,11 +1962,11 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1962
1962
|
for (var block = local_id.x; block < nBlocksPerCol; block += ${k}) {
|
|
1963
1963
|
//process one block
|
|
1964
1964
|
var word_offset: u32 = block * ${t.blockSize/g};
|
|
1965
|
-
${
|
|
1965
|
+
${oe()}
|
|
1966
1966
|
for (var word: u32 = 0; word < ${p}; word += ${w}) {
|
|
1967
1967
|
${Oe()}
|
|
1968
1968
|
for (var i: u32 = 0; i < ${w}; i++) {
|
|
1969
|
-
${
|
|
1969
|
+
${je()}
|
|
1970
1970
|
word_offset += ${Ge/g};
|
|
1971
1971
|
}
|
|
1972
1972
|
}
|
|
@@ -1974,24 +1974,24 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1974
1974
|
workgroupBarrier();
|
|
1975
1975
|
|
|
1976
1976
|
if (local_id.x < ${x}) {
|
|
1977
|
-
var output_value: ${
|
|
1977
|
+
var output_value: ${ye.type.value} = ${ye.type.value}(0);
|
|
1978
1978
|
var workgroup_shared_offset: u32 = local_id.x;
|
|
1979
1979
|
for (var b: u32 = 0u; b < ${k}u; b++) {
|
|
1980
1980
|
output_value += workgroup_shared[workgroup_shared_offset];
|
|
1981
1981
|
workgroup_shared_offset += ${x};
|
|
1982
1982
|
}
|
|
1983
|
-
${
|
|
1983
|
+
${ye.setByIndices(`${ye.type.indices}(batch, row, col + local_id.x)`,"output_value")};
|
|
1984
1984
|
}
|
|
1985
|
-
}`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${g};${w};${v};${x};${k}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:
|
|
1986
|
-
let a_data0 = vec4<${
|
|
1987
|
-
let a_data1 = vec4<${
|
|
1988
|
-
let a_data0 = vec4<${
|
|
1989
|
-
let a_data1 = vec4<${
|
|
1985
|
+
}`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${g};${w};${v};${x};${k}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:b,dataType:m}],dispatchGroup:{x:M},programUniforms:$}),getShaderSource:q}},Sc=(e,t)=>{let n=e[0].dims,i=n.length,o=n[i-2],l=t.k,u=t.n,c=n.slice(0,i-2),h=K.size(c),p=e[1].dims[2]/4,m=e[0].dataType,g=V(t.k),w=V(p),v=c.concat([o,u]),b=128,x=u%8===0?8:u%4===0?4:1,M=b/x,k=Math.floor(32/t.bits),$=M*w*k,P=$/g,I=$/t.blockSize,B=K.size(v)/x,q=[],H=[h,o,l/g],ee=K.convertShape(e[1].dims).slice();ee.splice(-1,1,p/w),q.push(...L(H)),q.push(...L(ee)),q.push(...L(e[2].dims)),e.length===4&&q.push(...L(K.convertShape(e[3].dims)));let ue=[h,o,u];q.push(...L(ue));let _e=Fe=>{let Re=H.length,Me=F("a",e[0].dataType,Re,g),Qe=F("b",12,ee.length,w),ye=F("scales",e[2].dataType,e[2].dims.length),xe=[Me,Qe,ye],Le=e.length===4?F("zero_points",12,e[3].dims.length):void 0;Le&&xe.push(Le);let Ge=ue.length,De=le("output",e[0].dataType,Ge),je=G(e[0].dataType),oe=()=>{switch(g){case 1:return`
|
|
1986
|
+
let a_data0 = vec4<${je}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);
|
|
1987
|
+
let a_data1 = vec4<${je}>(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<${je}>(sub_a[word_offset], sub_a[word_offset + 1]);
|
|
1989
|
+
let a_data1 = vec4<${je}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`
|
|
1990
1990
|
let a_data0 = sub_a[word_offset];
|
|
1991
1991
|
let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${g}-component is not supported.`)}};return`
|
|
1992
1992
|
var<workgroup> sub_a: array<${Me.type.value}, ${P}>;
|
|
1993
1993
|
var<workgroup> inter_results: array<array<${De.type.value}, ${M}>, ${x}>;
|
|
1994
|
-
${Fe.declareVariables(
|
|
1994
|
+
${Fe.declareVariables(...xe,De)}
|
|
1995
1995
|
${Fe.mainStart([M,x,1])}
|
|
1996
1996
|
let output_indices = ${De.offsetToIndices(`workgroup_index * ${x}`)};
|
|
1997
1997
|
let col = output_indices[2];
|
|
@@ -2004,7 +2004,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2004
2004
|
for (var tile: u32 = 0; tile < num_tiles; tile += 1) {
|
|
2005
2005
|
let a_col_start = tile * ${P};
|
|
2006
2006
|
// load one tile A data into shared memory.
|
|
2007
|
-
for (var a_offset = local_idx; a_offset < ${P}; a_offset += ${
|
|
2007
|
+
for (var a_offset = local_idx; a_offset < ${P}; a_offset += ${b})
|
|
2008
2008
|
{
|
|
2009
2009
|
let a_col = a_col_start + a_offset;
|
|
2010
2010
|
if (a_col < uniforms.a_shape[2])
|
|
@@ -2028,18 +2028,18 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2028
2028
|
let zero_point_sub_offset: u32 = block % zero_point_values_per_byte;
|
|
2029
2029
|
let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_sub_offset * ${t.bits}u);
|
|
2030
2030
|
let zero_point_word = ${Le.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
2031
|
-
let zero_point = ${
|
|
2031
|
+
let zero_point = ${je}((zero_point_word) & ${t.bits===2?"0x3u":"0xFu"});`:`
|
|
2032
2032
|
// The default zero point is ${Math.pow(2,t.bits-1)} for unsigned ${t.bits}-bit quantization.
|
|
2033
|
-
let zero_point = ${
|
|
2034
|
-
let scale = ${
|
|
2035
|
-
let b_data = ${
|
|
2033
|
+
let zero_point = ${je}(${Math.pow(2,t.bits-1).toFixed(1)});`}
|
|
2034
|
+
let scale = ${ye.getByOffset("b_row * n_blocks_per_col + block")};
|
|
2035
|
+
let b_data = ${Qe.getByIndices(`${Qe.type.indices}(b_row, block, 0)`)};
|
|
2036
2036
|
var word_offset = local_id.x * ${t.blockSize/g};
|
|
2037
2037
|
for (var i: u32 = 0; i < ${w}; i++) {
|
|
2038
2038
|
let b_value = ${w===1?"b_data":"b_data[i]"};
|
|
2039
|
-
${(()=>{let Oe=Math.floor(k/8),Ae="";for(let
|
|
2040
|
-
${
|
|
2039
|
+
${(()=>{let Oe=Math.floor(k/8),Ae="";for(let $e=0;$e<Oe;$e++){let Dt=$e*t.bits*4,Xt=Dt+t.bits;Ae+=`
|
|
2040
|
+
${oe()}
|
|
2041
2041
|
{${t.bits===2?`
|
|
2042
|
-
let half_word = b_value >> ${
|
|
2042
|
+
let half_word = b_value >> ${$e*16}u;
|
|
2043
2043
|
let byte_lo = half_word & 0xFFu;
|
|
2044
2044
|
let byte_hi = (half_word >> 8u) & 0xFFu;
|
|
2045
2045
|
let spread_word = (byte_lo & 0xFu) | ((byte_lo >> 4u) << 8u) | ((byte_hi & 0xFu) << 16u) | ((byte_hi >> 4u) << 24u);
|
|
@@ -2047,8 +2047,8 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2047
2047
|
let b_value_upper = unpack4xU8((spread_word >> 2u) & 0x03030303u);`:`
|
|
2048
2048
|
let b_value_lower = unpack4xU8((b_value >> ${Dt}u) & 0x0F0F0F0Fu);
|
|
2049
2049
|
let b_value_upper = unpack4xU8((b_value >> ${Xt}u) & 0x0F0F0F0Fu);`}
|
|
2050
|
-
let b_quantized_values = mat2x4<${
|
|
2051
|
-
let b_dequantized_values = (b_quantized_values - mat2x4<${
|
|
2050
|
+
let b_quantized_values = mat2x4<${je}>(${Array.from({length:4},(_t,Yt)=>`${je}(b_value_lower[${Yt}]), ${je}(b_value_upper[${Yt}])`).join(", ")});
|
|
2051
|
+
let b_dequantized_values = (b_quantized_values - mat2x4<${je}>(${Array(8).fill("zero_point").join(",")})) * scale;
|
|
2052
2052
|
inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(_t,Yt)=>`${`dot(a_data${Yt}, b_dequantized_values[${Yt}])`}`).join(" + ")};
|
|
2053
2053
|
}
|
|
2054
2054
|
word_offset += ${8/g};`}return Ae})()}
|
|
@@ -2066,7 +2066,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2066
2066
|
${De.setByIndices(`${De.type.indices}(batch, row, col + local_idx)`,"output_value")}
|
|
2067
2067
|
}
|
|
2068
2068
|
}
|
|
2069
|
-
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${g};${w};${M};${x}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:v,dataType:m}],dispatchGroup:{x:B},programUniforms:q}),getShaderSource:_e}},Tc=(e,t)=>{_c(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Sc(e.inputs,t)):e.compute(bc(e.inputs,t))},Ec=e=>E(e)}),$c,xc,Cc,kc,Rc,Ac,Ic,Mc,Pc,qm=
|
|
2069
|
+
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${g};${w};${M};${x}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:v,dataType:m}],dispatchGroup:{x:B},programUniforms:q}),getShaderSource:_e}},Tc=(e,t)=>{_c(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Sc(e.inputs,t)):e.compute(bc(e.inputs,t))},Ec=e=>E(e)}),$c,xc,Cc,kc,Rc,Ac,Ic,Mc,Pc,qm=S(()=>{Ie(),ke(),we(),$c=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].")}},xc=(e,t,n)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2070
2070
|
k = i32(${e.indicesGet("indices",o)}) - ${Q("uniforms.pads",o,n)};
|
|
2071
2071
|
if (k < 0) {
|
|
2072
2072
|
break;
|
|
@@ -2129,8 +2129,8 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2129
2129
|
var k = 0;
|
|
2130
2130
|
${i}
|
|
2131
2131
|
value = x[offset];
|
|
2132
|
-
`},Ac=(e,t,n)=>{switch(n.mode){case 0:return xc(e,t,n.pads.length);case 1:return Cc(e,t,n.pads.length);case 2:return kc(e,t,n.pads.length);case 3:return Rc(e,t,n.pads.length);default:throw new Error("Invalid mode")}},Ic=(e,t)=>{let n=
|
|
2133
|
-
${p.registerUniforms(
|
|
2132
|
+
`},Ac=(e,t,n)=>{switch(n.mode){case 0:return xc(e,t,n.pads.length);case 1:return Cc(e,t,n.pads.length);case 2:return kc(e,t,n.pads.length);case 3:return Rc(e,t,n.pads.length);default:throw new Error("Invalid mode")}},Ic=(e,t)=>{let n=K.padShape(e[0].dims.slice(),t.pads),i=e[0].dims,o=K.size(n),l=[{type:12,data:o},{type:6,data:t.pads}],u=e.length>=3&&e[2].data;t.mode===0&&l.push({type:u?e[2].dataType:1,data:t.value}),l.push(...L(e[0].dims,n));let c=["rank"],h=p=>{let m=le("output",e[0].dataType,n.length),g=F("x",e[0].dataType,i.length),w=g.type.value,v=Ac(m,i.length,t),b=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&b.push({name:"constant_value",type:u?w:"f32"}),`
|
|
2133
|
+
${p.registerUniforms(b).declareVariables(g,m)}
|
|
2134
2134
|
${p.mainStart()}
|
|
2135
2135
|
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2136
2136
|
|
|
@@ -2139,7 +2139,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2139
2139
|
var value = ${w}(0);
|
|
2140
2140
|
${v}
|
|
2141
2141
|
output[global_idx] = value;
|
|
2142
|
-
}`};return{name:"Pad",shaderCache:{hint:`${t.mode}${u}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(
|
|
2142
|
+
}`};return{name:"Pad",shaderCache:{hint:`${t.mode}${u}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(K.size(n)/64)},programUniforms:l}),getShaderSource:h}},Mc=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),i=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,l=new Int32Array(2*o).fill(0);if(e.length>=4){let c=e[3].getBigInt64Array();for(let h=0;h<c.length;h++)l[Number(c[h])]=Number(n[h]),l[Number(c[h])+o]=Number(n[h+c.length])}else n.forEach((c,h)=>l[Number(h)]=Number(c));let u=[];return l.forEach(c=>u.push(c)),{mode:t.mode,value:i,pads:u}}else return t},Pc=(e,t)=>{$c(e.inputs);let n=Mc(e.inputs,t);e.compute(Ic(e.inputs,n),{inputs:[0]})}}),Qn,xa,Ca,ka,Ra,Oc,Dc,Aa,Ia,zc,Lc,Ma,Bc,Nc,Pa,Uc,Fc,Vc,Gc,Wm=S(()=>{yt(),Ie(),ke(),we(),Qn=e=>{if(me.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},xa=(e,t,n)=>{let i=t.format==="NHWC",o=e.dims.slice();i&&o.splice(1,0,o.pop());let l=Object.hasOwnProperty.call(t,"dilations"),u=t.kernelShape.slice(),c=t.strides.slice(),h=l?t.dilations.slice():[],p=t.pads.slice();rs.adjustPoolAttributes(n,o,u,c,h,p);let m=rs.computePoolOutputShape(n,o,c,h,u,p,t.autoPad),g=Object.assign({},t);l?Object.assign(g,{kernelShape:u,strides:c,pads:p,dilations:h,cacheKey:t.cacheKey}):Object.assign(g,{kernelShape:u,strides:c,pads:p,cacheKey:t.cacheKey});let w=m.slice();return w.push(w.splice(1,1)[0]),[g,i?w:m]},Ca=(e,t)=>{let n=t.format==="NHWC",i=K.size(e),o=K.size(t.kernelShape),l=[{type:12,data:i},{type:12,data:o}],u=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let c=t.kernelShape[t.kernelShape.length-1],h=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],g=!!(p+m);l.push({type:12,data:c},{type:12,data:h},{type:12,data:p},{type:12,data:m}),u.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let w=!1;if(t.kernelShape.length===2){let v=t.kernelShape[t.kernelShape.length-2],b=t.strides[t.strides.length-2],x=t.pads[t.pads.length/2-2],M=t.pads[t.pads.length-2];w=!!(x+M),l.push({type:12,data:v},{type:12,data:b},{type:12,data:x},{type:12,data:M}),u.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[l,u,!0,g,w]}else{if(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let c=K.computeStrides(t.kernelShape);l.push({type:12,data:c},{type:12,data:t.pads},{type:12,data:t.strides}),u.push({name:"kernelStrides",type:"u32",length:c.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let h=t.pads.reduce((p,m)=>p+m);return[l,u,!!h,!1,!1]}},ka=(e,t,n,i,o,l,u,c,h,p,m,g)=>{let w=o.format==="NHWC",v=t.type.value,b=le("output",t.type.tensor,i);if(o.kernelShape.length<=2){let x="",M="",k="",$=n-(w?2:1);if(m?x=`
|
|
2143
2143
|
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2144
2144
|
xIndices[${$}] = indices[${$}] * uniforms.sw - uniforms.pwStart + i;
|
|
2145
2145
|
if (xIndices[${$}] < 0 || xIndices[${$}]
|
|
@@ -2167,13 +2167,13 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2167
2167
|
`,k=`
|
|
2168
2168
|
}
|
|
2169
2169
|
`}return`
|
|
2170
|
-
${e.registerUniforms(h).declareVariables(t,
|
|
2170
|
+
${e.registerUniforms(h).declareVariables(t,b)}
|
|
2171
2171
|
|
|
2172
2172
|
${e.mainStart()}
|
|
2173
2173
|
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2174
2174
|
|
|
2175
|
-
let indices = ${
|
|
2176
|
-
var xIndices = ${
|
|
2175
|
+
let indices = ${b.offsetToIndices("global_idx")};
|
|
2176
|
+
var xIndices = ${b.offsetToIndices("global_idx")};
|
|
2177
2177
|
|
|
2178
2178
|
var value = ${v}(${c});
|
|
2179
2179
|
var pad = 0;
|
|
@@ -2198,12 +2198,12 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2198
2198
|
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2199
2199
|
${l}
|
|
2200
2200
|
`,`
|
|
2201
|
-
${e.registerUniforms(h).declareVariables(t,
|
|
2201
|
+
${e.registerUniforms(h).declareVariables(t,b)}
|
|
2202
2202
|
|
|
2203
2203
|
${e.mainStart()}
|
|
2204
2204
|
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2205
|
-
let indices = ${
|
|
2206
|
-
var xIndices = ${
|
|
2205
|
+
let indices = ${b.offsetToIndices("global_idx")};
|
|
2206
|
+
var xIndices = ${b.offsetToIndices("global_idx")};
|
|
2207
2207
|
|
|
2208
2208
|
var offsets: array<u32, ${x}>;
|
|
2209
2209
|
|
|
@@ -2228,10 +2228,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2228
2228
|
${u}
|
|
2229
2229
|
|
|
2230
2230
|
output[global_idx] = value;
|
|
2231
|
-
}`}},Ra=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Oc=e=>`${Ra(e)};${e.countIncludePad}`,Dc=e=>`${Ra(e)};${e.storageOrder};${e.dilations}`,Aa=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}),Ia=(e,t,n,i)=>{let[o,l]=xa(t,i,n),u=F("x",t.dataType,t.dims.length),c=u.type.value,h="value += x_val;",p="";o.countIncludePad?p+=`value /= ${c}(uniforms.kernelSize);`:p+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[m,g,w,v,
|
|
2231
|
+
}`}},Ra=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Oc=e=>`${Ra(e)};${e.countIncludePad}`,Dc=e=>`${Ra(e)};${e.storageOrder};${e.dilations}`,Aa=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}),Ia=(e,t,n,i)=>{let[o,l]=xa(t,i,n),u=F("x",t.dataType,t.dims.length),c=u.type.value,h="value += x_val;",p="";o.countIncludePad?p+=`value /= ${c}(uniforms.kernelSize);`:p+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[m,g,w,v,b]=Ca(l,o);m.push(...L(t.dims,l));let x=["rank"];return{name:e,shaderCache:{hint:`${i.cacheKey};${w};${v};${b}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(K.size(l)/64)},programUniforms:m}),getShaderSource:M=>ka(M,u,t.dims.length,l.length,o,h,p,0,g,w,v,b)}},zc=e=>{let t=e.count_include_pad!==0,n=Aa(e);if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let i={countIncludePad:t,...n,cacheKey:""};return{...i,cacheKey:Oc(i)}},Lc=(e,t)=>{Qn(e.inputs),e.compute(Ia("AveragePool",e.inputs[0],!1,t))},Ma={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Bc=e=>{let t=e.format;return{format:t,...Ma,cacheKey:t}},Nc=(e,t)=>{Qn(e.inputs),e.compute(Ia("GlobalAveragePool",e.inputs[0],!0,t))},Pa=(e,t,n,i)=>{let[o,l]=xa(t,i,n),u=`
|
|
2232
2232
|
value = max(x_val, value);
|
|
2233
|
-
`,c="",h=F("x",t.dataType,t.dims.length),p=["rank"],[m,g,w,v,
|
|
2234
|
-
${Fe.registerUniforms(Re).declareVariables(...
|
|
2233
|
+
`,c="",h=F("x",t.dataType,t.dims.length),p=["rank"],[m,g,w,v,b]=Ca(l,o);return m.push(...L(t.dims,l)),{name:e,shaderCache:{hint:`${i.cacheKey};${w};${v};${b}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(K.size(l)/64)},programUniforms:m}),getShaderSource:x=>ka(x,h,t.dims.length,l.length,o,u,c,t.dataType===10?-65504:-1e5,g,w,v,b)}},Uc=(e,t)=>{Qn(e.inputs),e.compute(Pa("MaxPool",e.inputs[0],!1,t))},Fc=e=>{let t=e.storage_order,n=e.dilations,i=Aa(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 o={storageOrder:t,dilations:n,...i,cacheKey:""};return{...o,cacheKey:Dc(o)}},Vc=e=>{let t=e.format;return{format:t,...Ma,cacheKey:t}},Gc=(e,t)=>{Qn(e.inputs),e.compute(Pa("GlobalMaxPool",e.inputs[0],!0,t))}}),qc,Wc,Hc,jc,Hm=S(()=>{Ie(),ke(),A(),we(),qc=(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((n,i)=>n===e[2].dims[i]).reduce((n,i)=>n&&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((o,l)=>l===t.axis||o===e[0].dims[l]).reduce((o,l)=>o&&l,!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 n=e[0].dims[t.axis],i=e[1].dims[t.axis];if(t.blockSize<Math.ceil(n/i)||t.blockSize>Math.ceil(n/(i-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Wc=(e,t)=>{let n=K.normalizeAxis(t.axis,e[0].dims.length),i=e[0].dataType,o=i===3,l=e[0].dims,u=e[1].dataType,c=K.size(l),h=i===3||i===2,p=h?[Math.ceil(K.size(e[0].dims)/4)]:e[0].dims,m=e[1].dims,g=e.length>2?e[2]:void 0,w=g?h?[Math.ceil(K.size(g.dims)/4)]:g.dims:void 0,v=m.length===0||m.length===1&&m[0]===1,b=v===!1&&m.length===1,x=V(c),M=v&&(!h||x===4),k=M?x:1,$=M&&!h?x:1,P=F("input",h?12:i,p.length,$),I=F("scale",u,m.length),B=g?F("zero_point",h?12:i,w.length):void 0,q=le("output",u,l.length,k),H=[P,I];B&&H.push(B);let ee=[p,m];g&&ee.push(w);let ue=[{type:12,data:c/k},{type:12,data:n},{type:12,data:t.blockSize},...L(...ee,l)],_e=Fe=>{let Re=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
2234
|
+
${Fe.registerUniforms(Re).declareVariables(...H,q)}
|
|
2235
2235
|
${Fe.mainStart()}
|
|
2236
2236
|
${Fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2237
2237
|
let output_indices = ${q.offsetToIndices("global_idx")};
|
|
@@ -2243,7 +2243,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2243
2243
|
let x_value = ${k===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${P.getByOffset("global_idx")};`};
|
|
2244
2244
|
|
|
2245
2245
|
// Set scale input
|
|
2246
|
-
${v?`let scale_value= ${I.getByOffset("0")}`:
|
|
2246
|
+
${v?`let scale_value= ${I.getByOffset("0")}`:b?`
|
|
2247
2247
|
let scale_index = ${q.indicesGet("output_indices","uniforms.axis")};
|
|
2248
2248
|
let scale_value= ${I.getByOffset("scale_index")};`:`
|
|
2249
2249
|
var scale_indices: ${I.type.indices} = output_indices;
|
|
@@ -2255,7 +2255,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2255
2255
|
${B?v?h?`
|
|
2256
2256
|
let zero_point_input = ${B.getByOffset("0")};
|
|
2257
2257
|
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2258
|
-
let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${B.getByOffset("0")}`:
|
|
2258
|
+
let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${B.getByOffset("0")}`:b?h?`
|
|
2259
2259
|
let zero_point_index = ${q.indicesGet("output_indices","uniforms.axis")};
|
|
2260
2260
|
let zero_point_input = ${B.getByOffset("zero_point_index / 4")};
|
|
2261
2261
|
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
@@ -2268,12 +2268,12 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2268
2268
|
let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${B.getByIndices("scale_indices")};`:`let zero_point_value = ${h?o?"i32":"u32":P.type.value}(0);`};
|
|
2269
2269
|
// Compute and write output
|
|
2270
2270
|
${q.setByOffset("global_idx",`${q.type.value}(x_value - zero_point_value) * scale_value`)};
|
|
2271
|
-
}`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:B?["rank","rank","rank"]:["rank","rank"]},getShaderSource:_e,getRunData:()=>({outputs:[{dims:l,dataType:u}],dispatchGroup:{x:Math.ceil(c/k/64),y:1,z:1},programUniforms:ue})}},Hc=(e,t)=>{qc(e.inputs,t),e.compute(Wc(e.inputs,t))},
|
|
2271
|
+
}`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:B?["rank","rank","rank"]:["rank","rank"]},getShaderSource:_e,getRunData:()=>({outputs:[{dims:l,dataType:u}],dispatchGroup:{x:Math.ceil(c/k/64),y:1,z:1},programUniforms:ue})}},Hc=(e,t)=>{qc(e.inputs,t),e.compute(Wc(e.inputs,t))},jc=e=>E({axis:e.axis,blockSize:e.blockSize})}),Kc,Qc,Xc,jm=S(()=>{yt(),Ie(),we(),Kc=(e,t,n)=>{let i=e===t,o=e<t&&n<0,l=e>t&&n>0;if(i||o||l)throw new Error("Range these inputs' contents are invalid.")},Qc=(e,t,n,i)=>{let o=Math.abs(Math.ceil((t-e)/n)),l=[o],u=o,c=[{type:12,data:u},{type:i,data:e},{type:i,data:n},...L(l)],h=p=>{let m=le("output",i,l.length),g=m.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:g},{name:"delta",type:g}];return`
|
|
2272
2272
|
${p.registerUniforms(w).declareVariables(m)}
|
|
2273
2273
|
${p.mainStart()}
|
|
2274
2274
|
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2275
2275
|
output[global_idx] = uniforms.start + ${g}(global_idx) * uniforms.delta;
|
|
2276
|
-
}`};return{name:"Range",shaderCache:{hint:`${i}`},getShaderSource:h,getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c})}},Xc=e=>{let t=0,n=0,i=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],i=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],i=e.inputs[2].getFloat32Array()[0]),
|
|
2276
|
+
}`};return{name:"Range",shaderCache:{hint:`${i}`},getShaderSource:h,getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c})}},Xc=e=>{let t=0,n=0,i=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],i=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],i=e.inputs[2].getFloat32Array()[0]),me.webgpu.validateInputContent&&Kc(t,n,i),e.compute(Qc(t,n,i,e.inputs[0].dataType),{inputs:[]})}}),Yc,Jc,Zc,eh,Km=S(()=>{Ie(),ke(),A(),we(),Yc=(e,t,n,i)=>{if(e!=="none"&&i!=="i32"&&i!=="u32"&&i!=="f32")throw new Error(`Input ${i} is not supported with reduction ${e}.`);let o=`{
|
|
2277
2277
|
var oldValue = 0;
|
|
2278
2278
|
loop {
|
|
2279
2279
|
let newValueF32 =`,l=`;
|
|
@@ -2286,8 +2286,8 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2286
2286
|
}
|
|
2287
2287
|
}`;switch(e){case"none":return`${t}=${n};`;case"add":return i==="i32"||i==="u32"?`atomicAdd(&${t}, bitcast<${i}>(${n}));`:`
|
|
2288
2288
|
${o}bitcast<${i}>(oldValue) + (${n})${l}`;case"max":return i==="i32"||i==="u32"?`atomicMax(&${t}, bitcast<${i}>(${n}));`:`
|
|
2289
|
-
${o}max(bitcast<f32>(oldValue), (${n}))${l}`;case"min":return i==="i32"||i==="u32"?`atomicMin(&${t}, bitcast<${i}>(${n}));`:`${o}min(bitcast<${i}>(oldValue), (${n}))${l}`;case"mul":return`${o}(bitcast<${i}>(oldValue) * (${n}))${l}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Jc=(e,t)=>{let n=e[0].dims,i=e[1].dims,o=n,l=1,u=Math.ceil(
|
|
2290
|
-
${g.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(w,v,
|
|
2289
|
+
${o}max(bitcast<f32>(oldValue), (${n}))${l}`;case"min":return i==="i32"||i==="u32"?`atomicMin(&${t}, bitcast<${i}>(${n}));`:`${o}min(bitcast<${i}>(oldValue), (${n}))${l}`;case"mul":return`${o}(bitcast<${i}>(oldValue) * (${n}))${l}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Jc=(e,t)=>{let n=e[0].dims,i=e[1].dims,o=n,l=1,u=Math.ceil(K.sizeToDimension(i,i.length-1)/l),c=i[i.length-1],h=K.sizeFromDimension(n,c),p=[{type:12,data:u},{type:12,data:c},{type:12,data:h},...L(e[1].dims,e[2].dims,o)],m=g=>{let w=F("indices",e[1].dataType,e[1].dims.length),v=F("updates",e[2].dataType,e[2].dims.length,l),b=t.reduction!=="none"&&t.reduction!==""?ut("output",e[0].dataType,o.length):le("output",e[0].dataType,o.length,l);return`
|
|
2290
|
+
${g.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(w,v,b)}
|
|
2291
2291
|
${g.mainStart()}
|
|
2292
2292
|
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2293
2293
|
var data_offset = 0u;
|
|
@@ -2316,10 +2316,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2316
2316
|
|
|
2317
2317
|
for (var i = 0u; i < uniforms.num_updates_elements; i++) {
|
|
2318
2318
|
let value = updates[uniforms.num_updates_elements * global_idx + i];
|
|
2319
|
-
${Yc(t.reduction,"output[data_offset + i]","value",
|
|
2319
|
+
${Yc(t.reduction,"output[data_offset + i]","value",b.type.value)}
|
|
2320
2320
|
}
|
|
2321
2321
|
|
|
2322
|
-
}`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:m}},Zc=e=>E({reduction:e.reduction}),eh=(e,t)=>{e.compute(Jc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),th,rh,sh,Oa,nh,ih,ah,oh,lh,uh,dh,ch,Da,hh,ph,fh,mh,gh,yh,wh,Qm=
|
|
2322
|
+
}`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:m}},Zc=e=>E({reduction:e.reduction}),eh=(e,t)=>{e.compute(Jc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),th,rh,sh,Oa,nh,ih,ah,oh,lh,uh,dh,ch,Da,hh,ph,fh,mh,gh,yh,wh,Qm=S(()=>{Ie(),ke(),A(),we(),th=(e,t)=>{if(e.every(n=>n>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
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")}},rh=(e,t,n)=>{t.every(o=>o>=0&&o<n||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")}));let i=new Array(n).fill(1);return t.forEach((o,l)=>i[o]=e[l]),i},sh=(e,t,n,i,o,l)=>{let[u,c,h]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(u>0&&e.length>u&&e[u].dims.length>0)e[u].getFloat32Array().forEach(m=>l.push(m));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(c>0&&e.length>c&&e[c].dims.length===1&&e[c].dims[0]>0){if(e[c].getFloat32Array().forEach(m=>i.push(m)),i.length!==0&&i.length!==p&&n>=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");th(i,t),t.axes.length>0&&rh(i,t.axes,p).forEach((m,g)=>i[g]=m)}if(h>0&&e.length>h&&e[h].dims.length===1&&e[h].dims[0]>0&&(e[h].getBigInt64Array().forEach(m=>o.push(Number(m))),o.length!==0&&o.length!==p&&n>=18&&o.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(o.length!==0&&o.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 o<"u"&&i.length>0&&o.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},Oa=(e,t,n,i)=>`
|
|
2324
2324
|
// The whole part and the fractional part are calculated separately due to inaccuracy of floating
|
|
2325
2325
|
// point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
|
|
@@ -2455,7 +2455,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2455
2455
|
dy2 = 0.5;
|
|
2456
2456
|
}
|
|
2457
2457
|
return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);
|
|
2458
|
-
}`},ph=(e,t,n,i,o,l,u,c,h,p)=>{let m=n.length===2,[g,w]=m?[0,1]:[2,3],v=e.type.value,
|
|
2458
|
+
}`},ph=(e,t,n,i,o,l,u,c,h,p)=>{let m=n.length===2,[g,w]=m?[0,1]:[2,3],v=e.type.value,b=x=>{let M=x===g?"row":"col";return`
|
|
2459
2459
|
fn ${M}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${v} {
|
|
2460
2460
|
var output_index = ${t.indicesGet("output_indices",x)};
|
|
2461
2461
|
var originalIdx: ${v} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[x]},
|
|
@@ -2479,8 +2479,8 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2479
2479
|
}
|
|
2480
2480
|
return cubicInterpolation1D(data, coefs);
|
|
2481
2481
|
}`};return`
|
|
2482
|
-
${
|
|
2483
|
-
${
|
|
2482
|
+
${b(g)};
|
|
2483
|
+
${b(w)};
|
|
2484
2484
|
fn getCubicInterpolationCoefs(s: ${v}) -> array<${v}, 4> {
|
|
2485
2485
|
var absS = abs(s);
|
|
2486
2486
|
var coeffs: array<${v}, 4> = array<${v}, 4>(0.0, 0.0, 0.0, 0.0);
|
|
@@ -2562,18 +2562,18 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2562
2562
|
}
|
|
2563
2563
|
return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +
|
|
2564
2564
|
x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);
|
|
2565
|
-
}`},mh=(e,t,n,i,o,l)=>{let u=e.dims,c=ah(l,t.axes,u.length),h=oh(u,i,o,t.axes),p=i.slice();i.length===0&&(p=u.map(($,P)=>$===0?1:h[P]/$),t.keepAspectRatioPolicy!=="stretch"&&(h=lh(u,p,t)));let m=le("output",e.dataType,h.length),g=F("input",e.dataType,u.length),w=
|
|
2565
|
+
}`},mh=(e,t,n,i,o,l)=>{let u=e.dims,c=ah(l,t.axes,u.length),h=oh(u,i,o,t.axes),p=i.slice();i.length===0&&(p=u.map(($,P)=>$===0?1:h[P]/$),t.keepAspectRatioPolicy!=="stretch"&&(h=lh(u,p,t)));let m=le("output",e.dataType,h.length),g=F("input",e.dataType,u.length),w=K.size(h),v=u.length===h.length&&u.every(($,P)=>$===h[P]),b=t.coordinateTransformMode==="tf_crop_and_resize",x=t.extrapolationValue,M=g.type.value,k=$=>`
|
|
2566
2566
|
${v?"":`
|
|
2567
2567
|
${nh(t.coordinateTransformMode,M)};
|
|
2568
2568
|
${(()=>{switch(t.mode){case"nearest":return`
|
|
2569
2569
|
${ch(g,u)};
|
|
2570
2570
|
${ih(t.nearestMode,n,M)};
|
|
2571
|
-
${dh(g,m,u,h,p.length,c.length,
|
|
2571
|
+
${dh(g,m,u,h,p.length,c.length,b)};
|
|
2572
2572
|
`;case"linear":return`
|
|
2573
2573
|
${uh(m,u,h,p.length,c.length)};
|
|
2574
|
-
${(()=>{if(u.length===2||u.length===4)return`${hh(g,m,u,
|
|
2574
|
+
${(()=>{if(u.length===2||u.length===4)return`${hh(g,m,u,b,x)}`;if(u.length===3||u.length===5)return`${fh(g,m,u,b,x)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};
|
|
2575
2575
|
`;case"cubic":return`
|
|
2576
|
-
${(()=>{if(u.length===2||u.length===4)return`${ph(g,m,u,h,p,c,t.cubicCoeffA,
|
|
2576
|
+
${(()=>{if(u.length===2||u.length===4)return`${ph(g,m,u,h,p,c,t.cubicCoeffA,b,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};
|
|
2577
2577
|
`;default:throw Error("Invalid resize mode")}})()};
|
|
2578
2578
|
`}
|
|
2579
2579
|
${$.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",c.length).declareVariables(g,m)}
|
|
@@ -2589,9 +2589,9 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2589
2589
|
output[global_idx] = ${t.extrapolationValue};
|
|
2590
2590
|
}`;case"linear":return`output[global_idx] = ${u.length===2||u.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};
|
|
2591
2591
|
`}
|
|
2592
|
-
}`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${p.length>0?t.mode==="cubic"?p:p.length:""}|${o.length>0?o:""}|${c.length>0?c:""}|${v}|${t.mode==="nearest"?u.length:u}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[{dims:h,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},{type:1,data:p},{type:1,data:c},...L(u,h)]})}},gh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},yh=(e,t)=>{let n=[],i=[],o=[],l=gh(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");sh(e.inputs,t,l,n,i,o),e.compute(mh(e.inputs[0],t,l,n,i,o),{inputs:[0]})},wh=e=>{let t=e.antialias,n=e.axes,i=e.coordinateTransformMode,o=e.cubicCoeffA,l=e.excludeOutside!==0,u=e.extrapolationValue,c=e.keepAspectRatioPolicy,h=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return E({antialias:t,axes:n,coordinateTransformMode:i,cubicCoeffA:o,excludeOutside:l,extrapolationValue:u,keepAspectRatioPolicy:c,mode:h,nearestMode:p})}}),vh,_h,bh,Xm=
|
|
2592
|
+
}`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${p.length>0?t.mode==="cubic"?p:p.length:""}|${o.length>0?o:""}|${c.length>0?c:""}|${v}|${t.mode==="nearest"?u.length:u}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[{dims:h,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},{type:1,data:p},{type:1,data:c},...L(u,h)]})}},gh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},yh=(e,t)=>{let n=[],i=[],o=[],l=gh(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");sh(e.inputs,t,l,n,i,o),e.compute(mh(e.inputs[0],t,l,n,i,o),{inputs:[0]})},wh=e=>{let t=e.antialias,n=e.axes,i=e.coordinateTransformMode,o=e.cubicCoeffA,l=e.excludeOutside!==0,u=e.extrapolationValue,c=e.keepAspectRatioPolicy,h=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return E({antialias:t,axes:n,coordinateTransformMode:i,cubicCoeffA:o,excludeOutside:l,extrapolationValue:u,keepAspectRatioPolicy:c,mode:h,nearestMode:p})}}),vh,_h,bh,Xm=S(()=>{Ie(),ke(),we(),vh=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],n=e[1],i=e[2];if(t.dataType!==n.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(n.dims.length!==3&&n.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],l=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(n.dims[n.dims.length-2]!==l)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]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let u=e[3];if(u.dims.length!==1)throw new Error("Beta must be 1D");if(u.dims[u.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let u=e[4];if(u.dims.length!==1)throw new Error("Bias must be 1D");if(u.dims[u.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},_h=(e,t,n,i)=>{let o=t.simplified,l=e[0].dims,u=K.size(l),c=l,h=u,p=l.slice(-1)[0],m=i?l.slice(0,-1).concat(1):[],g=!o&&e.length>3,w=e.length>4,v=i&&n>1,b=i&&n>2,x=n>3,M=64,k=V(p),$=[{type:12,data:h},{type:12,data:k},{type:12,data:p},{type:1,data:t.epsilon}],P=B=>{let q=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],H=[F("x",e[0].dataType,e[0].dims,k),F("skip",e[1].dataType,e[1].dims,k),F("gamma",e[2].dataType,e[2].dims,k)];g&&H.push(F("beta",e[3].dataType,e[3].dims,k)),w&&H.push(F("bias",e[4].dataType,e[4].dims,k)),H.push(le("output",e[0].dataType,c,k)),v&&H.push(le("mean_output",1,m)),b&&H.push(le("inv_std_output",1,m)),x&&H.push(le("input_skip_bias_sum",e[0].dataType,c,k));let ee=G(e[0].dataType),ue=G(1,k);return`
|
|
2593
2593
|
|
|
2594
|
-
${B.registerUniforms(q).declareVariables(...
|
|
2594
|
+
${B.registerUniforms(q).declareVariables(...H)}
|
|
2595
2595
|
var<workgroup> sum_shared : array<${ue}, ${M}>;
|
|
2596
2596
|
var<workgroup> sum_squared_shared : array<${ue}, ${M}>;
|
|
2597
2597
|
|
|
@@ -2634,14 +2634,14 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2634
2634
|
let mean = ${Z("sum",k)} / f32(uniforms.hidden_size);
|
|
2635
2635
|
let inv_std_dev = inverseSqrt(${Z("square_sum",k)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon);
|
|
2636
2636
|
${v?"mean_output[global_idx] = mean;":""}
|
|
2637
|
-
${
|
|
2637
|
+
${b?"inv_std_output[global_idx] = inv_std_dev;":""}
|
|
2638
2638
|
|
|
2639
2639
|
for (var i: u32 = 0; i < stride; i++) {
|
|
2640
2640
|
output[offset + i] = (output[offset + i] ${o?"":`- ${ee}(mean)`}) *
|
|
2641
2641
|
${ee}(inv_std_dev) * gamma[offset1d + i]
|
|
2642
2642
|
${g?"+ beta[offset1d + i]":""};
|
|
2643
2643
|
}
|
|
2644
|
-
}`},I=[{dims:c,dataType:e[0].dataType}];return n>1&&I.push({dims:m,dataType:1}),n>2&&I.push({dims:m,dataType:1}),n>3&&I.push({dims:l,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${k};${v};${
|
|
2644
|
+
}`},I=[{dims:c,dataType:e[0].dataType}];return n>1&&I.push({dims:m,dataType:1}),n>2&&I.push({dims:m,dataType:1}),n>3&&I.push({dims:l,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${k};${v};${b};${x}`,inputDependencies:e.map((B,q)=>"type")},getShaderSource:P,getRunData:()=>({outputs:I,dispatchGroup:{x:Math.ceil(h/p)},programUniforms:$})}},bh=(e,t)=>{vh(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(_h(e.inputs,t,e.outputCount,!1),{outputs:n})}}),Sh,Xn,Th,za,Eh,$h,xh,Ch,Ym=S(()=>{Ie(),ke(),A(),we(),Sh=(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((n,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`)})},Xn=(e,t)=>{let n=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(i=>n.push(Number(i)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(i=>n.push(Number(i)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return n},Th=(e,t)=>{if(e.length>1){let n=Xn(e,1),i=Xn(e,2),o=Xn(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),E({starts:n,ends:i,axes:o})}else return t},za=(e,t,n,i,o)=>{let l=e;return e<0&&(l+=n[i[t]]),o[t]<0?Math.max(0,Math.min(l,n[i[t]]-1)):Math.max(0,Math.min(l,n[i[t]]))},Eh=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
|
|
2645
2645
|
var input_indices: ${e.type.indices};
|
|
2646
2646
|
var carry = 0u;
|
|
2647
2647
|
for (var i = ${n.length-1}; i >= 0; i--) {
|
|
@@ -2659,15 +2659,15 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2659
2659
|
${e.indicesSet("input_indices","i","input_index")};
|
|
2660
2660
|
}
|
|
2661
2661
|
return input_indices;
|
|
2662
|
-
}`,$h=(e,t)=>{let n=e[0].dims,i=
|
|
2663
|
-
${k.registerUniforms(
|
|
2662
|
+
}`,$h=(e,t)=>{let n=e[0].dims,i=K.size(n),o=t.axes.length>0?K.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],l=Xn(e,4);l.forEach(k=>k!==0||(()=>{throw new Error("step cannot be 0")})),l.length===0&&(l=Array(o.length).fill(1));let u=t.starts.map((k,$)=>za(k,$,n,o,l)),c=t.ends.map((k,$)=>za(k,$,n,o,l));if(o.length!==u.length||o.length!==c.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==n.length)for(let k=0;k<n.length;++k)o.includes(k)||(u.splice(k,0,0),c.splice(k,0,n[k]),l.splice(k,0,1));let h=l.map(k=>Math.sign(k));l.forEach((k,$,P)=>{if(k<0){let I=(c[$]-u[$])/k,B=u[$],q=B+I*l[$];u[$]=q,c[$]=B,P[$]=-k}});let p=n.slice(0);o.forEach((k,$)=>{p[k]=Math.ceil((c[k]-u[k])/l[k])});let m={dims:p,dataType:e[0].dataType},g=le("output",e[0].dataType,p.length),w=F("input",e[0].dataType,e[0].dims.length),v=K.size(p),b=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:u.length},{name:"signs",type:"i32",length:h.length},{name:"steps",type:"u32",length:l.length}],x=[{type:12,data:v},{type:12,data:u},{type:6,data:h},{type:12,data:l},...L(e[0].dims,p)],M=k=>`
|
|
2663
|
+
${k.registerUniforms(b).declareVariables(w,g)}
|
|
2664
2664
|
${Eh(w,g,n)}
|
|
2665
2665
|
${k.mainStart()}
|
|
2666
2666
|
${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2667
2667
|
let output_indices = ${g.offsetToIndices("global_idx")};
|
|
2668
2668
|
let input_indices = calculateInputIndices(output_indices);
|
|
2669
2669
|
${g.setByOffset("global_idx",w.getByIndices("input_indices"))}
|
|
2670
|
-
}`;return{name:"Slice",shaderCache:{hint:`${h.length}_${u.length}_${l.length}`,inputDependencies:["rank"]},getShaderSource:M,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:x})}},xh=(e,t)=>{Sh(e.inputs,t);let n=Th(e.inputs,t);e.compute($h(e.inputs,n),{inputs:[0]})},Ch=e=>{let t=e.starts,n=e.ends,i=e.axes;return E({starts:t,ends:n,axes:i})}}),kh,Rh,Ah,Ih,Jm=
|
|
2670
|
+
}`;return{name:"Slice",shaderCache:{hint:`${h.length}_${u.length}_${l.length}`,inputDependencies:["rank"]},getShaderSource:M,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:x})}},xh=(e,t)=>{Sh(e.inputs,t);let n=Th(e.inputs,t);e.compute($h(e.inputs,n),{inputs:[0]})},Ch=e=>{let t=e.starts,n=e.ends,i=e.axes;return E({starts:t,ends:n,axes:i})}}),kh,Rh,Ah,Ih,Jm=S(()=>{Ie(),ke(),A(),Ue(),we(),kh=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Rh=(e,t)=>{let n=e.inputs[0],i=n.dims,o=K.size(i),l=i.length,u=K.normalizeAxis(t.axis,l),c=u<i.length-1,h,p=[];c?(p=Array.from({length:l},(H,ee)=>ee),p[u]=l-1,p[l-1]=u,h=e.compute(ct(n,p),{inputs:[n],outputs:[-1]})[0]):h=n;let m=h.dims,g=m[l-1],w=o/g,v=V(g),b=g/v,x=64;w===1&&(x=256);let M=(H,ee)=>ee===4?`max(max(${H}.x, ${H}.y), max(${H}.z, ${H}.w))`:ee===2?`max(${H}.x, ${H}.y)`:ee===3?`max(max(${H}.x, ${H}.y), ${H}.z)`:H,k=F("x",h.dataType,h.dims,v),$=le("result",h.dataType,h.dims,v),P=k.type.value,I=G(h.dataType)==="f32"?`var threadMax = ${P}(-3.4028234663852886e+38f);`:`var threadMax = ${P}(-65504.0h);`,B=H=>`
|
|
2671
2671
|
var<workgroup> rowMaxShared : ${P};
|
|
2672
2672
|
var<workgroup> rowSumShared : ${P};
|
|
2673
2673
|
var<workgroup> threadShared : array<${P}, ${x}>;
|
|
@@ -2681,8 +2681,8 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2681
2681
|
let index = row * row_stride + col;
|
|
2682
2682
|
result[index] = value;
|
|
2683
2683
|
}
|
|
2684
|
-
${
|
|
2685
|
-
${
|
|
2684
|
+
${H.registerUniform("packedCols","i32").declareVariables(k,$)}
|
|
2685
|
+
${H.mainStart(x)}
|
|
2686
2686
|
let gindex = i32(global_idx);
|
|
2687
2687
|
let lindex = i32(local_idx);
|
|
2688
2688
|
const wg = ${x};
|
|
@@ -2741,7 +2741,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2741
2741
|
value = max(value, ${P}(0.0));
|
|
2742
2742
|
setValue(row, col, row_stride, value);
|
|
2743
2743
|
}
|
|
2744
|
-
}`,q=e.compute({name:"Softmax",shaderCache:{hint:`${v};${x}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:m,dataType:h.dataType}],dispatchGroup:{x:w},programUniforms:[{type:6,data:
|
|
2744
|
+
}`,q=e.compute({name:"Softmax",shaderCache:{hint:`${v};${x}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:m,dataType:h.dataType}],dispatchGroup:{x:w},programUniforms:[{type:6,data:b}]}),getShaderSource:B},{inputs:[h],outputs:[c?-1:0]})[0];c&&e.compute(ct(q,p),{inputs:[q]})},Ah=(e,t)=>{kh(e.inputs),Rh(e,t)},Ih=e=>E({axis:e.axis})}),La,Mh,Ph,Oh,Dh,Zm=S(()=>{Ie(),ke(),we(),La=e=>Array.from(e.getBigInt64Array(),Number),Mh=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(La(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")},Ph=(e,t)=>{let n=[];for(let i=0;i<e.length;++i)n.push(e[i]*t[i]);return n},Oh=(e,t)=>{let n=e[0].dims,i=t??La(e[1]),o=Ph(n,i),l=K.size(o),u=e[0].dataType,c=F("input",u,n.length),h=le("output",u,o.length),p=m=>`
|
|
2745
2745
|
const inputShape = ${c.indices(...n)};
|
|
2746
2746
|
${m.registerUniform("output_size","u32").declareVariables(c,h)}
|
|
2747
2747
|
${m.mainStart()}
|
|
@@ -2755,7 +2755,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2755
2755
|
${c.indicesSet("input_indices","i","input_dim_value")}
|
|
2756
2756
|
}
|
|
2757
2757
|
${h.setByOffset("global_idx",c.getByIndices("input_indices"))}
|
|
2758
|
-
}`;return{name:"Tile",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},...L(e[0].dims,o)]}),getShaderSource:p}},Dh=e=>{Mh(e.inputs),e.compute(Oh(e.inputs),{inputs:[0]})}}),zh,Lh,Bh,eg=
|
|
2758
|
+
}`;return{name:"Tile",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},...L(e[0].dims,o)]}),getShaderSource:p}},Dh=e=>{Mh(e.inputs),e.compute(Oh(e.inputs),{inputs:[0]})}}),zh,Lh,Bh,eg=S(()=>{Ie(),ke(),we(),zh=(e,t,n,i,o)=>{let l=le("output_data",o,n.length,4),u=F("a_data",t[1].dataType,t[1].dims.length,4),c=F("b_data",t[2].dataType,t[2].dims.length,4),h=F("c_data",t[0].dataType,t[0].dims.length,4),p,m=(g,w,v)=>`select(${w}, ${g}, ${v})`;if(!i)p=l.setByOffset("global_idx",m(u.getByOffset("global_idx"),c.getByOffset("global_idx"),h.getByOffset("global_idx")));else{let g=(w,v,b="")=>{let x=`a_data[index_a${v}][component_a${v}]`,M=`b_data[index_b${v}][component_b${v}]`,k=`bool(c_data[index_c${v}] & (0xffu << (component_c${v} * 8)))`;return`
|
|
2759
2759
|
let output_indices${v} = ${l.offsetToIndices(`global_idx * 4u + ${v}u`)};
|
|
2760
2760
|
let offset_a${v} = ${u.broadcastedIndicesToOffset(`output_indices${v}`,l)};
|
|
2761
2761
|
let offset_b${v} = ${c.broadcastedIndicesToOffset(`output_indices${v}`,l)};
|
|
@@ -2766,7 +2766,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2766
2766
|
let component_a${v} = offset_a${v} % 4u;
|
|
2767
2767
|
let component_b${v} = offset_b${v} % 4u;
|
|
2768
2768
|
let component_c${v} = offset_c${v} % 4u;
|
|
2769
|
-
${w}[${v}] = ${
|
|
2769
|
+
${w}[${v}] = ${b}(${m(x,M,k)});
|
|
2770
2770
|
`};o===9?p=`
|
|
2771
2771
|
var data = vec4<u32>(0);
|
|
2772
2772
|
${g("data",0,"u32")}
|
|
@@ -2783,10 +2783,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2783
2783
|
${e.mainStart()}
|
|
2784
2784
|
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
2785
2785
|
${p}
|
|
2786
|
-
}`},Lh=e=>{let t=e[1].dims,n=e[2].dims,i=e[0].dims,o=e[1].dataType,l=!(
|
|
2786
|
+
}`},Lh=e=>{let t=e[1].dims,n=e[2].dims,i=e[0].dims,o=e[1].dataType,l=!(K.areEqual(t,n)&&K.areEqual(n,i)),u=t,c=K.size(t);if(l){let p=kr.calcShape(kr.calcShape(t,n,!1),i,!1);if(!p)throw new Error("Can't perform where op on the given tensors");u=p,c=K.size(u)}let h=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>zh(p,e,u,l,o),getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:h},...L(i,t,n,u)]})}},Bh=e=>{e.compute(Lh(e.inputs))}}),Nh,tg=S(()=>{mm(),Zi(),gm(),ym(),wm(),vm(),_m(),$m(),Cm(),km(),Rm(),Am(),Im(),Mm(),Pm(),Om(),Dm(),zm(),Lm(),Bm(),Nm(),Um(),Fm(),Vm(),Gm(),Yd(),qm(),Wm(),Hm(),jm(),Km(),Xi(),Qm(),oc(),Xm(),Ym(),Jm(),nc(),Zm(),Ue(),sa(),eg(),Nh=new Map([["Abs",[vl]],["Acos",[_l]],["Acosh",[bl]],["Add",[lu]],["ArgMax",[nl,Ji]],["ArgMin",[sl,Ji]],["Asin",[Sl]],["Asinh",[Tl]],["Atan",[El]],["Atanh",[$l]],["Attention",[dl]],["AveragePool",[Lc,zc]],["BatchNormalization",[fl]],["BiasAdd",[yl]],["BiasSplitGelu",[iu]],["Cast",[Cl,xl]],["Ceil",[Al]],["Clip",[Rl]],["Concat",[Su,Tu]],["Conv",[ga,fa]],["ConvTranspose",[Xu,ju]],["Cos",[Il]],["Cosh",[Ml]],["CumSum",[Ju,Zu]],["DepthToSpace",[sd,nd]],["DequantizeLinear",[Hc,jc]],["Div",[uu]],["Einsum",[dd,cd]],["Elu",[Pl,qn]],["Equal",[du]],["Erf",[Ol]],["Exp",[Dl]],["Expand",[md]],["FastGelu",[yd]],["Floor",[zl]],["FusedConv",[ga,fa]],["Gather",[bd,_d]],["GatherElements",[Md,Id]],["GatherBlockQuantized",[Cd,kd]],["GatherND",[Td,Ed]],["Gelu",[Ll]],["Gemm",[zd,Dd]],["GlobalAveragePool",[Nc,Bc]],["GlobalMaxPool",[Gc,Vc]],["Greater",[fu]],["GreaterOrEqual",[gu]],["GridSample",[Wd,Hd]],["GroupQueryAttention",[cc]],["HardSigmoid",[Wl,ql]],["InstanceNormalization",[fc]],["LayerNormalization",[yc]],["LeakyRelu",[Bl,qn]],["Less",[mu]],["LessOrEqual",[yu]],["Log",[Zl]],["MatMul",[vc]],["MatMulNBits",[Tc,Ec]],["MaxPool",[Uc,Fc]],["Mul",[cu]],["MultiHeadAttention",[Xd,Kd]],["Neg",[Ul]],["Not",[Nl]],["Pad",[Pc]],["Pow",[hu]],["QuickGelu",[ru,qn]],["Range",[Xc]],["Reciprocal",[Fl]],["ReduceMin",[Jo]],["ReduceMean",[jo]],["ReduceMax",[Yo]],["ReduceSum",[el]],["ReduceProd",[Zo]],["ReduceL1",[Ko]],["ReduceL2",[Qo]],["ReduceLogSum",[rl]],["ReduceLogSumExp",[Xo]],["ReduceSumSquare",[tl]],["Relu",[Vl]],["Resize",[yh,wh]],["RotaryEmbedding",[ac]],["ScatterND",[eh,Zc]],["Sigmoid",[Gl]],["Sin",[Hl]],["Sinh",[jl]],["Slice",[xh,Ch]],["SkipLayerNormalization",[bh]],["Split",[rc,sc]],["Sqrt",[Kl]],["Softmax",[Ah,Ih]],["Sub",[pu]],["Tan",[Ql]],["Tanh",[Xl]],["ThresholdedRelu",[Jl,qn]],["Tile",[Dh]],["Transpose",[ar,Fn]],["Where",[Bh]]])}),Uh,rg=S(()=>{yt(),tr(),we(),Uh=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,n,i,o){gt(e.programInfo.name);let l=this.backend.device,u=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let c=[];for(let p of t)c.push({binding:c.length,resource:{buffer:p.buffer}});for(let p of n)c.push({binding:c.length,resource:{buffer:p.buffer}});o&&c.push({binding:c.length,resource:o});let h=l.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:c,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let p={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:h,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p)}u.setPipeline(e.computePipeline),u.setBindGroup(0,h),u.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(),ft(e.programInfo.name)}dispose(){}build(e,t){gt(e.name);let n=this.backend.device,i=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(p=>{n.features.has(p.feature)&&i.push(`enable ${p.extension};`)});let o=Ne(t,this.backend.device.limits),l=e.getShaderSource(o),u=`${i.join(`
|
|
2787
2787
|
`)}
|
|
2788
2788
|
${o.additionalImplementations}
|
|
2789
|
-
${l}`,c=n.createShaderModule({code:u,label:e.name});He("verbose",()=>`[WebGPU] ${e.name} shader code: ${u}`);let h=n.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:e.name});return yt(e.name),{programInfo:e,computePipeline:h,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,n=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&n<=o&&i<=o)return[t,n,i];let l=t*n*i,u=Math.ceil(Math.sqrt(l));if(u>o){if(u=Math.ceil(Math.cbrt(l)),u>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[u,u,u]}else return[u,u,1]}}}),Fh={};U(Fh,{WebGpuBackend:()=>Wh});var Vh,Gh,qh,Wh,sg=b(()=>{ct(),Ie(),tr(),Zr(),ji(),tg(),rg(),Vh=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let i=0;i<e.length;++i){let o=e[i].dataType;switch(t[i]){case"none":{n.push("");break}case"type":{n.push(`${o}`);break}case"rank":{let l=e[i].dims.length;n.push(`${o};${l}`);break}case"dims":{let l=e[i].dims.join(",");n.push(`${o};${l}`);break}default:throw new Error(`unsupported input dependency: ${t[i]}`)}}return n.join("|")},Gh=(e,t,n)=>{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+n+`:${Vh(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},qh=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Wh=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 n=[],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:n},o=l=>t.features.has(l)&&n.push(l)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await t.requestDevice(i),this.adapterInfo=new qh(t.info||await t.requestAdapterInfo()),this.gpuDataManager=fi(this),this.programManager=new Uh(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ws(e.logLevel,!!e.debug),this.device.onuncapturederror=l=>{l.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${l.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;gt(),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()),n=this.pendingQueries.get(e);for(let i=0;i<t.length/2;i++){let o=n[i],l=o.kernelId,u=this.kernels.get(l),c=u.kernelType,h=u.kernelName,p=o.programName,m=o.inputTensorViews,g=o.outputTensorViews,w=t[i*2],v=t[i*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=w);let S=Number(w-this.queryTimeBase),x=Number(v-this.queryTimeBase);if(!Number.isSafeInteger(S)||!Number.isSafeInteger(x))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:m.map(M=>({dims:M.dims,dataType:jt(M.dataType)})),outputsMetadata:g.map(M=>({dims:M.dims,dataType:jt(M.dataType)})),kernelId:l,kernelType:c,kernelName:h,programName:p,startTime:S,endTime:x});else{let M="";m.forEach(($,P)=>{M+=`input[${P}]: [${$.dims}] | ${jt($.dataType)}, `});let k="";g.forEach(($,P)=>{k+=`output[${P}]: [${$.dims}] | ${jt($.dataType)}, `}),console.log(`[profiling] kernel "${l}|${c}|${h}|${p}" ${M}${k}start time: ${S} ns, execution time: ${x-S} ns`)}er("GPU",`${p}::${w}::${v}`)}e.unmap(),this.pendingQueries.delete(e)}),yt()}run(e,t,n,i,o,l){gt(e.name);let u=[];for(let $=0;$<t.length;++$){let P=t[$].data;if(P===0)continue;let I=this.gpuDataManager.get(P);if(!I)throw new Error(`no GPU data for input: ${P}`);u.push(I)}let{outputs:c,dispatchGroup:h,programUniforms:p}=e.getRunData(t),m=n.length===0?c.map(($,P)=>P):n;if(m.length!==c.length)throw new Error(`Output size ${m.length} must be equal to ${c.length}.`);let g=[],w=[];for(let $=0;$<c.length;++$){if(!Number.isInteger(m[$])||m[$]<-3||m[$]>=l)throw new Error(`Invalid output index: ${m[$]}`);if(m[$]===-3)continue;let P=m[$]===-1,I=m[$]===-2,B=P||I?o(c[$].dataType,c[$].dims):i(m[$],c[$].dataType,c[$].dims);if(g.push(B),B.data===0)continue;let q=this.gpuDataManager.get(B.data);if(!q)throw new Error(`no GPU data for output: ${B.data}`);if(P&&this.temporaryData.push(q),I){let W=this.kernelPersistentData.get(this.currentKernelId);W||(W=[],this.kernelPersistentData.set(this.currentKernelId,W)),W.push(q)}w.push(q)}if(u.length!==t.length||w.length!==g.length){if(w.length===0)return yt(e.name),g;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let v;if(p){let $=0,P=[];p.forEach(W=>{let ee=typeof W.data=="number"?[W.data]:W.data;if(ee.length===0)return;let ue=W.type===10?2:4,_e,Fe;W.type===10?(Fe=ee.length>4?16:ee.length>2?8:ee.length*ue,_e=ee.length>4?16:ue*ee.length):(Fe=ee.length<=2?ee.length*ue:16,_e=16),$=Math.ceil($/Fe)*Fe,P.push($);let Re=W.type===10?8:4;$+=ee.length>4?Math.ceil(ee.length/Re)*_e:ee.length*ue});let I=16;$=Math.ceil($/I)*I;let B=new ArrayBuffer($);p.forEach((W,ee)=>{let ue=P[ee],_e=typeof W.data=="number"?[W.data]:W.data;if(W.type===6)new Int32Array(B,ue,_e.length).set(_e);else if(W.type===12)new Uint32Array(B,ue,_e.length).set(_e);else if(W.type===10)new Uint16Array(B,ue,_e.length).set(_e);else if(W.type===1)new Float32Array(B,ue,_e.length).set(_e);else throw new Error(`Unsupported uniform type: ${jt(W.type)}`)});let q=this.gpuDataManager.create($,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(q.buffer,0,B,0,$),this.gpuDataManager.release(q.id),v={offset:0,size:$,buffer:q.buffer}}let S=this.programManager.normalizeDispatchGroupSize(h),x=S[1]===1&&S[2]===1,M=Gh(e,t,x),k=this.programManager.getArtifact(M);if(k||(k=this.programManager.build(e,S),this.programManager.setArtifact(M,k),He("info",()=>`[artifact] key: ${M}, programName: ${e.name}`)),p&&k.uniformVariablesInfo){if(p.length!==k.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${k.uniformVariablesInfo.length}, got ${p.length} in program "${k.programInfo.name}".`);for(let $=0;$<p.length;$++){let P=p[$],I=P.type,B=typeof P.data=="number"?1:P.data.length,[q,W]=k.uniformVariablesInfo[$];if(I!==q||B!==W)throw new Error(`Uniform variable ${$} mismatch: expect type ${q} with size ${W}, got type ${I} with size ${B} in program "${k.programInfo.name}".`)}}if(He("info",()=>`[ProgramManager] run "${e.name}" (key=${M}) with ${S[0]}x${S[1]}x${S[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let $={kernelId:this.currentKernelId,programName:k.programInfo.name,inputTensorViews:t,outputTensorViews:g};this.pendingKernels.push($),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push($)}return this.programManager.run(k,u,w,S,v),yt(e.name),g}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,n,i){let o=Nh.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let l={kernelType:e,kernelName:i,kernelEntry:o[0],attributes:[o[1],n]};this.kernels.set(t,l)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let n of t)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let o=i.kernelType,l=i.kernelName,u=i.kernelEntry,c=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${l}" is not allowed to be called recursively`);this.currentKernelId=e,c[0]&&(c[1]=c[0](c[1]),c[0]=void 0),He("info",()=>`[WebGPU] Start to run kernel "[${o}] ${l}"...`);let h=this.env.debug;this.temporaryData=[];try{return h&&this.device.pushErrorScope("validation"),u(t,c[1]),0}catch(p){return n.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${l}" failed. ${p}`)),1}finally{h&&n.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${o}] ${l}": ${p.message}`:null));for(let p of this.temporaryData)this.gpuDataManager.release(p.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,i){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let l=o.get(t),u=this.gpuDataManager.registerExternalBuffer(n,i,l);return o.set(t,[u,n]),u}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[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,n){return async()=>{let i=await Bn(this,e,t);return kr(i.buffer,n)}}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(){He("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(){He("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){He("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let i=0;i<n;i++){let o=this.getComputePassEncoder(),l=e[i];this.writeTimestamp(this.pendingDispatchNumber*2),o.setPipeline(l.computePipeline),o.setBindGroup(0,l.bindGroup),o.dispatchWorkgroups(...l.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()}}}),Hh={};U(Hh,{init:()=>jh});var Ci,Kh,jh,ng=b(()=>{Ie(),tr(),ke(),Ln(),Ci=class cf{constructor(t,n,i,o){this.module=t,this.dataType=n,this.data=i,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=j.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=j.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=j.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=j.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(j.size(t)!==j.size(this.dims))throw new Error("Invalid new shape");return new cf(this.module,this.dataType,this.data,t)}},Kh=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,o=n/e.PTR_SIZE,l=i===4?"i32":"i64";this.opKernelContext=Number(e.getValue(i*o++,l));let u=Number(e.getValue(i*o++,l));this.outputCount=Number(e.getValue(i*o++,l)),this.customDataOffset=Number(e.getValue(i*o++,"*")),this.customDataSize=Number(e.getValue(i*o++,l));let c=[];for(let h=0;h<u;h++){let p=Number(e.getValue(i*o++,l)),m=Number(e.getValue(i*o++,"*")),g=Number(e.getValue(i*o++,l)),w=[];for(let v=0;v<g;v++)w.push(Number(e.getValue(i*o++,l)));c.push(new Ci(e,p,m,w))}this.inputs=c}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let n=t?.inputs?.map(u=>typeof u=="number"?this.inputs[u]:u)??this.inputs,i=t?.outputs??[],o=(u,c,h)=>new Ci(this.module,c,this.output(u,h),h),l=(u,c)=>{let h=Qt(u,c);if(!h)throw new Error(`Unsupported data type: ${u}`);let p=h>0?this.backend.gpuDataManager.create(h).id:0;return new Ci(this.module,u,p,c)};return this.backend.run(e,n,i,o,l,this.outputCount)}output(e,t){let n=this.module.stackSave();try{let i=this.module.PTR_SIZE,o=i===4?"i32":"i64",l=this.module.stackAlloc((1+t.length)*i);this.module.setValue(l,t.length,o);for(let u=0;u<t.length;u++)this.module.setValue(l+i*(u+1),t[u],o);return this.module._JsepOutput(this.opKernelContext,e,l)}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(n)}}},jh=async(e,t,n,i)=>{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let l=(sg(),re(Fh)).WebGpuBackend,u=new l;await u.initialize(n,i),o("webgpu",[u,c=>u.alloc(Number(c)),c=>u.free(c),(c,h,p,m=!1)=>{if(m)He("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(c)}, dst=${Number(h)}, size=${Number(p)}`),u.memcpy(Number(c),Number(h));else{He("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(c)}, gpuDataId=${Number(h)}, size=${Number(p)}`);let g=t.HEAPU8.subarray(Number(c>>>0),Number(c>>>0)+Number(p));u.upload(Number(h),g)}},async(c,h,p)=>{He("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${c}, dataOffset=${h}, size=${p}`),await u.download(Number(c),()=>t.HEAPU8.subarray(Number(h)>>>0,Number(h+p)>>>0))},(c,h,p)=>u.createKernel(c,Number(h),p,t.UTF8ToString(t._JsepGetNodeName(Number(h)))),c=>u.releaseKernel(c),(c,h,p,m)=>{He("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${c}, contextDataOffset=${h}`);let g=new Kh(t,u,Number(h));return u.computeKernel(Number(c),g,m)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else{let l=new zn(n);o("webnn",[l,()=>l.reserveTensorId(),u=>l.releaseTensorId(u),async(u,c,h,p,m)=>l.ensureTensor(u,c,h,p,m),(u,c)=>{l.uploadTensor(u,c)},async(u,c)=>l.downloadTensor(u,c),(u,c)=>l.registerMLContext(u,c),!!n.trace])}}}),Qh,Ba,Na,ns,Xh,Ua,ki,Fa,Va,Ga,qa,Wa,Ha,Yh=b(()=>{ct(),Hi(),Ki(),Ie(),Ht(),ws(),An(),Qh=(e,t)=>{Pe()._OrtInit(e,t)!==0&&Ce("Can't initialize onnxruntime.")},Ba=async e=>{Qh(e.wasm.numThreads,_s(e.logLevel))},Na=async(e,t)=>{Pe().asyncInit?.();let n=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.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 o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:o}),!n)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=(ng(),re(Hh)).init;t==="webgpu"&&await i("webgpu",Pe(),e,n),t==="webnn"&&await i("webnn",Pe(),e)}},ns=new Map,Xh=e=>{let t=Pe(),n=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,o,o+i)!==0&&Ce("Can't get session input/output count.");let l=i===4?"i32":"i64";return[Number(t.getValue(o,l)),Number(t.getValue(o+i,l))]}finally{t.stackRestore(n)}},Ua=(e,t)=>{let n=Pe(),i=n.stackSave(),o=0;try{let l=n.PTR_SIZE,u=n.stackAlloc(2*l);n._OrtGetInputOutputMetadata(e,t,u,u+l)!==0&&Ce("Can't get session input/output metadata.");let c=Number(n.getValue(u,"*"));o=Number(n.getValue(u+l,"*"));let h=n.HEAP32[o/4];if(h===0)return[c,0];let p=n.HEAPU32[o/4+1],m=[];for(let g=0;g<p;g++){let w=Number(n.getValue(o+8+g*l,"*"));m.push(w!==0?n.UTF8ToString(w):Number(n.getValue(o+8+(g+p)*l,"*")))}return[c,h,m]}finally{n.stackRestore(i),o!==0&&n._OrtFree(o)}},ki=e=>{let t=Pe(),n=t._malloc(e.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Fa=async(e,t)=>{let n,i,o=Pe();Array.isArray(e)?[n,i]=e:e.buffer===o.HEAPU8.buffer?[n,i]=[e.byteOffset,e.byteLength]:[n,i]=ki(e);let l=0,u=0,c=0,h=[],p=[],m=[];try{if([u,h]=await Rn(t),t?.externalData&&o.mountExternalData){let I=[];for(let B of t.externalData){let q=typeof B=="string"?B:B.path;I.push(Ts(typeof B=="string"?B:B.data).then(W=>{o.mountExternalData(q,W)}))}await Promise.all(I)}for(let I of t?.executionProviders??[])if((typeof I=="string"?I:I.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof I!="string"){let B=I,q=B?.context,W=B?.gpuDevice,ee=B?.deviceType,ue=B?.powerPreference;q?o.currentContext=q:W?o.currentContext=await o.webnnCreateMLContext(W):o.currentContext=await o.webnnCreateMLContext({deviceType:ee,powerPreference:ue})}else o.currentContext=await o.webnnCreateMLContext();break}l=await o._OrtCreateSession(n,i,u),o.webgpuOnCreateSession?.(l),l===0&&Ce("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.webnnRegisterMLContext(l,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[g,w]=Xh(l),v=!!t?.enableGraphCapture,S=[],x=[],M=[],k=[],$=[];for(let I=0;I<g;I++){let[B,q,W]=Ua(l,I);B===0&&Ce("Can't get an input name."),p.push(B);let ee=o.UTF8ToString(B);S.push(ee),M.push(q===0?{name:ee,isTensor:!1}:{name:ee,isTensor:!0,type:jt(q),shape:W})}for(let I=0;I<w;I++){let[B,q,W]=Ua(l,I+g);B===0&&Ce("Can't get an output name."),m.push(B);let ee=o.UTF8ToString(B);x.push(ee),k.push(q===0?{name:ee,isTensor:!1}:{name:ee,isTensor:!0,type:jt(q),shape:W});{if(v&&t?.preferredOutputLocation===void 0){$.push("gpu-buffer");continue}let ue=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[ee]??"cpu",_e=o.webnnIsGraphOutput;if(ue==="cpu"&&_e&&_e(l,ee)){$.push("ml-tensor-cpu-output");continue}if(ue!=="cpu"&&ue!=="cpu-pinned"&&ue!=="gpu-buffer"&&ue!=="ml-tensor")throw new Error(`Not supported preferred output location: ${ue}.`);if(v&&ue!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${ue}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);$.push(ue)}}let P=null;return $.some(I=>I==="gpu-buffer"||I==="ml-tensor"||I==="ml-tensor-cpu-output")&&(c=o._OrtCreateBinding(l),c===0&&Ce("Can't create IO binding."),P={handle:c,outputPreferredLocations:$,outputPreferredLocationsEncoded:$.map(I=>I==="ml-tensor-cpu-output"?"ml-tensor":I).map(I=>Vs(I))}),ns.set(l,[l,p,m,P,v,!1]),[l,S,x,M,k]}catch(g){throw p.forEach(w=>o._OrtFree(w)),m.forEach(w=>o._OrtFree(w)),c!==0&&o._OrtReleaseBinding(c)!==0&&Ce("Can't release IO binding."),l!==0&&o._OrtReleaseSession(l)!==0&&Ce("Can't release session."),g}finally{o._free(n),u!==0&&o._OrtReleaseSessionOptions(u)!==0&&Ce("Can't release session options."),h.forEach(g=>o._free(g)),o.unmountExternalData?.()}},Va=e=>{let t=Pe(),n=ns.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,o,l,u,c]=n;u&&(c&&t._OrtClearBoundOutputs(u.handle)!==0&&Ce("Can't clear bound outputs."),t._OrtReleaseBinding(u.handle)!==0&&Ce("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),o.forEach(h=>t._OrtFree(h)),l.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(i)!==0&&Ce("Can't release session."),ns.delete(e)},Ga=async(e,t,n,i,o,l,u=!1)=>{if(!e){t.push(0);return}let c=Pe(),h=c.PTR_SIZE,p=e[0],m=e[1],g=e[3],w=g,v,S;if(p==="string"&&(g==="gpu-buffer"||g==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(u&&g!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${l} when enableGraphCapture is true.`);if(g==="gpu-buffer"){let k=e[2].gpuBuffer;S=Qt(Kt(p),m);{let $=c.jsepRegisterBuffer;if(!$)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');v=$(i,l,k,S)}}else if(g==="ml-tensor"){let k=e[2].mlTensor;S=Qt(Kt(p),m);let $=c.webnnRegisterMLTensor;if(!$)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');v=$(i,k,Kt(p),m)}else{let k=e[2];if(Array.isArray(k)){S=h*k.length,v=c._malloc(S),n.push(v);for(let $=0;$<k.length;$++){if(typeof k[$]!="string")throw new TypeError(`tensor data at index ${$} is not a string`);c.setValue(v+$*h,mt(k[$],n),"*")}}else{let $=c.webnnIsGraphInput,P=c.webnnIsGraphOutput;if(p!=="string"&&$&&P){let I=c.UTF8ToString(o);if($(i,I)||P(i,I)){let B=Kt(p);S=Qt(B,m),w="ml-tensor";let q=c.webnnCreateTemporaryTensor,W=c.webnnUploadTensor;if(!q||!W)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let ee=await q(i,B,m);W(ee,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),v=ee}else S=k.byteLength,v=c._malloc(S),n.push(v),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),v)}else S=k.byteLength,v=c._malloc(S),n.push(v),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),v)}}let x=c.stackSave(),M=c.stackAlloc(4*m.length);try{m.forEach(($,P)=>c.setValue(M+P*h,$,h===4?"i32":"i64"));let k=c._OrtCreateTensor(Kt(p),v,S,M,m.length,Vs(w));k===0&&Ce(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(k)}finally{c.stackRestore(x)}},qa=async(e,t,n,i,o,l)=>{let u=Pe(),c=u.PTR_SIZE,h=ns.get(e);if(!h)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=h[0],m=h[1],g=h[2],w=h[3],v=h[4],S=h[5],x=t.length,M=i.length,k=0,$=[],P=[],I=[],B=[],q=[],W=u.stackSave(),ee=u.stackAlloc(x*c),ue=u.stackAlloc(x*c),_e=u.stackAlloc(M*c),Fe=u.stackAlloc(M*c);try{[k,$]=En(l),Ct("wasm prepareInputOutputTensor");for(let ge=0;ge<x;ge++)await Ga(n[ge],P,B,e,m[t[ge]],t[ge],v);for(let ge=0;ge<M;ge++)await Ga(o[ge],I,B,e,g[i[ge]],x+i[ge],v);kt("wasm prepareInputOutputTensor");for(let ge=0;ge<x;ge++)u.setValue(ee+ge*c,P[ge],"*"),u.setValue(ue+ge*c,m[t[ge]],"*");for(let ge=0;ge<M;ge++)u.setValue(_e+ge*c,I[ge],"*"),u.setValue(Fe+ge*c,g[i[ge]],"*");if(w&&!S){let{handle:ge,outputPreferredLocations:$e,outputPreferredLocationsEncoded:Le}=w;if(m.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${m.length}).`);Ct("wasm bindInputsOutputs");for(let Ge=0;Ge<x;Ge++){let De=t[Ge];await u._OrtBindInput(ge,m[De],P[Ge])!==0&&Ce(`Can't bind input[${Ge}] for session=${e}.`)}for(let Ge=0;Ge<M;Ge++){let De=i[Ge];o[Ge]?.[3]?(q.push(I[Ge]),u._OrtBindOutput(ge,g[De],I[Ge],0)!==0&&Ce(`Can't bind pre-allocated output[${Ge}] for session=${e}.`)):u._OrtBindOutput(ge,g[De],0,Le[De])!==0&&Ce(`Can't bind output[${Ge}] to ${$e[Ge]} for session=${e}.`)}kt("wasm bindInputsOutputs"),ns.set(e,[p,m,g,w,v,!0])}u.jsepOnRunStart?.(p),u.webnnOnRunStart?.(p);let Re;w?Re=await u._OrtRunWithBinding(p,w.handle,M,_e,k):Re=await u._OrtRun(p,ue,ee,x,Fe,M,_e,k),Re!==0&&Ce("failed to call OrtRun().");let Me=[],Xe=[];Ct("wasm ProcessOutputTensor");for(let ge=0;ge<M;ge++){let $e=Number(u.getValue(_e+ge*c,"*"));if($e===I[ge]||q.includes(I[ge])){Me.push(o[ge]),$e!==I[ge]&&u._OrtReleaseTensor($e)!==0&&Ce("Can't release tensor.");continue}let Le=u.stackSave(),Ge=u.stackAlloc(4*c),De=!1,Ke,ae=0;try{u._OrtGetTensorData($e,Ge,Ge+c,Ge+2*c,Ge+3*c)!==0&&Ce(`Can't access output tensor data on index ${ge}.`);let Oe=c===4?"i32":"i64",Ae=Number(u.getValue(Ge,Oe));ae=u.getValue(Ge+c,"*");let Ee=u.getValue(Ge+c*2,"*"),Dt=Number(u.getValue(Ge+c*3,Oe)),Xt=[];for(let nt=0;nt<Dt;nt++)Xt.push(Number(u.getValue(Ee+nt*c,Oe)));u._OrtFree(Ee)!==0&&Ce("Can't free memory for tensor dims.");let _t=Xt.reduce((nt,bt)=>nt*bt,1);Ke=jt(Ae);let Yt=w?.outputPreferredLocations[i[ge]];if(Ke==="string"){if(Yt==="gpu-buffer"||Yt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let nt=[];for(let bt=0;bt<_t;bt++){let Ur=u.getValue(ae+bt*c,"*"),ug=u.getValue(ae+(bt+1)*c,"*"),dg=bt===_t-1?void 0:ug-Ur;nt.push(u.UTF8ToString(Ur,dg))}Me.push([Ke,Xt,nt,"cpu"])}else if(Yt==="gpu-buffer"&&_t>0){let nt=u.jsepGetBuffer;if(!nt)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let bt=nt(ae),Ur=Qt(Ae,_t);if(Ur===void 0||!bs(Ke))throw new Error(`Unsupported data type: ${Ke}`);De=!0,Me.push([Ke,Xt,{gpuBuffer:bt,download:u.jsepCreateDownloader(bt,Ur,Ke),dispose:()=>{u._OrtReleaseTensor($e)!==0&&Ce("Can't release tensor.")}},"gpu-buffer"])}else if(Yt==="ml-tensor"&&_t>0){let nt=u.webnnEnsureTensor,bt=u.webnnIsGraphInputOutputTypeSupported;if(!nt||!bt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Qt(Ae,_t)===void 0||!Ss(Ke))throw new Error(`Unsupported data type: ${Ke}`);if(!bt(e,Ke,!1))throw new Error(`preferredLocation "ml-tensor" for ${Ke} output is not supported by current WebNN Context.`);let Ur=await nt(e,ae,Ae,Xt,!1);De=!0,Me.push([Ke,Xt,{mlTensor:Ur,download:u.webnnCreateMLTensorDownloader(ae,Ke),dispose:()=>{u.webnnReleaseTensorId(ae),u._OrtReleaseTensor($e)}},"ml-tensor"])}else if(Yt==="ml-tensor-cpu-output"&&_t>0){let nt=u.webnnCreateMLTensorDownloader(ae,Ke)(),bt=Me.length;De=!0,Xe.push((async()=>{let Ur=[bt,await nt];return u.webnnReleaseTensorId(ae),u._OrtReleaseTensor($e),Ur})()),Me.push([Ke,Xt,[],"cpu"])}else{let nt=vs(Ke),bt=new nt(_t);new Uint8Array(bt.buffer,bt.byteOffset,bt.byteLength).set(u.HEAPU8.subarray(ae,ae+bt.byteLength)),Me.push([Ke,Xt,bt,"cpu"])}}finally{u.stackRestore(Le),Ke==="string"&&ae&&u._free(ae),De||u._OrtReleaseTensor($e)}}w&&!v&&(u._OrtClearBoundOutputs(w.handle)!==0&&Ce("Can't clear bound outputs."),ns.set(e,[p,m,g,w,v,!1]));for(let[ge,$e]of await Promise.all(Xe))Me[ge][2]=$e;return kt("wasm ProcessOutputTensor"),Me}finally{u.webnnOnRunEnd?.(p),u.stackRestore(W),P.forEach(Re=>u._OrtReleaseTensor(Re)),I.forEach(Re=>u._OrtReleaseTensor(Re)),B.forEach(Re=>u._free(Re)),k!==0&&u._OrtReleaseRunOptions(k),$.forEach(Re=>u._free(Re))}},Wa=e=>{let t=Pe(),n=ns.get(e);if(!n)throw new Error("invalid session id");let i=n[0],o=t._OrtEndProfiling(i);o===0&&Ce("Can't get an profile file name."),t._OrtFree(o)},Ha=e=>{let t=[];for(let n of e){let i=n[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),is,or,on,Yn,Jn,Ri,Ka,Ai,Ds,zs,Jh,Zh,ep,tp,rp,sp,np,ip,ap=b(()=>{ct(),Yh(),Ht(),fs(),is=()=>!!fe.wasm.proxy&&typeof document<"u",on=!1,Yn=!1,Jn=!1,Ai=new Map,Ds=(e,t)=>{let n=Ai.get(e);n?n.push(t):Ai.set(e,[t])},zs=()=>{if(on||!Yn||Jn||!or)throw new Error("worker not ready")},Jh=e=>{switch(e.data.type){case"init-wasm":on=!1,e.data.err?(Jn=!0,Ka[1](e.data.err)):(Yn=!0,Ka[0]()),Ri&&(URL.revokeObjectURL(Ri),Ri=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Ai.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Zh=async()=>{if(!Yn){if(on)throw new Error("multiple calls to 'initWasm()' detected.");if(Jn)throw new Error("previous call to 'initWasm()' failed.");if(on=!0,is())return new Promise((e,t)=>{or?.terminate(),vn().then(([n,i])=>{try{or=i,or.onerror=l=>t(l),or.onmessage=Jh,Ka=[e,t];let o={type:"init-wasm",in:fe};if(!o.in.wasm.wasmPaths&&n){let l=ds();l&&(o.in.wasm.wasmPaths=l)}or.postMessage(o),Ri=n}catch(o){t(o)}},t)});try{await ys(fe.wasm),await Ba(fe),Yn=!0}catch(e){throw Jn=!0,e}finally{on=!1}}},ep=async e=>{if(is())return zs(),new Promise((t,n)=>{Ds("init-ep",[t,n]);let i={type:"init-ep",in:{epName:e,env:fe}};or.postMessage(i)});await Na(fe,e)},tp=async e=>is()?(zs(),new Promise((t,n)=>{Ds("copy-from",[t,n]);let i={type:"copy-from",in:{buffer:e}};or.postMessage(i,[e.buffer])})):ki(e),rp=async(e,t)=>{if(is()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return zs(),new Promise((n,i)=>{Ds("create",[n,i]);let o={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),or.postMessage(o,l)})}else return Fa(e,t)},sp=async e=>{if(is())return zs(),new Promise((t,n)=>{Ds("release",[t,n]);let i={type:"release",in:e};or.postMessage(i)});Va(e)},np=async(e,t,n,i,o,l)=>{if(is()){if(n.some(u=>u[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(u=>u))throw new Error("pre-allocated output tensor is not supported for proxy.");return zs(),new Promise((u,c)=>{Ds("run",[u,c]);let h=n,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:h,outputIndices:i,options:l}};or.postMessage(p,Ha(h))})}else return qa(e,t,n,i,o,l)},ip=async e=>{if(is())return zs(),new Promise((t,n)=>{Ds("end-profiling",[t,n]);let i={type:"end-profiling",in:e};or.postMessage(i)});Wa(e)}}),ja,op,lp,ig=b(()=>{ct(),ap(),Ie(),Ut(),An(),ja=(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()}`)}},op=e=>{switch(e[3]){case"cpu":return new lt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!bs(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:o}=e[2];return lt.fromGpuBuffer(n,{dataType:t,dims:e[1],download:i,dispose:o})}case"ml-tensor":{let t=e[0];if(!Ss(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:o}=e[2];return lt.fromMLTensor(n,{dataType:t,dims:e[1],download:i,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},lp=class{async fetchModelAndCopyToWasmMemory(e){return tp(await Ts(e))}async loadModel(e,t){gt();let n;typeof e=="string"?n=await this.fetchModelAndCopyToWasmMemory(e):n=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await rp(n,t),yt()}async dispose(){return sp(this.sessionId)}async run(e,t,n){gt();let i=[],o=[];Object.entries(e).forEach(g=>{let w=g[0],v=g[1],S=this.inputNames.indexOf(w);if(S===-1)throw new Error(`invalid input '${w}'`);i.push(v),o.push(S)});let l=[],u=[];Object.entries(t).forEach(g=>{let w=g[0],v=g[1],S=this.outputNames.indexOf(w);if(S===-1)throw new Error(`invalid output '${w}'`);l.push(v),u.push(S)});let c=i.map((g,w)=>ja(g,()=>`input "${this.inputNames[o[w]]}"`)),h=l.map((g,w)=>g?ja(g,()=>`output "${this.outputNames[u[w]]}"`):null),p=await np(this.sessionId,o,c,u,h,n),m={};for(let g=0;g<p.length;g++)m[this.outputNames[u[g]]]=l[g]??op(p[g]);return yt(),m}startProfiling(){}endProfiling(){ip(this.sessionId)}}}),up={};U(up,{OnnxruntimeWebAssemblyBackend:()=>Xa,initializeFlags:()=>Qa,wasmBackend:()=>dp});var Qa,Xa,dp,ag=b(()=>{ct(),ap(),ig(),Qa=()=>{(typeof fe.wasm.initTimeout!="number"||fe.wasm.initTimeout<0)&&(fe.wasm.initTimeout=0);let e=fe.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.`),fe.wasm.simd=!1),typeof fe.wasm.proxy!="boolean"&&(fe.wasm.proxy=!1),typeof fe.wasm.trace!="boolean"&&(fe.wasm.trace=!1),typeof fe.wasm.numThreads!="number"||!Number.isInteger(fe.wasm.numThreads)||fe.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)fe.wasm.numThreads=1;else{let t=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;fe.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Xa=class{async init(e){Qa(),await Zh(),await ep(e)}async createInferenceSessionHandler(e,t){let n=new lp;return await n.loadModel(e,t),n}},dp=new Xa}),cp={};U(cp,{InferenceSession:()=>Qe,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>Ct,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>yt,Tensor:()=>lt,default:()=>lg,env:()=>fe,registerBackend:()=>J}),ct(),ct(),ct();var og="1.26.0",lg=ls;{let e=(ag(),re(up)).wasmBackend;J("webgpu",e,5),J("webnn",e,5),J("cpu",e,10),J("wasm",e,10)}return Object.defineProperty(fe.versions,"web",{value:og,enumerable:!0}),re(cp)})();/**
|
|
2789
|
+
${l}`,c=n.createShaderModule({code:u,label:e.name});He("verbose",()=>`[WebGPU] ${e.name} shader code: ${u}`);let h=n.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:e.name});return ft(e.name),{programInfo:e,computePipeline:h,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,n=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&n<=o&&i<=o)return[t,n,i];let l=t*n*i,u=Math.ceil(Math.sqrt(l));if(u>o){if(u=Math.ceil(Math.cbrt(l)),u>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[u,u,u]}else return[u,u,1]}}}),Fh={};N(Fh,{WebGpuBackend:()=>Wh});var Vh,Gh,qh,Wh,sg=S(()=>{yt(),Ie(),tr(),ss(),Ki(),tg(),rg(),Vh=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let i=0;i<e.length;++i){let o=e[i].dataType;switch(t[i]){case"none":{n.push("");break}case"type":{n.push(`${o}`);break}case"rank":{let l=e[i].dims.length;n.push(`${o};${l}`);break}case"dims":{let l=e[i].dims.join(",");n.push(`${o};${l}`);break}default:throw new Error(`unsupported input dependency: ${t[i]}`)}}return n.join("|")},Gh=(e,t,n)=>{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+n+`:${Vh(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},qh=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Wh=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 n=[],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:n},o=l=>t.features.has(l)&&n.push(l)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await t.requestDevice(i),this.adapterInfo=new qh(t.info||await t.requestAdapterInfo()),this.gpuDataManager=mi(this),this.programManager=new Uh(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ks(e.logLevel,!!e.debug),this.device.onuncapturederror=l=>{l.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${l.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;gt(),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()),n=this.pendingQueries.get(e);for(let i=0;i<t.length/2;i++){let o=n[i],l=o.kernelId,u=this.kernels.get(l),c=u.kernelType,h=u.kernelName,p=o.programName,m=o.inputTensorViews,g=o.outputTensorViews,w=t[i*2],v=t[i*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=w);let b=Number(w-this.queryTimeBase),x=Number(v-this.queryTimeBase);if(!Number.isSafeInteger(b)||!Number.isSafeInteger(x))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:m.map(M=>({dims:M.dims,dataType:Kt(M.dataType)})),outputsMetadata:g.map(M=>({dims:M.dims,dataType:Kt(M.dataType)})),kernelId:l,kernelType:c,kernelName:h,programName:p,startTime:b,endTime:x});else{let M="";m.forEach(($,P)=>{M+=`input[${P}]: [${$.dims}] | ${Kt($.dataType)}, `});let k="";g.forEach(($,P)=>{k+=`output[${P}]: [${$.dims}] | ${Kt($.dataType)}, `}),console.log(`[profiling] kernel "${l}|${c}|${h}|${p}" ${M}${k}start time: ${b} ns, execution time: ${x-b} ns`)}er("GPU",`${p}::${w}::${v}`)}e.unmap(),this.pendingQueries.delete(e)}),ft()}run(e,t,n,i,o,l){gt(e.name);let u=[];for(let $=0;$<t.length;++$){let P=t[$].data;if(P===0)continue;let I=this.gpuDataManager.get(P);if(!I)throw new Error(`no GPU data for input: ${P}`);u.push(I)}let{outputs:c,dispatchGroup:h,programUniforms:p}=e.getRunData(t),m=n.length===0?c.map(($,P)=>P):n;if(m.length!==c.length)throw new Error(`Output size ${m.length} must be equal to ${c.length}.`);let g=[],w=[];for(let $=0;$<c.length;++$){if(!Number.isInteger(m[$])||m[$]<-3||m[$]>=l)throw new Error(`Invalid output index: ${m[$]}`);if(m[$]===-3)continue;let P=m[$]===-1,I=m[$]===-2,B=P||I?o(c[$].dataType,c[$].dims):i(m[$],c[$].dataType,c[$].dims);if(g.push(B),B.data===0)continue;let q=this.gpuDataManager.get(B.data);if(!q)throw new Error(`no GPU data for output: ${B.data}`);if(P&&this.temporaryData.push(q),I){let H=this.kernelPersistentData.get(this.currentKernelId);H||(H=[],this.kernelPersistentData.set(this.currentKernelId,H)),H.push(q)}w.push(q)}if(u.length!==t.length||w.length!==g.length){if(w.length===0)return ft(e.name),g;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let v;if(p){let $=0,P=[];p.forEach(H=>{let ee=typeof H.data=="number"?[H.data]:H.data;if(ee.length===0)return;let ue=H.type===10?2:4,_e,Fe;H.type===10?(Fe=ee.length>4?16:ee.length>2?8:ee.length*ue,_e=ee.length>4?16:ue*ee.length):(Fe=ee.length<=2?ee.length*ue:16,_e=16),$=Math.ceil($/Fe)*Fe,P.push($);let Re=H.type===10?8:4;$+=ee.length>4?Math.ceil(ee.length/Re)*_e:ee.length*ue});let I=16;$=Math.ceil($/I)*I;let B=new ArrayBuffer($);p.forEach((H,ee)=>{let ue=P[ee],_e=typeof H.data=="number"?[H.data]:H.data;if(H.type===6)new Int32Array(B,ue,_e.length).set(_e);else if(H.type===12)new Uint32Array(B,ue,_e.length).set(_e);else if(H.type===10)new Uint16Array(B,ue,_e.length).set(_e);else if(H.type===1)new Float32Array(B,ue,_e.length).set(_e);else throw new Error(`Unsupported uniform type: ${Kt(H.type)}`)});let q=this.gpuDataManager.create($,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(q.buffer,0,B,0,$),this.gpuDataManager.release(q.id),v={offset:0,size:$,buffer:q.buffer}}let b=this.programManager.normalizeDispatchGroupSize(h),x=b[1]===1&&b[2]===1,M=Gh(e,t,x),k=this.programManager.getArtifact(M);if(k||(k=this.programManager.build(e,b),this.programManager.setArtifact(M,k),He("info",()=>`[artifact] key: ${M}, programName: ${e.name}`)),p&&k.uniformVariablesInfo){if(p.length!==k.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${k.uniformVariablesInfo.length}, got ${p.length} in program "${k.programInfo.name}".`);for(let $=0;$<p.length;$++){let P=p[$],I=P.type,B=typeof P.data=="number"?1:P.data.length,[q,H]=k.uniformVariablesInfo[$];if(I!==q||B!==H)throw new Error(`Uniform variable ${$} mismatch: expect type ${q} with size ${H}, got type ${I} with size ${B} in program "${k.programInfo.name}".`)}}if(He("info",()=>`[ProgramManager] run "${e.name}" (key=${M}) with ${b[0]}x${b[1]}x${b[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let $={kernelId:this.currentKernelId,programName:k.programInfo.name,inputTensorViews:t,outputTensorViews:g};this.pendingKernels.push($),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push($)}return this.programManager.run(k,u,w,b,v),ft(e.name),g}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,n,i){let o=Nh.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let l={kernelType:e,kernelName:i,kernelEntry:o[0],attributes:[o[1],n]};this.kernels.set(t,l)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let n of t)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let o=i.kernelType,l=i.kernelName,u=i.kernelEntry,c=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${l}" is not allowed to be called recursively`);this.currentKernelId=e,c[0]&&(c[1]=c[0](c[1]),c[0]=void 0),He("info",()=>`[WebGPU] Start to run kernel "[${o}] ${l}"...`);let h=this.env.debug;this.temporaryData=[];try{return h&&this.device.pushErrorScope("validation"),u(t,c[1]),0}catch(p){return n.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${l}" failed. ${p}`)),1}finally{h&&n.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${o}] ${l}": ${p.message}`:null));for(let p of this.temporaryData)this.gpuDataManager.release(p.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,i){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let l=o.get(t),u=this.gpuDataManager.registerExternalBuffer(n,i,l);return o.set(t,[u,n]),u}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[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,n){return async()=>{let i=await Bn(this,e,t);return Rr(i.buffer,n)}}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(){He("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(){He("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){He("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let i=0;i<n;i++){let o=this.getComputePassEncoder(),l=e[i];this.writeTimestamp(this.pendingDispatchNumber*2),o.setPipeline(l.computePipeline),o.setBindGroup(0,l.bindGroup),o.dispatchWorkgroups(...l.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()}}}),Hh={};N(Hh,{init:()=>Kh});var ki,jh,Kh,ng=S(()=>{Ie(),tr(),ke(),Ln(),ki=class cf{constructor(t,n,i,o){this.module=t,this.dataType=n,this.data=i,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=K.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=K.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=K.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=K.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(K.size(t)!==K.size(this.dims))throw new Error("Invalid new shape");return new cf(this.module,this.dataType,this.data,t)}},jh=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,o=n/e.PTR_SIZE,l=i===4?"i32":"i64";this.opKernelContext=Number(e.getValue(i*o++,l));let u=Number(e.getValue(i*o++,l));this.outputCount=Number(e.getValue(i*o++,l)),this.customDataOffset=Number(e.getValue(i*o++,"*")),this.customDataSize=Number(e.getValue(i*o++,l));let c=[];for(let h=0;h<u;h++){let p=Number(e.getValue(i*o++,l)),m=Number(e.getValue(i*o++,"*")),g=Number(e.getValue(i*o++,l)),w=[];for(let v=0;v<g;v++)w.push(Number(e.getValue(i*o++,l)));c.push(new ki(e,p,m,w))}this.inputs=c}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let n=t?.inputs?.map(u=>typeof u=="number"?this.inputs[u]:u)??this.inputs,i=t?.outputs??[],o=(u,c,h)=>new ki(this.module,c,this.output(u,h),h),l=(u,c)=>{let h=Qt(u,c);if(!h)throw new Error(`Unsupported data type: ${u}`);let p=h>0?this.backend.gpuDataManager.create(h).id:0;return new ki(this.module,u,p,c)};return this.backend.run(e,n,i,o,l,this.outputCount)}output(e,t){let n=this.module.stackSave();try{let i=this.module.PTR_SIZE,o=i===4?"i32":"i64",l=this.module.stackAlloc((1+t.length)*i);this.module.setValue(l,t.length,o);for(let u=0;u<t.length;u++)this.module.setValue(l+i*(u+1),t[u],o);return this.module._JsepOutput(this.opKernelContext,e,l)}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(n)}}},Kh=async(e,t,n,i)=>{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let l=(sg(),te(Fh)).WebGpuBackend,u=new l;await u.initialize(n,i),o("webgpu",[u,c=>u.alloc(Number(c)),c=>u.free(c),(c,h,p,m=!1)=>{if(m)He("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(c)}, dst=${Number(h)}, size=${Number(p)}`),u.memcpy(Number(c),Number(h));else{He("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(c)}, gpuDataId=${Number(h)}, size=${Number(p)}`);let g=t.HEAPU8.subarray(Number(c>>>0),Number(c>>>0)+Number(p));u.upload(Number(h),g)}},async(c,h,p)=>{He("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${c}, dataOffset=${h}, size=${p}`),await u.download(Number(c),()=>t.HEAPU8.subarray(Number(h)>>>0,Number(h+p)>>>0))},(c,h,p)=>u.createKernel(c,Number(h),p,t.UTF8ToString(t._JsepGetNodeName(Number(h)))),c=>u.releaseKernel(c),(c,h,p,m)=>{He("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${c}, contextDataOffset=${h}`);let g=new jh(t,u,Number(h));return u.computeKernel(Number(c),g,m)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else{let l=new zn(n);o("webnn",[l,()=>l.reserveTensorId(),u=>l.releaseTensorId(u),async(u,c,h,p,m)=>l.ensureTensor(u,c,h,p,m),(u,c)=>{l.uploadTensor(u,c)},async(u,c)=>l.downloadTensor(u,c),(u,c)=>l.registerMLContext(u,c),!!n.trace])}}}),Qh,Ba,Na,ls,Xh,Ua,Ri,Fa,Va,Ga,qa,Wa,Ha,Yh=S(()=>{yt(),Hi(),ji(),Ie(),Ht(),vs(),An(),Qh=(e,t)=>{Pe()._OrtInit(e,t)!==0&&Ce("Can't initialize onnxruntime.")},Ba=async e=>{Qh(e.wasm.numThreads,bs(e.logLevel))},Na=async(e,t)=>{Pe().asyncInit?.();let n=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.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 o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:o}),!n)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=(ng(),te(Hh)).init;t==="webgpu"&&await i("webgpu",Pe(),e,n),t==="webnn"&&await i("webnn",Pe(),e)}},ls=new Map,Xh=e=>{let t=Pe(),n=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,o,o+i)!==0&&Ce("Can't get session input/output count.");let l=i===4?"i32":"i64";return[Number(t.getValue(o,l)),Number(t.getValue(o+i,l))]}finally{t.stackRestore(n)}},Ua=(e,t)=>{let n=Pe(),i=n.stackSave(),o=0;try{let l=n.PTR_SIZE,u=n.stackAlloc(2*l);n._OrtGetInputOutputMetadata(e,t,u,u+l)!==0&&Ce("Can't get session input/output metadata.");let c=Number(n.getValue(u,"*"));o=Number(n.getValue(u+l,"*"));let h=n.HEAP32[o/4];if(h===0)return[c,0];let p=n.HEAPU32[o/4+1],m=[];for(let g=0;g<p;g++){let w=Number(n.getValue(o+8+g*l,"*"));m.push(w!==0?n.UTF8ToString(w):Number(n.getValue(o+8+(g+p)*l,"*")))}return[c,h,m]}finally{n.stackRestore(i),o!==0&&n._OrtFree(o)}},Ri=e=>{let t=Pe(),n=t._malloc(e.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Fa=async(e,t)=>{let n,i,o=Pe();Array.isArray(e)?[n,i]=e:e.buffer===o.HEAPU8.buffer?[n,i]=[e.byteOffset,e.byteLength]:[n,i]=Ri(e);let l=0,u=0,c=0,h=[],p=[],m=[];try{if([u,h]=await Rn(t),t?.externalData&&o.mountExternalData){let I=[];for(let B of t.externalData){let q=typeof B=="string"?B:B.path;I.push(Es(typeof B=="string"?B:B.data).then(H=>{o.mountExternalData(q,H)}))}await Promise.all(I)}for(let I of t?.executionProviders??[])if((typeof I=="string"?I:I.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof I!="string"){let B=I,q=B?.context,H=B?.gpuDevice,ee=B?.deviceType,ue=B?.powerPreference;q?o.currentContext=q:H?o.currentContext=await o.webnnCreateMLContext(H):o.currentContext=await o.webnnCreateMLContext({deviceType:ee,powerPreference:ue})}else o.currentContext=await o.webnnCreateMLContext();break}l=await o._OrtCreateSession(n,i,u),o.webgpuOnCreateSession?.(l),l===0&&Ce("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.webnnRegisterMLContext(l,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[g,w]=Xh(l),v=!!t?.enableGraphCapture,b=[],x=[],M=[],k=[],$=[];for(let I=0;I<g;I++){let[B,q,H]=Ua(l,I);B===0&&Ce("Can't get an input name."),p.push(B);let ee=o.UTF8ToString(B);b.push(ee),M.push(q===0?{name:ee,isTensor:!1}:{name:ee,isTensor:!0,type:Kt(q),shape:H})}for(let I=0;I<w;I++){let[B,q,H]=Ua(l,I+g);B===0&&Ce("Can't get an output name."),m.push(B);let ee=o.UTF8ToString(B);x.push(ee),k.push(q===0?{name:ee,isTensor:!1}:{name:ee,isTensor:!0,type:Kt(q),shape:H});{if(v&&t?.preferredOutputLocation===void 0){$.push("gpu-buffer");continue}let ue=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[ee]??"cpu",_e=o.webnnIsGraphOutput;if(ue==="cpu"&&_e&&_e(l,ee)){$.push("ml-tensor-cpu-output");continue}if(ue!=="cpu"&&ue!=="cpu-pinned"&&ue!=="gpu-buffer"&&ue!=="ml-tensor")throw new Error(`Not supported preferred output location: ${ue}.`);if(v&&ue!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${ue}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);$.push(ue)}}let P=null;return $.some(I=>I==="gpu-buffer"||I==="ml-tensor"||I==="ml-tensor-cpu-output")&&(c=o._OrtCreateBinding(l),c===0&&Ce("Can't create IO binding."),P={handle:c,outputPreferredLocations:$,outputPreferredLocationsEncoded:$.map(I=>I==="ml-tensor-cpu-output"?"ml-tensor":I).map(I=>Ws(I))}),ls.set(l,[l,p,m,P,v,!1]),[l,b,x,M,k]}catch(g){throw p.forEach(w=>o._OrtFree(w)),m.forEach(w=>o._OrtFree(w)),c!==0&&o._OrtReleaseBinding(c)!==0&&Ce("Can't release IO binding."),l!==0&&o._OrtReleaseSession(l)!==0&&Ce("Can't release session."),g}finally{o._free(n),u!==0&&o._OrtReleaseSessionOptions(u)!==0&&Ce("Can't release session options."),h.forEach(g=>o._free(g)),o.unmountExternalData?.()}},Va=e=>{let t=Pe(),n=ls.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,o,l,u,c]=n;u&&(c&&t._OrtClearBoundOutputs(u.handle)!==0&&Ce("Can't clear bound outputs."),t._OrtReleaseBinding(u.handle)!==0&&Ce("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),o.forEach(h=>t._OrtFree(h)),l.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(i)!==0&&Ce("Can't release session."),ls.delete(e)},Ga=async(e,t,n,i,o,l,u=!1)=>{if(!e){t.push(0);return}let c=Pe(),h=c.PTR_SIZE,p=e[0],m=e[1],g=e[3],w=g,v,b;if(p==="string"&&(g==="gpu-buffer"||g==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(u&&g!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${l} when enableGraphCapture is true.`);if(g==="gpu-buffer"){let k=e[2].gpuBuffer;b=Qt(jt(p),m);{let $=c.jsepRegisterBuffer;if(!$)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');v=$(i,l,k,b)}}else if(g==="ml-tensor"){let k=e[2].mlTensor;b=Qt(jt(p),m);let $=c.webnnRegisterMLTensor;if(!$)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');v=$(i,k,jt(p),m)}else{let k=e[2];if(Array.isArray(k)){b=h*k.length,v=c._malloc(b),n.push(v);for(let $=0;$<k.length;$++){if(typeof k[$]!="string")throw new TypeError(`tensor data at index ${$} is not a string`);c.setValue(v+$*h,mt(k[$],n),"*")}}else{let $=c.webnnIsGraphInput,P=c.webnnIsGraphOutput;if(p!=="string"&&$&&P){let I=c.UTF8ToString(o);if($(i,I)||P(i,I)){let B=jt(p);b=Qt(B,m),w="ml-tensor";let q=c.webnnCreateTemporaryTensor,H=c.webnnUploadTensor;if(!q||!H)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let ee=await q(i,B,m);H(ee,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),v=ee}else b=k.byteLength,v=c._malloc(b),n.push(v),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,b),v)}else b=k.byteLength,v=c._malloc(b),n.push(v),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,b),v)}}let x=c.stackSave(),M=c.stackAlloc(4*m.length);try{m.forEach(($,P)=>c.setValue(M+P*h,$,h===4?"i32":"i64"));let k=c._OrtCreateTensor(jt(p),v,b,M,m.length,Ws(w));k===0&&Ce(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(k)}finally{c.stackRestore(x)}},qa=async(e,t,n,i,o,l)=>{let u=Pe(),c=u.PTR_SIZE,h=ls.get(e);if(!h)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=h[0],m=h[1],g=h[2],w=h[3],v=h[4],b=h[5],x=t.length,M=i.length,k=0,$=[],P=[],I=[],B=[],q=[],H=u.stackSave(),ee=u.stackAlloc(x*c),ue=u.stackAlloc(x*c),_e=u.stackAlloc(M*c),Fe=u.stackAlloc(M*c);try{[k,$]=En(l),At("wasm prepareInputOutputTensor");for(let ye=0;ye<x;ye++)await Ga(n[ye],P,B,e,m[t[ye]],t[ye],v);for(let ye=0;ye<M;ye++)await Ga(o[ye],I,B,e,g[i[ye]],x+i[ye],v);Ct("wasm prepareInputOutputTensor");for(let ye=0;ye<x;ye++)u.setValue(ee+ye*c,P[ye],"*"),u.setValue(ue+ye*c,m[t[ye]],"*");for(let ye=0;ye<M;ye++)u.setValue(_e+ye*c,I[ye],"*"),u.setValue(Fe+ye*c,g[i[ye]],"*");if(w&&!b){let{handle:ye,outputPreferredLocations:xe,outputPreferredLocationsEncoded:Le}=w;if(m.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${m.length}).`);At("wasm bindInputsOutputs");for(let Ge=0;Ge<x;Ge++){let De=t[Ge];await u._OrtBindInput(ye,m[De],P[Ge])!==0&&Ce(`Can't bind input[${Ge}] for session=${e}.`)}for(let Ge=0;Ge<M;Ge++){let De=i[Ge];o[Ge]?.[3]?(q.push(I[Ge]),u._OrtBindOutput(ye,g[De],I[Ge],0)!==0&&Ce(`Can't bind pre-allocated output[${Ge}] for session=${e}.`)):u._OrtBindOutput(ye,g[De],0,Le[De])!==0&&Ce(`Can't bind output[${Ge}] to ${xe[Ge]} for session=${e}.`)}Ct("wasm bindInputsOutputs"),ls.set(e,[p,m,g,w,v,!0])}u.jsepOnRunStart?.(p),u.webnnOnRunStart?.(p);let Re;w?Re=await u._OrtRunWithBinding(p,w.handle,M,_e,k):Re=await u._OrtRun(p,ue,ee,x,Fe,M,_e,k),Re!==0&&Ce("failed to call OrtRun().");let Me=[],Qe=[];At("wasm ProcessOutputTensor");for(let ye=0;ye<M;ye++){let xe=Number(u.getValue(_e+ye*c,"*"));if(xe===I[ye]||q.includes(I[ye])){Me.push(o[ye]),xe!==I[ye]&&u._OrtReleaseTensor(xe)!==0&&Ce("Can't release tensor.");continue}let Le=u.stackSave(),Ge=u.stackAlloc(4*c),De=!1,je,oe=0;try{u._OrtGetTensorData(xe,Ge,Ge+c,Ge+2*c,Ge+3*c)!==0&&Ce(`Can't access output tensor data on index ${ye}.`);let Oe=c===4?"i32":"i64",Ae=Number(u.getValue(Ge,Oe));oe=u.getValue(Ge+c,"*");let $e=u.getValue(Ge+c*2,"*"),Dt=Number(u.getValue(Ge+c*3,Oe)),Xt=[];for(let nt=0;nt<Dt;nt++)Xt.push(Number(u.getValue($e+nt*c,Oe)));u._OrtFree($e)!==0&&Ce("Can't free memory for tensor dims.");let _t=Xt.reduce((nt,bt)=>nt*bt,1);je=Kt(Ae);let Yt=w?.outputPreferredLocations[i[ye]];if(je==="string"){if(Yt==="gpu-buffer"||Yt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let nt=[];for(let bt=0;bt<_t;bt++){let qr=u.getValue(oe+bt*c,"*"),ug=u.getValue(oe+(bt+1)*c,"*"),dg=bt===_t-1?void 0:ug-qr;nt.push(u.UTF8ToString(qr,dg))}Me.push([je,Xt,nt,"cpu"])}else if(Yt==="gpu-buffer"&&_t>0){let nt=u.jsepGetBuffer;if(!nt)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let bt=nt(oe),qr=Qt(Ae,_t);if(qr===void 0||!Ss(je))throw new Error(`Unsupported data type: ${je}`);De=!0,Me.push([je,Xt,{gpuBuffer:bt,download:u.jsepCreateDownloader(bt,qr,je),dispose:()=>{u._OrtReleaseTensor(xe)!==0&&Ce("Can't release tensor.")}},"gpu-buffer"])}else if(Yt==="ml-tensor"&&_t>0){let nt=u.webnnEnsureTensor,bt=u.webnnIsGraphInputOutputTypeSupported;if(!nt||!bt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Qt(Ae,_t)===void 0||!Ts(je))throw new Error(`Unsupported data type: ${je}`);if(!bt(e,je,!1))throw new Error(`preferredLocation "ml-tensor" for ${je} output is not supported by current WebNN Context.`);let qr=await nt(e,oe,Ae,Xt,!1);De=!0,Me.push([je,Xt,{mlTensor:qr,download:u.webnnCreateMLTensorDownloader(oe,je),dispose:()=>{u.webnnReleaseTensorId(oe),u._OrtReleaseTensor(xe)}},"ml-tensor"])}else if(Yt==="ml-tensor-cpu-output"&&_t>0){let nt=u.webnnCreateMLTensorDownloader(oe,je)(),bt=Me.length;De=!0,Qe.push((async()=>{let qr=[bt,await nt];return u.webnnReleaseTensorId(oe),u._OrtReleaseTensor(xe),qr})()),Me.push([je,Xt,[],"cpu"])}else{let nt=_s(je),bt=new nt(_t);new Uint8Array(bt.buffer,bt.byteOffset,bt.byteLength).set(u.HEAPU8.subarray(oe,oe+bt.byteLength)),Me.push([je,Xt,bt,"cpu"])}}finally{u.stackRestore(Le),je==="string"&&oe&&u._free(oe),De||u._OrtReleaseTensor(xe)}}w&&!v&&(u._OrtClearBoundOutputs(w.handle)!==0&&Ce("Can't clear bound outputs."),ls.set(e,[p,m,g,w,v,!1]));for(let[ye,xe]of await Promise.all(Qe))Me[ye][2]=xe;return Ct("wasm ProcessOutputTensor"),Me}finally{u.webnnOnRunEnd?.(p),u.stackRestore(H),P.forEach(Re=>u._OrtReleaseTensor(Re)),I.forEach(Re=>u._OrtReleaseTensor(Re)),B.forEach(Re=>u._free(Re)),k!==0&&u._OrtReleaseRunOptions(k),$.forEach(Re=>u._free(Re))}},Wa=e=>{let t=Pe(),n=ls.get(e);if(!n)throw new Error("invalid session id");let i=n[0],o=t._OrtEndProfiling(i);o===0&&Ce("Can't get an profile file name."),t._OrtFree(o)},Ha=e=>{let t=[];for(let n of e){let i=n[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),us,lr,dn,Yn,Jn,Ai,ja,Ii,zs,Ls,Jh,Zh,ep,tp,rp,sp,np,ip,ap=S(()=>{yt(),Yh(),Ht(),ms(),us=()=>!!me.wasm.proxy&&typeof document<"u",dn=!1,Yn=!1,Jn=!1,Ii=new Map,zs=(e,t)=>{let n=Ii.get(e);n?n.push(t):Ii.set(e,[t])},Ls=()=>{if(dn||!Yn||Jn||!lr)throw new Error("worker not ready")},Jh=e=>{switch(e.data.type){case"init-wasm":dn=!1,e.data.err?(Jn=!0,ja[1](e.data.err)):(Yn=!0,ja[0]()),Ai&&(URL.revokeObjectURL(Ai),Ai=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Ii.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Zh=async()=>{if(!Yn){if(dn)throw new Error("multiple calls to 'initWasm()' detected.");if(Jn)throw new Error("previous call to 'initWasm()' failed.");if(dn=!0,us())return new Promise((e,t)=>{lr?.terminate(),vn().then(([n,i])=>{try{lr=i,lr.onerror=l=>t(l),lr.onmessage=Jh,ja=[e,t];let o={type:"init-wasm",in:me};if(!o.in.wasm.wasmPaths&&n){let l=cs();l&&(o.in.wasm.wasmPaths=l)}lr.postMessage(o),Ai=n}catch(o){t(o)}},t)});try{await ws(me.wasm),await Ba(me),Yn=!0}catch(e){throw Jn=!0,e}finally{dn=!1}}},ep=async e=>{if(us())return Ls(),new Promise((t,n)=>{zs("init-ep",[t,n]);let i={type:"init-ep",in:{epName:e,env:me}};lr.postMessage(i)});await Na(me,e)},tp=async e=>us()?(Ls(),new Promise((t,n)=>{zs("copy-from",[t,n]);let i={type:"copy-from",in:{buffer:e}};lr.postMessage(i,[e.buffer])})):Ri(e),rp=async(e,t)=>{if(us()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ls(),new Promise((n,i)=>{zs("create",[n,i]);let o={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),lr.postMessage(o,l)})}else return Fa(e,t)},sp=async e=>{if(us())return Ls(),new Promise((t,n)=>{zs("release",[t,n]);let i={type:"release",in:e};lr.postMessage(i)});Va(e)},np=async(e,t,n,i,o,l)=>{if(us()){if(n.some(u=>u[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(u=>u))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ls(),new Promise((u,c)=>{zs("run",[u,c]);let h=n,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:h,outputIndices:i,options:l}};lr.postMessage(p,Ha(h))})}else return qa(e,t,n,i,o,l)},ip=async e=>{if(us())return Ls(),new Promise((t,n)=>{zs("end-profiling",[t,n]);let i={type:"end-profiling",in:e};lr.postMessage(i)});Wa(e)}}),Ka,op,lp,ig=S(()=>{yt(),ap(),Ie(),Lr(),An(),Ka=(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()}`)}},op=e=>{switch(e[3]){case"cpu":return new lt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Ss(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:o}=e[2];return lt.fromGpuBuffer(n,{dataType:t,dims:e[1],download:i,dispose:o})}case"ml-tensor":{let t=e[0];if(!Ts(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:o}=e[2];return lt.fromMLTensor(n,{dataType:t,dims:e[1],download:i,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},lp=class{async fetchModelAndCopyToWasmMemory(e){return tp(await Es(e))}async loadModel(e,t){gt();let n;typeof e=="string"?n=await this.fetchModelAndCopyToWasmMemory(e):n=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await rp(n,t),ft()}async dispose(){return sp(this.sessionId)}async run(e,t,n){gt();let i=[],o=[];Object.entries(e).forEach(g=>{let w=g[0],v=g[1],b=this.inputNames.indexOf(w);if(b===-1)throw new Error(`invalid input '${w}'`);i.push(v),o.push(b)});let l=[],u=[];Object.entries(t).forEach(g=>{let w=g[0],v=g[1],b=this.outputNames.indexOf(w);if(b===-1)throw new Error(`invalid output '${w}'`);l.push(v),u.push(b)});let c=i.map((g,w)=>Ka(g,()=>`input "${this.inputNames[o[w]]}"`)),h=l.map((g,w)=>g?Ka(g,()=>`output "${this.outputNames[u[w]]}"`):null),p=await np(this.sessionId,o,c,u,h,n),m={};for(let g=0;g<p.length;g++)m[this.outputNames[u[g]]]=l[g]??op(p[g]);return ft(),m}startProfiling(){}endProfiling(){ip(this.sessionId)}}}),up={};N(up,{OnnxruntimeWebAssemblyBackend:()=>Xa,initializeFlags:()=>Qa,wasmBackend:()=>dp});var Qa,Xa,dp,ag=S(()=>{yt(),ap(),ig(),Qa=()=>{(typeof me.wasm.initTimeout!="number"||me.wasm.initTimeout<0)&&(me.wasm.initTimeout=0);let e=me.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.`),me.wasm.simd=!1),typeof me.wasm.proxy!="boolean"&&(me.wasm.proxy=!1),typeof me.wasm.trace!="boolean"&&(me.wasm.trace=!1),typeof me.wasm.numThreads!="number"||!Number.isInteger(me.wasm.numThreads)||me.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)me.wasm.numThreads=1;else{let t=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;me.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Xa=class{async init(e){Qa(),await Zh(),await ep(e)}async createInferenceSessionHandler(e,t){let n=new lp;return await n.loadModel(e,t),n}},dp=new Xa}),cp={};N(cp,{InferenceSession:()=>zr,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>At,TRACE_EVENT_END:()=>Ct,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>ft,Tensor:()=>lt,default:()=>lg,env:()=>me,registerBackend:()=>J}),yt(),yt(),yt();var og="1.26.0",lg=xr;{let e=(ag(),te(up)).wasmBackend;J("webgpu",e,5),J("webnn",e,5),J("cpu",e,10),J("wasm",e,10)}return Object.defineProperty(me.versions,"web",{value:og,enumerable:!0}),te(cp)})();/**
|
|
2790
2790
|
* @license
|
|
2791
2791
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
2792
2792
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
@@ -2831,11 +2831,11 @@ ${l}`,c=n.createShaderModule({code:u,label:e.name});He("verbose",()=>`[WebGPU] $
|
|
|
2831
2831
|
* See the License for the specific language governing permissions and
|
|
2832
2832
|
* limitations under the License.
|
|
2833
2833
|
* =============================================================================
|
|
2834
|
-
*/d.exports=s})(so)),so.exports}var
|
|
2834
|
+
*/d.exports=s})(so)),so.exports}var Bs={},no={},Ep;function wy(){return Ep||(Ep=1,Object.defineProperty(no,"__esModule",{value:!0})),no}var ii={},$p;function vy(){if($p)return ii;$p=1;var d;Object.defineProperty(ii,"__esModule",{value:!0}),ii.SileroLegacy=void 0;const r=hi();class s{constructor(f,_,C,R,S){this.ortInstance=f,this._session=_,this._h=C,this._c=R,this._sr=S,this.reset_state=()=>{const N=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",N,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",N,[2,1,64])},this.process=async N=>{const te={input:new this.ortInstance.Tensor("float32",N,[1,N.length]),h:this._h,c:this._c,sr:this._sr},j=await this._session.run(te);this._h=j.hn,this._c=j.cn;const[se]=j.output?.data;return{notSpeech:1-se,isSpeech:se}},this.release=async()=>{await this._session.release(),this._h.dispose(),this._c.dispose(),this._sr.dispose()}}}return ii.SileroLegacy=s,d=s,s.new=async(a,f)=>{r.log.debug("initializing vad");const _=await f(),C=await a.InferenceSession.create(_),R=new a.Tensor("int64",[16000n]),S=Array(128).fill(0),N=new a.Tensor("float32",S,[2,1,64]),z=new a.Tensor("float32",S,[2,1,64]);return r.log.debug("vad is initialized"),new d(a,C,N,z,R)},ii}var ai={},xp;function _y(){if(xp)return ai;xp=1;var d;Object.defineProperty(ai,"__esModule",{value:!0}),ai.SileroV5=void 0;const r=hi();function s(f){const _=Array(256).fill(0);return new f.Tensor("float32",_,[2,1,128])}class a{constructor(_,C,R,S){this._session=_,this._state=C,this._sr=R,this.ortInstance=S,this.reset_state=()=>{this._state=s(this.ortInstance)},this.process=async N=>{const te={input:new this.ortInstance.Tensor("float32",N,[1,N.length]),state:this._state,sr:this._sr},j=await this._session.run(te);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 se=j.output.data[0];if(typeof se!="number")throw new Error("Weird output data");return{notSpeech:1-se,isSpeech:se}},this.release=async()=>{await this._session.release(),this._state.dispose(),this._sr.dispose()}}}return ai.SileroV5=a,d=a,a.new=async(f,_)=>{r.log.debug("Loading VAD...");const C=await _(),R=await f.InferenceSession.create(C),S=new f.Tensor("int64",[16000n]),N=s(f);return r.log.debug("...finished loading VAD"),new d(R,N,S,f)},ai}var Cp;function hf(){return Cp||(Cp=1,(function(d){var r=Bs&&Bs.__createBinding||(Object.create?(function(_,C,R,S){S===void 0&&(S=R);var N=Object.getOwnPropertyDescriptor(C,R);(!N||("get"in N?!C.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return C[R]}}),Object.defineProperty(_,S,N)}):(function(_,C,R,S){S===void 0&&(S=R),_[S]=C[R]})),s=Bs&&Bs.__exportStar||function(_,C){for(var R in _)R!=="default"&&!Object.prototype.hasOwnProperty.call(C,R)&&r(C,_,R)};Object.defineProperty(d,"__esModule",{value:!0}),d.SileroV5=d.SileroLegacy=void 0,s(wy(),d);var a=vy();Object.defineProperty(d,"SileroLegacy",{enumerable:!0,get:function(){return a.SileroLegacy}});var f=_y();Object.defineProperty(d,"SileroV5",{enumerable:!0,get:function(){return f.SileroV5}})})(Bs)),Bs}var oi={},kp;function pf(){if(kp)return oi;kp=1,Object.defineProperty(oi,"__esModule",{value:!0}),oi.Resampler=void 0;const d=hi();class r{constructor(a){this.options=a,this.process=f=>{const _=[];for(const C of f)for(this.inputBuffer.push(C);this.hasEnoughDataForFrame();){const R=this.generateOutputFrame();_.push(R)}return _},a.nativeSampleRate<16e3&&d.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(a){for(const f of a)for(this.inputBuffer.push(f);this.hasEnoughDataForFrame();)yield this.generateOutputFrame()}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){const a=new Float32Array(this.options.targetFrameSize);let f=0,_=0;for(;f<this.options.targetFrameSize;){let C=0,R=0;for(;_<Math.min(this.inputBuffer.length,(f+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const S=this.inputBuffer[_];S!==void 0&&(C+=S,R++),_++}a[f]=C/R,f++}return this.inputBuffer=this.inputBuffer.slice(_),a}}return oi.Resampler=r,oi}var Rp;function by(){return Rp||(Rp=1,(function(d){var r=Hr&&Hr.__createBinding||(Object.create?(function(j,se,J,Y){Y===void 0&&(Y=J);var W=Object.getOwnPropertyDescriptor(se,J);(!W||("get"in W?!se.__esModule:W.writable||W.configurable))&&(W={enumerable:!0,get:function(){return se[J]}}),Object.defineProperty(j,Y,W)}):(function(j,se,J,Y){Y===void 0&&(Y=J),j[Y]=se[J]})),s=Hr&&Hr.__setModuleDefault||(Object.create?(function(j,se){Object.defineProperty(j,"default",{enumerable:!0,value:se})}):function(j,se){j.default=se}),a=Hr&&Hr.__importStar||function(j){if(j&&j.__esModule)return j;var se={};if(j!=null)for(var J in j)J!=="default"&&Object.prototype.hasOwnProperty.call(j,J)&&r(se,j,J);return s(se,j),se};Object.defineProperty(d,"__esModule",{value:!0}),d.NonRealTimeVAD=d.defaultNonRealTimeVADOptions=void 0;const f=a(yy()),_=uf(),C=Io(),R=Mo(),S=qi(),N=hf(),z=pf();d.defaultNonRealTimeVADOptions={...R.defaultFrameProcessorOptions,modelURL:_.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:C.defaultModelFetcher};class te{static async new(se={}){const J={...d.defaultNonRealTimeVADOptions,...se};(0,R.validateOptions)(J),J.ortConfig!==void 0&&J.ortConfig(f);const Y=()=>J.modelFetcher(J.modelURL),W=await N.SileroLegacy.new(f,Y),ne=new R.FrameProcessor(W.process,W.reset_state,{positiveSpeechThreshold:J.positiveSpeechThreshold,negativeSpeechThreshold:J.negativeSpeechThreshold,redemptionMs:J.redemptionMs,preSpeechPadMs:J.preSpeechPadMs,minSpeechMs:J.minSpeechMs,submitUserSpeechOnPause:J.submitUserSpeechOnPause},1536/16);return ne.resume(),new this(Y,f,J,ne)}constructor(se,J,Y,W){this.modelFetcher=se,this.ort=J,this.options=Y,this.frameProcessor=W,this.frameSamples=1536}async*run(se,J){const Y={nativeSampleRate:J,targetSampleRate:16e3,targetFrameSize:this.frameSamples},W=new z.Resampler(Y);let ne=0,fe=0,de=0;for await(const pe of W.stream(se)){const he=[];await this.frameProcessor.process(pe,Ve=>{he.push(Ve)});for(const Ve of he)switch(Ve.msg){case S.Message.SpeechStart:ne=de*this.frameSamples/16;break;case S.Message.SpeechEnd:fe=(de+1)*this.frameSamples/16,yield{audio:Ve.audio,start:ne,end:fe};break}de++}const ce=[];this.frameProcessor.endSegment(pe=>{ce.push(pe)});for(const pe of ce)switch(pe.msg){case S.Message.SpeechEnd:yield{audio:pe.audio,start:ne,end:de*this.frameSamples/16}}}}d.NonRealTimeVAD=te})(Hr)),Hr}var _r={},Ap;function Sy(){if(Ap)return _r;Ap=1,Object.defineProperty(_r,"__esModule",{value:!0}),_r.audioFileToArray=_r.encodeWAV=_r.arrayBufferToBase64=_r.minFramesForTargetMS=void 0;function d(R,S,N=16e3){return Math.ceil(R*N/1e3/S)}_r.minFramesForTargetMS=d;function r(R){const S=new Uint8Array(R),N=S.byteLength,z=new Array(N);for(let te=0;te<N;te++){const j=S[te];if(j===void 0)break;z[te]=String.fromCharCode(j)}return btoa(z.join(""))}_r.arrayBufferToBase64=r;function s(R,S=3,N=16e3,z=1,te=32){const j=te/8,se=z*j,J=new ArrayBuffer(44+R.length*j),Y=new DataView(J);return _(Y,0,"RIFF"),Y.setUint32(4,36+R.length*j,!0),_(Y,8,"WAVE"),_(Y,12,"fmt "),Y.setUint32(16,16,!0),Y.setUint16(20,S,!0),Y.setUint16(22,z,!0),Y.setUint32(24,N,!0),Y.setUint32(28,N*se,!0),Y.setUint16(32,se,!0),Y.setUint16(34,te,!0),_(Y,36,"data"),Y.setUint32(40,R.length*j,!0),S===1?f(Y,44,R):a(Y,44,R),J}_r.encodeWAV=s;function a(R,S,N){for(let z=0;z<N.length;z++,S+=4)R.setFloat32(S,N[z],!0)}function f(R,S,N){for(let z=0;z<N.length;z++,S+=2){const te=Math.max(-1,Math.min(1,N[z]));R.setInt16(S,te<0?te*32768:te*32767,!0)}}function _(R,S,N){for(let z=0;z<N.length;z++)R.setUint8(S+z,N.charCodeAt(z))}async function C(R){const S=new OfflineAudioContext(1,1,44100),N=new FileReader;let z=null;if(await new Promise(se=>{N.addEventListener("loadend",()=>{const J=N.result;S.decodeAudioData(J,Y=>{z=Y,S.startRendering().then(()=>{console.log("Rendering completed successfully"),se()}).catch(W=>{console.error("Rendering failed: ",W)})},Y=>{console.log("Error with decoding audio data: ",Y)})}),N.readAsArrayBuffer(R)}),z===null)throw Error("some shit");const te=z,j=new Float32Array(te.length);for(let se=0;se<te.length;se++)for(let J=0;J<te.numberOfChannels;J++){const Y=te.getChannelData(J)[se],W=j[se];if(Y===void 0||W===void 0)throw new Error("sample or out[i] is undefined");j[se]=W+Y}return{audio:j,sampleRate:te.sampleRate}}return _r.audioFileToArray=C,_r}var jr={},io={exports:{}};/*!
|
|
2835
2835
|
* ONNX Runtime Web v1.26.0
|
|
2836
2836
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2837
2837
|
* Licensed under the MIT License.
|
|
2838
|
-
*/var Ip;function Ty(){return Ip||(Ip=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,_=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(y=>typeof ur<"u"?ur:typeof Proxy<"u"?new Proxy(y,{get:(E,A)=>(typeof ur<"u"?ur:E)[A]}):y)(function(y){if(typeof ur<"u")return ur.apply(this,arguments);throw Error('Dynamic require of "'+y+'" is not supported')}),b=(y,E)=>()=>(y&&(E=y(y=0)),E),U=(y,E)=>{for(var A in E)a(y,A,{get:E[A],enumerable:!0})},z=(y,E,A,D)=>{if(E&&typeof E=="object"||typeof E=="function")for(let O of _(E))!C.call(y,O)&&O!==A&&a(y,O,{get:()=>E[O],enumerable:!(D=f(E,O))||D.enumerable});return y},re=y=>z(a({},"__esModule",{value:!0}),y),K,se,J,Y,H,ne=b(()=>{K=new Map,se=[],J=(y,E,A)=>{if(E&&typeof E.init=="function"&&typeof E.createInferenceSessionHandler=="function"){let D=K.get(y);if(D===void 0)K.set(y,{backend:E,priority:A});else{if(D.priority>A)return;if(D.priority===A&&D.backend!==E)throw new Error(`cannot register backend "${y}" using priority ${A}`)}if(A>=0){let O=se.indexOf(y);O!==-1&&se.splice(O,1);for(let G=0;G<se.length;G++)if(K.get(se[G]).priority<=A){se.splice(G,0,y);return}se.push(y)}return}throw new TypeError("not a valid backend")},Y=async y=>{let E=K.get(y);if(!E)return"backend not found.";if(E.initialized)return E.backend;if(E.aborted)return E.error;{let A=!!E.initPromise;try{return A||(E.initPromise=E.backend.init(y)),await E.initPromise,E.initialized=!0,E.backend}catch(D){return A||(E.error=`${D}`,E.aborted=!0),E.error}finally{delete E.initPromise}}},H=async y=>{let E=y.executionProviders||[],A=E.map(V=>typeof V=="string"?V:V.name),D=A.length===0?se:A,O,G=[],N=new Set;for(let V of D){let te=await Y(V);typeof te=="string"?G.push({name:V,err:te}):(O||(O=te),O===te&&N.add(V))}if(!O)throw new Error(`no available backend found. ERR: ${G.map(V=>`[${V.name}] ${V.err}`).join(", ")}`);for(let{name:V,err:te}of G)A.includes(V)&&console.warn(`removing requested execution provider "${V}" from session options because it is not available: ${te}`);let L=E.filter(V=>N.has(typeof V=="string"?V:V.name));return[O,new Proxy(y,{get:(V,te)=>te==="executionProviders"?L:Reflect.get(V,te)})]}}),ve=b(()=>{ne()}),de,ce=b(()=>{de="1.26.0"}),pe,he,Ve=b(()=>{ce(),pe="warning",he={wasm:{},webgl:{},webgpu:{},versions:{common:de},set logLevel(y){if(y!==void 0){if(typeof y!="string"||["verbose","info","warning","error","fatal"].indexOf(y)===-1)throw new Error(`Unsupported logging level: ${y}`);pe=y}},get logLevel(){return pe}},Object.defineProperty(he,"logLevel",{enumerable:!0})}),fe,Je=b(()=>{Ve(),fe=he}),qe,ot,Ze=b(()=>{qe=(y,E)=>{let A=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);A.width=y.dims[3],A.height=y.dims[2];let D=A.getContext("2d");if(D!=null){let O,G;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(O=y.dims[2],G=y.dims[3]):(O=y.dims[3],G=y.dims[2]);let N=E?.format!==void 0?E.format:"RGB",L=E?.norm,V,te;L===void 0||L.mean===void 0?V=[255,255,255,255]:typeof L.mean=="number"?V=[L.mean,L.mean,L.mean,L.mean]:(V=[L.mean[0],L.mean[1],L.mean[2],0],L.mean[3]!==void 0&&(V[3]=L.mean[3])),L===void 0||L.bias===void 0?te=[0,0,0,0]:typeof L.bias=="number"?te=[L.bias,L.bias,L.bias,L.bias]:(te=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(te[3]=L.bias[3]));let ie=G*O,Z=0,Q=ie,Se=ie*2,F=-1;N==="RGBA"?(Z=0,Q=ie,Se=ie*2,F=ie*3):N==="RGB"?(Z=0,Q=ie,Se=ie*2):N==="RBG"&&(Z=0,Se=ie,Q=ie*2);for(let le=0;le<G;le++)for(let ut=0;ut<O;ut++){let Be=(y.data[Z++]-te[0])*V[0],Te=(y.data[Q++]-te[1])*V[1],Ne=(y.data[Se++]-te[2])*V[2],ye=F===-1?255:(y.data[F++]-te[3])*V[3];D.fillStyle="rgba("+Be+","+Te+","+Ne+","+ye+")",D.fillRect(ut,le,1,1)}if("toDataURL"in A)return A.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},ot=(y,E)=>{let A=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),D;if(A!=null){let O,G,N;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(O=y.dims[2],G=y.dims[1],N=y.dims[3]):(O=y.dims[3],G=y.dims[2],N=y.dims[1]);let L=E!==void 0&&E.format!==void 0?E.format:"RGB",V=E?.norm,te,ie;V===void 0||V.mean===void 0?te=[255,255,255,255]:typeof V.mean=="number"?te=[V.mean,V.mean,V.mean,V.mean]:(te=[V.mean[0],V.mean[1],V.mean[2],255],V.mean[3]!==void 0&&(te[3]=V.mean[3])),V===void 0||V.bias===void 0?ie=[0,0,0,0]:typeof V.bias=="number"?ie=[V.bias,V.bias,V.bias,V.bias]:(ie=[V.bias[0],V.bias[1],V.bias[2],0],V.bias[3]!==void 0&&(ie[3]=V.bias[3]));let Z=G*O;if(E!==void 0&&(E.format!==void 0&&N===4&&E.format!=="RGBA"||N===3&&E.format!=="RGB"&&E.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Q=4,Se=0,F=1,le=2,ut=3,Be=0,Te=Z,Ne=Z*2,ye=-1;L==="RGBA"?(Be=0,Te=Z,Ne=Z*2,ye=Z*3):L==="RGB"?(Be=0,Te=Z,Ne=Z*2):L==="RBG"&&(Be=0,Ne=Z,Te=Z*2),D=A.createImageData(O,G);for(let Rt=0;Rt<G*O;Se+=Q,F+=Q,le+=Q,ut+=Q,Rt++)D.data[Se]=(y.data[Be++]-ie[0])*te[0],D.data[F]=(y.data[Te++]-ie[1])*te[1],D.data[le]=(y.data[Ne++]-ie[2])*te[2],D.data[ut]=ye===-1?255:(y.data[ye++]-ie[3])*te[3]}else throw new Error("Can not access image data");return D}}),it,tt,Wt,xt,je,We,st=b(()=>{Tr(),it=(y,E)=>{if(y===void 0)throw new Error("Image buffer must be defined");if(E.height===void 0||E.width===void 0)throw new Error("Image height and width must be defined");if(E.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:A,width:D}=E,O=E.norm??{mean:255,bias:0},G,N;typeof O.mean=="number"?G=[O.mean,O.mean,O.mean,O.mean]:G=[O.mean[0],O.mean[1],O.mean[2],O.mean[3]??255],typeof O.bias=="number"?N=[O.bias,O.bias,O.bias,O.bias]:N=[O.bias[0],O.bias[1],O.bias[2],O.bias[3]??0];let L=E.format!==void 0?E.format:"RGBA",V=E.tensorFormat!==void 0&&E.tensorFormat!==void 0?E.tensorFormat:"RGB",te=A*D,ie=V==="RGBA"?new Float32Array(te*4):new Float32Array(te*3),Z=4,Q=0,Se=1,F=2,le=3,ut=0,Be=te,Te=te*2,Ne=-1;L==="RGB"&&(Z=3,Q=0,Se=1,F=2,le=-1),V==="RGBA"?Ne=te*3:V==="RBG"?(ut=0,Te=te,Be=te*2):V==="BGR"&&(Te=0,Be=te,ut=te*2);for(let ye=0;ye<te;ye++,Q+=Z,F+=Z,Se+=Z,le+=Z)ie[ut++]=(y[Q]+N[0])/G[0],ie[Be++]=(y[Se]+N[1])/G[1],ie[Te++]=(y[F]+N[2])/G[2],Ne!==-1&&le!==-1&&(ie[Ne++]=(y[le]+N[3])/G[3]);return V==="RGBA"?new rt("float32",ie,[1,4,A,D]):new rt("float32",ie,[1,3,A,D])},tt=async(y,E)=>{let A=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,D=typeof ImageData<"u"&&y instanceof ImageData,O=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,G=typeof y=="string",N,L=E??{},V=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},te=ie=>typeof HTMLCanvasElement<"u"&&ie instanceof HTMLCanvasElement||ie instanceof OffscreenCanvas?ie.getContext("2d"):null;if(A){let ie=V();ie.width=y.width,ie.height=y.height;let Z=te(ie);if(Z!=null){let Q=y.height,Se=y.width;if(E!==void 0&&E.resizedHeight!==void 0&&E.resizedWidth!==void 0&&(Q=E.resizedHeight,Se=E.resizedWidth),E!==void 0){if(L=E,E.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");L.tensorFormat="RGBA",L.height=Q,L.width=Se}else L.tensorFormat="RGBA",L.height=Q,L.width=Se;Z.drawImage(y,0,0),N=Z.getImageData(0,0,Se,Q).data}else throw new Error("Can not access image data")}else if(D){let ie,Z;if(E!==void 0&&E.resizedWidth!==void 0&&E.resizedHeight!==void 0?(ie=E.resizedHeight,Z=E.resizedWidth):(ie=y.height,Z=y.width),E!==void 0&&(L=E),L.format="RGBA",L.height=ie,L.width=Z,E!==void 0){let Q=V();Q.width=Z,Q.height=ie;let Se=te(Q);if(Se!=null)Se.putImageData(y,0,0),N=Se.getImageData(0,0,Z,ie).data;else throw new Error("Can not access image data")}else N=y.data}else if(O){if(E===void 0)throw new Error("Please provide image config with format for Imagebitmap");let ie=V();ie.width=y.width,ie.height=y.height;let Z=te(ie);if(Z!=null){let Q=y.height,Se=y.width;return Z.drawImage(y,0,0,Se,Q),N=Z.getImageData(0,0,Se,Q).data,L.height=Q,L.width=Se,it(N,L)}else throw new Error("Can not access image data")}else{if(G)return new Promise((ie,Z)=>{let Q=V(),Se=te(Q);if(!y||!Se)return Z();let F=new Image;F.crossOrigin="Anonymous",F.src=y,F.onload=()=>{Q.width=F.width,Q.height=F.height,Se.drawImage(F,0,0,Q.width,Q.height);let le=Se.getImageData(0,0,Q.width,Q.height);L.height=Q.height,L.width=Q.width,ie(it(le.data,L))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(N!==void 0)return it(N,L);throw new Error("Input data provided is not supported - aborted tensor creation")},Wt=(y,E)=>{let{width:A,height:D,download:O,dispose:G}=E,N=[1,D,A,4];return new rt({location:"texture",type:"float32",texture:y,dims:N,download:O,dispose:G})},xt=(y,E)=>{let{dataType:A,dims:D,download:O,dispose:G}=E;return new rt({location:"gpu-buffer",type:A??"float32",gpuBuffer:y,dims:D,download:O,dispose:G})},je=(y,E)=>{let{dataType:A,dims:D,download:O,dispose:G}=E;return new rt({location:"ml-tensor",type:A??"float32",mlTensor:y,dims:D,download:O,dispose:G})},We=(y,E,A)=>new rt({location:"cpu-pinned",type:y,data:E,dims:A??[E.length]})}),ze,At,sr,Hr,Us=b(()=>{ze=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),At=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),sr=!1,Hr=()=>{if(!sr){sr=!0;let y=typeof BigInt64Array<"u"&&BigInt64Array.from,E=typeof BigUint64Array<"u"&&BigUint64Array.from,A=globalThis.Float16Array,D=typeof A<"u"&&A.from;y&&(ze.set("int64",BigInt64Array),At.set(BigInt64Array,"int64")),E&&(ze.set("uint64",BigUint64Array),At.set(BigUint64Array,"uint64")),D?(ze.set("float16",A),At.set(A,"float16")):ze.set("float16",Uint16Array)}}}),Kr,jr,Fs=b(()=>{Tr(),Kr=y=>{let E=1;for(let A=0;A<y.length;A++){let D=y[A];if(typeof D!="number"||!Number.isSafeInteger(D))throw new TypeError(`dims[${A}] must be an integer, got: ${D}`);if(D<0)throw new RangeError(`dims[${A}] must be a non-negative integer, got: ${D}`);E*=D}return E},jr=(y,E)=>{switch(y.location){case"cpu":return new rt(y.type,y.data,E);case"cpu-pinned":return new rt({location:"cpu-pinned",data:y.data,type:y.type,dims:E});case"texture":return new rt({location:"texture",texture:y.texture,type:y.type,dims:E});case"gpu-buffer":return new rt({location:"gpu-buffer",gpuBuffer:y.gpuBuffer,type:y.type,dims:E});case"ml-tensor":return new rt({location:"ml-tensor",mlTensor:y.mlTensor,type:y.type,dims:E});default:throw new Error(`tensorReshape: tensor location ${y.location} is not supported`)}}}),rt,Tr=b(()=>{Ze(),st(),Us(),Fs(),rt=class{constructor(y,E,A){Hr();let D,O;if(typeof y=="object"&&"location"in y)switch(this.dataLocation=y.location,D=y.type,O=y.dims,y.location){case"cpu-pinned":{let N=ze.get(D);if(!N)throw new TypeError(`unsupported type "${D}" to create tensor from pinned buffer`);if(!(y.data instanceof N))throw new TypeError(`buffer should be of type ${N.name}`);this.cpuData=y.data;break}case"texture":{if(D!=="float32")throw new TypeError(`unsupported type "${D}" to create tensor from texture`);this.gpuTextureData=y.texture,this.downloader=y.download,this.disposer=y.dispose;break}case"gpu-buffer":{if(D!=="float32"&&D!=="float16"&&D!=="int32"&&D!=="int64"&&D!=="uint32"&&D!=="uint8"&&D!=="bool"&&D!=="uint4"&&D!=="int4")throw new TypeError(`unsupported type "${D}" to create tensor from gpu buffer`);this.gpuBufferData=y.gpuBuffer,this.downloader=y.download,this.disposer=y.dispose;break}case"ml-tensor":{if(D!=="float32"&&D!=="float16"&&D!=="int32"&&D!=="int64"&&D!=="uint32"&&D!=="uint64"&&D!=="int8"&&D!=="uint8"&&D!=="bool"&&D!=="uint4"&&D!=="int4")throw new TypeError(`unsupported type "${D}" to create tensor from MLTensor`);this.mlTensorData=y.mlTensor,this.downloader=y.download,this.disposer=y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let N,L;if(typeof y=="string")if(D=y,L=A,y==="string"){if(!Array.isArray(E))throw new TypeError("A string tensor's data must be a string array.");N=E}else{let V=ze.get(y);if(V===void 0)throw new TypeError(`Unsupported tensor type: ${y}.`);if(Array.isArray(E)){if(y==="float16"&&V===Uint16Array||y==="uint4"||y==="int4")throw new TypeError(`Creating a ${y} tensor from number array is not supported. Please use ${V.name} as data.`);y==="uint64"||y==="int64"?N=V.from(E,BigInt):N=V.from(E)}else if(E instanceof V)N=E;else if(E instanceof Uint8ClampedArray)if(y==="uint8")N=Uint8Array.from(E);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(y==="float16"&&E instanceof Uint16Array&&V!==Uint16Array)N=new globalThis.Float16Array(E.buffer,E.byteOffset,E.length);else throw new TypeError(`A ${D} tensor's data must be type of ${V}`)}else if(L=E,Array.isArray(y)){if(y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let V=typeof y[0];if(V==="string")D="string",N=y;else if(V==="boolean")D="bool",N=Uint8Array.from(y);else throw new TypeError(`Invalid element type of data array: ${V}.`)}else if(y instanceof Uint8ClampedArray)D="uint8",N=Uint8Array.from(y);else{let V=At.get(y.constructor);if(V===void 0)throw new TypeError(`Unsupported type for tensor data: ${y.constructor}.`);D=V,N=y}if(L===void 0)L=[N.length];else if(!Array.isArray(L))throw new TypeError("A tensor's dims must be a number array");O=L,this.cpuData=N,this.dataLocation="cpu"}let G=Kr(O);if(this.cpuData&&G!==this.cpuData.length&&!((D==="uint4"||D==="int4")&&Math.ceil(G/2)===this.cpuData.length))throw new Error(`Tensor's size(${G}) does not match data length(${this.cpuData.length}).`);this.type=D,this.dims=O,this.size=G}static async fromImage(y,E){return tt(y,E)}static fromTexture(y,E){return Wt(y,E)}static fromGpuBuffer(y,E){return xt(y,E)}static fromMLTensor(y,E){return je(y,E)}static fromPinnedBuffer(y,E,A){return We(y,E,A)}toDataURL(y){return qe(this,y)}toImageData(y){return ot(this,y)}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(y){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 E=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=E,y&&this.disposer&&(this.disposer(),this.disposer=void 0),E}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(y){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return jr(this,y)}}}),lt,Qr=b(()=>{Tr(),lt=rt}),er,Er,gt,yt,Ct,kt,Xr=b(()=>{Ve(),er=(y,E)=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeStamp(`${y}::ORT::${E}`)},Er=(y,E)=>{let A=new Error().stack?.split(/\r\n|\r|\n/g)||[],D=!1;for(let O=0;O<A.length;O++){if(D&&!A[O].includes("TRACE_FUNC")){let G=`FUNC_${y}::${A[O].trim().split(" ")[1]}`;E&&(G+=`::${E}`),er("CPU",G);return}A[O].includes("TRACE_FUNC")&&(D=!0)}},gt=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||Er("BEGIN",y)},yt=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||Er("END",y)},Ct=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.time(`ORT::${y}`)},kt=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeEnd(`ORT::${y}`)}}),os,xe=b(()=>{ne(),Qr(),Xr(),os=class ff{constructor(E){this.handler=E}async run(E,A,D){gt(),Ct("InferenceSession.run");let O={},G={};if(typeof E!="object"||E===null||E instanceof lt||Array.isArray(E))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let N=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof lt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");N=!1;for(let te of A){if(typeof te!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(te)===-1)throw new RangeError(`'fetches' contains invalid output name: ${te}.`);O[te]=null}if(typeof D=="object"&&D!==null)G=D;else if(typeof D<"u")throw new TypeError("'options' must be an object.")}else{let te=!1,ie=Object.getOwnPropertyNames(A);for(let Z of this.outputNames)if(ie.indexOf(Z)!==-1){let Q=A[Z];(Q===null||Q instanceof lt)&&(te=!0,N=!1,O[Z]=Q)}if(te){if(typeof D=="object"&&D!==null)G=D;else if(typeof D<"u")throw new TypeError("'options' must be an object.")}else G=A}}else if(typeof A<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let te of this.inputNames)if(typeof E[te]>"u")throw new Error(`input '${te}' is missing in 'feeds'.`);if(N)for(let te of this.outputNames)O[te]=null;let L=await this.handler.run(E,O,G),V={};for(let te in L)if(Object.hasOwnProperty.call(L,te)){let ie=L[te];ie instanceof lt?V[te]=ie:V[te]=new lt(ie.type,ie.data,ie.dims)}return kt("InferenceSession.run"),yt(),V}async release(){return this.handler.dispose()}static async create(E,A,D,O){gt(),Ct("InferenceSession.create");let G,N={};if(typeof E=="string"){if(G=E,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(E instanceof Uint8Array){if(G=E,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(E instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&E instanceof SharedArrayBuffer){let ie=E,Z=0,Q=E.byteLength;if(typeof A=="object"&&A!==null)N=A;else if(typeof A=="number"){if(Z=A,!Number.isSafeInteger(Z))throw new RangeError("'byteOffset' must be an integer.");if(Z<0||Z>=ie.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${ie.byteLength}).`);if(Q=E.byteLength-Z,typeof D=="number"){if(Q=D,!Number.isSafeInteger(Q))throw new RangeError("'byteLength' must be an integer.");if(Q<=0||Z+Q>ie.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${ie.byteLength-Z}].`);if(typeof O=="object"&&O!==null)N=O;else if(typeof O<"u")throw new TypeError("'options' must be an object.")}else if(typeof D<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof A<"u")throw new TypeError("'options' must be an object.");G=new Uint8Array(ie,Z,Q)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[L,V]=await H(N),te=await L.createInferenceSessionHandler(G,V);return kt("InferenceSession.create"),yt(),new ff(te)}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}}}),Qe,Nt=b(()=>{xe(),Qe=os}),nr=b(()=>{}),It=b(()=>{}),Yr=b(()=>{}),hn=b(()=>{}),ls={};U(ls,{InferenceSession:()=>Qe,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>Ct,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>yt,Tensor:()=>lt,env:()=>fe,registerBackend:()=>J});var ct=b(()=>{ve(),Je(),Nt(),Qr(),nr(),It(),Xr(),Yr(),hn()}),Ut=b(()=>{}),$r={};U($r,{default:()=>pn});var Lt,us,pn,Wi=b(()=>{Mn(),Ht(),fs(),Lt="ort-wasm-proxy-worker",us=globalThis.self?.name===Lt,us&&(self.onmessage=y=>{let{type:E,in:A}=y.data;try{switch(E){case"init-wasm":ys(A.wasm).then(()=>{Gs(A).then(()=>{postMessage({type:E})},D=>{postMessage({type:E,err:D})})},D=>{postMessage({type:E,err:D})});break;case"init-ep":{let{epName:D,env:O}=A;qs(O,D).then(()=>{postMessage({type:E})},G=>{postMessage({type:E,err:G})});break}case"copy-from":{let{buffer:D}=A,O=He(D);postMessage({type:E,out:O});break}case"create":{let{model:D,options:O}=A;tr(D,O).then(G=>{postMessage({type:E,out:G})},G=>{postMessage({type:E,err:G})});break}case"release":Ks(A),postMessage({type:E});break;case"run":{let{sessionId:D,inputIndices:O,inputs:G,outputIndices:N,options:L}=A;j(D,O,G,N,new Array(N.length).fill(null),L).then(V=>{V.some(te=>te[3]!=="cpu")?postMessage({type:E,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:E,out:V},js([...G,...V]))},V=>{postMessage({type:E,err:V})});break}case"end-profiling":Jr(A),postMessage({type:E});break;default:}}catch(D){postMessage({type:E,err:D})}}),pn=us?null:y=>new Worker(y??at,{type:"classic",name:Lt})}),fn,mn,at,ds,Dr,gn,yn,cs,wn,hs,vn,ps,_n,fs=b(()=>{Ut(),fn=typeof location>"u"?void 0:location.origin,mn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,at=mn(),ds=()=>{if(at&&!at.startsWith("blob:"))return at.substring(0,at.lastIndexOf("/")+1)},Dr=(y,E)=>{try{let A=E??at;return(A?new URL(y,A):new URL(y)).origin===fn}catch{return!1}},gn=(y,E)=>{let A=E??at;try{return(A?new URL(y,A):new URL(y)).href}catch{return}},yn=(y,E)=>`${E??"./"}${y}`,cs=async y=>{let E=await(await fetch(y,{credentials:"same-origin"})).blob();return URL.createObjectURL(E)},wn=async y=>(await import(y)).default,hs=(Wi(),re($r)).default,vn=async()=>{if(!at)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Dr(at))return[void 0,hs()];let y=await cs(at);return[y,hs(y)]},ps=void 0,_n=async(y,E,A,D)=>{let O=ps&&!(y||E);if(O)if(at)O=Dr(at)||D&&!A;else if(D&&!A)O=!0;else throw new Error("cannot determine the script source URL.");if(O)return[void 0,ps];{let G="ort-wasm-simd-threaded.mjs",N=y??gn(G,E),L=A&&N&&!Dr(N,E),V=L?await cs(N):N??yn(G,E);return[L?V:void 0,await wn(V)]}}}),ms,zr,dr,gs,bn,Sn,Tn,ys,Pe,Ht=b(()=>{fs(),zr=!1,dr=!1,gs=!1,bn=()=>{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}},Sn=()=>{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}},Tn=()=>{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}},ys=async y=>{if(zr)return Promise.resolve();if(dr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(gs)throw new Error("previous call to 'initializeWebAssembly()' failed.");dr=!0;let E=y.initTimeout,A=y.numThreads;if(y.simd!==!1){if(y.simd==="relaxed"){if(!Tn())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Sn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let D=bn();A>1&&!D&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+A+", 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."),y.numThreads=A=1);let O=y.wasmPaths,G=typeof O=="string"?O:void 0,N=O?.mjs,L=N?.href??N,V=O?.wasm,te=V?.href??V,ie=y.wasmBinary,[Z,Q]=await _n(L,G,A>1,!!ie||!!te),Se=!1,F=[];if(E>0&&F.push(new Promise(le=>{setTimeout(()=>{Se=!0,le()},E)})),F.push(new Promise((le,ut)=>{let Be={numThreads:A};if(ie)Be.wasmBinary=ie,Be.locateFile=Te=>Te;else if(te||G)Be.locateFile=Te=>te??G+Te;else if(L&&L.indexOf("blob:")!==0)Be.locateFile=Te=>new URL(Te,L).href;else if(Z){let Te=ds();Te&&(Be.locateFile=Ne=>Te+Ne)}Q(Be).then(Te=>{dr=!1,zr=!0,ms=Te,le(),Z&&URL.revokeObjectURL(Z)},Te=>{dr=!1,gs=!0,ut(Te)})})),await Promise.race(F),Se)throw new Error(`WebAssembly backend initializing failed due to timeout: ${E}ms`)},Pe=()=>{if(zr&&ms)return ms;throw new Error("WebAssembly is not initialized yet.")}}),mt,Lr,Ce,ws=b(()=>{Ht(),mt=(y,E)=>{let A=Pe(),D=A.lengthBytesUTF8(y)+1,O=A._malloc(D);return A.stringToUTF8(y,O,D),E.push(O),O},Lr=(y,E,A,D)=>{if(typeof y=="object"&&y!==null){if(A.has(y))throw new Error("Circular reference in options");A.add(y)}Object.entries(y).forEach(([O,G])=>{let N=E?E+O:O;if(typeof G=="object")Lr(G,N+".",A,D);else if(typeof G=="string"||typeof G=="number")D(N,G.toString());else if(typeof G=="boolean")D(N,G?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof G}`)})},Ce=y=>{let E=Pe(),A=E.stackSave();try{let D=E.PTR_SIZE,O=E.stackAlloc(2*D);E._OrtGetLastError(O,O+D);let G=Number(E.getValue(O,D===4?"i32":"i64")),N=E.getValue(O+D,"*"),L=N?E.UTF8ToString(N):"";throw new Error(`${y} ERROR_CODE: ${G}, ERROR_MESSAGE: ${L}`)}finally{E.stackRestore(A)}}}),En,Hi=b(()=>{Ht(),ws(),En=y=>{let E=Pe(),A=0,D=[],O=y||{};try{if(y?.logSeverityLevel===void 0)O.logSeverityLevel=2;else if(typeof y.logSeverityLevel!="number"||!Number.isInteger(y.logSeverityLevel)||y.logSeverityLevel<0||y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${y.logSeverityLevel}`);if(y?.logVerbosityLevel===void 0)O.logVerbosityLevel=0;else if(typeof y.logVerbosityLevel!="number"||!Number.isInteger(y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${y.logVerbosityLevel}`);y?.terminate===void 0&&(O.terminate=!1);let G=0;return y?.tag!==void 0&&(G=mt(y.tag,D)),A=E._OrtCreateRunOptions(O.logSeverityLevel,O.logVerbosityLevel,!!O.terminate,G),A===0&&Ce("Can't create run options."),y?.extra!==void 0&&Lr(y.extra,"",new WeakSet,(N,L)=>{let V=mt(N,D),te=mt(L,D);E._OrtAddRunConfigEntry(A,V,te)!==0&&Ce(`Can't set a run config entry: ${N} - ${L}.`)}),[A,D]}catch(G){throw A!==0&&E._OrtReleaseRunOptions(A),D.forEach(N=>E._free(N)),G}}}),$n,xn,Cn,Ft,kn,Rn,Ki=b(()=>{Ht(),ws(),$n=y=>{switch(y){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: ${y}`)}},xn=y=>{switch(y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${y}`)}},Cn=y=>{y.extra||(y.extra={}),y.extra.session||(y.extra.session={});let E=y.extra.session;E.use_ort_model_bytes_directly||(E.use_ort_model_bytes_directly="1"),y.executionProviders&&y.executionProviders.some(A=>(typeof A=="string"?A:A.name)==="webgpu")&&(y.enableMemPattern=!1)},Ft=(y,E,A,D)=>{let O=mt(E,D),G=mt(A,D);Pe()._OrtAddSessionConfigEntry(y,O,G)!==0&&Ce(`Can't set a session config entry: ${E} - ${A}.`)},kn=async(y,E,A)=>{let D=E.executionProviders;for(let O of D){let G=typeof O=="string"?O:O.name,N=[];switch(G){case"webnn":if(G="WEBNN",Ft(y,"session.disable_quant_qdq","1",A),Ft(y,"session.disable_qdq_constant_folding","1",A),typeof O!="string"){let Z=O?.deviceType;Z&&Ft(y,"deviceType",Z,A)}break;case"webgpu":if(G="JS",typeof O!="string"){let Z=O;if(Z?.preferredLayout){if(Z.preferredLayout!=="NCHW"&&Z.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${Z.preferredLayout}`);Ft(y,"preferredLayout",Z.preferredLayout,A)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${G}`)}let L=mt(G,A),V=N.length,te=0,ie=0;if(V>0){te=Pe()._malloc(V*Pe().PTR_SIZE),A.push(te),ie=Pe()._malloc(V*Pe().PTR_SIZE),A.push(ie);for(let Z=0;Z<V;Z++)Pe().setValue(te+Z*Pe().PTR_SIZE,N[Z][0],"*"),Pe().setValue(ie+Z*Pe().PTR_SIZE,N[Z][1],"*")}await Pe()._OrtAppendExecutionProvider(y,L,te,ie,V)!==0&&Ce(`Can't append execution provider: ${G}.`)}},Rn=async y=>{let E=Pe(),A=0,D=[],O=y||{};Cn(O);try{let G=$n(O.graphOptimizationLevel??"all"),N=xn(O.executionMode??"sequential"),L=typeof O.logId=="string"?mt(O.logId,D):0,V=O.logSeverityLevel??2;if(!Number.isInteger(V)||V<0||V>4)throw new Error(`log severity level is not valid: ${V}`);let te=O.logVerbosityLevel??0;if(!Number.isInteger(te)||te<0||te>4)throw new Error(`log verbosity level is not valid: ${te}`);let ie=typeof O.optimizedModelFilePath=="string"?mt(O.optimizedModelFilePath,D):0;if(A=E._OrtCreateSessionOptions(G,!!O.enableCpuMemArena,!!O.enableMemPattern,N,!!O.enableProfiling,0,L,V,te,ie),A===0&&Ce("Can't create session options."),O.executionProviders&&await kn(A,O,D),O.enableGraphCapture!==void 0){if(typeof O.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${O.enableGraphCapture}`);Ft(A,"enableGraphCapture",O.enableGraphCapture.toString(),D)}if(O.freeDimensionOverrides)for(let[Z,Q]of Object.entries(O.freeDimensionOverrides)){if(typeof Z!="string")throw new Error(`free dimension override name must be a string: ${Z}`);if(typeof Q!="number"||!Number.isInteger(Q)||Q<0)throw new Error(`free dimension override value must be a non-negative integer: ${Q}`);let Se=mt(Z,D);E._OrtAddFreeDimensionOverride(A,Se,Q)!==0&&Ce(`Can't set a free dimension override: ${Z} - ${Q}.`)}return O.extra!==void 0&&Lr(O.extra,"",new WeakSet,(Z,Q)=>{Ft(A,Z,Q,D)}),[A,D]}catch(G){throw A!==0&&E._OrtReleaseSessionOptions(A)!==0&&Ce("Can't release session options."),D.forEach(N=>E._free(N)),G}}}),Kt,jt,Qt,vs,_s,bs,Ss,Vs,Ie=b(()=>{Kt=y=>{switch(y){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: ${y}`)}},jt=y=>{switch(y){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: ${y}`)}},Qt=(y,E)=>{let A=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][y],D=typeof E=="number"?E:E.reduce((O,G)=>O*G,1);return A>0?Math.ceil(D*A):void 0},vs=y=>{switch(y){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: ${y}`)}},_s=y=>{switch(y){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: ${y}`)}},bs=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Ss=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint64"||y==="int8"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Vs=y=>{switch(y){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: ${y}`)}}}),Ts,An=b(()=>{Ut(),Ts=async y=>{if(typeof y=="string"){let E=await fetch(y);if(!E.ok)throw new Error(`failed to load external data file: ${y}`);let A=E.headers.get("Content-Length"),D=A?parseInt(A,10):0;if(D<1073741824)return new Uint8Array(await E.arrayBuffer());{if(!E.body)throw new Error(`failed to load external data file: ${y}, no response body.`);let O=E.body.getReader(),G;try{G=new ArrayBuffer(D)}catch(L){if(L instanceof RangeError){let V=Math.ceil(D/65536);G=new WebAssembly.Memory({initial:V,maximum:V}).buffer}else throw L}let N=0;for(;;){let{done:L,value:V}=await O.read();if(L)break;let te=V.byteLength;new Uint8Array(G,N,te).set(V),N+=te}return new Uint8Array(G,0,D)}}else return y instanceof Blob?new Uint8Array(await y.arrayBuffer()):y instanceof Uint8Array?y:new Uint8Array(y)}}),In,Gs,qs,xr,Ws,Hs,He,tr,Ks,Cr,j,Jr,js,Mn=b(()=>{ct(),Hi(),Ki(),Ie(),Ht(),ws(),An(),In=(y,E)=>{Pe()._OrtInit(y,E)!==0&&Ce("Can't initialize onnxruntime.")},Gs=async y=>{In(y.wasm.numThreads,_s(y.logLevel))},qs=async(y,E)=>{Pe().asyncInit?.();let A=y.webgpu.adapter;if(E==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(A){if(typeof A.limits!="object"||typeof A.features!="object"||typeof A.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let D=y.webgpu.powerPreference;if(D!==void 0&&D!=="low-power"&&D!=="high-performance")throw new Error(`Invalid powerPreference setting: "${D}"`);let O=y.webgpu.forceFallbackAdapter;if(O!==void 0&&typeof O!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${O}"`);if(A=await navigator.gpu.requestAdapter({powerPreference:D,forceFallbackAdapter:O}),!A)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(E==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},xr=new Map,Ws=y=>{let E=Pe(),A=E.stackSave();try{let D=E.PTR_SIZE,O=E.stackAlloc(2*D);E._OrtGetInputOutputCount(y,O,O+D)!==0&&Ce("Can't get session input/output count.");let G=D===4?"i32":"i64";return[Number(E.getValue(O,G)),Number(E.getValue(O+D,G))]}finally{E.stackRestore(A)}},Hs=(y,E)=>{let A=Pe(),D=A.stackSave(),O=0;try{let G=A.PTR_SIZE,N=A.stackAlloc(2*G);A._OrtGetInputOutputMetadata(y,E,N,N+G)!==0&&Ce("Can't get session input/output metadata.");let L=Number(A.getValue(N,"*"));O=Number(A.getValue(N+G,"*"));let V=A.HEAP32[O/4];if(V===0)return[L,0];let te=A.HEAPU32[O/4+1],ie=[];for(let Z=0;Z<te;Z++){let Q=Number(A.getValue(O+8+Z*G,"*"));ie.push(Q!==0?A.UTF8ToString(Q):Number(A.getValue(O+8+(Z+te)*G,"*")))}return[L,V,ie]}finally{A.stackRestore(D),O!==0&&A._OrtFree(O)}},He=y=>{let E=Pe(),A=E._malloc(y.byteLength);if(A===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${y.byteLength}.`);return E.HEAPU8.set(y,A),[A,y.byteLength]},tr=async(y,E)=>{let A,D,O=Pe();Array.isArray(y)?[A,D]=y:y.buffer===O.HEAPU8.buffer?[A,D]=[y.byteOffset,y.byteLength]:[A,D]=He(y);let G=0,N=0,L=[],V=[],te=[];try{if([N,L]=await Rn(E),E?.externalData&&O.mountExternalData){let Te=[];for(let Ne of E.externalData){let ye=typeof Ne=="string"?Ne:Ne.path;Te.push(Ts(typeof Ne=="string"?Ne:Ne.data).then(Rt=>{O.mountExternalData(ye,Rt)}))}await Promise.all(Te)}for(let Te of E?.executionProviders??[])if((typeof Te=="string"?Te:Te.name)==="webnn"){if(O.shouldTransferToMLTensor=!1,typeof Te!="string"){let Ne=Te,ye=Ne?.context,Rt=Ne?.gpuDevice,Mt=Ne?.deviceType,Ar=Ne?.powerPreference;ye?O.currentContext=ye:Rt?O.currentContext=await O.webnnCreateMLContext(Rt):O.currentContext=await O.webnnCreateMLContext({deviceType:Mt,powerPreference:Ar})}else O.currentContext=await O.webnnCreateMLContext();break}G=await O._OrtCreateSession(A,D,N),O.webgpuOnCreateSession?.(G),G===0&&Ce("Can't create a session."),O.jsepOnCreateSession?.(),O.currentContext&&(O.webnnRegisterMLContext(G,O.currentContext),O.currentContext=void 0,O.shouldTransferToMLTensor=!0);let[ie,Z]=Ws(G),Q=!!E?.enableGraphCapture,Se=[],F=[],le=[],ut=[],Be=[];for(let Te=0;Te<ie;Te++){let[Ne,ye,Rt]=Hs(G,Te);Ne===0&&Ce("Can't get an input name."),V.push(Ne);let Mt=O.UTF8ToString(Ne);Se.push(Mt),le.push(ye===0?{name:Mt,isTensor:!1}:{name:Mt,isTensor:!0,type:jt(ye),shape:Rt})}for(let Te=0;Te<Z;Te++){let[Ne,ye,Rt]=Hs(G,Te+ie);Ne===0&&Ce("Can't get an output name."),te.push(Ne);let Mt=O.UTF8ToString(Ne);F.push(Mt),ut.push(ye===0?{name:Mt,isTensor:!1}:{name:Mt,isTensor:!0,type:jt(ye),shape:Rt})}return xr.set(G,[G,V,te,null,Q,!1]),[G,Se,F,le,ut]}catch(ie){throw V.forEach(Z=>O._OrtFree(Z)),te.forEach(Z=>O._OrtFree(Z)),G!==0&&O._OrtReleaseSession(G)!==0&&Ce("Can't release session."),ie}finally{O._free(A),N!==0&&O._OrtReleaseSessionOptions(N)!==0&&Ce("Can't release session options."),L.forEach(ie=>O._free(ie)),O.unmountExternalData?.()}},Ks=y=>{let E=Pe(),A=xr.get(y);if(!A)throw new Error(`cannot release session. invalid session id: ${y}`);let[D,O,G,N,L]=A;N&&(L&&E._OrtClearBoundOutputs(N.handle)!==0&&Ce("Can't clear bound outputs."),E._OrtReleaseBinding(N.handle)!==0&&Ce("Can't release IO binding.")),E.jsepOnReleaseSession?.(y),E.webnnOnReleaseSession?.(y),E.webgpuOnReleaseSession?.(y),O.forEach(V=>E._OrtFree(V)),G.forEach(V=>E._OrtFree(V)),E._OrtReleaseSession(D)!==0&&Ce("Can't release session."),xr.delete(y)},Cr=async(y,E,A,D,O,G,N=!1)=>{if(!y){E.push(0);return}let L=Pe(),V=L.PTR_SIZE,te=y[0],ie=y[1],Z=y[3],Q=Z,Se,F;if(te==="string"&&(Z==="gpu-buffer"||Z==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(N&&Z!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${G} when enableGraphCapture is true.`);if(Z==="gpu-buffer"){let Be=y[2].gpuBuffer;F=Qt(Kt(te),ie);{let Te=L.jsepRegisterBuffer;if(!Te)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Se=Te(D,G,Be,F)}}else if(Z==="ml-tensor"){let Be=y[2].mlTensor;F=Qt(Kt(te),ie);let Te=L.webnnRegisterMLTensor;if(!Te)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Se=Te(D,Be,Kt(te),ie)}else{let Be=y[2];if(Array.isArray(Be)){F=V*Be.length,Se=L._malloc(F),A.push(Se);for(let Te=0;Te<Be.length;Te++){if(typeof Be[Te]!="string")throw new TypeError(`tensor data at index ${Te} is not a string`);L.setValue(Se+Te*V,mt(Be[Te],A),"*")}}else{let Te=L.webnnIsGraphInput,Ne=L.webnnIsGraphOutput;if(te!=="string"&&Te&&Ne){let ye=L.UTF8ToString(O);if(Te(D,ye)||Ne(D,ye)){let Rt=Kt(te);F=Qt(Rt,ie),Q="ml-tensor";let Mt=L.webnnCreateTemporaryTensor,Ar=L.webnnUploadTensor;if(!Mt||!Ar)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let rs=await Mt(D,Rt,ie);Ar(rs,new Uint8Array(Be.buffer,Be.byteOffset,Be.byteLength)),Se=rs}else F=Be.byteLength,Se=L._malloc(F),A.push(Se),L.HEAPU8.set(new Uint8Array(Be.buffer,Be.byteOffset,F),Se)}else F=Be.byteLength,Se=L._malloc(F),A.push(Se),L.HEAPU8.set(new Uint8Array(Be.buffer,Be.byteOffset,F),Se)}}let le=L.stackSave(),ut=L.stackAlloc(4*ie.length);try{ie.forEach((Te,Ne)=>L.setValue(ut+Ne*V,Te,V===4?"i32":"i64"));let Be=L._OrtCreateTensor(Kt(te),Se,F,ut,ie.length,Vs(Q));Be===0&&Ce(`Can't create tensor for input/output. session=${D}, index=${G}.`),E.push(Be)}finally{L.stackRestore(le)}},j=async(y,E,A,D,O,G)=>{let N=Pe(),L=N.PTR_SIZE,V=xr.get(y);if(!V)throw new Error(`cannot run inference. invalid session id: ${y}`);let te=V[0],ie=V[1],Z=V[2],Q=V[3],Se=V[4];V[5];let F=E.length,le=D.length,ut=0,Be=[],Te=[],Ne=[],ye=[],Rt=[],Mt=N.stackSave(),Ar=N.stackAlloc(F*L),rs=N.stackAlloc(F*L),nn=N.stackAlloc(le*L),Un=N.stackAlloc(le*L);try{[ut,Be]=En(G),Ct("wasm prepareInputOutputTensor");for(let Ue=0;Ue<F;Ue++)await Cr(A[Ue],Te,ye,y,ie[E[Ue]],E[Ue],Se);for(let Ue=0;Ue<le;Ue++)await Cr(O[Ue],Ne,ye,y,Z[D[Ue]],F+D[Ue],Se);kt("wasm prepareInputOutputTensor");for(let Ue=0;Ue<F;Ue++)N.setValue(Ar+Ue*L,Te[Ue],"*"),N.setValue(rs+Ue*L,ie[E[Ue]],"*");for(let Ue=0;Ue<le;Ue++)N.setValue(nn+Ue*L,Ne[Ue],"*"),N.setValue(Un+Ue*L,Z[D[Ue]],"*");N.jsepOnRunStart?.(te),N.webnnOnRunStart?.(te);let ht;ht=await N._OrtRun(te,rs,Ar,F,Un,le,nn,ut),ht!==0&&Ce("failed to call OrtRun().");let ir=[],Fn=[];Ct("wasm ProcessOutputTensor");for(let Ue=0;Ue<le;Ue++){let rr=Number(N.getValue(nn+Ue*L,"*"));if(rr===Ne[Ue]||Rt.includes(Ne[Ue])){ir.push(O[Ue]),rr!==Ne[Ue]&&N._OrtReleaseTensor(rr)!==0&&Ce("Can't release tensor.");continue}let mi=N.stackSave(),pr=N.stackAlloc(4*L),Cs=!1,wt,Bt=0;try{N._OrtGetTensorData(rr,pr,pr+L,pr+2*L,pr+3*L)!==0&&Ce(`Can't access output tensor data on index ${Ue}.`);let an=L===4?"i32":"i64",ks=Number(N.getValue(pr,an));Bt=N.getValue(pr+L,"*");let Vn=N.getValue(pr+L*2,"*"),gi=Number(N.getValue(pr+L*3,an)),Et=[];for(let vt=0;vt<gi;vt++)Et.push(Number(N.getValue(Vn+vt*L,an)));N._OrtFree(Vn)!==0&&Ce("Can't free memory for tensor dims.");let fr=Et.reduce((vt,pt)=>vt*pt,1);wt=jt(ks);let ss=Q?.outputPreferredLocations[D[Ue]];if(wt==="string"){if(ss==="gpu-buffer"||ss==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let vt=[];for(let pt=0;pt<fr;pt++){let ar=N.getValue(Bt+pt*L,"*"),yi=N.getValue(Bt+(pt+1)*L,"*"),wi=pt===fr-1?void 0:yi-ar;vt.push(N.UTF8ToString(ar,wi))}ir.push([wt,Et,vt,"cpu"])}else if(ss==="gpu-buffer"&&fr>0){let vt=N.jsepGetBuffer;if(!vt)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let pt=vt(Bt),ar=Qt(ks,fr);if(ar===void 0||!bs(wt))throw new Error(`Unsupported data type: ${wt}`);Cs=!0,ir.push([wt,Et,{gpuBuffer:pt,download:N.jsepCreateDownloader(pt,ar,wt),dispose:()=>{N._OrtReleaseTensor(rr)!==0&&Ce("Can't release tensor.")}},"gpu-buffer"])}else if(ss==="ml-tensor"&&fr>0){let vt=N.webnnEnsureTensor,pt=N.webnnIsGraphInputOutputTypeSupported;if(!vt||!pt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Qt(ks,fr)===void 0||!Ss(wt))throw new Error(`Unsupported data type: ${wt}`);if(!pt(y,wt,!1))throw new Error(`preferredLocation "ml-tensor" for ${wt} output is not supported by current WebNN Context.`);let ar=await vt(y,Bt,ks,Et,!1);Cs=!0,ir.push([wt,Et,{mlTensor:ar,download:N.webnnCreateMLTensorDownloader(Bt,wt),dispose:()=>{N.webnnReleaseTensorId(Bt),N._OrtReleaseTensor(rr)}},"ml-tensor"])}else if(ss==="ml-tensor-cpu-output"&&fr>0){let vt=N.webnnCreateMLTensorDownloader(Bt,wt)(),pt=ir.length;Cs=!0,Fn.push((async()=>{let ar=[pt,await vt];return N.webnnReleaseTensorId(Bt),N._OrtReleaseTensor(rr),ar})()),ir.push([wt,Et,[],"cpu"])}else{let vt=vs(wt),pt=new vt(fr);new Uint8Array(pt.buffer,pt.byteOffset,pt.byteLength).set(N.HEAPU8.subarray(Bt,Bt+pt.byteLength)),ir.push([wt,Et,pt,"cpu"])}}finally{N.stackRestore(mi),wt==="string"&&Bt&&N._free(Bt),Cs||N._OrtReleaseTensor(rr)}}Q&&!Se&&(N._OrtClearBoundOutputs(Q.handle)!==0&&Ce("Can't clear bound outputs."),xr.set(y,[te,ie,Z,Q,Se,!1]));for(let[Ue,rr]of await Promise.all(Fn))ir[Ue][2]=rr;return kt("wasm ProcessOutputTensor"),ir}finally{N.webnnOnRunEnd?.(te),N.stackRestore(Mt),Te.forEach(ht=>N._OrtReleaseTensor(ht)),Ne.forEach(ht=>N._OrtReleaseTensor(ht)),ye.forEach(ht=>N._free(ht)),ut!==0&&N._OrtReleaseRunOptions(ut),Be.forEach(ht=>N._free(ht))}},Jr=y=>{let E=Pe(),A=xr.get(y);if(!A)throw new Error("invalid session id");let D=A[0],O=E._OrtEndProfiling(D);O===0&&Ce("Can't get an profile file name."),E._OrtFree(O)},js=y=>{let E=[];for(let A of y){let D=A[2];!Array.isArray(D)&&"buffer"in D&&E.push(D.buffer)}return E}}),cr,ke,kr,Zr,Br,es,Es,$s,hr,Rr,Qs,Xs,Ys,Pn,On,pi,ts,Dn,zn=b(()=>{ct(),Mn(),Ht(),fs(),cr=()=>!!fe.wasm.proxy&&typeof document<"u",kr=!1,Zr=!1,Br=!1,$s=new Map,hr=(y,E)=>{let A=$s.get(y);A?A.push(E):$s.set(y,[E])},Rr=()=>{if(kr||!Zr||Br||!ke)throw new Error("worker not ready")},Qs=y=>{switch(y.data.type){case"init-wasm":kr=!1,y.data.err?(Br=!0,Es[1](y.data.err)):(Zr=!0,Es[0]()),es&&(URL.revokeObjectURL(es),es=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let E=$s.get(y.data.type);y.data.err?E.shift()[1](y.data.err):E.shift()[0](y.data.out);break}}},Xs=async()=>{if(!Zr){if(kr)throw new Error("multiple calls to 'initWasm()' detected.");if(Br)throw new Error("previous call to 'initWasm()' failed.");if(kr=!0,cr())return new Promise((y,E)=>{ke?.terminate(),vn().then(([A,D])=>{try{ke=D,ke.onerror=G=>E(G),ke.onmessage=Qs,Es=[y,E];let O={type:"init-wasm",in:fe};if(!O.in.wasm.wasmPaths&&A){let G=ds();G&&(O.in.wasm.wasmPaths=G)}ke.postMessage(O),es=A}catch(O){E(O)}},E)});try{await ys(fe.wasm),await Gs(fe),Zr=!0}catch(y){throw Br=!0,y}finally{kr=!1}}},Ys=async y=>{if(cr())return Rr(),new Promise((E,A)=>{hr("init-ep",[E,A]);let D={type:"init-ep",in:{epName:y,env:fe}};ke.postMessage(D)});await qs(fe,y)},Pn=async y=>cr()?(Rr(),new Promise((E,A)=>{hr("copy-from",[E,A]);let D={type:"copy-from",in:{buffer:y}};ke.postMessage(D,[y.buffer])})):He(y),On=async(y,E)=>{if(cr()){if(E?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Rr(),new Promise((A,D)=>{hr("create",[A,D]);let O={type:"create",in:{model:y,options:{...E}}},G=[];y instanceof Uint8Array&&G.push(y.buffer),ke.postMessage(O,G)})}else return tr(y,E)},pi=async y=>{if(cr())return Rr(),new Promise((E,A)=>{hr("release",[E,A]);let D={type:"release",in:y};ke.postMessage(D)});Ks(y)},ts=async(y,E,A,D,O,G)=>{if(cr()){if(A.some(N=>N[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(O.some(N=>N))throw new Error("pre-allocated output tensor is not supported for proxy.");return Rr(),new Promise((N,L)=>{hr("run",[N,L]);let V=A,te={type:"run",in:{sessionId:y,inputIndices:E,inputs:V,outputIndices:D,options:G}};ke.postMessage(te,js(V))})}else return j(y,E,A,D,O,G)},Dn=async y=>{if(cr())return Rr(),new Promise((E,A)=>{hr("end-profiling",[E,A]);let D={type:"end-profiling",in:y};ke.postMessage(D)});Jr(y)}}),Ln,Js,Zs,en=b(()=>{ct(),zn(),Ie(),Ut(),An(),Ln=(y,E)=>{switch(y.location){case"cpu":return[y.type,y.dims,y.data,"cpu"];case"gpu-buffer":return[y.type,y.dims,{gpuBuffer:y.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[y.type,y.dims,{mlTensor:y.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${y.location} for ${E()}`)}},Js=y=>{switch(y[3]){case"cpu":return new lt(y[0],y[2],y[1]);case"gpu-buffer":{let E=y[0];if(!bs(E))throw new Error(`not supported data type: ${E} for deserializing GPU tensor`);let{gpuBuffer:A,download:D,dispose:O}=y[2];return lt.fromGpuBuffer(A,{dataType:E,dims:y[1],download:D,dispose:O})}case"ml-tensor":{let E=y[0];if(!Ss(E))throw new Error(`not supported data type: ${E} for deserializing MLTensor tensor`);let{mlTensor:A,download:D,dispose:O}=y[2];return lt.fromMLTensor(A,{dataType:E,dims:y[1],download:D,dispose:O})}default:throw new Error(`invalid data location: ${y[3]}`)}},Zs=class{async fetchModelAndCopyToWasmMemory(y){return Pn(await Ts(y))}async loadModel(y,E){gt();let A;typeof y=="string"?A=await this.fetchModelAndCopyToWasmMemory(y):A=y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await On(A,E),yt()}async dispose(){return pi(this.sessionId)}async run(y,E,A){gt();let D=[],O=[];Object.entries(y).forEach(Z=>{let Q=Z[0],Se=Z[1],F=this.inputNames.indexOf(Q);if(F===-1)throw new Error(`invalid input '${Q}'`);D.push(Se),O.push(F)});let G=[],N=[];Object.entries(E).forEach(Z=>{let Q=Z[0],Se=Z[1],F=this.outputNames.indexOf(Q);if(F===-1)throw new Error(`invalid output '${Q}'`);G.push(Se),N.push(F)});let L=D.map((Z,Q)=>Ln(Z,()=>`input "${this.inputNames[O[Q]]}"`)),V=G.map((Z,Q)=>Z?Ln(Z,()=>`output "${this.outputNames[N[Q]]}"`):null),te=await ts(this.sessionId,O,L,N,V,A),ie={};for(let Z=0;Z<te.length;Z++)ie[this.outputNames[N[Z]]]=G[Z]??Js(te[Z]);return yt(),ie}startProfiling(){}endProfiling(){Dn(this.sessionId)}}}),xs={};U(xs,{OnnxruntimeWebAssemblyBackend:()=>rn,initializeFlags:()=>tn,wasmBackend:()=>sn});var tn,rn,sn,Bn=b(()=>{ct(),zn(),en(),tn=()=>{(typeof fe.wasm.initTimeout!="number"||fe.wasm.initTimeout<0)&&(fe.wasm.initTimeout=0);let y=fe.wasm.simd;if(typeof y!="boolean"&&y!==void 0&&y!=="fixed"&&y!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${y}". Reset it to \`false\` and ignore SIMD feature checking.`),fe.wasm.simd=!1),typeof fe.wasm.proxy!="boolean"&&(fe.wasm.proxy=!1),typeof fe.wasm.trace!="boolean"&&(fe.wasm.trace=!1),typeof fe.wasm.numThreads!="number"||!Number.isInteger(fe.wasm.numThreads)||fe.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)fe.wasm.numThreads=1;else{let E=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;fe.wasm.numThreads=Math.min(4,Math.ceil((E||1)/2))}},rn=class{async init(y){tn(),await Xs(),await Ys(y)}async createInferenceSessionHandler(y,E){let A=new Zs;return await A.loadModel(y,E),A}},sn=new rn}),Nn={};U(Nn,{InferenceSession:()=>Qe,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>Ct,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>yt,Tensor:()=>lt,default:()=>ji,env:()=>fe,registerBackend:()=>J}),ct(),ct(),ct();var fi="1.26.0",ji=ls;{let y=(Bn(),re(xs)).wasmBackend;J("cpu",y,10),J("wasm",y,10)}return Object.defineProperty(fe.versions,"web",{value:fi,enumerable:!0}),re(Nn)})();d.exports=s})(io)),io.exports}var Mp;function Ey(){return Mp||(Mp=1,(function(d){var r=Gr&&Gr.__createBinding||(Object.create?(function(de,ce,pe,he){he===void 0&&(he=pe);var Ve=Object.getOwnPropertyDescriptor(ce,pe);(!Ve||("get"in Ve?!ce.__esModule:Ve.writable||Ve.configurable))&&(Ve={enumerable:!0,get:function(){return ce[pe]}}),Object.defineProperty(de,he,Ve)}):(function(de,ce,pe,he){he===void 0&&(he=pe),de[he]=ce[pe]})),s=Gr&&Gr.__setModuleDefault||(Object.create?(function(de,ce){Object.defineProperty(de,"default",{enumerable:!0,value:ce})}):function(de,ce){de.default=ce}),a=Gr&&Gr.__importStar||function(de){if(de&&de.__esModule)return de;var ce={};if(de!=null)for(var pe in de)pe!=="default"&&Object.prototype.hasOwnProperty.call(de,pe)&&r(ce,de,pe);return s(ce,de),ce};Object.defineProperty(d,"__esModule",{value:!0}),d.MicVAD=d.getDefaultRealTimeVADOptions=d.ort=d.DEFAULT_MODEL=void 0;const f=a(Ty()),_=Io(),C=Mo(),R=ci(),b=qi(),U=hf(),z=pf();d.DEFAULT_MODEL="legacy",d.ort=f;const re="vad.worklet.bundle.min.js",K="silero_vad_v5.onnx",se="silero_vad_legacy.onnx",J=de=>({...C.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{R.log.debug("VAD misfire")},onSpeechStart:()=>{R.log.debug("Detected speech start")},onSpeechEnd:()=>{R.log.debug("Detected speech end")},onSpeechRealStart:()=>{R.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:de,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async ce=>{ce.getTracks().forEach(pe=>{pe.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:ce=>{ce.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});d.getDefaultRealTimeVADOptions=J;const Y=de=>"audioWorklet"in de&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function H(de,ce,pe,he,Ve){await pe.audioWorklet.addModule(de),ce.processorOptions={...ce.processorOptions??{},frameSamples:he};const fe=new AudioWorkletNode(pe,"vad-helper-worklet",ce);return fe.port.onmessage=async Je=>{const qe=Je.data;if(!(typeof qe=="object"&&qe&&"message"in qe)){console.error("Invalid message event",qe);return}switch(qe.message){case b.Message.AudioFrame:{if(!("data"in qe&&qe.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const ot=new Float32Array(qe.data);await Ve(ot);break}}},fe}async function ne(de,ce,pe){const he=new z.Resampler({nativeSampleRate:de.sampleRate,targetSampleRate:16e3,targetFrameSize:ce});R.log.debug("using script processor");const fe=de.createScriptProcessor(4096,1,1);let Je=!1;return fe.onaudioprocess=async qe=>{if(!Je){Je=!0;try{const ot=qe.inputBuffer.getChannelData(0);qe.outputBuffer.getChannelData(0).fill(0);const it=he.process(ot);for(const tt of it)await pe(tt)}catch(ot){console.error("Error processing audio:",ot)}finally{Je=!1}}},fe.connect(de.destination),fe}class ve{constructor(ce,pe,he,Ve,fe=!1,Je=null,qe=null,ot=null,Ze=null,it=null,tt=null,Wt="uninitialized",xt=!1){this.options=ce,this.frameProcessor=pe,this.model=he,this.frameSamples=Ve,this.listening=fe,this.errored=Je,this._stream=qe,this._audioContext=ot,this._vadNode=Ze,this._mediaStreamAudioSourceNode=it,this._audioProcessorAdapterType=tt,this.initializationState=Wt,this.ownsAudioContext=xt,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":{R.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"?Y(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await H(this.options.baseAssetPath+re,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await ne(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),R.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{R.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:je,audioContext:We,vadNode:st}=this.getAudioInstances();this._stream=await this.options.resumeStream(je);const ze=new MediaStreamAudioSourceNode(We,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=ze,ze.connect(st);break}case"destroyed":{R.log.warn("start called after destroyed");break}case"errored":{R.log.error("start called after errored");break}default:{R.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:je,mediaStreamAudioSourceNode:We}=this.getAudioInstances();await this.options.pauseStream(je),We.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{R.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:je}=this.getAudioInstances();je instanceof AudioWorkletNode&&je.port.postMessage(b.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 b.Message.FrameProcessed:this.options.onFrameProcessed(je.probs,je.frame);break;case b.Message.SpeechStart:this.options.onSpeechStart();break;case b.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case b.Message.VADMisfire:this.options.onVADMisfire();break;case b.Message.SpeechEnd:this.options.onSpeechEnd(je.audio);break}}}static async new(ce={}){const pe={...(0,d.getDefaultRealTimeVADOptions)(ce.model??d.DEFAULT_MODEL),...ce};(0,C.validateOptions)(pe),d.ort.env.wasm.wasmPaths=pe.onnxWASMBasePath,pe.ortConfig!==void 0&&pe.ortConfig(d.ort);const he=pe.model==="v5"?K:se,Ve=pe.baseAssetPath+he,fe=pe.model==="v5"?U.SileroV5.new:U.SileroLegacy.new;let Je;try{Je=await fe(d.ort,()=>(0,_.defaultModelFetcher)(Ve))}catch(tt){throw console.error(`Encountered an error while loading model file ${Ve}`),tt}const qe=pe.model==="v5"?512:1536,ot=qe/16,Ze=new C.FrameProcessor(Je.process,Je.reset_state,{positiveSpeechThreshold:pe.positiveSpeechThreshold,negativeSpeechThreshold:pe.negativeSpeechThreshold,redemptionMs:pe.redemptionMs,preSpeechPadMs:pe.preSpeechPadMs,minSpeechMs:pe.minSpeechMs,submitUserSpeechOnPause:pe.submitUserSpeechOnPause},ot),it=new ve(pe,Ze,Je,qe);if(pe.startOnLoad)try{await it.start()}catch(tt){throw console.error("Error starting micVad",tt),tt}return it}}d.MicVAD=ve})(Gr)),Gr}var Pp;function Op(){return Pp||(Pp=1,(function(d){Object.defineProperty(d,"__esModule",{value:!0}),d.getDefaultRealTimeVADOptions=d.MicVAD=d.DEFAULT_MODEL=d.utils=d.NonRealTimeVAD=d.Message=d.FrameProcessor=d.defaultModelFetcher=d.baseAssetPath=void 0;var r=uf();Object.defineProperty(d,"baseAssetPath",{enumerable:!0,get:function(){return r.baseAssetPath}});var s=Io();Object.defineProperty(d,"defaultModelFetcher",{enumerable:!0,get:function(){return s.defaultModelFetcher}});var a=Mo();Object.defineProperty(d,"FrameProcessor",{enumerable:!0,get:function(){return a.FrameProcessor}});var f=qi();Object.defineProperty(d,"Message",{enumerable:!0,get:function(){return f.Message}});var _=by();Object.defineProperty(d,"NonRealTimeVAD",{enumerable:!0,get:function(){return _.NonRealTimeVAD}});const C=Sy();d.utils={audioFileToArray:C.audioFileToArray,minFramesForTargetMS:C.minFramesForTargetMS,arrayBufferToBase64:C.arrayBufferToBase64,encodeWAV:C.encodeWAV};var R=Ey();Object.defineProperty(d,"DEFAULT_MODEL",{enumerable:!0,get:function(){return R.DEFAULT_MODEL}}),Object.defineProperty(d,"MicVAD",{enumerable:!0,get:function(){return R.MicVAD}}),Object.defineProperty(d,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return R.getDefaultRealTimeVADOptions}})})(ro)),ro}var Dp;function $y(){return Dp||(Dp=1,(function(d){Object.defineProperty(d,"__esModule",{value:!0}),d.useMicVAD=d.getDefaultReactRealTimeVADOptions=d.utils=void 0;const r=Op(),s=oe;var a=Op();Object.defineProperty(d,"utils",{enumerable:!0,get:function(){return a.utils}});const f={userSpeakingThreshold:.6},_=b=>({...(0,r.getDefaultRealTimeVADOptions)(b),...f});d.getDefaultReactRealTimeVADOptions=_;function C(b){const U=b.model??r.DEFAULT_MODEL,z={...(0,d.getDefaultReactRealTimeVADOptions)(U),...b},re={userSpeakingThreshold:z.userSpeakingThreshold},K={positiveSpeechThreshold:z.positiveSpeechThreshold,negativeSpeechThreshold:z.negativeSpeechThreshold,redemptionMs:z.redemptionMs,preSpeechPadMs:z.preSpeechPadMs,minSpeechMs:z.minSpeechMs,submitUserSpeechOnPause:z.submitUserSpeechOnPause,onFrameProcessed:z.onFrameProcessed,onVADMisfire:z.onVADMisfire,onSpeechStart:z.onSpeechStart,onSpeechEnd:z.onSpeechEnd,onSpeechRealStart:z.onSpeechRealStart,baseAssetPath:z.baseAssetPath,onnxWASMBasePath:z.onnxWASMBasePath,model:z.model,workletOptions:z.workletOptions,getStream:z.getStream,pauseStream:z.pauseStream,resumeStream:z.resumeStream,startOnLoad:z.startOnLoad,processorType:z.processorType};return z.ortConfig&&(K.ortConfig=z.ortConfig),z.audioContext&&(K.audioContext=z.audioContext),[re,K]}function R(b){const[U,z]=C(b),re=b.model??r.DEFAULT_MODEL,[K,se]=(0,s.useState)(!1),[J,Y]=(0,s.useState)(!0),[H,ne]=(0,s.useState)(!1),[ve,de]=(0,s.useState)(!1),[ce,pe]=(0,s.useState)(null),he=(0,s.useRef)(z.onFrameProcessed),Ve=(0,s.useRef)(z.onSpeechEnd),fe=(0,s.useRef)(z.onSpeechStart),Je=(0,s.useRef)(z.onSpeechRealStart),qe=(0,s.useRef)(z.onVADMisfire),ot=(0,s.useRef)(z.getStream);(0,s.useEffect)(()=>{he.current=z.onFrameProcessed,Ve.current=z.onSpeechEnd,fe.current=z.onSpeechStart,Je.current=z.onSpeechRealStart,qe.current=z.onVADMisfire},[z.onFrameProcessed,z.onSpeechEnd,z.onSpeechStart,z.onSpeechRealStart,z.onVADMisfire]),(0,s.useEffect)(()=>{ot.current=z.getStream},[z.getStream]);const Ze=z.getStream.toString();(0,s.useEffect)(()=>{let xt=null,je=!1;return(async()=>{try{Y(!0),ne(!1);const st={...z,onFrameProcessed:(ze,At)=>{const sr=ze.isSpeech>U.userSpeakingThreshold;se(sr),he.current(ze,At)},onSpeechEnd:ze=>{Ve.current(ze)},onSpeechStart:()=>{fe.current()},onSpeechRealStart:()=>{Je.current()},onVADMisfire:()=>{qe.current()},getStream:()=>ot.current()};if(xt=await r.MicVAD.new(st),je){await xt.destroy();return}pe(xt),z.startOnLoad&&(await xt.start(),de(!0)),Y(!1)}catch(st){Y(!1),st instanceof Error?ne(st.message):ne(String(st))}})().catch(()=>{}),function(){je=!0,xt&&xt.destroy(),!J&&!H&&de(!1)}},[Ze,re]);const it=(0,s.useCallback)(async()=>{!J&&!H&&(await ce?.pause(),de(!1))},[J,H,ce]),tt=(0,s.useCallback)(async()=>{!J&&!H&&(await ce?.start(),de(!0))},[J,H,ce]),Wt=(0,s.useCallback)(async()=>{ve?await it():await tt()},[ve,it,tt]);return{listening:ve,errored:H,loading:J,userSpeaking:K,pause:it,start:tt,toggle:Wt}}d.useMicVAD=R})(to)),to}var xy=$y();const zp={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},Cy=16e3,mf=512,gf=1e3,ky=300,Ry=mf/Cy*1e3,Ay=Math.ceil(gf/Ry);function ao(d){const r=new ArrayBuffer(d.length*2),s=new DataView(r);for(let a=0;a<d.length;a++){const f=Math.max(-1,Math.min(1,d[a]));s.setInt16(a*2,f<0?f*32768:f*32767,!0)}return new Uint8Array(r)}function oo(d){if(!d.length)return new Float32Array(0);if(d.length===1)return d[0];const r=d.reduce((f,_)=>f+_.length,0),s=new Float32Array(r);let a=0;for(const f of d)s.set(f,a),a+=f.length;return s}function Iy(d={}){const{onAudioChunk:r,onAudioEnd:s,onSpeechStart:a,onSpeechEnd:f,onVADMisfire:_,onError:C,enabled:R=!0,preloadStream:b=!0}=d,{sendAudioChunk:U,endAudioStream:z}=dn(),[re,K]=oe.useState(!1),[se,J]=oe.useState(null),Y=oe.useRef(null),H=oe.useRef(!1),ne=oe.useRef(null),ve=oe.useRef([]),de=oe.useRef(!1),ce=oe.useRef([]),pe=r??U;oe.useEffect(()=>{!R||!b||typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||navigator.mediaDevices.getUserMedia({audio:zp}).then(We=>{Y.current=We,J(null)}).catch(We=>{J("permission_denied"),C?.(We)})},[R,C,b]);const he=oe.useCallback(async()=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone APIs are unavailable in this browser");if(Y.current&&Y.current.getTracks()[0]?.readyState==="live")return Y.current;const We=await navigator.mediaDevices.getUserMedia({audio:zp});return Y.current=We,J(null),We},[]),Ve=oe.useCallback(async We=>{We.getTracks().forEach(st=>{st.enabled=!1})},[]),fe=oe.useCallback(async()=>Y.current&&Y.current.getTracks()[0]?.readyState==="live"?(Y.current.getTracks().forEach(We=>{We.enabled=!0}),Y.current):he(),[he]);oe.useCallback(()=>{const We=ve.current;return ve.current=[],oo(We)},[]);const Je=oe.useCallback(()=>{ce.current=[];const We=ve.current;ve.current=[];for(const st of We)pe(ao(st));de.current=!0},[pe]),qe=oe.useCallback(()=>{de.current=!1;const We=ce.current;if(ce.current=[],We.length>0){const st=oo(We);pe(ao(st))}},[pe]),ot=oe.useCallback(()=>{Y.current&&(Y.current.getTracks().forEach(We=>We.stop()),Y.current=null)},[]);if(!R)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 Ze=xy.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:gf,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:mf}},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:We=>{We.env.wasm.numThreads=1,We.env.logLevel="error"},getStream:he,pauseStream:Ve,resumeStream:fe,onFrameProcessed:(We,st)=>{if(st&&(ve.current.push(new Float32Array(st)),ve.current.length>Ay&&ve.current.shift(),de.current)){const ze=ce.current;if(ze.push(new Float32Array(st)),ze.length>=3){const At=oo(ze);ze.length=0,pe(ao(At))}}},onSpeechStart:()=>{H.current||(ne.current&&(clearTimeout(ne.current),ne.current=null),K(!0),a?.(),Je())},onSpeechEnd:()=>{ne.current=setTimeout(()=>{K(!1),qe(),s?s():z(),H.current=!0,setTimeout(()=>{H.current=!1},300),f?.()},ky)},onVADMisfire:()=>{ne.current&&(clearTimeout(ne.current),ne.current=null),K(!1),qe(),_?.()}}),it=oe.useCallback(async()=>!R||Ze.loading||Ze.errored?!1:(Ze.listening&&(ne.current&&(clearTimeout(ne.current),ne.current=null),K(!1),qe(),await Ze.pause()),!0),[R,qe,Ze]),tt=oe.useCallback(async()=>{try{await Ze.start()}catch(We){const st=We instanceof Error?We.message:String(We);if(st.includes("null stream")||st.includes("audio context")||st.includes("processor adapter"))await new Promise(ze=>setTimeout(ze,100)),await Ze.start();else throw We}},[Ze]),Wt=oe.useCallback(async()=>!R||Ze.loading||Ze.errored?!1:(Ze.listening?(ne.current&&(clearTimeout(ne.current),ne.current=null),K(!1),qe(),await Ze.pause()):await tt(),!0),[R,qe,tt]),xt=oe.useCallback(async()=>R?he():null,[R,he]),je=oe.useCallback(async()=>!R||Ze.loading||Ze.errored?!1:(Ze.listening||await tt(),!0),[R,tt]);return oe.useEffect(()=>()=>{ne.current&&clearTimeout(ne.current),qe(),ot()},[ot,qe]),{isListening:Ze.listening,isLoading:Ze.loading,isErrored:!!Ze.errored,isSpeaking:re,micError:se,toggle:Wt,prepare:xt,start:je,stop:it,pause:Ze.pause,userSpeaking:Ze.userSpeaking}}function My({connect:d=!0,session:r,onError:s,onInitialized:a,clientTools:f,children:_}){const{initializeSession:C,joinDesktopSession:R,disconnect:b,registerClientTools:U}=of(),z=oe.useRef(!1),re=oe.useRef(!1),K=oe.useRef(C),se=oe.useRef(R),J=oe.useRef(b),Y=oe.useRef(s),H=oe.useRef(a),ne=oe.useRef(U),ve=oe.useRef(f);return oe.useEffect(()=>{K.current=C}),oe.useEffect(()=>{se.current=R}),oe.useEffect(()=>{J.current=b}),oe.useEffect(()=>{Y.current=s}),oe.useEffect(()=>{H.current=a}),oe.useEffect(()=>{ne.current=U}),oe.useEffect(()=>{ve.current=f}),oe.useEffect(()=>{if(!d||z.current)return;z.current=!0,re.current=!1;let de=!1;return(async()=>{try{const pe=ve.current;if(r?.mode==="join_desktop"){const Ve=await se.current({uniqueId:r.uniqueId});de||(pe&&ne.current(pe),H.current?.(Ve));return}const he=await K.current({apiKey:r?.apiKey,publicChatId:r?.publicChatId,agentId:r?.agentId,language:r?.language||"en",config:r?.config});de||(pe&&ne.current(pe),H.current?.(he))}catch(pe){de||(re.current=!0,Y.current?.(pe))}})(),()=>{de=!0,!re.current&&(J.current(),z.current=!1)}},[d,r]),Jt.jsx(Jt.Fragment,{children:_})}function Py({children:d,wsUrl:r,restUrl:s,session:a,connect:f=!0,enableAudio:_=!0,pcmOptions:C,debug:R=!1,withCredentials:b=!1,onError:U,onInitialized:z,clientTools:re}){return Jt.jsx(af,{wsUrl:r,restUrl:s,enableAudio:_,pcmOptions:C,debug:R,withCredentials:b,children:Jt.jsx(My,{connect:f,session:a,onError:U,onInitialized:z,clientTools:re,children:d})})}var lo={exports:{}},Lp;function Oy(){return Lp||(Lp=1,(function(d){const r={};r.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},r.localCName=r.generateIdentifier(),r.splitLines=function(s){return s.trim().split(`
|
|
2838
|
+
*/var Ip;function Ty(){return Ip||(Ip=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,_=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(y=>typeof dr<"u"?dr:typeof Proxy<"u"?new Proxy(y,{get:(E,A)=>(typeof dr<"u"?dr:E)[A]}):y)(function(y){if(typeof dr<"u")return dr.apply(this,arguments);throw Error('Dynamic require of "'+y+'" is not supported')}),S=(y,E)=>()=>(y&&(E=y(y=0)),E),N=(y,E)=>{for(var A in E)a(y,A,{get:E[A],enumerable:!0})},z=(y,E,A,D)=>{if(E&&typeof E=="object"||typeof E=="function")for(let O of _(E))!C.call(y,O)&&O!==A&&a(y,O,{get:()=>E[O],enumerable:!(D=f(E,O))||D.enumerable});return y},te=y=>z(a({},"__esModule",{value:!0}),y),j,se,J,Y,W,ne=S(()=>{j=new Map,se=[],J=(y,E,A)=>{if(E&&typeof E.init=="function"&&typeof E.createInferenceSessionHandler=="function"){let D=j.get(y);if(D===void 0)j.set(y,{backend:E,priority:A});else{if(D.priority>A)return;if(D.priority===A&&D.backend!==E)throw new Error(`cannot register backend "${y}" using priority ${A}`)}if(A>=0){let O=se.indexOf(y);O!==-1&&se.splice(O,1);for(let G=0;G<se.length;G++)if(j.get(se[G]).priority<=A){se.splice(G,0,y);return}se.push(y)}return}throw new TypeError("not a valid backend")},Y=async y=>{let E=j.get(y);if(!E)return"backend not found.";if(E.initialized)return E.backend;if(E.aborted)return E.error;{let A=!!E.initPromise;try{return A||(E.initPromise=E.backend.init(y)),await E.initPromise,E.initialized=!0,E.backend}catch(D){return A||(E.error=`${D}`,E.aborted=!0),E.error}finally{delete E.initPromise}}},W=async y=>{let E=y.executionProviders||[],A=E.map(V=>typeof V=="string"?V:V.name),D=A.length===0?se:A,O,G=[],U=new Set;for(let V of D){let re=await Y(V);typeof re=="string"?G.push({name:V,err:re}):(O||(O=re),O===re&&U.add(V))}if(!O)throw new Error(`no available backend found. ERR: ${G.map(V=>`[${V.name}] ${V.err}`).join(", ")}`);for(let{name:V,err:re}of G)A.includes(V)&&console.warn(`removing requested execution provider "${V}" from session options because it is not available: ${re}`);let L=E.filter(V=>U.has(typeof V=="string"?V:V.name));return[O,new Proxy(y,{get:(V,re)=>re==="executionProviders"?L:Reflect.get(V,re)})]}}),fe=S(()=>{ne()}),de,ce=S(()=>{de="1.26.0"}),pe,he,Ve=S(()=>{ce(),pe="warning",he={wasm:{},webgl:{},webgpu:{},versions:{common:de},set logLevel(y){if(y!==void 0){if(typeof y!="string"||["verbose","info","warning","error","fatal"].indexOf(y)===-1)throw new Error(`Unsupported logging level: ${y}`);pe=y}},get logLevel(){return pe}},Object.defineProperty(he,"logLevel",{enumerable:!0})}),me,Ye=S(()=>{Ve(),me=he}),qe,it,Je=S(()=>{qe=(y,E)=>{let A=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);A.width=y.dims[3],A.height=y.dims[2];let D=A.getContext("2d");if(D!=null){let O,G;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(O=y.dims[2],G=y.dims[3]):(O=y.dims[3],G=y.dims[2]);let U=E?.format!==void 0?E.format:"RGB",L=E?.norm,V,re;L===void 0||L.mean===void 0?V=[255,255,255,255]:typeof L.mean=="number"?V=[L.mean,L.mean,L.mean,L.mean]:(V=[L.mean[0],L.mean[1],L.mean[2],0],L.mean[3]!==void 0&&(V[3]=L.mean[3])),L===void 0||L.bias===void 0?re=[0,0,0,0]:typeof L.bias=="number"?re=[L.bias,L.bias,L.bias,L.bias]:(re=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(re[3]=L.bias[3]));let ie=G*O,Z=0,Q=ie,Te=ie*2,F=-1;U==="RGBA"?(Z=0,Q=ie,Te=ie*2,F=ie*3):U==="RGB"?(Z=0,Q=ie,Te=ie*2):U==="RBG"&&(Z=0,Te=ie,Q=ie*2);for(let le=0;le<G;le++)for(let ut=0;ut<O;ut++){let Be=(y.data[Z++]-re[0])*V[0],Ee=(y.data[Q++]-re[1])*V[1],Ne=(y.data[Te++]-re[2])*V[2],we=F===-1?255:(y.data[F++]-re[3])*V[3];D.fillStyle="rgba("+Be+","+Ee+","+Ne+","+we+")",D.fillRect(ut,le,1,1)}if("toDataURL"in A)return A.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},it=(y,E)=>{let A=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),D;if(A!=null){let O,G,U;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(O=y.dims[2],G=y.dims[1],U=y.dims[3]):(O=y.dims[3],G=y.dims[2],U=y.dims[1]);let L=E!==void 0&&E.format!==void 0?E.format:"RGB",V=E?.norm,re,ie;V===void 0||V.mean===void 0?re=[255,255,255,255]:typeof V.mean=="number"?re=[V.mean,V.mean,V.mean,V.mean]:(re=[V.mean[0],V.mean[1],V.mean[2],255],V.mean[3]!==void 0&&(re[3]=V.mean[3])),V===void 0||V.bias===void 0?ie=[0,0,0,0]:typeof V.bias=="number"?ie=[V.bias,V.bias,V.bias,V.bias]:(ie=[V.bias[0],V.bias[1],V.bias[2],0],V.bias[3]!==void 0&&(ie[3]=V.bias[3]));let Z=G*O;if(E!==void 0&&(E.format!==void 0&&U===4&&E.format!=="RGBA"||U===3&&E.format!=="RGB"&&E.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Q=4,Te=0,F=1,le=2,ut=3,Be=0,Ee=Z,Ne=Z*2,we=-1;L==="RGBA"?(Be=0,Ee=Z,Ne=Z*2,we=Z*3):L==="RGB"?(Be=0,Ee=Z,Ne=Z*2):L==="RBG"&&(Be=0,Ne=Z,Ee=Z*2),D=A.createImageData(O,G);for(let kt=0;kt<G*O;Te+=Q,F+=Q,le+=Q,ut+=Q,kt++)D.data[Te]=(y.data[Be++]-ie[0])*re[0],D.data[F]=(y.data[Ee++]-ie[1])*re[1],D.data[le]=(y.data[Ne++]-ie[2])*re[2],D.data[ut]=we===-1?255:(y.data[we++]-ie[3])*re[3]}else throw new Error("Can not access image data");return D}}),at,tt,qt,xt,Ke,We,st=S(()=>{Er(),at=(y,E)=>{if(y===void 0)throw new Error("Image buffer must be defined");if(E.height===void 0||E.width===void 0)throw new Error("Image height and width must be defined");if(E.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:A,width:D}=E,O=E.norm??{mean:255,bias:0},G,U;typeof O.mean=="number"?G=[O.mean,O.mean,O.mean,O.mean]:G=[O.mean[0],O.mean[1],O.mean[2],O.mean[3]??255],typeof O.bias=="number"?U=[O.bias,O.bias,O.bias,O.bias]:U=[O.bias[0],O.bias[1],O.bias[2],O.bias[3]??0];let L=E.format!==void 0?E.format:"RGBA",V=E.tensorFormat!==void 0&&E.tensorFormat!==void 0?E.tensorFormat:"RGB",re=A*D,ie=V==="RGBA"?new Float32Array(re*4):new Float32Array(re*3),Z=4,Q=0,Te=1,F=2,le=3,ut=0,Be=re,Ee=re*2,Ne=-1;L==="RGB"&&(Z=3,Q=0,Te=1,F=2,le=-1),V==="RGBA"?Ne=re*3:V==="RBG"?(ut=0,Ee=re,Be=re*2):V==="BGR"&&(Ee=0,Be=re,ut=re*2);for(let we=0;we<re;we++,Q+=Z,F+=Z,Te+=Z,le+=Z)ie[ut++]=(y[Q]+U[0])/G[0],ie[Be++]=(y[Te]+U[1])/G[1],ie[Ee++]=(y[F]+U[2])/G[2],Ne!==-1&&le!==-1&&(ie[Ne++]=(y[le]+U[3])/G[3]);return V==="RGBA"?new rt("float32",ie,[1,4,A,D]):new rt("float32",ie,[1,3,A,D])},tt=async(y,E)=>{let A=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,D=typeof ImageData<"u"&&y instanceof ImageData,O=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,G=typeof y=="string",U,L=E??{},V=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},re=ie=>typeof HTMLCanvasElement<"u"&&ie instanceof HTMLCanvasElement||ie instanceof OffscreenCanvas?ie.getContext("2d"):null;if(A){let ie=V();ie.width=y.width,ie.height=y.height;let Z=re(ie);if(Z!=null){let Q=y.height,Te=y.width;if(E!==void 0&&E.resizedHeight!==void 0&&E.resizedWidth!==void 0&&(Q=E.resizedHeight,Te=E.resizedWidth),E!==void 0){if(L=E,E.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");L.tensorFormat="RGBA",L.height=Q,L.width=Te}else L.tensorFormat="RGBA",L.height=Q,L.width=Te;Z.drawImage(y,0,0),U=Z.getImageData(0,0,Te,Q).data}else throw new Error("Can not access image data")}else if(D){let ie,Z;if(E!==void 0&&E.resizedWidth!==void 0&&E.resizedHeight!==void 0?(ie=E.resizedHeight,Z=E.resizedWidth):(ie=y.height,Z=y.width),E!==void 0&&(L=E),L.format="RGBA",L.height=ie,L.width=Z,E!==void 0){let Q=V();Q.width=Z,Q.height=ie;let Te=re(Q);if(Te!=null)Te.putImageData(y,0,0),U=Te.getImageData(0,0,Z,ie).data;else throw new Error("Can not access image data")}else U=y.data}else if(O){if(E===void 0)throw new Error("Please provide image config with format for Imagebitmap");let ie=V();ie.width=y.width,ie.height=y.height;let Z=re(ie);if(Z!=null){let Q=y.height,Te=y.width;return Z.drawImage(y,0,0,Te,Q),U=Z.getImageData(0,0,Te,Q).data,L.height=Q,L.width=Te,at(U,L)}else throw new Error("Can not access image data")}else{if(G)return new Promise((ie,Z)=>{let Q=V(),Te=re(Q);if(!y||!Te)return Z();let F=new Image;F.crossOrigin="Anonymous",F.src=y,F.onload=()=>{Q.width=F.width,Q.height=F.height,Te.drawImage(F,0,0,Q.width,Q.height);let le=Te.getImageData(0,0,Q.width,Q.height);L.height=Q.height,L.width=Q.width,ie(at(le.data,L))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(U!==void 0)return at(U,L);throw new Error("Input data provided is not supported - aborted tensor creation")},qt=(y,E)=>{let{width:A,height:D,download:O,dispose:G}=E,U=[1,D,A,4];return new rt({location:"texture",type:"float32",texture:y,dims:U,download:O,dispose:G})},xt=(y,E)=>{let{dataType:A,dims:D,download:O,dispose:G}=E;return new rt({location:"gpu-buffer",type:A??"float32",gpuBuffer:y,dims:D,download:O,dispose:G})},Ke=(y,E)=>{let{dataType:A,dims:D,download:O,dispose:G}=E;return new rt({location:"ml-tensor",type:A??"float32",mlTensor:y,dims:D,download:O,dispose:G})},We=(y,E,A)=>new rt({location:"cpu-pinned",type:y,data:E,dims:A??[E.length]})}),ze,Rt,sr,Xr,Vs=S(()=>{ze=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"]]),sr=!1,Xr=()=>{if(!sr){sr=!0;let y=typeof BigInt64Array<"u"&&BigInt64Array.from,E=typeof BigUint64Array<"u"&&BigUint64Array.from,A=globalThis.Float16Array,D=typeof A<"u"&&A.from;y&&(ze.set("int64",BigInt64Array),Rt.set(BigInt64Array,"int64")),E&&(ze.set("uint64",BigUint64Array),Rt.set(BigUint64Array,"uint64")),D?(ze.set("float16",A),Rt.set(A,"float16")):ze.set("float16",Uint16Array)}}}),Yr,Jr,Gs=S(()=>{Er(),Yr=y=>{let E=1;for(let A=0;A<y.length;A++){let D=y[A];if(typeof D!="number"||!Number.isSafeInteger(D))throw new TypeError(`dims[${A}] must be an integer, got: ${D}`);if(D<0)throw new RangeError(`dims[${A}] must be a non-negative integer, got: ${D}`);E*=D}return E},Jr=(y,E)=>{switch(y.location){case"cpu":return new rt(y.type,y.data,E);case"cpu-pinned":return new rt({location:"cpu-pinned",data:y.data,type:y.type,dims:E});case"texture":return new rt({location:"texture",texture:y.texture,type:y.type,dims:E});case"gpu-buffer":return new rt({location:"gpu-buffer",gpuBuffer:y.gpuBuffer,type:y.type,dims:E});case"ml-tensor":return new rt({location:"ml-tensor",mlTensor:y.mlTensor,type:y.type,dims:E});default:throw new Error(`tensorReshape: tensor location ${y.location} is not supported`)}}}),rt,Er=S(()=>{Je(),st(),Vs(),Gs(),rt=class{constructor(y,E,A){Xr();let D,O;if(typeof y=="object"&&"location"in y)switch(this.dataLocation=y.location,D=y.type,O=y.dims,y.location){case"cpu-pinned":{let U=ze.get(D);if(!U)throw new TypeError(`unsupported type "${D}" to create tensor from pinned buffer`);if(!(y.data instanceof U))throw new TypeError(`buffer should be of type ${U.name}`);this.cpuData=y.data;break}case"texture":{if(D!=="float32")throw new TypeError(`unsupported type "${D}" to create tensor from texture`);this.gpuTextureData=y.texture,this.downloader=y.download,this.disposer=y.dispose;break}case"gpu-buffer":{if(D!=="float32"&&D!=="float16"&&D!=="int32"&&D!=="int64"&&D!=="uint32"&&D!=="uint8"&&D!=="bool"&&D!=="uint4"&&D!=="int4")throw new TypeError(`unsupported type "${D}" to create tensor from gpu buffer`);this.gpuBufferData=y.gpuBuffer,this.downloader=y.download,this.disposer=y.dispose;break}case"ml-tensor":{if(D!=="float32"&&D!=="float16"&&D!=="int32"&&D!=="int64"&&D!=="uint32"&&D!=="uint64"&&D!=="int8"&&D!=="uint8"&&D!=="bool"&&D!=="uint4"&&D!=="int4")throw new TypeError(`unsupported type "${D}" to create tensor from MLTensor`);this.mlTensorData=y.mlTensor,this.downloader=y.download,this.disposer=y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let U,L;if(typeof y=="string")if(D=y,L=A,y==="string"){if(!Array.isArray(E))throw new TypeError("A string tensor's data must be a string array.");U=E}else{let V=ze.get(y);if(V===void 0)throw new TypeError(`Unsupported tensor type: ${y}.`);if(Array.isArray(E)){if(y==="float16"&&V===Uint16Array||y==="uint4"||y==="int4")throw new TypeError(`Creating a ${y} tensor from number array is not supported. Please use ${V.name} as data.`);y==="uint64"||y==="int64"?U=V.from(E,BigInt):U=V.from(E)}else if(E instanceof V)U=E;else if(E instanceof Uint8ClampedArray)if(y==="uint8")U=Uint8Array.from(E);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(y==="float16"&&E instanceof Uint16Array&&V!==Uint16Array)U=new globalThis.Float16Array(E.buffer,E.byteOffset,E.length);else throw new TypeError(`A ${D} tensor's data must be type of ${V}`)}else if(L=E,Array.isArray(y)){if(y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let V=typeof y[0];if(V==="string")D="string",U=y;else if(V==="boolean")D="bool",U=Uint8Array.from(y);else throw new TypeError(`Invalid element type of data array: ${V}.`)}else if(y instanceof Uint8ClampedArray)D="uint8",U=Uint8Array.from(y);else{let V=Rt.get(y.constructor);if(V===void 0)throw new TypeError(`Unsupported type for tensor data: ${y.constructor}.`);D=V,U=y}if(L===void 0)L=[U.length];else if(!Array.isArray(L))throw new TypeError("A tensor's dims must be a number array");O=L,this.cpuData=U,this.dataLocation="cpu"}let G=Yr(O);if(this.cpuData&&G!==this.cpuData.length&&!((D==="uint4"||D==="int4")&&Math.ceil(G/2)===this.cpuData.length))throw new Error(`Tensor's size(${G}) does not match data length(${this.cpuData.length}).`);this.type=D,this.dims=O,this.size=G}static async fromImage(y,E){return tt(y,E)}static fromTexture(y,E){return qt(y,E)}static fromGpuBuffer(y,E){return xt(y,E)}static fromMLTensor(y,E){return Ke(y,E)}static fromPinnedBuffer(y,E,A){return We(y,E,A)}toDataURL(y){return qe(this,y)}toImageData(y){return it(this,y)}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(y){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 E=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=E,y&&this.disposer&&(this.disposer(),this.disposer=void 0),E}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(y){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Jr(this,y)}}}),lt,Zr=S(()=>{Er(),lt=rt}),er,$r,gt,ft,At,Ct,es=S(()=>{Ve(),er=(y,E)=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeStamp(`${y}::ORT::${E}`)},$r=(y,E)=>{let A=new Error().stack?.split(/\r\n|\r|\n/g)||[],D=!1;for(let O=0;O<A.length;O++){if(D&&!A[O].includes("TRACE_FUNC")){let G=`FUNC_${y}::${A[O].trim().split(" ")[1]}`;E&&(G+=`::${E}`),er("CPU",G);return}A[O].includes("TRACE_FUNC")&&(D=!0)}},gt=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||$r("BEGIN",y)},ft=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||$r("END",y)},At=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.time(`ORT::${y}`)},Ct=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeEnd(`ORT::${y}`)}}),ts,qs=S(()=>{ne(),Zr(),es(),ts=class ff{constructor(E){this.handler=E}async run(E,A,D){gt(),At("InferenceSession.run");let O={},G={};if(typeof E!="object"||E===null||E instanceof lt||Array.isArray(E))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let U=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof lt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");U=!1;for(let re of A){if(typeof re!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(re)===-1)throw new RangeError(`'fetches' contains invalid output name: ${re}.`);O[re]=null}if(typeof D=="object"&&D!==null)G=D;else if(typeof D<"u")throw new TypeError("'options' must be an object.")}else{let re=!1,ie=Object.getOwnPropertyNames(A);for(let Z of this.outputNames)if(ie.indexOf(Z)!==-1){let Q=A[Z];(Q===null||Q instanceof lt)&&(re=!0,U=!1,O[Z]=Q)}if(re){if(typeof D=="object"&&D!==null)G=D;else if(typeof D<"u")throw new TypeError("'options' must be an object.")}else G=A}}else if(typeof A<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let re of this.inputNames)if(typeof E[re]>"u")throw new Error(`input '${re}' is missing in 'feeds'.`);if(U)for(let re of this.outputNames)O[re]=null;let L=await this.handler.run(E,O,G),V={};for(let re in L)if(Object.hasOwnProperty.call(L,re)){let ie=L[re];ie instanceof lt?V[re]=ie:V[re]=new lt(ie.type,ie.data,ie.dims)}return Ct("InferenceSession.run"),ft(),V}async release(){return this.handler.dispose()}static async create(E,A,D,O){gt(),At("InferenceSession.create");let G,U={};if(typeof E=="string"){if(G=E,typeof A=="object"&&A!==null)U=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(E instanceof Uint8Array){if(G=E,typeof A=="object"&&A!==null)U=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(E instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&E instanceof SharedArrayBuffer){let ie=E,Z=0,Q=E.byteLength;if(typeof A=="object"&&A!==null)U=A;else if(typeof A=="number"){if(Z=A,!Number.isSafeInteger(Z))throw new RangeError("'byteOffset' must be an integer.");if(Z<0||Z>=ie.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${ie.byteLength}).`);if(Q=E.byteLength-Z,typeof D=="number"){if(Q=D,!Number.isSafeInteger(Q))throw new RangeError("'byteLength' must be an integer.");if(Q<=0||Z+Q>ie.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${ie.byteLength-Z}].`);if(typeof O=="object"&&O!==null)U=O;else if(typeof O<"u")throw new TypeError("'options' must be an object.")}else if(typeof D<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof A<"u")throw new TypeError("'options' must be an object.");G=new Uint8Array(ie,Z,Q)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[L,V]=await W(U),re=await L.createInferenceSessionHandler(G,V);return Ct("InferenceSession.create"),ft(),new ff(re)}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}}}),zr,be=S(()=>{qs(),zr=ts}),Ze=S(()=>{}),Bt=S(()=>{}),nr=S(()=>{}),It=S(()=>{}),xr={};N(xr,{InferenceSession:()=>zr,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>At,TRACE_EVENT_END:()=>Ct,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>ft,Tensor:()=>lt,env:()=>me,registerBackend:()=>J});var yt=S(()=>{fe(),Ye(),be(),Zr(),Ze(),Bt(),es(),nr(),It()}),Lr=S(()=>{}),Br={};N(Br,{default:()=>Wt});var Nt,ir,Wt,Wi=S(()=>{Mn(),Ht(),ms(),Nt="ort-wasm-proxy-worker",ir=globalThis.self?.name===Nt,ir&&(self.onmessage=y=>{let{type:E,in:A}=y.data;try{switch(E){case"init-wasm":ws(A.wasm).then(()=>{Hs(A).then(()=>{postMessage({type:E})},D=>{postMessage({type:E,err:D})})},D=>{postMessage({type:E,err:D})});break;case"init-ep":{let{epName:D,env:O}=A;js(O,D).then(()=>{postMessage({type:E})},G=>{postMessage({type:E,err:G})});break}case"copy-from":{let{buffer:D}=A,O=He(D);postMessage({type:E,out:O});break}case"create":{let{model:D,options:O}=A;tr(D,O).then(G=>{postMessage({type:E,out:G})},G=>{postMessage({type:E,err:G})});break}case"release":Xs(A),postMessage({type:E});break;case"run":{let{sessionId:D,inputIndices:O,inputs:G,outputIndices:U,options:L}=A;K(D,O,G,U,new Array(U.length).fill(null),L).then(V=>{V.some(re=>re[3]!=="cpu")?postMessage({type:E,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:E,out:V},Ys([...G,...V]))},V=>{postMessage({type:E,err:V})});break}case"end-profiling":rs(A),postMessage({type:E});break;default:}}catch(D){postMessage({type:E,err:D})}}),Wt=ir?null:y=>new Worker(y??ot,{type:"classic",name:Nt})}),fn,mn,ot,cs,Nr,gn,yn,hs,wn,ps,vn,fs,_n,ms=S(()=>{Lr(),fn=typeof location>"u"?void 0:location.origin,mn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,ot=mn(),cs=()=>{if(ot&&!ot.startsWith("blob:"))return ot.substring(0,ot.lastIndexOf("/")+1)},Nr=(y,E)=>{try{let A=E??ot;return(A?new URL(y,A):new URL(y)).origin===fn}catch{return!1}},gn=(y,E)=>{let A=E??ot;try{return(A?new URL(y,A):new URL(y)).href}catch{return}},yn=(y,E)=>`${E??"./"}${y}`,hs=async y=>{let E=await(await fetch(y,{credentials:"same-origin"})).blob();return URL.createObjectURL(E)},wn=async y=>(await import(y)).default,ps=(Wi(),te(Br)).default,vn=async()=>{if(!ot)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Nr(ot))return[void 0,ps()];let y=await hs(ot);return[y,ps(y)]},fs=void 0,_n=async(y,E,A,D)=>{let O=fs&&!(y||E);if(O)if(ot)O=Nr(ot)||D&&!A;else if(D&&!A)O=!0;else throw new Error("cannot determine the script source URL.");if(O)return[void 0,fs];{let G="ort-wasm-simd-threaded.mjs",U=y??gn(G,E),L=A&&U&&!Nr(U,E),V=L?await hs(U):U??yn(G,E);return[L?V:void 0,await wn(V)]}}}),gs,Ur,cr,ys,bn,Sn,Tn,ws,Pe,Ht=S(()=>{ms(),Ur=!1,cr=!1,ys=!1,bn=()=>{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}},Sn=()=>{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}},Tn=()=>{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}},ws=async y=>{if(Ur)return Promise.resolve();if(cr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ys)throw new Error("previous call to 'initializeWebAssembly()' failed.");cr=!0;let E=y.initTimeout,A=y.numThreads;if(y.simd!==!1){if(y.simd==="relaxed"){if(!Tn())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Sn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let D=bn();A>1&&!D&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+A+", 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."),y.numThreads=A=1);let O=y.wasmPaths,G=typeof O=="string"?O:void 0,U=O?.mjs,L=U?.href??U,V=O?.wasm,re=V?.href??V,ie=y.wasmBinary,[Z,Q]=await _n(L,G,A>1,!!ie||!!re),Te=!1,F=[];if(E>0&&F.push(new Promise(le=>{setTimeout(()=>{Te=!0,le()},E)})),F.push(new Promise((le,ut)=>{let Be={numThreads:A};if(ie)Be.wasmBinary=ie,Be.locateFile=Ee=>Ee;else if(re||G)Be.locateFile=Ee=>re??G+Ee;else if(L&&L.indexOf("blob:")!==0)Be.locateFile=Ee=>new URL(Ee,L).href;else if(Z){let Ee=cs();Ee&&(Be.locateFile=Ne=>Ee+Ne)}Q(Be).then(Ee=>{cr=!1,Ur=!0,gs=Ee,le(),Z&&URL.revokeObjectURL(Z)},Ee=>{cr=!1,ys=!0,ut(Ee)})})),await Promise.race(F),Te)throw new Error(`WebAssembly backend initializing failed due to timeout: ${E}ms`)},Pe=()=>{if(Ur&&gs)return gs;throw new Error("WebAssembly is not initialized yet.")}}),mt,Fr,Ce,vs=S(()=>{Ht(),mt=(y,E)=>{let A=Pe(),D=A.lengthBytesUTF8(y)+1,O=A._malloc(D);return A.stringToUTF8(y,O,D),E.push(O),O},Fr=(y,E,A,D)=>{if(typeof y=="object"&&y!==null){if(A.has(y))throw new Error("Circular reference in options");A.add(y)}Object.entries(y).forEach(([O,G])=>{let U=E?E+O:O;if(typeof G=="object")Fr(G,U+".",A,D);else if(typeof G=="string"||typeof G=="number")D(U,G.toString());else if(typeof G=="boolean")D(U,G?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof G}`)})},Ce=y=>{let E=Pe(),A=E.stackSave();try{let D=E.PTR_SIZE,O=E.stackAlloc(2*D);E._OrtGetLastError(O,O+D);let G=Number(E.getValue(O,D===4?"i32":"i64")),U=E.getValue(O+D,"*"),L=U?E.UTF8ToString(U):"";throw new Error(`${y} ERROR_CODE: ${G}, ERROR_MESSAGE: ${L}`)}finally{E.stackRestore(A)}}}),En,Hi=S(()=>{Ht(),vs(),En=y=>{let E=Pe(),A=0,D=[],O=y||{};try{if(y?.logSeverityLevel===void 0)O.logSeverityLevel=2;else if(typeof y.logSeverityLevel!="number"||!Number.isInteger(y.logSeverityLevel)||y.logSeverityLevel<0||y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${y.logSeverityLevel}`);if(y?.logVerbosityLevel===void 0)O.logVerbosityLevel=0;else if(typeof y.logVerbosityLevel!="number"||!Number.isInteger(y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${y.logVerbosityLevel}`);y?.terminate===void 0&&(O.terminate=!1);let G=0;return y?.tag!==void 0&&(G=mt(y.tag,D)),A=E._OrtCreateRunOptions(O.logSeverityLevel,O.logVerbosityLevel,!!O.terminate,G),A===0&&Ce("Can't create run options."),y?.extra!==void 0&&Fr(y.extra,"",new WeakSet,(U,L)=>{let V=mt(U,D),re=mt(L,D);E._OrtAddRunConfigEntry(A,V,re)!==0&&Ce(`Can't set a run config entry: ${U} - ${L}.`)}),[A,D]}catch(G){throw A!==0&&E._OrtReleaseRunOptions(A),D.forEach(U=>E._free(U)),G}}}),$n,xn,Cn,Ut,kn,Rn,ji=S(()=>{Ht(),vs(),$n=y=>{switch(y){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: ${y}`)}},xn=y=>{switch(y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${y}`)}},Cn=y=>{y.extra||(y.extra={}),y.extra.session||(y.extra.session={});let E=y.extra.session;E.use_ort_model_bytes_directly||(E.use_ort_model_bytes_directly="1"),y.executionProviders&&y.executionProviders.some(A=>(typeof A=="string"?A:A.name)==="webgpu")&&(y.enableMemPattern=!1)},Ut=(y,E,A,D)=>{let O=mt(E,D),G=mt(A,D);Pe()._OrtAddSessionConfigEntry(y,O,G)!==0&&Ce(`Can't set a session config entry: ${E} - ${A}.`)},kn=async(y,E,A)=>{let D=E.executionProviders;for(let O of D){let G=typeof O=="string"?O:O.name,U=[];switch(G){case"webnn":if(G="WEBNN",Ut(y,"session.disable_quant_qdq","1",A),Ut(y,"session.disable_qdq_constant_folding","1",A),typeof O!="string"){let Z=O?.deviceType;Z&&Ut(y,"deviceType",Z,A)}break;case"webgpu":if(G="JS",typeof O!="string"){let Z=O;if(Z?.preferredLayout){if(Z.preferredLayout!=="NCHW"&&Z.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${Z.preferredLayout}`);Ut(y,"preferredLayout",Z.preferredLayout,A)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${G}`)}let L=mt(G,A),V=U.length,re=0,ie=0;if(V>0){re=Pe()._malloc(V*Pe().PTR_SIZE),A.push(re),ie=Pe()._malloc(V*Pe().PTR_SIZE),A.push(ie);for(let Z=0;Z<V;Z++)Pe().setValue(re+Z*Pe().PTR_SIZE,U[Z][0],"*"),Pe().setValue(ie+Z*Pe().PTR_SIZE,U[Z][1],"*")}await Pe()._OrtAppendExecutionProvider(y,L,re,ie,V)!==0&&Ce(`Can't append execution provider: ${G}.`)}},Rn=async y=>{let E=Pe(),A=0,D=[],O=y||{};Cn(O);try{let G=$n(O.graphOptimizationLevel??"all"),U=xn(O.executionMode??"sequential"),L=typeof O.logId=="string"?mt(O.logId,D):0,V=O.logSeverityLevel??2;if(!Number.isInteger(V)||V<0||V>4)throw new Error(`log severity level is not valid: ${V}`);let re=O.logVerbosityLevel??0;if(!Number.isInteger(re)||re<0||re>4)throw new Error(`log verbosity level is not valid: ${re}`);let ie=typeof O.optimizedModelFilePath=="string"?mt(O.optimizedModelFilePath,D):0;if(A=E._OrtCreateSessionOptions(G,!!O.enableCpuMemArena,!!O.enableMemPattern,U,!!O.enableProfiling,0,L,V,re,ie),A===0&&Ce("Can't create session options."),O.executionProviders&&await kn(A,O,D),O.enableGraphCapture!==void 0){if(typeof O.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${O.enableGraphCapture}`);Ut(A,"enableGraphCapture",O.enableGraphCapture.toString(),D)}if(O.freeDimensionOverrides)for(let[Z,Q]of Object.entries(O.freeDimensionOverrides)){if(typeof Z!="string")throw new Error(`free dimension override name must be a string: ${Z}`);if(typeof Q!="number"||!Number.isInteger(Q)||Q<0)throw new Error(`free dimension override value must be a non-negative integer: ${Q}`);let Te=mt(Z,D);E._OrtAddFreeDimensionOverride(A,Te,Q)!==0&&Ce(`Can't set a free dimension override: ${Z} - ${Q}.`)}return O.extra!==void 0&&Fr(O.extra,"",new WeakSet,(Z,Q)=>{Ut(A,Z,Q,D)}),[A,D]}catch(G){throw A!==0&&E._OrtReleaseSessionOptions(A)!==0&&Ce("Can't release session options."),D.forEach(U=>E._free(U)),G}}}),jt,Kt,Qt,_s,bs,Ss,Ts,Ws,Ie=S(()=>{jt=y=>{switch(y){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: ${y}`)}},Kt=y=>{switch(y){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: ${y}`)}},Qt=(y,E)=>{let A=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][y],D=typeof E=="number"?E:E.reduce((O,G)=>O*G,1);return A>0?Math.ceil(D*A):void 0},_s=y=>{switch(y){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: ${y}`)}},bs=y=>{switch(y){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: ${y}`)}},Ss=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Ts=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint64"||y==="int8"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Ws=y=>{switch(y){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: ${y}`)}}}),Es,An=S(()=>{Lr(),Es=async y=>{if(typeof y=="string"){let E=await fetch(y);if(!E.ok)throw new Error(`failed to load external data file: ${y}`);let A=E.headers.get("Content-Length"),D=A?parseInt(A,10):0;if(D<1073741824)return new Uint8Array(await E.arrayBuffer());{if(!E.body)throw new Error(`failed to load external data file: ${y}, no response body.`);let O=E.body.getReader(),G;try{G=new ArrayBuffer(D)}catch(L){if(L instanceof RangeError){let V=Math.ceil(D/65536);G=new WebAssembly.Memory({initial:V,maximum:V}).buffer}else throw L}let U=0;for(;;){let{done:L,value:V}=await O.read();if(L)break;let re=V.byteLength;new Uint8Array(G,U,re).set(V),U+=re}return new Uint8Array(G,0,D)}}else return y instanceof Blob?new Uint8Array(await y.arrayBuffer()):y instanceof Uint8Array?y:new Uint8Array(y)}}),In,Hs,js,Cr,Ks,Qs,He,tr,Xs,kr,K,rs,Ys,Mn=S(()=>{yt(),Hi(),ji(),Ie(),Ht(),vs(),An(),In=(y,E)=>{Pe()._OrtInit(y,E)!==0&&Ce("Can't initialize onnxruntime.")},Hs=async y=>{In(y.wasm.numThreads,bs(y.logLevel))},js=async(y,E)=>{Pe().asyncInit?.();let A=y.webgpu.adapter;if(E==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(A){if(typeof A.limits!="object"||typeof A.features!="object"||typeof A.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let D=y.webgpu.powerPreference;if(D!==void 0&&D!=="low-power"&&D!=="high-performance")throw new Error(`Invalid powerPreference setting: "${D}"`);let O=y.webgpu.forceFallbackAdapter;if(O!==void 0&&typeof O!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${O}"`);if(A=await navigator.gpu.requestAdapter({powerPreference:D,forceFallbackAdapter:O}),!A)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(E==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Cr=new Map,Ks=y=>{let E=Pe(),A=E.stackSave();try{let D=E.PTR_SIZE,O=E.stackAlloc(2*D);E._OrtGetInputOutputCount(y,O,O+D)!==0&&Ce("Can't get session input/output count.");let G=D===4?"i32":"i64";return[Number(E.getValue(O,G)),Number(E.getValue(O+D,G))]}finally{E.stackRestore(A)}},Qs=(y,E)=>{let A=Pe(),D=A.stackSave(),O=0;try{let G=A.PTR_SIZE,U=A.stackAlloc(2*G);A._OrtGetInputOutputMetadata(y,E,U,U+G)!==0&&Ce("Can't get session input/output metadata.");let L=Number(A.getValue(U,"*"));O=Number(A.getValue(U+G,"*"));let V=A.HEAP32[O/4];if(V===0)return[L,0];let re=A.HEAPU32[O/4+1],ie=[];for(let Z=0;Z<re;Z++){let Q=Number(A.getValue(O+8+Z*G,"*"));ie.push(Q!==0?A.UTF8ToString(Q):Number(A.getValue(O+8+(Z+re)*G,"*")))}return[L,V,ie]}finally{A.stackRestore(D),O!==0&&A._OrtFree(O)}},He=y=>{let E=Pe(),A=E._malloc(y.byteLength);if(A===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${y.byteLength}.`);return E.HEAPU8.set(y,A),[A,y.byteLength]},tr=async(y,E)=>{let A,D,O=Pe();Array.isArray(y)?[A,D]=y:y.buffer===O.HEAPU8.buffer?[A,D]=[y.byteOffset,y.byteLength]:[A,D]=He(y);let G=0,U=0,L=[],V=[],re=[];try{if([U,L]=await Rn(E),E?.externalData&&O.mountExternalData){let Ee=[];for(let Ne of E.externalData){let we=typeof Ne=="string"?Ne:Ne.path;Ee.push(Es(typeof Ne=="string"?Ne:Ne.data).then(kt=>{O.mountExternalData(we,kt)}))}await Promise.all(Ee)}for(let Ee of E?.executionProviders??[])if((typeof Ee=="string"?Ee:Ee.name)==="webnn"){if(O.shouldTransferToMLTensor=!1,typeof Ee!="string"){let Ne=Ee,we=Ne?.context,kt=Ne?.gpuDevice,Mt=Ne?.deviceType,Ir=Ne?.powerPreference;we?O.currentContext=we:kt?O.currentContext=await O.webnnCreateMLContext(kt):O.currentContext=await O.webnnCreateMLContext({deviceType:Mt,powerPreference:Ir})}else O.currentContext=await O.webnnCreateMLContext();break}G=await O._OrtCreateSession(A,D,U),O.webgpuOnCreateSession?.(G),G===0&&Ce("Can't create a session."),O.jsepOnCreateSession?.(),O.currentContext&&(O.webnnRegisterMLContext(G,O.currentContext),O.currentContext=void 0,O.shouldTransferToMLTensor=!0);let[ie,Z]=Ks(G),Q=!!E?.enableGraphCapture,Te=[],F=[],le=[],ut=[],Be=[];for(let Ee=0;Ee<ie;Ee++){let[Ne,we,kt]=Qs(G,Ee);Ne===0&&Ce("Can't get an input name."),V.push(Ne);let Mt=O.UTF8ToString(Ne);Te.push(Mt),le.push(we===0?{name:Mt,isTensor:!1}:{name:Mt,isTensor:!0,type:Kt(we),shape:kt})}for(let Ee=0;Ee<Z;Ee++){let[Ne,we,kt]=Qs(G,Ee+ie);Ne===0&&Ce("Can't get an output name."),re.push(Ne);let Mt=O.UTF8ToString(Ne);F.push(Mt),ut.push(we===0?{name:Mt,isTensor:!1}:{name:Mt,isTensor:!0,type:Kt(we),shape:kt})}return Cr.set(G,[G,V,re,null,Q,!1]),[G,Te,F,le,ut]}catch(ie){throw V.forEach(Z=>O._OrtFree(Z)),re.forEach(Z=>O._OrtFree(Z)),G!==0&&O._OrtReleaseSession(G)!==0&&Ce("Can't release session."),ie}finally{O._free(A),U!==0&&O._OrtReleaseSessionOptions(U)!==0&&Ce("Can't release session options."),L.forEach(ie=>O._free(ie)),O.unmountExternalData?.()}},Xs=y=>{let E=Pe(),A=Cr.get(y);if(!A)throw new Error(`cannot release session. invalid session id: ${y}`);let[D,O,G,U,L]=A;U&&(L&&E._OrtClearBoundOutputs(U.handle)!==0&&Ce("Can't clear bound outputs."),E._OrtReleaseBinding(U.handle)!==0&&Ce("Can't release IO binding.")),E.jsepOnReleaseSession?.(y),E.webnnOnReleaseSession?.(y),E.webgpuOnReleaseSession?.(y),O.forEach(V=>E._OrtFree(V)),G.forEach(V=>E._OrtFree(V)),E._OrtReleaseSession(D)!==0&&Ce("Can't release session."),Cr.delete(y)},kr=async(y,E,A,D,O,G,U=!1)=>{if(!y){E.push(0);return}let L=Pe(),V=L.PTR_SIZE,re=y[0],ie=y[1],Z=y[3],Q=Z,Te,F;if(re==="string"&&(Z==="gpu-buffer"||Z==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(U&&Z!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${G} when enableGraphCapture is true.`);if(Z==="gpu-buffer"){let Be=y[2].gpuBuffer;F=Qt(jt(re),ie);{let Ee=L.jsepRegisterBuffer;if(!Ee)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Te=Ee(D,G,Be,F)}}else if(Z==="ml-tensor"){let Be=y[2].mlTensor;F=Qt(jt(re),ie);let Ee=L.webnnRegisterMLTensor;if(!Ee)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Te=Ee(D,Be,jt(re),ie)}else{let Be=y[2];if(Array.isArray(Be)){F=V*Be.length,Te=L._malloc(F),A.push(Te);for(let Ee=0;Ee<Be.length;Ee++){if(typeof Be[Ee]!="string")throw new TypeError(`tensor data at index ${Ee} is not a string`);L.setValue(Te+Ee*V,mt(Be[Ee],A),"*")}}else{let Ee=L.webnnIsGraphInput,Ne=L.webnnIsGraphOutput;if(re!=="string"&&Ee&&Ne){let we=L.UTF8ToString(O);if(Ee(D,we)||Ne(D,we)){let kt=jt(re);F=Qt(kt,ie),Q="ml-tensor";let Mt=L.webnnCreateTemporaryTensor,Ir=L.webnnUploadTensor;if(!Mt||!Ir)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let as=await Mt(D,kt,ie);Ir(as,new Uint8Array(Be.buffer,Be.byteOffset,Be.byteLength)),Te=as}else F=Be.byteLength,Te=L._malloc(F),A.push(Te),L.HEAPU8.set(new Uint8Array(Be.buffer,Be.byteOffset,F),Te)}else F=Be.byteLength,Te=L._malloc(F),A.push(Te),L.HEAPU8.set(new Uint8Array(Be.buffer,Be.byteOffset,F),Te)}}let le=L.stackSave(),ut=L.stackAlloc(4*ie.length);try{ie.forEach((Ee,Ne)=>L.setValue(ut+Ne*V,Ee,V===4?"i32":"i64"));let Be=L._OrtCreateTensor(jt(re),Te,F,ut,ie.length,Ws(Q));Be===0&&Ce(`Can't create tensor for input/output. session=${D}, index=${G}.`),E.push(Be)}finally{L.stackRestore(le)}},K=async(y,E,A,D,O,G)=>{let U=Pe(),L=U.PTR_SIZE,V=Cr.get(y);if(!V)throw new Error(`cannot run inference. invalid session id: ${y}`);let re=V[0],ie=V[1],Z=V[2],Q=V[3],Te=V[4];V[5];let F=E.length,le=D.length,ut=0,Be=[],Ee=[],Ne=[],we=[],kt=[],Mt=U.stackSave(),Ir=U.stackAlloc(F*L),as=U.stackAlloc(F*L),ln=U.stackAlloc(le*L),Un=U.stackAlloc(le*L);try{[ut,Be]=En(G),At("wasm prepareInputOutputTensor");for(let Ue=0;Ue<F;Ue++)await kr(A[Ue],Ee,we,y,ie[E[Ue]],E[Ue],Te);for(let Ue=0;Ue<le;Ue++)await kr(O[Ue],Ne,we,y,Z[D[Ue]],F+D[Ue],Te);Ct("wasm prepareInputOutputTensor");for(let Ue=0;Ue<F;Ue++)U.setValue(Ir+Ue*L,Ee[Ue],"*"),U.setValue(as+Ue*L,ie[E[Ue]],"*");for(let Ue=0;Ue<le;Ue++)U.setValue(ln+Ue*L,Ne[Ue],"*"),U.setValue(Un+Ue*L,Z[D[Ue]],"*");U.jsepOnRunStart?.(re),U.webnnOnRunStart?.(re);let ct;ct=await U._OrtRun(re,as,Ir,F,Un,le,ln,ut),ct!==0&&Ce("failed to call OrtRun().");let ar=[],Fn=[];At("wasm ProcessOutputTensor");for(let Ue=0;Ue<le;Ue++){let rr=Number(U.getValue(ln+Ue*L,"*"));if(rr===Ne[Ue]||kt.includes(Ne[Ue])){ar.push(O[Ue]),rr!==Ne[Ue]&&U._OrtReleaseTensor(rr)!==0&&Ce("Can't release tensor.");continue}let gi=U.stackSave(),fr=U.stackAlloc(4*L),ks=!1,wt,Lt=0;try{U._OrtGetTensorData(rr,fr,fr+L,fr+2*L,fr+3*L)!==0&&Ce(`Can't access output tensor data on index ${Ue}.`);let un=L===4?"i32":"i64",Rs=Number(U.getValue(fr,un));Lt=U.getValue(fr+L,"*");let Vn=U.getValue(fr+L*2,"*"),yi=Number(U.getValue(fr+L*3,un)),Et=[];for(let vt=0;vt<yi;vt++)Et.push(Number(U.getValue(Vn+vt*L,un)));U._OrtFree(Vn)!==0&&Ce("Can't free memory for tensor dims.");let mr=Et.reduce((vt,ht)=>vt*ht,1);wt=Kt(Rs);let os=Q?.outputPreferredLocations[D[Ue]];if(wt==="string"){if(os==="gpu-buffer"||os==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let vt=[];for(let ht=0;ht<mr;ht++){let or=U.getValue(Lt+ht*L,"*"),wi=U.getValue(Lt+(ht+1)*L,"*"),vi=ht===mr-1?void 0:wi-or;vt.push(U.UTF8ToString(or,vi))}ar.push([wt,Et,vt,"cpu"])}else if(os==="gpu-buffer"&&mr>0){let vt=U.jsepGetBuffer;if(!vt)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ht=vt(Lt),or=Qt(Rs,mr);if(or===void 0||!Ss(wt))throw new Error(`Unsupported data type: ${wt}`);ks=!0,ar.push([wt,Et,{gpuBuffer:ht,download:U.jsepCreateDownloader(ht,or,wt),dispose:()=>{U._OrtReleaseTensor(rr)!==0&&Ce("Can't release tensor.")}},"gpu-buffer"])}else if(os==="ml-tensor"&&mr>0){let vt=U.webnnEnsureTensor,ht=U.webnnIsGraphInputOutputTypeSupported;if(!vt||!ht)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Qt(Rs,mr)===void 0||!Ts(wt))throw new Error(`Unsupported data type: ${wt}`);if(!ht(y,wt,!1))throw new Error(`preferredLocation "ml-tensor" for ${wt} output is not supported by current WebNN Context.`);let or=await vt(y,Lt,Rs,Et,!1);ks=!0,ar.push([wt,Et,{mlTensor:or,download:U.webnnCreateMLTensorDownloader(Lt,wt),dispose:()=>{U.webnnReleaseTensorId(Lt),U._OrtReleaseTensor(rr)}},"ml-tensor"])}else if(os==="ml-tensor-cpu-output"&&mr>0){let vt=U.webnnCreateMLTensorDownloader(Lt,wt)(),ht=ar.length;ks=!0,Fn.push((async()=>{let or=[ht,await vt];return U.webnnReleaseTensorId(Lt),U._OrtReleaseTensor(rr),or})()),ar.push([wt,Et,[],"cpu"])}else{let vt=_s(wt),ht=new vt(mr);new Uint8Array(ht.buffer,ht.byteOffset,ht.byteLength).set(U.HEAPU8.subarray(Lt,Lt+ht.byteLength)),ar.push([wt,Et,ht,"cpu"])}}finally{U.stackRestore(gi),wt==="string"&&Lt&&U._free(Lt),ks||U._OrtReleaseTensor(rr)}}Q&&!Te&&(U._OrtClearBoundOutputs(Q.handle)!==0&&Ce("Can't clear bound outputs."),Cr.set(y,[re,ie,Z,Q,Te,!1]));for(let[Ue,rr]of await Promise.all(Fn))ar[Ue][2]=rr;return Ct("wasm ProcessOutputTensor"),ar}finally{U.webnnOnRunEnd?.(re),U.stackRestore(Mt),Ee.forEach(ct=>U._OrtReleaseTensor(ct)),Ne.forEach(ct=>U._OrtReleaseTensor(ct)),we.forEach(ct=>U._free(ct)),ut!==0&&U._OrtReleaseRunOptions(ut),Be.forEach(ct=>U._free(ct))}},rs=y=>{let E=Pe(),A=Cr.get(y);if(!A)throw new Error("invalid session id");let D=A[0],O=E._OrtEndProfiling(D);O===0&&Ce("Can't get an profile file name."),E._OrtFree(O)},Ys=y=>{let E=[];for(let A of y){let D=A[2];!Array.isArray(D)&&"buffer"in D&&E.push(D.buffer)}return E}}),hr,ke,Rr,ss,Vr,ns,$s,xs,pr,Ar,Js,Zs,en,Pn,On,fi,is,Dn,zn=S(()=>{yt(),Mn(),Ht(),ms(),hr=()=>!!me.wasm.proxy&&typeof document<"u",Rr=!1,ss=!1,Vr=!1,xs=new Map,pr=(y,E)=>{let A=xs.get(y);A?A.push(E):xs.set(y,[E])},Ar=()=>{if(Rr||!ss||Vr||!ke)throw new Error("worker not ready")},Js=y=>{switch(y.data.type){case"init-wasm":Rr=!1,y.data.err?(Vr=!0,$s[1](y.data.err)):(ss=!0,$s[0]()),ns&&(URL.revokeObjectURL(ns),ns=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let E=xs.get(y.data.type);y.data.err?E.shift()[1](y.data.err):E.shift()[0](y.data.out);break}}},Zs=async()=>{if(!ss){if(Rr)throw new Error("multiple calls to 'initWasm()' detected.");if(Vr)throw new Error("previous call to 'initWasm()' failed.");if(Rr=!0,hr())return new Promise((y,E)=>{ke?.terminate(),vn().then(([A,D])=>{try{ke=D,ke.onerror=G=>E(G),ke.onmessage=Js,$s=[y,E];let O={type:"init-wasm",in:me};if(!O.in.wasm.wasmPaths&&A){let G=cs();G&&(O.in.wasm.wasmPaths=G)}ke.postMessage(O),ns=A}catch(O){E(O)}},E)});try{await ws(me.wasm),await Hs(me),ss=!0}catch(y){throw Vr=!0,y}finally{Rr=!1}}},en=async y=>{if(hr())return Ar(),new Promise((E,A)=>{pr("init-ep",[E,A]);let D={type:"init-ep",in:{epName:y,env:me}};ke.postMessage(D)});await js(me,y)},Pn=async y=>hr()?(Ar(),new Promise((E,A)=>{pr("copy-from",[E,A]);let D={type:"copy-from",in:{buffer:y}};ke.postMessage(D,[y.buffer])})):He(y),On=async(y,E)=>{if(hr()){if(E?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ar(),new Promise((A,D)=>{pr("create",[A,D]);let O={type:"create",in:{model:y,options:{...E}}},G=[];y instanceof Uint8Array&&G.push(y.buffer),ke.postMessage(O,G)})}else return tr(y,E)},fi=async y=>{if(hr())return Ar(),new Promise((E,A)=>{pr("release",[E,A]);let D={type:"release",in:y};ke.postMessage(D)});Xs(y)},is=async(y,E,A,D,O,G)=>{if(hr()){if(A.some(U=>U[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(O.some(U=>U))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ar(),new Promise((U,L)=>{pr("run",[U,L]);let V=A,re={type:"run",in:{sessionId:y,inputIndices:E,inputs:V,outputIndices:D,options:G}};ke.postMessage(re,Ys(V))})}else return K(y,E,A,D,O,G)},Dn=async y=>{if(hr())return Ar(),new Promise((E,A)=>{pr("end-profiling",[E,A]);let D={type:"end-profiling",in:y};ke.postMessage(D)});rs(y)}}),Ln,tn,rn,sn=S(()=>{yt(),zn(),Ie(),Lr(),An(),Ln=(y,E)=>{switch(y.location){case"cpu":return[y.type,y.dims,y.data,"cpu"];case"gpu-buffer":return[y.type,y.dims,{gpuBuffer:y.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[y.type,y.dims,{mlTensor:y.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${y.location} for ${E()}`)}},tn=y=>{switch(y[3]){case"cpu":return new lt(y[0],y[2],y[1]);case"gpu-buffer":{let E=y[0];if(!Ss(E))throw new Error(`not supported data type: ${E} for deserializing GPU tensor`);let{gpuBuffer:A,download:D,dispose:O}=y[2];return lt.fromGpuBuffer(A,{dataType:E,dims:y[1],download:D,dispose:O})}case"ml-tensor":{let E=y[0];if(!Ts(E))throw new Error(`not supported data type: ${E} for deserializing MLTensor tensor`);let{mlTensor:A,download:D,dispose:O}=y[2];return lt.fromMLTensor(A,{dataType:E,dims:y[1],download:D,dispose:O})}default:throw new Error(`invalid data location: ${y[3]}`)}},rn=class{async fetchModelAndCopyToWasmMemory(y){return Pn(await Es(y))}async loadModel(y,E){gt();let A;typeof y=="string"?A=await this.fetchModelAndCopyToWasmMemory(y):A=y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await On(A,E),ft()}async dispose(){return fi(this.sessionId)}async run(y,E,A){gt();let D=[],O=[];Object.entries(y).forEach(Z=>{let Q=Z[0],Te=Z[1],F=this.inputNames.indexOf(Q);if(F===-1)throw new Error(`invalid input '${Q}'`);D.push(Te),O.push(F)});let G=[],U=[];Object.entries(E).forEach(Z=>{let Q=Z[0],Te=Z[1],F=this.outputNames.indexOf(Q);if(F===-1)throw new Error(`invalid output '${Q}'`);G.push(Te),U.push(F)});let L=D.map((Z,Q)=>Ln(Z,()=>`input "${this.inputNames[O[Q]]}"`)),V=G.map((Z,Q)=>Z?Ln(Z,()=>`output "${this.outputNames[U[Q]]}"`):null),re=await is(this.sessionId,O,L,U,V,A),ie={};for(let Z=0;Z<re.length;Z++)ie[this.outputNames[U[Z]]]=G[Z]??tn(re[Z]);return ft(),ie}startProfiling(){}endProfiling(){Dn(this.sessionId)}}}),Cs={};N(Cs,{OnnxruntimeWebAssemblyBackend:()=>an,initializeFlags:()=>nn,wasmBackend:()=>on});var nn,an,on,Bn=S(()=>{yt(),zn(),sn(),nn=()=>{(typeof me.wasm.initTimeout!="number"||me.wasm.initTimeout<0)&&(me.wasm.initTimeout=0);let y=me.wasm.simd;if(typeof y!="boolean"&&y!==void 0&&y!=="fixed"&&y!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${y}". Reset it to \`false\` and ignore SIMD feature checking.`),me.wasm.simd=!1),typeof me.wasm.proxy!="boolean"&&(me.wasm.proxy=!1),typeof me.wasm.trace!="boolean"&&(me.wasm.trace=!1),typeof me.wasm.numThreads!="number"||!Number.isInteger(me.wasm.numThreads)||me.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)me.wasm.numThreads=1;else{let E=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;me.wasm.numThreads=Math.min(4,Math.ceil((E||1)/2))}},an=class{async init(y){nn(),await Zs(),await en(y)}async createInferenceSessionHandler(y,E){let A=new rn;return await A.loadModel(y,E),A}},on=new an}),Nn={};N(Nn,{InferenceSession:()=>zr,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>At,TRACE_EVENT_END:()=>Ct,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>ft,Tensor:()=>lt,default:()=>Ki,env:()=>me,registerBackend:()=>J}),yt(),yt(),yt();var mi="1.26.0",Ki=xr;{let y=(Bn(),te(Cs)).wasmBackend;J("cpu",y,10),J("wasm",y,10)}return Object.defineProperty(me.versions,"web",{value:mi,enumerable:!0}),te(Nn)})();d.exports=s})(io)),io.exports}var Mp;function Ey(){return Mp||(Mp=1,(function(d){var r=jr&&jr.__createBinding||(Object.create?(function(de,ce,pe,he){he===void 0&&(he=pe);var Ve=Object.getOwnPropertyDescriptor(ce,pe);(!Ve||("get"in Ve?!ce.__esModule:Ve.writable||Ve.configurable))&&(Ve={enumerable:!0,get:function(){return ce[pe]}}),Object.defineProperty(de,he,Ve)}):(function(de,ce,pe,he){he===void 0&&(he=pe),de[he]=ce[pe]})),s=jr&&jr.__setModuleDefault||(Object.create?(function(de,ce){Object.defineProperty(de,"default",{enumerable:!0,value:ce})}):function(de,ce){de.default=ce}),a=jr&&jr.__importStar||function(de){if(de&&de.__esModule)return de;var ce={};if(de!=null)for(var pe in de)pe!=="default"&&Object.prototype.hasOwnProperty.call(de,pe)&&r(ce,de,pe);return s(ce,de),ce};Object.defineProperty(d,"__esModule",{value:!0}),d.MicVAD=d.getDefaultRealTimeVADOptions=d.ort=d.DEFAULT_MODEL=void 0;const f=a(Ty()),_=Io(),C=Mo(),R=hi(),S=qi(),N=hf(),z=pf();d.DEFAULT_MODEL="legacy",d.ort=f;const te="vad.worklet.bundle.min.js",j="silero_vad_v5.onnx",se="silero_vad_legacy.onnx",J=de=>({...C.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{R.log.debug("VAD misfire")},onSpeechStart:()=>{R.log.debug("Detected speech start")},onSpeechEnd:()=>{R.log.debug("Detected speech end")},onSpeechRealStart:()=>{R.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:de,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async ce=>{ce.getTracks().forEach(pe=>{pe.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:ce=>{ce.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});d.getDefaultRealTimeVADOptions=J;const Y=de=>"audioWorklet"in de&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function W(de,ce,pe,he,Ve){await pe.audioWorklet.addModule(de),ce.processorOptions={...ce.processorOptions??{},frameSamples:he};const me=new AudioWorkletNode(pe,"vad-helper-worklet",ce);return me.port.onmessage=async Ye=>{const qe=Ye.data;if(!(typeof qe=="object"&&qe&&"message"in qe)){console.error("Invalid message event",qe);return}switch(qe.message){case S.Message.AudioFrame:{if(!("data"in qe&&qe.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const it=new Float32Array(qe.data);await Ve(it);break}}},me}async function ne(de,ce,pe){const he=new z.Resampler({nativeSampleRate:de.sampleRate,targetSampleRate:16e3,targetFrameSize:ce});R.log.debug("using script processor");const me=de.createScriptProcessor(4096,1,1);let Ye=!1;return me.onaudioprocess=async qe=>{if(!Ye){Ye=!0;try{const it=qe.inputBuffer.getChannelData(0);qe.outputBuffer.getChannelData(0).fill(0);const at=he.process(it);for(const tt of at)await pe(tt)}catch(it){console.error("Error processing audio:",it)}finally{Ye=!1}}},me.connect(de.destination),me}class fe{constructor(ce,pe,he,Ve,me=!1,Ye=null,qe=null,it=null,Je=null,at=null,tt=null,qt="uninitialized",xt=!1){this.options=ce,this.frameProcessor=pe,this.model=he,this.frameSamples=Ve,this.listening=me,this.errored=Ye,this._stream=qe,this._audioContext=it,this._vadNode=Je,this._mediaStreamAudioSourceNode=at,this._audioProcessorAdapterType=tt,this.initializationState=qt,this.ownsAudioContext=xt,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=Ke=>{this.initializationState="errored",this.errored=Ke},this.start=async()=>{switch(this.initializationState){case"uninitialized":{R.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(Ke){throw Ke instanceof Error?this.setErrored(Ke.message):this.setErrored(String(Ke)),Ke}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"?Y(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await W(this.options.baseAssetPath+te,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await ne(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),R.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{R.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:Ke,audioContext:We,vadNode:st}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ke);const ze=new MediaStreamAudioSourceNode(We,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=ze,ze.connect(st);break}case"destroyed":{R.log.warn("start called after destroyed");break}case"errored":{R.log.error("start called after errored");break}default:{R.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:Ke,mediaStreamAudioSourceNode:We}=this.getAudioInstances();await this.options.pauseStream(Ke),We.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{R.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ke}=this.getAudioInstances();Ke instanceof AudioWorkletNode&&Ke.port.postMessage(S.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await this._audioContext?.close()},this.setOptions=Ke=>{this.frameProcessor.setOptions(Ke)},this.processFrame=async Ke=>{await this.frameProcessor.process(Ke,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ke=>{switch(Ke.msg){case S.Message.FrameProcessed:this.options.onFrameProcessed(Ke.probs,Ke.frame);break;case S.Message.SpeechStart:this.options.onSpeechStart();break;case S.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case S.Message.VADMisfire:this.options.onVADMisfire();break;case S.Message.SpeechEnd:this.options.onSpeechEnd(Ke.audio);break}}}static async new(ce={}){const pe={...(0,d.getDefaultRealTimeVADOptions)(ce.model??d.DEFAULT_MODEL),...ce};(0,C.validateOptions)(pe),d.ort.env.wasm.wasmPaths=pe.onnxWASMBasePath,pe.ortConfig!==void 0&&pe.ortConfig(d.ort);const he=pe.model==="v5"?j:se,Ve=pe.baseAssetPath+he,me=pe.model==="v5"?N.SileroV5.new:N.SileroLegacy.new;let Ye;try{Ye=await me(d.ort,()=>(0,_.defaultModelFetcher)(Ve))}catch(tt){throw console.error(`Encountered an error while loading model file ${Ve}`),tt}const qe=pe.model==="v5"?512:1536,it=qe/16,Je=new C.FrameProcessor(Ye.process,Ye.reset_state,{positiveSpeechThreshold:pe.positiveSpeechThreshold,negativeSpeechThreshold:pe.negativeSpeechThreshold,redemptionMs:pe.redemptionMs,preSpeechPadMs:pe.preSpeechPadMs,minSpeechMs:pe.minSpeechMs,submitUserSpeechOnPause:pe.submitUserSpeechOnPause},it),at=new fe(pe,Je,Ye,qe);if(pe.startOnLoad)try{await at.start()}catch(tt){throw console.error("Error starting micVad",tt),tt}return at}}d.MicVAD=fe})(jr)),jr}var Pp;function Op(){return Pp||(Pp=1,(function(d){Object.defineProperty(d,"__esModule",{value:!0}),d.getDefaultRealTimeVADOptions=d.MicVAD=d.DEFAULT_MODEL=d.utils=d.NonRealTimeVAD=d.Message=d.FrameProcessor=d.defaultModelFetcher=d.baseAssetPath=void 0;var r=uf();Object.defineProperty(d,"baseAssetPath",{enumerable:!0,get:function(){return r.baseAssetPath}});var s=Io();Object.defineProperty(d,"defaultModelFetcher",{enumerable:!0,get:function(){return s.defaultModelFetcher}});var a=Mo();Object.defineProperty(d,"FrameProcessor",{enumerable:!0,get:function(){return a.FrameProcessor}});var f=qi();Object.defineProperty(d,"Message",{enumerable:!0,get:function(){return f.Message}});var _=by();Object.defineProperty(d,"NonRealTimeVAD",{enumerable:!0,get:function(){return _.NonRealTimeVAD}});const C=Sy();d.utils={audioFileToArray:C.audioFileToArray,minFramesForTargetMS:C.minFramesForTargetMS,arrayBufferToBase64:C.arrayBufferToBase64,encodeWAV:C.encodeWAV};var R=Ey();Object.defineProperty(d,"DEFAULT_MODEL",{enumerable:!0,get:function(){return R.DEFAULT_MODEL}}),Object.defineProperty(d,"MicVAD",{enumerable:!0,get:function(){return R.MicVAD}}),Object.defineProperty(d,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return R.getDefaultRealTimeVADOptions}})})(ro)),ro}var Dp;function $y(){return Dp||(Dp=1,(function(d){Object.defineProperty(d,"__esModule",{value:!0}),d.useMicVAD=d.getDefaultReactRealTimeVADOptions=d.utils=void 0;const r=Op(),s=ae;var a=Op();Object.defineProperty(d,"utils",{enumerable:!0,get:function(){return a.utils}});const f={userSpeakingThreshold:.6},_=S=>({...(0,r.getDefaultRealTimeVADOptions)(S),...f});d.getDefaultReactRealTimeVADOptions=_;function C(S){const N=S.model??r.DEFAULT_MODEL,z={...(0,d.getDefaultReactRealTimeVADOptions)(N),...S},te={userSpeakingThreshold:z.userSpeakingThreshold},j={positiveSpeechThreshold:z.positiveSpeechThreshold,negativeSpeechThreshold:z.negativeSpeechThreshold,redemptionMs:z.redemptionMs,preSpeechPadMs:z.preSpeechPadMs,minSpeechMs:z.minSpeechMs,submitUserSpeechOnPause:z.submitUserSpeechOnPause,onFrameProcessed:z.onFrameProcessed,onVADMisfire:z.onVADMisfire,onSpeechStart:z.onSpeechStart,onSpeechEnd:z.onSpeechEnd,onSpeechRealStart:z.onSpeechRealStart,baseAssetPath:z.baseAssetPath,onnxWASMBasePath:z.onnxWASMBasePath,model:z.model,workletOptions:z.workletOptions,getStream:z.getStream,pauseStream:z.pauseStream,resumeStream:z.resumeStream,startOnLoad:z.startOnLoad,processorType:z.processorType};return z.ortConfig&&(j.ortConfig=z.ortConfig),z.audioContext&&(j.audioContext=z.audioContext),[te,j]}function R(S){const[N,z]=C(S),te=S.model??r.DEFAULT_MODEL,[j,se]=(0,s.useState)(!1),[J,Y]=(0,s.useState)(!0),[W,ne]=(0,s.useState)(!1),[fe,de]=(0,s.useState)(!1),[ce,pe]=(0,s.useState)(null),he=(0,s.useRef)(z.onFrameProcessed),Ve=(0,s.useRef)(z.onSpeechEnd),me=(0,s.useRef)(z.onSpeechStart),Ye=(0,s.useRef)(z.onSpeechRealStart),qe=(0,s.useRef)(z.onVADMisfire),it=(0,s.useRef)(z.getStream);(0,s.useEffect)(()=>{he.current=z.onFrameProcessed,Ve.current=z.onSpeechEnd,me.current=z.onSpeechStart,Ye.current=z.onSpeechRealStart,qe.current=z.onVADMisfire},[z.onFrameProcessed,z.onSpeechEnd,z.onSpeechStart,z.onSpeechRealStart,z.onVADMisfire]),(0,s.useEffect)(()=>{it.current=z.getStream},[z.getStream]);const Je=z.getStream.toString();(0,s.useEffect)(()=>{let xt=null,Ke=!1;return(async()=>{try{Y(!0),ne(!1);const st={...z,onFrameProcessed:(ze,Rt)=>{const sr=ze.isSpeech>N.userSpeakingThreshold;se(sr),he.current(ze,Rt)},onSpeechEnd:ze=>{Ve.current(ze)},onSpeechStart:()=>{me.current()},onSpeechRealStart:()=>{Ye.current()},onVADMisfire:()=>{qe.current()},getStream:()=>it.current()};if(xt=await r.MicVAD.new(st),Ke){await xt.destroy();return}pe(xt),z.startOnLoad&&(await xt.start(),de(!0)),Y(!1)}catch(st){Y(!1),st instanceof Error?ne(st.message):ne(String(st))}})().catch(()=>{}),function(){Ke=!0,xt&&xt.destroy(),!J&&!W&&de(!1)}},[Je,te]);const at=(0,s.useCallback)(async()=>{!J&&!W&&(await ce?.pause(),de(!1))},[J,W,ce]),tt=(0,s.useCallback)(async()=>{!J&&!W&&(await ce?.start(),de(!0))},[J,W,ce]),qt=(0,s.useCallback)(async()=>{fe?await at():await tt()},[fe,at,tt]);return{listening:fe,errored:W,loading:J,userSpeaking:j,pause:at,start:tt,toggle:qt}}d.useMicVAD=R})(to)),to}var xy=$y();const zp={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},Cy=16e3,mf=512,gf=1e3,ky=300,Ry=mf/Cy*1e3,Ay=Math.ceil(gf/Ry);function ao(d){const r=new ArrayBuffer(d.length*2),s=new DataView(r);for(let a=0;a<d.length;a++){const f=Math.max(-1,Math.min(1,d[a]));s.setInt16(a*2,f<0?f*32768:f*32767,!0)}return new Uint8Array(r)}function oo(d){if(!d.length)return new Float32Array(0);if(d.length===1)return d[0];const r=d.reduce((f,_)=>f+_.length,0),s=new Float32Array(r);let a=0;for(const f of d)s.set(f,a),a+=f.length;return s}function Iy(d={}){const{onAudioChunk:r,onAudioEnd:s,onSpeechStart:a,onSpeechEnd:f,onVADMisfire:_,onError:C,enabled:R=!0,preloadStream:S=!0}=d,{sendAudioChunk:N,endAudioStream:z}=Fs(),[te,j]=ae.useState(!1),[se,J]=ae.useState(null),Y=ae.useRef(null),W=ae.useRef(!1),ne=ae.useRef(null),fe=ae.useRef([]),de=ae.useRef(!1),ce=ae.useRef([]),pe=r??N;ae.useEffect(()=>{!R||!S||typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||navigator.mediaDevices.getUserMedia({audio:zp}).then(We=>{Y.current=We,J(null)}).catch(We=>{J("permission_denied"),C?.(We)})},[R,C,S]);const he=ae.useCallback(async()=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone APIs are unavailable in this browser");if(Y.current&&Y.current.getTracks()[0]?.readyState==="live")return Y.current;const We=await navigator.mediaDevices.getUserMedia({audio:zp});return Y.current=We,J(null),We},[]),Ve=ae.useCallback(async We=>{We.getTracks().forEach(st=>{st.enabled=!1})},[]),me=ae.useCallback(async()=>Y.current&&Y.current.getTracks()[0]?.readyState==="live"?(Y.current.getTracks().forEach(We=>{We.enabled=!0}),Y.current):he(),[he]);ae.useCallback(()=>{const We=fe.current;return fe.current=[],oo(We)},[]);const Ye=ae.useCallback(()=>{ce.current=[];const We=fe.current;fe.current=[];for(const st of We)pe(ao(st));de.current=!0},[pe]),qe=ae.useCallback(()=>{de.current=!1;const We=ce.current;if(ce.current=[],We.length>0){const st=oo(We);pe(ao(st))}},[pe]),it=ae.useCallback(()=>{Y.current&&(Y.current.getTracks().forEach(We=>We.stop()),Y.current=null)},[]);if(!R)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 Je=xy.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:gf,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:mf}},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:We=>{We.env.wasm.numThreads=1,We.env.logLevel="error"},getStream:he,pauseStream:Ve,resumeStream:me,onFrameProcessed:(We,st)=>{if(st&&(fe.current.push(new Float32Array(st)),fe.current.length>Ay&&fe.current.shift(),de.current)){const ze=ce.current;if(ze.push(new Float32Array(st)),ze.length>=3){const Rt=oo(ze);ze.length=0,pe(ao(Rt))}}},onSpeechStart:()=>{W.current||(ne.current&&(clearTimeout(ne.current),ne.current=null),j(!0),a?.(),Ye())},onSpeechEnd:()=>{ne.current=setTimeout(()=>{j(!1),qe(),s?s():z(),W.current=!0,setTimeout(()=>{W.current=!1},300),f?.()},ky)},onVADMisfire:()=>{ne.current&&(clearTimeout(ne.current),ne.current=null),j(!1),qe(),_?.()}}),at=ae.useCallback(async()=>!R||Je.loading||Je.errored?!1:(Je.listening&&(ne.current&&(clearTimeout(ne.current),ne.current=null),j(!1),qe(),await Je.pause()),!0),[R,qe,Je]),tt=ae.useCallback(async()=>{try{await Je.start()}catch(We){const st=We instanceof Error?We.message:String(We);if(st.includes("null stream")||st.includes("audio context")||st.includes("processor adapter"))await new Promise(ze=>setTimeout(ze,100)),await Je.start();else throw We}},[Je]),qt=ae.useCallback(async()=>!R||Je.loading||Je.errored?!1:(Je.listening?(ne.current&&(clearTimeout(ne.current),ne.current=null),j(!1),qe(),await Je.pause()):await tt(),!0),[R,qe,tt]),xt=ae.useCallback(async()=>R?he():null,[R,he]),Ke=ae.useCallback(async()=>!R||Je.loading||Je.errored?!1:(Je.listening||await tt(),!0),[R,tt]);return ae.useEffect(()=>()=>{ne.current&&clearTimeout(ne.current),qe(),it()},[it,qe]),{isListening:Je.listening,isLoading:Je.loading,isErrored:!!Je.errored,isSpeaking:te,micError:se,toggle:qt,prepare:xt,start:Ke,stop:at,pause:Je.pause,userSpeaking:Je.userSpeaking}}function My(d,r,s=[]){const{events:a}=Fs();ae.useEffect(()=>a.on(d,r),[d,r,a,...s])}function Py({connect:d=!0,session:r,onError:s,onInitialized:a,clientTools:f,children:_}){const{initializeSession:C,joinDesktopSession:R,disconnect:S,registerClientTools:N}=of(),z=ae.useRef(!1),te=ae.useRef(!1),j=ae.useRef(C),se=ae.useRef(R),J=ae.useRef(S),Y=ae.useRef(s),W=ae.useRef(a),ne=ae.useRef(N),fe=ae.useRef(f);return ae.useEffect(()=>{j.current=C}),ae.useEffect(()=>{se.current=R}),ae.useEffect(()=>{J.current=S}),ae.useEffect(()=>{Y.current=s}),ae.useEffect(()=>{W.current=a}),ae.useEffect(()=>{ne.current=N}),ae.useEffect(()=>{fe.current=f}),ae.useEffect(()=>{if(!d||z.current)return;z.current=!0,te.current=!1;let de=!1;return(async()=>{try{const pe=fe.current;if(r?.mode==="join_desktop"){const Ve=await se.current({uniqueId:r.uniqueId});de||(pe&&ne.current(pe),W.current?.(Ve));return}const he=await j.current({apiKey:r?.apiKey,publicChatId:r?.publicChatId,agentId:r?.agentId,language:r?.language||"en",config:r?.config});de||(pe&&ne.current(pe),W.current?.(he))}catch(pe){de||(te.current=!0,Y.current?.(pe))}})(),()=>{de=!0,!te.current&&(J.current(),z.current=!1)}},[d,r]),Jt.jsx(Jt.Fragment,{children:_})}function Oy({children:d,wsUrl:r,restUrl:s,session:a,connect:f=!0,enableAudio:_=!0,pcmOptions:C,debug:R=!1,withCredentials:S=!1,onError:N,onInitialized:z,clientTools:te}){return Jt.jsx(af,{wsUrl:r,restUrl:s,enableAudio:_,pcmOptions:C,debug:R,withCredentials:S,children:Jt.jsx(Py,{connect:f,session:a,onError:N,onInitialized:z,clientTools:te,children:d})})}var lo={exports:{}},Lp;function Dy(){return Lp||(Lp=1,(function(d){const r={};r.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},r.localCName=r.generateIdentifier(),r.splitLines=function(s){return s.trim().split(`
|
|
2839
2839
|
`).map(a=>a.trim())},r.splitSections=function(s){return s.split(`
|
|
2840
2840
|
m=`).map((f,_)=>(_>0?"m="+f:f).trim()+`\r
|
|
2841
2841
|
`)},r.getDescription=function(s){const a=r.splitSections(s);return a&&a[0]},r.getMediaSections=function(s){const a=r.splitSections(s);return a.shift(),a},r.matchPrefix=function(s,a){return r.splitLines(s).filter(f=>f.indexOf(a)===0)},r.parseCandidate=function(s){let a;s.indexOf("a=candidate:")===0?a=s.substring(12).split(" "):a=s.substring(10).split(" ");const f={foundation:a[0],component:{1:"rtp",2:"rtcp"}[a[1]]||a[1],protocol:a[2].toLowerCase(),priority:parseInt(a[3],10),ip:a[4],address:a[4],port:parseInt(a[5],10),type:a[7]};for(let _=8;_<a.length;_+=2)switch(a[_]){case"raddr":f.relatedAddress=a[_+1];break;case"rport":f.relatedPort=parseInt(a[_+1],10);break;case"tcptype":f.tcpType=a[_+1];break;case"ufrag":f.ufrag=a[_+1],f.usernameFragment=a[_+1];break;default:f[a[_]]===void 0&&(f[a[_]]=a[_+1]);break}return f},r.writeCandidate=function(s){const a=[];a.push(s.foundation);const f=s.component;f==="rtp"?a.push(1):f==="rtcp"?a.push(2):a.push(f),a.push(s.protocol.toUpperCase()),a.push(s.priority),a.push(s.address||s.ip),a.push(s.port);const _=s.type;return a.push("typ"),a.push(_),_!=="host"&&s.relatedAddress&&s.relatedPort!==void 0&&(a.push("raddr"),a.push(s.relatedAddress),a.push("rport"),a.push(s.relatedPort)),s.tcpType&&s.protocol.toLowerCase()==="tcp"&&(a.push("tcptype"),a.push(s.tcpType)),(s.usernameFragment||s.ufrag)&&(a.push("ufrag"),a.push(s.usernameFragment||s.ufrag)),"candidate:"+a.join(" ")},r.parseIceOptions=function(s){return s.substring(14).split(" ")},r.parseRtpMap=function(s){let a=s.substring(9).split(" ");const f={payloadType:parseInt(a.shift(),10)};return a=a[0].split("/"),f.name=a[0],f.clockRate=parseInt(a[1],10),f.channels=a.length===3?parseInt(a[2],10):1,f.numChannels=f.channels,f},r.writeRtpMap=function(s){let a=s.payloadType;s.preferredPayloadType!==void 0&&(a=s.preferredPayloadType);const f=s.channels||s.numChannels||1;return"a=rtpmap:"+a+" "+s.name+"/"+s.clockRate+(f!==1?"/"+f:"")+`\r
|
|
@@ -2848,14 +2848,14 @@ m=`).map((f,_)=>(_>0?"m="+f:f).trim()+`\r
|
|
|
2848
2848
|
`},r.parseCryptoKeyParams=function(s){if(s.indexOf("inline:")!==0)return null;const a=s.substring(7).split("|");return{keyMethod:"inline",keySalt:a[0],lifeTime:a[1],mkiValue:a[2]?a[2].split(":")[0]:void 0,mkiLength:a[2]?a[2].split(":")[1]:void 0}},r.writeCryptoKeyParams=function(s){return s.keyMethod+":"+s.keySalt+(s.lifeTime?"|"+s.lifeTime:"")+(s.mkiValue&&s.mkiLength?"|"+s.mkiValue+":"+s.mkiLength:"")},r.getCryptoParameters=function(s,a){return r.matchPrefix(s+a,"a=crypto:").map(r.parseCryptoLine)},r.getIceParameters=function(s,a){const f=r.matchPrefix(s+a,"a=ice-ufrag:")[0],_=r.matchPrefix(s+a,"a=ice-pwd:")[0];return f&&_?{usernameFragment:f.substring(12),password:_.substring(10)}:null},r.writeIceParameters=function(s){let a="a=ice-ufrag:"+s.usernameFragment+`\r
|
|
2849
2849
|
a=ice-pwd:`+s.password+`\r
|
|
2850
2850
|
`;return s.iceLite&&(a+=`a=ice-lite\r
|
|
2851
|
-
`),a},r.parseRtpParameters=function(s){const a={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},_=r.splitLines(s)[0].split(" ");a.profile=_[2];for(let R=3;R<_.length;R++){const
|
|
2851
|
+
`),a},r.parseRtpParameters=function(s){const a={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},_=r.splitLines(s)[0].split(" ");a.profile=_[2];for(let R=3;R<_.length;R++){const S=_[R],N=r.matchPrefix(s,"a=rtpmap:"+S+" ")[0];if(N){const z=r.parseRtpMap(N),te=r.matchPrefix(s,"a=fmtp:"+S+" ");switch(z.parameters=te.length?r.parseFmtp(te[0]):{},z.rtcpFeedback=r.matchPrefix(s,"a=rtcp-fb:"+S+" ").map(r.parseRtcpFb),a.codecs.push(z),z.name.toUpperCase()){case"RED":case"ULPFEC":a.fecMechanisms.push(z.name.toUpperCase());break}}}r.matchPrefix(s,"a=extmap:").forEach(R=>{a.headerExtensions.push(r.parseExtmap(R))});const C=r.matchPrefix(s,"a=rtcp-fb:* ").map(r.parseRtcpFb);return a.codecs.forEach(R=>{C.forEach(S=>{R.rtcpFeedback.find(z=>z.type===S.type&&z.parameter===S.parameter)||R.rtcpFeedback.push(S)})}),a},r.writeRtpDescription=function(s,a){let f="";f+="m="+s+" ",f+=a.codecs.length>0?"9":"0",f+=" "+(a.profile||"UDP/TLS/RTP/SAVPF")+" ",f+=a.codecs.map(C=>C.preferredPayloadType!==void 0?C.preferredPayloadType:C.payloadType).join(" ")+`\r
|
|
2852
2852
|
`,f+=`c=IN IP4 0.0.0.0\r
|
|
2853
2853
|
`,f+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
2854
2854
|
`,a.codecs.forEach(C=>{f+=r.writeRtpMap(C),f+=r.writeFmtp(C),f+=r.writeRtcpFb(C)});let _=0;return a.codecs.forEach(C=>{C.maxptime>_&&(_=C.maxptime)}),_>0&&(f+="a=maxptime:"+_+`\r
|
|
2855
|
-
`),a.headerExtensions&&a.headerExtensions.forEach(C=>{f+=r.writeExtmap(C)}),f},r.parseRtpEncodingParameters=function(s){const a=[],f=r.parseRtpParameters(s),_=f.fecMechanisms.indexOf("RED")!==-1,C=f.fecMechanisms.indexOf("ULPFEC")!==-1,R=r.matchPrefix(s,"a=ssrc:").map(
|
|
2855
|
+
`),a.headerExtensions&&a.headerExtensions.forEach(C=>{f+=r.writeExtmap(C)}),f},r.parseRtpEncodingParameters=function(s){const a=[],f=r.parseRtpParameters(s),_=f.fecMechanisms.indexOf("RED")!==-1,C=f.fecMechanisms.indexOf("ULPFEC")!==-1,R=r.matchPrefix(s,"a=ssrc:").map(j=>r.parseSsrcMedia(j)).filter(j=>j.attribute==="cname"),S=R.length>0&&R[0].ssrc;let N;const z=r.matchPrefix(s,"a=ssrc-group:FID").map(j=>j.substring(17).split(" ").map(J=>parseInt(J,10)));z.length>0&&z[0].length>1&&z[0][0]===S&&(N=z[0][1]),f.codecs.forEach(j=>{if(j.name.toUpperCase()==="RTX"&&j.parameters.apt){let se={ssrc:S,codecPayloadType:parseInt(j.parameters.apt,10)};S&&N&&(se.rtx={ssrc:N}),a.push(se),_&&(se=JSON.parse(JSON.stringify(se)),se.fec={ssrc:S,mechanism:C?"red+ulpfec":"red"},a.push(se))}}),a.length===0&&S&&a.push({ssrc:S});let te=r.matchPrefix(s,"b=");return te.length&&(te[0].indexOf("b=TIAS:")===0?te=parseInt(te[0].substring(7),10):te[0].indexOf("b=AS:")===0?te=parseInt(te[0].substring(5),10)*1e3*.95-2e3*8:te=void 0,a.forEach(j=>{j.maxBitrate=te})),a},r.parseRtcpParameters=function(s){const a={},f=r.matchPrefix(s,"a=ssrc:").map(R=>r.parseSsrcMedia(R)).filter(R=>R.attribute==="cname")[0];f&&(a.cname=f.value,a.ssrc=f.ssrc);const _=r.matchPrefix(s,"a=rtcp-rsize");a.reducedSize=_.length>0,a.compound=_.length===0;const C=r.matchPrefix(s,"a=rtcp-mux");return a.mux=C.length>0,a},r.writeRtcpParameters=function(s){let a="";return s.reducedSize&&(a+=`a=rtcp-rsize\r
|
|
2856
2856
|
`),s.mux&&(a+=`a=rtcp-mux\r
|
|
2857
2857
|
`),s.ssrc!==void 0&&s.cname&&(a+="a=ssrc:"+s.ssrc+" cname:"+s.cname+`\r
|
|
2858
|
-
`),a},r.parseMsid=function(s){let a;const f=r.matchPrefix(s,"a=msid:");if(f.length===1)return a=f[0].substring(7).split(" "),{stream:a[0],track:a[1]};const _=r.matchPrefix(s,"a=ssrc:").map(C=>r.parseSsrcMedia(C)).filter(C=>C.attribute==="msid");if(_.length>0)return a=_[0].value.split(" "),{stream:a[0],track:a[1]}},r.parseSctpDescription=function(s){const a=r.parseMLine(s),f=r.matchPrefix(s,"a=max-message-size:");let _;f.length>0&&(_=parseInt(f[0].substring(19),10)),isNaN(_)&&(_=65536);const C=r.matchPrefix(s,"a=sctp-port:");if(C.length>0)return{port:parseInt(C[0].substring(12),10),protocol:a.fmt,maxMessageSize:_};const R=r.matchPrefix(s,"a=sctpmap:");if(R.length>0){const
|
|
2858
|
+
`),a},r.parseMsid=function(s){let a;const f=r.matchPrefix(s,"a=msid:");if(f.length===1)return a=f[0].substring(7).split(" "),{stream:a[0],track:a[1]};const _=r.matchPrefix(s,"a=ssrc:").map(C=>r.parseSsrcMedia(C)).filter(C=>C.attribute==="msid");if(_.length>0)return a=_[0].value.split(" "),{stream:a[0],track:a[1]}},r.parseSctpDescription=function(s){const a=r.parseMLine(s),f=r.matchPrefix(s,"a=max-message-size:");let _;f.length>0&&(_=parseInt(f[0].substring(19),10)),isNaN(_)&&(_=65536);const C=r.matchPrefix(s,"a=sctp-port:");if(C.length>0)return{port:parseInt(C[0].substring(12),10),protocol:a.fmt,maxMessageSize:_};const R=r.matchPrefix(s,"a=sctpmap:");if(R.length>0){const S=R[0].substring(10).split(" ");return{port:parseInt(S[0],10),protocol:S[1],maxMessageSize:_}}},r.writeSctpDescription=function(s,a){let f=[];return s.protocol!=="DTLS/SCTP"?f=["m="+s.kind+" 9 "+s.protocol+" "+a.protocol+`\r
|
|
2859
2859
|
`,`c=IN IP4 0.0.0.0\r
|
|
2860
2860
|
`,"a=sctp-port:"+a.port+`\r
|
|
2861
2861
|
`]:f=["m="+s.kind+" 9 "+s.protocol+" "+a.port+`\r
|
|
@@ -2866,28 +2866,28 @@ a=ice-pwd:`+s.password+`\r
|
|
|
2866
2866
|
o=`+(f||"thisisadapterortc")+" "+_+" "+C+` IN IP4 127.0.0.1\r
|
|
2867
2867
|
s=-\r
|
|
2868
2868
|
t=0 0\r
|
|
2869
|
-
`},r.getDirection=function(s,a){const f=r.splitLines(s);for(let _=0;_<f.length;_++)switch(f[_]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return f[_].substring(2)}return a?r.getDirection(a):"sendrecv"},r.getKind=function(s){return r.splitLines(s)[0].split(" ")[0].substring(2)},r.isRejected=function(s){return s.split(" ",2)[1]==="0"},r.parseMLine=function(s){const f=r.splitLines(s)[0].substring(2).split(" ");return{kind:f[0],port:parseInt(f[1],10),protocol:f[2],fmt:f.slice(3).join(" ")}},r.parseOLine=function(s){const f=r.matchPrefix(s,"o=")[0].substring(2).split(" ");return{username:f[0],sessionId:f[1],sessionVersion:parseInt(f[2],10),netType:f[3],addressType:f[4],address:f[5]}},r.isValidSDP=function(s){if(typeof s!="string"||s.length===0)return!1;const a=r.splitLines(s);for(let f=0;f<a.length;f++)if(a[f].length<2||a[f].charAt(1)!=="=")return!1;return!0},d.exports=r})(lo)),lo.exports}var Bp=
|
|
2869
|
+
`},r.getDirection=function(s,a){const f=r.splitLines(s);for(let _=0;_<f.length;_++)switch(f[_]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return f[_].substring(2)}return a?r.getDirection(a):"sendrecv"},r.getKind=function(s){return r.splitLines(s)[0].split(" ")[0].substring(2)},r.isRejected=function(s){return s.split(" ",2)[1]==="0"},r.parseMLine=function(s){const f=r.splitLines(s)[0].substring(2).split(" ");return{kind:f[0],port:parseInt(f[1],10),protocol:f[2],fmt:f.slice(3).join(" ")}},r.parseOLine=function(s){const f=r.matchPrefix(s,"o=")[0].substring(2).split(" ");return{username:f[0],sessionId:f[1],sessionVersion:parseInt(f[2],10),netType:f[3],addressType:f[4],address:f[5]}},r.isValidSDP=function(s){if(typeof s!="string"||s.length===0)return!1;const a=r.splitLines(s);for(let f=0;f<a.length;f++)if(a[f].length<2||a[f].charAt(1)!=="=")return!1;return!0},d.exports=r})(lo)),lo.exports}var Bp=Dy(),Tr,Tt,Ui={d:(d,r)=>{for(var s in r)Ui.o(r,s)&&!Ui.o(d,s)&&Object.defineProperty(d,s,{enumerable:!0,get:r[s]})},o:(d,r)=>Object.prototype.hasOwnProperty.call(d,r)},ve={};Ui.d(ve,{Dz:()=>Zf,g$:()=>Sf,Lt:()=>_f,Q9:()=>bf,qf:()=>So,hV:()=>nm,z$:()=>kw,J0:()=>Eo,De:()=>tw,$C:()=>Us,al:()=>If,_W:()=>Mf,Gv:()=>Hf,m:()=>jf,tz:()=>Af,Nu:()=>rm,zg:()=>om,vp:()=>Jf,vU:()=>X,wF:()=>Ff,rv:()=>em,Nh:()=>tm,ss:()=>am,qW:()=>Kf,QL:()=>Wf,cf:()=>um,eM:()=>Uf,Yd:()=>T,Tk:()=>Se,iM:()=>yf,qy:()=>Qr,ce:()=>Wy,sK:()=>ge,Ok:()=>dt,q5:()=>sm,g:()=>Cw,xl:()=>Bf,I:()=>Nf,bx:()=>To,dD:()=>Xf,Ib:()=>pi,Az:()=>St,Iw:()=>Pr,qY:()=>bo,db:()=>vf,mR:()=>di,Tn:()=>_o,rV:()=>Vf,gh:()=>Of,Mi:()=>Df,j:()=>zf,YB:()=>Lf,Yt:()=>qf,i5:()=>Gf,x_:()=>Kr,Am:()=>$o,eR:()=>Tf,r8:()=>Pf,u3:()=>lm,vd:()=>$f,iV:()=>Cf,jZ:()=>xf,SW:()=>Rf,ZH:()=>kf,Ni:()=>dm,lh:()=>Ef,ZP:()=>Yf,bq:()=>wf,$f:()=>cm,eu:()=>Qf,Ax:()=>Xy,Mc:()=>Qy});class T{static GetStackTrace(){const r=new Error;let s="No Stack Available for this browser";return r.stack&&(s=r.stack.toString().replace(/Error/g,"")),s}static SetLoggerVerbosity(r){this.verboseLogLevel!=null&&(this.verboseLogLevel=r)}static Log(r,s,a){if(a>this.verboseLogLevel)return;const f=`Level: Log
|
|
2870
2870
|
Msg: ${s}
|
|
2871
2871
|
Caller: ${r}`;console.log(f)}static Info(r,s,a){if(a>this.verboseLogLevel)return;const f=`Level: Info
|
|
2872
2872
|
Msg: ${s}`;console.info(f)}static Error(r,s){const a=`Level: Error
|
|
2873
2873
|
Msg: ${s}
|
|
2874
2874
|
Caller: ${r}`;console.error(a)}static Warning(r,s){const a=`Level: Warning
|
|
2875
2875
|
Caller: ${r}
|
|
2876
|
-
Msg: ${s}`;console.warn(a)}}T.verboseLogLevel=5,(function(d){d.LIST_STREAMERS="listStreamers",d.SUBSCRIBE="subscribe",d.UNSUBSCRIBE="unsubscribe",d.ICE_CANDIDATE="iceCandidate",d.OFFER="offer",d.ANSWER="answer",d.DATACHANNELREQUEST="dataChannelRequest",d.SFURECVDATACHANNELREADY="peerDataChannelsReady",d.PONG="pong"})(
|
|
2877
|
-
`+JSON.stringify(this,this.sendFilter,4),6),JSON.stringify(this,this.sendFilter)}}class
|
|
2878
|
-
`+JSON.stringify(this,void 0,4),6),JSON.stringify(this)}}(function(d){d.CONFIG="config",d.STREAMER_LIST="streamerList",d.STREAMER_ID_CHANGED="streamerIDChanged",d.PLAYER_COUNT="playerCount",d.OFFER="offer",d.ANSWER="answer",d.ICE_CANDIDATE="iceCandidate",d.PEER_DATA_CHANNELS="peerDataChannels",d.PING="ping",d.WARNING="warning"})(Tt||(Tt={}));class yf{}class
|
|
2879
|
-
`+JSON.stringify(JSON.parse(r.data),void 0,4),6),this.signallingProtocol.handleMessage(s.type,r.data)}handleOnOpen(r){T.Log(T.GetStackTrace(),"Connected to the signalling server via WebSocket",6),this.onOpen.dispatchEvent(new Event("open"))}handleOnError(){T.Error(T.GetStackTrace(),"WebSocket error")}handleOnClose(r){T.Log(T.GetStackTrace(),"Disconnected to the signalling server via WebSocket: "+JSON.stringify(r.code)+" - "+r.reason),this.onClose.dispatchEvent(new CustomEvent("close",{detail:r}))}requestStreamerList(){const r=new Dy;this.webSocket.send(r.payload())}sendSubscribe(r){const s=new zy(r);this.webSocket.send(s.payload())}sendUnsubscribe(){const r=new Ly;this.webSocket.send(r.payload())}sendWebRtcOffer(r,s){const a=new Ny(r,s);this.webSocket.send(a.payload())}sendWebRtcAnswer(r,s){const a=new Uy(r,s);this.webSocket.send(a.payload())}sendWebRtcDatachannelRequest(){const r=new Fy;this.webSocket.send(r.payload())}sendSFURecvDataChannelReady(){const r=new Vy;this.webSocket.send(r.payload())}sendIceCandidate(r){if(T.Log(T.GetStackTrace(),"Sending Ice Candidate"),this.webSocket&&this.webSocket.readyState===this.WS_OPEN_STATE){const s=new Gy(r);this.webSocket.send(s.payload())}}close(){var r;(r=this.webSocket)===null||r===void 0||r.close()}onConfig(r){}onStreamerList(r){}onStreamerIDChanged(r){}onIceCandidate(r){}onWebRtcAnswer(r){}onWebRtcOffer(r){}onWebRtcPeerDataChannels(r){}onPlayerCount(r){}}class Wy{constructor(r){this.videoElementProvider=r,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(r){if(T.Log(T.GetStackTrace(),"handleOnTrack "+JSON.stringify(r.streams),6),r.track.id=="probator")return;const s=this.videoElementProvider.getVideoElement();if(r.track&&T.Log(T.GetStackTrace(),"Got track - "+r.track.kind+" id="+r.track.id+" readyState="+r.track.readyState,6),r.track.kind!="audio")return r.track.kind=="video"&&s.srcObject!==r.streams[0]?(s.srcObject=r.streams[0],void T.Log(T.GetStackTrace(),"Set video source from video track ontrack.")):void 0;this.CreateAudioTrack(r.streams[0])}CreateAudioTrack(r){const s=this.videoElementProvider.getVideoElement();s.srcObject!=r&&s.srcObject&&s.srcObject!==r&&(this.audioElement.srcObject=r,T.Log(T.GetStackTrace(),"Created new audio element to play separate audio stream."))}}class Hy{constructor(r){this.freezeFrameHeight=0,this.freezeFrameWidth=0,this.rootDiv=r,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(r){const s=btoa(r.reduce(((a,f)=>a+String.fromCharCode(f)),""));this.imageElement.src="data:image/jpeg;base64,"+s}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(this.freezeFrameWidth!==0&&this.freezeFrameHeight!==0){let r=0,s=0,a=0,f=0;const _=this.rootDiv.clientWidth/this.rootDiv.clientHeight,C=this.freezeFrameWidth/this.freezeFrameHeight;_<C?(r=this.rootDiv.clientWidth,s=Math.floor(this.rootDiv.clientWidth/C),a=Math.floor(.5*(this.rootDiv.clientHeight-s)),f=0):(r=Math.floor(this.rootDiv.clientHeight*C),s=this.rootDiv.clientHeight,a=0,f=Math.floor(.5*(this.rootDiv.clientWidth-r))),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=r+"px",this.imageElement.style.height=s+"px",this.imageElement.style.left=f+"px",this.imageElement.style.top=a+"px"}}}class Ky{constructor(r){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Hy(r)}showFreezeFrame(){this.valid&&this.freezeFrame.setElementForShow()}hideFreezeFrame(){this.valid=!1,this.freezeFrame.setElementForHide()}updateFreezeFrameAndShow(r,s){this.freezeFrame.updateImageElementSource(r),this.freezeFrame.imageElement.onload=()=>{this.freezeFrame.setDimensionsFromElementAndResize(),s()}}processFreezeFrameMessage(r,s){this.receiving||(this.receiving=!0,this.valid=!1,this.size=0,this.jpeg=void 0),this.size=new DataView(r.slice(1,5).buffer).getInt32(0,!0);const a=r.slice(5);if(this.jpeg){const f=new Uint8Array(this.jpeg.length+a.length);f.set(this.jpeg,0),f.set(a,this.jpeg.length),this.jpeg=f}else this.jpeg=a,this.receiving=!0,T.Log(T.GetStackTrace(),`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`,6);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,T.Log(T.GetStackTrace(),`received complete freeze frame ${this.size}`,6),this.updateFreezeFrameAndShow(this.jpeg,s)):this.jpeg.length>this.size&&(T.Error(T.GetStackTrace(),`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class hi{constructor(r,s,a,f,_=(()=>{})){this.onChange=_,this.onChangeEmit=()=>{},this.id=r,this.description=a,this.label=s,this.value=f}set label(r){this._label=r,this.onChangeEmit(this._value)}get label(){return this._label}get value(){return this._value}set value(r){this._value=r,this.onChange(this._value,this),this.onChangeEmit(this._value)}}class St extends hi{constructor(r,s,a,f,_,C=(()=>{})){super(r,s,a,f,C);const R=new URLSearchParams(window.location.search);if(_&&R.has(this.id)){const b=this.getUrlParamFlag();this.flag=b}else this.flag=f;this.useUrlParams=_}getUrlParamFlag(){const r=new URLSearchParams(window.location.search);return!!r.has(this.id)&&r.get(this.id)!=="false"&&r.get(this.id)!=="False"}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);this.flag===!0?r.set(this.id,"true"):r.set(this.id,"false"),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}enable(){this.flag=!0}get flag(){return!!this.value}set flag(r){this.value=r}}class Mr extends hi{constructor(r,s,a,f,_,C,R,b=(()=>{})){super(r,s,a,C,b),this._min=f,this._max=_;const U=new URLSearchParams(window.location.search);if(R&&U.has(this.id)){const z=Number.parseFloat(U.get(this.id));this.number=Number.isNaN(z)?C:z}else this.number=C;this.useUrlParams=R}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.number.toString()),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}set number(r){this.value=this.clamp(r)}get number(){return this.value}clamp(r){return this._min==null&&this._max==null?r:this._min==null?Math.min(this._max,r):this._max==null?Math.max(this._min,r):Math.max(Math.min(this._max,r),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(r){this.onChange=r}}class vf extends hi{constructor(r,s,a,f,_,C=(()=>{})){super(r,s,a,f,C);const R=new URLSearchParams(window.location.search);if(_&&R.has(this.id)){const b=this.getUrlParamText();this.text=b}else this.text=f;this.useUrlParams=_}getUrlParamText(){var r;const s=new URLSearchParams(window.location.search);return s.has(this.id)&&(r=s.get(this.id))!==null&&r!==void 0?r:""}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.text),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}get text(){return this.value}set text(r){this.value=r}}class bo extends hi{constructor(r,s,a,f,_,C,R=(()=>{})){super(r,s,a,f,R),this.options=_;const b=new URLSearchParams(window.location.search),U=C&&b.has(this.id)?this.getUrlParamText():f;this.selected=U,this.useUrlParams=C}getUrlParamText(){var r;const s=new URLSearchParams(window.location.search);return s.has(this.id)&&(r=s.get(this.id))!==null&&r!==void 0?r:""}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.selected),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}addOnChangedListener(r){this.onChange=r}get options(){return this._options}set options(r){this._options=r,this.onChangeEmit(this.selected)}get selected(){return this.value}set selected(r){let s=this.options.filter((a=>a.indexOf(r)!==-1));s.length?this.value=s[0]:(s=this.options.filter((a=>a.indexOf(r.split(" ")[0])!==-1)),s.length&&(this.value=s[0]))}}class _f extends Event{constructor(r){super("afkWarningActivate"),this.data=r}}class So extends Event{constructor(r){super("afkWarningUpdate"),this.data=r}}class bf extends Event{constructor(){super("afkWarningDeactivate")}}class Sf extends Event{constructor(){super("afkTimedOut")}}class Tf extends Event{constructor(r){super("videoEncoderAvgQP"),this.data=r}}class Ef extends Event{constructor(){super("webRtcSdp")}}class $f extends Event{constructor(){super("webRtcAutoConnect")}}class xf extends Event{constructor(){super("webRtcConnecting")}}class Cf extends Event{constructor(){super("webRtcConnected")}}class kf extends Event{constructor(){super("webRtcFailed")}}class Rf extends Event{constructor(r){super("webRtcDisconnected"),this.data=r}}class Af extends Event{constructor(r){super("dataChannelOpen"),this.data=r}}class If extends Event{constructor(r){super("dataChannelClose"),this.data=r}}class Mf extends Event{constructor(r){super("dataChannelError"),this.data=r}}class Pf extends Event{constructor(){super("videoInitialized")}}class Of extends Event{constructor(){super("streamLoading")}}class Df extends Event{constructor(){super("streamConnect")}}class zf extends Event{constructor(){super("streamDisconnect")}}class Lf extends Event{constructor(){super("streamReconnect")}}class Bf extends Event{constructor(r){super("playStreamError"),this.data=r}}class Nf extends Event{constructor(){super("playStream")}}class To extends Event{constructor(r){super("playStreamRejected"),this.data=r}}class Uf extends Event{constructor(r){super("loadFreezeFrame"),this.data=r}}class Ff extends Event{constructor(){super("hideFreezeFrame")}}class Vf extends Event{constructor(r){super("statsReceived"),this.data=r}}class Gf extends Event{constructor(r){super("streamerListMessage"),this.data=r}}class qf extends Event{constructor(r){super("StreamerIDChangedMessage"),this.data=r}}class Wf extends Event{constructor(r){super("latencyTestResult"),this.data=r}}class Hf extends Event{constructor(r){super("dataChannelLatencyTestResponse"),this.data=r}}class Kf extends Event{constructor(r){super("dataChannelLatencyTestResult"),this.data=r}}class jf extends Event{constructor(r){super("initialSettings"),this.data=r}}class ui extends Event{constructor(r){super("settingsChanged"),this.data=r}}class jy extends Event{constructor(){super("xrSessionStarted")}}class Qy extends Event{constructor(){super("xrSessionEnded")}}class Qf extends Event{constructor(r){super("xrFrame"),this.data=r}}class Xf extends Event{constructor(r){super("playerCount"),this.data=r}}class Yf extends Event{constructor(){super("webRtcTCPRelayDetected")}}class Jf extends EventTarget{dispatchEvent(r){return super.dispatchEvent(r)}addEventListener(r,s){super.addEventListener(r,s)}removeEventListener(r,s){super.removeEventListener(r,s)}}class X{}X.AutoConnect="AutoConnect",X.AutoPlayVideo="AutoPlayVideo",X.AFKDetection="TimeoutIfIdle",X.BrowserSendOffer="OfferToReceive",X.HoveringMouseMode="HoveringMouse",X.ForceMonoAudio="ForceMonoAudio",X.ForceTURN="ForceTURN",X.FakeMouseWithTouches="FakeMouseWithTouches",X.IsQualityController="ControlsQuality",X.MatchViewportResolution="MatchViewportRes",X.StartVideoMuted="StartVideoMuted",X.SuppressBrowserKeys="SuppressBrowserKeys",X.UseMic="UseMic",X.KeyboardInput="KeyboardInput",X.MouseInput="MouseInput",X.TouchInput="TouchInput",X.GamepadInput="GamepadInput",X.XRControllerInput="XRControllerInput",X.WaitForStreamer="WaitForStreamer",X.HideUI="HideUI";const Xy=d=>Object.getOwnPropertyNames(X).some((r=>X[r]===d));class me{}me.AFKTimeoutSecs="AFKTimeout",me.AFKCountdownSecs="AFKCountdown",me.MinQP="MinQP",me.MaxQP="MaxQP",me.WebRTCFPS="WebRTCFPS",me.WebRTCMinBitrate="WebRTCMinBitrate",me.WebRTCMaxBitrate="WebRTCMaxBitrate",me.MaxReconnectAttempts="MaxReconnectAttempts",me.StreamerAutoJoinInterval="StreamerAutoJoinInterval";const Yy=d=>Object.getOwnPropertyNames(me).some((r=>me[r]===d));class qr{}qr.SignallingServerUrl="ss";const Jy=d=>Object.getOwnPropertyNames(qr).some((r=>qr[r]===d));class dt{}dt.PreferredCodec="PreferredCodec",dt.StreamerId="StreamerId";const Zy=d=>Object.getOwnPropertyNames(dt).some((r=>dt[r]===d));class ew{constructor(r={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:s,useUrlParams:a}=r;this._useUrlParams=!!a,this.populateDefaultSettings(this._useUrlParams,s)}get useUrlParams(){return this._useUrlParams}populateDefaultSettings(r,s){this.textParameters.set(qr.SignallingServerUrl,new vf(qr.SignallingServerUrl,"Signalling url","Url of the signalling server",s&&s.hasOwnProperty(qr.SignallingServerUrl)?s[qr.SignallingServerUrl]:(location.protocol==="https:"?"wss://":"ws://")+window.location.hostname+(window.location.port==="80"||window.location.port===""?"":`:${window.location.port}`),r)),this.optionParameters.set(dt.StreamerId,new bo(dt.StreamerId,"Streamer ID","The ID of the streamer to stream.",s&&s.hasOwnProperty(dt.StreamerId)?s[dt.StreamerId]:"",[],r)),this.optionParameters.set(dt.PreferredCodec,new bo(dt.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation","H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",s&&s.hasOwnProperty(dt.PreferredCodec)?[s[dt.PreferredCodec]]:(function(){const a=[];if(!RTCRtpReceiver.getCapabilities)return a.push("Only available on Chrome"),a;const f=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((_=>{const C=_.mimeType.split("/")[1]+" "+(_.sdpFmtpLine||"");f.exec(C)!==null&&a.push(C)})),a})(),r)),this.flags.set(X.AutoConnect,new St(X.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",!(!s||!s.hasOwnProperty(X.AutoConnect))&&s[X.AutoConnect],r)),this.flags.set(X.AutoPlayVideo,new St(X.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!s||!s.hasOwnProperty(X.AutoPlayVideo)||s[X.AutoPlayVideo],r)),this.flags.set(X.BrowserSendOffer,new St(X.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!s||!s.hasOwnProperty(X.BrowserSendOffer))&&s[X.BrowserSendOffer],r)),this.flags.set(X.UseMic,new St(X.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!s||!s.hasOwnProperty(X.UseMic))&&s[X.UseMic],r)),this.flags.set(X.StartVideoMuted,new St(X.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!s||!s.hasOwnProperty(X.StartVideoMuted))&&s[X.StartVideoMuted],r)),this.flags.set(X.SuppressBrowserKeys,new St(X.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.",!s||!s.hasOwnProperty(X.SuppressBrowserKeys)||s[X.SuppressBrowserKeys],r)),this.flags.set(X.IsQualityController,new St(X.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!s||!s.hasOwnProperty(X.IsQualityController)||s[X.IsQualityController],r)),this.flags.set(X.ForceMonoAudio,new St(X.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!s||!s.hasOwnProperty(X.ForceMonoAudio))&&s[X.ForceMonoAudio],r)),this.flags.set(X.ForceTURN,new St(X.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!s||!s.hasOwnProperty(X.ForceTURN))&&s[X.ForceTURN],r)),this.flags.set(X.AFKDetection,new St(X.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!s||!s.hasOwnProperty(X.AFKDetection))&&s[X.AFKDetection],r)),this.flags.set(X.MatchViewportResolution,new St(X.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",!(!s||!s.hasOwnProperty(X.MatchViewportResolution))&&s[X.MatchViewportResolution],r)),this.flags.set(X.HoveringMouseMode,new St(X.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.",!(!s||!s.hasOwnProperty(X.HoveringMouseMode))&&s[X.HoveringMouseMode],r,((a,f)=>{f.label=`Control Scheme: ${a?"Hovering":"Locked"} Mouse`}))),this.flags.set(X.FakeMouseWithTouches,new St(X.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.",!(!s||!s.hasOwnProperty(X.FakeMouseWithTouches))&&s[X.FakeMouseWithTouches],r)),this.flags.set(X.KeyboardInput,new St(X.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!s||!s.hasOwnProperty(X.KeyboardInput)||s[X.KeyboardInput],r)),this.flags.set(X.MouseInput,new St(X.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!s||!s.hasOwnProperty(X.MouseInput)||s[X.MouseInput],r)),this.flags.set(X.TouchInput,new St(X.TouchInput,"Touch input","If enabled, send touch events to streamer",!s||!s.hasOwnProperty(X.TouchInput)||s[X.TouchInput],r)),this.flags.set(X.GamepadInput,new St(X.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!s||!s.hasOwnProperty(X.GamepadInput)||s[X.GamepadInput],r)),this.flags.set(X.XRControllerInput,new St(X.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!s||!s.hasOwnProperty(X.XRControllerInput)||s[X.XRControllerInput],r)),this.flags.set(X.WaitForStreamer,new St(X.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!s||!s.hasOwnProperty(X.WaitForStreamer)||s[X.WaitForStreamer],r)),this.flags.set(X.HideUI,new St(X.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!s||!s.hasOwnProperty(X.HideUI))&&s[X.HideUI],r)),this.numericParameters.set(me.AFKTimeoutSecs,new Mr(me.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,s&&s.hasOwnProperty(me.AFKTimeoutSecs)?s[me.AFKTimeoutSecs]:120,r)),this.numericParameters.set(me.AFKCountdownSecs,new Mr(me.AFKCountdownSecs,"AFK countdown","The time (in seconds) for a user to respond before the stream is ended after an AFK timeout.",10,null,10,r)),this.numericParameters.set(me.MaxReconnectAttempts,new Mr(me.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,s&&s.hasOwnProperty(me.MaxReconnectAttempts)?s[me.MaxReconnectAttempts]:3,r)),this.numericParameters.set(me.MinQP,new Mr(me.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,s&&s.hasOwnProperty(me.MinQP)?s[me.MinQP]:0,r)),this.numericParameters.set(me.MaxQP,new Mr(me.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,s&&s.hasOwnProperty(me.MaxQP)?s[me.MaxQP]:51,r)),this.numericParameters.set(me.WebRTCFPS,new Mr(me.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,s&&s.hasOwnProperty(me.WebRTCFPS)?s[me.WebRTCFPS]:60,r)),this.numericParameters.set(me.WebRTCMinBitrate,new Mr(me.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,s&&s.hasOwnProperty(me.WebRTCMinBitrate)?s[me.WebRTCMinBitrate]:0,r)),this.numericParameters.set(me.WebRTCMaxBitrate,new Mr(me.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,s&&s.hasOwnProperty(me.WebRTCMaxBitrate)?s[me.WebRTCMaxBitrate]:0,r)),this.numericParameters.set(me.StreamerAutoJoinInterval,new Mr(me.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,s&&s.hasOwnProperty(me.StreamerAutoJoinInterval)?s[me.StreamerAutoJoinInterval]:3e3,r))}_addOnNumericSettingChangedListener(r,s){this.numericParameters.has(r)&&this.numericParameters.get(r).addOnChangedListener(s)}_addOnOptionSettingChangedListener(r,s){this.optionParameters.has(r)&&this.optionParameters.get(r).addOnChangedListener(s)}getNumericSettingValue(r){if(this.numericParameters.has(r))return this.numericParameters.get(r).number;throw new Error(`There is no numeric setting with the id of ${r}`)}getTextSettingValue(r){if(this.textParameters.has(r))return this.textParameters.get(r).value;throw new Error(`There is no numeric setting with the id of ${r}`)}setNumericSetting(r,s){if(!this.numericParameters.has(r))throw new Error(`There is no numeric setting with the id of ${r}`);this.numericParameters.get(r).number=s}_addOnSettingChangedListener(r,s){this.flags.has(r)&&(this.flags.get(r).onChange=s)}_addOnTextSettingChangedListener(r,s){this.textParameters.has(r)&&(this.textParameters.get(r).onChange=s)}getSettingOption(r){return this.optionParameters.get(r)}isFlagEnabled(r){return this.flags.get(r).flag}setFlagEnabled(r,s){this.flags.has(r)?this.flags.get(r).flag=s:T.Warning(T.GetStackTrace(),`Cannot toggle flag called ${r} - it does not exist in the Config.flags map.`)}setTextSetting(r,s){this.textParameters.has(r)?this.textParameters.get(r).text=s:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.textParameters map.`)}setOptionSettingOptions(r,s){this.optionParameters.has(r)?this.optionParameters.get(r).options=s:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(r,s){if(this.optionParameters.has(r)){const a=this.optionParameters.get(r),f=a.options;f.includes(s)||(f.push(s),a.options=f),a.selected=s}else T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.enumParameters map.`)}setFlagLabel(r,s){this.flags.has(r)?this.flags.get(r).label=s:T.Warning(T.GetStackTrace(),`Cannot set label for flag called ${r} - it does not exist in the Config.flags map.`)}setSettings(r){for(const s of Object.keys(r))Xy(s)?this.setFlagEnabled(s,r[s]):Yy(s)?this.setNumericSetting(s,r[s]):Jy(s)?this.setTextSetting(s,r[s]):Zy(s)&&this.setOptionSettingValue(s,r[s])}getSettings(){const r={};for(const[s,a]of this.flags.entries())r[s]=a.flag;for(const[s,a]of this.numericParameters.entries())r[s]=a.number;for(const[s,a]of this.textParameters.entries())r[s]=a.text;for(const[s,a]of this.optionParameters.entries())r[s]=a.selected;return r}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(r){for(const s of this.flags.keys()){const a=this.flags.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"flag",value:f,target:a})))}for(const s of this.numericParameters.keys()){const a=this.numericParameters.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"number",value:f,target:a})))}for(const s of this.textParameters.keys()){const a=this.textParameters.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"text",value:f,target:a})))}for(const s of this.optionParameters.keys()){const a=this.optionParameters.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"option",value:f,target:a})))}}}var Ns;(function(d){d[d.LockedMouse=0]="LockedMouse",d[d.HoveringMouse=1]="HoveringMouse"})(Ns||(Ns={}));class Zf{constructor(r,s,a){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=r,this.pixelStreaming=s,this.onDismissAfk=a,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 bf))}startAfkWarningTimer(){this.config.getNumericSettingValue(me.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(X.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(X.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(me.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new _f({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(me.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new So({countDown:this.countDown})),this.config.isFlagEnabled(X.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new Sf),this.onAFKTimedOutCallback(),T.Log(T.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new So({countDown:this.countDown}))}),1e3)}}class Np{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(r,s,a){this.peerConnection=r,this.label=s,this.datachannelOptions=a,a==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=r=>this.handleOnOpen(r),this.dataChannel.onclose=r=>this.handleOnClose(r),this.dataChannel.onmessage=r=>this.handleOnMessage(r),this.dataChannel.onerror=r=>this.handleOnError(r)}handleOnOpen(r){var s;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) opened.`,7),this.onOpen((s=this.dataChannel)===null||s===void 0?void 0:s.label,r)}handleOnClose(r){var s;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) closed.`,7),this.onClose((s=this.dataChannel)===null||s===void 0?void 0:s.label,r)}handleOnMessage(r){T.Log(T.GetStackTrace(),`Data Channel (${this.label}) message: ${r}`,8)}handleOnError(r){var s;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) error: ${r}`,7),this.onError((s=this.dataChannel)===null||s===void 0?void 0:s.label,r)}onOpen(r,s){}onClose(r,s){}onError(r,s){}}class em{}class tm{}class rm{}class Eo{}class sm{}class tw{}class rw{}class nm{constructor(){this.inboundVideoStats=new tm,this.inboundAudioStats=new em,this.DataChannelStats=new rm,this.outBoundVideoStats=new sm,this.sessionStats=new tw,this.streamStats=new rw,this.codecs=new Map}processStats(r){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,r.forEach((s=>{switch(s.type){case"candidate-pair":this.handleCandidatePair(s);break;case"certificate":case"media-source":case"media-playout":case"outbound-rtp":case"peer-connection":case"remote-inbound-rtp":break;case"codec":this.handleCodec(s);break;case"data-channel":this.handleDataChannel(s);break;case"inbound-rtp":this.handleInBoundRTP(s);break;case"local-candidate":this.handleLocalCandidate(s);break;case"remote-candidate":this.handleRemoteCandidate(s);break;case"remote-outbound-rtp":this.handleRemoteOutBound(s);break;case"track":this.handleTrack(s);break;case"transport":this.handleTransport(s);break;case"stream":this.handleStream(s);break;default:T.Error(T.GetStackTrace(),"unhandled Stat Type"),T.Log(T.GetStackTrace(),s)}}))}handleStream(r){this.streamStats=r}handleCandidatePair(r){this.candidatePairs.push(r)}handleDataChannel(r){this.DataChannelStats.bytesReceived=r.bytesReceived,this.DataChannelStats.bytesSent=r.bytesSent,this.DataChannelStats.dataChannelIdentifier=r.dataChannelIdentifier,this.DataChannelStats.id=r.id,this.DataChannelStats.label=r.label,this.DataChannelStats.messagesReceived=r.messagesReceived,this.DataChannelStats.messagesSent=r.messagesSent,this.DataChannelStats.protocol=r.protocol,this.DataChannelStats.state=r.state,this.DataChannelStats.timestamp=r.timestamp}handleLocalCandidate(r){const s=new Eo;s.label="local-candidate",s.address=r.address,s.port=r.port,s.protocol=r.protocol,s.candidateType=r.candidateType,s.id=r.id,s.relayProtocol=r.relayProtocol,s.transportId=r.transportId,this.localCandidates.push(s)}handleRemoteCandidate(r){const s=new Eo;s.label="remote-candidate",s.address=r.address,s.port=r.port,s.protocol=r.protocol,s.id=r.id,s.candidateType=r.candidateType,s.relayProtocol=r.relayProtocol,s.transportId=r.transportId,this.remoteCandidates.push(s)}handleInBoundRTP(r){switch(r.kind){case"video":this.inboundVideoStats=r,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=r,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:T.Log(T.GetStackTrace(),"Kind is not handled")}}handleRemoteOutBound(r){r.kind==="video"&&(this.outBoundVideoStats.bytesSent=r.bytesSent,this.outBoundVideoStats.id=r.id,this.outBoundVideoStats.localId=r.localId,this.outBoundVideoStats.packetsSent=r.packetsSent,this.outBoundVideoStats.remoteTimestamp=r.remoteTimestamp,this.outBoundVideoStats.timestamp=r.timestamp)}handleTrack(r){r.type!=="track"||r.trackIdentifier!=="video_label"&&r.kind!=="video"||(this.inboundVideoStats.framesDropped=r.framesDropped,this.inboundVideoStats.framesReceived=r.framesReceived,this.inboundVideoStats.frameHeight=r.frameHeight,this.inboundVideoStats.frameWidth=r.frameWidth)}handleTransport(r){this.transportStats=r}handleCodec(r){const s=r.id,a=`${r.mimeType.replace("video/","").replace("audio/","")}${r.sdpFmtpLine?` ${r.sdpFmtpLine}`:""}`;this.codecs.set(s,a)}handleSessionStatistics(r,s,a){const f=Date.now()-r;this.sessionStats.runTime=new Date(f).toISOString().substr(11,8).toString();const _=s===null?"Not sent yet":s?"true":"false";this.sessionStats.controlsStreamInput=_,this.sessionStats.videoEncoderAvgQP=a}isNumber(r){return typeof r=="number"&&isFinite(r)}getActiveCandidatePair(){return this.transportStats?this.candidatePairs.find((r=>r.id===this.transportStats.selectedCandidatePairId),null):this.candidatePairs.find((r=>r.selected),null)}}const Up=(Fp={parseRtpParameters:()=>Bp.parseRtpParameters,splitSections:()=>Bp.splitSections},uo={},Ui.d(uo,Fp),uo);var Fp,uo;class im{static isVideoTransciever(r){return this.canTransceiverReceiveVideo(r)||this.canTransceiverSendVideo(r)}static canTransceiverReceiveVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="video"}static canTransceiverSendVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="video"}static isAudioTransciever(r){return this.canTransceiverReceiveAudio(r)||this.canTransceiverSendAudio(r)}static canTransceiverReceiveAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="audio"}static canTransceiverSendAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="audio"}}var ln,be,co=function(d,r,s,a){return new(s||(s=Promise))((function(f,_){function C(U){try{b(a.next(U))}catch(z){_(z)}}function R(U){try{b(a.throw(U))}catch(z){_(z)}}function b(U){var z;U.done?f(U.value):(z=U.value,z instanceof s?z:new s((function(re){re(z)}))).then(C,R)}b((a=a.apply(d,[])).next())}))};class sw{constructor(r,s,a){this.config=s,this.createPeerConnection(r,a)}createPeerConnection(r,s){this.config.isFlagEnabled(X.ForceTURN)&&(r.iceTransportPolicy="relay",T.Log(T.GetStackTrace(),"Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(r),this.peerConnection.onsignalingstatechange=a=>this.handleSignalStateChange(a),this.peerConnection.oniceconnectionstatechange=a=>this.handleIceConnectionStateChange(a),this.peerConnection.onicegatheringstatechange=a=>this.handleIceGatheringStateChange(a),this.peerConnection.ontrack=a=>this.handleOnTrack(a),this.peerConnection.onicecandidate=a=>this.handleIceCandidate(a),this.peerConnection.ondatachannel=a=>this.handleDataChannel(a),this.aggregatedStats=new nm,this.preferredCodec=s,this.updateCodecSelection=!0}createOffer(r,s){return co(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Create Offer",6);const a=location.hostname==="localhost"||location.hostname==="127.0.0.1",f=location.protocol==="https:";let _=s.isFlagEnabled(X.UseMic);!_||a||f||(_=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(_).finally((()=>{var C;(C=this.peerConnection)===null||C===void 0||C.createOffer(r).then((R=>{var b;this.showTextOverlayConnecting(),R.sdp=this.mungeSDP(R.sdp,_),(b=this.peerConnection)===null||b===void 0||b.setLocalDescription(R),this.onSendWebRTCOffer(R)})).catch((()=>{this.showTextOverlaySetupFailure()}))}))}))}receiveOffer(r,s){var a;return co(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Receive Offer",6),(a=this.peerConnection)===null||a===void 0||a.setRemoteDescription(r).then((()=>{const f=location.hostname==="localhost"||location.hostname==="127.0.0.1",_=location.protocol==="https:";let C=s.isFlagEnabled(X.UseMic);!C||f||_||(C=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.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(dt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r)),this.setupTransceiversAsync(C).finally((()=>{var R;(R=this.peerConnection)===null||R===void 0||R.createAnswer().then((b=>{var U;return b.sdp=this.mungeSDP(b.sdp,C),(U=this.peerConnection)===null||U===void 0?void 0:U.setLocalDescription(b)})).then((()=>{var b;this.onSendWebRTCAnswer((b=this.peerConnection)===null||b===void 0?void 0:b.currentLocalDescription)})).catch((()=>{T.Error(T.GetStackTrace(),"createAnswer() failed")}))}))}))}))}receiveAnswer(r){var s;(s=this.peerConnection)===null||s===void 0||s.setRemoteDescription(r),this.config.setOptionSettingOptions(dt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r))}generateStats(){var r;(r=this.peerConnection)===null||r===void 0||r.getStats(null).then((s=>{this.aggregatedStats.processStats(s),this.onVideoStats(this.aggregatedStats),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId&&this.config.setOptionSettingValue(dt.PreferredCodec,this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId))}))}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(r,s){let a=r.replace(/(a=fmtp:\d+ .*level-asymmetry-allowed=.*)\r\n/gm,`$1;x-google-start-bitrate=10000;x-google-max-bitrate=100000\r
|
|
2880
|
-
`),f="maxaveragebitrate=510000;";return s&&(f+="sprop-maxcapturerate=48000;"),f+=this.config.isFlagEnabled(X.ForceMonoAudio)?"stereo=0;":"stereo=1;",f+="useinbandfec=1",a=a.replace("useinbandfec=1",f),a}handleOnIce(r){var s;T.Log(T.GetStackTrace(),"peerconnection handleOnIce",6),this.config.isFlagEnabled(X.ForceTURN)&&r.candidate.indexOf("relay")<0?T.Info(T.GetStackTrace(),`Dropping candidate because it was not TURN relay. | Type= ${r.type} | Protocol= ${r.protocol} | Address=${r.address} | Port=${r.port} |`,6):(s=this.peerConnection)===null||s===void 0||s.addIceCandidate(r)}handleSignalStateChange(r){T.Log(T.GetStackTrace(),"signaling state change: "+r,6)}handleIceConnectionStateChange(r){T.Log(T.GetStackTrace(),"ice connection state change: "+r,6),this.onIceConnectionStateChange(r)}handleIceGatheringStateChange(r){T.Log(T.GetStackTrace(),"ice gathering state change: "+JSON.stringify(r),6)}handleOnTrack(r){this.onTrack(r)}handleIceCandidate(r){this.onPeerIceCandidate(r)}handleDataChannel(r){this.onDataChannel(r)}onTrack(r){}onIceConnectionStateChange(r){}onPeerIceCandidate(r){}onDataChannel(r){}fuzzyIntersectUEAndBrowserCodecs(r){const s=new Array,a=this.parseAvailableCodecs(r),f=this.config.getSettingOption(dt.PreferredCodec).options;for(const _ of a)if(f.includes(_))s.push(_);else{const C=_.split(" ")[0];for(const R of f)if(R.includes(C)){s.push(R);break}}return s}setupTransceiversAsync(r){var s,a,f,_,C,R,
|
|
2876
|
+
Msg: ${s}`;console.warn(a)}}T.verboseLogLevel=5,(function(d){d.LIST_STREAMERS="listStreamers",d.SUBSCRIBE="subscribe",d.UNSUBSCRIBE="unsubscribe",d.ICE_CANDIDATE="iceCandidate",d.OFFER="offer",d.ANSWER="answer",d.DATACHANNELREQUEST="dataChannelRequest",d.SFURECVDATACHANNELREADY="peerDataChannelsReady",d.PONG="pong"})(Tr||(Tr={}));class Qr{sendFilter(r,s){return s}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2877
|
+
`+JSON.stringify(this,this.sendFilter,4),6),JSON.stringify(this,this.sendFilter)}}class zy extends Qr{constructor(){super(),this.type=Tr.LIST_STREAMERS}}class Ly extends Qr{constructor(r){super(),this.type=Tr.SUBSCRIBE,this.streamerId=r}}class By extends Qr{constructor(){super(),this.type=Tr.UNSUBSCRIBE}}class Ny extends Qr{constructor(r){super(),this.type=Tr.PONG,this.time=r}}class Uy extends Qr{constructor(r,s){super(),this.type=Tr.OFFER,this.minBitrate=0,this.maxBitrate=0,r&&(this.type=r.type,this.sdp=r.sdp,this.minBitrate=s.minBitrateBps,this.maxBitrate=s.maxBitrateBps)}sendFilter(r,s){if(r!="minBitrate"&&r!="maxBitrate"||!(s<=0))return s}}class Fy extends Qr{constructor(r,s){super(),this.type=Tr.ANSWER,this.minBitrate=0,this.maxBitrate=0,r&&(this.type=r.type,this.sdp=r.sdp,this.minBitrate=s.minBitrateBps,this.maxBitrate=s.maxBitrateBps)}sendFilter(r,s){if(r!="minBitrate"&&r!="maxBitrate"||!(s<=0))return s}}class Vy extends Qr{constructor(){super(),this.type=Tr.DATACHANNELREQUEST}}class Gy extends Qr{constructor(){super(),this.type=Tr.SFURECVDATACHANNELREADY}}class qy{constructor(r){this.type=Tr.ICE_CANDIDATE,this.candidate=r}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2878
|
+
`+JSON.stringify(this,void 0,4),6),JSON.stringify(this)}}(function(d){d.CONFIG="config",d.STREAMER_LIST="streamerList",d.STREAMER_ID_CHANGED="streamerIDChanged",d.PLAYER_COUNT="playerCount",d.OFFER="offer",d.ANSWER="answer",d.ICE_CANDIDATE="iceCandidate",d.PEER_DATA_CHANNELS="peerDataChannels",d.PING="ping",d.WARNING="warning"})(Tt||(Tt={}));class yf{}class Wy extends yf{}class _o{constructor(){this.FromUEMessageHandlers=new Map}addMessageHandler(r,s){this.FromUEMessageHandlers.set(r,s)}handleMessage(r,s){this.FromUEMessageHandlers.has(r)?this.FromUEMessageHandlers.get(r)(s):T.Error(T.GetStackTrace(),`Message type of ${r} does not have a message handler registered on the frontend - ignoring message.`)}static setupDefaultHandlers(r){r.signallingProtocol.addMessageHandler(Tt.PING,(s=>{const a=new Ny(new Date().getTime()).payload();T.Log(T.GetStackTrace(),Tt.PING+": "+s,6),r.webSocket.send(a)})),r.signallingProtocol.addMessageHandler(Tt.CONFIG,(s=>{T.Log(T.GetStackTrace(),Tt.CONFIG,6);const a=JSON.parse(s);r.onConfig(a)})),r.signallingProtocol.addMessageHandler(Tt.STREAMER_LIST,(s=>{T.Log(T.GetStackTrace(),Tt.STREAMER_LIST,6);const a=JSON.parse(s);r.onStreamerList(a)})),r.signallingProtocol.addMessageHandler(Tt.STREAMER_ID_CHANGED,(s=>{T.Log(T.GetStackTrace(),Tt.STREAMER_ID_CHANGED,6);const a=JSON.parse(s);r.onStreamerIDChanged(a)})),r.signallingProtocol.addMessageHandler(Tt.PLAYER_COUNT,(s=>{T.Log(T.GetStackTrace(),Tt.PLAYER_COUNT,6);const a=JSON.parse(s);T.Log(T.GetStackTrace(),"Player Count: "+a.count,6),r.onPlayerCount(a)})),r.signallingProtocol.addMessageHandler(Tt.ANSWER,(s=>{T.Log(T.GetStackTrace(),Tt.ANSWER,6);const a=JSON.parse(s);r.onWebRtcAnswer(a)})),r.signallingProtocol.addMessageHandler(Tt.OFFER,(s=>{T.Log(T.GetStackTrace(),Tt.OFFER,6);const a=JSON.parse(s);r.onWebRtcOffer(a)})),r.signallingProtocol.addMessageHandler(Tt.ICE_CANDIDATE,(s=>{T.Log(T.GetStackTrace(),Tt.ICE_CANDIDATE,6);const a=JSON.parse(s);r.onIceCandidate(a.candidate)})),r.signallingProtocol.addMessageHandler(Tt.WARNING,(s=>{T.Warning(T.GetStackTrace(),`Warning received: ${s}`)})),r.signallingProtocol.addMessageHandler(Tt.PEER_DATA_CHANNELS,(s=>{T.Log(T.GetStackTrace(),Tt.PEER_DATA_CHANNELS,6);const a=JSON.parse(s);r.onWebRtcPeerDataChannels(a)}))}}class wf{constructor(){this.WS_OPEN_STATE=1,this.onOpen=new EventTarget,this.onClose=new EventTarget,this.signallingProtocol=new _o,_o.setupDefaultHandlers(this)}connect(r){T.Log(T.GetStackTrace(),r,6);try{return this.webSocket=new WebSocket(r),this.webSocket.onopen=s=>this.handleOnOpen(s),this.webSocket.onerror=()=>this.handleOnError(),this.webSocket.onclose=s=>this.handleOnClose(s),this.webSocket.onmessage=s=>this.handleOnMessage(s),this.webSocket.onmessagebinary=s=>this.handleOnMessageBinary(s),!0}catch(s){return T.Error(s,s),!1}}handleOnMessageBinary(r){r&&r.data&&r.data.text().then((s=>{const a=new MessageEvent("messageFromBinary",{data:s});this.handleOnMessage(a)})).catch((s=>{T.Error(T.GetStackTrace(),`Failed to parse binary blob from websocket, reason: ${s}`)}))}handleOnMessage(r){if(r.data&&r.data instanceof Blob)return void this.handleOnMessageBinary(r);const s=JSON.parse(r.data);T.Log(T.GetStackTrace(),`received =>
|
|
2879
|
+
`+JSON.stringify(JSON.parse(r.data),void 0,4),6),this.signallingProtocol.handleMessage(s.type,r.data)}handleOnOpen(r){T.Log(T.GetStackTrace(),"Connected to the signalling server via WebSocket",6),this.onOpen.dispatchEvent(new Event("open"))}handleOnError(){T.Error(T.GetStackTrace(),"WebSocket error")}handleOnClose(r){T.Log(T.GetStackTrace(),"Disconnected to the signalling server via WebSocket: "+JSON.stringify(r.code)+" - "+r.reason),this.onClose.dispatchEvent(new CustomEvent("close",{detail:r}))}requestStreamerList(){const r=new zy;this.webSocket.send(r.payload())}sendSubscribe(r){const s=new Ly(r);this.webSocket.send(s.payload())}sendUnsubscribe(){const r=new By;this.webSocket.send(r.payload())}sendWebRtcOffer(r,s){const a=new Uy(r,s);this.webSocket.send(a.payload())}sendWebRtcAnswer(r,s){const a=new Fy(r,s);this.webSocket.send(a.payload())}sendWebRtcDatachannelRequest(){const r=new Vy;this.webSocket.send(r.payload())}sendSFURecvDataChannelReady(){const r=new Gy;this.webSocket.send(r.payload())}sendIceCandidate(r){if(T.Log(T.GetStackTrace(),"Sending Ice Candidate"),this.webSocket&&this.webSocket.readyState===this.WS_OPEN_STATE){const s=new qy(r);this.webSocket.send(s.payload())}}close(){var r;(r=this.webSocket)===null||r===void 0||r.close()}onConfig(r){}onStreamerList(r){}onStreamerIDChanged(r){}onIceCandidate(r){}onWebRtcAnswer(r){}onWebRtcOffer(r){}onWebRtcPeerDataChannels(r){}onPlayerCount(r){}}class Hy{constructor(r){this.videoElementProvider=r,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(r){if(T.Log(T.GetStackTrace(),"handleOnTrack "+JSON.stringify(r.streams),6),r.track.id=="probator")return;const s=this.videoElementProvider.getVideoElement();if(r.track&&T.Log(T.GetStackTrace(),"Got track - "+r.track.kind+" id="+r.track.id+" readyState="+r.track.readyState,6),r.track.kind!="audio")return r.track.kind=="video"&&s.srcObject!==r.streams[0]?(s.srcObject=r.streams[0],void T.Log(T.GetStackTrace(),"Set video source from video track ontrack.")):void 0;this.CreateAudioTrack(r.streams[0])}CreateAudioTrack(r){const s=this.videoElementProvider.getVideoElement();s.srcObject!=r&&s.srcObject&&s.srcObject!==r&&(this.audioElement.srcObject=r,T.Log(T.GetStackTrace(),"Created new audio element to play separate audio stream."))}}class jy{constructor(r){this.freezeFrameHeight=0,this.freezeFrameWidth=0,this.rootDiv=r,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(r){const s=btoa(r.reduce(((a,f)=>a+String.fromCharCode(f)),""));this.imageElement.src="data:image/jpeg;base64,"+s}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(this.freezeFrameWidth!==0&&this.freezeFrameHeight!==0){let r=0,s=0,a=0,f=0;const _=this.rootDiv.clientWidth/this.rootDiv.clientHeight,C=this.freezeFrameWidth/this.freezeFrameHeight;_<C?(r=this.rootDiv.clientWidth,s=Math.floor(this.rootDiv.clientWidth/C),a=Math.floor(.5*(this.rootDiv.clientHeight-s)),f=0):(r=Math.floor(this.rootDiv.clientHeight*C),s=this.rootDiv.clientHeight,a=0,f=Math.floor(.5*(this.rootDiv.clientWidth-r))),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=r+"px",this.imageElement.style.height=s+"px",this.imageElement.style.left=f+"px",this.imageElement.style.top=a+"px"}}}class Ky{constructor(r){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new jy(r)}showFreezeFrame(){this.valid&&this.freezeFrame.setElementForShow()}hideFreezeFrame(){this.valid=!1,this.freezeFrame.setElementForHide()}updateFreezeFrameAndShow(r,s){this.freezeFrame.updateImageElementSource(r),this.freezeFrame.imageElement.onload=()=>{this.freezeFrame.setDimensionsFromElementAndResize(),s()}}processFreezeFrameMessage(r,s){this.receiving||(this.receiving=!0,this.valid=!1,this.size=0,this.jpeg=void 0),this.size=new DataView(r.slice(1,5).buffer).getInt32(0,!0);const a=r.slice(5);if(this.jpeg){const f=new Uint8Array(this.jpeg.length+a.length);f.set(this.jpeg,0),f.set(a,this.jpeg.length),this.jpeg=f}else this.jpeg=a,this.receiving=!0,T.Log(T.GetStackTrace(),`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`,6);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,T.Log(T.GetStackTrace(),`received complete freeze frame ${this.size}`,6),this.updateFreezeFrameAndShow(this.jpeg,s)):this.jpeg.length>this.size&&(T.Error(T.GetStackTrace(),`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class pi{constructor(r,s,a,f,_=(()=>{})){this.onChange=_,this.onChangeEmit=()=>{},this.id=r,this.description=a,this.label=s,this.value=f}set label(r){this._label=r,this.onChangeEmit(this._value)}get label(){return this._label}get value(){return this._value}set value(r){this._value=r,this.onChange(this._value,this),this.onChangeEmit(this._value)}}class St extends pi{constructor(r,s,a,f,_,C=(()=>{})){super(r,s,a,f,C);const R=new URLSearchParams(window.location.search);if(_&&R.has(this.id)){const S=this.getUrlParamFlag();this.flag=S}else this.flag=f;this.useUrlParams=_}getUrlParamFlag(){const r=new URLSearchParams(window.location.search);return!!r.has(this.id)&&r.get(this.id)!=="false"&&r.get(this.id)!=="False"}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);this.flag===!0?r.set(this.id,"true"):r.set(this.id,"false"),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}enable(){this.flag=!0}get flag(){return!!this.value}set flag(r){this.value=r}}class Pr extends pi{constructor(r,s,a,f,_,C,R,S=(()=>{})){super(r,s,a,C,S),this._min=f,this._max=_;const N=new URLSearchParams(window.location.search);if(R&&N.has(this.id)){const z=Number.parseFloat(N.get(this.id));this.number=Number.isNaN(z)?C:z}else this.number=C;this.useUrlParams=R}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.number.toString()),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}set number(r){this.value=this.clamp(r)}get number(){return this.value}clamp(r){return this._min==null&&this._max==null?r:this._min==null?Math.min(this._max,r):this._max==null?Math.max(this._min,r):Math.max(Math.min(this._max,r),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(r){this.onChange=r}}class vf extends pi{constructor(r,s,a,f,_,C=(()=>{})){super(r,s,a,f,C);const R=new URLSearchParams(window.location.search);if(_&&R.has(this.id)){const S=this.getUrlParamText();this.text=S}else this.text=f;this.useUrlParams=_}getUrlParamText(){var r;const s=new URLSearchParams(window.location.search);return s.has(this.id)&&(r=s.get(this.id))!==null&&r!==void 0?r:""}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.text),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}get text(){return this.value}set text(r){this.value=r}}class bo extends pi{constructor(r,s,a,f,_,C,R=(()=>{})){super(r,s,a,f,R),this.options=_;const S=new URLSearchParams(window.location.search),N=C&&S.has(this.id)?this.getUrlParamText():f;this.selected=N,this.useUrlParams=C}getUrlParamText(){var r;const s=new URLSearchParams(window.location.search);return s.has(this.id)&&(r=s.get(this.id))!==null&&r!==void 0?r:""}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.selected),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}addOnChangedListener(r){this.onChange=r}get options(){return this._options}set options(r){this._options=r,this.onChangeEmit(this.selected)}get selected(){return this.value}set selected(r){let s=this.options.filter((a=>a.indexOf(r)!==-1));s.length?this.value=s[0]:(s=this.options.filter((a=>a.indexOf(r.split(" ")[0])!==-1)),s.length&&(this.value=s[0]))}}class _f extends Event{constructor(r){super("afkWarningActivate"),this.data=r}}class So extends Event{constructor(r){super("afkWarningUpdate"),this.data=r}}class bf extends Event{constructor(){super("afkWarningDeactivate")}}class Sf extends Event{constructor(){super("afkTimedOut")}}class Tf extends Event{constructor(r){super("videoEncoderAvgQP"),this.data=r}}class Ef extends Event{constructor(){super("webRtcSdp")}}class $f extends Event{constructor(){super("webRtcAutoConnect")}}class xf extends Event{constructor(){super("webRtcConnecting")}}class Cf extends Event{constructor(){super("webRtcConnected")}}class kf extends Event{constructor(){super("webRtcFailed")}}class Rf extends Event{constructor(r){super("webRtcDisconnected"),this.data=r}}class Af extends Event{constructor(r){super("dataChannelOpen"),this.data=r}}class If extends Event{constructor(r){super("dataChannelClose"),this.data=r}}class Mf extends Event{constructor(r){super("dataChannelError"),this.data=r}}class Pf extends Event{constructor(){super("videoInitialized")}}class Of extends Event{constructor(){super("streamLoading")}}class Df extends Event{constructor(){super("streamConnect")}}class zf extends Event{constructor(){super("streamDisconnect")}}class Lf extends Event{constructor(){super("streamReconnect")}}class Bf extends Event{constructor(r){super("playStreamError"),this.data=r}}class Nf extends Event{constructor(){super("playStream")}}class To extends Event{constructor(r){super("playStreamRejected"),this.data=r}}class Uf extends Event{constructor(r){super("loadFreezeFrame"),this.data=r}}class Ff extends Event{constructor(){super("hideFreezeFrame")}}class Vf extends Event{constructor(r){super("statsReceived"),this.data=r}}class Gf extends Event{constructor(r){super("streamerListMessage"),this.data=r}}class qf extends Event{constructor(r){super("StreamerIDChangedMessage"),this.data=r}}class Wf extends Event{constructor(r){super("latencyTestResult"),this.data=r}}class Hf extends Event{constructor(r){super("dataChannelLatencyTestResponse"),this.data=r}}class jf extends Event{constructor(r){super("dataChannelLatencyTestResult"),this.data=r}}class Kf extends Event{constructor(r){super("initialSettings"),this.data=r}}class di extends Event{constructor(r){super("settingsChanged"),this.data=r}}class Qy extends Event{constructor(){super("xrSessionStarted")}}class Xy extends Event{constructor(){super("xrSessionEnded")}}class Qf extends Event{constructor(r){super("xrFrame"),this.data=r}}class Xf extends Event{constructor(r){super("playerCount"),this.data=r}}class Yf extends Event{constructor(){super("webRtcTCPRelayDetected")}}class Jf extends EventTarget{dispatchEvent(r){return super.dispatchEvent(r)}addEventListener(r,s){super.addEventListener(r,s)}removeEventListener(r,s){super.removeEventListener(r,s)}}class X{}X.AutoConnect="AutoConnect",X.AutoPlayVideo="AutoPlayVideo",X.AFKDetection="TimeoutIfIdle",X.BrowserSendOffer="OfferToReceive",X.HoveringMouseMode="HoveringMouse",X.ForceMonoAudio="ForceMonoAudio",X.ForceTURN="ForceTURN",X.FakeMouseWithTouches="FakeMouseWithTouches",X.IsQualityController="ControlsQuality",X.MatchViewportResolution="MatchViewportRes",X.StartVideoMuted="StartVideoMuted",X.SuppressBrowserKeys="SuppressBrowserKeys",X.UseMic="UseMic",X.KeyboardInput="KeyboardInput",X.MouseInput="MouseInput",X.TouchInput="TouchInput",X.GamepadInput="GamepadInput",X.XRControllerInput="XRControllerInput",X.WaitForStreamer="WaitForStreamer",X.HideUI="HideUI";const Yy=d=>Object.getOwnPropertyNames(X).some((r=>X[r]===d));class ge{}ge.AFKTimeoutSecs="AFKTimeout",ge.AFKCountdownSecs="AFKCountdown",ge.MinQP="MinQP",ge.MaxQP="MaxQP",ge.WebRTCFPS="WebRTCFPS",ge.WebRTCMinBitrate="WebRTCMinBitrate",ge.WebRTCMaxBitrate="WebRTCMaxBitrate",ge.MaxReconnectAttempts="MaxReconnectAttempts",ge.StreamerAutoJoinInterval="StreamerAutoJoinInterval";const Jy=d=>Object.getOwnPropertyNames(ge).some((r=>ge[r]===d));class Kr{}Kr.SignallingServerUrl="ss";const Zy=d=>Object.getOwnPropertyNames(Kr).some((r=>Kr[r]===d));class dt{}dt.PreferredCodec="PreferredCodec",dt.StreamerId="StreamerId";const ew=d=>Object.getOwnPropertyNames(dt).some((r=>dt[r]===d));class tw{constructor(r={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:s,useUrlParams:a}=r;this._useUrlParams=!!a,this.populateDefaultSettings(this._useUrlParams,s)}get useUrlParams(){return this._useUrlParams}populateDefaultSettings(r,s){this.textParameters.set(Kr.SignallingServerUrl,new vf(Kr.SignallingServerUrl,"Signalling url","Url of the signalling server",s&&s.hasOwnProperty(Kr.SignallingServerUrl)?s[Kr.SignallingServerUrl]:(location.protocol==="https:"?"wss://":"ws://")+window.location.hostname+(window.location.port==="80"||window.location.port===""?"":`:${window.location.port}`),r)),this.optionParameters.set(dt.StreamerId,new bo(dt.StreamerId,"Streamer ID","The ID of the streamer to stream.",s&&s.hasOwnProperty(dt.StreamerId)?s[dt.StreamerId]:"",[],r)),this.optionParameters.set(dt.PreferredCodec,new bo(dt.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation","H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",s&&s.hasOwnProperty(dt.PreferredCodec)?[s[dt.PreferredCodec]]:(function(){const a=[];if(!RTCRtpReceiver.getCapabilities)return a.push("Only available on Chrome"),a;const f=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((_=>{const C=_.mimeType.split("/")[1]+" "+(_.sdpFmtpLine||"");f.exec(C)!==null&&a.push(C)})),a})(),r)),this.flags.set(X.AutoConnect,new St(X.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",!(!s||!s.hasOwnProperty(X.AutoConnect))&&s[X.AutoConnect],r)),this.flags.set(X.AutoPlayVideo,new St(X.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!s||!s.hasOwnProperty(X.AutoPlayVideo)||s[X.AutoPlayVideo],r)),this.flags.set(X.BrowserSendOffer,new St(X.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!s||!s.hasOwnProperty(X.BrowserSendOffer))&&s[X.BrowserSendOffer],r)),this.flags.set(X.UseMic,new St(X.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!s||!s.hasOwnProperty(X.UseMic))&&s[X.UseMic],r)),this.flags.set(X.StartVideoMuted,new St(X.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!s||!s.hasOwnProperty(X.StartVideoMuted))&&s[X.StartVideoMuted],r)),this.flags.set(X.SuppressBrowserKeys,new St(X.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.",!s||!s.hasOwnProperty(X.SuppressBrowserKeys)||s[X.SuppressBrowserKeys],r)),this.flags.set(X.IsQualityController,new St(X.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!s||!s.hasOwnProperty(X.IsQualityController)||s[X.IsQualityController],r)),this.flags.set(X.ForceMonoAudio,new St(X.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!s||!s.hasOwnProperty(X.ForceMonoAudio))&&s[X.ForceMonoAudio],r)),this.flags.set(X.ForceTURN,new St(X.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!s||!s.hasOwnProperty(X.ForceTURN))&&s[X.ForceTURN],r)),this.flags.set(X.AFKDetection,new St(X.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!s||!s.hasOwnProperty(X.AFKDetection))&&s[X.AFKDetection],r)),this.flags.set(X.MatchViewportResolution,new St(X.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",!(!s||!s.hasOwnProperty(X.MatchViewportResolution))&&s[X.MatchViewportResolution],r)),this.flags.set(X.HoveringMouseMode,new St(X.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.",!(!s||!s.hasOwnProperty(X.HoveringMouseMode))&&s[X.HoveringMouseMode],r,((a,f)=>{f.label=`Control Scheme: ${a?"Hovering":"Locked"} Mouse`}))),this.flags.set(X.FakeMouseWithTouches,new St(X.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.",!(!s||!s.hasOwnProperty(X.FakeMouseWithTouches))&&s[X.FakeMouseWithTouches],r)),this.flags.set(X.KeyboardInput,new St(X.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!s||!s.hasOwnProperty(X.KeyboardInput)||s[X.KeyboardInput],r)),this.flags.set(X.MouseInput,new St(X.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!s||!s.hasOwnProperty(X.MouseInput)||s[X.MouseInput],r)),this.flags.set(X.TouchInput,new St(X.TouchInput,"Touch input","If enabled, send touch events to streamer",!s||!s.hasOwnProperty(X.TouchInput)||s[X.TouchInput],r)),this.flags.set(X.GamepadInput,new St(X.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!s||!s.hasOwnProperty(X.GamepadInput)||s[X.GamepadInput],r)),this.flags.set(X.XRControllerInput,new St(X.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!s||!s.hasOwnProperty(X.XRControllerInput)||s[X.XRControllerInput],r)),this.flags.set(X.WaitForStreamer,new St(X.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!s||!s.hasOwnProperty(X.WaitForStreamer)||s[X.WaitForStreamer],r)),this.flags.set(X.HideUI,new St(X.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!s||!s.hasOwnProperty(X.HideUI))&&s[X.HideUI],r)),this.numericParameters.set(ge.AFKTimeoutSecs,new Pr(ge.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,s&&s.hasOwnProperty(ge.AFKTimeoutSecs)?s[ge.AFKTimeoutSecs]:120,r)),this.numericParameters.set(ge.AFKCountdownSecs,new Pr(ge.AFKCountdownSecs,"AFK countdown","The time (in seconds) for a user to respond before the stream is ended after an AFK timeout.",10,null,10,r)),this.numericParameters.set(ge.MaxReconnectAttempts,new Pr(ge.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,s&&s.hasOwnProperty(ge.MaxReconnectAttempts)?s[ge.MaxReconnectAttempts]:3,r)),this.numericParameters.set(ge.MinQP,new Pr(ge.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,s&&s.hasOwnProperty(ge.MinQP)?s[ge.MinQP]:0,r)),this.numericParameters.set(ge.MaxQP,new Pr(ge.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,s&&s.hasOwnProperty(ge.MaxQP)?s[ge.MaxQP]:51,r)),this.numericParameters.set(ge.WebRTCFPS,new Pr(ge.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,s&&s.hasOwnProperty(ge.WebRTCFPS)?s[ge.WebRTCFPS]:60,r)),this.numericParameters.set(ge.WebRTCMinBitrate,new Pr(ge.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,s&&s.hasOwnProperty(ge.WebRTCMinBitrate)?s[ge.WebRTCMinBitrate]:0,r)),this.numericParameters.set(ge.WebRTCMaxBitrate,new Pr(ge.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,s&&s.hasOwnProperty(ge.WebRTCMaxBitrate)?s[ge.WebRTCMaxBitrate]:0,r)),this.numericParameters.set(ge.StreamerAutoJoinInterval,new Pr(ge.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,s&&s.hasOwnProperty(ge.StreamerAutoJoinInterval)?s[ge.StreamerAutoJoinInterval]:3e3,r))}_addOnNumericSettingChangedListener(r,s){this.numericParameters.has(r)&&this.numericParameters.get(r).addOnChangedListener(s)}_addOnOptionSettingChangedListener(r,s){this.optionParameters.has(r)&&this.optionParameters.get(r).addOnChangedListener(s)}getNumericSettingValue(r){if(this.numericParameters.has(r))return this.numericParameters.get(r).number;throw new Error(`There is no numeric setting with the id of ${r}`)}getTextSettingValue(r){if(this.textParameters.has(r))return this.textParameters.get(r).value;throw new Error(`There is no numeric setting with the id of ${r}`)}setNumericSetting(r,s){if(!this.numericParameters.has(r))throw new Error(`There is no numeric setting with the id of ${r}`);this.numericParameters.get(r).number=s}_addOnSettingChangedListener(r,s){this.flags.has(r)&&(this.flags.get(r).onChange=s)}_addOnTextSettingChangedListener(r,s){this.textParameters.has(r)&&(this.textParameters.get(r).onChange=s)}getSettingOption(r){return this.optionParameters.get(r)}isFlagEnabled(r){return this.flags.get(r).flag}setFlagEnabled(r,s){this.flags.has(r)?this.flags.get(r).flag=s:T.Warning(T.GetStackTrace(),`Cannot toggle flag called ${r} - it does not exist in the Config.flags map.`)}setTextSetting(r,s){this.textParameters.has(r)?this.textParameters.get(r).text=s:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.textParameters map.`)}setOptionSettingOptions(r,s){this.optionParameters.has(r)?this.optionParameters.get(r).options=s:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(r,s){if(this.optionParameters.has(r)){const a=this.optionParameters.get(r),f=a.options;f.includes(s)||(f.push(s),a.options=f),a.selected=s}else T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.enumParameters map.`)}setFlagLabel(r,s){this.flags.has(r)?this.flags.get(r).label=s:T.Warning(T.GetStackTrace(),`Cannot set label for flag called ${r} - it does not exist in the Config.flags map.`)}setSettings(r){for(const s of Object.keys(r))Yy(s)?this.setFlagEnabled(s,r[s]):Jy(s)?this.setNumericSetting(s,r[s]):Zy(s)?this.setTextSetting(s,r[s]):ew(s)&&this.setOptionSettingValue(s,r[s])}getSettings(){const r={};for(const[s,a]of this.flags.entries())r[s]=a.flag;for(const[s,a]of this.numericParameters.entries())r[s]=a.number;for(const[s,a]of this.textParameters.entries())r[s]=a.text;for(const[s,a]of this.optionParameters.entries())r[s]=a.selected;return r}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(r){for(const s of this.flags.keys()){const a=this.flags.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new di({id:a.id,type:"flag",value:f,target:a})))}for(const s of this.numericParameters.keys()){const a=this.numericParameters.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new di({id:a.id,type:"number",value:f,target:a})))}for(const s of this.textParameters.keys()){const a=this.textParameters.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new di({id:a.id,type:"text",value:f,target:a})))}for(const s of this.optionParameters.keys()){const a=this.optionParameters.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new di({id:a.id,type:"option",value:f,target:a})))}}}var Us;(function(d){d[d.LockedMouse=0]="LockedMouse",d[d.HoveringMouse=1]="HoveringMouse"})(Us||(Us={}));class Zf{constructor(r,s,a){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=r,this.pixelStreaming=s,this.onDismissAfk=a,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 bf))}startAfkWarningTimer(){this.config.getNumericSettingValue(ge.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(X.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(X.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(ge.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new _f({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(ge.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new So({countDown:this.countDown})),this.config.isFlagEnabled(X.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new Sf),this.onAFKTimedOutCallback(),T.Log(T.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new So({countDown:this.countDown}))}),1e3)}}class Np{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(r,s,a){this.peerConnection=r,this.label=s,this.datachannelOptions=a,a==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=r=>this.handleOnOpen(r),this.dataChannel.onclose=r=>this.handleOnClose(r),this.dataChannel.onmessage=r=>this.handleOnMessage(r),this.dataChannel.onerror=r=>this.handleOnError(r)}handleOnOpen(r){var s;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) opened.`,7),this.onOpen((s=this.dataChannel)===null||s===void 0?void 0:s.label,r)}handleOnClose(r){var s;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) closed.`,7),this.onClose((s=this.dataChannel)===null||s===void 0?void 0:s.label,r)}handleOnMessage(r){T.Log(T.GetStackTrace(),`Data Channel (${this.label}) message: ${r}`,8)}handleOnError(r){var s;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) error: ${r}`,7),this.onError((s=this.dataChannel)===null||s===void 0?void 0:s.label,r)}onOpen(r,s){}onClose(r,s){}onError(r,s){}}class em{}class tm{}class rm{}class Eo{}class sm{}class rw{}class sw{}class nm{constructor(){this.inboundVideoStats=new tm,this.inboundAudioStats=new em,this.DataChannelStats=new rm,this.outBoundVideoStats=new sm,this.sessionStats=new rw,this.streamStats=new sw,this.codecs=new Map}processStats(r){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,r.forEach((s=>{switch(s.type){case"candidate-pair":this.handleCandidatePair(s);break;case"certificate":case"media-source":case"media-playout":case"outbound-rtp":case"peer-connection":case"remote-inbound-rtp":break;case"codec":this.handleCodec(s);break;case"data-channel":this.handleDataChannel(s);break;case"inbound-rtp":this.handleInBoundRTP(s);break;case"local-candidate":this.handleLocalCandidate(s);break;case"remote-candidate":this.handleRemoteCandidate(s);break;case"remote-outbound-rtp":this.handleRemoteOutBound(s);break;case"track":this.handleTrack(s);break;case"transport":this.handleTransport(s);break;case"stream":this.handleStream(s);break;default:T.Error(T.GetStackTrace(),"unhandled Stat Type"),T.Log(T.GetStackTrace(),s)}}))}handleStream(r){this.streamStats=r}handleCandidatePair(r){this.candidatePairs.push(r)}handleDataChannel(r){this.DataChannelStats.bytesReceived=r.bytesReceived,this.DataChannelStats.bytesSent=r.bytesSent,this.DataChannelStats.dataChannelIdentifier=r.dataChannelIdentifier,this.DataChannelStats.id=r.id,this.DataChannelStats.label=r.label,this.DataChannelStats.messagesReceived=r.messagesReceived,this.DataChannelStats.messagesSent=r.messagesSent,this.DataChannelStats.protocol=r.protocol,this.DataChannelStats.state=r.state,this.DataChannelStats.timestamp=r.timestamp}handleLocalCandidate(r){const s=new Eo;s.label="local-candidate",s.address=r.address,s.port=r.port,s.protocol=r.protocol,s.candidateType=r.candidateType,s.id=r.id,s.relayProtocol=r.relayProtocol,s.transportId=r.transportId,this.localCandidates.push(s)}handleRemoteCandidate(r){const s=new Eo;s.label="remote-candidate",s.address=r.address,s.port=r.port,s.protocol=r.protocol,s.id=r.id,s.candidateType=r.candidateType,s.relayProtocol=r.relayProtocol,s.transportId=r.transportId,this.remoteCandidates.push(s)}handleInBoundRTP(r){switch(r.kind){case"video":this.inboundVideoStats=r,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=r,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:T.Log(T.GetStackTrace(),"Kind is not handled")}}handleRemoteOutBound(r){r.kind==="video"&&(this.outBoundVideoStats.bytesSent=r.bytesSent,this.outBoundVideoStats.id=r.id,this.outBoundVideoStats.localId=r.localId,this.outBoundVideoStats.packetsSent=r.packetsSent,this.outBoundVideoStats.remoteTimestamp=r.remoteTimestamp,this.outBoundVideoStats.timestamp=r.timestamp)}handleTrack(r){r.type!=="track"||r.trackIdentifier!=="video_label"&&r.kind!=="video"||(this.inboundVideoStats.framesDropped=r.framesDropped,this.inboundVideoStats.framesReceived=r.framesReceived,this.inboundVideoStats.frameHeight=r.frameHeight,this.inboundVideoStats.frameWidth=r.frameWidth)}handleTransport(r){this.transportStats=r}handleCodec(r){const s=r.id,a=`${r.mimeType.replace("video/","").replace("audio/","")}${r.sdpFmtpLine?` ${r.sdpFmtpLine}`:""}`;this.codecs.set(s,a)}handleSessionStatistics(r,s,a){const f=Date.now()-r;this.sessionStats.runTime=new Date(f).toISOString().substr(11,8).toString();const _=s===null?"Not sent yet":s?"true":"false";this.sessionStats.controlsStreamInput=_,this.sessionStats.videoEncoderAvgQP=a}isNumber(r){return typeof r=="number"&&isFinite(r)}getActiveCandidatePair(){return this.transportStats?this.candidatePairs.find((r=>r.id===this.transportStats.selectedCandidatePairId),null):this.candidatePairs.find((r=>r.selected),null)}}const Up=(Fp={parseRtpParameters:()=>Bp.parseRtpParameters,splitSections:()=>Bp.splitSections},uo={},Ui.d(uo,Fp),uo);var Fp,uo;class im{static isVideoTransciever(r){return this.canTransceiverReceiveVideo(r)||this.canTransceiverSendVideo(r)}static canTransceiverReceiveVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="video"}static canTransceiverSendVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="video"}static isAudioTransciever(r){return this.canTransceiverReceiveAudio(r)||this.canTransceiverSendAudio(r)}static canTransceiverReceiveAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="audio"}static canTransceiverSendAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="audio"}}var cn,Se,co=function(d,r,s,a){return new(s||(s=Promise))((function(f,_){function C(N){try{S(a.next(N))}catch(z){_(z)}}function R(N){try{S(a.throw(N))}catch(z){_(z)}}function S(N){var z;N.done?f(N.value):(z=N.value,z instanceof s?z:new s((function(te){te(z)}))).then(C,R)}S((a=a.apply(d,[])).next())}))};class nw{constructor(r,s,a){this.config=s,this.createPeerConnection(r,a)}createPeerConnection(r,s){this.config.isFlagEnabled(X.ForceTURN)&&(r.iceTransportPolicy="relay",T.Log(T.GetStackTrace(),"Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(r),this.peerConnection.onsignalingstatechange=a=>this.handleSignalStateChange(a),this.peerConnection.oniceconnectionstatechange=a=>this.handleIceConnectionStateChange(a),this.peerConnection.onicegatheringstatechange=a=>this.handleIceGatheringStateChange(a),this.peerConnection.ontrack=a=>this.handleOnTrack(a),this.peerConnection.onicecandidate=a=>this.handleIceCandidate(a),this.peerConnection.ondatachannel=a=>this.handleDataChannel(a),this.aggregatedStats=new nm,this.preferredCodec=s,this.updateCodecSelection=!0}createOffer(r,s){return co(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Create Offer",6);const a=location.hostname==="localhost"||location.hostname==="127.0.0.1",f=location.protocol==="https:";let _=s.isFlagEnabled(X.UseMic);!_||a||f||(_=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(_).finally((()=>{var C;(C=this.peerConnection)===null||C===void 0||C.createOffer(r).then((R=>{var S;this.showTextOverlayConnecting(),R.sdp=this.mungeSDP(R.sdp,_),(S=this.peerConnection)===null||S===void 0||S.setLocalDescription(R),this.onSendWebRTCOffer(R)})).catch((()=>{this.showTextOverlaySetupFailure()}))}))}))}receiveOffer(r,s){var a;return co(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Receive Offer",6),(a=this.peerConnection)===null||a===void 0||a.setRemoteDescription(r).then((()=>{const f=location.hostname==="localhost"||location.hostname==="127.0.0.1",_=location.protocol==="https:";let C=s.isFlagEnabled(X.UseMic);!C||f||_||(C=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.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(dt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r)),this.setupTransceiversAsync(C).finally((()=>{var R;(R=this.peerConnection)===null||R===void 0||R.createAnswer().then((S=>{var N;return S.sdp=this.mungeSDP(S.sdp,C),(N=this.peerConnection)===null||N===void 0?void 0:N.setLocalDescription(S)})).then((()=>{var S;this.onSendWebRTCAnswer((S=this.peerConnection)===null||S===void 0?void 0:S.currentLocalDescription)})).catch((()=>{T.Error(T.GetStackTrace(),"createAnswer() failed")}))}))}))}))}receiveAnswer(r){var s;(s=this.peerConnection)===null||s===void 0||s.setRemoteDescription(r),this.config.setOptionSettingOptions(dt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r))}generateStats(){var r;(r=this.peerConnection)===null||r===void 0||r.getStats(null).then((s=>{this.aggregatedStats.processStats(s),this.onVideoStats(this.aggregatedStats),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId&&this.config.setOptionSettingValue(dt.PreferredCodec,this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId))}))}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(r,s){let a=r.replace(/(a=fmtp:\d+ .*level-asymmetry-allowed=.*)\r\n/gm,`$1;x-google-start-bitrate=10000;x-google-max-bitrate=100000\r
|
|
2880
|
+
`),f="maxaveragebitrate=510000;";return s&&(f+="sprop-maxcapturerate=48000;"),f+=this.config.isFlagEnabled(X.ForceMonoAudio)?"stereo=0;":"stereo=1;",f+="useinbandfec=1",a=a.replace("useinbandfec=1",f),a}handleOnIce(r){var s;T.Log(T.GetStackTrace(),"peerconnection handleOnIce",6),this.config.isFlagEnabled(X.ForceTURN)&&r.candidate.indexOf("relay")<0?T.Info(T.GetStackTrace(),`Dropping candidate because it was not TURN relay. | Type= ${r.type} | Protocol= ${r.protocol} | Address=${r.address} | Port=${r.port} |`,6):(s=this.peerConnection)===null||s===void 0||s.addIceCandidate(r)}handleSignalStateChange(r){T.Log(T.GetStackTrace(),"signaling state change: "+r,6)}handleIceConnectionStateChange(r){T.Log(T.GetStackTrace(),"ice connection state change: "+r,6),this.onIceConnectionStateChange(r)}handleIceGatheringStateChange(r){T.Log(T.GetStackTrace(),"ice gathering state change: "+JSON.stringify(r),6)}handleOnTrack(r){this.onTrack(r)}handleIceCandidate(r){this.onPeerIceCandidate(r)}handleDataChannel(r){this.onDataChannel(r)}onTrack(r){}onIceConnectionStateChange(r){}onPeerIceCandidate(r){}onDataChannel(r){}fuzzyIntersectUEAndBrowserCodecs(r){const s=new Array,a=this.parseAvailableCodecs(r),f=this.config.getSettingOption(dt.PreferredCodec).options;for(const _ of a)if(f.includes(_))s.push(_);else{const C=_.split(" ")[0];for(const R of f)if(R.includes(C)){s.push(R);break}}return s}setupTransceiversAsync(r){var s,a,f,_,C,R,S,N,z,te,j,se;return co(this,void 0,void 0,(function*(){let J=!1;for(const W of(a=(s=this.peerConnection)===null||s===void 0?void 0:s.getTransceivers())!==null&&a!==void 0?a:[])if(W&&W.receiver&&W.receiver.track&&W.receiver.track.kind==="video"){J=!0;break}if(J||(f=this.peerConnection)===null||f===void 0||f.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&this.preferredCodec!=""){for(const W of(C=(_=this.peerConnection)===null||_===void 0?void 0:_.getTransceivers())!==null&&C!==void 0?C:[])if(W&&W.receiver&&W.receiver.track&&W.receiver.track.kind==="video"&&W.setCodecPreferences){const ne=this.preferredCodec.split(" "),fe={mimeType:"video/"+ne[0],clockRate:9e4,sdpFmtpLine:ne[1]?ne[1]:""},de=[fe];RTCRtpReceiver.getCapabilities("video").codecs.forEach((ce=>{(ce.mimeType!=fe.mimeType||ce?.sdpFmtpLine!=fe?.sdpFmtpLine)&&de.push(ce)}));for(const ce of de)ce?.sdpFmtpLine!==void 0&&ce.sdpFmtpLine!==""||delete ce.sdpFmtpLine;W.setCodecPreferences(de)}}let Y=!1;for(const W of(S=(R=this.peerConnection)===null||R===void 0?void 0:R.getTransceivers())!==null&&S!==void 0?S:[])if(W&&W.receiver&&W.receiver.track&&W.receiver.track.kind==="audio"){Y=!0;break}if(r){const W={video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}},ne=yield navigator.mediaDevices.getUserMedia(W);if(ne)if(Y){for(const fe of(te=(z=this.peerConnection)===null||z===void 0?void 0:z.getTransceivers())!==null&&te!==void 0?te:[])if(im.canTransceiverReceiveAudio(fe))for(const de of ne.getTracks())de.kind&&de.kind=="audio"&&(fe.sender.replaceTrack(de),fe.direction="sendrecv")}else for(const fe of ne.getTracks())fe.kind&&fe.kind=="audio"&&((j=this.peerConnection)===null||j===void 0||j.addTransceiver(fe,{direction:"sendrecv"}));else Y||(se=this.peerConnection)===null||se===void 0||se.addTransceiver("audio",{direction:"recvonly"})}else Y||(N=this.peerConnection)===null||N===void 0||N.addTransceiver("audio",{direction:"recvonly"})}))}onVideoStats(r){}onSendWebRTCOffer(r){}onSendWebRTCAnswer(r){}showTextOverlayConnecting(){}showTextOverlaySetupFailure(){}parseAvailableCodecs(r){if(!RTCRtpReceiver.getCapabilities)return["Only available on Chrome"];const s=[],a=(0,Up.splitSections)(r.sdp);return a.shift(),a.forEach((f=>{const{codecs:_}=(0,Up.parseRtpParameters)(f),C=/(VP\d|H26\d|AV1).*/;_.forEach((R=>{const S=R.name+" "+Object.keys(R.parameters||{}).map((N=>N+"="+R.parameters[N])).join(";");if(C.exec(S)!==null){R.name=="VP9"&&(R.parameters={"profile-id":"0"});const N=R.name+" "+Object.keys(R.parameters||{}).map((z=>z+"="+R.parameters[z])).join(";");s.push(N)}}))})),s}}class am{constructor(){this.PixelStreamingSettings=new iw,this.EncoderSettings=new om,this.WebRTCSettings=new lm}ueCompatible(){this.WebRTCSettings.MaxFPS!=null&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class iw{}class om{}class lm{}class um{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(r){this.frameDisplayDeltaTimeMs==0&&(this.frameDisplayDeltaTimeMs=Math.round(r))}processFields(){this.EncodeMs!=null||this.PreEncodeTimeMs==null&&this.PostEncodeTimeMs==null||(T.Log(T.GetStackTrace(),`Setting Encode Ms
|
|
2881
2881
|
${this.PostEncodeTimeMs}
|
|
2882
2882
|
${this.PreEncodeTimeMs}`,6),this.EncodeMs=this.PostEncodeTimeMs-this.PreEncodeTimeMs),this.CaptureToSendMs!=null||this.PreCaptureTimeMs==null&&this.PostCaptureTimeMs==null||(T.Log(T.GetStackTrace(),`Setting CaptureToSendMs Ms
|
|
2883
2883
|
${this.PostCaptureTimeMs}
|
|
2884
|
-
${this.PreCaptureTimeMs}`,6),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class ho{static setExtensionFromBytes(r,s){s.receiving||(s.mimetype="",s.extension="",s.receiving=!0,s.valid=!1,s.chunks=0,s.data=[],s.timestampStart=new Date().getTime(),T.Log(T.GetStackTrace(),"Received first chunk of file",6));const a=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),a,6),s.extension=a}static setMimeTypeFromBytes(r,s){s.receiving||(s.mimetype="",s.extension="",s.receiving=!0,s.valid=!1,s.chunks=0,s.data=[],s.timestampStart=new Date().getTime(),T.Log(T.GetStackTrace(),"Received first chunk of file",6));const a=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),a,6),s.mimetype=a}static setContentsFromBytes(r,s){if(!s.receiving)return;s.chunks=Math.ceil(new DataView(r.slice(1,5).buffer).getInt32(0,!0)/16379);const a=r.slice(5);if(s.data.push(a),T.Log(T.GetStackTrace(),`Received file chunk: ${s.data.length}/${s.chunks}`,6),s.data.length===s.chunks){s.receiving=!1,s.valid=!0,T.Log(T.GetStackTrace(),"Received complete file",6);const f=new Date().getTime()-s.timestampStart,_=Math.round(16384*s.chunks/f);T.Log(T.GetStackTrace(),`Average transfer bitrate: ${_}kb/s over ${f/1e3} seconds`,6);const C=new Blob(s.data,{type:s.mimetype}),R=document.createElement("a");R.setAttribute("href",URL.createObjectURL(C)),R.setAttribute("download",`transfer.${s.extension}`),document.body.append(R),R.remove()}else s.data.length>s.chunks&&(s.receiving=!1,T.Error(T.GetStackTrace(),`Received bigger file than advertised: ${s.data.length}/${s.chunks}`))}}class iw{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}}class zt{}zt.mainButton=0,zt.auxiliaryButton=1,zt.secondaryButton=2,zt.fourthButton=3,zt.fifthButton=4;class Gt{}Gt.primaryButton=1,Gt.secondaryButton=2,Gt.auxiliaryButton=4,Gt.fourthButton=8,Gt.fifthButton=16;class cn{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(r){this.unregisterCallbacks.push(r)}unregisterAll(){for(const r of this.unregisterCallbacks)r();this.unregisterCallbacks=[]}}class aw{constructor(r,s,a){this.touchEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a;const f=R=>this.onTouchStart(R),_=R=>this.onTouchEnd(R),C=R=>this.onTouchMove(R);document.addEventListener("touchstart",f,{passive:!1}),document.addEventListener("touchend",_,{passive:!1}),document.addEventListener("touchmove",C,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchend",_))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",C)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}setVideoElementParentClientRect(r){this.videoElementParentClientRect=r}onTouchStart(r){if(this.videoElementProvider.isVideoReady()&&r.target===this.videoElementProvider.getVideoElement()){if(this.fakeTouchFinger==null){const s=r.changedTouches[0];this.fakeTouchFinger=new ow(s.identifier,s.clientX-this.videoElementParentClientRect.left,s.clientY-this.videoElementParentClientRect.top);const a=this.videoElementProvider.getVideoParentElement(),f=new MouseEvent("mouseenter",s);a.dispatchEvent(f);const _=this.coordinateConverter.normalizeAndQuantizeUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([zt.mainButton,_.x,_.y])}r.preventDefault()}}onTouchEnd(r){if(!this.videoElementProvider.isVideoReady()||this.fakeTouchFinger==null)return;const s=this.videoElementProvider.getVideoParentElement(),a=this.toStreamerMessagesProvider.toStreamerHandlers;for(let f=0;f<r.changedTouches.length;f++){const _=r.changedTouches[f];if(_.identifier===this.fakeTouchFinger.id){const C=_.clientX-this.videoElementParentClientRect.left,R=_.clientY-this.videoElementParentClientRect.top,b=this.coordinateConverter.normalizeAndQuantizeUnsigned(C,R);a.get("MouseUp")([zt.mainButton,b.x,b.y]);const U=new MouseEvent("mouseleave",_);s.dispatchEvent(U),this.fakeTouchFinger=null;break}}r.preventDefault()}onTouchMove(r){if(!this.videoElementProvider.isVideoReady()||this.fakeTouchFinger==null)return;const s=this.toStreamerMessagesProvider.toStreamerHandlers;for(let a=0;a<r.touches.length;a++){const f=r.touches[a];if(f.identifier===this.fakeTouchFinger.id){const _=f.clientX-this.videoElementParentClientRect.left,C=f.clientY-this.videoElementParentClientRect.top,R=this.coordinateConverter.normalizeAndQuantizeUnsigned(_,C),b=this.coordinateConverter.normalizeAndQuantizeSigned(_-this.fakeTouchFinger.x,C-this.fakeTouchFinger.y);s.get("MouseMove")([R.x,R.y,b.x,b.y]),this.fakeTouchFinger.x=_,this.fakeTouchFinger.y=C;break}}r.preventDefault()}}class ow{constructor(r,s,a){this.id=r,this.x=s,this.y=a}}class qt{}qt.backSpace=8,qt.shift=16,qt.control=17,qt.alt=18,qt.rightShift=253,qt.rightControl=254,qt.rightAlt=255;class lw{constructor(r,s,a){this.keyboardEventListenerTracker=new cn,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=r,this.config=s,this.activeKeysProvider=a}registerKeyBoardEvents(){const r=_=>this.handleOnCompositionEnd(_),s=_=>this.handleOnKeyDown(_),a=_=>this.handleOnKeyUp(_),f=_=>this.handleOnKeyPress(_);document.addEventListener("compositionend",r),document.addEventListener("keydown",s),document.addEventListener("keyup",a),document.addEventListener("keypress",f),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("compositionend",r))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keydown",s))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keyup",a))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keypress",f)))}unregisterKeyBoardEvents(){this.keyboardEventListenerTracker.unregisterAll()}handleOnKeyDown(r){const s=this.getKeycode(r);s&&s!==229&&(T.Log(T.GetStackTrace(),`key down ${s}, repeat = ${r.repeat}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyDown")([this.getKeycode(r),r.repeat?1:0]),this.activeKeysProvider.getActiveKeys().push(s),s===qt.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:qt.backSpace})),this.config.isFlagEnabled(X.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(s)&&r.preventDefault())}handleOnKeyUp(r){const s=this.getKeycode(r);s&&(T.Log(T.GetStackTrace(),`key up ${s}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyUp")([s]),this.config.isFlagEnabled(X.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(s)&&r.preventDefault())}handleOnKeyPress(r){if(!("charCode"in r))return void T.Warning(T.GetStackTrace(),"KeyboardEvent.charCode is deprecated in this browser, cannot send key press.");const s=r.charCode;T.Log(T.GetStackTrace(),`key press ${s}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyPress")([s])}handleOnCompositionEnd(r){r.data&&r.data.length&&r.data.split("").forEach((s=>{this.handleOnKeyDown(new KeyboardEvent("keydown",{keyCode:s.toUpperCase().charCodeAt(0),charCode:s.charCodeAt(0)})),this.handleOnKeyPress(new KeyboardEvent("keypress",{keyCode:s.toUpperCase().charCodeAt(0),charCode:s.charCodeAt(0)})),this.handleOnKeyUp(new KeyboardEvent("keyup",{keyCode:s.toUpperCase().charCodeAt(0),charCode:s.charCodeAt(0)}))}))}getKeycode(r){if(!("keyCode"in r)){const s=r;return s.code in this.CodeToKeyCode?this.CodeToKeyCode[s.code]:(T.Warning(T.GetStackTrace(),`Keyboard code of ${s.code} is not supported in our mapping, ignoring this key.`),null)}return r.keyCode===qt.shift&&r.code==="ShiftRight"?qt.rightShift:r.keyCode===qt.control&&r.code==="ControlRight"?qt.rightControl:r.keyCode===qt.alt&&r.code==="AltRight"?qt.rightAlt:r.keyCode}isKeyCodeBrowserKey(r){return r>=112&&r<=123||r===9}}class uw{constructor(r,s,a){this.x=0,this.y=0,this.updateMouseMovePositionEvent=_=>{this.updateMouseMovePosition(_)},this.mouseEventListenerTracker=new cn,this.videoElementProvider=r,this.mouseController=s,this.activeKeysProvider=a;const f=this.videoElementProvider.getVideoParentElement();this.x=f.getBoundingClientRect().width/2,this.y=f.getBoundingClientRect().height/2,this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y)}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}lockStateChange(){const r=this.videoElementProvider.getVideoParentElement(),s=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers;if(document.pointerLockElement===r||document.mozPointerLockElement===r)T.Log(T.GetStackTrace(),"Pointer locked",6),document.addEventListener("mousemove",this.updateMouseMovePositionEvent,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1)));else{T.Log(T.GetStackTrace(),"The pointer lock status is now unlocked",6),document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1);let a=this.activeKeysProvider.getActiveKeys();const f=new Set(a),_=[];f.forEach((C=>{})),_.forEach((C=>{s.get("KeyUp")([C])})),a=[]}}updateMouseMovePosition(r){if(!this.videoElementProvider.isVideoReady())return;const s=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers,a=this.videoElementProvider.getVideoParentElement().clientWidth,f=this.videoElementProvider.getVideoParentElement().clientHeight;this.x+=r.movementX,this.y+=r.movementY,this.x>a&&(this.x-=a),this.y>f&&(this.y-=f),this.x<0&&(this.x=a+this.x),this.y<0&&(this.y=f-this.y),this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y);const _=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(r.movementX,r.movementY);s.get("MouseMove")([this.coord.x,this.coord.y,_.x,_.y])}handleMouseDown(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([r.button,this.coord.x,this.coord.y])}handleMouseUp(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r.button,this.coord.x,this.coord.y])}handleMouseWheel(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([r.wheelDelta,this.coord.x,this.coord.y])}handleMouseDouble(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([r.button,this.coord.x,this.coord.y])}handlePressMouseButtons(r){this.videoElementProvider.isVideoReady()&&this.mouseController.pressMouseButtons(r.buttons,this.x,this.y)}handleReleaseMouseButtons(r){this.videoElementProvider.isVideoReady()&&this.mouseController.releaseMouseButtons(r.buttons,this.x,this.y)}}class dw{constructor(r){this.mouseController=r}unregisterMouseEvents(){}updateMouseMovePosition(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),"MouseMove",6);const s=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY),a=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(r.movementX,r.movementY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseMove")([s.x,s.y,a.x,a.y]),r.preventDefault()}handleMouseDown(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),"onMouse Down",6);const s=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([r.button,s.x,s.y]),r.preventDefault()}handleMouseUp(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),"onMouse Up",6);const s=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r.button,s.x,s.y]),r.preventDefault()}handleContextMenu(r){this.mouseController.videoElementProvider.isVideoReady()&&r.preventDefault()}handleMouseWheel(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;const s=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([r.wheelDelta,s.x,s.y]),r.preventDefault()}handleMouseDouble(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;const s=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([r.button,s.x,s.y])}handlePressMouseButtons(r){this.mouseController.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"onMouse press",6),this.mouseController.pressMouseButtons(r.buttons,r.offsetX,r.offsetY))}handleReleaseMouseButtons(r){this.mouseController.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"onMouse release",6),this.mouseController.releaseMouseButtons(r.buttons,r.offsetX,r.offsetY))}}class cw{constructor(r,s,a,f){this.mouseEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.coordinateConverter=a,this.videoElementProvider=s,this.activeKeysProvider=f,this.registerMouseEnterAndLeaveEvents()}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}registerLockedMouseEvents(r){const s=this.videoElementProvider.getVideoParentElement(),a=new uw(this.videoElementProvider,r,this.activeKeysProvider);if(s.requestPointerLock=s.requestPointerLock||s.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,s.requestPointerLock){const U=()=>{s.requestPointerLock()};s.addEventListener("click",U),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("click",U)))}const f=()=>a.lockStateChange();document.addEventListener("pointerlockchange",f,!1),document.addEventListener("mozpointerlockchange",f,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("pointerlockchange",f,!1))),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mozpointerlockchange",f,!1)));const _=U=>a.handleMouseDown(U),C=U=>a.handleMouseUp(U),R=U=>a.handleMouseWheel(U),b=U=>a.handleMouseDouble(U);s.addEventListener("mousedown",_),s.addEventListener("mouseup",C),s.addEventListener("wheel",R),s.addEventListener("dblclick",b),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousedown",_))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mouseup",C))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("wheel",R))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("dblclick",b))),this.mouseEventListenerTracker.addUnregisterCallback((()=>a.unregisterMouseEvents())),this.mouseEventListenerTracker.addUnregisterCallback((()=>{!document.exitPointerLock||document.pointerLockElement!==s&&document.mozPointerLockElement!==s||document.exitPointerLock()}))}registerHoveringMouseEvents(r){const s=this.videoElementProvider.getVideoParentElement(),a=new dw(r),f=z=>a.updateMouseMovePosition(z),_=z=>a.handleMouseDown(z),C=z=>a.handleMouseUp(z),R=z=>a.handleContextMenu(z),b=z=>a.handleMouseWheel(z),U=z=>a.handleMouseDouble(z);s.addEventListener("mousemove",f),s.addEventListener("mousedown",_),s.addEventListener("mouseup",C),s.addEventListener("contextmenu",R),s.addEventListener("wheel",b),s.addEventListener("dblclick",U),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousemove",f))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousedown",_))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mouseup",C))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("contextmenu",R))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("wheel",b))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("dblclick",U))),this.mouseEventListenerTracker.addUnregisterCallback((()=>a.unregisterMouseEvents()))}registerMouseEnterAndLeaveEvents(){const r=this.videoElementProvider.getVideoParentElement(),s=f=>{this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"Mouse Entered",6),this.sendMouseEnter(),this.pressMouseButtons(f.buttons,f.x,f.y))},a=f=>{this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"Mouse Left",6),this.sendMouseLeave(),this.releaseMouseButtons(f.buttons,f.x,f.y))};r.addEventListener("mouseenter",s),r.addEventListener("mouseleave",a),this.mouseEventListenerTracker.addUnregisterCallback((()=>r.removeEventListener("mouseenter",s))),this.mouseEventListenerTracker.addUnregisterCallback((()=>r.removeEventListener("mouseleave",a)))}releaseMouseButtons(r,s,a){const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);r&Gt.primaryButton&&this.sendMouseUp(zt.mainButton,f.x,f.y),r&Gt.secondaryButton&&this.sendMouseUp(zt.secondaryButton,f.x,f.y),r&Gt.auxiliaryButton&&this.sendMouseUp(zt.auxiliaryButton,f.x,f.y),r&Gt.fourthButton&&this.sendMouseUp(zt.fourthButton,f.x,f.y),r&Gt.fifthButton&&this.sendMouseUp(zt.fifthButton,f.x,f.y)}pressMouseButtons(r,s,a){if(!this.videoElementProvider.isVideoReady())return;const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);r&Gt.primaryButton&&this.sendMouseDown(zt.mainButton,f.x,f.y),r&Gt.secondaryButton&&this.sendMouseDown(zt.secondaryButton,f.x,f.y),r&Gt.auxiliaryButton&&this.sendMouseDown(zt.auxiliaryButton,f.x,f.y),r&Gt.fourthButton&&this.sendMouseDown(zt.fourthButton,f.x,f.y),r&Gt.fifthButton&&this.sendMouseDown(zt.fifthButton,f.x,f.y)}sendMouseEnter(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseEnter")()}sendMouseLeave(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseLeave")()}sendMouseDown(r,s,a){this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),`mouse button ${r} down at (${s}, ${a})`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([r,s,a]))}sendMouseUp(r,s,a){if(!this.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),`mouse button ${r} up at (${s}, ${a})`,6);const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r,f.x,f.y])}}class hw{constructor(r,s,a){this.fingers=[9,8,7,6,5,4,3,2,1,0],this.fingerIds=new Map,this.maxByteValue=255,this.touchEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a,this.videoElementParent=s.getVideoElement();const f=b=>this.onTouchStart(b),_=b=>this.onTouchEnd(b),C=b=>this.onTouchMove(b);this.videoElementParent.addEventListener("touchstart",f),this.videoElementParent.addEventListener("touchend",_),this.videoElementParent.addEventListener("touchmove",C),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchend",_))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchmove",C))),T.Log(T.GetStackTrace(),"Touch Events Registered",6);const R=b=>{b.preventDefault()};document.addEventListener("touchmove",R),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",R)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}rememberTouch(r){const s=this.fingers.pop();s===void 0&&T.Log(T.GetStackTrace(),"exhausted touch identifiers",6),this.fingerIds.set(r.identifier,s)}forgetTouch(r){this.fingers.push(this.fingerIds.get(r.identifier)),this.fingers.sort((function(s,a){return a-s})),this.fingerIds.delete(r.identifier)}onTouchStart(r){if(this.videoElementProvider.isVideoReady()){for(let s=0;s<r.changedTouches.length;s++)this.rememberTouch(r.changedTouches[s]);T.Log(T.GetStackTrace(),"touch start",6),this.emitTouchData("TouchStart",r.changedTouches),r.preventDefault()}}onTouchEnd(r){if(this.videoElementProvider.isVideoReady()){T.Log(T.GetStackTrace(),"touch end",6),this.emitTouchData("TouchEnd",r.changedTouches);for(let s=0;s<r.changedTouches.length;s++)this.forgetTouch(r.changedTouches[s]);r.preventDefault()}}onTouchMove(r){this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"touch move",6),this.emitTouchData("TouchMove",r.touches),r.preventDefault())}emitTouchData(r,s){if(!this.videoElementProvider.isVideoReady())return;const a=this.videoElementProvider.getVideoParentElement().getBoundingClientRect(),f=this.toStreamerMessagesProvider.toStreamerHandlers;for(let _=0;_<s.length;_++){const R=s[_],b=R.clientX-a.left,U=R.clientY-a.top;T.Log(T.GetStackTrace(),`F${this.fingerIds.get(R.identifier)}=(${b}, ${U})`,6);const z=this.coordinateConverter.normalizeAndQuantizeUnsigned(b,U);switch(r){case"TouchStart":f.get("TouchStart")([1,z.x,z.y,this.fingerIds.get(R.identifier),this.maxByteValue*(R.force>0?R.force:1),z.inRange?1:0]);break;case"TouchEnd":f.get("TouchEnd")([1,z.x,z.y,this.fingerIds.get(R.identifier),this.maxByteValue*R.force,z.inRange?1:0]);break;case"TouchMove":f.get("TouchMove")([1,z.x,z.y,this.fingerIds.get(R.identifier),this.maxByteValue*(R.force>0?R.force:1),z.inRange?1:0])}}}}class pw{constructor(r){this.gamePadEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.requestAnimationFrame=(window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.requestAnimationFrame).bind(window);const s=window;if(window.addEventListener("beforeunload",(a=>this.onBeforeUnload(a))),"GamepadEvent"in s){const a=_=>this.gamePadConnectHandler(_),f=_=>this.gamePadDisconnectHandler(_);window.addEventListener("gamepadconnected",a),window.addEventListener("gamepaddisconnected",f),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepadconnected",a))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepaddisconnected",f)))}else if("WebKitGamepadEvent"in s){const a=_=>this.gamePadConnectHandler(_),f=_=>this.gamePadDisconnectHandler(_);window.addEventListener("webkitgamepadconnected",a),window.addEventListener("webkitgamepaddisconnected",f),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepadconnected",a))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepaddisconnected",f)))}if(this.controllers=[],navigator.getGamepads)for(const a of navigator.getGamepads())a&&this.gamePadConnectHandler(new GamepadEvent("gamepadconnected",{gamepad:a}))}unregisterGamePadEvents(){this.gamePadEventListenerTracker.unregisterAll();for(const r of this.controllers)r.id!==void 0&&this.onGamepadDisconnected(r.id);this.controllers=[],this.onGamepadConnected=()=>{},this.onGamepadDisconnected=()=>{}}gamePadConnectHandler(r){T.Log(T.GetStackTrace(),"Gamepad connect handler",6);const s=r.gamepad,a={currentState:s,prevState:s,id:void 0};this.controllers.push(a),this.controllers[s.index].currentState=s,this.controllers[s.index].prevState=s,T.Log(T.GetStackTrace(),"gamepad: "+s.id+" connected",6),window.requestAnimationFrame((()=>this.updateStatus())),this.onGamepadConnected()}gamePadDisconnectHandler(r){T.Log(T.GetStackTrace(),"Gamepad disconnect handler",6),T.Log(T.GetStackTrace(),"gamepad: "+r.gamepad.id+" disconnected",6);const s=this.controllers[r.gamepad.index];delete this.controllers[r.gamepad.index],this.controllers=this.controllers.filter((a=>a!==void 0)),this.onGamepadDisconnected(s.id)}scanGamePads(){const r=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[];for(let s=0;s<r.length;s++)r[s]&&r[s].index in this.controllers&&(this.controllers[r[s].index].currentState=r[s])}updateStatus(){this.scanGamePads();const r=this.toStreamerMessagesProvider.toStreamerHandlers;for(const s of this.controllers){const a=s.id===void 0?this.controllers.indexOf(s):s.id,f=s.currentState;for(let _=0;_<s.currentState.buttons.length;_++){const C=s.currentState.buttons[_],R=s.prevState.buttons[_];C.pressed?_==ln.LeftTrigger?r.get("GamepadAnalog")([a,5,C.value]):_==ln.RightTrigger?r.get("GamepadAnalog")([a,6,C.value]):r.get("GamepadButtonPressed")([a,_,R.pressed?1:0]):!C.pressed&&R.pressed&&(_==ln.LeftTrigger?r.get("GamepadAnalog")([a,5,0]):_==ln.RightTrigger?r.get("GamepadAnalog")([a,6,0]):r.get("GamepadButtonReleased")([a,_,0]))}for(let _=0;_<f.axes.length;_+=2){const C=parseFloat(f.axes[_].toFixed(4)),R=-parseFloat(f.axes[_+1].toFixed(4));r.get("GamepadAnalog")([a,_+1,C]),r.get("GamepadAnalog")([a,_+2,R])}this.controllers[a].prevState=f}this.controllers.length>0&&this.requestAnimationFrame((()=>this.updateStatus()))}onGamepadResponseReceived(r){for(const s of this.controllers)if(s.id===void 0){s.id=r;break}}onGamepadConnected(){}onGamepadDisconnected(r){}onBeforeUnload(r){for(const s of this.controllers)this.onGamepadDisconnected(s.id)}}(function(d){d[d.RightClusterBottomButton=0]="RightClusterBottomButton",d[d.RightClusterRightButton=1]="RightClusterRightButton",d[d.RightClusterLeftButton=2]="RightClusterLeftButton",d[d.RightClusterTopButton=3]="RightClusterTopButton",d[d.LeftShoulder=4]="LeftShoulder",d[d.RightShoulder=5]="RightShoulder",d[d.LeftTrigger=6]="LeftTrigger",d[d.RightTrigger=7]="RightTrigger",d[d.SelectOrBack=8]="SelectOrBack",d[d.StartOrForward=9]="StartOrForward",d[d.LeftAnalogPress=10]="LeftAnalogPress",d[d.RightAnalogPress=11]="RightAnalogPress",d[d.LeftClusterTopButton=12]="LeftClusterTopButton",d[d.LeftClusterBottomButton=13]="LeftClusterBottomButton",d[d.LeftClusterLeftButton=14]="LeftClusterLeftButton",d[d.LeftClusterRightButton=15]="LeftClusterRightButton",d[d.CentreButton=16]="CentreButton",d[d.LeftStickHorizontal=0]="LeftStickHorizontal",d[d.LeftStickVertical=1]="LeftStickVertical",d[d.RightStickHorizontal=2]="RightStickHorizontal",d[d.RightStickVertical=3]="RightStickVertical"})(ln||(ln={}));class fw{constructor(r,s,a){this.activeKeys=new mw,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a}registerKeyBoard(r){T.Log(T.GetStackTrace(),"Register Keyboard Events",7);const s=new lw(this.toStreamerMessagesProvider,r,this.activeKeys);return s.registerKeyBoardEvents(),s}registerMouse(r){T.Log(T.GetStackTrace(),"Register Mouse Events",7);const s=new cw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys);switch(r){case Ns.LockedMouse:s.registerLockedMouseEvents(s);break;case Ns.HoveringMouse:s.registerHoveringMouseEvents(s);break;default:T.Info(T.GetStackTrace(),"unknown Control Scheme Type Defaulting to Locked Mouse Events"),s.registerLockedMouseEvents(s)}return s}registerTouch(r,s){if(T.Log(T.GetStackTrace(),"Registering Touch",6),r){const a=new aw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return a.setVideoElementParentClientRect(s),a}return new hw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return T.Log(T.GetStackTrace(),"Register Game Pad",7),new pw(this.toStreamerMessagesProvider)}}class mw{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class gw{constructor(r,s){this.lastTimeResized=new Date().getTime(),this.videoElement=document.createElement("video"),this.config=s,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",r.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(r){this.audioElement=r}play(){return this.videoElement.muted=this.config.isFlagEnabled(X.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(X.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(r){this.videoElement.srcObject.getTracks().forEach((s=>s.enabled=r))}onVideoInitialized(){}onOrientationChange(){clearTimeout(this.orientationChangeTimeout),this.orientationChangeTimeout=window.setTimeout((()=>{this.resizePlayerStyle()}),500)}resizePlayerStyle(){const r=this.getVideoParentElement();r&&(this.updateVideoStreamSize(),r.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(X.MatchViewportResolution))if(new Date().getTime()-this.lastTimeResized>300){const r=this.getVideoParentElement();if(!r)return;this.onMatchViewportResolutionCallback(r.clientWidth,r.clientHeight),this.lastTimeResized=new Date().getTime()}else T.Log(T.GetStackTrace(),"Resizing too often - skipping",6),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout((()=>this.updateVideoStreamSize()),100)}}class yw{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(r,s,a){switch(r){case be.ToStreamer:this.toStreamerHandlers.set(s,a);break;case be.FromStreamer:this.fromStreamerHandlers.set(s,a);break;default:T.Log(T.GetStackTrace(),`Unknown message direction ${r}`)}}}(function(d){d[d.ToStreamer=0]="ToStreamer",d[d.FromStreamer=1]="FromStreamer"})(be||(be={}));class ww{constructor(){this.responseEventListeners=new Map}addResponseEventListener(r,s){this.responseEventListeners.set(r,s)}removeResponseEventListener(r){this.responseEventListeners.delete(r)}onResponse(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.Response",6);const s=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),s,6),this.responseEventListeners.forEach((a=>{a(s)}))}}class vw{constructor(r,s){this.dataChannelSender=r,this.toStreamerMessagesMapProvider=s}sendMessageToStreamer(r,s){s===void 0&&(s=[]);const a=this.toStreamerMessagesMapProvider.toStreamerMessages.get(r);if(a===void 0)return void T.Error(T.GetStackTrace(),`Attempted to send a message to the streamer with message type: ${r}, but the frontend hasn't been configured to send such a message. Check you've added the message type in your cpp`);if(a.structure&&s&&a.structure.length!==s.length)return void T.Error(T.GetStackTrace(),`Provided message data doesn't match expected layout. Expected [ ${a.structure.map((b=>{switch(b){case"uint8":case"uint16":case"int16":case"float":case"double":return"number";case"string":return"string"}})).toString()} ] but received [ ${s.map((b=>typeof b)).toString()} ]`);let f=0;const _=new TextEncoder;s.forEach(((b,U)=>{switch(a.structure[U]){case"uint8":f+=1;break;case"uint16":case"int16":f+=2;break;case"float":f+=4;break;case"double":f+=8;break;case"string":f+=2,f+=2*_.encode(b).length}}));const C=new DataView(new ArrayBuffer(f+1));C.setUint8(0,a.id);let R=1;s.forEach(((b,U)=>{switch(a.structure[U]){case"uint8":C.setUint8(R,b),R+=1;break;case"uint16":C.setUint16(R,b,!0),R+=2;break;case"int16":C.setInt16(R,b,!0),R+=2;break;case"float":C.setFloat32(R,b,!0),R+=4;break;case"double":C.setFloat64(R,b,!0),R+=8;break;case"string":C.setUint16(R,b.length,!0),R+=2;for(let z=0;z<b.length;z++)C.setUint16(R,b.charCodeAt(z),!0),R+=2}})),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(C.buffer):T.Info(T.GetStackTrace(),`Data channel cannot send yet, skipping sending message: ${r} - ${new Uint8Array(C.buffer)}`)}}class _w{constructor(r){this.sendMessageController=r}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 bw{constructor(r){this.dataChannelProvider=r}canSend(){return this.dataChannelProvider.getDataChannelInstance().dataChannel!==void 0&&this.dataChannelProvider.getDataChannelInstance().dataChannel.readyState=="open"}sendData(r){const s=this.dataChannelProvider.getDataChannelInstance();s.dataChannel.readyState=="open"?(s.dataChannel.send(r),T.Log(T.GetStackTrace(),`Message Sent: ${new Uint8Array(r)}`,6),this.resetAfkWarningTimerOnDataSend()):T.Error(T.GetStackTrace(),`Message Failed: ${new Uint8Array(r)}`)}resetAfkWarningTimerOnDataSend(){}}class Sw{constructor(r){this.videoElementProvider=r,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(r,s){return this.normalizeAndQuantizeUnsignedFunc(r,s)}unquantizeAndDenormalizeUnsigned(r,s){return this.denormalizeAndUnquantizeUnsignedFunc(r,s)}normalizeAndQuantizeSigned(r,s){return this.normalizeAndQuantizeSignedFunc(r,s)}setupNormalizeAndQuantize(){if(this.videoElementParent=this.videoElementProvider.getVideoParentElement(),this.videoElement=this.videoElementProvider.getVideoElement(),this.videoElementParent&&this.videoElement){const r=this.videoElementParent.clientWidth||1,s=this.videoElementParent.clientHeight||1,a=this.videoElement.videoWidth||1,f=s/r,_=(this.videoElement.videoHeight||1)/a;f>_?(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio > videoAspectRatio",6),this.ratio=f/_,this.normalizeAndQuantizeUnsignedFunc=(C,R)=>this.normalizeAndQuantizeUnsignedPlayerBigger(C,R),this.normalizeAndQuantizeSignedFunc=(C,R)=>this.normalizeAndQuantizeSignedPlayerBigger(C,R),this.denormalizeAndUnquantizeUnsignedFunc=(C,R)=>this.denormalizeAndUnquantizeUnsignedPlayerBigger(C,R)):(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio <= videoAspectRatio",6),this.ratio=_/f,this.normalizeAndQuantizeUnsignedFunc=(C,R)=>this.normalizeAndQuantizeUnsignedPlayerSmaller(C,R),this.normalizeAndQuantizeSignedFunc=(C,R)=>this.normalizeAndQuantizeSignedPlayerSmaller(C,R),this.denormalizeAndUnquantizeUnsignedFunc=(C,R)=>this.denormalizeAndUnquantizeUnsignedPlayerSmaller(C,R))}}normalizeAndQuantizeUnsignedPlayerBigger(r,s){const a=r/this.videoElementParent.clientWidth,f=this.ratio*(s/this.videoElementParent.clientHeight-.5)+.5;return a<0||a>1||f<0||f>1?new Oi(!1,65535,65535):new Oi(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerBigger(r,s){const a=r/65536,f=(s/65536-.5)/this.ratio+.5;return new $o(a*this.videoElementParent.clientWidth,f*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerBigger(r,s){const a=r/(.5*this.videoElementParent.clientWidth),f=this.ratio*s/(.5*this.videoElementParent.clientHeight);return new Vp(32767*a,32767*f)}normalizeAndQuantizeUnsignedPlayerSmaller(r,s){const a=this.ratio*(r/this.videoElementParent.clientWidth-.5)+.5,f=s/this.videoElementParent.clientHeight;return a<0||a>1||f<0||f>1?new Oi(!1,65535,65535):new Oi(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerSmaller(r,s){const a=(r/65536-.5)/this.ratio+.5,f=s/65536;return new $o(a*this.videoElementParent.clientWidth,f*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerSmaller(r,s){const a=this.ratio*r/(.5*this.videoElementParent.clientWidth),f=s/(.5*this.videoElementParent.clientHeight);return new Vp(32767*a,32767*f)}}class Oi{constructor(r,s,a){this.inRange=r,this.x=s,this.y=a}}class $o{constructor(r,s){this.x=r,this.y=s}}class Vp{constructor(r,s){this.x=r,this.y=s}}class dm{constructor(r,s){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=r,this.pixelStreaming=s,this.responseController=new ww,this.file=new iw,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new Zf(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new Ky(this.pixelStreaming.videoElementParent),this.videoPlayer=new gw(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(a,f)=>{const _={"Resolution.Width":a,"Resolution.Height":f};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(_)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new Wy(this.videoPlayer),this.coordinateConverter=new Sw(this.videoPlayer),this.sendrecvDataChannelController=new Np,this.recvDataChannelController=new Np,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new bw(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new yw,this.webSocketController=new wf,this.webSocketController.onConfig=a=>this.handleOnConfigMessage(a),this.webSocketController.onStreamerList=a=>this.handleStreamerListMessage(a),this.webSocketController.onStreamerIDChanged=a=>this.handleStreamerIDChangedMessage(a),this.webSocketController.onPlayerCount=a=>{this.pixelStreaming._onPlayerCount(a.count)},this.webSocketController.onOpen.addEventListener("open",(()=>{this.config.isFlagEnabled(X.BrowserSendOffer)||this.webSocketController.requestStreamerList()})),this.webSocketController.onClose.addEventListener("close",(a=>{const f=this.shouldReconnect&&a.detail.code!=1001&&this.config.getNumericSettingValue(me.MaxReconnectAttempts)>0,_=this.disconnectMessage?this.disconnectMessage:a.detail.reason;this.pixelStreaming._onDisconnect(_,!f&&!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),f&&setTimeout((()=>{this.isReconnecting=!0,this.reconnectAttempt++,this.tryReconnect(a.detail.reason)}),2e3)})),this.sendMessageController=new vw(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new _w(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new fw(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(dt.StreamerId,(a=>{a!==""&&(this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=a,this.webSocketController.sendSubscribe(a))})),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>{let a=this.config.getTextSettingValue(qr.SignallingServerUrl);return this.config.isFlagEnabled(X.BrowserSendOffer)&&(a+="?"+X.BrowserSendOffer+"=true"),a}}requestUnquantizedAndDenormalizeUnsigned(r,s){return this.coordinateConverter.unquantizeAndDenormalizeUnsigned(r,s)}handleOnMessage(r){const s=new Uint8Array(r.data);T.Log(T.GetStackTrace(),"Message incoming:"+s,6);const a=this.streamMessageController.fromStreamerMessages.get(s[0]);this.streamMessageController.fromStreamerHandlers.get(a)(r.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(be.FromStreamer,"QualityControlOwnership",(r=>this.onQualityControlOwnership(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"Response",(r=>this.responseController.onResponse(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"Command",(r=>{this.onCommand(r)})),this.streamMessageController.registerMessageHandler(be.FromStreamer,"FreezeFrame",(r=>this.onFreezeFrameMessage(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"UnfreezeFrame",(()=>this.invalidateFreezeFrameAndEnableVideo())),this.streamMessageController.registerMessageHandler(be.FromStreamer,"VideoEncoderAvgQP",(r=>this.handleVideoEncoderAvgQP(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"LatencyTest",(r=>this.handleLatencyTestResult(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"DataChannelLatencyTest",(r=>this.handleDataChannelLatencyTestResponse(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"InitialSettings",(r=>this.handleInitialSettings(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"FileExtension",(r=>this.onFileExtension(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"FileMimeType",(r=>this.onFileMimeType(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"FileContents",(r=>this.onFileContents(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(be.FromStreamer,"InputControlOwnership",(r=>this.onInputControlOwnership(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"GamepadResponse",(r=>this.onGamepadResponse(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"Protocol",(r=>this.onProtocolMessage(r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"IFrameRequest",(()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"RequestQualityControl",(()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"FpsRequest",(()=>this.sendMessageController.sendMessageToStreamer("FpsRequest"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"AverageBitrateRequest",(()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"StartStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StartStreaming"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"StopStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StopStreaming"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"LatencyTest",(r=>this.sendMessageController.sendMessageToStreamer("LatencyTest",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"RequestInitialSettings",(()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(be.ToStreamer,"UIInteraction",(r=>this.sendMessageController.sendMessageToStreamer("UIInteraction",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"Command",(r=>this.sendMessageController.sendMessageToStreamer("Command",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"TextboxEntry",(r=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"KeyDown",(r=>this.sendMessageController.sendMessageToStreamer("KeyDown",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"KeyUp",(r=>this.sendMessageController.sendMessageToStreamer("KeyUp",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"KeyPress",(r=>this.sendMessageController.sendMessageToStreamer("KeyPress",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseEnter",(r=>this.sendMessageController.sendMessageToStreamer("MouseEnter",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseLeave",(r=>this.sendMessageController.sendMessageToStreamer("MouseLeave",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseDown",(r=>this.sendMessageController.sendMessageToStreamer("MouseDown",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseUp",(r=>this.sendMessageController.sendMessageToStreamer("MouseUp",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseMove",(r=>this.sendMessageController.sendMessageToStreamer("MouseMove",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseWheel",(r=>this.sendMessageController.sendMessageToStreamer("MouseWheel",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseDouble",(r=>this.sendMessageController.sendMessageToStreamer("MouseDouble",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"TouchStart",(r=>this.sendMessageController.sendMessageToStreamer("TouchStart",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"TouchEnd",(r=>this.sendMessageController.sendMessageToStreamer("TouchEnd",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"TouchMove",(r=>this.sendMessageController.sendMessageToStreamer("TouchMove",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"GamepadConnected",(()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"GamepadButtonPressed",(r=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"GamepadButtonReleased",(r=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"GamepadAnalog",(r=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"GamepadDisconnected",(r=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XREyeViews",(r=>this.sendMessageController.sendMessageToStreamer("XREyeViews",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRHMDTransform",(r=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRControllerTransform",(r=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRSystem",(r=>this.sendMessageController.sendMessageToStreamer("XRSystem",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRButtonTouched",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRButtonTouchReleased",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRButtonPressed",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRButtonReleased",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRAnalog",(r=>this.sendMessageController.sendMessageToStreamer("XRAnalog",r)))}onCommand(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.Command",6);const s=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),"Data Channel Command: "+s,6);const a=JSON.parse(s);a.command==="onScreenKeyboard"&&this.pixelStreaming._activateOnScreenKeyboard(a)}onProtocolMessage(r){try{const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s);Object.prototype.hasOwnProperty.call(a,"Direction")||T.Error(T.GetStackTrace(),"Malformed protocol received. Ensure the protocol message contains a direction");const f=a.Direction;delete a.Direction,T.Log(T.GetStackTrace(),`Received new ${f==be.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(a).forEach((_=>{const C=a[_];switch(f){case be.ToStreamer:if(!Object.prototype.hasOwnProperty.call(C,"id"))return void T.Error(T.GetStackTrace(),`ToStreamer->${_} protocol definition was malformed as it didn't contain at least an id
|
|
2884
|
+
${this.PreCaptureTimeMs}`,6),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class ho{static setExtensionFromBytes(r,s){s.receiving||(s.mimetype="",s.extension="",s.receiving=!0,s.valid=!1,s.chunks=0,s.data=[],s.timestampStart=new Date().getTime(),T.Log(T.GetStackTrace(),"Received first chunk of file",6));const a=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),a,6),s.extension=a}static setMimeTypeFromBytes(r,s){s.receiving||(s.mimetype="",s.extension="",s.receiving=!0,s.valid=!1,s.chunks=0,s.data=[],s.timestampStart=new Date().getTime(),T.Log(T.GetStackTrace(),"Received first chunk of file",6));const a=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),a,6),s.mimetype=a}static setContentsFromBytes(r,s){if(!s.receiving)return;s.chunks=Math.ceil(new DataView(r.slice(1,5).buffer).getInt32(0,!0)/16379);const a=r.slice(5);if(s.data.push(a),T.Log(T.GetStackTrace(),`Received file chunk: ${s.data.length}/${s.chunks}`,6),s.data.length===s.chunks){s.receiving=!1,s.valid=!0,T.Log(T.GetStackTrace(),"Received complete file",6);const f=new Date().getTime()-s.timestampStart,_=Math.round(16384*s.chunks/f);T.Log(T.GetStackTrace(),`Average transfer bitrate: ${_}kb/s over ${f/1e3} seconds`,6);const C=new Blob(s.data,{type:s.mimetype}),R=document.createElement("a");R.setAttribute("href",URL.createObjectURL(C)),R.setAttribute("download",`transfer.${s.extension}`),document.body.append(R),R.remove()}else s.data.length>s.chunks&&(s.receiving=!1,T.Error(T.GetStackTrace(),`Received bigger file than advertised: ${s.data.length}/${s.chunks}`))}}class aw{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}}class zt{}zt.mainButton=0,zt.auxiliaryButton=1,zt.secondaryButton=2,zt.fourthButton=3,zt.fifthButton=4;class Vt{}Vt.primaryButton=1,Vt.secondaryButton=2,Vt.auxiliaryButton=4,Vt.fourthButton=8,Vt.fifthButton=16;class pn{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(r){this.unregisterCallbacks.push(r)}unregisterAll(){for(const r of this.unregisterCallbacks)r();this.unregisterCallbacks=[]}}class ow{constructor(r,s,a){this.touchEventListenerTracker=new pn,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a;const f=R=>this.onTouchStart(R),_=R=>this.onTouchEnd(R),C=R=>this.onTouchMove(R);document.addEventListener("touchstart",f,{passive:!1}),document.addEventListener("touchend",_,{passive:!1}),document.addEventListener("touchmove",C,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchend",_))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",C)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}setVideoElementParentClientRect(r){this.videoElementParentClientRect=r}onTouchStart(r){if(this.videoElementProvider.isVideoReady()&&r.target===this.videoElementProvider.getVideoElement()){if(this.fakeTouchFinger==null){const s=r.changedTouches[0];this.fakeTouchFinger=new lw(s.identifier,s.clientX-this.videoElementParentClientRect.left,s.clientY-this.videoElementParentClientRect.top);const a=this.videoElementProvider.getVideoParentElement(),f=new MouseEvent("mouseenter",s);a.dispatchEvent(f);const _=this.coordinateConverter.normalizeAndQuantizeUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([zt.mainButton,_.x,_.y])}r.preventDefault()}}onTouchEnd(r){if(!this.videoElementProvider.isVideoReady()||this.fakeTouchFinger==null)return;const s=this.videoElementProvider.getVideoParentElement(),a=this.toStreamerMessagesProvider.toStreamerHandlers;for(let f=0;f<r.changedTouches.length;f++){const _=r.changedTouches[f];if(_.identifier===this.fakeTouchFinger.id){const C=_.clientX-this.videoElementParentClientRect.left,R=_.clientY-this.videoElementParentClientRect.top,S=this.coordinateConverter.normalizeAndQuantizeUnsigned(C,R);a.get("MouseUp")([zt.mainButton,S.x,S.y]);const N=new MouseEvent("mouseleave",_);s.dispatchEvent(N),this.fakeTouchFinger=null;break}}r.preventDefault()}onTouchMove(r){if(!this.videoElementProvider.isVideoReady()||this.fakeTouchFinger==null)return;const s=this.toStreamerMessagesProvider.toStreamerHandlers;for(let a=0;a<r.touches.length;a++){const f=r.touches[a];if(f.identifier===this.fakeTouchFinger.id){const _=f.clientX-this.videoElementParentClientRect.left,C=f.clientY-this.videoElementParentClientRect.top,R=this.coordinateConverter.normalizeAndQuantizeUnsigned(_,C),S=this.coordinateConverter.normalizeAndQuantizeSigned(_-this.fakeTouchFinger.x,C-this.fakeTouchFinger.y);s.get("MouseMove")([R.x,R.y,S.x,S.y]),this.fakeTouchFinger.x=_,this.fakeTouchFinger.y=C;break}}r.preventDefault()}}class lw{constructor(r,s,a){this.id=r,this.x=s,this.y=a}}class Gt{}Gt.backSpace=8,Gt.shift=16,Gt.control=17,Gt.alt=18,Gt.rightShift=253,Gt.rightControl=254,Gt.rightAlt=255;class uw{constructor(r,s,a){this.keyboardEventListenerTracker=new pn,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=r,this.config=s,this.activeKeysProvider=a}registerKeyBoardEvents(){const r=_=>this.handleOnCompositionEnd(_),s=_=>this.handleOnKeyDown(_),a=_=>this.handleOnKeyUp(_),f=_=>this.handleOnKeyPress(_);document.addEventListener("compositionend",r),document.addEventListener("keydown",s),document.addEventListener("keyup",a),document.addEventListener("keypress",f),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("compositionend",r))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keydown",s))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keyup",a))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keypress",f)))}unregisterKeyBoardEvents(){this.keyboardEventListenerTracker.unregisterAll()}handleOnKeyDown(r){const s=this.getKeycode(r);s&&s!==229&&(T.Log(T.GetStackTrace(),`key down ${s}, repeat = ${r.repeat}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyDown")([this.getKeycode(r),r.repeat?1:0]),this.activeKeysProvider.getActiveKeys().push(s),s===Gt.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:Gt.backSpace})),this.config.isFlagEnabled(X.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(s)&&r.preventDefault())}handleOnKeyUp(r){const s=this.getKeycode(r);s&&(T.Log(T.GetStackTrace(),`key up ${s}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyUp")([s]),this.config.isFlagEnabled(X.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(s)&&r.preventDefault())}handleOnKeyPress(r){if(!("charCode"in r))return void T.Warning(T.GetStackTrace(),"KeyboardEvent.charCode is deprecated in this browser, cannot send key press.");const s=r.charCode;T.Log(T.GetStackTrace(),`key press ${s}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyPress")([s])}handleOnCompositionEnd(r){r.data&&r.data.length&&r.data.split("").forEach((s=>{this.handleOnKeyDown(new KeyboardEvent("keydown",{keyCode:s.toUpperCase().charCodeAt(0),charCode:s.charCodeAt(0)})),this.handleOnKeyPress(new KeyboardEvent("keypress",{keyCode:s.toUpperCase().charCodeAt(0),charCode:s.charCodeAt(0)})),this.handleOnKeyUp(new KeyboardEvent("keyup",{keyCode:s.toUpperCase().charCodeAt(0),charCode:s.charCodeAt(0)}))}))}getKeycode(r){if(!("keyCode"in r)){const s=r;return s.code in this.CodeToKeyCode?this.CodeToKeyCode[s.code]:(T.Warning(T.GetStackTrace(),`Keyboard code of ${s.code} is not supported in our mapping, ignoring this key.`),null)}return r.keyCode===Gt.shift&&r.code==="ShiftRight"?Gt.rightShift:r.keyCode===Gt.control&&r.code==="ControlRight"?Gt.rightControl:r.keyCode===Gt.alt&&r.code==="AltRight"?Gt.rightAlt:r.keyCode}isKeyCodeBrowserKey(r){return r>=112&&r<=123||r===9}}class dw{constructor(r,s,a){this.x=0,this.y=0,this.updateMouseMovePositionEvent=_=>{this.updateMouseMovePosition(_)},this.mouseEventListenerTracker=new pn,this.videoElementProvider=r,this.mouseController=s,this.activeKeysProvider=a;const f=this.videoElementProvider.getVideoParentElement();this.x=f.getBoundingClientRect().width/2,this.y=f.getBoundingClientRect().height/2,this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y)}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}lockStateChange(){const r=this.videoElementProvider.getVideoParentElement(),s=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers;if(document.pointerLockElement===r||document.mozPointerLockElement===r)T.Log(T.GetStackTrace(),"Pointer locked",6),document.addEventListener("mousemove",this.updateMouseMovePositionEvent,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1)));else{T.Log(T.GetStackTrace(),"The pointer lock status is now unlocked",6),document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1);let a=this.activeKeysProvider.getActiveKeys();const f=new Set(a),_=[];f.forEach((C=>{})),_.forEach((C=>{s.get("KeyUp")([C])})),a=[]}}updateMouseMovePosition(r){if(!this.videoElementProvider.isVideoReady())return;const s=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers,a=this.videoElementProvider.getVideoParentElement().clientWidth,f=this.videoElementProvider.getVideoParentElement().clientHeight;this.x+=r.movementX,this.y+=r.movementY,this.x>a&&(this.x-=a),this.y>f&&(this.y-=f),this.x<0&&(this.x=a+this.x),this.y<0&&(this.y=f-this.y),this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y);const _=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(r.movementX,r.movementY);s.get("MouseMove")([this.coord.x,this.coord.y,_.x,_.y])}handleMouseDown(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([r.button,this.coord.x,this.coord.y])}handleMouseUp(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r.button,this.coord.x,this.coord.y])}handleMouseWheel(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([r.wheelDelta,this.coord.x,this.coord.y])}handleMouseDouble(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([r.button,this.coord.x,this.coord.y])}handlePressMouseButtons(r){this.videoElementProvider.isVideoReady()&&this.mouseController.pressMouseButtons(r.buttons,this.x,this.y)}handleReleaseMouseButtons(r){this.videoElementProvider.isVideoReady()&&this.mouseController.releaseMouseButtons(r.buttons,this.x,this.y)}}class cw{constructor(r){this.mouseController=r}unregisterMouseEvents(){}updateMouseMovePosition(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),"MouseMove",6);const s=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY),a=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(r.movementX,r.movementY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseMove")([s.x,s.y,a.x,a.y]),r.preventDefault()}handleMouseDown(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),"onMouse Down",6);const s=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([r.button,s.x,s.y]),r.preventDefault()}handleMouseUp(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),"onMouse Up",6);const s=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r.button,s.x,s.y]),r.preventDefault()}handleContextMenu(r){this.mouseController.videoElementProvider.isVideoReady()&&r.preventDefault()}handleMouseWheel(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;const s=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([r.wheelDelta,s.x,s.y]),r.preventDefault()}handleMouseDouble(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;const s=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([r.button,s.x,s.y])}handlePressMouseButtons(r){this.mouseController.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"onMouse press",6),this.mouseController.pressMouseButtons(r.buttons,r.offsetX,r.offsetY))}handleReleaseMouseButtons(r){this.mouseController.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"onMouse release",6),this.mouseController.releaseMouseButtons(r.buttons,r.offsetX,r.offsetY))}}class hw{constructor(r,s,a,f){this.mouseEventListenerTracker=new pn,this.toStreamerMessagesProvider=r,this.coordinateConverter=a,this.videoElementProvider=s,this.activeKeysProvider=f,this.registerMouseEnterAndLeaveEvents()}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}registerLockedMouseEvents(r){const s=this.videoElementProvider.getVideoParentElement(),a=new dw(this.videoElementProvider,r,this.activeKeysProvider);if(s.requestPointerLock=s.requestPointerLock||s.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,s.requestPointerLock){const N=()=>{s.requestPointerLock()};s.addEventListener("click",N),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("click",N)))}const f=()=>a.lockStateChange();document.addEventListener("pointerlockchange",f,!1),document.addEventListener("mozpointerlockchange",f,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("pointerlockchange",f,!1))),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mozpointerlockchange",f,!1)));const _=N=>a.handleMouseDown(N),C=N=>a.handleMouseUp(N),R=N=>a.handleMouseWheel(N),S=N=>a.handleMouseDouble(N);s.addEventListener("mousedown",_),s.addEventListener("mouseup",C),s.addEventListener("wheel",R),s.addEventListener("dblclick",S),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousedown",_))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mouseup",C))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("wheel",R))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("dblclick",S))),this.mouseEventListenerTracker.addUnregisterCallback((()=>a.unregisterMouseEvents())),this.mouseEventListenerTracker.addUnregisterCallback((()=>{!document.exitPointerLock||document.pointerLockElement!==s&&document.mozPointerLockElement!==s||document.exitPointerLock()}))}registerHoveringMouseEvents(r){const s=this.videoElementProvider.getVideoParentElement(),a=new cw(r),f=z=>a.updateMouseMovePosition(z),_=z=>a.handleMouseDown(z),C=z=>a.handleMouseUp(z),R=z=>a.handleContextMenu(z),S=z=>a.handleMouseWheel(z),N=z=>a.handleMouseDouble(z);s.addEventListener("mousemove",f),s.addEventListener("mousedown",_),s.addEventListener("mouseup",C),s.addEventListener("contextmenu",R),s.addEventListener("wheel",S),s.addEventListener("dblclick",N),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousemove",f))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousedown",_))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mouseup",C))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("contextmenu",R))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("wheel",S))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("dblclick",N))),this.mouseEventListenerTracker.addUnregisterCallback((()=>a.unregisterMouseEvents()))}registerMouseEnterAndLeaveEvents(){const r=this.videoElementProvider.getVideoParentElement(),s=f=>{this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"Mouse Entered",6),this.sendMouseEnter(),this.pressMouseButtons(f.buttons,f.x,f.y))},a=f=>{this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"Mouse Left",6),this.sendMouseLeave(),this.releaseMouseButtons(f.buttons,f.x,f.y))};r.addEventListener("mouseenter",s),r.addEventListener("mouseleave",a),this.mouseEventListenerTracker.addUnregisterCallback((()=>r.removeEventListener("mouseenter",s))),this.mouseEventListenerTracker.addUnregisterCallback((()=>r.removeEventListener("mouseleave",a)))}releaseMouseButtons(r,s,a){const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);r&Vt.primaryButton&&this.sendMouseUp(zt.mainButton,f.x,f.y),r&Vt.secondaryButton&&this.sendMouseUp(zt.secondaryButton,f.x,f.y),r&Vt.auxiliaryButton&&this.sendMouseUp(zt.auxiliaryButton,f.x,f.y),r&Vt.fourthButton&&this.sendMouseUp(zt.fourthButton,f.x,f.y),r&Vt.fifthButton&&this.sendMouseUp(zt.fifthButton,f.x,f.y)}pressMouseButtons(r,s,a){if(!this.videoElementProvider.isVideoReady())return;const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);r&Vt.primaryButton&&this.sendMouseDown(zt.mainButton,f.x,f.y),r&Vt.secondaryButton&&this.sendMouseDown(zt.secondaryButton,f.x,f.y),r&Vt.auxiliaryButton&&this.sendMouseDown(zt.auxiliaryButton,f.x,f.y),r&Vt.fourthButton&&this.sendMouseDown(zt.fourthButton,f.x,f.y),r&Vt.fifthButton&&this.sendMouseDown(zt.fifthButton,f.x,f.y)}sendMouseEnter(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseEnter")()}sendMouseLeave(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseLeave")()}sendMouseDown(r,s,a){this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),`mouse button ${r} down at (${s}, ${a})`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([r,s,a]))}sendMouseUp(r,s,a){if(!this.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),`mouse button ${r} up at (${s}, ${a})`,6);const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r,f.x,f.y])}}class pw{constructor(r,s,a){this.fingers=[9,8,7,6,5,4,3,2,1,0],this.fingerIds=new Map,this.maxByteValue=255,this.touchEventListenerTracker=new pn,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a,this.videoElementParent=s.getVideoElement();const f=S=>this.onTouchStart(S),_=S=>this.onTouchEnd(S),C=S=>this.onTouchMove(S);this.videoElementParent.addEventListener("touchstart",f),this.videoElementParent.addEventListener("touchend",_),this.videoElementParent.addEventListener("touchmove",C),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchend",_))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchmove",C))),T.Log(T.GetStackTrace(),"Touch Events Registered",6);const R=S=>{S.preventDefault()};document.addEventListener("touchmove",R),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",R)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}rememberTouch(r){const s=this.fingers.pop();s===void 0&&T.Log(T.GetStackTrace(),"exhausted touch identifiers",6),this.fingerIds.set(r.identifier,s)}forgetTouch(r){this.fingers.push(this.fingerIds.get(r.identifier)),this.fingers.sort((function(s,a){return a-s})),this.fingerIds.delete(r.identifier)}onTouchStart(r){if(this.videoElementProvider.isVideoReady()){for(let s=0;s<r.changedTouches.length;s++)this.rememberTouch(r.changedTouches[s]);T.Log(T.GetStackTrace(),"touch start",6),this.emitTouchData("TouchStart",r.changedTouches),r.preventDefault()}}onTouchEnd(r){if(this.videoElementProvider.isVideoReady()){T.Log(T.GetStackTrace(),"touch end",6),this.emitTouchData("TouchEnd",r.changedTouches);for(let s=0;s<r.changedTouches.length;s++)this.forgetTouch(r.changedTouches[s]);r.preventDefault()}}onTouchMove(r){this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"touch move",6),this.emitTouchData("TouchMove",r.touches),r.preventDefault())}emitTouchData(r,s){if(!this.videoElementProvider.isVideoReady())return;const a=this.videoElementProvider.getVideoParentElement().getBoundingClientRect(),f=this.toStreamerMessagesProvider.toStreamerHandlers;for(let _=0;_<s.length;_++){const R=s[_],S=R.clientX-a.left,N=R.clientY-a.top;T.Log(T.GetStackTrace(),`F${this.fingerIds.get(R.identifier)}=(${S}, ${N})`,6);const z=this.coordinateConverter.normalizeAndQuantizeUnsigned(S,N);switch(r){case"TouchStart":f.get("TouchStart")([1,z.x,z.y,this.fingerIds.get(R.identifier),this.maxByteValue*(R.force>0?R.force:1),z.inRange?1:0]);break;case"TouchEnd":f.get("TouchEnd")([1,z.x,z.y,this.fingerIds.get(R.identifier),this.maxByteValue*R.force,z.inRange?1:0]);break;case"TouchMove":f.get("TouchMove")([1,z.x,z.y,this.fingerIds.get(R.identifier),this.maxByteValue*(R.force>0?R.force:1),z.inRange?1:0])}}}}class fw{constructor(r){this.gamePadEventListenerTracker=new pn,this.toStreamerMessagesProvider=r,this.requestAnimationFrame=(window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.requestAnimationFrame).bind(window);const s=window;if(window.addEventListener("beforeunload",(a=>this.onBeforeUnload(a))),"GamepadEvent"in s){const a=_=>this.gamePadConnectHandler(_),f=_=>this.gamePadDisconnectHandler(_);window.addEventListener("gamepadconnected",a),window.addEventListener("gamepaddisconnected",f),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepadconnected",a))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepaddisconnected",f)))}else if("WebKitGamepadEvent"in s){const a=_=>this.gamePadConnectHandler(_),f=_=>this.gamePadDisconnectHandler(_);window.addEventListener("webkitgamepadconnected",a),window.addEventListener("webkitgamepaddisconnected",f),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepadconnected",a))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepaddisconnected",f)))}if(this.controllers=[],navigator.getGamepads)for(const a of navigator.getGamepads())a&&this.gamePadConnectHandler(new GamepadEvent("gamepadconnected",{gamepad:a}))}unregisterGamePadEvents(){this.gamePadEventListenerTracker.unregisterAll();for(const r of this.controllers)r.id!==void 0&&this.onGamepadDisconnected(r.id);this.controllers=[],this.onGamepadConnected=()=>{},this.onGamepadDisconnected=()=>{}}gamePadConnectHandler(r){T.Log(T.GetStackTrace(),"Gamepad connect handler",6);const s=r.gamepad,a={currentState:s,prevState:s,id:void 0};this.controllers.push(a),this.controllers[s.index].currentState=s,this.controllers[s.index].prevState=s,T.Log(T.GetStackTrace(),"gamepad: "+s.id+" connected",6),window.requestAnimationFrame((()=>this.updateStatus())),this.onGamepadConnected()}gamePadDisconnectHandler(r){T.Log(T.GetStackTrace(),"Gamepad disconnect handler",6),T.Log(T.GetStackTrace(),"gamepad: "+r.gamepad.id+" disconnected",6);const s=this.controllers[r.gamepad.index];delete this.controllers[r.gamepad.index],this.controllers=this.controllers.filter((a=>a!==void 0)),this.onGamepadDisconnected(s.id)}scanGamePads(){const r=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[];for(let s=0;s<r.length;s++)r[s]&&r[s].index in this.controllers&&(this.controllers[r[s].index].currentState=r[s])}updateStatus(){this.scanGamePads();const r=this.toStreamerMessagesProvider.toStreamerHandlers;for(const s of this.controllers){const a=s.id===void 0?this.controllers.indexOf(s):s.id,f=s.currentState;for(let _=0;_<s.currentState.buttons.length;_++){const C=s.currentState.buttons[_],R=s.prevState.buttons[_];C.pressed?_==cn.LeftTrigger?r.get("GamepadAnalog")([a,5,C.value]):_==cn.RightTrigger?r.get("GamepadAnalog")([a,6,C.value]):r.get("GamepadButtonPressed")([a,_,R.pressed?1:0]):!C.pressed&&R.pressed&&(_==cn.LeftTrigger?r.get("GamepadAnalog")([a,5,0]):_==cn.RightTrigger?r.get("GamepadAnalog")([a,6,0]):r.get("GamepadButtonReleased")([a,_,0]))}for(let _=0;_<f.axes.length;_+=2){const C=parseFloat(f.axes[_].toFixed(4)),R=-parseFloat(f.axes[_+1].toFixed(4));r.get("GamepadAnalog")([a,_+1,C]),r.get("GamepadAnalog")([a,_+2,R])}this.controllers[a].prevState=f}this.controllers.length>0&&this.requestAnimationFrame((()=>this.updateStatus()))}onGamepadResponseReceived(r){for(const s of this.controllers)if(s.id===void 0){s.id=r;break}}onGamepadConnected(){}onGamepadDisconnected(r){}onBeforeUnload(r){for(const s of this.controllers)this.onGamepadDisconnected(s.id)}}(function(d){d[d.RightClusterBottomButton=0]="RightClusterBottomButton",d[d.RightClusterRightButton=1]="RightClusterRightButton",d[d.RightClusterLeftButton=2]="RightClusterLeftButton",d[d.RightClusterTopButton=3]="RightClusterTopButton",d[d.LeftShoulder=4]="LeftShoulder",d[d.RightShoulder=5]="RightShoulder",d[d.LeftTrigger=6]="LeftTrigger",d[d.RightTrigger=7]="RightTrigger",d[d.SelectOrBack=8]="SelectOrBack",d[d.StartOrForward=9]="StartOrForward",d[d.LeftAnalogPress=10]="LeftAnalogPress",d[d.RightAnalogPress=11]="RightAnalogPress",d[d.LeftClusterTopButton=12]="LeftClusterTopButton",d[d.LeftClusterBottomButton=13]="LeftClusterBottomButton",d[d.LeftClusterLeftButton=14]="LeftClusterLeftButton",d[d.LeftClusterRightButton=15]="LeftClusterRightButton",d[d.CentreButton=16]="CentreButton",d[d.LeftStickHorizontal=0]="LeftStickHorizontal",d[d.LeftStickVertical=1]="LeftStickVertical",d[d.RightStickHorizontal=2]="RightStickHorizontal",d[d.RightStickVertical=3]="RightStickVertical"})(cn||(cn={}));class mw{constructor(r,s,a){this.activeKeys=new gw,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a}registerKeyBoard(r){T.Log(T.GetStackTrace(),"Register Keyboard Events",7);const s=new uw(this.toStreamerMessagesProvider,r,this.activeKeys);return s.registerKeyBoardEvents(),s}registerMouse(r){T.Log(T.GetStackTrace(),"Register Mouse Events",7);const s=new hw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys);switch(r){case Us.LockedMouse:s.registerLockedMouseEvents(s);break;case Us.HoveringMouse:s.registerHoveringMouseEvents(s);break;default:T.Info(T.GetStackTrace(),"unknown Control Scheme Type Defaulting to Locked Mouse Events"),s.registerLockedMouseEvents(s)}return s}registerTouch(r,s){if(T.Log(T.GetStackTrace(),"Registering Touch",6),r){const a=new ow(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return a.setVideoElementParentClientRect(s),a}return new pw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return T.Log(T.GetStackTrace(),"Register Game Pad",7),new fw(this.toStreamerMessagesProvider)}}class gw{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class yw{constructor(r,s){this.lastTimeResized=new Date().getTime(),this.videoElement=document.createElement("video"),this.config=s,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",r.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(r){this.audioElement=r}play(){return this.videoElement.muted=this.config.isFlagEnabled(X.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(X.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(r){this.videoElement.srcObject.getTracks().forEach((s=>s.enabled=r))}onVideoInitialized(){}onOrientationChange(){clearTimeout(this.orientationChangeTimeout),this.orientationChangeTimeout=window.setTimeout((()=>{this.resizePlayerStyle()}),500)}resizePlayerStyle(){const r=this.getVideoParentElement();r&&(this.updateVideoStreamSize(),r.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(X.MatchViewportResolution))if(new Date().getTime()-this.lastTimeResized>300){const r=this.getVideoParentElement();if(!r)return;this.onMatchViewportResolutionCallback(r.clientWidth,r.clientHeight),this.lastTimeResized=new Date().getTime()}else T.Log(T.GetStackTrace(),"Resizing too often - skipping",6),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout((()=>this.updateVideoStreamSize()),100)}}class ww{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(r,s,a){switch(r){case Se.ToStreamer:this.toStreamerHandlers.set(s,a);break;case Se.FromStreamer:this.fromStreamerHandlers.set(s,a);break;default:T.Log(T.GetStackTrace(),`Unknown message direction ${r}`)}}}(function(d){d[d.ToStreamer=0]="ToStreamer",d[d.FromStreamer=1]="FromStreamer"})(Se||(Se={}));class vw{constructor(){this.responseEventListeners=new Map}addResponseEventListener(r,s){this.responseEventListeners.set(r,s)}removeResponseEventListener(r){this.responseEventListeners.delete(r)}onResponse(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.Response",6);const s=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),s,6),this.responseEventListeners.forEach((a=>{a(s)}))}}class _w{constructor(r,s){this.dataChannelSender=r,this.toStreamerMessagesMapProvider=s}sendMessageToStreamer(r,s){s===void 0&&(s=[]);const a=this.toStreamerMessagesMapProvider.toStreamerMessages.get(r);if(a===void 0)return void T.Error(T.GetStackTrace(),`Attempted to send a message to the streamer with message type: ${r}, but the frontend hasn't been configured to send such a message. Check you've added the message type in your cpp`);if(a.structure&&s&&a.structure.length!==s.length)return void T.Error(T.GetStackTrace(),`Provided message data doesn't match expected layout. Expected [ ${a.structure.map((S=>{switch(S){case"uint8":case"uint16":case"int16":case"float":case"double":return"number";case"string":return"string"}})).toString()} ] but received [ ${s.map((S=>typeof S)).toString()} ]`);let f=0;const _=new TextEncoder;s.forEach(((S,N)=>{switch(a.structure[N]){case"uint8":f+=1;break;case"uint16":case"int16":f+=2;break;case"float":f+=4;break;case"double":f+=8;break;case"string":f+=2,f+=2*_.encode(S).length}}));const C=new DataView(new ArrayBuffer(f+1));C.setUint8(0,a.id);let R=1;s.forEach(((S,N)=>{switch(a.structure[N]){case"uint8":C.setUint8(R,S),R+=1;break;case"uint16":C.setUint16(R,S,!0),R+=2;break;case"int16":C.setInt16(R,S,!0),R+=2;break;case"float":C.setFloat32(R,S,!0),R+=4;break;case"double":C.setFloat64(R,S,!0),R+=8;break;case"string":C.setUint16(R,S.length,!0),R+=2;for(let z=0;z<S.length;z++)C.setUint16(R,S.charCodeAt(z),!0),R+=2}})),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(C.buffer):T.Info(T.GetStackTrace(),`Data channel cannot send yet, skipping sending message: ${r} - ${new Uint8Array(C.buffer)}`)}}class bw{constructor(r){this.sendMessageController=r}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 Sw{constructor(r){this.dataChannelProvider=r}canSend(){return this.dataChannelProvider.getDataChannelInstance().dataChannel!==void 0&&this.dataChannelProvider.getDataChannelInstance().dataChannel.readyState=="open"}sendData(r){const s=this.dataChannelProvider.getDataChannelInstance();s.dataChannel.readyState=="open"?(s.dataChannel.send(r),T.Log(T.GetStackTrace(),`Message Sent: ${new Uint8Array(r)}`,6),this.resetAfkWarningTimerOnDataSend()):T.Error(T.GetStackTrace(),`Message Failed: ${new Uint8Array(r)}`)}resetAfkWarningTimerOnDataSend(){}}class Tw{constructor(r){this.videoElementProvider=r,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(r,s){return this.normalizeAndQuantizeUnsignedFunc(r,s)}unquantizeAndDenormalizeUnsigned(r,s){return this.denormalizeAndUnquantizeUnsignedFunc(r,s)}normalizeAndQuantizeSigned(r,s){return this.normalizeAndQuantizeSignedFunc(r,s)}setupNormalizeAndQuantize(){if(this.videoElementParent=this.videoElementProvider.getVideoParentElement(),this.videoElement=this.videoElementProvider.getVideoElement(),this.videoElementParent&&this.videoElement){const r=this.videoElementParent.clientWidth||1,s=this.videoElementParent.clientHeight||1,a=this.videoElement.videoWidth||1,f=s/r,_=(this.videoElement.videoHeight||1)/a;f>_?(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio > videoAspectRatio",6),this.ratio=f/_,this.normalizeAndQuantizeUnsignedFunc=(C,R)=>this.normalizeAndQuantizeUnsignedPlayerBigger(C,R),this.normalizeAndQuantizeSignedFunc=(C,R)=>this.normalizeAndQuantizeSignedPlayerBigger(C,R),this.denormalizeAndUnquantizeUnsignedFunc=(C,R)=>this.denormalizeAndUnquantizeUnsignedPlayerBigger(C,R)):(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio <= videoAspectRatio",6),this.ratio=_/f,this.normalizeAndQuantizeUnsignedFunc=(C,R)=>this.normalizeAndQuantizeUnsignedPlayerSmaller(C,R),this.normalizeAndQuantizeSignedFunc=(C,R)=>this.normalizeAndQuantizeSignedPlayerSmaller(C,R),this.denormalizeAndUnquantizeUnsignedFunc=(C,R)=>this.denormalizeAndUnquantizeUnsignedPlayerSmaller(C,R))}}normalizeAndQuantizeUnsignedPlayerBigger(r,s){const a=r/this.videoElementParent.clientWidth,f=this.ratio*(s/this.videoElementParent.clientHeight-.5)+.5;return a<0||a>1||f<0||f>1?new Oi(!1,65535,65535):new Oi(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerBigger(r,s){const a=r/65536,f=(s/65536-.5)/this.ratio+.5;return new $o(a*this.videoElementParent.clientWidth,f*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerBigger(r,s){const a=r/(.5*this.videoElementParent.clientWidth),f=this.ratio*s/(.5*this.videoElementParent.clientHeight);return new Vp(32767*a,32767*f)}normalizeAndQuantizeUnsignedPlayerSmaller(r,s){const a=this.ratio*(r/this.videoElementParent.clientWidth-.5)+.5,f=s/this.videoElementParent.clientHeight;return a<0||a>1||f<0||f>1?new Oi(!1,65535,65535):new Oi(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerSmaller(r,s){const a=(r/65536-.5)/this.ratio+.5,f=s/65536;return new $o(a*this.videoElementParent.clientWidth,f*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerSmaller(r,s){const a=this.ratio*r/(.5*this.videoElementParent.clientWidth),f=s/(.5*this.videoElementParent.clientHeight);return new Vp(32767*a,32767*f)}}class Oi{constructor(r,s,a){this.inRange=r,this.x=s,this.y=a}}class $o{constructor(r,s){this.x=r,this.y=s}}class Vp{constructor(r,s){this.x=r,this.y=s}}class dm{constructor(r,s){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=r,this.pixelStreaming=s,this.responseController=new vw,this.file=new aw,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new Zf(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new Ky(this.pixelStreaming.videoElementParent),this.videoPlayer=new yw(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(a,f)=>{const _={"Resolution.Width":a,"Resolution.Height":f};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(_)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new Hy(this.videoPlayer),this.coordinateConverter=new Tw(this.videoPlayer),this.sendrecvDataChannelController=new Np,this.recvDataChannelController=new Np,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new Sw(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new ww,this.webSocketController=new wf,this.webSocketController.onConfig=a=>this.handleOnConfigMessage(a),this.webSocketController.onStreamerList=a=>this.handleStreamerListMessage(a),this.webSocketController.onStreamerIDChanged=a=>this.handleStreamerIDChangedMessage(a),this.webSocketController.onPlayerCount=a=>{this.pixelStreaming._onPlayerCount(a.count)},this.webSocketController.onOpen.addEventListener("open",(()=>{this.config.isFlagEnabled(X.BrowserSendOffer)||this.webSocketController.requestStreamerList()})),this.webSocketController.onClose.addEventListener("close",(a=>{const f=this.shouldReconnect&&a.detail.code!=1001&&this.config.getNumericSettingValue(ge.MaxReconnectAttempts)>0,_=this.disconnectMessage?this.disconnectMessage:a.detail.reason;this.pixelStreaming._onDisconnect(_,!f&&!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),f&&setTimeout((()=>{this.isReconnecting=!0,this.reconnectAttempt++,this.tryReconnect(a.detail.reason)}),2e3)})),this.sendMessageController=new _w(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new bw(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new mw(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(dt.StreamerId,(a=>{a!==""&&(this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=a,this.webSocketController.sendSubscribe(a))})),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>{let a=this.config.getTextSettingValue(Kr.SignallingServerUrl);return this.config.isFlagEnabled(X.BrowserSendOffer)&&(a+="?"+X.BrowserSendOffer+"=true"),a}}requestUnquantizedAndDenormalizeUnsigned(r,s){return this.coordinateConverter.unquantizeAndDenormalizeUnsigned(r,s)}handleOnMessage(r){const s=new Uint8Array(r.data);T.Log(T.GetStackTrace(),"Message incoming:"+s,6);const a=this.streamMessageController.fromStreamerMessages.get(s[0]);this.streamMessageController.fromStreamerHandlers.get(a)(r.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(Se.FromStreamer,"QualityControlOwnership",(r=>this.onQualityControlOwnership(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"Response",(r=>this.responseController.onResponse(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"Command",(r=>{this.onCommand(r)})),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"FreezeFrame",(r=>this.onFreezeFrameMessage(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"UnfreezeFrame",(()=>this.invalidateFreezeFrameAndEnableVideo())),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"VideoEncoderAvgQP",(r=>this.handleVideoEncoderAvgQP(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"LatencyTest",(r=>this.handleLatencyTestResult(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"DataChannelLatencyTest",(r=>this.handleDataChannelLatencyTestResponse(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"InitialSettings",(r=>this.handleInitialSettings(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"FileExtension",(r=>this.onFileExtension(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"FileMimeType",(r=>this.onFileMimeType(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"FileContents",(r=>this.onFileContents(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"InputControlOwnership",(r=>this.onInputControlOwnership(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"GamepadResponse",(r=>this.onGamepadResponse(r))),this.streamMessageController.registerMessageHandler(Se.FromStreamer,"Protocol",(r=>this.onProtocolMessage(r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"IFrameRequest",(()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest"))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"RequestQualityControl",(()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl"))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"FpsRequest",(()=>this.sendMessageController.sendMessageToStreamer("FpsRequest"))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"AverageBitrateRequest",(()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest"))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"StartStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StartStreaming"))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"StopStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StopStreaming"))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"LatencyTest",(r=>this.sendMessageController.sendMessageToStreamer("LatencyTest",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"RequestInitialSettings",(()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings"))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"UIInteraction",(r=>this.sendMessageController.sendMessageToStreamer("UIInteraction",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"Command",(r=>this.sendMessageController.sendMessageToStreamer("Command",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"TextboxEntry",(r=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"KeyDown",(r=>this.sendMessageController.sendMessageToStreamer("KeyDown",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"KeyUp",(r=>this.sendMessageController.sendMessageToStreamer("KeyUp",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"KeyPress",(r=>this.sendMessageController.sendMessageToStreamer("KeyPress",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"MouseEnter",(r=>this.sendMessageController.sendMessageToStreamer("MouseEnter",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"MouseLeave",(r=>this.sendMessageController.sendMessageToStreamer("MouseLeave",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"MouseDown",(r=>this.sendMessageController.sendMessageToStreamer("MouseDown",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"MouseUp",(r=>this.sendMessageController.sendMessageToStreamer("MouseUp",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"MouseMove",(r=>this.sendMessageController.sendMessageToStreamer("MouseMove",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"MouseWheel",(r=>this.sendMessageController.sendMessageToStreamer("MouseWheel",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"MouseDouble",(r=>this.sendMessageController.sendMessageToStreamer("MouseDouble",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"TouchStart",(r=>this.sendMessageController.sendMessageToStreamer("TouchStart",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"TouchEnd",(r=>this.sendMessageController.sendMessageToStreamer("TouchEnd",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"TouchMove",(r=>this.sendMessageController.sendMessageToStreamer("TouchMove",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"GamepadConnected",(()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected"))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"GamepadButtonPressed",(r=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"GamepadButtonReleased",(r=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"GamepadAnalog",(r=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"GamepadDisconnected",(r=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"XREyeViews",(r=>this.sendMessageController.sendMessageToStreamer("XREyeViews",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"XRHMDTransform",(r=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"XRControllerTransform",(r=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"XRSystem",(r=>this.sendMessageController.sendMessageToStreamer("XRSystem",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"XRButtonTouched",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"XRButtonTouchReleased",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"XRButtonPressed",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"XRButtonReleased",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",r))),this.streamMessageController.registerMessageHandler(Se.ToStreamer,"XRAnalog",(r=>this.sendMessageController.sendMessageToStreamer("XRAnalog",r)))}onCommand(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.Command",6);const s=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),"Data Channel Command: "+s,6);const a=JSON.parse(s);a.command==="onScreenKeyboard"&&this.pixelStreaming._activateOnScreenKeyboard(a)}onProtocolMessage(r){try{const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s);Object.prototype.hasOwnProperty.call(a,"Direction")||T.Error(T.GetStackTrace(),"Malformed protocol received. Ensure the protocol message contains a direction");const f=a.Direction;delete a.Direction,T.Log(T.GetStackTrace(),`Received new ${f==Se.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(a).forEach((_=>{const C=a[_];switch(f){case Se.ToStreamer:if(!Object.prototype.hasOwnProperty.call(C,"id"))return void T.Error(T.GetStackTrace(),`ToStreamer->${_} protocol definition was malformed as it didn't contain at least an id
|
|
2885
2885
|
|
|
2886
|
-
Definition was: ${JSON.stringify(C,null,2)}`);if(_==="UIInteraction"||_==="Command"||_==="LatencyTest")return;this.streamMessageController.toStreamerHandlers.get(_)?this.streamMessageController.toStreamerMessages.set(_,C):T.Error(T.GetStackTrace(),`There was no registered handler for "${_}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${_}", myHandler)`);break;case
|
|
2886
|
+
Definition was: ${JSON.stringify(C,null,2)}`);if(_==="UIInteraction"||_==="Command"||_==="LatencyTest")return;this.streamMessageController.toStreamerHandlers.get(_)?this.streamMessageController.toStreamerMessages.set(_,C):T.Error(T.GetStackTrace(),`There was no registered handler for "${_}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${_}", myHandler)`);break;case Se.FromStreamer:if(!Object.prototype.hasOwnProperty.call(C,"id"))return void T.Error(T.GetStackTrace(),`FromStreamer->${_} protocol definition was malformed as it didn't contain at least an id
|
|
2887
2887
|
|
|
2888
|
-
Definition was: ${JSON.stringify(C,null,2)}`);this.streamMessageController.fromStreamerHandlers.get(_)?this.streamMessageController.fromStreamerMessages.set(C.id,_):T.Error(T.GetStackTrace(),`There was no registered handler for "${C}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${_}", myHandler)`);break;default:T.Error(T.GetStackTrace(),`Unknown direction: ${f}`)}})),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(s){T.Log(T.GetStackTrace(),s)}}onInputControlOwnership(r){const s=new Uint8Array(r);T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.InputControlOwnership",6);const a=new Boolean(s[1]).valueOf();T.Log(T.GetStackTrace(),`Received input controller message - will your input control the stream: ${a}`),this.pixelStreaming._onInputControlOwnership(a)}onGamepadResponse(r){const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s);this.gamePadController.onGamepadResponseReceived(a.controllerId)}onAfkTriggered(){this.afkController.onAfkClick(),this.videoPlayer.isPaused()&&this.videoPlayer.hasVideoSource()&&this.playStream()}setAfkEnabled(r){r?this.onAfkTriggered():this.afkController.stopAfkWarningTimer()}tryReconnect(r){this.webSocketController?(this.isReconnecting=!0,this.webSocketController.webSocket&&this.webSocketController.webSocket.readyState!=WebSocket.CLOSED?(this.closeSignalingServer(`${r} Restarting stream...`),setTimeout((()=>{this.tryReconnect(r)}),3e3)):(this.pixelStreaming._onWebRtcAutoConnect(),this.connectToSignallingServer())):T.Log(T.GetStackTrace(),"The Web Socket Controller does not exist so this will not work right now.")}loadFreezeFrameOrShowPlayOverlay(){this.pixelStreaming.dispatchEvent(new Uf({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),this.shouldShowPlayOverlay===!0?(T.Log(T.GetStackTrace(),"showing play overlay"),this.resizePlayerStyle()):(T.Log(T.GetStackTrace(),"showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout((()=>{this.videoPlayer.setVideoEnabled(!1)}),this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6);const s=new Uint8Array(r);this.freezeFrameController.processFreezeFrameMessage(s,(()=>this.loadFreezeFrameOrShowPlayOverlay()))}invalidateFreezeFrameAndEnableVideo(){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6),setTimeout((()=>{this.pixelStreaming.dispatchEvent(new Ff),this.freezeFrameController.hideFreezeFrame()}),this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(r){const s=new Uint8Array(r);ho.setExtensionFromBytes(s,this.file)}onFileMimeType(r){const s=new Uint8Array(r);ho.setMimeTypeFromBytes(s,this.file)}onFileContents(r){const s=new Uint8Array(r);ho.setContentsFromBytes(s,this.file)}playStream(){if(!this.videoPlayer.getVideoElement()){const r="Could not play video stream because the video player was not initialized correctly.";return this.pixelStreaming.dispatchEvent(new Bf({message:r})),T.Error(T.GetStackTrace(),r),void this.closeSignalingServer("Stream not initialized correctly")}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(X.TouchInput)),this.pixelStreaming.dispatchEvent(new Nf),this.streamController.audioElement.srcObject){const r=this.config.isFlagEnabled(X.StartVideoMuted);this.streamController.audioElement.muted=r,r?this.playVideo():this.streamController.audioElement.play().then((()=>{this.playVideo()})).catch((s=>{T.Log(T.GetStackTrace(),s),T.Log(T.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 To({reason:s}))}))}else this.playVideo();this.shouldShowPlayOverlay=!1,this.freezeFrameController.showFreezeFrame()}else T.Warning(T.GetStackTrace(),"Cannot play stream, the video element has no srcObject to play.")}playVideo(){this.videoPlayer.play().catch((r=>{this.streamController.audioElement.srcObject&&this.streamController.audioElement.pause(),T.Log(T.GetStackTrace(),r),T.Log(T.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 To({reason:r}))}))}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(X.AutoPlayVideo)&&this.playStream(),this.resizePlayerStyle()}connectToSignallingServer(){this.locallyClosed=!1,this.shouldReconnect=!0,this.disconnectMessage=null;const r=this.signallingUrlBuilder();this.webSocketController.connect(r)}startSession(r){if(this.peerConfig=r,this.config.isFlagEnabled(X.ForceTURN)&&!this.checkTurnServerAvailability(r))return T.Info(T.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 sw(this.peerConfig,this.config,this.preferredCodec),this.peerConnectionController.onVideoStats=a=>this.handleVideoStats(a),this.peerConnectionController.onSendWebRTCOffer=a=>this.handleSendWebRTCOffer(a),this.peerConnectionController.onSendWebRTCAnswer=a=>this.handleSendWebRTCAnswer(a),this.peerConnectionController.onPeerIceCandidate=a=>this.handleSendIceCandidate(a),this.peerConnectionController.onDataChannel=a=>this.handleDataChannel(a),this.peerConnectionController.showTextOverlayConnecting=()=>this.pixelStreaming._onWebRtcConnecting(),this.peerConnectionController.showTextOverlaySetupFailure=()=>this.pixelStreaming._onWebRtcFailed();let s=!1;this.peerConnectionController.onIceConnectionStateChange=()=>{!s&&["connected","completed"].includes(this.peerConnectionController.peerConnection.iceConnectionState)&&(this.pixelStreaming._onWebRtcConnected(),s=!0)},this.peerConnectionController.onTrack=a=>this.streamController.handleOnTrack(a),this.config.isFlagEnabled(X.BrowserSendOffer)&&(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"cirrus",this.datachannelOptions),this.sendrecvDataChannelController.handleOnMessage=a=>this.handleOnMessage(a),this.peerConnectionController.createOffer(this.sdpConstraints,this.config))}checkTurnServerAvailability(r){if(!r.iceServers)return T.Info(T.GetStackTrace(),"A turn sever was not found"),!1;for(const s of r.iceServers)for(const a of s.urls)if(a.includes("turn"))return T.Log(T.GetStackTrace(),`A turn sever was found at ${a}`),!0;return T.Info(T.GetStackTrace(),"A turn sever was not found"),!1}handleOnConfigMessage(r){this.resizePlayerStyle(),this.startSession(r.peerConnectionOptions),this.webSocketController.onWebRtcAnswer=s=>this.handleWebRtcAnswer(s),this.webSocketController.onWebRtcOffer=s=>this.handleWebRtcOffer(s),this.webSocketController.onWebRtcPeerDataChannels=s=>this.handleWebRtcSFUPeerDatachannels(s),this.webSocketController.onIceCandidate=s=>this.handleIceCandidate(s)}handleStreamerListMessage(r){T.Log(T.GetStackTrace(),`Got streamer list ${r.ids}`,6);let s=null;var a=this.config.getSettingOption(dt.StreamerId);a.selected.toString().trim()&&(s=a.selected);const f=[...r.ids];f.unshift(""),this.config.setOptionSettingOptions(dt.StreamerId,f);let _=null;const C=this.config.isFlagEnabled(X.WaitForStreamer),R=this.config.getNumericSettingValue(me.MaxReconnectAttempts),b=this.config.getNumericSettingValue(me.StreamerAutoJoinInterval),U=this.config.useUrlParams,z=new URLSearchParams(window.location.search);U&&z.has(dt.StreamerId)?s=z.get(dt.StreamerId):this.subscribedStream&&(s=this.subscribedStream),s&&r.ids.includes(s)?_=s:s&&C||r.ids.length!=1||(_=r.ids[0]),_?(this.isReconnecting=!1,this.reconnectAttempt=0,this.config.setOptionSettingValue(dt.StreamerId,_)):C&&(this.reconnectAttempt<R?(this.isReconnecting=!0,this.reconnectAttempt++,setTimeout((()=>{this.webSocketController.requestStreamerList()}),b)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.shouldReconnect=!1)),this.pixelStreaming.dispatchEvent(new Gf({messageStreamerList:r,autoSelectedStreamerId:_,wantedStreamerId:s}))}handleStreamerIDChangedMessage(r){const s=r.newID;var a=this.config.getSettingOption(dt.StreamerId),f=a.onChange;a.onChange=()=>{};for(var _=a.options,C=0;C<_.length;++C)if(_[C]==this.subscribedStream){_[C]=s;break}a.options=_,a.selected=s,a.onChange=f,this.subscribedStream=r.newID,this.pixelStreaming.dispatchEvent(new qf({newID:s}))}handleWebRtcAnswer(r){T.Log(T.GetStackTrace(),`Got answer sdp ${r.sdp}`,6);const s={sdp:r.sdp,type:"answer"};this.peerConnectionController.receiveAnswer(s),this.handlePostWebrtcNegotiation()}handleWebRtcOffer(r){T.Log(T.GetStackTrace(),`Got offer sdp ${r.sdp}`,6),this.isUsingSFU=!!r.sfu&&r.sfu,this.isUsingSFU&&(this.peerConnectionController.preferredCodec="");const s={sdp:r.sdp,type:"offer"};this.peerConnectionController.receiveOffer(s,this.config),this.handlePostWebrtcNegotiation()}handleWebRtcSFUPeerDatachannels(r){const s={ordered:!0,negotiated:!0,id:r.sendStreamId},a=r.sendStreamId!=r.recvStreamId;if(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,a?"send-datachannel":"datachannel",s),a){const f={ordered:!0,negotiated:!0,id:r.recvStreamId};this.recvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"recv-datachannel",f),this.recvDataChannelController.handleOnOpen=()=>this.webSocketController.sendSFURecvDataChannelReady(),this.recvDataChannelController.handleOnMessage=_=>this.handleOnMessage(_)}else this.sendrecvDataChannelController.handleOnMessage=f=>this.handleOnMessage(f)}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(X.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(X.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(X.GamepadInput))}handleIceCandidate(r){T.Log(T.GetStackTrace(),"Web RTC Controller: onWebRtcIce",6);const s=new RTCIceCandidate(r);this.peerConnectionController.handleOnIce(s)}handleSendIceCandidate(r){T.Log(T.GetStackTrace(),"OnIceCandidate",6),r.candidate&&r.candidate.candidate&&this.webSocketController.sendIceCandidate(r.candidate)}handleDataChannel(r){T.Log(T.GetStackTrace(),"Data channel created for us by browser as we are a receiving peer.",6),this.sendrecvDataChannelController.dataChannel=r.channel,this.sendrecvDataChannelController.setupDataChannel(),this.sendrecvDataChannelController.handleOnMessage=s=>this.handleOnMessage(s)}handleSendWebRTCOffer(r){T.Log(T.GetStackTrace(),"Sending the offer to the Server",6);const s={minBitrateBps:1e3*this.config.getNumericSettingValue(me.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(me.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcOffer(r,s)}handleSendWebRTCAnswer(r){T.Log(T.GetStackTrace(),"Sending the answer to the Server",6);const s={minBitrateBps:1e3*this.config.getNumericSettingValue(me.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(me.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcAnswer(r,s),this.isUsingSFU&&this.webSocketController.sendWebRtcDatachannelRequest()}setUpMouseAndFreezeFrame(){this.videoElementParentClientRect=this.videoPlayer.getVideoParentElement().getBoundingClientRect(),this.coordinateConverter.setupNormalizeAndQuantize(),this.freezeFrameController.freezeFrame.resize()}closeSignalingServer(r){var s;this.locallyClosed=!0,this.shouldReconnect=!1,this.disconnectMessage=r,(s=this.webSocketController)===null||s===void 0||s.close()}closePeerConnection(){var r;(r=this.peerConnectionController)===null||r===void 0||r.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(r){this.streamMessageController.toStreamerHandlers.get("DataChannelLatencyTest")([JSON.stringify(r)])}sendEncoderMinQP(r){T.Log(T.GetStackTrace(),`MinQP=${r}
|
|
2888
|
+
Definition was: ${JSON.stringify(C,null,2)}`);this.streamMessageController.fromStreamerHandlers.get(_)?this.streamMessageController.fromStreamerMessages.set(C.id,_):T.Error(T.GetStackTrace(),`There was no registered handler for "${C}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${_}", myHandler)`);break;default:T.Error(T.GetStackTrace(),`Unknown direction: ${f}`)}})),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(s){T.Log(T.GetStackTrace(),s)}}onInputControlOwnership(r){const s=new Uint8Array(r);T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.InputControlOwnership",6);const a=new Boolean(s[1]).valueOf();T.Log(T.GetStackTrace(),`Received input controller message - will your input control the stream: ${a}`),this.pixelStreaming._onInputControlOwnership(a)}onGamepadResponse(r){const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s);this.gamePadController.onGamepadResponseReceived(a.controllerId)}onAfkTriggered(){this.afkController.onAfkClick(),this.videoPlayer.isPaused()&&this.videoPlayer.hasVideoSource()&&this.playStream()}setAfkEnabled(r){r?this.onAfkTriggered():this.afkController.stopAfkWarningTimer()}tryReconnect(r){this.webSocketController?(this.isReconnecting=!0,this.webSocketController.webSocket&&this.webSocketController.webSocket.readyState!=WebSocket.CLOSED?(this.closeSignalingServer(`${r} Restarting stream...`),setTimeout((()=>{this.tryReconnect(r)}),3e3)):(this.pixelStreaming._onWebRtcAutoConnect(),this.connectToSignallingServer())):T.Log(T.GetStackTrace(),"The Web Socket Controller does not exist so this will not work right now.")}loadFreezeFrameOrShowPlayOverlay(){this.pixelStreaming.dispatchEvent(new Uf({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),this.shouldShowPlayOverlay===!0?(T.Log(T.GetStackTrace(),"showing play overlay"),this.resizePlayerStyle()):(T.Log(T.GetStackTrace(),"showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout((()=>{this.videoPlayer.setVideoEnabled(!1)}),this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6);const s=new Uint8Array(r);this.freezeFrameController.processFreezeFrameMessage(s,(()=>this.loadFreezeFrameOrShowPlayOverlay()))}invalidateFreezeFrameAndEnableVideo(){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6),setTimeout((()=>{this.pixelStreaming.dispatchEvent(new Ff),this.freezeFrameController.hideFreezeFrame()}),this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(r){const s=new Uint8Array(r);ho.setExtensionFromBytes(s,this.file)}onFileMimeType(r){const s=new Uint8Array(r);ho.setMimeTypeFromBytes(s,this.file)}onFileContents(r){const s=new Uint8Array(r);ho.setContentsFromBytes(s,this.file)}playStream(){if(!this.videoPlayer.getVideoElement()){const r="Could not play video stream because the video player was not initialized correctly.";return this.pixelStreaming.dispatchEvent(new Bf({message:r})),T.Error(T.GetStackTrace(),r),void this.closeSignalingServer("Stream not initialized correctly")}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(X.TouchInput)),this.pixelStreaming.dispatchEvent(new Nf),this.streamController.audioElement.srcObject){const r=this.config.isFlagEnabled(X.StartVideoMuted);this.streamController.audioElement.muted=r,r?this.playVideo():this.streamController.audioElement.play().then((()=>{this.playVideo()})).catch((s=>{T.Log(T.GetStackTrace(),s),T.Log(T.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 To({reason:s}))}))}else this.playVideo();this.shouldShowPlayOverlay=!1,this.freezeFrameController.showFreezeFrame()}else T.Warning(T.GetStackTrace(),"Cannot play stream, the video element has no srcObject to play.")}playVideo(){this.videoPlayer.play().catch((r=>{this.streamController.audioElement.srcObject&&this.streamController.audioElement.pause(),T.Log(T.GetStackTrace(),r),T.Log(T.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 To({reason:r}))}))}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(X.AutoPlayVideo)&&this.playStream(),this.resizePlayerStyle()}connectToSignallingServer(){this.locallyClosed=!1,this.shouldReconnect=!0,this.disconnectMessage=null;const r=this.signallingUrlBuilder();this.webSocketController.connect(r)}startSession(r){if(this.peerConfig=r,this.config.isFlagEnabled(X.ForceTURN)&&!this.checkTurnServerAvailability(r))return T.Info(T.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 nw(this.peerConfig,this.config,this.preferredCodec),this.peerConnectionController.onVideoStats=a=>this.handleVideoStats(a),this.peerConnectionController.onSendWebRTCOffer=a=>this.handleSendWebRTCOffer(a),this.peerConnectionController.onSendWebRTCAnswer=a=>this.handleSendWebRTCAnswer(a),this.peerConnectionController.onPeerIceCandidate=a=>this.handleSendIceCandidate(a),this.peerConnectionController.onDataChannel=a=>this.handleDataChannel(a),this.peerConnectionController.showTextOverlayConnecting=()=>this.pixelStreaming._onWebRtcConnecting(),this.peerConnectionController.showTextOverlaySetupFailure=()=>this.pixelStreaming._onWebRtcFailed();let s=!1;this.peerConnectionController.onIceConnectionStateChange=()=>{!s&&["connected","completed"].includes(this.peerConnectionController.peerConnection.iceConnectionState)&&(this.pixelStreaming._onWebRtcConnected(),s=!0)},this.peerConnectionController.onTrack=a=>this.streamController.handleOnTrack(a),this.config.isFlagEnabled(X.BrowserSendOffer)&&(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"cirrus",this.datachannelOptions),this.sendrecvDataChannelController.handleOnMessage=a=>this.handleOnMessage(a),this.peerConnectionController.createOffer(this.sdpConstraints,this.config))}checkTurnServerAvailability(r){if(!r.iceServers)return T.Info(T.GetStackTrace(),"A turn sever was not found"),!1;for(const s of r.iceServers)for(const a of s.urls)if(a.includes("turn"))return T.Log(T.GetStackTrace(),`A turn sever was found at ${a}`),!0;return T.Info(T.GetStackTrace(),"A turn sever was not found"),!1}handleOnConfigMessage(r){this.resizePlayerStyle(),this.startSession(r.peerConnectionOptions),this.webSocketController.onWebRtcAnswer=s=>this.handleWebRtcAnswer(s),this.webSocketController.onWebRtcOffer=s=>this.handleWebRtcOffer(s),this.webSocketController.onWebRtcPeerDataChannels=s=>this.handleWebRtcSFUPeerDatachannels(s),this.webSocketController.onIceCandidate=s=>this.handleIceCandidate(s)}handleStreamerListMessage(r){T.Log(T.GetStackTrace(),`Got streamer list ${r.ids}`,6);let s=null;var a=this.config.getSettingOption(dt.StreamerId);a.selected.toString().trim()&&(s=a.selected);const f=[...r.ids];f.unshift(""),this.config.setOptionSettingOptions(dt.StreamerId,f);let _=null;const C=this.config.isFlagEnabled(X.WaitForStreamer),R=this.config.getNumericSettingValue(ge.MaxReconnectAttempts),S=this.config.getNumericSettingValue(ge.StreamerAutoJoinInterval),N=this.config.useUrlParams,z=new URLSearchParams(window.location.search);N&&z.has(dt.StreamerId)?s=z.get(dt.StreamerId):this.subscribedStream&&(s=this.subscribedStream),s&&r.ids.includes(s)?_=s:s&&C||r.ids.length!=1||(_=r.ids[0]),_?(this.isReconnecting=!1,this.reconnectAttempt=0,this.config.setOptionSettingValue(dt.StreamerId,_)):C&&(this.reconnectAttempt<R?(this.isReconnecting=!0,this.reconnectAttempt++,setTimeout((()=>{this.webSocketController.requestStreamerList()}),S)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.shouldReconnect=!1)),this.pixelStreaming.dispatchEvent(new Gf({messageStreamerList:r,autoSelectedStreamerId:_,wantedStreamerId:s}))}handleStreamerIDChangedMessage(r){const s=r.newID;var a=this.config.getSettingOption(dt.StreamerId),f=a.onChange;a.onChange=()=>{};for(var _=a.options,C=0;C<_.length;++C)if(_[C]==this.subscribedStream){_[C]=s;break}a.options=_,a.selected=s,a.onChange=f,this.subscribedStream=r.newID,this.pixelStreaming.dispatchEvent(new qf({newID:s}))}handleWebRtcAnswer(r){T.Log(T.GetStackTrace(),`Got answer sdp ${r.sdp}`,6);const s={sdp:r.sdp,type:"answer"};this.peerConnectionController.receiveAnswer(s),this.handlePostWebrtcNegotiation()}handleWebRtcOffer(r){T.Log(T.GetStackTrace(),`Got offer sdp ${r.sdp}`,6),this.isUsingSFU=!!r.sfu&&r.sfu,this.isUsingSFU&&(this.peerConnectionController.preferredCodec="");const s={sdp:r.sdp,type:"offer"};this.peerConnectionController.receiveOffer(s,this.config),this.handlePostWebrtcNegotiation()}handleWebRtcSFUPeerDatachannels(r){const s={ordered:!0,negotiated:!0,id:r.sendStreamId},a=r.sendStreamId!=r.recvStreamId;if(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,a?"send-datachannel":"datachannel",s),a){const f={ordered:!0,negotiated:!0,id:r.recvStreamId};this.recvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"recv-datachannel",f),this.recvDataChannelController.handleOnOpen=()=>this.webSocketController.sendSFURecvDataChannelReady(),this.recvDataChannelController.handleOnMessage=_=>this.handleOnMessage(_)}else this.sendrecvDataChannelController.handleOnMessage=f=>this.handleOnMessage(f)}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(X.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(X.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(X.GamepadInput))}handleIceCandidate(r){T.Log(T.GetStackTrace(),"Web RTC Controller: onWebRtcIce",6);const s=new RTCIceCandidate(r);this.peerConnectionController.handleOnIce(s)}handleSendIceCandidate(r){T.Log(T.GetStackTrace(),"OnIceCandidate",6),r.candidate&&r.candidate.candidate&&this.webSocketController.sendIceCandidate(r.candidate)}handleDataChannel(r){T.Log(T.GetStackTrace(),"Data channel created for us by browser as we are a receiving peer.",6),this.sendrecvDataChannelController.dataChannel=r.channel,this.sendrecvDataChannelController.setupDataChannel(),this.sendrecvDataChannelController.handleOnMessage=s=>this.handleOnMessage(s)}handleSendWebRTCOffer(r){T.Log(T.GetStackTrace(),"Sending the offer to the Server",6);const s={minBitrateBps:1e3*this.config.getNumericSettingValue(ge.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(ge.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcOffer(r,s)}handleSendWebRTCAnswer(r){T.Log(T.GetStackTrace(),"Sending the answer to the Server",6);const s={minBitrateBps:1e3*this.config.getNumericSettingValue(ge.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(ge.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcAnswer(r,s),this.isUsingSFU&&this.webSocketController.sendWebRtcDatachannelRequest()}setUpMouseAndFreezeFrame(){this.videoElementParentClientRect=this.videoPlayer.getVideoParentElement().getBoundingClientRect(),this.coordinateConverter.setupNormalizeAndQuantize(),this.freezeFrameController.freezeFrame.resize()}closeSignalingServer(r){var s;this.locallyClosed=!0,this.shouldReconnect=!1,this.disconnectMessage=r,(s=this.webSocketController)===null||s===void 0||s.close()}closePeerConnection(){var r;(r=this.peerConnectionController)===null||r===void 0||r.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(r){this.streamMessageController.toStreamerHandlers.get("DataChannelLatencyTest")([JSON.stringify(r)])}sendEncoderMinQP(r){T.Log(T.GetStackTrace(),`MinQP=${r}
|
|
2889
2889
|
`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQP":r})])}sendEncoderMaxQP(r){T.Log(T.GetStackTrace(),`MaxQP=${r}
|
|
2890
|
-
`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQP":r})])}sendWebRTCMinBitrate(r){T.Log(T.GetStackTrace(),`WebRTC Min Bitrate=${r}`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MinBitrate":r})])}sendWebRTCMaxBitrate(r){T.Log(T.GetStackTrace(),`WebRTC Max Bitrate=${r}`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxBitrate":r})])}sendWebRTCFps(r){T.Log(T.GetStackTrace(),`WebRTC FPS=${r}`,6),r!=null&&(this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.Fps":r})]),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxFps":r})]))}sendShowFps(){T.Log(T.GetStackTrace(),"---- Sending show stat to UE ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"stat.fps":""})])}sendIframeRequest(){T.Log(T.GetStackTrace(),"---- Sending Request for an IFrame ----",6),this.streamMessageController.toStreamerHandlers.get("IFrameRequest")()}emitUIInteraction(r){T.Log(T.GetStackTrace(),"---- Sending custom UIInteraction message ----",6),this.streamMessageController.toStreamerHandlers.get("UIInteraction")([JSON.stringify(r)])}emitCommand(r){T.Log(T.GetStackTrace(),"---- Sending custom Command message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(r)])}emitConsoleCommand(r){T.Log(T.GetStackTrace(),"---- Sending custom Command:ConsoleCommand message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({ConsoleCommand:r})])}sendRequestQualityControlOwnership(){T.Log(T.GetStackTrace(),"---- Sending Request to Control Quality ----",6),this.toStreamerMessagesController.SendRequestQualityControl()}handleLatencyTestResult(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.latencyTest",6);const s=new TextDecoder("utf-16").decode(r.slice(1)),a=new um;Object.assign(a,JSON.parse(s)),a.processFields(),a.testStartTimeMs=this.latencyStartTime,a.browserReceiptTimeMs=Date.now(),a.latencyExcludingDecode=~~(a.browserReceiptTimeMs-a.testStartTimeMs),a.testDuration=~~(a.TransmissionTimeMs-a.ReceiptTimeMs),a.networkLatency=~~(a.latencyExcludingDecode-a.testDuration),a.frameDisplayDeltaTimeMs&&a.browserReceiptTimeMs&&(a.endToEndLatency=(a.frameDisplayDeltaTimeMs,a.networkLatency,~~+a.CaptureToSendMs)),this.pixelStreaming._onLatencyTestResult(a)}handleDataChannelLatencyTestResponse(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.dataChannelLatencyResponse",6);const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s);this.pixelStreaming._onDataChannelLatencyTestResponse(a)}handleInitialSettings(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.InitialSettings",6);const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s),f=new am;a.Encoder&&(f.EncoderSettings=a.Encoder),a.WebRTC&&(f.WebRTCSettings=a.WebRTC),a.PixelStreaming&&(f.PixelStreamingSettings=a.PixelStreaming),a.ConfigOptions&&a.ConfigOptions.DefaultToHover!==void 0&&this.config.setFlagEnabled(X.HoveringMouseMode,!!a.ConfigOptions.DefaultToHover),f.ueCompatible(),T.Log(T.GetStackTrace(),s,6),this.pixelStreaming._onInitialSettings(f)}handleVideoEncoderAvgQP(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.VideoEncoderAvgQP",6);const s=Number(new TextDecoder("utf-16").decode(r.slice(1)));this.setVideoEncoderAvgQP(s)}handleVideoInitialized(){this.pixelStreaming._onVideoInitialized(),this.autoPlayVideoOrSetUpPlayOverlay(),this.resizePlayerStyle(),this.videoPlayer.updateVideoStreamSize()}onQualityControlOwnership(r){const s=new Uint8Array(r);T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.QualityControlOwnership",6),this.isQualityController=new Boolean(s[1]).valueOf(),T.Log(T.GetStackTrace(),`Received quality controller message, will control quality: ${this.isQualityController}`),this.pixelStreaming._onQualityControlOwnership(this.isQualityController)}handleVideoStats(r){this.pixelStreaming._onVideoStats(r)}resizePlayerStyle(){this.videoPlayer.resizePlayerStyle()}setPreferredCodec(r){this.preferredCodec=r,this.peerConnectionController&&(this.peerConnectionController.preferredCodec=r,this.peerConnectionController.updateCodecSelection=!1)}setVideoEncoderAvgQP(r){this.videoAvgQp=r,this.pixelStreaming._onVideoEncoderAvgQP(this.videoAvgQp)}setKeyboardInputEnabled(r){var s;(s=this.keyboardController)===null||s===void 0||s.unregisterKeyBoardEvents(),r&&(this.keyboardController=this.inputClassesFactory.registerKeyBoard(this.config))}setMouseInputEnabled(r){var s;if((s=this.mouseController)===null||s===void 0||s.unregisterMouseEvents(),r){const a=this.config.isFlagEnabled(X.HoveringMouseMode)?
|
|
2890
|
+
`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQP":r})])}sendWebRTCMinBitrate(r){T.Log(T.GetStackTrace(),`WebRTC Min Bitrate=${r}`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MinBitrate":r})])}sendWebRTCMaxBitrate(r){T.Log(T.GetStackTrace(),`WebRTC Max Bitrate=${r}`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxBitrate":r})])}sendWebRTCFps(r){T.Log(T.GetStackTrace(),`WebRTC FPS=${r}`,6),r!=null&&(this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.Fps":r})]),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxFps":r})]))}sendShowFps(){T.Log(T.GetStackTrace(),"---- Sending show stat to UE ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"stat.fps":""})])}sendIframeRequest(){T.Log(T.GetStackTrace(),"---- Sending Request for an IFrame ----",6),this.streamMessageController.toStreamerHandlers.get("IFrameRequest")()}emitUIInteraction(r){T.Log(T.GetStackTrace(),"---- Sending custom UIInteraction message ----",6),this.streamMessageController.toStreamerHandlers.get("UIInteraction")([JSON.stringify(r)])}emitCommand(r){T.Log(T.GetStackTrace(),"---- Sending custom Command message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(r)])}emitConsoleCommand(r){T.Log(T.GetStackTrace(),"---- Sending custom Command:ConsoleCommand message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({ConsoleCommand:r})])}sendRequestQualityControlOwnership(){T.Log(T.GetStackTrace(),"---- Sending Request to Control Quality ----",6),this.toStreamerMessagesController.SendRequestQualityControl()}handleLatencyTestResult(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.latencyTest",6);const s=new TextDecoder("utf-16").decode(r.slice(1)),a=new um;Object.assign(a,JSON.parse(s)),a.processFields(),a.testStartTimeMs=this.latencyStartTime,a.browserReceiptTimeMs=Date.now(),a.latencyExcludingDecode=~~(a.browserReceiptTimeMs-a.testStartTimeMs),a.testDuration=~~(a.TransmissionTimeMs-a.ReceiptTimeMs),a.networkLatency=~~(a.latencyExcludingDecode-a.testDuration),a.frameDisplayDeltaTimeMs&&a.browserReceiptTimeMs&&(a.endToEndLatency=(a.frameDisplayDeltaTimeMs,a.networkLatency,~~+a.CaptureToSendMs)),this.pixelStreaming._onLatencyTestResult(a)}handleDataChannelLatencyTestResponse(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.dataChannelLatencyResponse",6);const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s);this.pixelStreaming._onDataChannelLatencyTestResponse(a)}handleInitialSettings(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.InitialSettings",6);const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s),f=new am;a.Encoder&&(f.EncoderSettings=a.Encoder),a.WebRTC&&(f.WebRTCSettings=a.WebRTC),a.PixelStreaming&&(f.PixelStreamingSettings=a.PixelStreaming),a.ConfigOptions&&a.ConfigOptions.DefaultToHover!==void 0&&this.config.setFlagEnabled(X.HoveringMouseMode,!!a.ConfigOptions.DefaultToHover),f.ueCompatible(),T.Log(T.GetStackTrace(),s,6),this.pixelStreaming._onInitialSettings(f)}handleVideoEncoderAvgQP(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.VideoEncoderAvgQP",6);const s=Number(new TextDecoder("utf-16").decode(r.slice(1)));this.setVideoEncoderAvgQP(s)}handleVideoInitialized(){this.pixelStreaming._onVideoInitialized(),this.autoPlayVideoOrSetUpPlayOverlay(),this.resizePlayerStyle(),this.videoPlayer.updateVideoStreamSize()}onQualityControlOwnership(r){const s=new Uint8Array(r);T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.QualityControlOwnership",6),this.isQualityController=new Boolean(s[1]).valueOf(),T.Log(T.GetStackTrace(),`Received quality controller message, will control quality: ${this.isQualityController}`),this.pixelStreaming._onQualityControlOwnership(this.isQualityController)}handleVideoStats(r){this.pixelStreaming._onVideoStats(r)}resizePlayerStyle(){this.videoPlayer.resizePlayerStyle()}setPreferredCodec(r){this.preferredCodec=r,this.peerConnectionController&&(this.peerConnectionController.preferredCodec=r,this.peerConnectionController.updateCodecSelection=!1)}setVideoEncoderAvgQP(r){this.videoAvgQp=r,this.pixelStreaming._onVideoEncoderAvgQP(this.videoAvgQp)}setKeyboardInputEnabled(r){var s;(s=this.keyboardController)===null||s===void 0||s.unregisterKeyBoardEvents(),r&&(this.keyboardController=this.inputClassesFactory.registerKeyBoard(this.config))}setMouseInputEnabled(r){var s;if((s=this.mouseController)===null||s===void 0||s.unregisterMouseEvents(),r){const a=this.config.isFlagEnabled(X.HoveringMouseMode)?Us.HoveringMouse:Us.LockedMouse;this.mouseController=this.inputClassesFactory.registerMouse(a)}}setTouchInputEnabled(r){var s;(s=this.touchController)===null||s===void 0||s.unregisterTouchEvents(),r&&(this.touchController=this.inputClassesFactory.registerTouch(this.config.isFlagEnabled(X.FakeMouseWithTouches),this.videoElementParentClientRect))}setGamePadInputEnabled(r){var s;(s=this.gamePadController)===null||s===void 0||s.unregisterGamePadEvents(),r&&(this.gamePadController=this.inputClassesFactory.registerGamePad(),this.gamePadController.onGamepadConnected=()=>{this.streamMessageController.toStreamerHandlers.get("GamepadConnected")()},this.gamePadController.onGamepadDisconnected=a=>{this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([a])})}registerDataChannelEventEmitters(r){r.onOpen=(s,a)=>this.pixelStreaming.dispatchEvent(new Af({label:s,event:a})),r.onClose=(s,a)=>this.pixelStreaming.dispatchEvent(new If({label:s,event:a})),r.onError=(s,a)=>this.pixelStreaming.dispatchEvent(new Mf({label:s,event:a}))}registerMessageHandler(r,s,a){s===Se.FromStreamer&&a===void 0&&T.Warning(T.GetStackTrace(),`Unable to register handler for ${r} as no handler was passed`),this.streamMessageController.registerMessageHandler(s,r,(f=>a===void 0&&s===Se.ToStreamer?this.sendMessageController.sendMessageToStreamer(r,f):a(f)))}}class Fi{constructor(r){this.toStreamerMessagesProvider=r,this.controllers=[]}static deepCopyGamepad(r){return JSON.parse(JSON.stringify({buttons:r.buttons.map((s=>JSON.parse(JSON.stringify({pressed:s.pressed,touched:s.touched,value:s.value})))),axes:r.axes}))}updateStatus(r,s,a){if(r.gamepad){const f=s.getPose(r.gripSpace,a);if(!f)return;let _=0;r.profiles.includes("htc-vive")?_=1:r.profiles.includes("oculus-touch")&&(_=2),this.toStreamerMessagesProvider.toStreamerHandlers.get("XRSystem")([_]);let C=2;switch(r.handedness){case"left":C=0;break;case"right":C=1}const R=f.transform.matrix,S=[];for(let j=0;j<16;j++)S[j]=new Float32Array([R[j]])[0];this.toStreamerMessagesProvider.toStreamerHandlers.get("XRControllerTransform")([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],C]),this.controllers[C]===void 0&&(this.controllers[C]={prevState:void 0,currentState:void 0,id:void 0},this.controllers[C].prevState=Fi.deepCopyGamepad(r.gamepad)),this.controllers[C].currentState=Fi.deepCopyGamepad(r.gamepad);const N=this.controllers[C],z=N.currentState,te=N.prevState;for(let j=0;j<z.buttons.length;j++){const se=z.buttons[j],J=te.buttons[j];if(se.pressed){let Y=J.pressed?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonPressed")([C,j,Y])}else J.pressed&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonReleased")([C,j,0]);if(se.touched){let Y=J.touched?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouched")([C,j,Y])}else J.touched&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouchReleased")([C,j,0])}for(let j=0;j<z.axes.length;j++){let se=z.axes[j];se!=te.axes[j]&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRAnalog")([C,j,se])}this.controllers[C].prevState=z}}}class cm{constructor(r){this.xrViewerPose=null,this.videoTexture=null,this.prevVideoWidth=0,this.prevVideoHeight=0,this.leftView=null,this.rightView=null,this.xrSession=null,this.webRtcController=r,this.xrGamepadController=new Fi(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 T.Error(T.GetStackTrace(),"This browser does not support XR.");navigator.xr.requestSession("immersive-vr",{optionalFeatures:[]}).then((r=>{this.onXrSessionStarted(r)}))}}onXrSessionEnded(){T.Log(T.GetStackTrace(),"XR Session ended"),this.xrSession=null,this.onSessionEnded.dispatchEvent(new Event("xrSessionEnded"))}initGL(){if(this.gl)return;const r=document.createElement("canvas");this.gl=r.getContext("webgl2",{xrCompatible:!0}),this.gl.clearColor(0,0,0,1)}initShaders(){const r=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(r,`
|
|
2891
2891
|
attribute vec2 a_position;
|
|
2892
2892
|
attribute vec2 a_texCoord;
|
|
2893
2893
|
|
|
@@ -2912,7 +2912,7 @@ Msg: ${s}`;console.warn(a)}}T.verboseLogLevel=5,(function(d){d.LIST_STREAMERS="l
|
|
|
2912
2912
|
void main() {
|
|
2913
2913
|
gl_FragColor = texture2D(u_image, v_texCoord);
|
|
2914
2914
|
}
|
|
2915
|
-
`),this.gl.compileShader(s);const a=this.gl.createProgram();this.gl.attachShader(a,r),this.gl.attachShader(a,s),this.gl.linkProgram(a),this.gl.useProgram(a),this.positionLocation=this.gl.getAttribLocation(a,"a_position"),this.texcoordLocation=this.gl.getAttribLocation(a,"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 r=this.webRtcController.videoPlayer.getVideoElement().videoHeight,s=this.webRtcController.videoPlayer.getVideoElement().videoWidth;this.prevVideoHeight!=r||this.prevVideoWidth!=s?this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,s,r,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()):this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,0,0,s,r,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()),this.prevVideoHeight=r,this.prevVideoWidth=s}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(r){T.Log(T.GetStackTrace(),"XR Session started"),this.xrSession=r,this.xrSession.addEventListener("end",(()=>{this.onXrSessionEnded()})),this.initGL(),this.initShaders(),this.initBuffers(),r.requestReferenceSpace("local").then((s=>{if(this.xrRefSpace=s,this.xrSession.updateRenderState({baseLayer:new XRWebGLLayer(this.xrSession,this.gl)}),this.xrSession.supportedFrameRates)for(let a of this.xrSession.supportedFrameRates)a==90&&r.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 r=this.leftView.transform.matrix,s=this.leftView.projectionMatrix,a=this.rightView.transform.matrix,f=this.rightView.projectionMatrix;this.webRtcController.streamMessageController.toStreamerHandlers.get("XREyeViews")([r[0],r[4],r[8],r[12],r[1],r[5],r[9],r[13],r[2],r[6],r[10],r[14],r[3],r[7],r[11],r[15],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],a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15],f[0],f[4],f[8],f[12],f[1],f[5],f[9],f[13],f[2],f[6],f[10],f[14],f[3],f[7],f[11],f[15]])}onXrFrame(r,s){if(this.xrViewerPose=s.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(X.XRControllerInput)&&this.xrSession.inputSources.forEach(((a,f,_)=>{this.xrGamepadController.updateStatus(a,s,this.xrRefSpace)}),this),this.xrSession.requestAnimationFrame(((a,f)=>this.onXrFrame(a,f))),this.onFrame.dispatchEvent(new Qf({time:r,frame:s}))}updateViews(){if(this.xrViewerPose)for(const r of this.xrViewerPose.views)r.eye==="left"?this.leftView=r:r.eye==="right"&&(this.rightView=r)}render(){if(!this.gl)return;const r=this.xrSession.renderState.baseLayer;this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,r.framebuffer),this.gl.viewport(0,0,r.framebufferWidth,r.framebufferHeight),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}static isSessionSupported(r){return location.protocol!=="https:"&&T.Info(null,"WebXR requires https, if you want WebXR use https."),navigator.xr?navigator.xr.isSessionSupported(r):new Promise((()=>!1))}}class
|
|
2915
|
+
`),this.gl.compileShader(s);const a=this.gl.createProgram();this.gl.attachShader(a,r),this.gl.attachShader(a,s),this.gl.linkProgram(a),this.gl.useProgram(a),this.positionLocation=this.gl.getAttribLocation(a,"a_position"),this.texcoordLocation=this.gl.getAttribLocation(a,"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 r=this.webRtcController.videoPlayer.getVideoElement().videoHeight,s=this.webRtcController.videoPlayer.getVideoElement().videoWidth;this.prevVideoHeight!=r||this.prevVideoWidth!=s?this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,s,r,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()):this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,0,0,s,r,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()),this.prevVideoHeight=r,this.prevVideoWidth=s}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(r){T.Log(T.GetStackTrace(),"XR Session started"),this.xrSession=r,this.xrSession.addEventListener("end",(()=>{this.onXrSessionEnded()})),this.initGL(),this.initShaders(),this.initBuffers(),r.requestReferenceSpace("local").then((s=>{if(this.xrRefSpace=s,this.xrSession.updateRenderState({baseLayer:new XRWebGLLayer(this.xrSession,this.gl)}),this.xrSession.supportedFrameRates)for(let a of this.xrSession.supportedFrameRates)a==90&&r.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 r=this.leftView.transform.matrix,s=this.leftView.projectionMatrix,a=this.rightView.transform.matrix,f=this.rightView.projectionMatrix;this.webRtcController.streamMessageController.toStreamerHandlers.get("XREyeViews")([r[0],r[4],r[8],r[12],r[1],r[5],r[9],r[13],r[2],r[6],r[10],r[14],r[3],r[7],r[11],r[15],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],a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15],f[0],f[4],f[8],f[12],f[1],f[5],f[9],f[13],f[2],f[6],f[10],f[14],f[3],f[7],f[11],f[15]])}onXrFrame(r,s){if(this.xrViewerPose=s.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(X.XRControllerInput)&&this.xrSession.inputSources.forEach(((a,f,_)=>{this.xrGamepadController.updateStatus(a,s,this.xrRefSpace)}),this),this.xrSession.requestAnimationFrame(((a,f)=>this.onXrFrame(a,f))),this.onFrame.dispatchEvent(new Qf({time:r,frame:s}))}updateViews(){if(this.xrViewerPose)for(const r of this.xrViewerPose.views)r.eye==="left"?this.leftView=r:r.eye==="right"&&(this.rightView=r)}render(){if(!this.gl)return;const r=this.xrSession.renderState.baseLayer;this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,r.framebuffer),this.gl.viewport(0,0,r.framebufferWidth,r.framebufferHeight),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}static isSessionSupported(r){return location.protocol!=="https:"&&T.Info(null,"WebXR requires https, if you want WebXR use https."),navigator.xr?navigator.xr.isSessionSupported(r):new Promise((()=>!1))}}class Ew{constructor(r){this.editTextButton=null,this.hiddenInput=null,"ontouchstart"in document.documentElement&&this.createOnScreenKeyboardHelpers(r)}unquantizeAndDenormalizeUnsigned(r,s){return null}createOnScreenKeyboardHelpers(r){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",r.appendChild(this.hiddenInput)),this.editTextButton||(this.editTextButton=document.createElement("button"),this.editTextButton.id="editTextButton",this.editTextButton.innerHTML="edit text",r.appendChild(this.editTextButton),this.editTextButton.style.display="none",this.editTextButton.addEventListener("touchend",(s=>{this.hiddenInput.focus(),s.preventDefault()})))}showOnScreenKeyboard(r){if(r.showOnScreenKeyboard){this.editTextButton.style.display="default";const s=this.unquantizeAndDenormalizeUnsigned(r.x,r.y);this.editTextButton.style.top=s.y.toString()+"px",this.editTextButton.style.left=(s.x-40).toString()+"px"}else this.editTextButton.style.display="none",this.hiddenInput.blur()}}class $w{constructor(r){this.seq=r.Seq,this.playerSentTimestamp=Date.now(),this.requestFillerSize=r.Filler?r.Filler.length:0}update(r){this.playerReceivedTimestamp=Date.now(),this.streamerReceivedTimestamp=r.ReceivedTimestamp,this.streamerSentTimestamp=r.SentTimestamp,this.responseFillerSize=r.Filler?r.Filler.length:0}}class xw{constructor(r,s){this.sink=r,this.callback=s,this.records=new Map,this.seq=0}start(r){return!this.isRunning()&&(this.startTime=Date.now(),this.records.clear(),this.interval=setInterval((()=>{Date.now()-this.startTime>=r.duration?this.stop():this.sendRequest(r.requestSize,r.responseSize)}).bind(this),Math.floor(1e3/r.rps)),!0)}stop(){this.interval&&(clearInterval(this.interval),this.interval=void 0,this.callback(this.produceResult()))}produceResult(){const r=new Map(this.records);return{records:r,dataChannelRtt:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.playerReceivedTimestamp-a.playerSentTimestamp)),0)/this.records.size),playerToStreamerTime:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.streamerReceivedTimestamp-a.playerSentTimestamp)),0)/this.records.size),streamerToPlayerTime:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.playerReceivedTimestamp-a.streamerSentTimestamp)),0)/this.records.size),exportLatencyAsCSV:()=>{let s=`Timestamp;RTT;PlayerToStreamer;StreamerToPlayer;
|
|
2916
2916
|
`;return r.forEach((a=>{s+=a.playerSentTimestamp+";",s+=a.playerReceivedTimestamp-a.playerSentTimestamp+";",s+=a.streamerReceivedTimestamp-a.playerSentTimestamp+";",s+=a.playerReceivedTimestamp-a.streamerSentTimestamp+";",s+=`
|
|
2917
|
-
`})),s}}}isRunning(){return!!this.interval}receive(r){if(!this.isRunning())return;if(!r)return void T.Error(T.GetStackTrace(),"Undefined response from server");let s=this.records.get(r.Seq);s&&s.update(r)}sendRequest(r,s){let a=this.createRequest(r,s),f=new Ew(a);this.records.set(f.seq,f),this.sink(a)}createRequest(r,s){return{Seq:this.seq++,FillResponseSize:s,Filler:r?"A".repeat(r):""}}}class xw{constructor(r,s){this.allowConsoleCommands=!1,this.config=r,s?.videoElementParent&&(this._videoElementParent=s.videoElementParent),this._eventEmitter=new Jf,this.configureSettings(),this.setWebRtcPlayerController(new dm(this.config,this)),this.onScreenKeyboardHelper=new Tw(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(a,f)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(a,f),this._activateOnScreenKeyboard=a=>this.onScreenKeyboardHelper.showOnScreenKeyboard(a),this._webXrController=new cm(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",(a=>{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(X.IsQualityController,(r=>{r!==!0||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(X.AFKDetection,(r=>{this._webRtcController.setAfkEnabled(r)})),this.config._addOnSettingChangedListener(X.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(X.HoveringMouseMode,(r=>{this.config.setFlagLabel(X.HoveringMouseMode,`Control Scheme: ${r?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(X.MouseInput))})),this.config._addOnSettingChangedListener(X.KeyboardInput,(r=>{this._webRtcController.setKeyboardInputEnabled(r)})),this.config._addOnSettingChangedListener(X.MouseInput,(r=>{this._webRtcController.setMouseInputEnabled(r)})),this.config._addOnSettingChangedListener(X.FakeMouseWithTouches,(r=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(X.TouchInput))})),this.config._addOnSettingChangedListener(X.TouchInput,(r=>{this._webRtcController.setTouchInputEnabled(r)})),this.config._addOnSettingChangedListener(X.GamepadInput,(r=>{this._webRtcController.setGamePadInputEnabled(r)})),this.config._addOnNumericSettingChangedListener(me.MinQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending MinQP --------",7),this._webRtcController.sendEncoderMinQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.MaxQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending encoder settings --------",7),this._webRtcController.sendEncoderMaxQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.WebRTCMinBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMinBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.WebRTCMaxBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMaxBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.WebRTCFPS,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCFps(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnOptionSettingChangedListener(dt.PreferredCodec,(r=>{this._webRtcController&&this._webRtcController.setPreferredCodec(r)})),this.config._registerOnChangeEvents(this._eventEmitter)}_activateOnScreenKeyboard(r){throw new Error("Method not implemented.")}_onInputControlOwnership(r){this._inputController=r}setWebRtcPlayerController(r){this._webRtcController=r,this._webRtcController.setPreferredCodec(this.config.getSettingOption(dt.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Df),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Lf),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new zf),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(X.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(r=!1){if(!this.config.isFlagEnabled("UseMic"))return r?(this.config.setFlagEnabled("UseMic",!0),void this.reconnect()):void T.Warning(T.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):T.Info(T.GetStackTrace(),"Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(r){var s,a,f,_;for(const C of(_=(f=(a=(s=this._webRtcController)===null||s===void 0?void 0:s.peerConnectionController)===null||a===void 0?void 0:a.peerConnection)===null||f===void 0?void 0:f.getTransceivers())!==null&&_!==void 0?_:[])im.canTransceiverSendAudio(C)&&(C.sender.track.enabled=!r)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new $f)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new Ef)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new Of)}_onDisconnect(r,s){this._eventEmitter.dispatchEvent(new Rf({eventString:r,allowClickToReconnect:s}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new xf)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Cf)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new kf)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new Pf),this._videoStartTime=Date.now()}_onLatencyTestResult(r){this._eventEmitter.dispatchEvent(new Wf({latencyTimings:r}))}_onDataChannelLatencyTestResponse(r){this._eventEmitter.dispatchEvent(new Hf({response:r}))}_onVideoStats(r){this._videoStartTime&&this._videoStartTime!==void 0||(this._videoStartTime=Date.now()),r.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new Vf({aggregatedStats:r}))}_onVideoEncoderAvgQP(r){this._eventEmitter.dispatchEvent(new Tf({avgQP:r}))}_onInitialSettings(r){var s;this._eventEmitter.dispatchEvent(new jf({settings:r})),r.PixelStreamingSettings&&(this.allowConsoleCommands=(s=r.PixelStreamingSettings.AllowPixelStreamingCommands)!==null&&s!==void 0&&s,this.allowConsoleCommands===!1&&T.Info(T.GetStackTrace(),"-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const a=this.config.useUrlParams,f=new URLSearchParams(window.location.search);T.Info(T.GetStackTrace(),`using URL parameters ${a}`),r.EncoderSettings&&(this.config.setNumericSetting(me.MinQP,a&&f.has(me.MinQP)?Number.parseFloat(f.get(me.MinQP)):r.EncoderSettings.MinQP),this.config.setNumericSetting(me.MaxQP,a&&f.has(me.MaxQP)?Number.parseFloat(f.get(me.MaxQP)):r.EncoderSettings.MaxQP)),r.WebRTCSettings&&(this.config.setNumericSetting(me.WebRTCMinBitrate,a&&f.has(me.WebRTCMinBitrate)?Number.parseFloat(f.get(me.WebRTCMinBitrate)):r.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(me.WebRTCMaxBitrate,a&&f.has(me.WebRTCMaxBitrate)?Number.parseFloat(f.get(me.WebRTCMaxBitrate)):r.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(me.WebRTCFPS,a&&f.has(me.WebRTCFPS)?Number.parseFloat(f.get(me.WebRTCFPS)):r.WebRTCSettings.FPS))}_onQualityControlOwnership(r){this.config.setFlagEnabled(X.IsQualityController,r)}_onPlayerCount(r){this._eventEmitter.dispatchEvent(new Xf({count:r}))}_setupWebRtcTCPRelayDetection(r){let s=r.data.aggregatedStats.getActiveCandidatePair();if(s!=null){let a=r.data.aggregatedStats.localCandidates.find((f=>f.id==s.localCandidateId),null);a!=null&&a.candidateType=="relay"&&a.relayProtocol=="tcp"&&this._eventEmitter.dispatchEvent(new Yf),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new $w(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(s=>{this._eventEmitter.dispatchEvent(new Kf({result:s}))})),this.addEventListener("dataChannelLatencyTestResponse",(({data:{response:s}})=>{this._dataChannelLatencyTestController.receive(s)}))),this._dataChannelLatencyTestController.start(r))}requestShowFps(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendShowFps(),!0)}requestIframe(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendIframeRequest(),!0)}emitUIInteraction(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.emitUIInteraction(r),!0)}emitCommand(r){return!(!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in r||(this._webRtcController.emitCommand(r),0))}emitConsoleCommand(r){return!(!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()||(this._webRtcController.emitConsoleCommand(r),0))}addResponseEventListener(r,s){this._webRtcController.responseController.addResponseEventListener(r,s)}removeResponseEventListener(r){this._webRtcController.responseController.removeResponseEventListener(r)}dispatchEvent(r){return this._eventEmitter.dispatchEvent(r)}addEventListener(r,s){this._eventEmitter.addEventListener(r,s)}removeEventListener(r,s){this._eventEmitter.removeEventListener(r,s)}toggleXR(){this.webXrController.xrClicked()}setSignallingUrlBuilder(r){this._webRtcController.signallingUrlBuilder=r}get webSocketController(){return this._webRtcController.webSocketController}get webXrController(){return this._webXrController}registerMessageHandler(r,s,a){s!==be.FromStreamer||a!==void 0?s===be.ToStreamer&&a===void 0?this._webRtcController.streamMessageController.registerMessageHandler(s,r,(f=>this._webRtcController.sendMessageController.sendMessageToStreamer(r,f))):this._webRtcController.streamMessageController.registerMessageHandler(s,r,(f=>a(f))):T.Warning(T.GetStackTrace(),`Unable to register an undefined handler for ${r}`)}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}}class Cw{}we.Dz;we.g$;we.Lt;we.Q9;we.qf;we.hV;we.z$;we.J0;var kw=we.De;we.$C;we.al;we._W;we.Gv;we.m;we.tz;we.Nu;we.zg;we.vp;we.vU;we.wF;we.rv;we.Nh;we.ss;we.qW;we.QL;we.cf;we.eM;we.Yd;we.Tk;we.iM;we.qy;we.ce;we.sK;we.Ok;we.q5;var Rw=we.g;we.xl;we.I;we.bx;we.dD;we.Ib;we.Az;we.Iw;we.qY;we.db;we.mR;we.Tn;we.rV;we.gh;we.Mi;we.j;we.YB;we.Yt;we.i5;we.x_;we.Am;we.eR;we.r8;we.u3;we.vd;we.iV;we.jZ;we.SW;we.ZH;we.Ni;we.lh;we.ZP;we.bq;we.$f;we.eu;we.Ax;we.Mc;const hm=({signallingUrl:d,autoConnect:r=!0,width:s,height:a,onConnecting:f,onLoading:_,onConnected:C,onDisconnected:R,onError:b,muted:U=!1})=>{const z=oe.useRef(null),re=oe.useRef(null),K=oe.useRef(!1),[se,J]=oe.useState(!1),[Y,H]=oe.useState(!1),[ne,ve]=oe.useState(null);return oe.useEffect(()=>{if(!(!z.current||!d)){f&&f(),process.env.NODE_ENV==="development"&&console.log("Initializing Epic Pixel Streaming with URL:",d),"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 de=new kw({useUrlParams:!1,initialSettings:{ss:d,AutoConnect:r,AutoPlayVideo:!0,StartVideoMuted:U,UseMic:!1,HoveringMouse:!1,FakeMouseWithTouches:!0,TouchInput:!1,MouseInput:!1,KeyboardInput:!1,WaitForStreamer:!0}}),ce=new Rw(de,{videoElementParent:z.current});ce.addEventListener("webRtcConnected",()=>{K.current=!0,J(!0),H(!1),ve(null),C?.()}),ce.addEventListener("webRtcDisconnected",()=>{K.current=!1,J(!1),R?.()}),ce.addEventListener("streamLoading",()=>{H(!0),_?.()}),ce.addEventListener("playStreamError",()=>{ve("Failed to play stream"),H(!1),b?.("Failed to play stream")}),ce.addEventListener("playStream",()=>{H(!1),K.current||(K.current=!0,J(!0),C?.())}),ce.addEventListener("videoInitialized",()=>{H(!1)}),re.current=ce}catch(de){process.env.NODE_ENV==="development"&&console.error("Failed to initialize Pixel Streaming:",de),ve("Failed to initialize streaming: "+de.message),H(!1),b?.(de.message)}return()=>{if(re.current){try{const de=re.current;de._webSocketController&&de._webSocketController.close(),re.current.disconnect()}catch(de){process.env.NODE_ENV==="development"&&console.error("Error during cleanup:",de)}re.current=null}}}},[d,r,f,_,C,R,b]),oe.useEffect(()=>{if(re.current)try{const ce=re.current._webRtcController?.videoPlayer;if(!ce)return;let pe=!1;if(ce.audioElement){const Ve=ce.audioElement.srcObject;if(Ve){const fe=Ve.getAudioTracks();fe.length>0&&(fe.forEach(Je=>{Je.enabled=!U}),pe=!0)}}const he=ce.getVideoElement();if(he&&he.srcObject&&he.srcObject instanceof MediaStream){const fe=he.srcObject.getAudioTracks();fe.length>0&&(fe.forEach(Je=>{Je.enabled=!U}),pe=!0)}!pe&&he&&(he.muted=U)}catch(de){process.env.NODE_ENV==="development"&&console.error("Error controlling audio:",de)}},[U]),Jt.jsxs("div",{className:"pixel-streaming-container",style:{width:s||"100%",height:a||"100%",position:"relative",display:"flex",flexDirection:"column",touchAction:"none",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},children:[Jt.jsx("div",{ref:z,className:"player-container",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"hidden",touchAction:"none"}}),Y&&Jt.jsxs("div",{className:"loading-overlay",children:[Jt.jsx("div",{className:"loading-spinner"}),Jt.jsx("div",{className:"loading-text",children:"Connecting to stream..."})]}),!se&&!Y&&ne&&Jt.jsx("div",{className:"connection-overlay",children:Jt.jsx("div",{className:"error-message",children:ne})})]})};function pm({className:d,style:r,autoConnect:s=!0,muted:a=!1,onConnected:f,onDisconnected:_,onError:C}){const{streamingUrl:R,setCloudStreamState:b}=lf();if(!R)return null;const U=()=>{b(Zt.CONNECTING)},z=()=>{b(Zt.LOADING)},re=()=>{b(Zt.CONNECTED),f?.()},K=()=>{b(Zt.DISCONNECTED),_?.()},se=J=>{b(Zt.ERROR,J),C?.(J)};return Jt.jsx("div",{className:d,style:r,children:Jt.jsx(hm,{signallingUrl:R,autoConnect:s,muted:a,onConnecting:U,onLoading:z,onConnected:re,onDisconnected:K,onError:se})})}const Aw=Object.freeze(Object.defineProperty({__proto__:null,RqmiiCloudAvatarPlayer:pm},Symbol.toStringTag,{value:"Module"}));exports.AGENT_TYPES=di;exports.CLOUD_STREAM_STATE=Zt;exports.CONNECTION_STATE=ft;exports.DEFAULT_PCM_OPTIONS=Gp;exports.EpicPixelStreamingPlayer=hm;exports.EventEmitter=sf;exports.RqmiiAgentProvider=af;exports.RqmiiAgentRoom=Py;exports.RqmiiCloudAvatarPlayer=pm;exports.RqmiiCloudAvatarPlayer$1=Aw;exports.SESSION_STATE=Bs;exports.SOCKET_EVENTS=_r;exports.useRqmiiAgentContext=dn;exports.useRqmiiAvatar=lf;exports.useRqmiiConnection=of;exports.useRqmiiMessages=my;exports.useRqmiiVAD=Iy;exports.useRqmiiVoice=gy;
|
|
2918
|
-
//# sourceMappingURL=RqmiiCloudAvatarPlayer-
|
|
2917
|
+
`})),s}}}isRunning(){return!!this.interval}receive(r){if(!this.isRunning())return;if(!r)return void T.Error(T.GetStackTrace(),"Undefined response from server");let s=this.records.get(r.Seq);s&&s.update(r)}sendRequest(r,s){let a=this.createRequest(r,s),f=new $w(a);this.records.set(f.seq,f),this.sink(a)}createRequest(r,s){return{Seq:this.seq++,FillResponseSize:s,Filler:r?"A".repeat(r):""}}}class Cw{constructor(r,s){this.allowConsoleCommands=!1,this.config=r,s?.videoElementParent&&(this._videoElementParent=s.videoElementParent),this._eventEmitter=new Jf,this.configureSettings(),this.setWebRtcPlayerController(new dm(this.config,this)),this.onScreenKeyboardHelper=new Ew(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(a,f)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(a,f),this._activateOnScreenKeyboard=a=>this.onScreenKeyboardHelper.showOnScreenKeyboard(a),this._webXrController=new cm(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",(a=>{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(X.IsQualityController,(r=>{r!==!0||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(X.AFKDetection,(r=>{this._webRtcController.setAfkEnabled(r)})),this.config._addOnSettingChangedListener(X.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(X.HoveringMouseMode,(r=>{this.config.setFlagLabel(X.HoveringMouseMode,`Control Scheme: ${r?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(X.MouseInput))})),this.config._addOnSettingChangedListener(X.KeyboardInput,(r=>{this._webRtcController.setKeyboardInputEnabled(r)})),this.config._addOnSettingChangedListener(X.MouseInput,(r=>{this._webRtcController.setMouseInputEnabled(r)})),this.config._addOnSettingChangedListener(X.FakeMouseWithTouches,(r=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(X.TouchInput))})),this.config._addOnSettingChangedListener(X.TouchInput,(r=>{this._webRtcController.setTouchInputEnabled(r)})),this.config._addOnSettingChangedListener(X.GamepadInput,(r=>{this._webRtcController.setGamePadInputEnabled(r)})),this.config._addOnNumericSettingChangedListener(ge.MinQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending MinQP --------",7),this._webRtcController.sendEncoderMinQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ge.MaxQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending encoder settings --------",7),this._webRtcController.sendEncoderMaxQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ge.WebRTCMinBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMinBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ge.WebRTCMaxBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMaxBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ge.WebRTCFPS,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCFps(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnOptionSettingChangedListener(dt.PreferredCodec,(r=>{this._webRtcController&&this._webRtcController.setPreferredCodec(r)})),this.config._registerOnChangeEvents(this._eventEmitter)}_activateOnScreenKeyboard(r){throw new Error("Method not implemented.")}_onInputControlOwnership(r){this._inputController=r}setWebRtcPlayerController(r){this._webRtcController=r,this._webRtcController.setPreferredCodec(this.config.getSettingOption(dt.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Df),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Lf),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new zf),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(X.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(r=!1){if(!this.config.isFlagEnabled("UseMic"))return r?(this.config.setFlagEnabled("UseMic",!0),void this.reconnect()):void T.Warning(T.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):T.Info(T.GetStackTrace(),"Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(r){var s,a,f,_;for(const C of(_=(f=(a=(s=this._webRtcController)===null||s===void 0?void 0:s.peerConnectionController)===null||a===void 0?void 0:a.peerConnection)===null||f===void 0?void 0:f.getTransceivers())!==null&&_!==void 0?_:[])im.canTransceiverSendAudio(C)&&(C.sender.track.enabled=!r)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new $f)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new Ef)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new Of)}_onDisconnect(r,s){this._eventEmitter.dispatchEvent(new Rf({eventString:r,allowClickToReconnect:s}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new xf)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Cf)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new kf)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new Pf),this._videoStartTime=Date.now()}_onLatencyTestResult(r){this._eventEmitter.dispatchEvent(new Wf({latencyTimings:r}))}_onDataChannelLatencyTestResponse(r){this._eventEmitter.dispatchEvent(new Hf({response:r}))}_onVideoStats(r){this._videoStartTime&&this._videoStartTime!==void 0||(this._videoStartTime=Date.now()),r.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new Vf({aggregatedStats:r}))}_onVideoEncoderAvgQP(r){this._eventEmitter.dispatchEvent(new Tf({avgQP:r}))}_onInitialSettings(r){var s;this._eventEmitter.dispatchEvent(new Kf({settings:r})),r.PixelStreamingSettings&&(this.allowConsoleCommands=(s=r.PixelStreamingSettings.AllowPixelStreamingCommands)!==null&&s!==void 0&&s,this.allowConsoleCommands===!1&&T.Info(T.GetStackTrace(),"-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const a=this.config.useUrlParams,f=new URLSearchParams(window.location.search);T.Info(T.GetStackTrace(),`using URL parameters ${a}`),r.EncoderSettings&&(this.config.setNumericSetting(ge.MinQP,a&&f.has(ge.MinQP)?Number.parseFloat(f.get(ge.MinQP)):r.EncoderSettings.MinQP),this.config.setNumericSetting(ge.MaxQP,a&&f.has(ge.MaxQP)?Number.parseFloat(f.get(ge.MaxQP)):r.EncoderSettings.MaxQP)),r.WebRTCSettings&&(this.config.setNumericSetting(ge.WebRTCMinBitrate,a&&f.has(ge.WebRTCMinBitrate)?Number.parseFloat(f.get(ge.WebRTCMinBitrate)):r.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(ge.WebRTCMaxBitrate,a&&f.has(ge.WebRTCMaxBitrate)?Number.parseFloat(f.get(ge.WebRTCMaxBitrate)):r.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(ge.WebRTCFPS,a&&f.has(ge.WebRTCFPS)?Number.parseFloat(f.get(ge.WebRTCFPS)):r.WebRTCSettings.FPS))}_onQualityControlOwnership(r){this.config.setFlagEnabled(X.IsQualityController,r)}_onPlayerCount(r){this._eventEmitter.dispatchEvent(new Xf({count:r}))}_setupWebRtcTCPRelayDetection(r){let s=r.data.aggregatedStats.getActiveCandidatePair();if(s!=null){let a=r.data.aggregatedStats.localCandidates.find((f=>f.id==s.localCandidateId),null);a!=null&&a.candidateType=="relay"&&a.relayProtocol=="tcp"&&this._eventEmitter.dispatchEvent(new Yf),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new xw(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(s=>{this._eventEmitter.dispatchEvent(new jf({result:s}))})),this.addEventListener("dataChannelLatencyTestResponse",(({data:{response:s}})=>{this._dataChannelLatencyTestController.receive(s)}))),this._dataChannelLatencyTestController.start(r))}requestShowFps(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendShowFps(),!0)}requestIframe(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendIframeRequest(),!0)}emitUIInteraction(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.emitUIInteraction(r),!0)}emitCommand(r){return!(!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in r||(this._webRtcController.emitCommand(r),0))}emitConsoleCommand(r){return!(!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()||(this._webRtcController.emitConsoleCommand(r),0))}addResponseEventListener(r,s){this._webRtcController.responseController.addResponseEventListener(r,s)}removeResponseEventListener(r){this._webRtcController.responseController.removeResponseEventListener(r)}dispatchEvent(r){return this._eventEmitter.dispatchEvent(r)}addEventListener(r,s){this._eventEmitter.addEventListener(r,s)}removeEventListener(r,s){this._eventEmitter.removeEventListener(r,s)}toggleXR(){this.webXrController.xrClicked()}setSignallingUrlBuilder(r){this._webRtcController.signallingUrlBuilder=r}get webSocketController(){return this._webRtcController.webSocketController}get webXrController(){return this._webXrController}registerMessageHandler(r,s,a){s!==Se.FromStreamer||a!==void 0?s===Se.ToStreamer&&a===void 0?this._webRtcController.streamMessageController.registerMessageHandler(s,r,(f=>this._webRtcController.sendMessageController.sendMessageToStreamer(r,f))):this._webRtcController.streamMessageController.registerMessageHandler(s,r,(f=>a(f))):T.Warning(T.GetStackTrace(),`Unable to register an undefined handler for ${r}`)}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}}class kw{}ve.Dz;ve.g$;ve.Lt;ve.Q9;ve.qf;ve.hV;ve.z$;ve.J0;var Rw=ve.De;ve.$C;ve.al;ve._W;ve.Gv;ve.m;ve.tz;ve.Nu;ve.zg;ve.vp;ve.vU;ve.wF;ve.rv;ve.Nh;ve.ss;ve.qW;ve.QL;ve.cf;ve.eM;ve.Yd;ve.Tk;ve.iM;ve.qy;ve.ce;ve.sK;ve.Ok;ve.q5;var Aw=ve.g;ve.xl;ve.I;ve.bx;ve.dD;ve.Ib;ve.Az;ve.Iw;ve.qY;ve.db;ve.mR;ve.Tn;ve.rV;ve.gh;ve.Mi;ve.j;ve.YB;ve.Yt;ve.i5;ve.x_;ve.Am;ve.eR;ve.r8;ve.u3;ve.vd;ve.iV;ve.jZ;ve.SW;ve.ZH;ve.Ni;ve.lh;ve.ZP;ve.bq;ve.$f;ve.eu;ve.Ax;ve.Mc;const hm=({signallingUrl:d,autoConnect:r=!0,width:s,height:a,onConnecting:f,onLoading:_,onConnected:C,onDisconnected:R,onError:S,muted:N=!1})=>{const z=ae.useRef(null),te=ae.useRef(null),j=ae.useRef(!1),[se,J]=ae.useState(!1),[Y,W]=ae.useState(!1),[ne,fe]=ae.useState(null);return ae.useEffect(()=>{if(!(!z.current||!d)){f&&f(),process.env.NODE_ENV==="development"&&console.log("Initializing Epic Pixel Streaming with URL:",d),"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 de=new Rw({useUrlParams:!1,initialSettings:{ss:d,AutoConnect:r,AutoPlayVideo:!0,StartVideoMuted:N,UseMic:!1,HoveringMouse:!1,FakeMouseWithTouches:!0,TouchInput:!1,MouseInput:!1,KeyboardInput:!1,WaitForStreamer:!0}}),ce=new Aw(de,{videoElementParent:z.current});ce.addEventListener("webRtcConnected",()=>{j.current=!0,J(!0),W(!1),fe(null),C?.()}),ce.addEventListener("webRtcDisconnected",()=>{j.current=!1,J(!1),R?.()}),ce.addEventListener("streamLoading",()=>{W(!0),_?.()}),ce.addEventListener("playStreamError",()=>{fe("Failed to play stream"),W(!1),S?.("Failed to play stream")}),ce.addEventListener("playStream",()=>{W(!1),j.current||(j.current=!0,J(!0),C?.())}),ce.addEventListener("videoInitialized",()=>{W(!1)}),te.current=ce}catch(de){process.env.NODE_ENV==="development"&&console.error("Failed to initialize Pixel Streaming:",de),fe("Failed to initialize streaming: "+de.message),W(!1),S?.(de.message)}return()=>{if(te.current){try{const de=te.current;de._webSocketController&&de._webSocketController.close(),te.current.disconnect()}catch(de){process.env.NODE_ENV==="development"&&console.error("Error during cleanup:",de)}te.current=null}}}},[d,r,f,_,C,R,S]),ae.useEffect(()=>{if(te.current)try{const ce=te.current._webRtcController?.videoPlayer;if(!ce)return;let pe=!1;if(ce.audioElement){const Ve=ce.audioElement.srcObject;if(Ve){const me=Ve.getAudioTracks();me.length>0&&(me.forEach(Ye=>{Ye.enabled=!N}),pe=!0)}}const he=ce.getVideoElement();if(he&&he.srcObject&&he.srcObject instanceof MediaStream){const me=he.srcObject.getAudioTracks();me.length>0&&(me.forEach(Ye=>{Ye.enabled=!N}),pe=!0)}!pe&&he&&(he.muted=N)}catch(de){process.env.NODE_ENV==="development"&&console.error("Error controlling audio:",de)}},[N]),Jt.jsxs("div",{className:"pixel-streaming-container",style:{width:s||"100%",height:a||"100%",position:"relative",display:"flex",flexDirection:"column",touchAction:"none",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},children:[Jt.jsx("div",{ref:z,className:"player-container",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"hidden",touchAction:"none"}}),Y&&Jt.jsxs("div",{className:"loading-overlay",children:[Jt.jsx("div",{className:"loading-spinner"}),Jt.jsx("div",{className:"loading-text",children:"Connecting to stream..."})]}),!se&&!Y&&ne&&Jt.jsx("div",{className:"connection-overlay",children:Jt.jsx("div",{className:"error-message",children:ne})})]})};function pm({className:d,style:r,autoConnect:s=!0,muted:a=!1,onConnected:f,onDisconnected:_,onError:C}){const{streamingUrl:R,setCloudStreamState:S}=lf();if(!R)return null;const N=()=>{S(Zt.CONNECTING)},z=()=>{S(Zt.LOADING)},te=()=>{S(Zt.CONNECTED),f?.()},j=()=>{S(Zt.DISCONNECTED),_?.()},se=J=>{S(Zt.ERROR,J),C?.(J)};return Jt.jsx("div",{className:d,style:r,children:Jt.jsx(hm,{signallingUrl:R,autoConnect:s,muted:a,onConnecting:N,onLoading:z,onConnected:te,onDisconnected:j,onError:se})})}const Iw=Object.freeze(Object.defineProperty({__proto__:null,RqmiiCloudAvatarPlayer:pm},Symbol.toStringTag,{value:"Module"}));exports.AGENT_TYPES=ci;exports.CLOUD_STREAM_STATE=Zt;exports.CONNECTION_STATE=pt;exports.DEFAULT_PCM_OPTIONS=Gp;exports.EpicPixelStreamingPlayer=hm;exports.EventEmitter=sf;exports.RqmiiAgentProvider=af;exports.RqmiiAgentRoom=Oy;exports.RqmiiCloudAvatarPlayer=pm;exports.RqmiiCloudAvatarPlayer$1=Iw;exports.SESSION_STATE=Ns;exports.SOCKET_EVENTS=br;exports.useRqmiiAgentContext=Fs;exports.useRqmiiAvatar=lf;exports.useRqmiiConnection=of;exports.useRqmiiEvents=My;exports.useRqmiiMessages=my;exports.useRqmiiVAD=Iy;exports.useRqmiiVoice=gy;
|
|
2918
|
+
//# sourceMappingURL=RqmiiCloudAvatarPlayer-DGywLDgp.cjs.map
|