@rqmii_immersive/agent-react-sdk 5.2.0 → 5.3.1
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-BL7GVcr_.js → RqmiiCloudAvatarPlayer-Bi44g7bl.js} +1117 -1115
- package/dist/RqmiiCloudAvatarPlayer-Bi44g7bl.js.map +1 -0
- package/dist/{RqmiiCloudAvatarPlayer-Dc1h266_.cjs → RqmiiCloudAvatarPlayer-DDtkCYFJ.cjs} +99 -99
- package/dist/RqmiiCloudAvatarPlayer-DDtkCYFJ.cjs.map +1 -0
- package/dist/components/RqmiiAgentRoom.d.ts.map +1 -1
- package/dist/core/managers/session.d.ts +3 -1
- package/dist/core/managers/session.d.ts.map +1 -1
- package/dist/embed.js +291 -291
- package/dist/embed.js.map +1 -1
- package/dist/hooks/use-rqmii-connection.d.ts.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/provider/use-manager-lifecycle.d.ts +2 -1
- package/dist/provider/use-manager-lifecycle.d.ts.map +1 -1
- package/dist/types/index.d.ts +18 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/ui/RqmiiAgentChat.d.ts +1 -1
- package/dist/ui/RqmiiAgentChat.d.ts.map +1 -1
- package/dist/ui/chat/panels.d.ts +0 -1
- package/dist/ui/chat/panels.d.ts.map +1 -1
- package/dist/ui.cjs +21 -21
- package/dist/ui.cjs.map +1 -1
- package/dist/ui.js +682 -680
- package/dist/ui.js.map +1 -1
- package/package.json +1 -1
- package/dist/RqmiiCloudAvatarPlayer-BL7GVcr_.js.map +0 -1
- package/dist/RqmiiCloudAvatarPlayer-Dc1h266_.cjs.map +0 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";const ae=require("react"),Yt=require("react/jsx-runtime");function Gp(){if(typeof window>"u")return;const d=window;d.__rqmii_orig_console||(d.__rqmii_orig_console={error:console.error,warn:console.warn,log:console.log,debug:console.debug});const r=d.__rqmii_orig_console,s=v=>{if(v.length===0)return!1;const C=String(v[0]);return C.includes("reading 'S'")||C.includes("reading 'state'")||C.includes("MicVAD has null stream")||C.includes("VAD |")||C.includes("audioCtx.state")||C.includes("using default audio context")};console.error=(...v)=>{s(v)||r.error.apply(console,v)},console.warn=(...v)=>{s(v)||r.warn.apply(console,v)},console.log=(...v)=>{s(v)||r.log.apply(console,v)},console.debug=(...v)=>{s(v)||r.debug.apply(console,v)};const a=d.onerror;d.onerror=function(v,C,R,S,N){const z=String(v);return z.includes("reading 'state'")||z.includes("reading 'S'")||z.includes("MicVAD has null stream")?!0:a?a(v,C,R,S,N):!1};const f=d.onunhandledrejection;d.onunhandledrejection=function(v){const C=String(v.reason&&v.reason.message?v.reason.message:v.reason);return C.includes("reading 'state'")||C.includes("reading 'S'")||C.includes("MicVAD has null stream")?(v.preventDefault(),!0):f?f.call(d,v):!1}}const hi={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},Sr={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"},Jt={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"},qp={encoding:"16bitInt",channels:1,sampleRate:16e3},po={connectionState:pt.IDLE,isConnected:!1,isSessionReady:!1,error:null,isAudioPlaying:!1,isAvatarSpeaking:!1,sessionState:Bs.IDLE,cloudStream:{state:Jt.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 pg(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 fg(){const d=new Map;return{addChunk(r,s){const a=r||`request-${Date.now()}`,v=`${d.get(a)||""}${s||""}`;return d.set(a,v),{id:a,text:v}},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 mg(){try{const d=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof d=="string"&&d.trim()?d.trim():void 0}catch{return}}async function ei(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 gg({restUrl:d,log:r,withCredentials:s}){function a(){if(!d)throw new Error("Missing restUrl in RqmiiAgentProvider")}async function f({apiKey:N,agentId:z,userId:te,language:j="en",timezone:se,config:J}={}){a();const Y={...N?{api_key:N}:{},...z?{agent_id:z}:{},...te?{user_id:te}:{},language:j,...se?{timezone:se}:{},...J?{config:J}:{}};r("initializeSession — POST /sessions/init",Y);const W=await fetch(`${d}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y),...s?{credentials:"include"}:{}}),ne=await ei(W);if(!ne?.session_id||!ne?.session_token)throw new Error("Invalid initialize session response");return ne}async function v({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 ei(z);if(!te?.session_id||!te?.session_token)throw new Error("Invalid join session response");return te}async function C(N){if(!d)throw new Error("SessionManager: restUrl missing");r("fetchAgentConfig — GET /agent/{agentId}",{agentId:N});const z=await fetch(`${d}/agent/${encodeURIComponent(N)}/customization`,{method:"GET",headers:{"Content-Type":"application/json"},...s?{credentials:"include"}:{}});return ei(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 ei(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 ei(j)}return{initializeSession:f,joinDesktopSession:v,fetchAgentConfig:C,submitFeedback:R,submitLead:S}}const zr=Object.create(null);zr.open="0";zr.close="1";zr.ping="2";zr.pong="3";zr.message="4";zr.upgrade="5";zr.noop="6";const Di=Object.create(null);Object.keys(zr).forEach(d=>{Di[zr[d]]=d});const fo={type:"error",data:"parser error"},Wp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Hp=typeof ArrayBuffer=="function",jp=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d&&d.buffer instanceof ArrayBuffer,xo=({type:d,data:r},s,a)=>Wp&&r instanceof Blob?s?a(r):pp(r,a):Hp&&(r instanceof ArrayBuffer||jp(r))?s?a(r):pp(new Blob([r]),a):a(zr[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 yg(d,r){if(Wp&&d.data instanceof Blob)return d.data.arrayBuffer().then(fp).then(r);if(Hp&&(d.data instanceof ArrayBuffer||jp(d.data)))return r(fp(d.data));xo(d,!1,s=>{Ya||(Ya=new TextEncoder),r(Ya.encode(s))})}const mp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ui=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let d=0;d<mp.length;d++)ui[mp.charCodeAt(d)]=d;const wg=d=>{let r=d.length*.75,s=d.length,a,f=0,v,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)v=ui[d.charCodeAt(a)],C=ui[d.charCodeAt(a+1)],R=ui[d.charCodeAt(a+2)],S=ui[d.charCodeAt(a+3)],z[f++]=v<<2|C>>4,z[f++]=(C&15)<<4|R>>2,z[f++]=(R&3)<<6|S&63;return N},vg=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:_g(d.substring(1),r)}:Di[s]?d.length>1?{type:Di[s],data:d.substring(1)}:{type:Di[s]}:fo},_g=(d,r)=>{if(vg){const s=wg(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}},Qp="",bg=(d,r)=>{const s=d.length,a=new Array(s);let f=0;d.forEach((v,C)=>{xo(v,!1,R=>{a[C]=R,++f===s&&r(a.join(Qp))})})},Sg=(d,r)=>{const s=d.split(Qp),a=[];for(let f=0;f<s.length;f++){const v=Co(s[f],r);if(a.push(v),v.type==="error")break}return a};function Tg(){return new TransformStream({transform(d,r){yg(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 v=new DataView(f.buffer);v.setUint8(0,126),v.setUint16(1,a)}else{f=new Uint8Array(9);const v=new DataView(f.buffer);v.setUint8(0,127),v.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 Oi(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 Eg(d,r){Ja||(Ja=new TextDecoder);const s=[];let a=0,f=-1,v=!1;return new TransformStream({transform(C,R){for(s.push(C);;){if(a===0){if(Mi(s)<1)break;const S=Oi(s,1);v=(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=Oi(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=Oi(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=Oi(s,f);R.enqueue(Co(v?S:Ja.decode(S),r)),a=0}if(f===0||f>d){R.enqueue(fo);break}}}})}const Xp=4;function $t(d){if(d)return $g(d)}function $g(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")(),xg="arraybuffer";function Yp(d,...r){return r.reduce((s,a)=>(d.hasOwnProperty(a)&&(s[a]=d[a]),s),{})}const Cg=ur.setTimeout,kg=ur.clearTimeout;function Gi(d,r){r.useNativeTimers?(d.setTimeoutFn=Cg.bind(ur),d.clearTimeoutFn=kg.bind(ur)):(d.setTimeoutFn=ur.setTimeout.bind(ur),d.clearTimeoutFn=ur.clearTimeout.bind(ur))}const Rg=1.33;function Ag(d){return typeof d=="string"?Ig(d):Math.ceil((d.byteLength||d.size)*Rg)}function Ig(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 Jp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Mg(d){let r="";for(let s in d)d.hasOwnProperty(s)&&(r.length&&(r+="&"),r+=encodeURIComponent(s)+"="+encodeURIComponent(d[s]));return r}function Og(d){let r={},s=d.split("&");for(let a=0,f=s.length;a<f;a++){let v=s[a].split("=");r[decodeURIComponent(v[0])]=decodeURIComponent(v[1])}return r}class Pg 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 Pg(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=Mg(r);return s.length?"?"+s:""}}class Dg 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)};Sg(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,bg(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]=Jp()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(r,s)}}let Zp=!1;try{Zp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const zg=Zp;function Lg(){}class Bg extends Dg{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,v)=>{this.onError("xhr post error",f,v)})}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 Dr 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=Yp(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=Dr.requestsCount++,Dr.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=Lg,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Dr.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()}}Dr.requestsCount=0;Dr.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 Dr.requests)Dr.requests.hasOwnProperty(d)&&Dr.requests[d].abort()}const Ng=(function(){const d=ef({xdomain:!1});return d&&d.responseType!==null})();class Ug extends Bg{constructor(r){super(r);const s=r&&r.forceBase64;this.supportsBinary=Ng&&!s}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Dr(ef,this.uri(),r)}}function ef(d){const r=d.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||zg))return new XMLHttpRequest}catch{}if(!r)try{return new ur[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const tf=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Fg extends ko{get name(){return"websocket"}doOpen(){const r=this.uri(),s=this.opts.protocols,a=tf?{}:Yp(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,v=>{try{this.doWrite(a,v)}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]=Jp()),this.supportsBinary||(s.b64=1),this.createUri(r,s)}}const Za=ur.WebSocket||ur.MozWebSocket;class Vg extends Fg{createSocket(r,s,a){return tf?new Za(r,s,a):s?new Za(r,s):new Za(r)}doWrite(r,s){this.ws.send(s)}}class Gg 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=Eg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(s).getReader(),f=Tg();f.readable.pipeTo(r.writable),this._writer=f.writable.getWriter();const v=()=>{a.read().then(({done:R,value:S})=>{R||(this.onPacket(S),v())}).catch(R=>{})};v();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 qg={websocket:Vg,webtransport:Gg,polling:Ug},Wg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Hg=["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=Wg.exec(d||""),v={},C=14;for(;C--;)v[Hg[C]]=f[C]||"";return s!=-1&&a!=-1&&(v.source=r,v.host=v.host.substring(1,v.host.length-1).replace(/;/g,":"),v.authority=v.authority.replace("[","").replace("]","").replace(/;/g,":"),v.ipv6uri=!0),v.pathNames=jg(v,v.path),v.queryKey=Kg(v,v.query),v}function jg(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 Kg(d,r){const s={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,v){f&&(s[f]=v)}),s}const go=typeof addEventListener=="function"&&typeof removeEventListener=="function",zi=[];go&&addEventListener("offline",()=>{zi.forEach(d=>d())},!1);class us extends $t{constructor(r,s){if(super(),this.binaryType=xg,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=Og(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=Xp,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&&us.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",us.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+=Ag(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 v={type:r,data:s,options:a};this.emitReserved("packetCreate",v),this.writeBuffer.push(v),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(us.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}}}us.protocol=Xp;class Qg extends us{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;us.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;us.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 v(){a||(a=!0,z(),s.close(),s=null)}const C=te=>{const j=new Error("probe error: "+te);j.transport=s.name,v(),this.emitReserved("upgradeError",j)};function R(){C("transport closed")}function S(){C("socket closed")}function N(te){s&&te.name!==s.name&&v()}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 Xg=class extends Qg{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=>qg[f]).filter(f=>!!f)),super(r,a)}};function Yg(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 v=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+v+":"+a.port+r,a.href=a.protocol+"://"+v+(s&&s.port===a.port?"":":"+a.port),a}const Jg=typeof ArrayBuffer=="function",Zg=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d.buffer instanceof ArrayBuffer,rf=Object.prototype.toString,ey=typeof Blob=="function"||typeof Blob<"u"&&rf.call(Blob)==="[object BlobConstructor]",ty=typeof File=="function"||typeof File<"u"&&rf.call(File)==="[object FileConstructor]";function Ro(d){return Jg&&(d instanceof ArrayBuffer||Zg(d))||ey&&d instanceof Blob||ty&&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 ry(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 sy(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 ny=["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 iy{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=ry(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 ay(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 v=s+1;for(;r.charAt(++s)!=="-"&&s!=r.length;);const C=r.substring(v,s);if(C!=Number(C)||r.charAt(s)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!oy(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 v=s+1;for(;++s&&!(r.charAt(s)===","||s===r.length););a.nsp=r.substring(v,s)}else a.nsp="/";const f=r.charAt(s+1);if(f!==""&&Number(f)==f){const v=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(v,s+1))}if(r.charAt(++s)){const v=this.tryParse(r.substr(s));if(Ao.isPayloadValid(a.type,v))a.data=v;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"&&ny.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 ay{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=sy(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const oy=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 ly=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ao,Encoder:iy,get PacketType(){return Xe}},Symbol.toStringTag,{value:"Module"}));function Tr(d,r,s){return d.on(r,s),function(){d.off(r,s)}}const uy=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class sf 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=[Tr(r,"open",this.onopen.bind(this)),Tr(r,"packet",this.onpacket.bind(this)),Tr(r,"error",this.onerror.bind(this)),Tr(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,v;if(uy.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&&!(!((v=this.io.engine)===null||v===void 0)&&v._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 v=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(v),s.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...s){return new Promise((a,f)=>{const v=(C,R)=>C?f(C):a(R);v.withError=!0,s.push(v),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,...v)=>(this._queue[0],f!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),s&&s(f)):(this._queue.shift(),s&&s(null,...v)),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 cn(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}cn.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};cn.prototype.reset=function(){this.attempts=0};cn.prototype.setMin=function(d){this.ms=d};cn.prototype.setMax=function(d){this.max=d};cn.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 cn({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||ly;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 Xg(this.uri,this.opts);const s=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const f=Tr(s,"open",function(){a.onopen(),r&&r()}),v=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=Tr(s,"error",v);if(this._timeout!==!1){const R=this._timeout,S=this.setTimeoutFn(()=>{f(),v(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(Tr(r,"ping",this.onping.bind(this)),Tr(r,"data",this.ondata.bind(this)),Tr(r,"error",this.onerror.bind(this)),Tr(r,"close",this.onclose.bind(this)),Tr(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 sf(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 ti={};function Bi(d,r){typeof d=="object"&&(r=d,d=void 0),r=r||{};const s=Yg(d,r.path||"/socket.io"),a=s.source,f=s.id,v=s.path,C=ti[f]&&v in ti[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let S;return R?S=new vo(a,r):(ti[f]||(ti[f]=new vo(a,r)),S=ti[f]),s.query&&!r.query&&(r.query=s.queryKey),S.socket(s.path,r)}Object.assign(Bi,{Manager:vo,Socket:sf,io:Bi,connect:Bi});function dy({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 v(){return s}return{connectSocketRaw:a,cleanupSocket:f,getSocket:v}}const cy=d=>{if(window.audioCtx=d,d.state!=="suspended")return;const r=document.body,s=["touchstart","touchend","mousedown","keydown"];s.forEach(v=>r.addEventListener(v,a,!1));function a(){d.resume().then(f)}function f(){s.forEach(v=>r.removeEventListener(v,a))}};function Pt(d){this.init(d)}Pt.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()};Pt.prototype.getMaxValue=function(){var d={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Pt.prototype.getTypedArray=function(){var d={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Pt.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),cy(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Pt.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};Pt.prototype.isTypedArray=function(d){return d.byteLength&&d.buffer&&d.buffer.constructor==ArrayBuffer};Pt.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()}};Pt.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};Pt.prototype.volume=function(d){this.gainNode.gain.value=d};Pt.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Pt.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};Pt.prototype.setRequestStop=function(){this.flag_request_stop=!0};Pt.prototype.setOnEnd=function(d){this.onEnd=d};Pt.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};Pt.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)}})();Pt.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Pt.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,v,C,R;for(f=0;f<this.option.channels;f++)for(a=s.getChannelData(f),v=f,R=50,C=0;C<r;C++)a[C]=this.samples[v],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),v+=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 hy(d,r){const s=new Pt(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 py({enableAudio:d,pcmOptions:r,log:s,onPlaybackComplete:a}){let f=null,v=null;function C(){if(!d||f)return f;const W={...qp,...r||{}};return f=hy(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(ge){s("feedAudio: player.feed() failed",ge),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){v=W||null}function J(){return v}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 fy(d){const{wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:v,withCredentials:C,onPlaybackComplete:R}=d,S=ae.useCallback((...j)=>{v&&console.log("[RqmiiSDK]",...j)},[v]),N=ae.useRef(null),z=ae.useRef(null),te=ae.useRef(null);return N.current||(N.current=dy({wsUrl:r,log:S})),z.current||(z.current=py({enableAudio:a,pcmOptions:f,log:S,onPlaybackComplete:R})),te.current||(te.current=gg({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 my(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 gy(d){const{socket:r,dispatch:s,stateRef:a,sessionIdRef:f,sessionAgentTypeRef:v,interruptedRef:C,manualDisconnectRef:R,chunkAccumulatorRef:S,clientToolsRef:N,audioMgrRef:z,enableAudio:te,cbRefs:j,eventsEmitter:se}=d,J=Sr,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 ge=W||null;s({type:"SET_PARTIAL_TRANSCRIPT",payload:ge}),se.emit("partial_transcript",ge??void 0)}),r.on(J.AGENT_RESPONSE_CHUNK,W=>{const{id:ne,text:ge}=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:ge,streaming:!0,timestamp:new Date().toISOString()}]})}),r.on(J.AGENT_RESPONSE,W=>{const{id:ne,text:ge}=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:ge,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(v.current);if(ne==="cloud_avatar"||ne==="desktop_avatar"||ne==="text")return;const ge=my(W?.audio);ge&&(Y.feedAudio(ge),s({type:"SET_AUDIO_PLAYING",payload:!0}))}),r.on(J.AGENT_AUDIO_COMPLETE,()=>{if(!te)return;const W=eo(v.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:[],ge=W?.agentId;!ge||ne.length===0||s({type:"ADD_MESSAGE",payload:{id:`lead-form-${Date.now()}`,role:"lead_form",text:"",form:{agentId:ge,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,ge=W?.toolName,de=W?.parameters??{},he=W?.waitForResponse!==!1;if(!ge)return;const pe=N.current[ge];if(!pe)return;const ce={minimize:()=>se.emit("minimize_chat"),maximize:()=>se.emit("maximize_chat")};he&&ne?pe(de,ce).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,ce).catch(()=>{})})}class nf{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 af=ae.createContext(null);function of({children:d,wsUrl:r="wss://ws.rqmii.com",restUrl:s="https://api.rqmii.com",enableAudio:a=!0,pcmOptions:f,debug:v=!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(fg()),ge=ae.useRef(null),de=ae.useRef(po.session.agentType),he=ae.useRef(!1),pe=ae.useRef(new nf),ce=ae.useRef({}),Ve=ae.useRef({onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te});ae.useEffect(()=>{Gp(),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(()=>{ge.current=j.session.sessionId},[j.session.sessionId]);const fe=ae.useCallback(()=>{Y({type:"SET_AUDIO_PLAYING",payload:!1});const be=Ye.current?.getSocket();be?.connected&&be.emit(Sr.AUDIO_PLAYBACK_COMPLETE,{session_id:ge.current})},[]),{socketMgrRef:Ye,audioMgrRef:qe,sessionMgrRef:it}=fy({wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:v,withCredentials:R,onPlaybackComplete:fe}),Je=ae.useCallback(be=>{gy({socket:be,dispatch:Y,stateRef:J,sessionIdRef:ge,sessionAgentTypeRef:de,interruptedRef:he,manualDisconnectRef:W,chunkAccumulatorRef:ne,clientToolsRef:ce,audioMgrRef:{current:qe.current},enableAudio:a,cbRefs:Ve,eventsEmitter:pe.current})},[a]),at=ae.useCallback(({authPayload:be,queryToken:Ze})=>new Promise((qt,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}),qt(It)}),It.once("connect_error",Cr=>{Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Cr?.message||"Connection error"}),nr(Cr)})}),[Je]),tt=ae.useCallback(({keepManualDisconnect:be=!1}={})=>{W.current=!0,he.current=!1,ne.current.clear(),qe.current.destroyPcmPlayer(),Ye.current.cleanupSocket(),be||(W.current=!1),Y({type:"HARD_RESET"})},[]),Gt=ae.useCallback(async({apiKey:be,agentId:Ze,userId:qt,language:nr="en",clientTools:It,config:Cr}={})=>{if(!be&&!Ze)throw new Error("Provide one of apiKey or agentId");tt(),ce.current=It??{},Y({type:"SET_CONNECTION_STATE",payload:pt.INITIALIZING}),Y({type:"SET_ERROR",payload:null});const yt=mg();let cr;try{cr=await it.current.initializeSession({apiKey:be,agentId:Ze,userId:qt,language:nr,timezone:yt,config:Cr})}catch(ir){const Lt=ir;throw Lt.status===401||Lt.status===403?(Y({type:"SET_CONNECTION_STATE",payload:pt.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:pt.FAILED})):Lt.status===429?(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Too many requests. Please try again later."})):(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Failed to initialize session"})),ir}const er=cr;Y({type:"UPDATE_SESSION",payload:{sessionId:er.session_id,agentType:er.streaming_url?hi.CLOUD_AVATAR:j.session.agentType,streamingUrl:er.streaming_url||null,uniqueId:er.unique_id||null}}),Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:er.streaming_url?Jt.CONNECTING:Jt.IDLE,error:null}}),W.current=!0;try{await at({authPayload:{token:er.session_token},queryToken:er.session_token}),W.current=!1}catch(ir){throw W.current=!1,ir}return cr},[at,tt,r,j.session.agentType]),xt=ae.useCallback(async({uniqueId:be})=>{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 qt=Ze;Y({type:"UPDATE_SESSION",payload:{sessionId:qt.session_id,uniqueId:be,role:"user",agentType:hi.DESKTOP_AVATAR}}),Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Jt.IDLE,error:null}}),W.current=!0;try{await at({authPayload:{token:qt.session_token},queryToken:qt.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 qt=Ye.current?.getSocket();return!qt||!j.isConnected?!1:(qt.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(Sr.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()}})},[]),Qr=ae.useCallback(be=>!be||!String(be).trim()?!1:ze(Sr.USER_MESSAGE,{message:String(be)}),[ze]),Fs=ae.useCallback(be=>ze(Sr.AUDIO_CHUNK,{audio:be}),[ze]),Xr=ae.useCallback(()=>ze(Sr.AUDIO_END,{}),[ze]),Yr=ae.useCallback(()=>(he.current=!0,qe.current.interruptPlayback(),Y({type:"SET_AUDIO_PLAYING",payload:!1}),ze(Sr.INTERRUPT,{})),[ze]),Vs=ae.useCallback(()=>ze(Sr.CLEAR_SESSION_HISTORY,{}),[ze]),rt=ae.useCallback(be=>be?ze(Sr.CHANGE_SESSION_LANGUAGE,{language:be}):!1,[ze]),$r=ae.useCallback((be={})=>ze(Sr.CLIENT_READY,be),[ze]),lt=ae.useCallback(()=>{ne.current.clear(),Y({type:"SET_MESSAGES",payload:[]})},[]),Jr=ae.useCallback(be=>{Y({type:"SET_MESSAGES",payload:be})},[]),Zt=ae.useCallback(()=>qe.current.resumeAudioPlayback(),[]),xr=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=>{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=>{Object.keys(ce.current).length===0?ce.current=be:Object.assign(ce.current,be)},[]),Zr=ae.useCallback(be=>{const Ze=be.sessionId||ge.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"))},[]),es=ae.useCallback(be=>{const Ze=be.sessionId||ge.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"))},[]),Gs=ae.useMemo(()=>pg(j.sessionState),[j.sessionState]),Lr=ae.useMemo(()=>({...j,...Gs,initializeSession:Gt,joinDesktopSession:xt,disconnect:Ke,terminateSession:We,endSession:st,emit:ze,sendTextMessage:Rt,addLocalMessage:sr,emitUserMessage:Qr,sendAudioChunk:Fs,endAudioStream:Xr,interrupt:Yr,clearSessionHistory:Vs,changeSessionLanguage:rt,signalClientReady:$r,clearMessages:lt,setMessages:Jr,resumeAudioPlayback:Zt,pauseAudioPlayback:xr,attachAudioElement:gt,fetchAgentConfig:At,submitFeedback:Zr,submitLead:es,setCloudStreamState:ft,registerClientTools:Ct,events:pe.current,audioElement:qe.current?.getAudioElement()??null,socket:Ye.current?.getSocket()??null}),[j,Gs,Gt,xt,Ke,We,st,ze,Rt,sr,Qr,Fs,Xr,Yr,Vs,rt,$r,lt,Jr,Zt,xr,gt,ft,Ct,Zr,es]);return Yt.jsx(af.Provider,{value:Lr,children:d})}function Us(){const d=ae.useContext(af);if(!d)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return d}function lf(){const d=Us();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 yy(){const d=Us();return{messages:d.messages,sendTextMessage:d.sendTextMessage,addLocalMessage:d.addLocalMessage,emitUserMessage:d.emitUserMessage,clearMessages:d.clearMessages}}function wy(){const d=Us();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 uf(){const d=Us(),r=d.cloudStream?.state||Jt.IDLE;return{streamingUrl:d.session.streamingUrl,isAvatarSpeaking:d.isAvatarSpeaking,speakingSource:"avatar_events",isCloudAvatar:d.session.agentType===hi.CLOUD_AVATAR,isDesktopAvatar:d.session.agentType===hi.DESKTOP_AVATAR,cloudStreamState:r,cloudStreamError:d.cloudStream?.error||null,isCloudStreamConnected:r===Jt.CONNECTED,isCloudStreamLoading:r===Jt.CONNECTING||r===Jt.LOADING,setCloudStreamState:d.setCloudStreamState}}var to={},ro={},ri={},wp;function df(){if(wp)return ri;wp=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.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(/\/[^/]+$/,"/")),ri.baseAssetPath=s,ri}var si={},vp;function Io(){if(vp)return si;vp=1,Object.defineProperty(si,"__esModule",{value:!0}),si.defaultModelFetcher=void 0;const d=r=>fetch(r).then(s=>s.arrayBuffer());return si.defaultModelFetcher=d,si}var qr={},ni={},_p;function hn(){if(_p)return ni;_p=1,Object.defineProperty(ni,"__esModule",{value:!0}),ni.log=void 0;const d=r=>s=>{console.log(`VAD | ${r} >`,s)};return ni.log={error:d("error"),debug:d("debug"),warn:d("warn")},ni}var ii={},bp;function qi(){if(bp)return ii;bp=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.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||(ii.Message=d={})),ii}var Sp;function Mo(){if(Sp)return qr;Sp=1,Object.defineProperty(qr,"__esModule",{value:!0}),qr.FrameProcessor=qr.validateOptions=qr.defaultFrameProcessorOptions=void 0;const d=hn(),r=qi();qr.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")}qr.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 v{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((ge,de)=>de.isSpeech?ge+1:ge,0)>=this.minSpeechFrames){const ge=a(Y.map(de=>de.frame));J({msg:r.Message.SpeechEnd,audio:ge})}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 ge=this.audioBuffer;if(this.audioBuffer=[],ge.reduce((he,pe)=>pe.isSpeech?he+1:he,0)>=this.minSpeechFrames){const he=a(ge.map(pe=>pe.frame));Y({msg:r.Message.SpeechEnd,audio:he})}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 qr.FrameProcessor=v,qr}var Wr={};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:{}};/*!
|
|
1
|
+
"use strict";const ae=require("react"),Jt=require("react/jsx-runtime");function Gp(){if(typeof window>"u")return;const d=window;d.__rqmii_orig_console||(d.__rqmii_orig_console={error:console.error,warn:console.warn,log:console.log,debug:console.debug});const r=d.__rqmii_orig_console,s=v=>{if(v.length===0)return!1;const C=String(v[0]);return C.includes("reading 'S'")||C.includes("reading 'state'")||C.includes("MicVAD has null stream")||C.includes("VAD |")||C.includes("audioCtx.state")||C.includes("using default audio context")};console.error=(...v)=>{s(v)||r.error.apply(console,v)},console.warn=(...v)=>{s(v)||r.warn.apply(console,v)},console.log=(...v)=>{s(v)||r.log.apply(console,v)},console.debug=(...v)=>{s(v)||r.debug.apply(console,v)};const a=d.onerror;d.onerror=function(v,C,R,S,N){const z=String(v);return z.includes("reading 'state'")||z.includes("reading 'S'")||z.includes("MicVAD has null stream")?!0:a?a(v,C,R,S,N):!1};const f=d.onunhandledrejection;d.onunhandledrejection=function(v){const C=String(v.reason&&v.reason.message?v.reason.message:v.reason);return C.includes("reading 'state'")||C.includes("reading 'S'")||C.includes("MicVAD has null stream")?(v.preventDefault(),!0):f?f.call(d,v):!1}}const hi={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"},qp={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 pg(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 fg(){const d=new Map;return{addChunk(r,s){const a=r||`request-${Date.now()}`,v=`${d.get(a)||""}${s||""}`;return d.set(a,v),{id:a,text:v}},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 mg(){try{const d=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof d=="string"&&d.trim()?d.trim():void 0}catch{return}}async function ei(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 gg({restUrl:d,log:r,withCredentials:s}){function a(){if(!d)throw new Error("Missing restUrl in RqmiiAgentProvider")}async function f({apiKey:N,agentId:z,userId:te,language:j="en",timezone:se,config:J,promptOverrides:Y}={}){a();const W=Y?{...J??{},prompt_overrides:Y}:J,ne={...N?{api_key:N}:{},...z?{agent_id:z}:{},...te?{user_id:te}:{},language:j,...se?{timezone:se}:{},...W?{config:W}:{}};r("initializeSession — POST /sessions/init",ne);const fe=await fetch(`${d}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ne),...s?{credentials:"include"}:{}}),ue=await ei(fe);if(!ue?.session_id||!ue?.session_token)throw new Error("Invalid initialize session response");return ue}async function v({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 ei(z);if(!te?.session_id||!te?.session_token)throw new Error("Invalid join session response");return te}async function C(N){if(!d)throw new Error("SessionManager: restUrl missing");r("fetchAgentConfig — GET /agent/{agentId}",{agentId:N});const z=await fetch(`${d}/agent/${encodeURIComponent(N)}/customization`,{method:"GET",headers:{"Content-Type":"application/json"},...s?{credentials:"include"}:{}});return ei(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 ei(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 ei(j)}return{initializeSession:f,joinDesktopSession:v,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"},Wp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Hp=typeof ArrayBuffer=="function",jp=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d&&d.buffer instanceof ArrayBuffer,xo=({type:d,data:r},s,a)=>Wp&&r instanceof Blob?s?a(r):pp(r,a):Hp&&(r instanceof ArrayBuffer||jp(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 yg(d,r){if(Wp&&d.data instanceof Blob)return d.data.arrayBuffer().then(fp).then(r);if(Hp&&(d.data instanceof ArrayBuffer||jp(d.data)))return r(fp(d.data));xo(d,!1,s=>{Ya||(Ya=new TextEncoder),r(Ya.encode(s))})}const mp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ui=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let d=0;d<mp.length;d++)ui[mp.charCodeAt(d)]=d;const wg=d=>{let r=d.length*.75,s=d.length,a,f=0,v,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)v=ui[d.charCodeAt(a)],C=ui[d.charCodeAt(a+1)],R=ui[d.charCodeAt(a+2)],S=ui[d.charCodeAt(a+3)],z[f++]=v<<2|C>>4,z[f++]=(C&15)<<4|R>>2,z[f++]=(R&3)<<6|S&63;return N},vg=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:_g(d.substring(1),r)}:Di[s]?d.length>1?{type:Di[s],data:d.substring(1)}:{type:Di[s]}:fo},_g=(d,r)=>{if(vg){const s=wg(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}},Qp="",bg=(d,r)=>{const s=d.length,a=new Array(s);let f=0;d.forEach((v,C)=>{xo(v,!1,R=>{a[C]=R,++f===s&&r(a.join(Qp))})})},Sg=(d,r)=>{const s=d.split(Qp),a=[];for(let f=0;f<s.length;f++){const v=Co(s[f],r);if(a.push(v),v.type==="error")break}return a};function Tg(){return new TransformStream({transform(d,r){yg(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 v=new DataView(f.buffer);v.setUint8(0,126),v.setUint16(1,a)}else{f=new Uint8Array(9);const v=new DataView(f.buffer);v.setUint8(0,127),v.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 Oi(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 Eg(d,r){Ja||(Ja=new TextDecoder);const s=[];let a=0,f=-1,v=!1;return new TransformStream({transform(C,R){for(s.push(C);;){if(a===0){if(Mi(s)<1)break;const S=Oi(s,1);v=(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=Oi(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=Oi(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=Oi(s,f);R.enqueue(Co(v?S:Ja.decode(S),r)),a=0}if(f===0||f>d){R.enqueue(fo);break}}}})}const Xp=4;function $t(d){if(d)return $g(d)}function $g(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")(),xg="arraybuffer";function Yp(d,...r){return r.reduce((s,a)=>(d.hasOwnProperty(a)&&(s[a]=d[a]),s),{})}const Cg=ur.setTimeout,kg=ur.clearTimeout;function Gi(d,r){r.useNativeTimers?(d.setTimeoutFn=Cg.bind(ur),d.clearTimeoutFn=kg.bind(ur)):(d.setTimeoutFn=ur.setTimeout.bind(ur),d.clearTimeoutFn=ur.clearTimeout.bind(ur))}const Rg=1.33;function Ag(d){return typeof d=="string"?Ig(d):Math.ceil((d.byteLength||d.size)*Rg)}function Ig(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 Jp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Mg(d){let r="";for(let s in d)d.hasOwnProperty(s)&&(r.length&&(r+="&"),r+=encodeURIComponent(s)+"="+encodeURIComponent(d[s]));return r}function Og(d){let r={},s=d.split("&");for(let a=0,f=s.length;a<f;a++){let v=s[a].split("=");r[decodeURIComponent(v[0])]=decodeURIComponent(v[1])}return r}class Pg 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 Pg(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=Mg(r);return s.length?"?"+s:""}}class Dg 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)};Sg(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,bg(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]=Jp()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(r,s)}}let Zp=!1;try{Zp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const zg=Zp;function Lg(){}class Bg extends Dg{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,v)=>{this.onError("xhr post error",f,v)})}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=Yp(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=Lg,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 ur?"pagehide":"unload";addEventListener(d,gp,!1)}}function gp(){for(let d in Pr.requests)Pr.requests.hasOwnProperty(d)&&Pr.requests[d].abort()}const Ng=(function(){const d=ef({xdomain:!1});return d&&d.responseType!==null})();class Ug extends Bg{constructor(r){super(r);const s=r&&r.forceBase64;this.supportsBinary=Ng&&!s}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Pr(ef,this.uri(),r)}}function ef(d){const r=d.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||zg))return new XMLHttpRequest}catch{}if(!r)try{return new ur[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const tf=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Fg extends ko{get name(){return"websocket"}doOpen(){const r=this.uri(),s=this.opts.protocols,a=tf?{}:Yp(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,v=>{try{this.doWrite(a,v)}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]=Jp()),this.supportsBinary||(s.b64=1),this.createUri(r,s)}}const Za=ur.WebSocket||ur.MozWebSocket;class Vg extends Fg{createSocket(r,s,a){return tf?new Za(r,s,a):s?new Za(r,s):new Za(r)}doWrite(r,s){this.ws.send(s)}}class Gg 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=Eg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(s).getReader(),f=Tg();f.readable.pipeTo(r.writable),this._writer=f.writable.getWriter();const v=()=>{a.read().then(({done:R,value:S})=>{R||(this.onPacket(S),v())}).catch(R=>{})};v();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 qg={websocket:Vg,webtransport:Gg,polling:Ug},Wg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Hg=["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=Wg.exec(d||""),v={},C=14;for(;C--;)v[Hg[C]]=f[C]||"";return s!=-1&&a!=-1&&(v.source=r,v.host=v.host.substring(1,v.host.length-1).replace(/;/g,":"),v.authority=v.authority.replace("[","").replace("]","").replace(/;/g,":"),v.ipv6uri=!0),v.pathNames=jg(v,v.path),v.queryKey=Kg(v,v.query),v}function jg(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 Kg(d,r){const s={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,v){f&&(s[f]=v)}),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=xg,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=Og(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=Xp,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+=Ag(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 v={type:r,data:s,options:a};this.emitReserved("packetCreate",v),this.writeBuffer.push(v),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=Xp;class Qg 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 v(){a||(a=!0,z(),s.close(),s=null)}const C=te=>{const j=new Error("probe error: "+te);j.transport=s.name,v(),this.emitReserved("upgradeError",j)};function R(){C("transport closed")}function S(){C("socket closed")}function N(te){s&&te.name!==s.name&&v()}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 Xg=class extends Qg{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=>qg[f]).filter(f=>!!f)),super(r,a)}};function Yg(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 v=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+v+":"+a.port+r,a.href=a.protocol+"://"+v+(s&&s.port===a.port?"":":"+a.port),a}const Jg=typeof ArrayBuffer=="function",Zg=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d.buffer instanceof ArrayBuffer,rf=Object.prototype.toString,ey=typeof Blob=="function"||typeof Blob<"u"&&rf.call(Blob)==="[object BlobConstructor]",ty=typeof File=="function"||typeof File<"u"&&rf.call(File)==="[object FileConstructor]";function Ro(d){return Jg&&(d instanceof ArrayBuffer||Zg(d))||ey&&d instanceof Blob||ty&&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 ry(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 sy(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 ny=["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 iy{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=ry(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 ay(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 v=s+1;for(;r.charAt(++s)!=="-"&&s!=r.length;);const C=r.substring(v,s);if(C!=Number(C)||r.charAt(s)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!oy(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 v=s+1;for(;++s&&!(r.charAt(s)===","||s===r.length););a.nsp=r.substring(v,s)}else a.nsp="/";const f=r.charAt(s+1);if(f!==""&&Number(f)==f){const v=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(v,s+1))}if(r.charAt(++s)){const v=this.tryParse(r.substr(s));if(Ao.isPayloadValid(a.type,v))a.data=v;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"&&ny.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 ay{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=sy(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const oy=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 ly=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ao,Encoder:iy,get PacketType(){return Xe}},Symbol.toStringTag,{value:"Module"}));function Sr(d,r,s){return d.on(r,s),function(){d.off(r,s)}}const uy=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class sf 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,v;if(uy.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&&!(!((v=this.io.engine)===null||v===void 0)&&v._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 v=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(v),s.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...s){return new Promise((a,f)=>{const v=(C,R)=>C?f(C):a(R);v.withError=!0,s.push(v),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,...v)=>(this._queue[0],f!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),s&&s(f)):(this._queue.shift(),s&&s(null,...v)),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||ly;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 Xg(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()}),v=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=Sr(s,"error",v);if(this._timeout!==!1){const R=this._timeout,S=this.setTimeoutFn(()=>{f(),v(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 sf(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 ti={};function Bi(d,r){typeof d=="object"&&(r=d,d=void 0),r=r||{};const s=Yg(d,r.path||"/socket.io"),a=s.source,f=s.id,v=s.path,C=ti[f]&&v in ti[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let S;return R?S=new vo(a,r):(ti[f]||(ti[f]=new vo(a,r)),S=ti[f]),s.query&&!r.query&&(r.query=s.queryKey),S.socket(s.path,r)}Object.assign(Bi,{Manager:vo,Socket:sf,io:Bi,connect:Bi});function dy({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 v(){return s}return{connectSocketRaw:a,cleanupSocket:f,getSocket:v}}const cy=d=>{if(window.audioCtx=d,d.state!=="suspended")return;const r=document.body,s=["touchstart","touchend","mousedown","keydown"];s.forEach(v=>r.addEventListener(v,a,!1));function a(){d.resume().then(f)}function f(){s.forEach(v=>r.removeEventListener(v,a))}};function Pt(d){this.init(d)}Pt.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()};Pt.prototype.getMaxValue=function(){var d={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Pt.prototype.getTypedArray=function(){var d={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Pt.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),cy(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Pt.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};Pt.prototype.isTypedArray=function(d){return d.byteLength&&d.buffer&&d.buffer.constructor==ArrayBuffer};Pt.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()}};Pt.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};Pt.prototype.volume=function(d){this.gainNode.gain.value=d};Pt.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Pt.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};Pt.prototype.setRequestStop=function(){this.flag_request_stop=!0};Pt.prototype.setOnEnd=function(d){this.onEnd=d};Pt.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};Pt.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)}})();Pt.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Pt.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,v,C,R;for(f=0;f<this.option.channels;f++)for(a=s.getChannelData(f),v=f,R=50,C=0;C<r;C++)a[C]=this.samples[v],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),v+=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 hy(d,r){const s=new Pt(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 py({enableAudio:d,pcmOptions:r,log:s,onPlaybackComplete:a}){let f=null,v=null;function C(){if(!d||f)return f;const W={...qp,...r||{}};return f=hy(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){v=W||null}function J(){return v}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 fy(d){const{wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:v,withCredentials:C,onPlaybackComplete:R}=d,S=ae.useCallback((...j)=>{v&&console.log("[RqmiiSDK]",...j)},[v]),N=ae.useRef(null),z=ae.useRef(null),te=ae.useRef(null);return N.current||(N.current=dy({wsUrl:r,log:S})),z.current||(z.current=py({enableAudio:a,pcmOptions:f,log:S,onPlaybackComplete:R})),te.current||(te.current=gg({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 my(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 gy(d){const{socket:r,dispatch:s,stateRef:a,sessionIdRef:f,sessionAgentTypeRef:v,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(ue=>ue.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(ue=>ue.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(v.current);if(ne==="cloud_avatar"||ne==="desktop_avatar"||ne==="text")return;const fe=my(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(v.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,ue=W?.parameters??{},he=W?.waitForResponse!==!1;if(!fe)return;const pe=N.current[fe];if(!pe)return;const ce={minimize:()=>se.emit("minimize_chat"),maximize:()=>se.emit("maximize_chat")};he&&ne?pe(ue,ce).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(ue,ce).catch(()=>{})})}class nf{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 af=ae.createContext(null);function of({children:d,wsUrl:r="wss://ws.rqmii.com",restUrl:s="https://api.rqmii.com",enableAudio:a=!0,pcmOptions:f,debug:v=!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(fg()),fe=ae.useRef(null),ue=ae.useRef(po.session.agentType),he=ae.useRef(!1),pe=ae.useRef(new nf),ce=ae.useRef({}),Ve=ae.useRef({onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te});ae.useEffect(()=>{Gp(),Ve.current={onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te}},[S,N,z,te]),ae.useEffect(()=>{ue.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}=fy({wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:v,withCredentials:R,onPlaybackComplete:me}),Je=ae.useCallback(be=>{gy({socket:be,dispatch:Y,stateRef:J,sessionIdRef:fe,sessionAgentTypeRef:ue,interruptedRef:he,manualDisconnectRef:W,chunkAccumulatorRef:ne,clientToolsRef:ce,audioMgrRef:{current:qe.current},enableAudio:a,cbRefs:Ve,eventsEmitter:pe.current})},[a]),at=ae.useCallback(({authPayload:be,queryToken:Ze})=>new Promise((qt,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}),qt(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,he.current=!1,ne.current.clear(),qe.current.destroyPcmPlayer(),Ye.current.cleanupSocket(),be||(W.current=!1),Y({type:"HARD_RESET"})},[]),Gt=ae.useCallback(async({apiKey:be,agentId:Ze,userId:qt,language:nr="en",clientTools:It,config:xr,promptOverrides:yt}={})=>{if(!be&&!Ze)throw new Error("Provide one of apiKey or agentId");tt(),ce.current=It??{},Y({type:"SET_CONNECTION_STATE",payload:pt.INITIALIZING}),Y({type:"SET_ERROR",payload:null});const Lr=mg();let Br;try{Br=await it.current.initializeSession({apiKey:be,agentId:Ze,userId:qt,language:nr,timezone:Lr,config:xr,promptOverrides: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 Bt=Br;Y({type:"UPDATE_SESSION",payload:{sessionId:Bt.session_id,agentType:Bt.streaming_url?hi.CLOUD_AVATAR:j.session.agentType,streamingUrl:Bt.streaming_url||null,uniqueId:Bt.unique_id||null}}),Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Bt.streaming_url?Zt.CONNECTING:Zt.IDLE,error:null}}),W.current=!0;try{await at({authPayload:{token:Bt.session_token},queryToken:Bt.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(!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 qt=Ze;Y({type:"UPDATE_SESSION",payload:{sessionId:qt.session_id,uniqueId:be,role:"user",agentType:hi.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:qt.session_token},queryToken:qt.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 qt=Ye.current?.getSocket();return!qt||!j.isConnected?!1:(qt.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(()=>(he.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=>{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=>{Object.keys(ce.current).length===0?ce.current=be:Object.assign(ce.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(()=>pg(j.sessionState),[j.sessionState]),zr=ae.useMemo(()=>({...j,...qs,initializeSession:Gt,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,Gt,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(af.Provider,{value:zr,children:d})}function Fs(){const d=ae.useContext(af);if(!d)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return d}function lf(){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 yy(){const d=Fs();return{messages:d.messages,sendTextMessage:d.sendTextMessage,addLocalMessage:d.addLocalMessage,emitUserMessage:d.emitUserMessage,clearMessages:d.clearMessages}}function wy(){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 uf(){const d=Fs(),r=d.cloudStream?.state||Zt.IDLE;return{streamingUrl:d.session.streamingUrl,isAvatarSpeaking:d.isAvatarSpeaking,speakingSource:"avatar_events",isCloudAvatar:d.session.agentType===hi.CLOUD_AVATAR,isDesktopAvatar:d.session.agentType===hi.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={},ri={},wp;function df(){if(wp)return ri;wp=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.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(/\/[^/]+$/,"/")),ri.baseAssetPath=s,ri}var si={},vp;function Io(){if(vp)return si;vp=1,Object.defineProperty(si,"__esModule",{value:!0}),si.defaultModelFetcher=void 0;const d=r=>fetch(r).then(s=>s.arrayBuffer());return si.defaultModelFetcher=d,si}var Wr={},ni={},_p;function pn(){if(_p)return ni;_p=1,Object.defineProperty(ni,"__esModule",{value:!0}),ni.log=void 0;const d=r=>s=>{console.log(`VAD | ${r} >`,s)};return ni.log={error:d("error"),debug:d("debug"),warn:d("warn")},ni}var ii={},bp;function qi(){if(bp)return ii;bp=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.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||(ii.Message=d={})),ii}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=pn(),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 v{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,ue)=>ue.isSpeech?fe+1:fe,0)>=this.minSpeechFrames){const fe=a(Y.map(ue=>ue.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((he,pe)=>pe.isSpeech?he+1:he,0)>=this.minSpeechFrames){const he=a(fe.map(pe=>pe.frame));Y({msg:r.Message.SpeechEnd,audio:he})}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=v,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 vy(){return Tp||(Tp=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=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 v(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)})]}}),ge=S(()=>{ne()}),de,he=S(()=>{de="1.26.0"}),pe,ce,Ve=S(()=>{he(),pe="warning",ce={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(ce,"logLevel",{enumerable:!0})}),fe,Ye=S(()=>{Ve(),fe=ce}),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,_=m*2,b=-1;u==="RGBA"?(g=0,w=m,_=m*2,b=m*3):u==="RGB"?(g=0,w=m,_=m*2):u==="RBG"&&(g=0,_=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],O=(e.data[_++]-p[2])*h[2],I=b===-1?255:(e.data[b++]-p[3])*h[3];i.fillStyle="rgba("+k+","+$+","+O+","+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,_=0,b=1,x=2,M=3,k=0,$=g,O=g*2,I=-1;c==="RGBA"?(k=0,$=g,O=g*2,I=g*3):c==="RGB"?(k=0,$=g,O=g*2):c==="RBG"&&(k=0,O=g,$=g*2),i=n.createImageData(o,l);for(let B=0;B<l*o;_+=w,b+=w,x+=w,M+=w,B++)i.data[_]=(e.data[k++]-m[0])*p[0],i.data[b]=(e.data[$++]-m[1])*p[1],i.data[x]=(e.data[O++]-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,Gt,xt,Ke,We,st=S(()=>{$r(),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,_=1,b=2,x=3,M=0,k=p,$=p*2,O=-1;c==="RGB"&&(g=3,w=0,_=1,b=2,x=-1),h==="RGBA"?O=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,_+=g,x+=g)m[M++]=(e[w]+u[0])/l[0],m[k++]=(e[_]+u[1])/l[1],m[$++]=(e[b]+u[2])/l[2],O!==-1&&x!==-1&&(m[O++]=(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,_=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(w=t.resizedHeight,_=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=_}else c.tensorFormat="RGBA",c.height=w,c.width=_;g.drawImage(e,0,0),u=g.getImageData(0,0,_,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 _=p(w);if(_!=null)_.putImageData(e,0,0),u=_.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,_=e.width;return g.drawImage(e,0,0,_,w),u=g.getImageData(0,0,_,w).data,c.height=w,c.width=_,at(u,c)}else throw new Error("Can not access image data")}else{if(l)return new Promise((m,g)=>{let w=h(),_=p(w);if(!e||!_)return g();let b=new Image;b.crossOrigin="Anonymous",b.src=e,b.onload=()=>{w.width=b.width,w.height=b.height,_.drawImage(b,0,0,w.width,w.height);let x=_.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")},Gt=(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,Qr,Fs=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,Qr=()=>{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)}}}),Xr,Yr,Vs=S(()=>{$r(),Xr=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},Yr=(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,$r=S(()=>{Je(),st(),Fs(),Vs(),rt=class{constructor(e,t,n){Qr();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=Xr(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 Gt(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 Yr(this,e)}}}),lt,Jr=S(()=>{$r(),lt=rt}),Zt,xr,gt,ft,At,Ct,Zr=S(()=>{Ve(),Zt=(e,t)=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.timeStamp(`${e}::ORT::${t}`)},xr=(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}`),Zt("CPU",l);return}n[o].includes("TRACE_FUNC")&&(i=!0)}},gt=e=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||xr("BEGIN",e)},ft=e=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||xr("END",e)},At=e=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.time(`ORT::${e}`)},Ct=e=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.timeEnd(`ORT::${e}`)}}),es,Gs=S(()=>{ne(),Jr(),Zr(),es=class cf{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 cf(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}}}),Lr,be=S(()=>{Gs(),Lr=es}),Ze=S(()=>{}),qt=S(()=>{}),nr=S(()=>{}),It=S(()=>{}),Cr={};N(Cr,{InferenceSession:()=>Lr,TRACE:()=>Zt,TRACE_EVENT_BEGIN:()=>At,TRACE_EVENT_END:()=>Ct,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>ft,Tensor:()=>lt,env:()=>fe,registerBackend:()=>J});var yt=S(()=>{ge(),Ye(),be(),Jr(),Ze(),qt(),Zr(),nr(),It()}),cr=S(()=>{}),er={};N(er,{default:()=>fn});var ir,Lt,fn,Wi=S(()=>{Yh(),Wt(),fs(),ir="ort-wasm-proxy-worker",Lt=globalThis.self?.name===ir,Lt&&(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=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})}}),fn=Lt?null:e=>new Worker(e??ot,{type:"classic",name:ir})}),mn,gn,ot,ds,Br,yn,wn,cs,vn,hs,_n,ps,bn,fs=S(()=>{cr(),mn=typeof location>"u"?void 0:location.origin,gn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,ot=gn(),ds=()=>{if(ot&&!ot.startsWith("blob:"))return ot.substring(0,ot.lastIndexOf("/")+1)},Br=(e,t)=>{try{let n=t??ot;return(n?new URL(e,n):new URL(e)).origin===mn}catch{return!1}},yn=(e,t)=>{let n=t??ot;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},wn=(e,t)=>`${t??"./"}${e}`,cs=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},vn=async e=>(await import(e)).default,hs=(Wi(),te(er)).default,_n=async()=>{if(!ot)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Br(ot))return[void 0,hs()];let e=await cs(ot);return[e,hs(e)]},ps=void 0,bn=async(e,t,n,i)=>{let o=ps&&!(e||t);if(o)if(ot)o=Br(ot)||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??yn(l,t),c=n&&u&&!Br(u,t),h=c?await cs(u):u??wn(l,t);return[c?h:void 0,await vn(h)]}}}),ms,Nr,hr,gs,Sn,Tn,En,ys,Oe,Wt=S(()=>{fs(),Nr=!1,hr=!1,gs=!1,Sn=()=>{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}},Tn=()=>{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}},En=()=>{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(Nr)return Promise.resolve();if(hr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(gs)throw new Error("previous call to 'initializeWebAssembly()' failed.");hr=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!En())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Tn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=Sn();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 bn(c,l,n>1,!!m||!!p),_=!1,b=[];if(t>0&&b.push(new Promise(x=>{setTimeout(()=>{_=!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 $=ds();$&&(k.locateFile=O=>$+O)}w(k).then($=>{hr=!1,Nr=!0,ms=$,x(),g&&URL.revokeObjectURL(g)},$=>{hr=!1,gs=!0,M($)})})),await Promise.race(b),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Oe=()=>{if(Nr&&ms)return ms;throw new Error("WebAssembly is not initialized yet.")}}),mt,Ur,Ce,ws=S(()=>{Wt(),mt=(e,t)=>{let n=Oe(),i=n.lengthBytesUTF8(e)+1,o=n._malloc(i);return n.stringToUTF8(e,o,i),t.push(o),o},Ur=(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")Ur(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=Oe(),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)}}}),$n,Hi=S(()=>{Wt(),ws(),$n=e=>{let t=Oe(),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&&Ur(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}}}),xn,Cn,kn,Nt,Rn,An,ji=S(()=>{Wt(),ws(),xn=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}`)}},Cn=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},kn=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)},Nt=(e,t,n,i)=>{let o=mt(t,i),l=mt(n,i);Oe()._OrtAddSessionConfigEntry(e,o,l)!==0&&Ce(`Can't set a session config entry: ${t} - ${n}.`)},Rn=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",Nt(e,"session.disable_quant_qdq","1",n),Nt(e,"session.disable_qdq_constant_folding","1",n),typeof o!="string"){let g=o?.deviceType;g&&Nt(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}`);Nt(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=Oe()._malloc(h*Oe().PTR_SIZE),n.push(p),m=Oe()._malloc(h*Oe().PTR_SIZE),n.push(m);for(let g=0;g<h;g++)Oe().setValue(p+g*Oe().PTR_SIZE,u[g][0],"*"),Oe().setValue(m+g*Oe().PTR_SIZE,u[g][1],"*")}await Oe()._OrtAppendExecutionProvider(e,c,p,m,h)!==0&&Ce(`Can't append execution provider: ${l}.`)}},An=async e=>{let t=Oe(),n=0,i=[],o=e||{};kn(o);try{let l=xn(o.graphOptimizationLevel??"all"),u=Cn(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 Rn(n,o,i),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);Nt(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 _=mt(g,i);t._OrtAddFreeDimensionOverride(n,_,w)!==0&&Ce(`Can't set a free dimension override: ${g} - ${w}.`)}return o.extra!==void 0&&Ur(o.extra,"",new WeakSet,(g,w)=>{Nt(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}}}),Ht,jt,Kt,vs,_s,bs,Ss,qs,Ie=S(()=>{Ht=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}`)}},Kt=(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",qs=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,In=S(()=>{cr(),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)}}),Mn,Ws,Hs,kr,js,Ks,He,tr=S(()=>{Ie(),Mn=["V","I","W","E","F"],Ws=(e,t)=>{console.log(`[${Mn[e]},${new Date().toISOString()}]${t}`)},js=(e,t)=>{Hs=e,kr=t},Ks=(e,t)=>{let n=_s(e),i=_s(Hs);n>=i&&Ws(n,typeof t=="function"?t():t)},He=(...e)=>{kr&&Ks(...e)}}),Qs,Rr,K,ts,Xs,On,pr,ke=S(()=>{Qs=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Rr=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=Qs.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])}},ts=class di{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++)di.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 di.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 di.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(di.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)}},Xs=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&&!Rr.isValidBroadcast(o,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,u]}},On=-34028234663852886e22,pr=34028234663852886e22}),Ar,rs=S(()=>{Ie(),Ar=(e,t)=>new(vs(t))(e)}),Fr,ss,Es,$s,fr,Ir,Ys,Js,Zs,Pn,Dn,fi=S(()=>{Ie(),tr(),Fr=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),ss=(e,t)=>{if(t==="int32")return e;let n=Fr.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,fr=()=>$s++,Ir=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Ys=(e,t)=>{let n=Fr.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},Js=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 Ys(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}},Zs=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=Ir.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!==Ys(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=ss(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=fr();return this.tensorTrackersById.set(e,new Zs(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=fr(),u=new Js({sessionId:e,context:o,tensor:t,dataType:n,shape:i});return this.tensorTrackersById.set(l,new Zs(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 Js({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)}},Dn=(...e)=>new Pn(...e)}),ns,zn,Ln,Bn=S(()=>{Ie(),Wt(),rs(),fi(),tr(),ns=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),zn=(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])},Ln=class{constructor(e){this.tensorManager=Dn(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,js(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=>zn(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=ns.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=ns.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(!Oe().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 Ar(n,t)}}registerMLTensor(e,t,n,i){let o=ns.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=ss(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=ns.get(Ht(t)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:n?!!o?.input.dataTypes.includes(i):!!o?.output.dataTypes.includes(i)}flush(){}}}),en=S(()=>{}),tn,rn,xs,sn,nn,an,Nn,Un,mi,Ki=S(()=>{tr(),en(),tn=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]]),rn=[],xs=e=>Math.ceil(Number(e)/16)*16,sn=e=>{for(let t=0;t<rn.length;t++){let n=rn[t];if(e<=n)return n}return Math.ceil(e/16)*16},nn=1,an=()=>nn++,Nn=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()}},Un=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 tn)rn.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=
|
|
5
|
+
*/var Tp;function vy(){return Tp||(Tp=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=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 v(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()}),ue,he=S(()=>{ue="1.26.0"}),pe,ce,Ve=S(()=>{he(),pe="warning",ce={wasm:{},webgl:{},webgpu:{},versions:{common:ue},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(ce,"logLevel",{enumerable:!0})}),me,Ye=S(()=>{Ve(),me=ce}),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,_=m*2,b=-1;u==="RGBA"?(g=0,w=m,_=m*2,b=m*3):u==="RGB"?(g=0,w=m,_=m*2):u==="RBG"&&(g=0,_=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],O=(e.data[_++]-p[2])*h[2],I=b===-1?255:(e.data[b++]-p[3])*h[3];i.fillStyle="rgba("+k+","+$+","+O+","+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,_=0,b=1,x=2,M=3,k=0,$=g,O=g*2,I=-1;c==="RGBA"?(k=0,$=g,O=g*2,I=g*3):c==="RGB"?(k=0,$=g,O=g*2):c==="RBG"&&(k=0,O=g,$=g*2),i=n.createImageData(o,l);for(let B=0;B<l*o;_+=w,b+=w,x+=w,M+=w,B++)i.data[_]=(e.data[k++]-m[0])*p[0],i.data[b]=(e.data[$++]-m[1])*p[1],i.data[x]=(e.data[O++]-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,Gt,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,_=1,b=2,x=3,M=0,k=p,$=p*2,O=-1;c==="RGB"&&(g=3,w=0,_=1,b=2,x=-1),h==="RGBA"?O=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,_+=g,x+=g)m[M++]=(e[w]+u[0])/l[0],m[k++]=(e[_]+u[1])/l[1],m[$++]=(e[b]+u[2])/l[2],O!==-1&&x!==-1&&(m[O++]=(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,_=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(w=t.resizedHeight,_=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=_}else c.tensorFormat="RGBA",c.height=w,c.width=_;g.drawImage(e,0,0),u=g.getImageData(0,0,_,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 _=p(w);if(_!=null)_.putImageData(e,0,0),u=_.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,_=e.width;return g.drawImage(e,0,0,_,w),u=g.getImageData(0,0,_,w).data,c.height=w,c.width=_,at(u,c)}else throw new Error("Can not access image data")}else{if(l)return new Promise((m,g)=>{let w=h(),_=p(w);if(!e||!_)return g();let b=new Image;b.crossOrigin="Anonymous",b.src=e,b.onload=()=>{w.width=b.width,w.height=b.height,_.drawImage(b,0,0,w.width,w.height);let x=_.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")},Gt=(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 Gt(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 ce.trace>"u"?!ce.wasm.trace:!ce.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 ce.trace>"u"?!ce.wasm.trace:!ce.trace)||$r("BEGIN",e)},ft=e=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||$r("END",e)},At=e=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.time(`ORT::${e}`)},Ct=e=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.timeEnd(`ORT::${e}`)}}),ts,qs=S(()=>{ne(),Zr(),es(),ts=class cf{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 cf(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(()=>{}),qt=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(),qt(),es(),nr(),It()}),Lr=S(()=>{}),Br={};N(Br,{default:()=>Wt});var Bt,ir,Wt,Wi=S(()=>{Yh(),Ht(),ms(),Bt="ort-wasm-proxy-worker",ir=globalThis.self?.name===Bt,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:Bt})}),mn,gn,ot,cs,Nr,yn,wn,hs,vn,ps,_n,fs,bn,ms=S(()=>{Lr(),mn=typeof location>"u"?void 0:location.origin,gn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,ot=gn(),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===mn}catch{return!1}},yn=(e,t)=>{let n=t??ot;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},wn=(e,t)=>`${t??"./"}${e}`,hs=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},vn=async e=>(await import(e)).default,ps=(Wi(),te(Br)).default,_n=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,bn=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??yn(l,t),c=n&&u&&!Nr(u,t),h=c?await hs(u):u??wn(l,t);return[c?h:void 0,await vn(h)]}}}),gs,Ur,cr,ys,Sn,Tn,En,ws,Oe,Ht=S(()=>{ms(),Ur=!1,cr=!1,ys=!1,Sn=()=>{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}},Tn=()=>{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}},En=()=>{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(!En())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Tn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=Sn();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 bn(c,l,n>1,!!m||!!p),_=!1,b=[];if(t>0&&b.push(new Promise(x=>{setTimeout(()=>{_=!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=O=>$+O)}w(k).then($=>{cr=!1,Ur=!0,gs=$,x(),g&&URL.revokeObjectURL(g)},$=>{cr=!1,ys=!0,M($)})})),await Promise.race(b),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Oe=()=>{if(Ur&&gs)return gs;throw new Error("WebAssembly is not initialized yet.")}}),mt,Fr,Ce,vs=S(()=>{Ht(),mt=(e,t)=>{let n=Oe(),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=Oe(),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)}}}),$n,Hi=S(()=>{Ht(),vs(),$n=e=>{let t=Oe(),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}}}),xn,Cn,kn,Nt,Rn,An,ji=S(()=>{Ht(),vs(),xn=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}`)}},Cn=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},kn=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)},Nt=(e,t,n,i)=>{let o=mt(t,i),l=mt(n,i);Oe()._OrtAddSessionConfigEntry(e,o,l)!==0&&Ce(`Can't set a session config entry: ${t} - ${n}.`)},Rn=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",Nt(e,"session.disable_quant_qdq","1",n),Nt(e,"session.disable_qdq_constant_folding","1",n),typeof o!="string"){let g=o?.deviceType;g&&Nt(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}`);Nt(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=Oe()._malloc(h*Oe().PTR_SIZE),n.push(p),m=Oe()._malloc(h*Oe().PTR_SIZE),n.push(m);for(let g=0;g<h;g++)Oe().setValue(p+g*Oe().PTR_SIZE,u[g][0],"*"),Oe().setValue(m+g*Oe().PTR_SIZE,u[g][1],"*")}await Oe()._OrtAppendExecutionProvider(e,c,p,m,h)!==0&&Ce(`Can't append execution provider: ${l}.`)}},An=async e=>{let t=Oe(),n=0,i=[],o=e||{};kn(o);try{let l=xn(o.graphOptimizationLevel??"all"),u=Cn(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 Rn(n,o,i),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);Nt(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 _=mt(g,i);t._OrtAddFreeDimensionOverride(n,_,w)!==0&&Ce(`Can't set a free dimension override: ${g} - ${w}.`)}return o.extra!==void 0&&Fr(o.extra,"",new WeakSet,(g,w)=>{Nt(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,In=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)}}),Mn,Hs,js,Cr,Ks,Qs,He,tr=S(()=>{Ie(),Mn=["V","I","W","E","F"],Hs=(e,t)=>{console.log(`[${Mn[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,On,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 di{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++)di.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 di.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 di.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(di.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]}},On=-34028234663852886e22,hr=34028234663852886e22}),Rr,ss=S(()=>{Ie(),Rr=(e,t)=>new(_s(t))(e)}),Vr,ns,$s,xs,pr,Ar,Js,Zs,en,Pn,Dn,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)}},Dn=(...e)=>new Pn(...e)}),is,zn,Ln,Bn=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"]]),zn=(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])},Ln=class{constructor(e){this.tensorManager=Dn(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=>zn(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(!Oe().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,Nn,Un,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++,Nn=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()}},Un=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 Nn(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 Un(...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,P,G,U,L,V,re,ie,Z,Q,Te,F,le,ut,Be,Ee,Ne,we=S(()=>{Ie(),ke(),D=64,P=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}<f16>`:"f16";case 1:return t>1?`vec${t}<f32>`:"f32";case 6:return t>1?`vec${t}<i32>`:"i32";case 12:return t>1?`vec${t}<u32>`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4<bool>"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},G=(e,t=1)=>{let n=P(e,t);return typeof n=="string"?n:n[0]},U=(e,t=1)=>{let n=P(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=P(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},_=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
7
|
let dim${oe} = current / ${Q(k,oe,u)};
|
|
8
8
|
let rest${oe} = current % ${Q(k,oe,u)};
|
|
9
9
|
indices[${oe}] = dim${oe};
|
|
@@ -17,7 +17,7 @@
|
|
|
17
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
|
-
}`,H=oe=>(b.indicesToOffset=!0,u<2?oe:`i2o_${e}(${oe})`),ee=(...oe)=>u===0?"0u":`${w.indices}(${oe.map(_).join(",")})`,
|
|
20
|
+
}`,H=oe=>(b.indicesToOffset=!0,u<2?oe:`i2o_${e}(${oe})`),ee=(...oe)=>u===0?"0u":`${w.indices}(${oe.map(_).join(",")})`,de=(oe,Pe)=>u<2?`${oe}`:`${Q(oe,Pe,u)}`,_e=(oe,Pe,Ae)=>u<2?`${oe}=${Ae};`:`${Q(oe,Pe,u)}=${Ae};`,Fe={},Re=(oe,Pe)=>{b.broadcastedIndicesToOffset=!0;let Ae=`${Pe.name}broadcastedIndicesTo${e}Offset`;if(Ae in Fe)return`${Ae}(${oe})`;let $e=[];for(let Dt=u-1;Dt>=0;Dt--){let Xt=Pe.indicesGet("outputIndices",Dt+Pe.rank-u);$e.push(`${de(k,Dt)} * (${Xt} % ${de(M,Dt)})`)}return Fe[Ae]=`fn ${Ae}(outputIndices: ${Pe.type.indices}) -> u32 {
|
|
21
21
|
return ${$e.length>0?$e.join("+"):"0u"};
|
|
22
22
|
}`,`${Ae}(${oe})`},Me=(oe,Pe)=>(()=>{if(w.storage===w.value)return`${e}[${oe}]=${Pe};`;if(w.storage==="vec2<u32>"&&w.value==="i32")return`${e}[${oe}]=vec2<u32>(u32(${Pe}), select(0u, 0xFFFFFFFFu, ${Pe} < 0));`;if(w.storage==="vec2<u32>"&&w.value==="u32")return`${e}[${oe}]=vec2<u32>(u32(${Pe}), 0u);`;if(w.storage==="u32"&&w.value==="vec4<bool>")return`${e}[${oe}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${Pe}));`;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} {
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
fn set_${e}(${oe}, value: ${m}) {
|
|
33
33
|
set_${e}ByIndices(${ee(Pe)}, value);
|
|
34
34
|
}`})();return{impl:()=>{let oe=[],Pe=!1;return b.offsetToIndices&&(oe.push(O),Pe=!0),b.indicesToOffset&&(oe.push(q),Pe=!0),b.broadcastedIndicesToOffset&&(Object.values(Fe).forEach(Ae=>oe.push(Ae)),Pe=!0),b.set&&(oe.push(je),Pe=!0),b.setByIndices&&(oe.push(De),Pe=!0),b.get&&(oe.push(xe),Pe=!0),b.getByIndices&&(oe.push(ye),Pe=!0),!l&&Pe&&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:
|
|
35
|
+
`)},type:w,offsetToIndices:I,indicesToOffset:H,broadcastedIndicesToOffset:Re,indices:ee,indicesGet:de,indicesSet:_e,set:(...oe)=>{if(oe.length!==u+1)throw new Error(`indices length must be ${u}`);let Pe=oe[u];if(typeof Pe!="string")throw new Error("value must be string");let Ae=oe.slice(0,u).map(_).join(",");return u===0?Me("0u",Pe):u===1?Me(Ae[0],Pe):(b.set=!0,b.setByIndices=!0,b.indicesToOffset=!0,`set_${e}(${Ae}, ${Pe})`)},setByOffset:Me,setByIndices:(oe,Pe)=>u<2?Me(oe,Pe):(b.setByIndices=!0,b.indicesToOffset=!0,`set_${e}ByIndices(${oe}, ${Pe});`),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,13 +50,13 @@
|
|
|
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 Ee(e,t)}),kt,Mt,
|
|
54
|
-
var a: ${n.type.indices};`;for(let l=0;l<t;++l)o+=`a[${e[l]}]=i[${l}];`;return o+="return a;}"},
|
|
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,Fn,ct,ar,Vn,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}},Fn=(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||Fn(o,e.dims),p;if(h)return p=b=>{let x=F("input",n,u,4),M=le("output",n,c,4);return`
|
|
55
55
|
${b.registerUniform("output_size","u32").declareVariables(x,M)}
|
|
56
56
|
${b.mainStart()}
|
|
57
57
|
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
58
58
|
output[global_idx] = input[global_idx];
|
|
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}=
|
|
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]),_=K.areEqual(g,[3,1,2]);if(m.length===2||w||_){u=w?[m[0],m[1]*m[2]]:_?[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
61
|
var<workgroup> tile : array<array<${k.type.value}, ${b+1}>, ${b}>;
|
|
62
62
|
${x.mainStart([b,b,1])}
|
|
@@ -78,7 +78,7 @@
|
|
|
78
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
79
|
${b.registerUniform("output_size","u32").declareVariables(x,M)}
|
|
80
80
|
|
|
81
|
-
${
|
|
81
|
+
${as(o,i,x,M)}
|
|
82
82
|
|
|
83
83
|
${b.mainStart()}
|
|
84
84
|
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -87,7 +87,7 @@
|
|
|
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 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))},Vn=e=>E({perm:e.perm})}),rr,gi,
|
|
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))},Vn=e=>E({perm:e.perm})}),rr,gi,fr,ks,wt,Lt,un,Rs,Gn,yi,Et,mr,os,vt,ht,or,wi,vi,Oo,Po,Do,gm=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},Gn=(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 _=`
|
|
91
91
|
var<workgroup> aBestValues : array<f32, ${w}>;
|
|
92
92
|
`,b=x=>`
|
|
93
93
|
${x.registerUniform("reduceSize","u32").declareVariables(m,g)}
|
|
@@ -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")});
|
|
@@ -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: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((_,b)=>b));let u=K.normalizeAxes(l,e.inputs[0].dims.length),c=u,h=e.inputs[0],p=Gn(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]=
|
|
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((_,b)=>b));let u=K.normalizeAxes(l,e.inputs[0].dims.length),c=u,h=e.inputs[0],p=Gn(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")},Oo=(e,t)=>{Et(e,"ReduceSumShared",t,"sum")},Po=(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(),gm(),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 _=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,_),O=i(k,$,g),I=O[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
|
${O[2].includes("last_index")?`let last_index = j${B};`:""}
|
|
130
130
|
${k.indicesSet("input_indices",B,`j${B}`)}
|
|
131
131
|
${I}
|
|
@@ -146,9 +146,9 @@
|
|
|
146
146
|
${O[3]}
|
|
147
147
|
${O.length===4?$.setByOffset("global_idx","value"):O.slice(4).join(`
|
|
148
148
|
`)}
|
|
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})},
|
|
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):Oo(e,t)},tl=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ho(e,t):Po(e,t)},rl=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Lo(e,t):Do(e,t)}}),Yi,sl,nl,Ji,ym=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")};
|
|
@@ -158,7 +158,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
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(_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,qn,ul,dl,Zi=S(()=>{Ie(),ke(),
|
|
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,qn,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,_=w;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let O of t.qkvHiddenSizes)if(O%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");g=t.qkvHiddenSizes[0],w=t.qkvHiddenSizes[1],_=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+_)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!==_)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:_,headSize:Math.floor(g/t.numHeads),vHeadSize:Math.floor(_/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;
|
|
@@ -222,13 +222,13 @@ 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};${_};${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,_=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,O={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:_,dataType:t.dataType,gpuDataType:0});let ee=
|
|
225
|
+
}`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${p};${_};${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,_=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,O={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:_,dataType:t.dataType,gpuDataType:0});let ee=de=>{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,_,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
|
-
${
|
|
231
|
-
${
|
|
230
|
+
${de.registerUniforms(Ge).declareVariables(...Re,...xe)}
|
|
231
|
+
${de.mainStart([$,$,1])}
|
|
232
232
|
// x holds the N and y holds the M
|
|
233
233
|
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
234
234
|
let kvHeadIdx = ${b===1?"headIdx":"headIdx / uniforms.n_reps"};
|
|
@@ -279,11 +279,11 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
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
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:H,dispatchGroup:O,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,_=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,O=["type","type"];$&&O.push("type"),u&&O.push("type"),c&&O.push("type");let I=[{dims:b,dataType:t.dataType,gpuDataType:0}];g&&I.push({dims:_,dataType:t.dataType,gpuDataType:0});let B=q=>{let H=F("probs",t.dataType,t.dims),ee=F("v",n.dataType,n.dims),
|
|
282
|
+
}`};return{name:"AttentionProbs",shaderCache:{hint:`${M};${o!==void 0};${i!==void 0};${e}`,inputDependencies:q},getRunData:()=>({outputs:H,dispatchGroup:O,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,_=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,O=["type","type"];$&&O.push("type"),u&&O.push("type"),c&&O.push("type");let I=[{dims:b,dataType:t.dataType,gpuDataType:0}];g&&I.push({dims:_,dataType:t.dataType,gpuDataType:0});let B=q=>{let H=F("probs",t.dataType,t.dims),ee=F("v",n.dataType,n.dims),de=[H,ee];$&&de.push(F("past_value",i.dataType,i.dims));let _e=u?F("seq_lens",u.dataType,u.dims):void 0;u&&de.push(_e);let Fe=c?F("total_sequence_length_input",c.dataType,c.dims):void 0;c&&de.push(Fe);let Re=[le("output",t.dataType,b)];g&&Re.push(le("present_value",t.dataType,_));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
284
|
var<workgroup> tileQ: array<${H.type.value}, ${x*x}>;
|
|
285
285
|
var<workgroup> tileV: array<${H.type.value}, ${x*x}>;
|
|
286
|
-
${q.registerUniforms(Me).declareVariables(...
|
|
286
|
+
${q.registerUniforms(Me).declareVariables(...de,...Re)}
|
|
287
287
|
${q.mainStart([x,x,1])}
|
|
288
288
|
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
289
289
|
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
@@ -406,7 +406,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
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,vm=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
|
|
|
@@ -489,7 +489,7 @@ 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,
|
|
492
|
+
}`}},iu=e=>{su(e.inputs),e.compute(nu(e.inputs))}}),au,ou,vr,lu,uu,du,cu,hu,pu,fu,mu,gu,yu,bm=S(()=>{Ie(),ke(),we(),au=(e,t,n,i,o,l,u,c,h,p,m,g)=>{let w,_;typeof c=="string"?w=_=($,O)=>`${c}((${$}),(${O}))`:typeof c=="function"?w=_=c:(w=c.scalar,_=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,O=K.size(n)===1,I=t.length>0&&t[t.length-1]%4===0,B=n.length>0&&n[n.length-1]%4===0;$||O?k=b.setByOffset("global_idx",_($?`${x.type.value}(${x.getByOffset("0")}.x)`:x.getByOffset("global_idx"),O?`${M.type.value}(${M.getByOffset("0")}.x)`:M.getByOffset("global_idx"))):k=`
|
|
493
493
|
let outputIndices = ${b.offsetToIndices("global_idx * 4u")};
|
|
494
494
|
let offsetA = ${x.broadcastedIndicesToOffset("outputIndices",b)};
|
|
495
495
|
let offsetB = ${M.broadcastedIndicesToOffset("outputIndices",b)};
|
|
@@ -522,7 +522,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
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=!K.areEqual(c,h),m=c,g=K.size(c),w=!1,_=!1,b=[p];if(p){let x=
|
|
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,_=!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,O=h.length>0&&h[h.length-1]%4===0;b.push(M),b.push(k),b.push($),b.push(O);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?(_=!0,w=!0):(M||k||$||O)&&(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,_,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,Sm=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 ) {
|
|
@@ -563,9 +563,9 @@ 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: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})}),
|
|
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,Os=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||[On,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}}}),Ot,Eu,ia=S(()=>{Ot=(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
570
|
`}),$u,Tm=S(()=>{$u=e=>`
|
|
571
571
|
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
|
|
@@ -576,14 +576,14 @@ 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
|
-
`}),Hn,aa,oa=S(()=>{Ie(),ke(),we(),
|
|
579
|
+
`}),Hn,aa,oa=S(()=>{Ie(),ke(),we(),Os(),Hn=(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(h),b=K.size(n)/g/_,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}];
|
|
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(h),b=K.size(n)/g/_,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 O=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),de=G(ee.type.tensor),_e=As(t,ee.type.value,de),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
587
|
let b_data${xe} = b[(b_offset + (k + ${xe}) * uniforms.N + col) / ${g}];`;for(let xe=0;xe<_;xe++){ye+=`a_data = a[(a_offset + (row + ${xe}) * uniforms.K + k) / ${w}];`;for(let Le=0;Le<w;Le++)ye+=`
|
|
588
588
|
values[${xe}] = fma(${H.type.value}(a_data${w===1?"":`[${Le}]`}), b_data${Le}, values[${xe}]);
|
|
589
589
|
`}return ye};return`
|
|
@@ -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};${_};${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:O}}}),xu,Cu,la,ua,ku,da,Ru,Ti,ca=S(()=>{Ie(),ke(),we(),
|
|
625
|
+
`};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${g};${w};${_};${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:O}}}),xu,Cu,la,ua,ku,da,Ru,Ti,ca=S(()=>{Ie(),ke(),we(),Os(),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":""});
|
|
@@ -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
|
-
`},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],_=u[u.length-1],b=c[c.length-1],x=_%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])],O=x?4:1,I=[...h,w,_/O],B=I.length,q=[...p,_,b/O],H=q.length,ee=[g,w,b/O],
|
|
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],_=u[u.length-1],b=c[c.length-1],x=_%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])],O=x?4:1,I=[...h,w,_/O],B=I.length,q=[...p,_,b/O],H=q.length,ee=[g,w,b/O],de=[{type:6,data:w},{type:6,data:b},{type:6,data:_}];Is(t,de),de.push(...L(m,I,q));let _e=["rank","rank"],Fe=e.length>2;Fe&&(de.push(...L(e[2].dims)),_e.push("rank")),de.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,O),Ge=F("b",e[1].dataType,H,O),De=le("result",e[0].dataType,ee.length,O),je=[Le,Ge];if(Fe){let Dt=o?O: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 Pe=G(De.type.tensor),Ae=As(t,De.type.value,Pe),$e=Ru(O,Fe,Ae,[ye,Le,Ge,De],o);return`
|
|
889
889
|
${Me.registerUniforms(oe).registerInternalVariables(ye).declareVariables(...je,De)}
|
|
890
890
|
${$e}
|
|
891
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:
|
|
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:de}),getShaderSource:Re}}}),Au,Iu,Em=S(()=>{Ie(),tr(),we(),Os(),ia(),Tm(),ca(),Au=(e,t,n,i,o=!1,l,u=4,c=4,h=4,p="f32")=>{let m=de=>{switch(de){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 ${de} is not supported.`)}},g=de=>{switch(de){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 ${de} 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);
|
|
@@ -948,7 +948,7 @@ 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 ${Ot(c,p)}(0.0);`,B=Ot(h,p),q=Ot(e?u:c,p),H=Ot(e?c:u,p),ee=
|
|
951
|
+
return ${Ot(c,p)}(0.0);`,B=Ot(h,p),q=Ot(e?u:c,p),H=Ot(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?O:I}
|
|
954
954
|
}
|
|
@@ -968,7 +968,7 @@ 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],_=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*_,k=p?w*_:b,$=[8,8,1],O=i<=8?[4,1,1]:[4,4,1],I=[Math.ceil(M/$[0]/O[0]),Math.ceil(k/$[1]/O[1]),Math.ceil(g/$[2]/O[2])];He("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${I}`);let B=x?p&&m%4!==0?3:4:1,q=$[1]*O[1],H=$[0]*O[0],ee=Math.max($[0]*B,$[1]),
|
|
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],_=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*_,k=p?w*_:b,$=[8,8,1],O=i<=8?[4,1,1]:[4,4,1],I=[Math.ceil(M/$[0]/O[0]),Math.ceil(k/$[1]/O[1]),Math.ceil(g/$[2]/O[2])];He("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${I}`);let B=x?p&&m%4!==0?3:4:1,q=$[1]*O[1],H=$[0]*O[0],ee=Math.max($[0]*B,$[1]),de=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
|
}
|
|
@@ -985,11 +985,11 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
985
985
|
// dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };
|
|
986
986
|
${xe.registerUniforms(Le).declareVariables(...Ae,$e)}
|
|
987
987
|
${je}
|
|
988
|
-
${Au(p,
|
|
989
|
-
${x?la(O,$,De,void 0,!p,ee):da(O,$,De,void 0,!p,ee,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${B};${x};${
|
|
988
|
+
${Au(p,de,_e,Fe,u,t,Re[0],Re[1],Re[2],De)}
|
|
989
|
+
${x?la(O,$,De,void 0,!p,ee):da(O,$,De,void 0,!p,ee,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${B};${x};${de};${_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,jn,Ou,pa,Pu,Du,zu,$m=S(()=>{Ie(),tr(),ke(),we(),Os(),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,jn=(e,t)=>t<=1?e:e+(e-1)*(t-1),Ou=(e,t,n,i=1)=>{let o=jn(t,i);return Math.floor((e[0]*(n-1)-n+o)/2)},pa=(e,t,n,i,o)=>{o==null&&(o=Ou(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},Pu=(e,t,n,i,o,l,u,c,h,p)=>{let m,g,w,_;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],_=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],_=b[2]}else if(e==="SAME_UPPER"){g=Math.ceil(t/o),w=Math.ceil(n/l),_=Math.ceil(i/u);let b=(g-1)*o+c-t,x=(w-1)*l+h-n,M=(_-1)*u+p-i,k=Math.floor(b/2),$=b-k,O=Math.floor(x/2),I=x-O,B=Math.floor(M/2),q=M-B;m={top:O,bottom:I,left:B,right:q,front:k,back:$}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:m,outDepth:g,outHeight:w,outWidth:_}},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,,_,b,x]=t,[M,k,$]=ha(n),[O,I,B]=ha(i),q=jn(_,O),H=jn(b,I),ee=jn(x,B),{padInfo:de,outDepth:_e,outHeight:Fe,outWidth:Re}=Pu(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:de,strideDepth:M,strideHeight:k,strideWidth:$,filterDepth:_,filterHeight:b,filterWidth:x,effectiveFilterDepth:q,effectiveFilterHeight:H,effectiveFilterWidth:ee,dilationDepth:O,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 _=["rank","rank"],b=e.length===3;b&&(w.push(...L(e[2].dims)),_.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,O=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>) -> ${O} {
|
|
991
991
|
return bias[${u?Q("coords",4,5):Q("coords",1,5)}];
|
|
992
|
-
}`}let
|
|
992
|
+
}`}let de=Ot(m,O),_e=As(t,de,O);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);
|
|
@@ -1094,7 +1094,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
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};${b}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:p[0],y:p[1],z:p[2]},programUniforms:w}),getShaderSource:x}}}),Lu,Bu,xm=S(()=>{Ie(),ke(),we(),
|
|
1097
|
+
}`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${u};${m};${b}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:p[0],y:p[1],z:p[2]},programUniforms:w}),getShaderSource:x}}}),Lu,Bu,xm=S(()=>{Ie(),ke(),we(),Os(),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,_=[{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,_),_.push(...L(u,[c[0],c[1],c[2],c[3]/g]));let b=o?["rank","rank","rank"]:["rank","rank"];_.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),O=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
|
|
|
@@ -1156,7 +1156,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1156
1156
|
${l}
|
|
1157
1157
|
${O}
|
|
1158
1158
|
${k.setByOffset("global_idx","value")}
|
|
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:_}),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]]}];
|
|
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:_}),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],_=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),O=F("w",e[1].dataType,p.length,l),I=[$,O];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
1160
|
${b.registerUniforms(q).declareVariables(...I,x)}
|
|
1161
1161
|
${b.mainStart()}
|
|
1162
1162
|
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1201,7 +1201,7 @@ 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:_}}}),Nu,Ei,Uu,$i,fa,ma,Fu,Vu,ga,Cm=S(()=>{ke(),Em(),$m(),ca(),xm(),
|
|
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:_}}}),Nu,Ei,Uu,$i,fa,ma,Fu,Vu,ga,Cm=S(()=>{ke(),Em(),$m(),ca(),xm(),Os(),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,_)=>w+(w-1)*(n[_]-1)),g=c.map((w,_)=>w+i[_]+i[_+h]).map((w,_)=>Math.floor((w-m[_]+o[_])/o[_]));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],_=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,de,_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]),de=[1,q,b]}else H=t[0].reshape([q,c*h,p]),ee=Me.reshape([1,p,b]),de=[q,w*_,b];_e.push(H),_e.push(ee)}else H=t[0].reshape([q,p,c*h]),ee=t[1].reshape([1,b,p]),de=[q,b,w*_],_e.push(ee),_e.push(H);u&&_e.push(t[2]);let Fe=de[2],Re=_e[0].dims[_e[0].dims.length-1];Fe<8&&Re<8?e.compute(aa(_e,n,l,de,o,i),{inputs:_e}):e.compute(Ti(_e,n,l,de,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 O=o?w*_:b,I=o?b:w*_,B=m*g*p;e.compute(Iu($,n,l,O,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,km=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,_=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"],O=[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:O},{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 de=_e=>{let Fe=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:O.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
1206
|
let wValue = ${xe.getByOffset("w_offset")};
|
|
1207
1207
|
dotProd = dotProd + dot(xValue, wValue);
|
|
@@ -1289,7 +1289,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1289
1289
|
${_e.registerUniforms(Fe).declareVariables(...Ge,De)}
|
|
1290
1290
|
${_e.mainStart()}
|
|
1291
1291
|
${_e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};
|
|
1292
|
-
${Pe}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${m}${x}${b}${g}${_}`,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:
|
|
1292
|
+
${Pe}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${m}${x}${b}${g}${_}`,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:de}}}),qu,Wu,Hu,ya,ju,Ku,wa,Qu,Xu,Rm=S(()=>{km(),Os(),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],_=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,_)},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,Am=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")}) `,_=Q("uniforms.input_shape","uniforms.axis",l),b=i.reverse?w+(i.exclusive?" + 1":""):"0",x=i.reverse?_: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")}
|
|
@@ -1316,7 +1316,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1316
1316
|
let aIndices = perm(indices);
|
|
1317
1317
|
|
|
1318
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],O=K.size($),I=g.dims,B=K.sortBasedOnPerm(I,c);return{outputs:[{dims:$,dataType:k[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:[{type:12,data:O},...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,Kn,va,id,ad,od,ld,_a,ud,dd,cd,Mm=S(()=>{Ie(),ke(),A(),we(),xi="[a-zA-Z]|\\.\\.\\.",Kn="("+xi+")+",va="^"+Kn+"$",id="("+Kn+",)*"+Kn,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(Kn)))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 _=0;_<u.length;_++){let b=String.fromCharCode(48+_);p.addSymbol(b,g+_),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;",_="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
|
|
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],O=K.size($),I=g.dims,B=K.sortBasedOnPerm(I,c);return{outputs:[{dims:$,dataType:k[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:[{type:12,data:O},...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,Kn,va,id,ad,od,ld,_a,ud,dd,cd,Mm=S(()=>{Ie(),ke(),A(),we(),xi="[a-zA-Z]|\\.\\.\\.",Kn="("+xi+")+",va="^"+Kn+"$",id="("+Kn+",)*"+Kn,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(Kn)))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 _=0;_<u.length;_++){let b=String.fromCharCode(48+_);p.addSymbol(b,g+_),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;",_="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 de=H.symbolToIndices.get(B);if(de===void 0)throw new Error("Invalid symbol error");de.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(de=>{b.push(`${o[H].indicesSet(`input${H}Indices`,de,`${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 O=$?[...m,`let sum = ${o.map((I,B)=>I.getByIndices(`input${B}Indices`)).join(" * ")};`]:[...m,w,...x,...b,g,...k,_,...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()}
|
|
@@ -1483,7 +1483,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1483
1483
|
let value = ${g.getByIndices("inputIndices")};
|
|
1484
1484
|
|
|
1485
1485
|
${_.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))}}),Od,Pd,Dd,zd,Nm=S(()=>{Ie(),ke(),we(),Od=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")},Pd=(e,t)=>{let n=e[0].dims.slice(),i=e[1].dims.slice(),[o,l,u]=
|
|
1486
|
+
}`}},Id=e=>E({axis:e.axis}),Md=(e,t)=>{let n=e.inputs;Rd(n),e.compute(Ad(e.inputs,t))}}),Od,Pd,Dd,zd,Nm=S(()=>{Ie(),ke(),we(),Od=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")},Pd=(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 _=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 O=le("output",e[0].dataType,c.length);$.push(O);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) {
|
|
@@ -1575,7 +1575,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
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:_}},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)=>{Od(e.inputs),e.compute(Pd(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:_}},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)=>{Od(e.inputs),e.compute(Pd(e.inputs,t))}}),Mr,Gr,Ps,Ds,Ld,Bd,Nd,Ud,Fd,Vd,Gd,qd,Wd,Hd,Um=S(()=>{Ie(),ke(),A(),we(),[Mr,Gr,Ps,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[${Ps}] = 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[${Ps}] = 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[${Ps}] = 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,Ps,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[${Ps}]);
|
|
1700
|
+
let W_in = i32(uniforms.x_shape[${Ds}]);
|
|
1701
1701
|
|
|
1702
1702
|
${t.alignCorners===0?`
|
|
1703
1703
|
let x_min = -0.5;
|
|
@@ -1713,13 +1713,13 @@ 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[${Ps}], 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=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})}),Ut,jd,Kd,Sa,Qd,Qn,Xd,Yd=S(()=>{Ie(),ke(),A(),
|
|
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})}),Ut,jd,Kd,Sa,Qd,Qn,Xd,Yd=S(()=>{Ie(),ke(),A(),tn(),Zi(),we(),Ue(),Ut=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,jd=(e,t)=>{let n=e[0],i=Ut(e,1),o=Ut(e,2),l=Ut(e,3),u=Ut(e,4),c=Ut(e,5),h=Ut(e,6),p=Ut(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],_=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,_=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,_=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,_=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+_,O=0;if(u&&K.size(u.dims)>0){O=8;let H=u.dims;throw H.length===1?H[0]===m?O=1:H[0]===3*m+2&&(O=3):H.length===2&&H[0]===m&&H[1]===$&&(O=5),O===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(_!==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(_!==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:_,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:O,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),_=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
1723
|
${g.registerUniforms(x).declareVariables(_,b,w)}
|
|
1724
1724
|
${g.mainStart()}
|
|
1725
1725
|
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1811,7 +1811,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1811
1811
|
${_.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,_,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],
|
|
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,_,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],de=[-1];x=e.compute(Ci(ee,H),{inputs:ee,outputs:de})[0],ee.splice(0,1,_);let _e=E({interleaved:t.rotaryInterleaved!==0,numHeads:n.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});M=e.compute(Ci(ee,_e),{inputs:ee,outputs:de})[0]}let k=Qn(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,t.doRotary?x:w,void 0,0),$=Ea(e,t.doRotary?M:_,n),O=Ea(e,b,n);qn(e,k,$,O,void 0,void 0,u,c,void 0,n,h,p)}}),$a,hc,pc,fc,Vm=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 _=[o,u,l/h],b=[o,u,2],x=["rank","type","type"],M=[];M.push(...L(_,b));let k=$=>{let O=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=[O,I,B,q];return`
|
|
1815
1815
|
var<workgroup> workgroup_shared : array<${m}, ${w}>;
|
|
1816
1816
|
const workgroup_size = ${w}u;
|
|
1817
1817
|
${$.declareVariables(...H)}
|
|
@@ -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")} * ${O.type.value}(scale_shift.x) + ${O.type.value}(scale_shift.y);
|
|
1857
1857
|
${O.setByOffset("global_idx","value")};
|
|
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,_,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,_=[0,i.length-1];for(let k=0;k<i.length-2;k++)w=w||i[k+1]!==1,_.push(k+1);w=w&&i[i.length-1]!==1;let b=w?e.compute(ct(e.inputs[0],_),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:i.length},(k,$)=>i[_[$]])),x=$a(e,b,t[1],t[2],l,c,u,n.epsilon),M=k=>{let $=G(t[0].dataType),O=h===1?"vec2f":`mat${h}x2f`,I=H=>{let ee=H===0?"x":"y",
|
|
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,_,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,_=[0,i.length-1];for(let k=0;k<i.length-2;k++)w=w||i[k+1]!==1,_.push(k+1);w=w&&i[i.length-1]!==1;let b=w?e.compute(ct(e.inputs[0],_),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:i.length},(k,$)=>i[_[$]])),x=$a(e,b,t[1],t[2],l,c,u,n.epsilon),M=k=>{let $=G(t[0].dataType),O=h===1?"vec2f":`mat${h}x2f`,I=H=>{let ee=H===0?"x":"y",de=h===1?"f32":`vec${h}f`;switch(h){case 1:return`${$}(${de}(scale.${ee}))`;case 2:return`vec2<${$}>(${de}(scale[0].${ee}, scale[1].${ee}))`;case 4:return`vec4<${$}>(${de}(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<${O}>;
|
|
1861
1861
|
@group(0) @binding(2) var<storage, read_write> output : array<${q.type.storage}>;
|
|
@@ -1897,12 +1897,12 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
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:_,dataType:1}),$&&I.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${b};${n};${i}`,inputDependencies:x},getRunData:()=>({outputs:I,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:M}),getShaderSource:O}},yc=(e,t)=>{mc(e.inputs),e.compute(gc(e.inputs,t,e.outputCount))}}),wc,vc,qm=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=
|
|
1900
|
+
}`},I=[{dims:c,dataType:e[0].dataType}];return k&&I.push({dims:_,dataType:1}),$&&I.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${b};${n};${i}`,inputDependencies:x},getRunData:()=>({outputs:I,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:M}),getShaderSource:O}},yc=(e,t)=>{mc(e.inputs),e.compute(gc(e.inputs,t,e.outputCount))}}),wc,vc,qm=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,Wm=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(u),b=c.concat([o,u]),x=o>1&&u/_%2===0?2:1,M=K.size(b)/_/x,k=64,$=[],O=[h,o,l/g],I=K.convertShape(e[1].dims).slice();I.splice(-1,1,p/w),$.push(...L(O)),$.push(...L(I)),$.push(...L(e[2].dims)),e.length===4&&$.push(...L(K.convertShape(e[3].dims)));let B=[h,o,u/_];$.push(...L(B));let q=H=>{let ee=O.length,de=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=[de,_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,_),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
1901
|
// reuse a data (pass ${$e})
|
|
1902
|
-
var input_offset${$e>0?$e:""} = ${$e===0?
|
|
1902
|
+
var input_offset${$e>0?$e:""} = ${$e===0?de.indicesToOffset(`${de.type.indices}(batch, row, word_offset)`):"input_offset"};
|
|
1903
1903
|
var a_data${$e>0?$e:""}: ${Le};
|
|
1904
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:""}] = ${
|
|
1905
|
+
a_data${$e>0?$e:""}[j${$e>0?$e:""}] = ${de.getByOffset(`input_offset${$e>0?$e:""}`)};
|
|
1906
1906
|
input_offset${$e>0?$e:""}++;
|
|
1907
1907
|
}
|
|
1908
1908
|
`;for(let _t=0;_t<_*x;_t++)Ae+=`
|
|
@@ -1915,10 +1915,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1915
1915
|
b_value_lower = unpack4xU8(spread_word & b_mask);
|
|
1916
1916
|
b_value_upper = unpack4xU8((spread_word >> 2u) & b_mask);
|
|
1917
1917
|
}`:`b_value_lower = unpack4xU8((b_value >> ${Dt}u) & b_mask);
|
|
1918
|
-
b_value_upper = unpack4xU8((b_value >> ${
|
|
1919
|
-
b_quantized_values = ${Le}(${Array.from({length:4},(
|
|
1920
|
-
b_dequantized_values = ${g===1?`${Le}(${Array.from({length:8},(
|
|
1921
|
-
workgroup_shared[local_id.x * ${x} + ${Math.floor(_t/_)}]${_>1?`[${_t%_}]`:""} += ${Array.from({length:8/g},(
|
|
1918
|
+
b_value_upper = unpack4xU8((b_value >> ${Xt}u) & b_mask);`}
|
|
1919
|
+
b_quantized_values = ${Le}(${Array.from({length:4},(Yt,nt)=>`${xe}(b_value_lower[${nt}]), ${xe}(b_value_upper[${nt}])`).join(", ")});
|
|
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/_)}]${_>1?`[${_t%_}]`:""} += ${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
1922
|
`}return Ae},oe=()=>{let Ae=`
|
|
1923
1923
|
var col_index = col * ${_};
|
|
1924
1924
|
${Me?`
|
|
@@ -1982,7 +1982,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
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};${_};${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),_=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,O=$/g,I=$/t.blockSize,B=K.size(_)/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
|
|
1985
|
+
}`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${g};${w};${_};${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),_=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,O=$/g,I=$/t.blockSize,B=K.size(_)/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 de=[h,o,u];q.push(...L(de));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=de.length,De=le("output",e[0].dataType,Ge),je=G(e[0].dataType),oe=()=>{switch(g){case 1:return`
|
|
1986
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
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
1988
|
let a_data0 = vec4<${je}>(sub_a[word_offset], sub_a[word_offset + 1]);
|
|
@@ -2036,7 +2036,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
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 Pe=Math.floor(k/8),Ae="";for(let $e=0;$e<Pe;$e++){let Dt=$e*t.bits*4,
|
|
2039
|
+
${(()=>{let Pe=Math.floor(k/8),Ae="";for(let $e=0;$e<Pe;$e++){let Dt=$e*t.bits*4,Xt=Dt+t.bits;Ae+=`
|
|
2040
2040
|
${oe()}
|
|
2041
2041
|
{${t.bits===2?`
|
|
2042
2042
|
let half_word = b_value >> ${$e*16}u;
|
|
@@ -2046,10 +2046,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2046
2046
|
let b_value_lower = unpack4xU8(spread_word & 0x03030303u);
|
|
2047
2047
|
let b_value_upper = unpack4xU8((spread_word >> 2u) & 0x03030303u);`:`
|
|
2048
2048
|
let b_value_lower = unpack4xU8((b_value >> ${Dt}u) & 0x0F0F0F0Fu);
|
|
2049
|
-
let b_value_upper = unpack4xU8((b_value >> ${
|
|
2050
|
-
let b_quantized_values = mat2x4<${je}>(${Array.from({length:4},(_t,
|
|
2049
|
+
let b_value_upper = unpack4xU8((b_value >> ${Xt}u) & 0x0F0F0F0Fu);`}
|
|
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
2051
|
let b_dequantized_values = (b_quantized_values - mat2x4<${je}>(${Array(8).fill("zero_point").join(",")})) * scale;
|
|
2052
|
-
inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(_t,
|
|
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})()}
|
|
2055
2055
|
}
|
|
@@ -2139,7 +2139,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2139
2139
|
var value = ${w}(0);
|
|
2140
2140
|
${_}
|
|
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(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},Oc=(e,t)=>{$c(e.inputs);let n=Mc(e.inputs,t);e.compute(Ic(e.inputs,n),{inputs:[0]})}}),Xn,xa,Ca,ka,Ra,Pc,Dc,Aa,Ia,zc,Lc,Ma,Bc,Nc,Oa,Uc,Fc,Vc,Gc,jm=S(()=>{yt(),Ie(),ke(),we(),Xn=e=>{if(
|
|
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},Oc=(e,t)=>{$c(e.inputs);let n=Mc(e.inputs,t);e.compute(Ic(e.inputs,n),{inputs:[0]})}}),Xn,xa,Ca,ka,Ra,Pc,Dc,Aa,Ia,zc,Lc,Ma,Bc,Nc,Oa,Uc,Fc,Vc,Gc,jm=S(()=>{yt(),Ie(),ke(),we(),Xn=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 _=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:_},{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",_=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[${$}]
|
|
@@ -2230,7 +2230,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2230
2230
|
output[global_idx] = value;
|
|
2231
2231
|
}`}},Ra=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Pc=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,_,b]=Ca(l,o);m.push(...L(t.dims,l));let x=["rank"];return{name:e,shaderCache:{hint:`${i.cacheKey};${w};${_};${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,_,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:Pc(i)}},Lc=(e,t)=>{Xn(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)=>{Xn(e.inputs),e.compute(Ia("GlobalAveragePool",e.inputs[0],!0,t))},Oa=(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,_,b]=Ca(l,o);return m.push(...L(t.dims,l)),{name:e,shaderCache:{hint:`${i.cacheKey};${w};${_};${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,_,b)}},Uc=(e,t)=>{Xn(e.inputs),e.compute(Oa("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)=>{Xn(e.inputs),e.compute(Oa("GlobalMaxPool",e.inputs[0],!0,t))}}),qc,Wc,Hc,jc,Km=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,_=m.length===0||m.length===1&&m[0]===1,b=_===!1&&m.length===1,x=V(c),M=_&&(!h||x===4),k=M?x:1,$=M&&!h?x:1,O=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=[O,I];B&&H.push(B);let ee=[p,m];g&&ee.push(w);let
|
|
2233
|
+
`,c="",h=F("x",t.dataType,t.dims.length),p=["rank"],[m,g,w,_,b]=Ca(l,o);return m.push(...L(t.dims,l)),{name:e,shaderCache:{hint:`${i.cacheKey};${w};${_};${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,_,b)}},Uc=(e,t)=>{Xn(e.inputs),e.compute(Oa("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)=>{Xn(e.inputs),e.compute(Oa("GlobalMaxPool",e.inputs[0],!0,t))}}),qc,Wc,Hc,jc,Km=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,_=m.length===0||m.length===1&&m[0]===1,b=_===!1&&m.length===1,x=V(c),M=_&&(!h||x===4),k=M?x:1,$=M&&!h?x:1,O=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=[O,I];B&&H.push(B);let ee=[p,m];g&&ee.push(w);let de=[{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
2234
|
${Fe.registerUniforms(Re).declareVariables(...H,q)}
|
|
2235
2235
|
${Fe.mainStart()}
|
|
2236
2236
|
${Fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -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":O.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:
|
|
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:de})}},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,Qm=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,Xm=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=`;
|
|
@@ -2589,11 +2589,11 @@ 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:""}|${_}|${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,Jm=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,_=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}],O=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)),_&&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),
|
|
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:""}|${_}|${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,Jm=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,_=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}],O=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)),_&&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),de=G(1,k);return`
|
|
2593
2593
|
|
|
2594
2594
|
${B.registerUniforms(q).declareVariables(...H)}
|
|
2595
|
-
var<workgroup> sum_shared : array<${
|
|
2596
|
-
var<workgroup> sum_squared_shared : array<${
|
|
2595
|
+
var<workgroup> sum_shared : array<${de}, ${M}>;
|
|
2596
|
+
var<workgroup> sum_squared_shared : array<${de}, ${M}>;
|
|
2597
2597
|
|
|
2598
2598
|
${B.mainStart([M,1,1])}
|
|
2599
2599
|
let ix = local_id.x;
|
|
@@ -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=!(K.areEqual(t,n)&&K.areEqual(n,i)),u=t,c=K.size(t);if(l){let p=
|
|
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,sg=S(()=>{ym(),Zi(),wm(),vm(),_m(),bm(),Sm(),Cm(),Rm(),Am(),Im(),Mm(),Om(),Pm(),Dm(),zm(),Lm(),Bm(),Nm(),Um(),Fm(),Vm(),Gm(),qm(),Wm(),Yd(),Hm(),jm(),Km(),Qm(),Xm(),Xi(),Ym(),oc(),Jm(),Zm(),eg(),nc(),tg(),Ue(),sa(),rg(),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",[Ol,Wn]],["Equal",[du]],["Erf",[Pl]],["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,Wn]],["Less",[mu]],["LessOrEqual",[yu]],["Log",[Zl]],["MatMul",[vc]],["MatMulNBits",[Tc,Ec]],["MaxPool",[Uc,Fc]],["Mul",[cu]],["MultiHeadAttention",[Xd,Kd]],["Neg",[Ul]],["Not",[Nl]],["Pad",[Oc]],["Pow",[hu]],["QuickGelu",[ru,Wn]],["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,Wn]],["Tile",[Dh]],["Transpose",[ar,Vn]],["Where",[Bh]]])}),Uh,ng=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 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,ig=S(()=>{yt(),Ie(),tr(),rs(),Ki(),sg(),ng(),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,js(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],_=t[i*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=w);let b=Number(w-this.queryTimeBase),x=Number(_-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:jt(M.dataType)})),outputsMetadata:g.map(M=>({dims:M.dims,dataType:jt(M.dataType)})),kernelId:l,kernelType:c,kernelName:h,programName:p,startTime:b,endTime:x});else{let M="";m.forEach(($,O)=>{M+=`input[${O}]: [${$.dims}] | ${jt($.dataType)}, `});let k="";g.forEach(($,O)=>{k+=`output[${O}]: [${$.dims}] | ${jt($.dataType)}, `}),console.log(`[profiling] kernel "${l}|${c}|${h}|${p}" ${M}${k}start time: ${b} ns, execution time: ${x-b} ns`)}Zt("GPU",`${p}::${w}::${_}`)}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 O=t[$].data;if(O===0)continue;let I=this.gpuDataManager.get(O);if(!I)throw new Error(`no GPU data for input: ${O}`);u.push(I)}let{outputs:c,dispatchGroup:h,programUniforms:p}=e.getRunData(t),m=n.length===0?c.map(($,O)=>O):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 O=m[$]===-1,I=m[$]===-2,B=O||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(O&&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 _;if(p){let $=0,O=[];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,O.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=O[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: ${jt(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),_={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 O=p[$],I=O.type,B=typeof O.data=="number"?1:O.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,_),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 Nn(this,e,t);return Ar(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,ag=S(()=>{Ie(),tr(),ke(),Bn(),ki=class hf{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 hf(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 _=0;_<g;_++)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=Kt(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=(ig(),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 Ln(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,os,Xh,Ua,Ri,Fa,Va,Ga,qa,Wa,Ha,Yh=S(()=>{yt(),Hi(),ji(),Ie(),Wt(),ws(),In(),Qh=(e,t)=>{Oe()._OrtInit(e,t)!==0&&Ce("Can't initialize onnxruntime.")},Ba=async e=>{Qh(e.wasm.numThreads,_s(e.logLevel))},Na=async(e,t)=>{Oe().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=(ag(),te(Hh)).init;t==="webgpu"&&await i("webgpu",Oe(),e,n),t==="webnn"&&await i("webnn",Oe(),e)}},os=new Map,Xh=e=>{let t=Oe(),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=Oe(),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=Oe(),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=Oe();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 An(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(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),_=!!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:jt(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:jt(q),shape:H});{if(_&&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(_&&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 O=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."),O={handle:c,outputPreferredLocations:$,outputPreferredLocationsEncoded:$.map(I=>I==="ml-tensor-cpu-output"?"ml-tensor":I).map(I=>qs(I))}),os.set(l,[l,p,m,O,_,!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=Oe(),n=os.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."),os.delete(e)},Ga=async(e,t,n,i,o,l,u=!1)=>{if(!e){t.push(0);return}let c=Oe(),h=c.PTR_SIZE,p=e[0],m=e[1],g=e[3],w=g,_,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=Kt(Ht(p),m);{let $=c.jsepRegisterBuffer;if(!$)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=$(i,l,k,b)}}else if(g==="ml-tensor"){let k=e[2].mlTensor;b=Kt(Ht(p),m);let $=c.webnnRegisterMLTensor;if(!$)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=$(i,k,Ht(p),m)}else{let k=e[2];if(Array.isArray(k)){b=h*k.length,_=c._malloc(b),n.push(_);for(let $=0;$<k.length;$++){if(typeof k[$]!="string")throw new TypeError(`tensor data at index ${$} is not a string`);c.setValue(_+$*h,mt(k[$],n),"*")}}else{let $=c.webnnIsGraphInput,O=c.webnnIsGraphOutput;if(p!=="string"&&$&&O){let I=c.UTF8ToString(o);if($(i,I)||O(i,I)){let B=Ht(p);b=Kt(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)),_=ee}else b=k.byteLength,_=c._malloc(b),n.push(_),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,b),_)}else b=k.byteLength,_=c._malloc(b),n.push(_),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,b),_)}}let x=c.stackSave(),M=c.stackAlloc(4*m.length);try{m.forEach(($,O)=>c.setValue(M+O*h,$,h===4?"i32":"i64"));let k=c._OrtCreateTensor(Ht(p),_,b,M,m.length,qs(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=Oe(),c=u.PTR_SIZE,h=os.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],_=h[4],b=h[5],x=t.length,M=i.length,k=0,$=[],O=[],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,$]=$n(l),At("wasm prepareInputOutputTensor");for(let ye=0;ye<x;ye++)await Ga(n[ye],O,B,e,m[t[ye]],t[ye],_);for(let ye=0;ye<M;ye++)await Ga(o[ye],I,B,e,g[i[ye]],x+i[ye],_);Ct("wasm prepareInputOutputTensor");for(let ye=0;ye<x;ye++)u.setValue(ee+ye*c,O[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],O[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"),os.set(e,[p,m,g,w,_,!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 Pe=c===4?"i32":"i64",Ae=Number(u.getValue(Ge,Pe));oe=u.getValue(Ge+c,"*");let $e=u.getValue(Ge+c*2,"*"),Dt=Number(u.getValue(Ge+c*3,Pe)),Qt=[];for(let nt=0;nt<Dt;nt++)Qt.push(Number(u.getValue($e+nt*c,Pe)));u._OrtFree($e)!==0&&Ce("Can't free memory for tensor dims.");let _t=Qt.reduce((nt,bt)=>nt*bt,1);je=jt(Ae);let Xt=w?.outputPreferredLocations[i[ye]];if(je==="string"){if(Xt==="gpu-buffer"||Xt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let nt=[];for(let bt=0;bt<_t;bt++){let Gr=u.getValue(oe+bt*c,"*"),cg=u.getValue(oe+(bt+1)*c,"*"),hg=bt===_t-1?void 0:cg-Gr;nt.push(u.UTF8ToString(Gr,hg))}Me.push([je,Qt,nt,"cpu"])}else if(Xt==="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),Gr=Kt(Ae,_t);if(Gr===void 0||!bs(je))throw new Error(`Unsupported data type: ${je}`);De=!0,Me.push([je,Qt,{gpuBuffer:bt,download:u.jsepCreateDownloader(bt,Gr,je),dispose:()=>{u._OrtReleaseTensor(xe)!==0&&Ce("Can't release tensor.")}},"gpu-buffer"])}else if(Xt==="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(Kt(Ae,_t)===void 0||!Ss(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 Gr=await nt(e,oe,Ae,Qt,!1);De=!0,Me.push([je,Qt,{mlTensor:Gr,download:u.webnnCreateMLTensorDownloader(oe,je),dispose:()=>{u.webnnReleaseTensorId(oe),u._OrtReleaseTensor(xe)}},"ml-tensor"])}else if(Xt==="ml-tensor-cpu-output"&&_t>0){let nt=u.webnnCreateMLTensorDownloader(oe,je)(),bt=Me.length;De=!0,Qe.push((async()=>{let Gr=[bt,await nt];return u.webnnReleaseTensorId(oe),u._OrtReleaseTensor(xe),Gr})()),Me.push([je,Qt,[],"cpu"])}else{let nt=vs(je),bt=new nt(_t);new Uint8Array(bt.buffer,bt.byteOffset,bt.byteLength).set(u.HEAPU8.subarray(oe,oe+bt.byteLength)),Me.push([je,Qt,bt,"cpu"])}}finally{u.stackRestore(Le),je==="string"&&oe&&u._free(oe),De||u._OrtReleaseTensor(xe)}}w&&!_&&(u._OrtClearBoundOutputs(w.handle)!==0&&Ce("Can't clear bound outputs."),os.set(e,[p,m,g,w,_,!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),O.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=Oe(),n=os.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}}),ls,lr,un,Jn,Zn,Ai,ja,Ii,Ds,zs,Jh,Zh,ep,tp,rp,sp,np,ip,ap=S(()=>{yt(),Yh(),Wt(),fs(),ls=()=>!!fe.wasm.proxy&&typeof document<"u",un=!1,Jn=!1,Zn=!1,Ii=new Map,Ds=(e,t)=>{let n=Ii.get(e);n?n.push(t):Ii.set(e,[t])},zs=()=>{if(un||!Jn||Zn||!lr)throw new Error("worker not ready")},Jh=e=>{switch(e.data.type){case"init-wasm":un=!1,e.data.err?(Zn=!0,ja[1](e.data.err)):(Jn=!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(!Jn){if(un)throw new Error("multiple calls to 'initWasm()' detected.");if(Zn)throw new Error("previous call to 'initWasm()' failed.");if(un=!0,ls())return new Promise((e,t)=>{lr?.terminate(),_n().then(([n,i])=>{try{lr=i,lr.onerror=l=>t(l),lr.onmessage=Jh,ja=[e,t];let o={type:"init-wasm",in:fe};if(!o.in.wasm.wasmPaths&&n){let l=ds();l&&(o.in.wasm.wasmPaths=l)}lr.postMessage(o),Ai=n}catch(o){t(o)}},t)});try{await ys(fe.wasm),await Ba(fe),Jn=!0}catch(e){throw Zn=!0,e}finally{un=!1}}},ep=async e=>{if(ls())return zs(),new Promise((t,n)=>{Ds("init-ep",[t,n]);let i={type:"init-ep",in:{epName:e,env:fe}};lr.postMessage(i)});await Na(fe,e)},tp=async e=>ls()?(zs(),new Promise((t,n)=>{Ds("copy-from",[t,n]);let i={type:"copy-from",in:{buffer:e}};lr.postMessage(i,[e.buffer])})):Ri(e),rp=async(e,t)=>{if(ls()){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),lr.postMessage(o,l)})}else return Fa(e,t)},sp=async e=>{if(ls())return zs(),new Promise((t,n)=>{Ds("release",[t,n]);let i={type:"release",in:e};lr.postMessage(i)});Va(e)},np=async(e,t,n,i,o,l)=>{if(ls()){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}};lr.postMessage(p,Ha(h))})}else return qa(e,t,n,i,o,l)},ip=async e=>{if(ls())return zs(),new Promise((t,n)=>{Ds("end-profiling",[t,n]);let i={type:"end-profiling",in:e};lr.postMessage(i)});Wa(e)}}),Ka,op,lp,og=S(()=>{yt(),ap(),Ie(),cr(),In(),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(!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),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],_=g[1],b=this.inputNames.indexOf(w);if(b===-1)throw new Error(`invalid input '${w}'`);i.push(_),o.push(b)});let l=[],u=[];Object.entries(t).forEach(g=>{let w=g[0],_=g[1],b=this.outputNames.indexOf(w);if(b===-1)throw new Error(`invalid output '${w}'`);l.push(_),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,lg=S(()=>{yt(),ap(),og(),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={};N(cp,{InferenceSession:()=>Lr,TRACE:()=>Zt,TRACE_EVENT_BEGIN:()=>At,TRACE_EVENT_END:()=>Ct,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>ft,Tensor:()=>lt,default:()=>dg,env:()=>fe,registerBackend:()=>J}),yt(),yt(),yt();var ug="1.26.0",dg=Cr;{let e=(lg(),te(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:ug,enumerable:!0}),te(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,ig=S(()=>{yt(),Ie(),tr(),ss(),Ki(),sg(),ng(),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],_=t[i*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=w);let b=Number(w-this.queryTimeBase),x=Number(_-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(($,O)=>{M+=`input[${O}]: [${$.dims}] | ${Kt($.dataType)}, `});let k="";g.forEach(($,O)=>{k+=`output[${O}]: [${$.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}::${_}`)}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 O=t[$].data;if(O===0)continue;let I=this.gpuDataManager.get(O);if(!I)throw new Error(`no GPU data for input: ${O}`);u.push(I)}let{outputs:c,dispatchGroup:h,programUniforms:p}=e.getRunData(t),m=n.length===0?c.map(($,O)=>O):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 O=m[$]===-1,I=m[$]===-2,B=O||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(O&&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 _;if(p){let $=0,O=[];p.forEach(H=>{let ee=typeof H.data=="number"?[H.data]:H.data;if(ee.length===0)return;let de=H.type===10?2:4,_e,Fe;H.type===10?(Fe=ee.length>4?16:ee.length>2?8:ee.length*de,_e=ee.length>4?16:de*ee.length):(Fe=ee.length<=2?ee.length*de:16,_e=16),$=Math.ceil($/Fe)*Fe,O.push($);let Re=H.type===10?8:4;$+=ee.length>4?Math.ceil(ee.length/Re)*_e:ee.length*de});let I=16;$=Math.ceil($/I)*I;let B=new ArrayBuffer($);p.forEach((H,ee)=>{let de=O[ee],_e=typeof H.data=="number"?[H.data]:H.data;if(H.type===6)new Int32Array(B,de,_e.length).set(_e);else if(H.type===12)new Uint32Array(B,de,_e.length).set(_e);else if(H.type===10)new Uint16Array(B,de,_e.length).set(_e);else if(H.type===1)new Float32Array(B,de,_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),_={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 O=p[$],I=O.type,B=typeof O.data=="number"?1:O.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,_),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 Nn(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,ag=S(()=>{Ie(),tr(),ke(),Bn(),ki=class hf{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 hf(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 _=0;_<g;_++)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=(ig(),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 Ln(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(),In(),Qh=(e,t)=>{Oe()._OrtInit(e,t)!==0&&Ce("Can't initialize onnxruntime.")},Ba=async e=>{Qh(e.wasm.numThreads,bs(e.logLevel))},Na=async(e,t)=>{Oe().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=(ag(),te(Hh)).init;t==="webgpu"&&await i("webgpu",Oe(),e,n),t==="webnn"&&await i("webnn",Oe(),e)}},ls=new Map,Xh=e=>{let t=Oe(),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=Oe(),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=Oe(),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=Oe();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 An(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,de=B?.powerPreference;q?o.currentContext=q:H?o.currentContext=await o.webnnCreateMLContext(H):o.currentContext=await o.webnnCreateMLContext({deviceType:ee,powerPreference:de})}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),_=!!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(_&&t?.preferredOutputLocation===void 0){$.push("gpu-buffer");continue}let de=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[ee]??"cpu",_e=o.webnnIsGraphOutput;if(de==="cpu"&&_e&&_e(l,ee)){$.push("ml-tensor-cpu-output");continue}if(de!=="cpu"&&de!=="cpu-pinned"&&de!=="gpu-buffer"&&de!=="ml-tensor")throw new Error(`Not supported preferred output location: ${de}.`);if(_&&de!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${de}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);$.push(de)}}let O=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."),O={handle:c,outputPreferredLocations:$,outputPreferredLocationsEncoded:$.map(I=>I==="ml-tensor-cpu-output"?"ml-tensor":I).map(I=>Ws(I))}),ls.set(l,[l,p,m,O,_,!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=Oe(),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=Oe(),h=c.PTR_SIZE,p=e[0],m=e[1],g=e[3],w=g,_,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.');_=$(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.');_=$(i,k,jt(p),m)}else{let k=e[2];if(Array.isArray(k)){b=h*k.length,_=c._malloc(b),n.push(_);for(let $=0;$<k.length;$++){if(typeof k[$]!="string")throw new TypeError(`tensor data at index ${$} is not a string`);c.setValue(_+$*h,mt(k[$],n),"*")}}else{let $=c.webnnIsGraphInput,O=c.webnnIsGraphOutput;if(p!=="string"&&$&&O){let I=c.UTF8ToString(o);if($(i,I)||O(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)),_=ee}else b=k.byteLength,_=c._malloc(b),n.push(_),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,b),_)}else b=k.byteLength,_=c._malloc(b),n.push(_),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,b),_)}}let x=c.stackSave(),M=c.stackAlloc(4*m.length);try{m.forEach(($,O)=>c.setValue(M+O*h,$,h===4?"i32":"i64"));let k=c._OrtCreateTensor(jt(p),_,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=Oe(),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],_=h[4],b=h[5],x=t.length,M=i.length,k=0,$=[],O=[],I=[],B=[],q=[],H=u.stackSave(),ee=u.stackAlloc(x*c),de=u.stackAlloc(x*c),_e=u.stackAlloc(M*c),Fe=u.stackAlloc(M*c);try{[k,$]=$n(l),At("wasm prepareInputOutputTensor");for(let ye=0;ye<x;ye++)await Ga(n[ye],O,B,e,m[t[ye]],t[ye],_);for(let ye=0;ye<M;ye++)await Ga(o[ye],I,B,e,g[i[ye]],x+i[ye],_);Ct("wasm prepareInputOutputTensor");for(let ye=0;ye<x;ye++)u.setValue(ee+ye*c,O[ye],"*"),u.setValue(de+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],O[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,_,!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,de,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 Pe=c===4?"i32":"i64",Ae=Number(u.getValue(Ge,Pe));oe=u.getValue(Ge+c,"*");let $e=u.getValue(Ge+c*2,"*"),Dt=Number(u.getValue(Ge+c*3,Pe)),Xt=[];for(let nt=0;nt<Dt;nt++)Xt.push(Number(u.getValue($e+nt*c,Pe)));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,"*"),cg=u.getValue(oe+(bt+1)*c,"*"),hg=bt===_t-1?void 0:cg-qr;nt.push(u.UTF8ToString(qr,hg))}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&&!_&&(u._OrtClearBoundOutputs(w.handle)!==0&&Ce("Can't clear bound outputs."),ls.set(e,[p,m,g,w,_,!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),O.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=Oe(),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,Jn,Zn,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,Jn=!1,Zn=!1,Ii=new Map,zs=(e,t)=>{let n=Ii.get(e);n?n.push(t):Ii.set(e,[t])},Ls=()=>{if(dn||!Jn||Zn||!lr)throw new Error("worker not ready")},Jh=e=>{switch(e.data.type){case"init-wasm":dn=!1,e.data.err?(Zn=!0,ja[1](e.data.err)):(Jn=!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(!Jn){if(dn)throw new Error("multiple calls to 'initWasm()' detected.");if(Zn)throw new Error("previous call to 'initWasm()' failed.");if(dn=!0,us())return new Promise((e,t)=>{lr?.terminate(),_n().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),Jn=!0}catch(e){throw Zn=!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,og=S(()=>{yt(),ap(),Ie(),Lr(),In(),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],_=g[1],b=this.inputNames.indexOf(w);if(b===-1)throw new Error(`invalid input '${w}'`);i.push(_),o.push(b)});let l=[],u=[];Object.entries(t).forEach(g=>{let w=g[0],_=g[1],b=this.outputNames.indexOf(w);if(b===-1)throw new Error(`invalid output '${w}'`);l.push(_),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,lg=S(()=>{yt(),ap(),og(),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:()=>dg,env:()=>me,registerBackend:()=>J}),yt(),yt(),yt();var ug="1.26.0",dg=xr;{let e=(lg(),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:ug,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 _y(){return Ep||(Ep=1,Object.defineProperty(no,"__esModule",{value:!0})),no}var ai={},$p;function by(){if($p)return ai;$p=1;var d;Object.defineProperty(ai,"__esModule",{value:!0}),ai.SileroLegacy=void 0;const r=pn();class s{constructor(f,v,C,R,S){this.ortInstance=f,this._session=v,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 ai.SileroLegacy=s,d=s,s.new=async(a,f)=>{r.log.debug("initializing vad");const v=await f(),C=await a.InferenceSession.create(v),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)},ai}var oi={},xp;function Sy(){if(xp)return oi;xp=1;var d;Object.defineProperty(oi,"__esModule",{value:!0}),oi.SileroV5=void 0;const r=pn();function s(f){const v=Array(256).fill(0);return new f.Tensor("float32",v,[2,1,128])}class a{constructor(v,C,R,S){this._session=v,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 oi.SileroV5=a,d=a,a.new=async(f,v)=>{r.log.debug("Loading VAD...");const C=await v(),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)},oi}var Cp;function pf(){return Cp||(Cp=1,(function(d){var r=Bs&&Bs.__createBinding||(Object.create?(function(v,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(v,S,N)}):(function(v,C,R,S){S===void 0&&(S=R),v[S]=C[R]})),s=Bs&&Bs.__exportStar||function(v,C){for(var R in v)R!=="default"&&!Object.prototype.hasOwnProperty.call(C,R)&&r(C,v,R)};Object.defineProperty(d,"__esModule",{value:!0}),d.SileroV5=d.SileroLegacy=void 0,s(_y(),d);var a=by();Object.defineProperty(d,"SileroLegacy",{enumerable:!0,get:function(){return a.SileroLegacy}});var f=Sy();Object.defineProperty(d,"SileroV5",{enumerable:!0,get:function(){return f.SileroV5}})})(Bs)),Bs}var li={},kp;function ff(){if(kp)return li;kp=1,Object.defineProperty(li,"__esModule",{value:!0}),li.Resampler=void 0;const d=pn();class r{constructor(a){this.options=a,this.process=f=>{const v=[];for(const C of f)for(this.inputBuffer.push(C);this.hasEnoughDataForFrame();){const R=this.generateOutputFrame();v.push(R)}return v},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,v=0;for(;f<this.options.targetFrameSize;){let C=0,R=0;for(;v<Math.min(this.inputBuffer.length,(f+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const S=this.inputBuffer[v];S!==void 0&&(C+=S,R++),v++}a[f]=C/R,f++}return this.inputBuffer=this.inputBuffer.slice(v),a}}return li.Resampler=r,li}var Rp;function Ty(){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(vy()),v=df(),C=Io(),R=Mo(),S=qi(),N=pf(),z=ff();d.defaultNonRealTimeVADOptions={...R.defaultFrameProcessorOptions,modelURL:v.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,ue=0;for await(const pe of W.stream(se)){const ce=[];await this.frameProcessor.process(pe,Ve=>{ce.push(Ve)});for(const Ve of ce)switch(Ve.msg){case S.Message.SpeechStart:ne=ue*this.frameSamples/16;break;case S.Message.SpeechEnd:fe=(ue+1)*this.frameSamples/16,yield{audio:Ve.audio,start:ne,end:fe};break}ue++}const he=[];this.frameProcessor.endSegment(pe=>{he.push(pe)});for(const pe of he)switch(pe.msg){case S.Message.SpeechEnd:yield{audio:pe.audio,start:ne,end:ue*this.frameSamples/16}}}}d.NonRealTimeVAD=te})(Hr)),Hr}var _r={},Ap;function Ey(){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 v(Y,0,"RIFF"),Y.setUint32(4,36+R.length*j,!0),v(Y,8,"WAVE"),v(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),v(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 v(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 $y(){return Ip||(Ip=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=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 P of v(E))!C.call(y,P)&&P!==A&&a(y,P,{get:()=>E[P],enumerable:!(D=f(E,P))||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 P=se.indexOf(y);P!==-1&&se.splice(P,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,P,G=[],U=new Set;for(let V of D){let re=await Y(V);typeof re=="string"?G.push({name:V,err:re}):(P||(P=re),P===re&&U.add(V))}if(!P)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[P,new Proxy(y,{get:(V,re)=>re==="executionProviders"?L:Reflect.get(V,re)})]}}),ge=S(()=>{ne()}),de,he=S(()=>{de="1.26.0"}),pe,ce,Ve=S(()=>{he(),pe="warning",ce={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(ce,"logLevel",{enumerable:!0})}),fe,Ye=S(()=>{Ve(),fe=ce}),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 P,G;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[3]):(P=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*P,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<P;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 P,G,U;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[1],U=y.dims[3]):(P=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*P;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(P,G);for(let kt=0;kt<G*P;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,Gt,xt,Ke,We,st=S(()=>{$r(),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,P=E.norm??{mean:255,bias:0},G,U;typeof P.mean=="number"?G=[P.mean,P.mean,P.mean,P.mean]:G=[P.mean[0],P.mean[1],P.mean[2],P.mean[3]??255],typeof P.bias=="number"?U=[P.bias,P.bias,P.bias,P.bias]:U=[P.bias[0],P.bias[1],P.bias[2],P.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,P=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(P){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")},Gt=(y,E)=>{let{width:A,height:D,download:P,dispose:G}=E,U=[1,D,A,4];return new rt({location:"texture",type:"float32",texture:y,dims:U,download:P,dispose:G})},xt=(y,E)=>{let{dataType:A,dims:D,download:P,dispose:G}=E;return new rt({location:"gpu-buffer",type:A??"float32",gpuBuffer:y,dims:D,download:P,dispose:G})},Ke=(y,E)=>{let{dataType:A,dims:D,download:P,dispose:G}=E;return new rt({location:"ml-tensor",type:A??"float32",mlTensor:y,dims:D,download:P,dispose:G})},We=(y,E,A)=>new rt({location:"cpu-pinned",type:y,data:E,dims:A??[E.length]})}),ze,Rt,sr,Qr,Fs=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,Qr=()=>{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)}}}),Xr,Yr,Vs=S(()=>{$r(),Xr=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},Yr=(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,$r=S(()=>{Je(),st(),Fs(),Vs(),rt=class{constructor(y,E,A){Qr();let D,P;if(typeof y=="object"&&"location"in y)switch(this.dataLocation=y.location,D=y.type,P=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");P=L,this.cpuData=U,this.dataLocation="cpu"}let G=Xr(P);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=P,this.size=G}static async fromImage(y,E){return tt(y,E)}static fromTexture(y,E){return Gt(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 Yr(this,y)}}}),lt,Jr=S(()=>{$r(),lt=rt}),Zt,xr,gt,ft,At,Ct,Zr=S(()=>{Ve(),Zt=(y,E)=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.timeStamp(`${y}::ORT::${E}`)},xr=(y,E)=>{let A=new Error().stack?.split(/\r\n|\r|\n/g)||[],D=!1;for(let P=0;P<A.length;P++){if(D&&!A[P].includes("TRACE_FUNC")){let G=`FUNC_${y}::${A[P].trim().split(" ")[1]}`;E&&(G+=`::${E}`),Zt("CPU",G);return}A[P].includes("TRACE_FUNC")&&(D=!0)}},gt=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||xr("BEGIN",y)},ft=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||xr("END",y)},At=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.time(`ORT::${y}`)},Ct=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.timeEnd(`ORT::${y}`)}}),es,Gs=S(()=>{ne(),Jr(),Zr(),es=class mf{constructor(E){this.handler=E}async run(E,A,D){gt(),At("InferenceSession.run");let P={},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}.`);P[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,P[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)P[re]=null;let L=await this.handler.run(E,P,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,P){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 P=="object"&&P!==null)U=P;else if(typeof P<"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 mf(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}}}),Lr,be=S(()=>{Gs(),Lr=es}),Ze=S(()=>{}),qt=S(()=>{}),nr=S(()=>{}),It=S(()=>{}),Cr={};N(Cr,{InferenceSession:()=>Lr,TRACE:()=>Zt,TRACE_EVENT_BEGIN:()=>At,TRACE_EVENT_END:()=>Ct,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>ft,Tensor:()=>lt,env:()=>fe,registerBackend:()=>J});var yt=S(()=>{ge(),Ye(),be(),Jr(),Ze(),qt(),Zr(),nr(),It()}),cr=S(()=>{}),er={};N(er,{default:()=>fn});var ir,Lt,fn,Wi=S(()=>{On(),Wt(),fs(),ir="ort-wasm-proxy-worker",Lt=globalThis.self?.name===ir,Lt&&(self.onmessage=y=>{let{type:E,in:A}=y.data;try{switch(E){case"init-wasm":ys(A.wasm).then(()=>{Ws(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:P}=A;Hs(P,D).then(()=>{postMessage({type:E})},G=>{postMessage({type:E,err:G})});break}case"copy-from":{let{buffer:D}=A,P=He(D);postMessage({type:E,out:P});break}case"create":{let{model:D,options:P}=A;tr(D,P).then(G=>{postMessage({type:E,out:G})},G=>{postMessage({type:E,err:G})});break}case"release":Qs(A),postMessage({type:E});break;case"run":{let{sessionId:D,inputIndices:P,inputs:G,outputIndices:U,options:L}=A;K(D,P,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},Xs([...G,...V]))},V=>{postMessage({type:E,err:V})});break}case"end-profiling":ts(A),postMessage({type:E});break;default:}}catch(D){postMessage({type:E,err:D})}}),fn=Lt?null:y=>new Worker(y??ot,{type:"classic",name:ir})}),mn,gn,ot,ds,Br,yn,wn,cs,vn,hs,_n,ps,bn,fs=S(()=>{cr(),mn=typeof location>"u"?void 0:location.origin,gn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,ot=gn(),ds=()=>{if(ot&&!ot.startsWith("blob:"))return ot.substring(0,ot.lastIndexOf("/")+1)},Br=(y,E)=>{try{let A=E??ot;return(A?new URL(y,A):new URL(y)).origin===mn}catch{return!1}},yn=(y,E)=>{let A=E??ot;try{return(A?new URL(y,A):new URL(y)).href}catch{return}},wn=(y,E)=>`${E??"./"}${y}`,cs=async y=>{let E=await(await fetch(y,{credentials:"same-origin"})).blob();return URL.createObjectURL(E)},vn=async y=>(await import(y)).default,hs=(Wi(),te(er)).default,_n=async()=>{if(!ot)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Br(ot))return[void 0,hs()];let y=await cs(ot);return[y,hs(y)]},ps=void 0,bn=async(y,E,A,D)=>{let P=ps&&!(y||E);if(P)if(ot)P=Br(ot)||D&&!A;else if(D&&!A)P=!0;else throw new Error("cannot determine the script source URL.");if(P)return[void 0,ps];{let G="ort-wasm-simd-threaded.mjs",U=y??yn(G,E),L=A&&U&&!Br(U,E),V=L?await cs(U):U??wn(G,E);return[L?V:void 0,await vn(V)]}}}),ms,Nr,hr,gs,Sn,Tn,En,ys,Oe,Wt=S(()=>{fs(),Nr=!1,hr=!1,gs=!1,Sn=()=>{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}},Tn=()=>{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}},En=()=>{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(Nr)return Promise.resolve();if(hr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(gs)throw new Error("previous call to 'initializeWebAssembly()' failed.");hr=!0;let E=y.initTimeout,A=y.numThreads;if(y.simd!==!1){if(y.simd==="relaxed"){if(!En())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Tn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let D=Sn();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 P=y.wasmPaths,G=typeof P=="string"?P:void 0,U=P?.mjs,L=U?.href??U,V=P?.wasm,re=V?.href??V,ie=y.wasmBinary,[Z,Q]=await bn(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=ds();Ee&&(Be.locateFile=Ne=>Ee+Ne)}Q(Be).then(Ee=>{hr=!1,Nr=!0,ms=Ee,le(),Z&&URL.revokeObjectURL(Z)},Ee=>{hr=!1,gs=!0,ut(Ee)})})),await Promise.race(F),Te)throw new Error(`WebAssembly backend initializing failed due to timeout: ${E}ms`)},Oe=()=>{if(Nr&&ms)return ms;throw new Error("WebAssembly is not initialized yet.")}}),mt,Ur,Ce,ws=S(()=>{Wt(),mt=(y,E)=>{let A=Oe(),D=A.lengthBytesUTF8(y)+1,P=A._malloc(D);return A.stringToUTF8(y,P,D),E.push(P),P},Ur=(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(([P,G])=>{let U=E?E+P:P;if(typeof G=="object")Ur(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=Oe(),A=E.stackSave();try{let D=E.PTR_SIZE,P=E.stackAlloc(2*D);E._OrtGetLastError(P,P+D);let G=Number(E.getValue(P,D===4?"i32":"i64")),U=E.getValue(P+D,"*"),L=U?E.UTF8ToString(U):"";throw new Error(`${y} ERROR_CODE: ${G}, ERROR_MESSAGE: ${L}`)}finally{E.stackRestore(A)}}}),$n,Hi=S(()=>{Wt(),ws(),$n=y=>{let E=Oe(),A=0,D=[],P=y||{};try{if(y?.logSeverityLevel===void 0)P.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)P.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&&(P.terminate=!1);let G=0;return y?.tag!==void 0&&(G=mt(y.tag,D)),A=E._OrtCreateRunOptions(P.logSeverityLevel,P.logVerbosityLevel,!!P.terminate,G),A===0&&Ce("Can't create run options."),y?.extra!==void 0&&Ur(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}}}),xn,Cn,kn,Nt,Rn,An,ji=S(()=>{Wt(),ws(),xn=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}`)}},Cn=y=>{switch(y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${y}`)}},kn=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)},Nt=(y,E,A,D)=>{let P=mt(E,D),G=mt(A,D);Oe()._OrtAddSessionConfigEntry(y,P,G)!==0&&Ce(`Can't set a session config entry: ${E} - ${A}.`)},Rn=async(y,E,A)=>{let D=E.executionProviders;for(let P of D){let G=typeof P=="string"?P:P.name,U=[];switch(G){case"webnn":if(G="WEBNN",Nt(y,"session.disable_quant_qdq","1",A),Nt(y,"session.disable_qdq_constant_folding","1",A),typeof P!="string"){let Z=P?.deviceType;Z&&Nt(y,"deviceType",Z,A)}break;case"webgpu":if(G="JS",typeof P!="string"){let Z=P;if(Z?.preferredLayout){if(Z.preferredLayout!=="NCHW"&&Z.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${Z.preferredLayout}`);Nt(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=Oe()._malloc(V*Oe().PTR_SIZE),A.push(re),ie=Oe()._malloc(V*Oe().PTR_SIZE),A.push(ie);for(let Z=0;Z<V;Z++)Oe().setValue(re+Z*Oe().PTR_SIZE,U[Z][0],"*"),Oe().setValue(ie+Z*Oe().PTR_SIZE,U[Z][1],"*")}await Oe()._OrtAppendExecutionProvider(y,L,re,ie,V)!==0&&Ce(`Can't append execution provider: ${G}.`)}},An=async y=>{let E=Oe(),A=0,D=[],P=y||{};kn(P);try{let G=xn(P.graphOptimizationLevel??"all"),U=Cn(P.executionMode??"sequential"),L=typeof P.logId=="string"?mt(P.logId,D):0,V=P.logSeverityLevel??2;if(!Number.isInteger(V)||V<0||V>4)throw new Error(`log severity level is not valid: ${V}`);let re=P.logVerbosityLevel??0;if(!Number.isInteger(re)||re<0||re>4)throw new Error(`log verbosity level is not valid: ${re}`);let ie=typeof P.optimizedModelFilePath=="string"?mt(P.optimizedModelFilePath,D):0;if(A=E._OrtCreateSessionOptions(G,!!P.enableCpuMemArena,!!P.enableMemPattern,U,!!P.enableProfiling,0,L,V,re,ie),A===0&&Ce("Can't create session options."),P.executionProviders&&await Rn(A,P,D),P.enableGraphCapture!==void 0){if(typeof P.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${P.enableGraphCapture}`);Nt(A,"enableGraphCapture",P.enableGraphCapture.toString(),D)}if(P.freeDimensionOverrides)for(let[Z,Q]of Object.entries(P.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 P.extra!==void 0&&Ur(P.extra,"",new WeakSet,(Z,Q)=>{Nt(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}}}),Ht,jt,Kt,vs,_s,bs,Ss,qs,Ie=S(()=>{Ht=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}`)}},Kt=(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((P,G)=>P*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",qs=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,In=S(()=>{cr(),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 P=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 P.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)}}),Mn,Ws,Hs,kr,js,Ks,He,tr,Qs,Rr,K,ts,Xs,On=S(()=>{yt(),Hi(),ji(),Ie(),Wt(),ws(),In(),Mn=(y,E)=>{Oe()._OrtInit(y,E)!==0&&Ce("Can't initialize onnxruntime.")},Ws=async y=>{Mn(y.wasm.numThreads,_s(y.logLevel))},Hs=async(y,E)=>{Oe().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 P=y.webgpu.forceFallbackAdapter;if(P!==void 0&&typeof P!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${P}"`);if(A=await navigator.gpu.requestAdapter({powerPreference:D,forceFallbackAdapter:P}),!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")},kr=new Map,js=y=>{let E=Oe(),A=E.stackSave();try{let D=E.PTR_SIZE,P=E.stackAlloc(2*D);E._OrtGetInputOutputCount(y,P,P+D)!==0&&Ce("Can't get session input/output count.");let G=D===4?"i32":"i64";return[Number(E.getValue(P,G)),Number(E.getValue(P+D,G))]}finally{E.stackRestore(A)}},Ks=(y,E)=>{let A=Oe(),D=A.stackSave(),P=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,"*"));P=Number(A.getValue(U+G,"*"));let V=A.HEAP32[P/4];if(V===0)return[L,0];let re=A.HEAPU32[P/4+1],ie=[];for(let Z=0;Z<re;Z++){let Q=Number(A.getValue(P+8+Z*G,"*"));ie.push(Q!==0?A.UTF8ToString(Q):Number(A.getValue(P+8+(Z+re)*G,"*")))}return[L,V,ie]}finally{A.stackRestore(D),P!==0&&A._OrtFree(P)}},He=y=>{let E=Oe(),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,P=Oe();Array.isArray(y)?[A,D]=y:y.buffer===P.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 An(E),E?.externalData&&P.mountExternalData){let Ee=[];for(let Ne of E.externalData){let we=typeof Ne=="string"?Ne:Ne.path;Ee.push(Ts(typeof Ne=="string"?Ne:Ne.data).then(kt=>{P.mountExternalData(we,kt)}))}await Promise.all(Ee)}for(let Ee of E?.executionProviders??[])if((typeof Ee=="string"?Ee:Ee.name)==="webnn"){if(P.shouldTransferToMLTensor=!1,typeof Ee!="string"){let Ne=Ee,we=Ne?.context,kt=Ne?.gpuDevice,Mt=Ne?.deviceType,Mr=Ne?.powerPreference;we?P.currentContext=we:kt?P.currentContext=await P.webnnCreateMLContext(kt):P.currentContext=await P.webnnCreateMLContext({deviceType:Mt,powerPreference:Mr})}else P.currentContext=await P.webnnCreateMLContext();break}G=await P._OrtCreateSession(A,D,U),P.webgpuOnCreateSession?.(G),G===0&&Ce("Can't create a session."),P.jsepOnCreateSession?.(),P.currentContext&&(P.webnnRegisterMLContext(G,P.currentContext),P.currentContext=void 0,P.shouldTransferToMLTensor=!0);let[ie,Z]=js(G),Q=!!E?.enableGraphCapture,Te=[],F=[],le=[],ut=[],Be=[];for(let Ee=0;Ee<ie;Ee++){let[Ne,we,kt]=Ks(G,Ee);Ne===0&&Ce("Can't get an input name."),V.push(Ne);let Mt=P.UTF8ToString(Ne);Te.push(Mt),le.push(we===0?{name:Mt,isTensor:!1}:{name:Mt,isTensor:!0,type:jt(we),shape:kt})}for(let Ee=0;Ee<Z;Ee++){let[Ne,we,kt]=Ks(G,Ee+ie);Ne===0&&Ce("Can't get an output name."),re.push(Ne);let Mt=P.UTF8ToString(Ne);F.push(Mt),ut.push(we===0?{name:Mt,isTensor:!1}:{name:Mt,isTensor:!0,type:jt(we),shape:kt})}return kr.set(G,[G,V,re,null,Q,!1]),[G,Te,F,le,ut]}catch(ie){throw V.forEach(Z=>P._OrtFree(Z)),re.forEach(Z=>P._OrtFree(Z)),G!==0&&P._OrtReleaseSession(G)!==0&&Ce("Can't release session."),ie}finally{P._free(A),U!==0&&P._OrtReleaseSessionOptions(U)!==0&&Ce("Can't release session options."),L.forEach(ie=>P._free(ie)),P.unmountExternalData?.()}},Qs=y=>{let E=Oe(),A=kr.get(y);if(!A)throw new Error(`cannot release session. invalid session id: ${y}`);let[D,P,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),P.forEach(V=>E._OrtFree(V)),G.forEach(V=>E._OrtFree(V)),E._OrtReleaseSession(D)!==0&&Ce("Can't release session."),kr.delete(y)},Rr=async(y,E,A,D,P,G,U=!1)=>{if(!y){E.push(0);return}let L=Oe(),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=Kt(Ht(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=Kt(Ht(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,Ht(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(P);if(Ee(D,we)||Ne(D,we)){let kt=Ht(re);F=Kt(kt,ie),Q="ml-tensor";let Mt=L.webnnCreateTemporaryTensor,Mr=L.webnnUploadTensor;if(!Mt||!Mr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let is=await Mt(D,kt,ie);Mr(is,new Uint8Array(Be.buffer,Be.byteOffset,Be.byteLength)),Te=is}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(Ht(re),Te,F,ut,ie.length,qs(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,P,G)=>{let U=Oe(),L=U.PTR_SIZE,V=kr.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(),Mr=U.stackAlloc(F*L),is=U.stackAlloc(F*L),on=U.stackAlloc(le*L),Fn=U.stackAlloc(le*L);try{[ut,Be]=$n(G),At("wasm prepareInputOutputTensor");for(let Ue=0;Ue<F;Ue++)await Rr(A[Ue],Ee,we,y,ie[E[Ue]],E[Ue],Te);for(let Ue=0;Ue<le;Ue++)await Rr(P[Ue],Ne,we,y,Z[D[Ue]],F+D[Ue],Te);Ct("wasm prepareInputOutputTensor");for(let Ue=0;Ue<F;Ue++)U.setValue(Mr+Ue*L,Ee[Ue],"*"),U.setValue(is+Ue*L,ie[E[Ue]],"*");for(let Ue=0;Ue<le;Ue++)U.setValue(on+Ue*L,Ne[Ue],"*"),U.setValue(Fn+Ue*L,Z[D[Ue]],"*");U.jsepOnRunStart?.(re),U.webnnOnRunStart?.(re);let ct;ct=await U._OrtRun(re,is,Mr,F,Fn,le,on,ut),ct!==0&&Ce("failed to call OrtRun().");let ar=[],Vn=[];At("wasm ProcessOutputTensor");for(let Ue=0;Ue<le;Ue++){let rr=Number(U.getValue(on+Ue*L,"*"));if(rr===Ne[Ue]||kt.includes(Ne[Ue])){ar.push(P[Ue]),rr!==Ne[Ue]&&U._OrtReleaseTensor(rr)!==0&&Ce("Can't release tensor.");continue}let gi=U.stackSave(),mr=U.stackAlloc(4*L),Cs=!1,wt,Bt=0;try{U._OrtGetTensorData(rr,mr,mr+L,mr+2*L,mr+3*L)!==0&&Ce(`Can't access output tensor data on index ${Ue}.`);let ln=L===4?"i32":"i64",ks=Number(U.getValue(mr,ln));Bt=U.getValue(mr+L,"*");let Gn=U.getValue(mr+L*2,"*"),yi=Number(U.getValue(mr+L*3,ln)),Et=[];for(let vt=0;vt<yi;vt++)Et.push(Number(U.getValue(Gn+vt*L,ln)));U._OrtFree(Gn)!==0&&Ce("Can't free memory for tensor dims.");let gr=Et.reduce((vt,ht)=>vt*ht,1);wt=jt(ks);let as=Q?.outputPreferredLocations[D[Ue]];if(wt==="string"){if(as==="gpu-buffer"||as==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let vt=[];for(let ht=0;ht<gr;ht++){let or=U.getValue(Bt+ht*L,"*"),wi=U.getValue(Bt+(ht+1)*L,"*"),vi=ht===gr-1?void 0:wi-or;vt.push(U.UTF8ToString(or,vi))}ar.push([wt,Et,vt,"cpu"])}else if(as==="gpu-buffer"&&gr>0){let vt=U.jsepGetBuffer;if(!vt)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ht=vt(Bt),or=Kt(ks,gr);if(or===void 0||!bs(wt))throw new Error(`Unsupported data type: ${wt}`);Cs=!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(as==="ml-tensor"&&gr>0){let vt=U.webnnEnsureTensor,ht=U.webnnIsGraphInputOutputTypeSupported;if(!vt||!ht)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Kt(ks,gr)===void 0||!Ss(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,Bt,ks,Et,!1);Cs=!0,ar.push([wt,Et,{mlTensor:or,download:U.webnnCreateMLTensorDownloader(Bt,wt),dispose:()=>{U.webnnReleaseTensorId(Bt),U._OrtReleaseTensor(rr)}},"ml-tensor"])}else if(as==="ml-tensor-cpu-output"&&gr>0){let vt=U.webnnCreateMLTensorDownloader(Bt,wt)(),ht=ar.length;Cs=!0,Vn.push((async()=>{let or=[ht,await vt];return U.webnnReleaseTensorId(Bt),U._OrtReleaseTensor(rr),or})()),ar.push([wt,Et,[],"cpu"])}else{let vt=vs(wt),ht=new vt(gr);new Uint8Array(ht.buffer,ht.byteOffset,ht.byteLength).set(U.HEAPU8.subarray(Bt,Bt+ht.byteLength)),ar.push([wt,Et,ht,"cpu"])}}finally{U.stackRestore(gi),wt==="string"&&Bt&&U._free(Bt),Cs||U._OrtReleaseTensor(rr)}}Q&&!Te&&(U._OrtClearBoundOutputs(Q.handle)!==0&&Ce("Can't clear bound outputs."),kr.set(y,[re,ie,Z,Q,Te,!1]));for(let[Ue,rr]of await Promise.all(Vn))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))}},ts=y=>{let E=Oe(),A=kr.get(y);if(!A)throw new Error("invalid session id");let D=A[0],P=E._OrtEndProfiling(D);P===0&&Ce("Can't get an profile file name."),E._OrtFree(P)},Xs=y=>{let E=[];for(let A of y){let D=A[2];!Array.isArray(D)&&"buffer"in D&&E.push(D.buffer)}return E}}),pr,ke,Ar,rs,Fr,ss,Es,$s,fr,Ir,Ys,Js,Zs,Pn,Dn,fi,ns,zn,Ln=S(()=>{yt(),On(),Wt(),fs(),pr=()=>!!fe.wasm.proxy&&typeof document<"u",Ar=!1,rs=!1,Fr=!1,$s=new Map,fr=(y,E)=>{let A=$s.get(y);A?A.push(E):$s.set(y,[E])},Ir=()=>{if(Ar||!rs||Fr||!ke)throw new Error("worker not ready")},Ys=y=>{switch(y.data.type){case"init-wasm":Ar=!1,y.data.err?(Fr=!0,Es[1](y.data.err)):(rs=!0,Es[0]()),ss&&(URL.revokeObjectURL(ss),ss=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}}},Js=async()=>{if(!rs){if(Ar)throw new Error("multiple calls to 'initWasm()' detected.");if(Fr)throw new Error("previous call to 'initWasm()' failed.");if(Ar=!0,pr())return new Promise((y,E)=>{ke?.terminate(),_n().then(([A,D])=>{try{ke=D,ke.onerror=G=>E(G),ke.onmessage=Ys,Es=[y,E];let P={type:"init-wasm",in:fe};if(!P.in.wasm.wasmPaths&&A){let G=ds();G&&(P.in.wasm.wasmPaths=G)}ke.postMessage(P),ss=A}catch(P){E(P)}},E)});try{await ys(fe.wasm),await Ws(fe),rs=!0}catch(y){throw Fr=!0,y}finally{Ar=!1}}},Zs=async y=>{if(pr())return Ir(),new Promise((E,A)=>{fr("init-ep",[E,A]);let D={type:"init-ep",in:{epName:y,env:fe}};ke.postMessage(D)});await Hs(fe,y)},Pn=async y=>pr()?(Ir(),new Promise((E,A)=>{fr("copy-from",[E,A]);let D={type:"copy-from",in:{buffer:y}};ke.postMessage(D,[y.buffer])})):He(y),Dn=async(y,E)=>{if(pr()){if(E?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ir(),new Promise((A,D)=>{fr("create",[A,D]);let P={type:"create",in:{model:y,options:{...E}}},G=[];y instanceof Uint8Array&&G.push(y.buffer),ke.postMessage(P,G)})}else return tr(y,E)},fi=async y=>{if(pr())return Ir(),new Promise((E,A)=>{fr("release",[E,A]);let D={type:"release",in:y};ke.postMessage(D)});Qs(y)},ns=async(y,E,A,D,P,G)=>{if(pr()){if(A.some(U=>U[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(P.some(U=>U))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ir(),new Promise((U,L)=>{fr("run",[U,L]);let V=A,re={type:"run",in:{sessionId:y,inputIndices:E,inputs:V,outputIndices:D,options:G}};ke.postMessage(re,Xs(V))})}else return K(y,E,A,D,P,G)},zn=async y=>{if(pr())return Ir(),new Promise((E,A)=>{fr("end-profiling",[E,A]);let D={type:"end-profiling",in:y};ke.postMessage(D)});ts(y)}}),Bn,en,tn,rn=S(()=>{yt(),Ln(),Ie(),cr(),In(),Bn=(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()}`)}},en=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:P}=y[2];return lt.fromGpuBuffer(A,{dataType:E,dims:y[1],download:D,dispose:P})}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:P}=y[2];return lt.fromMLTensor(A,{dataType:E,dims:y[1],download:D,dispose:P})}default:throw new Error(`invalid data location: ${y[3]}`)}},tn=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 Dn(A,E),ft()}async dispose(){return fi(this.sessionId)}async run(y,E,A){gt();let D=[],P=[];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),P.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)=>Bn(Z,()=>`input "${this.inputNames[P[Q]]}"`)),V=G.map((Z,Q)=>Z?Bn(Z,()=>`output "${this.outputNames[U[Q]]}"`):null),re=await ns(this.sessionId,P,L,U,V,A),ie={};for(let Z=0;Z<re.length;Z++)ie[this.outputNames[U[Z]]]=G[Z]??en(re[Z]);return ft(),ie}startProfiling(){}endProfiling(){zn(this.sessionId)}}}),xs={};N(xs,{OnnxruntimeWebAssemblyBackend:()=>nn,initializeFlags:()=>sn,wasmBackend:()=>an});var sn,nn,an,Nn=S(()=>{yt(),Ln(),rn(),sn=()=>{(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))}},nn=class{async init(y){sn(),await Js(),await Zs(y)}async createInferenceSessionHandler(y,E){let A=new tn;return await A.loadModel(y,E),A}},an=new nn}),Un={};N(Un,{InferenceSession:()=>Lr,TRACE:()=>Zt,TRACE_EVENT_BEGIN:()=>At,TRACE_EVENT_END:()=>Ct,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>ft,Tensor:()=>lt,default:()=>Ki,env:()=>fe,registerBackend:()=>J}),yt(),yt(),yt();var mi="1.26.0",Ki=Cr;{let y=(Nn(),te(xs)).wasmBackend;J("cpu",y,10),J("wasm",y,10)}return Object.defineProperty(fe.versions,"web",{value:mi,enumerable:!0}),te(Un)})();d.exports=s})(io)),io.exports}var Mp;function xy(){return Mp||(Mp=1,(function(d){var r=Hr&&Hr.__createBinding||(Object.create?(function(de,he,pe,ce){ce===void 0&&(ce=pe);var Ve=Object.getOwnPropertyDescriptor(he,pe);(!Ve||("get"in Ve?!he.__esModule:Ve.writable||Ve.configurable))&&(Ve={enumerable:!0,get:function(){return he[pe]}}),Object.defineProperty(de,ce,Ve)}):(function(de,he,pe,ce){ce===void 0&&(ce=pe),de[ce]=he[pe]})),s=Hr&&Hr.__setModuleDefault||(Object.create?(function(de,he){Object.defineProperty(de,"default",{enumerable:!0,value:he})}):function(de,he){de.default=he}),a=Hr&&Hr.__importStar||function(de){if(de&&de.__esModule)return de;var he={};if(de!=null)for(var pe in de)pe!=="default"&&Object.prototype.hasOwnProperty.call(de,pe)&&r(he,de,pe);return s(he,de),he};Object.defineProperty(d,"__esModule",{value:!0}),d.MicVAD=d.getDefaultRealTimeVADOptions=d.ort=d.DEFAULT_MODEL=void 0;const f=a($y()),v=Io(),C=Mo(),R=hn(),S=qi(),N=pf(),z=ff();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 he=>{he.getTracks().forEach(pe=>{pe.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:he=>{he.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,he,pe,ce,Ve){await pe.audioWorklet.addModule(de),he.processorOptions={...he.processorOptions??{},frameSamples:ce};const fe=new AudioWorkletNode(pe,"vad-helper-worklet",he);return fe.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}}},fe}async function ne(de,he,pe){const ce=new z.Resampler({nativeSampleRate:de.sampleRate,targetSampleRate:16e3,targetFrameSize:he});R.log.debug("using script processor");const fe=de.createScriptProcessor(4096,1,1);let Ye=!1;return fe.onaudioprocess=async qe=>{if(!Ye){Ye=!0;try{const it=qe.inputBuffer.getChannelData(0);qe.outputBuffer.getChannelData(0).fill(0);const at=ce.process(it);for(const tt of at)await pe(tt)}catch(it){console.error("Error processing audio:",it)}finally{Ye=!1}}},fe.connect(de.destination),fe}class ge{constructor(he,pe,ce,Ve,fe=!1,Ye=null,qe=null,it=null,Je=null,at=null,tt=null,Gt="uninitialized",xt=!1){this.options=he,this.frameProcessor=pe,this.model=ce,this.frameSamples=Ve,this.listening=fe,this.errored=Ye,this._stream=qe,this._audioContext=it,this._vadNode=Je,this._mediaStreamAudioSourceNode=at,this._audioProcessorAdapterType=tt,this.initializationState=Gt,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(he={}){const pe={...(0,d.getDefaultRealTimeVADOptions)(he.model??d.DEFAULT_MODEL),...he};(0,C.validateOptions)(pe),d.ort.env.wasm.wasmPaths=pe.onnxWASMBasePath,pe.ortConfig!==void 0&&pe.ortConfig(d.ort);const ce=pe.model==="v5"?j:se,Ve=pe.baseAssetPath+ce,fe=pe.model==="v5"?N.SileroV5.new:N.SileroLegacy.new;let Ye;try{Ye=await fe(d.ort,()=>(0,v.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 ge(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=ge})(Hr)),Hr}var Op;function Pp(){return Op||(Op=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=df();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 v=Ty();Object.defineProperty(d,"NonRealTimeVAD",{enumerable:!0,get:function(){return v.NonRealTimeVAD}});const C=Ey();d.utils={audioFileToArray:C.audioFileToArray,minFramesForTargetMS:C.minFramesForTargetMS,arrayBufferToBase64:C.arrayBufferToBase64,encodeWAV:C.encodeWAV};var R=xy();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 Cy(){return Dp||(Dp=1,(function(d){Object.defineProperty(d,"__esModule",{value:!0}),d.useMicVAD=d.getDefaultReactRealTimeVADOptions=d.utils=void 0;const r=Pp(),s=ae;var a=Pp();Object.defineProperty(d,"utils",{enumerable:!0,get:function(){return a.utils}});const f={userSpeakingThreshold:.6},v=S=>({...(0,r.getDefaultRealTimeVADOptions)(S),...f});d.getDefaultReactRealTimeVADOptions=v;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),[ge,de]=(0,s.useState)(!1),[he,pe]=(0,s.useState)(null),ce=(0,s.useRef)(z.onFrameProcessed),Ve=(0,s.useRef)(z.onSpeechEnd),fe=(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)(()=>{ce.current=z.onFrameProcessed,Ve.current=z.onSpeechEnd,fe.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),ce.current(ze,Rt)},onSpeechEnd:ze=>{Ve.current(ze)},onSpeechStart:()=>{fe.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 he?.pause(),de(!1))},[J,W,he]),tt=(0,s.useCallback)(async()=>{!J&&!W&&(await he?.start(),de(!0))},[J,W,he]),Gt=(0,s.useCallback)(async()=>{ge?await at():await tt()},[ge,at,tt]);return{listening:ge,errored:W,loading:J,userSpeaking:j,pause:at,start:tt,toggle:Gt}}d.useMicVAD=R})(to)),to}var ky=Cy(),gf=hn();gf.log.debug=()=>{};gf.log.warn=()=>{};const zp={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1};typeof window<"u"&&(window.addEventListener("unhandledrejection",d=>{d.reason&&d.reason.message&&d.reason.message.includes("MicVAD has null stream")&&d.preventDefault()}),window.addEventListener("error",d=>{d.message&&(d.message.includes("Cannot read properties of null (reading 'state')")||d.message.includes("Cannot read properties of undefined (reading 'S')"))&&d.preventDefault()}));const Ry=16e3,yf=512,wf=1e3,Ay=300,Iy=yf/Ry*1e3,My=Math.ceil(wf/Iy);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,v)=>f+v.length,0),s=new Float32Array(r);let a=0;for(const f of d)s.set(f,a),a+=f.length;return s}function Oy(d={}){const{onAudioChunk:r,onAudioEnd:s,onSpeechStart:a,onSpeechEnd:f,onVADMisfire:v,onError:C,enabled:R=!0,preloadStream:S=!0}=d,{sendAudioChunk:N,endAudioStream:z}=Us(),[te,j]=ae.useState(!1),[se,J]=ae.useState(null),Y=ae.useRef(null),W=ae.useRef(!1),ne=ae.useRef(null),ge=ae.useRef([]),de=ae.useRef(!1),he=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 ce=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})},[]),fe=ae.useCallback(async()=>Y.current&&Y.current.getTracks()[0]?.readyState==="live"?(Y.current.getTracks().forEach(We=>{We.enabled=!0}),Y.current):ce(),[ce]);ae.useCallback(()=>{const We=ge.current;return ge.current=[],oo(We)},[]);const Ye=ae.useCallback(()=>{he.current=[];const We=ge.current;ge.current=[];for(const st of We)pe(ao(st));de.current=!0},[pe]),qe=ae.useCallback(()=>{de.current=!1;const We=he.current;if(he.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=ky.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:wf,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:yf}},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:ce,pauseStream:Ve,resumeStream:fe,onFrameProcessed:(We,st)=>{if(st&&(ge.current.push(new Float32Array(st)),ge.current.length>My&&ge.current.shift(),de.current)){const ze=he.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?.()},Ay)},onVADMisfire:()=>{ne.current&&(clearTimeout(ne.current),ne.current=null),j(!1),qe(),v?.()}}),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]),Gt=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?ce():null,[R,ce]),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:Gt,prepare:xt,start:Ke,stop:at,pause:Je.pause,userSpeaking:Je.userSpeaking}}function Py(d,r,s=[]){const{events:a}=Us();ae.useEffect(()=>a.on(d,r),[d,r,a,...s])}function Dy({connect:d=!0,session:r,onError:s,onInitialized:a,clientTools:f,children:v}){const{initializeSession:C,joinDesktopSession:R,disconnect:S,registerClientTools:N}=lf(),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),ge=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(()=>{ge.current=f}),ae.useEffect(()=>{if(!d||z.current)return;z.current=!0,te.current=!1;let de=!1;return(async()=>{try{const pe=ge.current;if(r?.mode==="join_desktop"){const Ve=await se.current({uniqueId:r.uniqueId});de||(pe&&ne.current(pe),W.current?.(Ve));return}const ce=await j.current({apiKey:r?.apiKey,agentId:r?.agentId,language:r?.language||"en",config:r?.config,clientTools:pe});de||W.current?.(ce)}catch(pe){de||(te.current=!0,Y.current?.(pe))}})(),()=>{de=!0,!te.current&&(J.current(),z.current=!1)}},[d,r]),Yt.jsx(Yt.Fragment,{children:v})}function zy({children:d,wsUrl:r,restUrl:s,session:a,connect:f=!0,enableAudio:v=!0,pcmOptions:C,debug:R=!1,withCredentials:S=!1,onError:N,onInitialized:z,clientTools:te}){return Yt.jsx(of,{wsUrl:r,restUrl:s,enableAudio:v,pcmOptions:C,debug:R,withCredentials:S,children:Yt.jsx(Dy,{connect:f,session:a,onError:N,onInitialized:z,clientTools:te,children:d})})}var lo={exports:{}},Lp;function Ly(){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 $y(){return Ip||(Ip=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=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 P of v(E))!C.call(y,P)&&P!==A&&a(y,P,{get:()=>E[P],enumerable:!(D=f(E,P))||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 P=se.indexOf(y);P!==-1&&se.splice(P,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,P,G=[],U=new Set;for(let V of D){let re=await Y(V);typeof re=="string"?G.push({name:V,err:re}):(P||(P=re),P===re&&U.add(V))}if(!P)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[P,new Proxy(y,{get:(V,re)=>re==="executionProviders"?L:Reflect.get(V,re)})]}}),fe=S(()=>{ne()}),ue,he=S(()=>{ue="1.26.0"}),pe,ce,Ve=S(()=>{he(),pe="warning",ce={wasm:{},webgl:{},webgpu:{},versions:{common:ue},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(ce,"logLevel",{enumerable:!0})}),me,Ye=S(()=>{Ve(),me=ce}),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 P,G;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[3]):(P=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*P,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<P;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 P,G,U;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[1],U=y.dims[3]):(P=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*P;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(P,G);for(let kt=0;kt<G*P;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,Gt,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,P=E.norm??{mean:255,bias:0},G,U;typeof P.mean=="number"?G=[P.mean,P.mean,P.mean,P.mean]:G=[P.mean[0],P.mean[1],P.mean[2],P.mean[3]??255],typeof P.bias=="number"?U=[P.bias,P.bias,P.bias,P.bias]:U=[P.bias[0],P.bias[1],P.bias[2],P.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,P=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(P){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")},Gt=(y,E)=>{let{width:A,height:D,download:P,dispose:G}=E,U=[1,D,A,4];return new rt({location:"texture",type:"float32",texture:y,dims:U,download:P,dispose:G})},xt=(y,E)=>{let{dataType:A,dims:D,download:P,dispose:G}=E;return new rt({location:"gpu-buffer",type:A??"float32",gpuBuffer:y,dims:D,download:P,dispose:G})},Ke=(y,E)=>{let{dataType:A,dims:D,download:P,dispose:G}=E;return new rt({location:"ml-tensor",type:A??"float32",mlTensor:y,dims:D,download:P,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,P;if(typeof y=="object"&&"location"in y)switch(this.dataLocation=y.location,D=y.type,P=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");P=L,this.cpuData=U,this.dataLocation="cpu"}let G=Yr(P);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=P,this.size=G}static async fromImage(y,E){return tt(y,E)}static fromTexture(y,E){return Gt(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 ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.timeStamp(`${y}::ORT::${E}`)},$r=(y,E)=>{let A=new Error().stack?.split(/\r\n|\r|\n/g)||[],D=!1;for(let P=0;P<A.length;P++){if(D&&!A[P].includes("TRACE_FUNC")){let G=`FUNC_${y}::${A[P].trim().split(" ")[1]}`;E&&(G+=`::${E}`),er("CPU",G);return}A[P].includes("TRACE_FUNC")&&(D=!0)}},gt=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||$r("BEGIN",y)},ft=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||$r("END",y)},At=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.time(`ORT::${y}`)},Ct=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.timeEnd(`ORT::${y}`)}}),ts,qs=S(()=>{ne(),Zr(),es(),ts=class mf{constructor(E){this.handler=E}async run(E,A,D){gt(),At("InferenceSession.run");let P={},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}.`);P[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,P[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)P[re]=null;let L=await this.handler.run(E,P,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,P){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 P=="object"&&P!==null)U=P;else if(typeof P<"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 mf(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(()=>{}),qt=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(),qt(),es(),nr(),It()}),Lr=S(()=>{}),Br={};N(Br,{default:()=>Wt});var Bt,ir,Wt,Wi=S(()=>{On(),Ht(),ms(),Bt="ort-wasm-proxy-worker",ir=globalThis.self?.name===Bt,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:P}=A;js(P,D).then(()=>{postMessage({type:E})},G=>{postMessage({type:E,err:G})});break}case"copy-from":{let{buffer:D}=A,P=He(D);postMessage({type:E,out:P});break}case"create":{let{model:D,options:P}=A;tr(D,P).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:P,inputs:G,outputIndices:U,options:L}=A;K(D,P,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:Bt})}),mn,gn,ot,cs,Nr,yn,wn,hs,vn,ps,_n,fs,bn,ms=S(()=>{Lr(),mn=typeof location>"u"?void 0:location.origin,gn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,ot=gn(),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===mn}catch{return!1}},yn=(y,E)=>{let A=E??ot;try{return(A?new URL(y,A):new URL(y)).href}catch{return}},wn=(y,E)=>`${E??"./"}${y}`,hs=async y=>{let E=await(await fetch(y,{credentials:"same-origin"})).blob();return URL.createObjectURL(E)},vn=async y=>(await import(y)).default,ps=(Wi(),te(Br)).default,_n=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,bn=async(y,E,A,D)=>{let P=fs&&!(y||E);if(P)if(ot)P=Nr(ot)||D&&!A;else if(D&&!A)P=!0;else throw new Error("cannot determine the script source URL.");if(P)return[void 0,fs];{let G="ort-wasm-simd-threaded.mjs",U=y??yn(G,E),L=A&&U&&!Nr(U,E),V=L?await hs(U):U??wn(G,E);return[L?V:void 0,await vn(V)]}}}),gs,Ur,cr,ys,Sn,Tn,En,ws,Oe,Ht=S(()=>{ms(),Ur=!1,cr=!1,ys=!1,Sn=()=>{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}},Tn=()=>{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}},En=()=>{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(!En())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Tn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let D=Sn();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 P=y.wasmPaths,G=typeof P=="string"?P:void 0,U=P?.mjs,L=U?.href??U,V=P?.wasm,re=V?.href??V,ie=y.wasmBinary,[Z,Q]=await bn(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`)},Oe=()=>{if(Ur&&gs)return gs;throw new Error("WebAssembly is not initialized yet.")}}),mt,Fr,Ce,vs=S(()=>{Ht(),mt=(y,E)=>{let A=Oe(),D=A.lengthBytesUTF8(y)+1,P=A._malloc(D);return A.stringToUTF8(y,P,D),E.push(P),P},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(([P,G])=>{let U=E?E+P:P;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=Oe(),A=E.stackSave();try{let D=E.PTR_SIZE,P=E.stackAlloc(2*D);E._OrtGetLastError(P,P+D);let G=Number(E.getValue(P,D===4?"i32":"i64")),U=E.getValue(P+D,"*"),L=U?E.UTF8ToString(U):"";throw new Error(`${y} ERROR_CODE: ${G}, ERROR_MESSAGE: ${L}`)}finally{E.stackRestore(A)}}}),$n,Hi=S(()=>{Ht(),vs(),$n=y=>{let E=Oe(),A=0,D=[],P=y||{};try{if(y?.logSeverityLevel===void 0)P.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)P.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&&(P.terminate=!1);let G=0;return y?.tag!==void 0&&(G=mt(y.tag,D)),A=E._OrtCreateRunOptions(P.logSeverityLevel,P.logVerbosityLevel,!!P.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}}}),xn,Cn,kn,Nt,Rn,An,ji=S(()=>{Ht(),vs(),xn=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}`)}},Cn=y=>{switch(y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${y}`)}},kn=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)},Nt=(y,E,A,D)=>{let P=mt(E,D),G=mt(A,D);Oe()._OrtAddSessionConfigEntry(y,P,G)!==0&&Ce(`Can't set a session config entry: ${E} - ${A}.`)},Rn=async(y,E,A)=>{let D=E.executionProviders;for(let P of D){let G=typeof P=="string"?P:P.name,U=[];switch(G){case"webnn":if(G="WEBNN",Nt(y,"session.disable_quant_qdq","1",A),Nt(y,"session.disable_qdq_constant_folding","1",A),typeof P!="string"){let Z=P?.deviceType;Z&&Nt(y,"deviceType",Z,A)}break;case"webgpu":if(G="JS",typeof P!="string"){let Z=P;if(Z?.preferredLayout){if(Z.preferredLayout!=="NCHW"&&Z.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${Z.preferredLayout}`);Nt(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=Oe()._malloc(V*Oe().PTR_SIZE),A.push(re),ie=Oe()._malloc(V*Oe().PTR_SIZE),A.push(ie);for(let Z=0;Z<V;Z++)Oe().setValue(re+Z*Oe().PTR_SIZE,U[Z][0],"*"),Oe().setValue(ie+Z*Oe().PTR_SIZE,U[Z][1],"*")}await Oe()._OrtAppendExecutionProvider(y,L,re,ie,V)!==0&&Ce(`Can't append execution provider: ${G}.`)}},An=async y=>{let E=Oe(),A=0,D=[],P=y||{};kn(P);try{let G=xn(P.graphOptimizationLevel??"all"),U=Cn(P.executionMode??"sequential"),L=typeof P.logId=="string"?mt(P.logId,D):0,V=P.logSeverityLevel??2;if(!Number.isInteger(V)||V<0||V>4)throw new Error(`log severity level is not valid: ${V}`);let re=P.logVerbosityLevel??0;if(!Number.isInteger(re)||re<0||re>4)throw new Error(`log verbosity level is not valid: ${re}`);let ie=typeof P.optimizedModelFilePath=="string"?mt(P.optimizedModelFilePath,D):0;if(A=E._OrtCreateSessionOptions(G,!!P.enableCpuMemArena,!!P.enableMemPattern,U,!!P.enableProfiling,0,L,V,re,ie),A===0&&Ce("Can't create session options."),P.executionProviders&&await Rn(A,P,D),P.enableGraphCapture!==void 0){if(typeof P.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${P.enableGraphCapture}`);Nt(A,"enableGraphCapture",P.enableGraphCapture.toString(),D)}if(P.freeDimensionOverrides)for(let[Z,Q]of Object.entries(P.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 P.extra!==void 0&&Fr(P.extra,"",new WeakSet,(Z,Q)=>{Nt(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((P,G)=>P*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,In=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 P=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 P.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)}}),Mn,Hs,js,Cr,Ks,Qs,He,tr,Xs,kr,K,rs,Ys,On=S(()=>{yt(),Hi(),ji(),Ie(),Ht(),vs(),In(),Mn=(y,E)=>{Oe()._OrtInit(y,E)!==0&&Ce("Can't initialize onnxruntime.")},Hs=async y=>{Mn(y.wasm.numThreads,bs(y.logLevel))},js=async(y,E)=>{Oe().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 P=y.webgpu.forceFallbackAdapter;if(P!==void 0&&typeof P!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${P}"`);if(A=await navigator.gpu.requestAdapter({powerPreference:D,forceFallbackAdapter:P}),!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=Oe(),A=E.stackSave();try{let D=E.PTR_SIZE,P=E.stackAlloc(2*D);E._OrtGetInputOutputCount(y,P,P+D)!==0&&Ce("Can't get session input/output count.");let G=D===4?"i32":"i64";return[Number(E.getValue(P,G)),Number(E.getValue(P+D,G))]}finally{E.stackRestore(A)}},Qs=(y,E)=>{let A=Oe(),D=A.stackSave(),P=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,"*"));P=Number(A.getValue(U+G,"*"));let V=A.HEAP32[P/4];if(V===0)return[L,0];let re=A.HEAPU32[P/4+1],ie=[];for(let Z=0;Z<re;Z++){let Q=Number(A.getValue(P+8+Z*G,"*"));ie.push(Q!==0?A.UTF8ToString(Q):Number(A.getValue(P+8+(Z+re)*G,"*")))}return[L,V,ie]}finally{A.stackRestore(D),P!==0&&A._OrtFree(P)}},He=y=>{let E=Oe(),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,P=Oe();Array.isArray(y)?[A,D]=y:y.buffer===P.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 An(E),E?.externalData&&P.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=>{P.mountExternalData(we,kt)}))}await Promise.all(Ee)}for(let Ee of E?.executionProviders??[])if((typeof Ee=="string"?Ee:Ee.name)==="webnn"){if(P.shouldTransferToMLTensor=!1,typeof Ee!="string"){let Ne=Ee,we=Ne?.context,kt=Ne?.gpuDevice,Mt=Ne?.deviceType,Ir=Ne?.powerPreference;we?P.currentContext=we:kt?P.currentContext=await P.webnnCreateMLContext(kt):P.currentContext=await P.webnnCreateMLContext({deviceType:Mt,powerPreference:Ir})}else P.currentContext=await P.webnnCreateMLContext();break}G=await P._OrtCreateSession(A,D,U),P.webgpuOnCreateSession?.(G),G===0&&Ce("Can't create a session."),P.jsepOnCreateSession?.(),P.currentContext&&(P.webnnRegisterMLContext(G,P.currentContext),P.currentContext=void 0,P.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=P.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=P.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=>P._OrtFree(Z)),re.forEach(Z=>P._OrtFree(Z)),G!==0&&P._OrtReleaseSession(G)!==0&&Ce("Can't release session."),ie}finally{P._free(A),U!==0&&P._OrtReleaseSessionOptions(U)!==0&&Ce("Can't release session options."),L.forEach(ie=>P._free(ie)),P.unmountExternalData?.()}},Xs=y=>{let E=Oe(),A=Cr.get(y);if(!A)throw new Error(`cannot release session. invalid session id: ${y}`);let[D,P,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),P.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,P,G,U=!1)=>{if(!y){E.push(0);return}let L=Oe(),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(P);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,P,G)=>{let U=Oe(),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),Fn=U.stackAlloc(le*L);try{[ut,Be]=$n(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(P[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(Fn+Ue*L,Z[D[Ue]],"*");U.jsepOnRunStart?.(re),U.webnnOnRunStart?.(re);let ct;ct=await U._OrtRun(re,as,Ir,F,Fn,le,ln,ut),ct!==0&&Ce("failed to call OrtRun().");let ar=[],Vn=[];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(P[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 Gn=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(Gn+vt*L,un)));U._OrtFree(Gn)!==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,Vn.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(Vn))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=Oe(),A=Cr.get(y);if(!A)throw new Error("invalid session id");let D=A[0],P=E._OrtEndProfiling(D);P===0&&Ce("Can't get an profile file name."),E._OrtFree(P)},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,Dn,fi,is,zn,Ln=S(()=>{yt(),On(),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(),_n().then(([A,D])=>{try{ke=D,ke.onerror=G=>E(G),ke.onmessage=Js,$s=[y,E];let P={type:"init-wasm",in:me};if(!P.in.wasm.wasmPaths&&A){let G=cs();G&&(P.in.wasm.wasmPaths=G)}ke.postMessage(P),ns=A}catch(P){E(P)}},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),Dn=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 P={type:"create",in:{model:y,options:{...E}}},G=[];y instanceof Uint8Array&&G.push(y.buffer),ke.postMessage(P,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,P,G)=>{if(hr()){if(A.some(U=>U[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(P.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,P,G)},zn=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)}}),Bn,tn,rn,sn=S(()=>{yt(),Ln(),Ie(),Lr(),In(),Bn=(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:P}=y[2];return lt.fromGpuBuffer(A,{dataType:E,dims:y[1],download:D,dispose:P})}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:P}=y[2];return lt.fromMLTensor(A,{dataType:E,dims:y[1],download:D,dispose:P})}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 Dn(A,E),ft()}async dispose(){return fi(this.sessionId)}async run(y,E,A){gt();let D=[],P=[];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),P.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)=>Bn(Z,()=>`input "${this.inputNames[P[Q]]}"`)),V=G.map((Z,Q)=>Z?Bn(Z,()=>`output "${this.outputNames[U[Q]]}"`):null),re=await is(this.sessionId,P,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(){zn(this.sessionId)}}}),Cs={};N(Cs,{OnnxruntimeWebAssemblyBackend:()=>an,initializeFlags:()=>nn,wasmBackend:()=>on});var nn,an,on,Nn=S(()=>{yt(),Ln(),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}),Un={};N(Un,{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=(Nn(),te(Cs)).wasmBackend;J("cpu",y,10),J("wasm",y,10)}return Object.defineProperty(me.versions,"web",{value:mi,enumerable:!0}),te(Un)})();d.exports=s})(io)),io.exports}var Mp;function xy(){return Mp||(Mp=1,(function(d){var r=jr&&jr.__createBinding||(Object.create?(function(ue,he,pe,ce){ce===void 0&&(ce=pe);var Ve=Object.getOwnPropertyDescriptor(he,pe);(!Ve||("get"in Ve?!he.__esModule:Ve.writable||Ve.configurable))&&(Ve={enumerable:!0,get:function(){return he[pe]}}),Object.defineProperty(ue,ce,Ve)}):(function(ue,he,pe,ce){ce===void 0&&(ce=pe),ue[ce]=he[pe]})),s=jr&&jr.__setModuleDefault||(Object.create?(function(ue,he){Object.defineProperty(ue,"default",{enumerable:!0,value:he})}):function(ue,he){ue.default=he}),a=jr&&jr.__importStar||function(ue){if(ue&&ue.__esModule)return ue;var he={};if(ue!=null)for(var pe in ue)pe!=="default"&&Object.prototype.hasOwnProperty.call(ue,pe)&&r(he,ue,pe);return s(he,ue),he};Object.defineProperty(d,"__esModule",{value:!0}),d.MicVAD=d.getDefaultRealTimeVADOptions=d.ort=d.DEFAULT_MODEL=void 0;const f=a($y()),v=Io(),C=Mo(),R=pn(),S=qi(),N=pf(),z=ff();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=ue=>({...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:ue,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async he=>{he.getTracks().forEach(pe=>{pe.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:he=>{he.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});d.getDefaultRealTimeVADOptions=J;const Y=ue=>"audioWorklet"in ue&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function W(ue,he,pe,ce,Ve){await pe.audioWorklet.addModule(ue),he.processorOptions={...he.processorOptions??{},frameSamples:ce};const me=new AudioWorkletNode(pe,"vad-helper-worklet",he);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(ue,he,pe){const ce=new z.Resampler({nativeSampleRate:ue.sampleRate,targetSampleRate:16e3,targetFrameSize:he});R.log.debug("using script processor");const me=ue.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=ce.process(it);for(const tt of at)await pe(tt)}catch(it){console.error("Error processing audio:",it)}finally{Ye=!1}}},me.connect(ue.destination),me}class fe{constructor(he,pe,ce,Ve,me=!1,Ye=null,qe=null,it=null,Je=null,at=null,tt=null,Gt="uninitialized",xt=!1){this.options=he,this.frameProcessor=pe,this.model=ce,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=Gt,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(he={}){const pe={...(0,d.getDefaultRealTimeVADOptions)(he.model??d.DEFAULT_MODEL),...he};(0,C.validateOptions)(pe),d.ort.env.wasm.wasmPaths=pe.onnxWASMBasePath,pe.ortConfig!==void 0&&pe.ortConfig(d.ort);const ce=pe.model==="v5"?j:se,Ve=pe.baseAssetPath+ce,me=pe.model==="v5"?N.SileroV5.new:N.SileroLegacy.new;let Ye;try{Ye=await me(d.ort,()=>(0,v.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 Op;function Pp(){return Op||(Op=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=df();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 v=Ty();Object.defineProperty(d,"NonRealTimeVAD",{enumerable:!0,get:function(){return v.NonRealTimeVAD}});const C=Ey();d.utils={audioFileToArray:C.audioFileToArray,minFramesForTargetMS:C.minFramesForTargetMS,arrayBufferToBase64:C.arrayBufferToBase64,encodeWAV:C.encodeWAV};var R=xy();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 Cy(){return Dp||(Dp=1,(function(d){Object.defineProperty(d,"__esModule",{value:!0}),d.useMicVAD=d.getDefaultReactRealTimeVADOptions=d.utils=void 0;const r=Pp(),s=ae;var a=Pp();Object.defineProperty(d,"utils",{enumerable:!0,get:function(){return a.utils}});const f={userSpeakingThreshold:.6},v=S=>({...(0,r.getDefaultRealTimeVADOptions)(S),...f});d.getDefaultReactRealTimeVADOptions=v;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,ue]=(0,s.useState)(!1),[he,pe]=(0,s.useState)(null),ce=(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)(()=>{ce.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),ce.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(),ue(!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&&ue(!1)}},[Je,te]);const at=(0,s.useCallback)(async()=>{!J&&!W&&(await he?.pause(),ue(!1))},[J,W,he]),tt=(0,s.useCallback)(async()=>{!J&&!W&&(await he?.start(),ue(!0))},[J,W,he]),Gt=(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:Gt}}d.useMicVAD=R})(to)),to}var ky=Cy(),gf=pn();gf.log.debug=()=>{};gf.log.warn=()=>{};const zp={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1};typeof window<"u"&&(window.addEventListener("unhandledrejection",d=>{d.reason&&d.reason.message&&d.reason.message.includes("MicVAD has null stream")&&d.preventDefault()}),window.addEventListener("error",d=>{d.message&&(d.message.includes("Cannot read properties of null (reading 'state')")||d.message.includes("Cannot read properties of undefined (reading 'S')"))&&d.preventDefault()}));const Ry=16e3,yf=512,wf=1e3,Ay=300,Iy=yf/Ry*1e3,My=Math.ceil(wf/Iy);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,v)=>f+v.length,0),s=new Float32Array(r);let a=0;for(const f of d)s.set(f,a),a+=f.length;return s}function Oy(d={}){const{onAudioChunk:r,onAudioEnd:s,onSpeechStart:a,onSpeechEnd:f,onVADMisfire:v,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([]),ue=ae.useRef(!1),he=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 ce=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):ce(),[ce]);ae.useCallback(()=>{const We=fe.current;return fe.current=[],oo(We)},[]);const Ye=ae.useCallback(()=>{he.current=[];const We=fe.current;fe.current=[];for(const st of We)pe(ao(st));ue.current=!0},[pe]),qe=ae.useCallback(()=>{ue.current=!1;const We=he.current;if(he.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=ky.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:wf,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:yf}},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:ce,pauseStream:Ve,resumeStream:me,onFrameProcessed:(We,st)=>{if(st&&(fe.current.push(new Float32Array(st)),fe.current.length>My&&fe.current.shift(),ue.current)){const ze=he.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?.()},Ay)},onVADMisfire:()=>{ne.current&&(clearTimeout(ne.current),ne.current=null),j(!1),qe(),v?.()}}),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]),Gt=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?ce():null,[R,ce]),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:Gt,prepare:xt,start:Ke,stop:at,pause:Je.pause,userSpeaking:Je.userSpeaking}}function Py(d,r,s=[]){const{events:a}=Fs();ae.useEffect(()=>a.on(d,r),[d,r,a,...s])}function Dy({connect:d=!0,session:r,onError:s,onInitialized:a,clientTools:f,children:v}){const{initializeSession:C,joinDesktopSession:R,disconnect:S,registerClientTools:N}=lf(),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 ue=!1;return(async()=>{try{const pe=fe.current;if(r?.mode==="join_desktop"){const Ve=await se.current({uniqueId:r.uniqueId});ue||(pe&&ne.current(pe),W.current?.(Ve));return}const ce=await j.current({apiKey:r?.apiKey,agentId:r?.agentId,language:r?.language||"en",config:r?.config,promptOverrides:r?.promptOverrides,clientTools:pe});ue||W.current?.(ce)}catch(pe){ue||(te.current=!0,Y.current?.(pe))}})(),()=>{ue=!0,!te.current&&(J.current(),z.current=!1)}},[d,r]),Jt.jsx(Jt.Fragment,{children:v})}function zy({children:d,wsUrl:r,restUrl:s,session:a,connect:f=!0,enableAudio:v=!0,pcmOptions:C,debug:R=!1,withCredentials:S=!1,onError:N,onInitialized:z,clientTools:te}){return Jt.jsx(of,{wsUrl:r,restUrl:s,enableAudio:v,pcmOptions:C,debug:R,withCredentials:S,children:Jt.jsx(Dy,{connect:f,session:a,onError:N,onInitialized:z,clientTools:te,children:d})})}var lo={exports:{}},Lp;function Ly(){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,v)=>(v>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 v=8;v<a.length;v+=2)switch(a[v]){case"raddr":f.relatedAddress=a[v+1];break;case"rport":f.relatedPort=parseInt(a[v+1],10);break;case"tcptype":f.tcpType=a[v+1];break;case"ufrag":f.ufrag=a[v+1],f.usernameFragment=a[v+1];break;default:f[a[v]]===void 0&&(f[a[v]]=a[v+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 v=s.type;return a.push("typ"),a.push(v),v!=="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
|
|
@@ -2866,28 +2866,28 @@ a=ice-pwd:`+s.password+`\r
|
|
|
2866
2866
|
o=`+(f||"thisisadapterortc")+" "+v+" "+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 v=0;v<f.length;v++)switch(f[v]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return f[v].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=Ly(),
|
|
2869
|
+
`},r.getDirection=function(s,a){const f=r.splitLines(s);for(let v=0;v<f.length;v++)switch(f[v]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return f[v].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=Ly(),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:()=>tm,g$:()=>Ef,Lt:()=>Sf,Q9:()=>Tf,qf:()=>So,hV:()=>am,z$:()=>Aw,J0:()=>Eo,De:()=>sw,$C:()=>Us,al:()=>Of,_W:()=>Pf,Gv:()=>Kf,m:()=>Qf,tz:()=>Mf,Nu:()=>nm,zg:()=>um,vp:()=>em,vU:()=>X,wF:()=>Gf,rv:()=>rm,Nh:()=>sm,ss:()=>lm,qW:()=>Xf,QL:()=>jf,cf:()=>cm,eM:()=>Vf,Yd:()=>T,Tk:()=>Se,iM:()=>vf,qy:()=>Qr,ce:()=>jy,sK:()=>ge,Ok:()=>dt,q5:()=>im,g:()=>Rw,xl:()=>Uf,I:()=>Ff,bx:()=>To,dD:()=>Jf,Ib:()=>pi,Az:()=>St,Iw:()=>Or,qY:()=>bo,db:()=>bf,mR:()=>ci,Tn:()=>_o,rV:()=>qf,gh:()=>zf,Mi:()=>Lf,j:()=>Bf,YB:()=>Nf,Yt:()=>Hf,i5:()=>Wf,x_:()=>Kr,Am:()=>$o,eR:()=>$f,r8:()=>Df,u3:()=>dm,vd:()=>Cf,iV:()=>Rf,jZ:()=>kf,SW:()=>If,ZH:()=>Af,Ni:()=>hm,lh:()=>xf,ZP:()=>Zf,bq:()=>_f,$f:()=>pm,eu:()=>Yf,Ax:()=>Jy,Mc:()=>Yy});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 By extends
|
|
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 By extends Qr{constructor(){super(),this.type=Tr.LIST_STREAMERS}}class Ny extends Qr{constructor(r){super(),this.type=Tr.SUBSCRIBE,this.streamerId=r}}class Uy extends Qr{constructor(){super(),this.type=Tr.UNSUBSCRIBE}}class Fy extends Qr{constructor(r){super(),this.type=Tr.PONG,this.time=r}}class Vy 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 Gy 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 qy extends Qr{constructor(){super(),this.type=Tr.DATACHANNELREQUEST}}class Wy extends Qr{constructor(){super(),this.type=Tr.SFURECVDATACHANNELREADY}}class Hy{constructor(r){this.type=Tr.ICE_CANDIDATE,this.candidate=r}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2878
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 vf{}class jy extends vf{}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 Fy(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 _f{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 By;this.webSocket.send(r.payload())}sendSubscribe(r){const s=new Ny(r);this.webSocket.send(s.payload())}sendUnsubscribe(){const r=new Uy;this.webSocket.send(r.payload())}sendWebRtcOffer(r,s){const a=new Vy(r,s);this.webSocket.send(a.payload())}sendWebRtcAnswer(r,s){const a=new Gy(r,s);this.webSocket.send(a.payload())}sendWebRtcDatachannelRequest(){const r=new qy;this.webSocket.send(r.payload())}sendSFURecvDataChannelReady(){const r=new Wy;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 Hy(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 Ky{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 Qy{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 v=this.rootDiv.clientWidth/this.rootDiv.clientHeight,C=this.freezeFrameWidth/this.freezeFrameHeight;v<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 Xy{constructor(r){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Qy(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,v=(()=>{})){this.onChange=v,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,v,C=(()=>{})){super(r,s,a,f,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const S=this.getUrlParamFlag();this.flag=S}else this.flag=f;this.useUrlParams=v}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,v,C,R,S=(()=>{})){super(r,s,a,C,S),this._min=f,this._max=v;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 bf extends pi{constructor(r,s,a,f,v,C=(()=>{})){super(r,s,a,f,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const S=this.getUrlParamText();this.text=S}else this.text=f;this.useUrlParams=v}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,v,C,R=(()=>{})){super(r,s,a,f,R),this.options=v;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 Sf extends Event{constructor(r){super("afkWarningActivate"),this.data=r}}class So extends Event{constructor(r){super("afkWarningUpdate"),this.data=r}}class Tf extends Event{constructor(){super("afkWarningDeactivate")}}class Ef extends Event{constructor(){super("afkTimedOut")}}class $f extends Event{constructor(r){super("videoEncoderAvgQP"),this.data=r}}class xf extends Event{constructor(){super("webRtcSdp")}}class Cf extends Event{constructor(){super("webRtcAutoConnect")}}class kf extends Event{constructor(){super("webRtcConnecting")}}class Rf extends Event{constructor(){super("webRtcConnected")}}class Af extends Event{constructor(){super("webRtcFailed")}}class If extends Event{constructor(r){super("webRtcDisconnected"),this.data=r}}class Mf extends Event{constructor(r){super("dataChannelOpen"),this.data=r}}class Of extends Event{constructor(r){super("dataChannelClose"),this.data=r}}class Pf extends Event{constructor(r){super("dataChannelError"),this.data=r}}class Df extends Event{constructor(){super("videoInitialized")}}class zf extends Event{constructor(){super("streamLoading")}}class Lf extends Event{constructor(){super("streamConnect")}}class Bf extends Event{constructor(){super("streamDisconnect")}}class Nf extends Event{constructor(){super("streamReconnect")}}class Uf extends Event{constructor(r){super("playStreamError"),this.data=r}}class Ff extends Event{constructor(){super("playStream")}}class To extends Event{constructor(r){super("playStreamRejected"),this.data=r}}class Vf extends Event{constructor(r){super("loadFreezeFrame"),this.data=r}}class Gf extends Event{constructor(){super("hideFreezeFrame")}}class qf extends Event{constructor(r){super("statsReceived"),this.data=r}}class Wf extends Event{constructor(r){super("streamerListMessage"),this.data=r}}class Hf extends Event{constructor(r){super("StreamerIDChangedMessage"),this.data=r}}class jf extends Event{constructor(r){super("latencyTestResult"),this.data=r}}class Kf extends Event{constructor(r){super("dataChannelLatencyTestResponse"),this.data=r}}class Qf extends Event{constructor(r){super("dataChannelLatencyTestResult"),this.data=r}}class Xf extends Event{constructor(r){super("initialSettings"),this.data=r}}class ci extends Event{constructor(r){super("settingsChanged"),this.data=r}}class Yy extends Event{constructor(){super("xrSessionStarted")}}class Jy extends Event{constructor(){super("xrSessionEnded")}}class Yf extends Event{constructor(r){super("xrFrame"),this.data=r}}class Jf extends Event{constructor(r){super("playerCount"),this.data=r}}class Zf extends Event{constructor(){super("webRtcTCPRelayDetected")}}class em 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 Zy=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 ew=d=>Object.getOwnPropertyNames(me).some((r=>me[r]===d));class jr{}jr.SignallingServerUrl="ss";const tw=d=>Object.getOwnPropertyNames(jr).some((r=>jr[r]===d));class dt{}dt.PreferredCodec="PreferredCodec",dt.StreamerId="StreamerId";const rw=d=>Object.getOwnPropertyNames(dt).some((r=>dt[r]===d));class sw{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(jr.SignallingServerUrl,new bf(jr.SignallingServerUrl,"Signalling url","Url of the signalling server",s&&s.hasOwnProperty(jr.SignallingServerUrl)?s[jr.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((v=>{const C=v.mimeType.split("/")[1]+" "+(v.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 Pr(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 Pr(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 Pr(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 Pr(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 Pr(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 Pr(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 Pr(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 Pr(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 Pr(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))Zy(s)?this.setFlagEnabled(s,r[s]):ew(s)?this.setNumericSetting(s,r[s]):tw(s)?this.setTextSetting(s,r[s]):rw(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 ci({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 ci({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 ci({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 ci({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 tm{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 Tf))}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 Sf({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 Ef),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 rm{}class sm{}class nm{}class Eo{}class im{}class nw{}class iw{}class am{constructor(){this.inboundVideoStats=new sm,this.inboundAudioStats=new rm,this.DataChannelStats=new nm,this.outBoundVideoStats=new im,this.sessionStats=new nw,this.streamStats=new iw,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 v=s===null?"Not sent yet":s?"true":"false";this.sessionStats.controlsStreamInput=v,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 om{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 dn,Se,co=function(d,r,s,a){return new(s||(s=Promise))((function(f,v){function C(N){try{S(a.next(N))}catch(z){v(z)}}function R(N){try{S(a.throw(N))}catch(z){v(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 aw{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 am,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 v=s.isFlagEnabled(X.UseMic);!v||a||f||(v=!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(v).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,v),(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",v=location.protocol==="https:";let C=s.isFlagEnabled(X.UseMic);!C||f||v||(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 v of a)if(f.includes(v))s.push(v);else{const C=v.split(" ")[0];for(const R of f)if(R.includes(C)){s.push(R);break}}return s}setupTransceiversAsync(r){var s,a,f,v,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=(v=this.peerConnection)===null||v===void 0?void 0:v.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(" "),
|
|
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 By;this.webSocket.send(r.payload())}sendSubscribe(r){const s=new Ny(r);this.webSocket.send(s.payload())}sendUnsubscribe(){const r=new Uy;this.webSocket.send(r.payload())}sendWebRtcOffer(r,s){const a=new Vy(r,s);this.webSocket.send(a.payload())}sendWebRtcAnswer(r,s){const a=new Gy(r,s);this.webSocket.send(a.payload())}sendWebRtcDatachannelRequest(){const r=new qy;this.webSocket.send(r.payload())}sendSFURecvDataChannelReady(){const r=new Wy;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 Hy(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 Ky{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 Qy{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 v=this.rootDiv.clientWidth/this.rootDiv.clientHeight,C=this.freezeFrameWidth/this.freezeFrameHeight;v<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 Xy{constructor(r){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Qy(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,v=(()=>{})){this.onChange=v,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,v,C=(()=>{})){super(r,s,a,f,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const S=this.getUrlParamFlag();this.flag=S}else this.flag=f;this.useUrlParams=v}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 Or extends pi{constructor(r,s,a,f,v,C,R,S=(()=>{})){super(r,s,a,C,S),this._min=f,this._max=v;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 bf extends pi{constructor(r,s,a,f,v,C=(()=>{})){super(r,s,a,f,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const S=this.getUrlParamText();this.text=S}else this.text=f;this.useUrlParams=v}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,v,C,R=(()=>{})){super(r,s,a,f,R),this.options=v;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 Sf extends Event{constructor(r){super("afkWarningActivate"),this.data=r}}class So extends Event{constructor(r){super("afkWarningUpdate"),this.data=r}}class Tf extends Event{constructor(){super("afkWarningDeactivate")}}class Ef extends Event{constructor(){super("afkTimedOut")}}class $f extends Event{constructor(r){super("videoEncoderAvgQP"),this.data=r}}class xf extends Event{constructor(){super("webRtcSdp")}}class Cf extends Event{constructor(){super("webRtcAutoConnect")}}class kf extends Event{constructor(){super("webRtcConnecting")}}class Rf extends Event{constructor(){super("webRtcConnected")}}class Af extends Event{constructor(){super("webRtcFailed")}}class If extends Event{constructor(r){super("webRtcDisconnected"),this.data=r}}class Mf extends Event{constructor(r){super("dataChannelOpen"),this.data=r}}class Of extends Event{constructor(r){super("dataChannelClose"),this.data=r}}class Pf extends Event{constructor(r){super("dataChannelError"),this.data=r}}class Df extends Event{constructor(){super("videoInitialized")}}class zf extends Event{constructor(){super("streamLoading")}}class Lf extends Event{constructor(){super("streamConnect")}}class Bf extends Event{constructor(){super("streamDisconnect")}}class Nf extends Event{constructor(){super("streamReconnect")}}class Uf extends Event{constructor(r){super("playStreamError"),this.data=r}}class Ff extends Event{constructor(){super("playStream")}}class To extends Event{constructor(r){super("playStreamRejected"),this.data=r}}class Vf extends Event{constructor(r){super("loadFreezeFrame"),this.data=r}}class Gf extends Event{constructor(){super("hideFreezeFrame")}}class qf extends Event{constructor(r){super("statsReceived"),this.data=r}}class Wf extends Event{constructor(r){super("streamerListMessage"),this.data=r}}class Hf extends Event{constructor(r){super("StreamerIDChangedMessage"),this.data=r}}class jf extends Event{constructor(r){super("latencyTestResult"),this.data=r}}class Kf extends Event{constructor(r){super("dataChannelLatencyTestResponse"),this.data=r}}class Qf extends Event{constructor(r){super("dataChannelLatencyTestResult"),this.data=r}}class Xf extends Event{constructor(r){super("initialSettings"),this.data=r}}class ci extends Event{constructor(r){super("settingsChanged"),this.data=r}}class Yy extends Event{constructor(){super("xrSessionStarted")}}class Jy extends Event{constructor(){super("xrSessionEnded")}}class Yf extends Event{constructor(r){super("xrFrame"),this.data=r}}class Jf extends Event{constructor(r){super("playerCount"),this.data=r}}class Zf extends Event{constructor(){super("webRtcTCPRelayDetected")}}class em 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 Zy=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 ew=d=>Object.getOwnPropertyNames(ge).some((r=>ge[r]===d));class Kr{}Kr.SignallingServerUrl="ss";const tw=d=>Object.getOwnPropertyNames(Kr).some((r=>Kr[r]===d));class dt{}dt.PreferredCodec="PreferredCodec",dt.StreamerId="StreamerId";const rw=d=>Object.getOwnPropertyNames(dt).some((r=>dt[r]===d));class sw{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 bf(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((v=>{const C=v.mimeType.split("/")[1]+" "+(v.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 Or(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 Or(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 Or(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 Or(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 Or(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 Or(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 Or(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 Or(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 Or(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))Zy(s)?this.setFlagEnabled(s,r[s]):ew(s)?this.setNumericSetting(s,r[s]):tw(s)?this.setTextSetting(s,r[s]):rw(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 ci({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 ci({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 ci({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 ci({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 tm{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 Tf))}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 Sf({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 Ef),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 rm{}class sm{}class nm{}class Eo{}class im{}class nw{}class iw{}class am{constructor(){this.inboundVideoStats=new sm,this.inboundAudioStats=new rm,this.DataChannelStats=new nm,this.outBoundVideoStats=new im,this.sessionStats=new nw,this.streamStats=new iw,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 v=s===null?"Not sent yet":s?"true":"false";this.sessionStats.controlsStreamInput=v,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 om{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,v){function C(N){try{S(a.next(N))}catch(z){v(z)}}function R(N){try{S(a.throw(N))}catch(z){v(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 aw{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 am,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 v=s.isFlagEnabled(X.UseMic);!v||a||f||(v=!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(v).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,v),(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",v=location.protocol==="https:";let C=s.isFlagEnabled(X.UseMic);!C||f||v||(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 v of a)if(f.includes(v))s.push(v);else{const C=v.split(" ")[0];for(const R of f)if(R.includes(C)){s.push(R);break}}return s}setupTransceiversAsync(r){var s,a,f,v,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=(v=this.peerConnection)===null||v===void 0?void 0:v.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]:""},ue=[fe];RTCRtpReceiver.getCapabilities("video").codecs.forEach((he=>{(he.mimeType!=fe.mimeType||he?.sdpFmtpLine!=fe?.sdpFmtpLine)&&ue.push(he)}));for(const he of ue)he?.sdpFmtpLine!==void 0&&he.sdpFmtpLine!==""||delete he.sdpFmtpLine;W.setCodecPreferences(ue)}}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(om.canTransceiverReceiveAudio(fe))for(const ue of ne.getTracks())ue.kind&&ue.kind=="audio"&&(fe.sender.replaceTrack(ue),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:v}=(0,Up.parseRtpParameters)(f),C=/(VP\d|H26\d|AV1).*/;v.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 lm{constructor(){this.PixelStreamingSettings=new ow,this.EncoderSettings=new um,this.WebRTCSettings=new dm}ueCompatible(){this.WebRTCSettings.MaxFPS!=null&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class ow{}class um{}class dm{}class cm{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,v=Math.round(16384*s.chunks/f);T.Log(T.GetStackTrace(),`Average transfer bitrate: ${v}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 lw{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 Ft{}Ft.primaryButton=1,Ft.secondaryButton=2,Ft.auxiliaryButton=4,Ft.fourthButton=8,Ft.fifthButton=16;class pn{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(r){this.unregisterCallbacks.push(r)}unregisterAll(){for(const r of this.unregisterCallbacks)r();this.unregisterCallbacks=[]}}class uw{constructor(r,s,a){this.touchEventListenerTracker=new pn,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a;const f=R=>this.onTouchStart(R),v=R=>this.onTouchEnd(R),C=R=>this.onTouchMove(R);document.addEventListener("touchstart",f,{passive:!1}),document.addEventListener("touchend",v,{passive:!1}),document.addEventListener("touchmove",C,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchend",v))),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 dw(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 v=this.coordinateConverter.normalizeAndQuantizeUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([zt.mainButton,v.x,v.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 v=r.changedTouches[f];if(v.identifier===this.fakeTouchFinger.id){const C=v.clientX-this.videoElementParentClientRect.left,R=v.clientY-this.videoElementParentClientRect.top,S=this.coordinateConverter.normalizeAndQuantizeUnsigned(C,R);a.get("MouseUp")([zt.mainButton,S.x,S.y]);const N=new MouseEvent("mouseleave",v);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 v=f.clientX-this.videoElementParentClientRect.left,C=f.clientY-this.videoElementParentClientRect.top,R=this.coordinateConverter.normalizeAndQuantizeUnsigned(v,C),S=this.coordinateConverter.normalizeAndQuantizeSigned(v-this.fakeTouchFinger.x,C-this.fakeTouchFinger.y);s.get("MouseMove")([R.x,R.y,S.x,S.y]),this.fakeTouchFinger.x=v,this.fakeTouchFinger.y=C;break}}r.preventDefault()}}class dw{constructor(r,s,a){this.id=r,this.x=s,this.y=a}}class Vt{}Vt.backSpace=8,Vt.shift=16,Vt.control=17,Vt.alt=18,Vt.rightShift=253,Vt.rightControl=254,Vt.rightAlt=255;class cw{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=v=>this.handleOnCompositionEnd(v),s=v=>this.handleOnKeyDown(v),a=v=>this.handleOnKeyUp(v),f=v=>this.handleOnKeyPress(v);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===Vt.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:Vt.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===Vt.shift&&r.code==="ShiftRight"?Vt.rightShift:r.keyCode===Vt.control&&r.code==="ControlRight"?Vt.rightControl:r.keyCode===Vt.alt&&r.code==="AltRight"?Vt.rightAlt:r.keyCode}isKeyCodeBrowserKey(r){return r>=112&&r<=123||r===9}}class hw{constructor(r,s,a){this.x=0,this.y=0,this.updateMouseMovePositionEvent=v=>{this.updateMouseMovePosition(v)},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),v=[];f.forEach((C=>{})),v.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 v=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(r.movementX,r.movementY);s.get("MouseMove")([this.coord.x,this.coord.y,v.x,v.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 pw{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 fw{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 hw(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 v=N=>a.handleMouseDown(N),C=N=>a.handleMouseUp(N),R=N=>a.handleMouseWheel(N),S=N=>a.handleMouseDouble(N);s.addEventListener("mousedown",v),s.addEventListener("mouseup",C),s.addEventListener("wheel",R),s.addEventListener("dblclick",S),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousedown",v))),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 pw(r),f=z=>a.updateMouseMovePosition(z),v=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",v),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",v))),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&Ft.primaryButton&&this.sendMouseUp(zt.mainButton,f.x,f.y),r&Ft.secondaryButton&&this.sendMouseUp(zt.secondaryButton,f.x,f.y),r&Ft.auxiliaryButton&&this.sendMouseUp(zt.auxiliaryButton,f.x,f.y),r&Ft.fourthButton&&this.sendMouseUp(zt.fourthButton,f.x,f.y),r&Ft.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&Ft.primaryButton&&this.sendMouseDown(zt.mainButton,f.x,f.y),r&Ft.secondaryButton&&this.sendMouseDown(zt.secondaryButton,f.x,f.y),r&Ft.auxiliaryButton&&this.sendMouseDown(zt.auxiliaryButton,f.x,f.y),r&Ft.fourthButton&&this.sendMouseDown(zt.fourthButton,f.x,f.y),r&Ft.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 mw{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),v=S=>this.onTouchEnd(S),C=S=>this.onTouchMove(S);this.videoElementParent.addEventListener("touchstart",f),this.videoElementParent.addEventListener("touchend",v),this.videoElementParent.addEventListener("touchmove",C),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchend",v))),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 v=0;v<s.length;v++){const R=s[v],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 gw{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=v=>this.gamePadConnectHandler(v),f=v=>this.gamePadDisconnectHandler(v);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=v=>this.gamePadConnectHandler(v),f=v=>this.gamePadDisconnectHandler(v);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 v=0;v<s.currentState.buttons.length;v++){const C=s.currentState.buttons[v],R=s.prevState.buttons[v];C.pressed?v==dn.LeftTrigger?r.get("GamepadAnalog")([a,5,C.value]):v==dn.RightTrigger?r.get("GamepadAnalog")([a,6,C.value]):r.get("GamepadButtonPressed")([a,v,R.pressed?1:0]):!C.pressed&&R.pressed&&(v==dn.LeftTrigger?r.get("GamepadAnalog")([a,5,0]):v==dn.RightTrigger?r.get("GamepadAnalog")([a,6,0]):r.get("GamepadButtonReleased")([a,v,0]))}for(let v=0;v<f.axes.length;v+=2){const C=parseFloat(f.axes[v].toFixed(4)),R=-parseFloat(f.axes[v+1].toFixed(4));r.get("GamepadAnalog")([a,v+1,C]),r.get("GamepadAnalog")([a,v+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"})(dn||(dn={}));class yw{constructor(r,s,a){this.activeKeys=new ww,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a}registerKeyBoard(r){T.Log(T.GetStackTrace(),"Register Keyboard Events",7);const s=new cw(this.toStreamerMessagesProvider,r,this.activeKeys);return s.registerKeyBoardEvents(),s}registerMouse(r){T.Log(T.GetStackTrace(),"Register Mouse Events",7);const s=new fw(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 uw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return a.setVideoElementParentClientRect(s),a}return new mw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return T.Log(T.GetStackTrace(),"Register Game Pad",7),new gw(this.toStreamerMessagesProvider)}}class ww{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class vw{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 _w{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 bw{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 Sw{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 v=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*v.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 Tw{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 Ew{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 $w{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,v=(this.videoElement.videoHeight||1)/a;f>v?(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio > videoAspectRatio",6),this.ratio=f/v,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=v/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 Pi(!1,65535,65535):new Pi(!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 Pi(!1,65535,65535):new Pi(!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 Pi{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 hm{constructor(r,s){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=r,this.pixelStreaming=s,this.responseController=new bw,this.file=new lw,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new tm(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new Xy(this.pixelStreaming.videoElementParent),this.videoPlayer=new vw(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(a,f)=>{const v={"Resolution.Width":a,"Resolution.Height":f};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(v)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new Ky(this.videoPlayer),this.coordinateConverter=new $w(this.videoPlayer),this.sendrecvDataChannelController=new Np,this.recvDataChannelController=new Np,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new Ew(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new _w,this.webSocketController=new _f,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,v=this.disconnectMessage?this.disconnectMessage:a.detail.reason;this.pixelStreaming._onDisconnect(v,!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 Sw(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new Tw(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new yw(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(jr.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((v=>{const C=a[v];switch(f){case Se.ToStreamer:if(!Object.prototype.hasOwnProperty.call(C,"id"))return void T.Error(T.GetStackTrace(),`ToStreamer->${v} 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,v=Math.round(16384*s.chunks/f);T.Log(T.GetStackTrace(),`Average transfer bitrate: ${v}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 lw{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 Ft{}Ft.primaryButton=1,Ft.secondaryButton=2,Ft.auxiliaryButton=4,Ft.fourthButton=8,Ft.fifthButton=16;class fn{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(r){this.unregisterCallbacks.push(r)}unregisterAll(){for(const r of this.unregisterCallbacks)r();this.unregisterCallbacks=[]}}class uw{constructor(r,s,a){this.touchEventListenerTracker=new fn,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a;const f=R=>this.onTouchStart(R),v=R=>this.onTouchEnd(R),C=R=>this.onTouchMove(R);document.addEventListener("touchstart",f,{passive:!1}),document.addEventListener("touchend",v,{passive:!1}),document.addEventListener("touchmove",C,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchend",v))),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 dw(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 v=this.coordinateConverter.normalizeAndQuantizeUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([zt.mainButton,v.x,v.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 v=r.changedTouches[f];if(v.identifier===this.fakeTouchFinger.id){const C=v.clientX-this.videoElementParentClientRect.left,R=v.clientY-this.videoElementParentClientRect.top,S=this.coordinateConverter.normalizeAndQuantizeUnsigned(C,R);a.get("MouseUp")([zt.mainButton,S.x,S.y]);const N=new MouseEvent("mouseleave",v);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 v=f.clientX-this.videoElementParentClientRect.left,C=f.clientY-this.videoElementParentClientRect.top,R=this.coordinateConverter.normalizeAndQuantizeUnsigned(v,C),S=this.coordinateConverter.normalizeAndQuantizeSigned(v-this.fakeTouchFinger.x,C-this.fakeTouchFinger.y);s.get("MouseMove")([R.x,R.y,S.x,S.y]),this.fakeTouchFinger.x=v,this.fakeTouchFinger.y=C;break}}r.preventDefault()}}class dw{constructor(r,s,a){this.id=r,this.x=s,this.y=a}}class Vt{}Vt.backSpace=8,Vt.shift=16,Vt.control=17,Vt.alt=18,Vt.rightShift=253,Vt.rightControl=254,Vt.rightAlt=255;class cw{constructor(r,s,a){this.keyboardEventListenerTracker=new fn,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=v=>this.handleOnCompositionEnd(v),s=v=>this.handleOnKeyDown(v),a=v=>this.handleOnKeyUp(v),f=v=>this.handleOnKeyPress(v);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===Vt.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:Vt.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===Vt.shift&&r.code==="ShiftRight"?Vt.rightShift:r.keyCode===Vt.control&&r.code==="ControlRight"?Vt.rightControl:r.keyCode===Vt.alt&&r.code==="AltRight"?Vt.rightAlt:r.keyCode}isKeyCodeBrowserKey(r){return r>=112&&r<=123||r===9}}class hw{constructor(r,s,a){this.x=0,this.y=0,this.updateMouseMovePositionEvent=v=>{this.updateMouseMovePosition(v)},this.mouseEventListenerTracker=new fn,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),v=[];f.forEach((C=>{})),v.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 v=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(r.movementX,r.movementY);s.get("MouseMove")([this.coord.x,this.coord.y,v.x,v.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 pw{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 fw{constructor(r,s,a,f){this.mouseEventListenerTracker=new fn,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 hw(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 v=N=>a.handleMouseDown(N),C=N=>a.handleMouseUp(N),R=N=>a.handleMouseWheel(N),S=N=>a.handleMouseDouble(N);s.addEventListener("mousedown",v),s.addEventListener("mouseup",C),s.addEventListener("wheel",R),s.addEventListener("dblclick",S),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousedown",v))),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 pw(r),f=z=>a.updateMouseMovePosition(z),v=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",v),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",v))),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&Ft.primaryButton&&this.sendMouseUp(zt.mainButton,f.x,f.y),r&Ft.secondaryButton&&this.sendMouseUp(zt.secondaryButton,f.x,f.y),r&Ft.auxiliaryButton&&this.sendMouseUp(zt.auxiliaryButton,f.x,f.y),r&Ft.fourthButton&&this.sendMouseUp(zt.fourthButton,f.x,f.y),r&Ft.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&Ft.primaryButton&&this.sendMouseDown(zt.mainButton,f.x,f.y),r&Ft.secondaryButton&&this.sendMouseDown(zt.secondaryButton,f.x,f.y),r&Ft.auxiliaryButton&&this.sendMouseDown(zt.auxiliaryButton,f.x,f.y),r&Ft.fourthButton&&this.sendMouseDown(zt.fourthButton,f.x,f.y),r&Ft.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 mw{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 fn,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a,this.videoElementParent=s.getVideoElement();const f=S=>this.onTouchStart(S),v=S=>this.onTouchEnd(S),C=S=>this.onTouchMove(S);this.videoElementParent.addEventListener("touchstart",f),this.videoElementParent.addEventListener("touchend",v),this.videoElementParent.addEventListener("touchmove",C),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchend",v))),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 v=0;v<s.length;v++){const R=s[v],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 gw{constructor(r){this.gamePadEventListenerTracker=new fn,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=v=>this.gamePadConnectHandler(v),f=v=>this.gamePadDisconnectHandler(v);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=v=>this.gamePadConnectHandler(v),f=v=>this.gamePadDisconnectHandler(v);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 v=0;v<s.currentState.buttons.length;v++){const C=s.currentState.buttons[v],R=s.prevState.buttons[v];C.pressed?v==cn.LeftTrigger?r.get("GamepadAnalog")([a,5,C.value]):v==cn.RightTrigger?r.get("GamepadAnalog")([a,6,C.value]):r.get("GamepadButtonPressed")([a,v,R.pressed?1:0]):!C.pressed&&R.pressed&&(v==cn.LeftTrigger?r.get("GamepadAnalog")([a,5,0]):v==cn.RightTrigger?r.get("GamepadAnalog")([a,6,0]):r.get("GamepadButtonReleased")([a,v,0]))}for(let v=0;v<f.axes.length;v+=2){const C=parseFloat(f.axes[v].toFixed(4)),R=-parseFloat(f.axes[v+1].toFixed(4));r.get("GamepadAnalog")([a,v+1,C]),r.get("GamepadAnalog")([a,v+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 yw{constructor(r,s,a){this.activeKeys=new ww,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a}registerKeyBoard(r){T.Log(T.GetStackTrace(),"Register Keyboard Events",7);const s=new cw(this.toStreamerMessagesProvider,r,this.activeKeys);return s.registerKeyBoardEvents(),s}registerMouse(r){T.Log(T.GetStackTrace(),"Register Mouse Events",7);const s=new fw(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 uw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return a.setVideoElementParentClientRect(s),a}return new mw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return T.Log(T.GetStackTrace(),"Register Game Pad",7),new gw(this.toStreamerMessagesProvider)}}class ww{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class vw{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 _w{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 bw{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 Sw{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 v=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*v.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 Tw{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 Ew{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 $w{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,v=(this.videoElement.videoHeight||1)/a;f>v?(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio > videoAspectRatio",6),this.ratio=f/v,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=v/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 Pi(!1,65535,65535):new Pi(!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 Pi(!1,65535,65535):new Pi(!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 Pi{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 hm{constructor(r,s){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=r,this.pixelStreaming=s,this.responseController=new bw,this.file=new lw,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new tm(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new Xy(this.pixelStreaming.videoElementParent),this.videoPlayer=new vw(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(a,f)=>{const v={"Resolution.Width":a,"Resolution.Height":f};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(v)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new Ky(this.videoPlayer),this.coordinateConverter=new $w(this.videoPlayer),this.sendrecvDataChannelController=new Np,this.recvDataChannelController=new Np,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new Ew(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new _w,this.webSocketController=new _f,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,v=this.disconnectMessage?this.disconnectMessage:a.detail.reason;this.pixelStreaming._onDisconnect(v,!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 Sw(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new Tw(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new yw(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((v=>{const C=a[v];switch(f){case Se.ToStreamer:if(!Object.prototype.hasOwnProperty.call(C,"id"))return void T.Error(T.GetStackTrace(),`ToStreamer->${v} protocol definition was malformed as it didn't contain at least an id
|
|
2885
2885
|
|
|
2886
2886
|
Definition was: ${JSON.stringify(C,null,2)}`);if(v==="UIInteraction"||v==="Command"||v==="LatencyTest")return;this.streamMessageController.toStreamerHandlers.get(v)?this.streamMessageController.toStreamerMessages.set(v,C):T.Error(T.GetStackTrace(),`There was no registered handler for "${v}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${v}", myHandler)`);break;case Se.FromStreamer:if(!Object.prototype.hasOwnProperty.call(C,"id"))return void T.Error(T.GetStackTrace(),`FromStreamer->${v} 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(v)?this.streamMessageController.fromStreamerMessages.set(C.id,v):T.Error(T.GetStackTrace(),`There was no registered handler for "${C}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${v}", 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 Vf({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 Gf),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 Uf({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 Ff),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 aw(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 v=null;const C=this.config.isFlagEnabled(X.WaitForStreamer),R=this.config.getNumericSettingValue(me.MaxReconnectAttempts),S=this.config.getNumericSettingValue(me.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)?v=s:s&&C||r.ids.length!=1||(v=r.ids[0]),v?(this.isReconnecting=!1,this.reconnectAttempt=0,this.config.setOptionSettingValue(dt.StreamerId,v)):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 Wf({messageStreamerList:r,autoSelectedStreamerId:v,wantedStreamerId:s}))}handleStreamerIDChangedMessage(r){const s=r.newID;var a=this.config.getSettingOption(dt.StreamerId),f=a.onChange;a.onChange=()=>{};for(var v=a.options,C=0;C<v.length;++C)if(v[C]==this.subscribedStream){v[C]=s;break}a.options=v,a.selected=s,a.onChange=f,this.subscribedStream=r.newID,this.pixelStreaming.dispatchEvent(new Hf({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=v=>this.handleOnMessage(v)}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(v)?this.streamMessageController.fromStreamerMessages.set(C.id,v):T.Error(T.GetStackTrace(),`There was no registered handler for "${C}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${v}", 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 Vf({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 Gf),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 Uf({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 Ff),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 aw(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 v=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)?v=s:s&&C||r.ids.length!=1||(v=r.ids[0]),v?(this.isReconnecting=!1,this.reconnectAttempt=0,this.config.setOptionSettingValue(dt.StreamerId,v)):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 Wf({messageStreamerList:r,autoSelectedStreamerId:v,wantedStreamerId:s}))}handleStreamerIDChangedMessage(r){const s=r.newID;var a=this.config.getSettingOption(dt.StreamerId),f=a.onChange;a.onChange=()=>{};for(var v=a.options,C=0;C<v.length;++C)if(v[C]==this.subscribedStream){v[C]=s;break}a.options=v,a.selected=s,a.onChange=f,this.subscribedStream=r.newID,this.pixelStreaming.dispatchEvent(new Hf({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=v=>this.handleOnMessage(v)}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 cm;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 lm;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 cm;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 lm;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 Mf({label:s,event:a})),r.onClose=(s,a)=>this.pixelStreaming.dispatchEvent(new Of({label:s,event:a})),r.onError=(s,a)=>this.pixelStreaming.dispatchEvent(new Pf({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 v=0;r.profiles.includes("htc-vive")?v=1:r.profiles.includes("oculus-touch")&&(v=2),this.toStreamerMessagesProvider.toStreamerHandlers.get("XRSystem")([v]);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 pm{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
|
|
|
@@ -2914,5 +2914,5 @@ Msg: ${s}`;console.warn(a)}}T.verboseLogLevel=5,(function(d){d.LIST_STREAMERS="l
|
|
|
2914
2914
|
}
|
|
2915
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,v)=>{this.xrGamepadController.updateStatus(a,s,this.xrRefSpace)}),this),this.xrSession.requestAnimationFrame(((a,f)=>this.onXrFrame(a,f))),this.onFrame.dispatchEvent(new Yf({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 xw{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 Cw{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 kw{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 Cw(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 Rw{constructor(r,s){this.allowConsoleCommands=!1,this.config=r,s?.videoElementParent&&(this._videoElementParent=s.videoElementParent),this._eventEmitter=new em,this.configureSettings(),this.setWebRtcPlayerController(new hm(this.config,this)),this.onScreenKeyboardHelper=new xw(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(a,f)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(a,f),this._activateOnScreenKeyboard=a=>this.onScreenKeyboardHelper.showOnScreenKeyboard(a),this._webXrController=new pm(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 Lf),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Nf),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Bf),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,v;for(const C of(v=(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&&v!==void 0?v:[])om.canTransceiverSendAudio(C)&&(C.sender.track.enabled=!r)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new Cf)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new xf)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new zf)}_onDisconnect(r,s){this._eventEmitter.dispatchEvent(new If({eventString:r,allowClickToReconnect:s}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new kf)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Rf)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new Af)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new Df),this._videoStartTime=Date.now()}_onLatencyTestResult(r){this._eventEmitter.dispatchEvent(new jf({latencyTimings:r}))}_onDataChannelLatencyTestResponse(r){this._eventEmitter.dispatchEvent(new Kf({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 qf({aggregatedStats:r}))}_onVideoEncoderAvgQP(r){this._eventEmitter.dispatchEvent(new $f({avgQP:r}))}_onInitialSettings(r){var s;this._eventEmitter.dispatchEvent(new Xf({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 Jf({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 Zf),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 kw(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(s=>{this._eventEmitter.dispatchEvent(new Qf({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 Aw{}ve.Dz;ve.g$;ve.Lt;ve.Q9;ve.qf;ve.hV;ve.z$;ve.J0;var Iw=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 Mw=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 fm=({signallingUrl:d,autoConnect:r=!0,width:s,height:a,onConnecting:f,onLoading:v,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,ge]=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 Iw({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}}),he=new Mw(de,{videoElementParent:z.current});he.addEventListener("webRtcConnected",()=>{j.current=!0,J(!0),W(!1),ge(null),C?.()}),he.addEventListener("webRtcDisconnected",()=>{j.current=!1,J(!1),R?.()}),he.addEventListener("streamLoading",()=>{W(!0),v?.()}),he.addEventListener("playStreamError",()=>{ge("Failed to play stream"),W(!1),S?.("Failed to play stream")}),he.addEventListener("playStream",()=>{W(!1),j.current||(j.current=!0,J(!0),C?.())}),he.addEventListener("videoInitialized",()=>{W(!1)}),te.current=he}catch(de){process.env.NODE_ENV==="development"&&console.error("Failed to initialize Pixel Streaming:",de),ge("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,v,C,R,S]),ae.useEffect(()=>{if(te.current)try{const he=te.current._webRtcController?.videoPlayer;if(!he)return;let pe=!1;if(he.audioElement){const Ve=he.audioElement.srcObject;if(Ve){const fe=Ve.getAudioTracks();fe.length>0&&(fe.forEach(Ye=>{Ye.enabled=!N}),pe=!0)}}const ce=he.getVideoElement();if(ce&&ce.srcObject&&ce.srcObject instanceof MediaStream){const fe=ce.srcObject.getAudioTracks();fe.length>0&&(fe.forEach(Ye=>{Ye.enabled=!N}),pe=!0)}!pe&&ce&&(ce.muted=N)}catch(de){process.env.NODE_ENV==="development"&&console.error("Error controlling audio:",de)}},[N]),Yt.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:[Yt.jsx("div",{ref:z,className:"player-container",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"hidden",touchAction:"none"}}),Y&&Yt.jsxs("div",{className:"loading-overlay",children:[Yt.jsx("div",{className:"loading-spinner"}),Yt.jsx("div",{className:"loading-text",children:"Connecting to stream..."})]}),!se&&!Y&&ne&&Yt.jsx("div",{className:"connection-overlay",children:Yt.jsx("div",{className:"error-message",children:ne})})]})};function mm({className:d,style:r,autoConnect:s=!0,muted:a=!1,onConnected:f,onDisconnected:v,onError:C}){const{streamingUrl:R,setCloudStreamState:S}=uf();if(!R)return null;const N=()=>{S(Jt.CONNECTING)},z=()=>{S(Jt.LOADING)},te=()=>{S(Jt.CONNECTED),f?.()},j=()=>{S(Jt.DISCONNECTED),v?.()},se=J=>{S(Jt.ERROR,J),C?.(J)};return Yt.jsx("div",{className:d,style:r,children:Yt.jsx(fm,{signallingUrl:R,autoConnect:s,muted:a,onConnecting:N,onLoading:z,onConnected:te,onDisconnected:j,onError:se})})}const Ow=Object.freeze(Object.defineProperty({__proto__:null,RqmiiCloudAvatarPlayer:mm},Symbol.toStringTag,{value:"Module"}));exports.AGENT_TYPES=hi;exports.CLOUD_STREAM_STATE=Jt;exports.CONNECTION_STATE=pt;exports.DEFAULT_PCM_OPTIONS=qp;exports.EpicPixelStreamingPlayer=fm;exports.EventEmitter=nf;exports.RqmiiAgentProvider=of;exports.RqmiiAgentRoom=zy;exports.RqmiiCloudAvatarPlayer=mm;exports.RqmiiCloudAvatarPlayer$1=Ow;exports.SESSION_STATE=Bs;exports.SOCKET_EVENTS=Sr;exports.suppressNoisyLogs=Gp;exports.useRqmiiAgentContext=Us;exports.useRqmiiAvatar=uf;exports.useRqmiiConnection=lf;exports.useRqmiiEvents=Py;exports.useRqmiiMessages=yy;exports.useRqmiiVAD=Oy;exports.useRqmiiVoice=wy;
|
|
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 Cw(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 Rw{constructor(r,s){this.allowConsoleCommands=!1,this.config=r,s?.videoElementParent&&(this._videoElementParent=s.videoElementParent),this._eventEmitter=new em,this.configureSettings(),this.setWebRtcPlayerController(new hm(this.config,this)),this.onScreenKeyboardHelper=new xw(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(a,f)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(a,f),this._activateOnScreenKeyboard=a=>this.onScreenKeyboardHelper.showOnScreenKeyboard(a),this._webXrController=new pm(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 Lf),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Nf),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Bf),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,v;for(const C of(v=(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&&v!==void 0?v:[])om.canTransceiverSendAudio(C)&&(C.sender.track.enabled=!r)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new Cf)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new xf)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new zf)}_onDisconnect(r,s){this._eventEmitter.dispatchEvent(new If({eventString:r,allowClickToReconnect:s}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new kf)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Rf)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new Af)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new Df),this._videoStartTime=Date.now()}_onLatencyTestResult(r){this._eventEmitter.dispatchEvent(new jf({latencyTimings:r}))}_onDataChannelLatencyTestResponse(r){this._eventEmitter.dispatchEvent(new Kf({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 qf({aggregatedStats:r}))}_onVideoEncoderAvgQP(r){this._eventEmitter.dispatchEvent(new $f({avgQP:r}))}_onInitialSettings(r){var s;this._eventEmitter.dispatchEvent(new Xf({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 Jf({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 Zf),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 kw(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(s=>{this._eventEmitter.dispatchEvent(new Qf({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 Aw{}ve.Dz;ve.g$;ve.Lt;ve.Q9;ve.qf;ve.hV;ve.z$;ve.J0;var Iw=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 Mw=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 fm=({signallingUrl:d,autoConnect:r=!0,width:s,height:a,onConnecting:f,onLoading:v,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 ue=new Iw({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}}),he=new Mw(ue,{videoElementParent:z.current});he.addEventListener("webRtcConnected",()=>{j.current=!0,J(!0),W(!1),fe(null),C?.()}),he.addEventListener("webRtcDisconnected",()=>{j.current=!1,J(!1),R?.()}),he.addEventListener("streamLoading",()=>{W(!0),v?.()}),he.addEventListener("playStreamError",()=>{fe("Failed to play stream"),W(!1),S?.("Failed to play stream")}),he.addEventListener("playStream",()=>{W(!1),j.current||(j.current=!0,J(!0),C?.())}),he.addEventListener("videoInitialized",()=>{W(!1)}),te.current=he}catch(ue){process.env.NODE_ENV==="development"&&console.error("Failed to initialize Pixel Streaming:",ue),fe("Failed to initialize streaming: "+ue.message),W(!1),S?.(ue.message)}return()=>{if(te.current){try{const ue=te.current;ue._webSocketController&&ue._webSocketController.close(),te.current.disconnect()}catch(ue){process.env.NODE_ENV==="development"&&console.error("Error during cleanup:",ue)}te.current=null}}}},[d,r,f,v,C,R,S]),ae.useEffect(()=>{if(te.current)try{const he=te.current._webRtcController?.videoPlayer;if(!he)return;let pe=!1;if(he.audioElement){const Ve=he.audioElement.srcObject;if(Ve){const me=Ve.getAudioTracks();me.length>0&&(me.forEach(Ye=>{Ye.enabled=!N}),pe=!0)}}const ce=he.getVideoElement();if(ce&&ce.srcObject&&ce.srcObject instanceof MediaStream){const me=ce.srcObject.getAudioTracks();me.length>0&&(me.forEach(Ye=>{Ye.enabled=!N}),pe=!0)}!pe&&ce&&(ce.muted=N)}catch(ue){process.env.NODE_ENV==="development"&&console.error("Error controlling audio:",ue)}},[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 mm({className:d,style:r,autoConnect:s=!0,muted:a=!1,onConnected:f,onDisconnected:v,onError:C}){const{streamingUrl:R,setCloudStreamState:S}=uf();if(!R)return null;const N=()=>{S(Zt.CONNECTING)},z=()=>{S(Zt.LOADING)},te=()=>{S(Zt.CONNECTED),f?.()},j=()=>{S(Zt.DISCONNECTED),v?.()},se=J=>{S(Zt.ERROR,J),C?.(J)};return Jt.jsx("div",{className:d,style:r,children:Jt.jsx(fm,{signallingUrl:R,autoConnect:s,muted:a,onConnecting:N,onLoading:z,onConnected:te,onDisconnected:j,onError:se})})}const Ow=Object.freeze(Object.defineProperty({__proto__:null,RqmiiCloudAvatarPlayer:mm},Symbol.toStringTag,{value:"Module"}));exports.AGENT_TYPES=hi;exports.CLOUD_STREAM_STATE=Zt;exports.CONNECTION_STATE=pt;exports.DEFAULT_PCM_OPTIONS=qp;exports.EpicPixelStreamingPlayer=fm;exports.EventEmitter=nf;exports.RqmiiAgentProvider=of;exports.RqmiiAgentRoom=zy;exports.RqmiiCloudAvatarPlayer=mm;exports.RqmiiCloudAvatarPlayer$1=Ow;exports.SESSION_STATE=Ns;exports.SOCKET_EVENTS=br;exports.suppressNoisyLogs=Gp;exports.useRqmiiAgentContext=Fs;exports.useRqmiiAvatar=uf;exports.useRqmiiConnection=lf;exports.useRqmiiEvents=Py;exports.useRqmiiMessages=yy;exports.useRqmiiVAD=Oy;exports.useRqmiiVoice=wy;
|
|
2918
|
+
//# sourceMappingURL=RqmiiCloudAvatarPlayer-DDtkCYFJ.cjs.map
|