@rqmii_immersive/agent-react-sdk 2.0.0 → 4.0.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/README.md +103 -357
- package/dist/{RqmiiCloudAvatarPlayer-BnsY8xIR.js → RqmiiCloudAvatarPlayer-CESlcAGy.js} +6095 -6108
- package/dist/RqmiiCloudAvatarPlayer-CESlcAGy.js.map +1 -0
- package/dist/RqmiiCloudAvatarPlayer-D5npgPcs.cjs +2939 -0
- package/dist/RqmiiCloudAvatarPlayer-D5npgPcs.cjs.map +1 -0
- package/dist/agent-react-sdk.css +1 -1
- package/dist/components/RqmiiAgentRoom.d.ts +3 -0
- package/dist/components/RqmiiAgentRoom.d.ts.map +1 -0
- package/dist/components/RqmiiCloudAvatarPlayer.d.ts +3 -0
- package/dist/components/RqmiiCloudAvatarPlayer.d.ts.map +1 -0
- package/dist/components/RqmiiErrorBoundary.d.ts +19 -0
- package/dist/components/RqmiiErrorBoundary.d.ts.map +1 -0
- package/dist/components/pxs/EpicPixelStreamingPlayer.d.ts +5 -0
- package/dist/components/pxs/EpicPixelStreamingPlayer.d.ts.map +1 -0
- package/dist/core/constants.d.ts +81 -0
- package/dist/core/constants.d.ts.map +1 -0
- package/dist/core/events/emitter.d.ts +10 -0
- package/dist/core/events/emitter.d.ts.map +1 -0
- package/dist/core/managers/audio.d.ts +24 -0
- package/dist/core/managers/audio.d.ts.map +1 -0
- package/dist/core/managers/heartbeat.d.ts +13 -0
- package/dist/core/managers/heartbeat.d.ts.map +1 -0
- package/dist/core/managers/reconnect.d.ts +29 -0
- package/dist/core/managers/reconnect.d.ts.map +1 -0
- package/dist/core/managers/session.d.ts +20 -0
- package/dist/core/managers/session.d.ts.map +1 -0
- package/dist/core/managers/socket.d.ts +15 -0
- package/dist/core/managers/socket.d.ts.map +1 -0
- package/dist/core/state/reducer.d.ts +4 -0
- package/dist/core/state/reducer.d.ts.map +1 -0
- package/dist/core/state/selectors.d.ts +24 -0
- package/dist/core/state/selectors.d.ts.map +1 -0
- package/dist/core/state/types.d.ts +60 -0
- package/dist/core/state/types.d.ts.map +1 -0
- package/dist/core/utils/accumulator.d.ts +11 -0
- package/dist/core/utils/accumulator.d.ts.map +1 -0
- package/dist/core/utils/agent-type.d.ts +2 -0
- package/dist/core/utils/agent-type.d.ts.map +1 -0
- package/dist/core/utils/bytes.d.ts +2 -0
- package/dist/core/utils/bytes.d.ts.map +1 -0
- package/dist/core/utils/sleep.d.ts +2 -0
- package/dist/core/utils/sleep.d.ts.map +1 -0
- package/dist/hooks/index.d.ts +12 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/use-rqmii-agent.d.ts +2 -0
- package/dist/hooks/use-rqmii-agent.d.ts.map +1 -0
- package/dist/hooks/use-rqmii-audio-element.d.ts +2 -0
- package/dist/hooks/use-rqmii-audio-element.d.ts.map +1 -0
- package/dist/hooks/use-rqmii-avatar.d.ts +13 -0
- package/dist/hooks/use-rqmii-avatar.d.ts.map +1 -0
- package/dist/hooks/use-rqmii-connection.d.ts +27 -0
- package/dist/hooks/use-rqmii-connection.d.ts.map +1 -0
- package/dist/hooks/use-rqmii-events.d.ts +3 -0
- package/dist/hooks/use-rqmii-events.d.ts.map +1 -0
- package/dist/hooks/use-rqmii-messages.d.ts +6 -0
- package/dist/hooks/use-rqmii-messages.d.ts.map +1 -0
- package/dist/hooks/use-rqmii-press-to-talk.d.ts +3 -0
- package/dist/hooks/use-rqmii-press-to-talk.d.ts.map +1 -0
- package/dist/hooks/use-rqmii-sdk.d.ts +81 -0
- package/dist/hooks/use-rqmii-sdk.d.ts.map +1 -0
- package/dist/hooks/use-rqmii-session.d.ts +9 -0
- package/dist/hooks/use-rqmii-session.d.ts.map +1 -0
- package/dist/hooks/use-rqmii-vad.d.ts +3 -0
- package/dist/hooks/use-rqmii-vad.d.ts.map +1 -0
- package/dist/hooks/use-rqmii-voice.d.ts +12 -0
- package/dist/hooks/use-rqmii-voice.d.ts.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +10 -340
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +270 -20
- package/dist/index.js.map +1 -1
- package/dist/provider/RqmiiAgentProvider.d.ts +4 -0
- package/dist/provider/RqmiiAgentProvider.d.ts.map +1 -0
- package/dist/provider/socket-handlers.d.ts +77 -0
- package/dist/provider/socket-handlers.d.ts.map +1 -0
- package/dist/provider/use-manager-lifecycle.d.ts +76 -0
- package/dist/provider/use-manager-lifecycle.d.ts.map +1 -0
- package/dist/types/index.d.ts +385 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/ui/Orb.d.ts +19 -0
- package/dist/ui/Orb.d.ts.map +1 -0
- package/dist/ui/RqmiiAgentChat.d.ts +4 -0
- package/dist/ui/RqmiiAgentChat.d.ts.map +1 -0
- package/dist/ui/agent-data.d.ts +17 -0
- package/dist/ui/agent-data.d.ts.map +1 -0
- package/dist/ui/chat/ChatBox.d.ts +22 -0
- package/dist/ui/chat/ChatBox.d.ts.map +1 -0
- package/dist/ui/chat/CreditsExhaustedPanel.d.ts +6 -0
- package/dist/ui/chat/CreditsExhaustedPanel.d.ts.map +1 -0
- package/dist/ui/chat/chat-box-avatar.d.ts +3 -0
- package/dist/ui/chat/chat-box-avatar.d.ts.map +1 -0
- package/dist/ui/chat/chat-box-content.d.ts +26 -0
- package/dist/ui/chat/chat-box-content.d.ts.map +1 -0
- package/dist/ui/chat/chat-box-shared.d.ts +24 -0
- package/dist/ui/chat/chat-box-shared.d.ts.map +1 -0
- package/dist/ui/chat/chat-box-text-and-voice.d.ts +3 -0
- package/dist/ui/chat/chat-box-text-and-voice.d.ts.map +1 -0
- package/dist/ui/chat/chat-box-text.d.ts +3 -0
- package/dist/ui/chat/chat-box-text.d.ts.map +1 -0
- package/dist/ui/chat/chat-box-types.d.ts +83 -0
- package/dist/ui/chat/chat-box-types.d.ts.map +1 -0
- package/dist/ui/chat/chat-box-voice.d.ts +3 -0
- package/dist/ui/chat/chat-box-voice.d.ts.map +1 -0
- package/dist/ui/chat/components.d.ts +4 -0
- package/dist/ui/chat/components.d.ts.map +1 -0
- package/dist/ui/chat/panels.d.ts +78 -0
- package/dist/ui/chat/panels.d.ts.map +1 -0
- package/dist/ui/chat/primitives.d.ts +47 -0
- package/dist/ui/chat/primitives.d.ts.map +1 -0
- package/dist/ui/chat/utils.d.ts +7 -0
- package/dist/ui/chat/utils.d.ts.map +1 -0
- package/dist/ui/faces.d.ts +3 -0
- package/dist/ui/faces.d.ts.map +1 -0
- package/dist/ui/languages.d.ts +10 -0
- package/dist/ui/languages.d.ts.map +1 -0
- package/dist/ui.cjs +122 -1
- package/dist/ui.cjs.map +1 -1
- package/dist/ui.d.ts +11 -10
- package/dist/ui.d.ts.map +1 -0
- package/dist/ui.js +1771 -4
- package/dist/ui.js.map +1 -1
- package/package.json +33 -5
- package/dist/RqmiiCloudAvatarPlayer-BnsY8xIR.js.map +0 -1
- package/dist/RqmiiCloudAvatarPlayer-lqCz2xlU.cjs +0 -2938
- package/dist/RqmiiCloudAvatarPlayer-lqCz2xlU.cjs.map +0 -1
|
@@ -0,0 +1,2939 @@
|
|
|
1
|
+
"use strict";const ce=require("react");var Oi={exports:{}},Zn={};/**
|
|
2
|
+
* @license React
|
|
3
|
+
* react-jsx-runtime.production.js
|
|
4
|
+
*
|
|
5
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
6
|
+
*
|
|
7
|
+
* This source code is licensed under the MIT license found in the
|
|
8
|
+
* LICENSE file in the root directory of this source tree.
|
|
9
|
+
*/var pp;function gg(){if(pp)return Zn;pp=1;var d=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function s(a,p,v){var C=null;if(v!==void 0&&(C=""+v),p.key!==void 0&&(C=""+p.key),"key"in p){v={};for(var R in p)R!=="key"&&(v[R]=p[R])}else v=p;return p=v.ref,{$$typeof:d,type:a,key:C,ref:p!==void 0?p:null,props:v}}return Zn.Fragment=r,Zn.jsx=s,Zn.jsxs=s,Zn}var ei={};/**
|
|
10
|
+
* @license React
|
|
11
|
+
* react-jsx-runtime.development.js
|
|
12
|
+
*
|
|
13
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
14
|
+
*
|
|
15
|
+
* This source code is licensed under the MIT license found in the
|
|
16
|
+
* LICENSE file in the root directory of this source tree.
|
|
17
|
+
*/var fp;function yg(){return fp||(fp=1,process.env.NODE_ENV!=="production"&&(function(){function d(J){if(J==null)return null;if(typeof J=="function")return J.$$typeof===dt?null:J.displayName||J.name||null;if(typeof J=="string")return J;switch(J){case ee:return"Fragment";case ae:return"Profiler";case _e:return"StrictMode";case pe:return"Suspense";case Ve:return"SuspenseList";case tt:return"Activity"}if(typeof J=="object")switch(typeof J.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),J.$$typeof){case Z:return"Portal";case H:return J.displayName||"Context";case he:return(J._context.displayName||"Context")+".Consumer";case le:var Oe=J.render;return J=J.displayName,J||(J=Oe.displayName||Oe.name||"",J=J!==""?"ForwardRef("+J+")":"ForwardRef"),J;case me:return Oe=J.displayName||null,Oe!==null?Oe:d(J.type)||"Memo";case Ze:Oe=J._payload,J=J._init;try{return d(J(Oe))}catch{}}return null}function r(J){return""+J}function s(J){try{r(J);var Oe=!1}catch{Oe=!0}if(Oe){Oe=console;var it=Oe.error,Ke=typeof Symbol=="function"&&Symbol.toStringTag&&J[Symbol.toStringTag]||J.constructor.name||"Object";return it.call(Oe,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",Ke),r(J)}}function a(J){if(J===ee)return"<>";if(typeof J=="object"&&J!==null&&J.$$typeof===Ze)return"<...>";try{var Oe=d(J);return Oe?"<"+Oe+">":"<...>"}catch{return"<...>"}}function p(){var J=wt.A;return J===null?null:J.getOwner()}function v(){return Error("react-stack-top-frame")}function C(J){if(lt.call(J,"key")){var Oe=Object.getOwnPropertyDescriptor(J,"key").get;if(Oe&&Oe.isReactWarning)return!1}return J.key!==void 0}function R(J,Oe){function it(){vt||(vt=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",Oe))}it.isReactWarning=!0,Object.defineProperty(J,"key",{get:it,configurable:!0})}function S(){var J=d(this.type);return Ye[J]||(Ye[J]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),J=this.props.ref,J!==void 0?J:null}function F(J,Oe,it,Ke,Pe,ot){var Je=it.ref;return J={$$typeof:se,type:J,key:Oe,props:it,_owner:Ke},(Je!==void 0?Je:null)!==null?Object.defineProperty(J,"ref",{enumerable:!1,get:S}):Object.defineProperty(J,"ref",{enumerable:!1,value:null}),J._store={},Object.defineProperty(J._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(J,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(J,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:Pe}),Object.defineProperty(J,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:ot}),Object.freeze&&(Object.freeze(J.props),Object.freeze(J)),J}function z(J,Oe,it,Ke,Pe,ot){var Je=Oe.children;if(Je!==void 0)if(Ke)if(yt(Je)){for(Ke=0;Ke<Je.length;Ke++)ie(Je[Ke]);Object.freeze&&Object.freeze(Je)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ie(Je);if(lt.call(Oe,"key")){Je=d(J);var We=Object.keys(Oe).filter(function(et){return et!=="key"});Ke=0<We.length?"{key: someKey, "+We.join(": ..., ")+": ...}":"{key: someKey}",at[Je+Ke]||(We=0<We.length?"{"+We.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
|
|
18
|
+
let props = %s;
|
|
19
|
+
<%s {...props} />
|
|
20
|
+
React keys must be passed directly to JSX without using spread:
|
|
21
|
+
let props = %s;
|
|
22
|
+
<%s key={someKey} {...props} />`,Ke,Je,We,Je),at[Je+Ke]=!0)}if(Je=null,it!==void 0&&(s(it),Je=""+it),C(Oe)&&(s(Oe.key),Je=""+Oe.key),"key"in Oe){it={};for(var xt in Oe)xt!=="key"&&(it[xt]=Oe[xt])}else it=Oe;return Je&&R(it,typeof J=="function"?J.displayName||J.name||"Unknown":J),F(J,Je,it,p(),Pe,ot)}function ie(J){X(J)?J._store&&(J._store.validated=1):typeof J=="object"&&J!==null&&J.$$typeof===Ze&&(J._payload.status==="fulfilled"?X(J._payload.value)&&J._payload.value._store&&(J._payload.value._store.validated=1):J._store&&(J._store.validated=1))}function X(J){return typeof J=="object"&&J!==null&&J.$$typeof===se}var re=ce,se=Symbol.for("react.transitional.element"),Z=Symbol.for("react.portal"),ee=Symbol.for("react.fragment"),_e=Symbol.for("react.strict_mode"),ae=Symbol.for("react.profiler"),he=Symbol.for("react.consumer"),H=Symbol.for("react.context"),le=Symbol.for("react.forward_ref"),pe=Symbol.for("react.suspense"),Ve=Symbol.for("react.suspense_list"),me=Symbol.for("react.memo"),Ze=Symbol.for("react.lazy"),tt=Symbol.for("react.activity"),dt=Symbol.for("react.client.reference"),wt=re.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,lt=Object.prototype.hasOwnProperty,yt=Array.isArray,$t=console.createTask?console.createTask:function(){return null};re={react_stack_bottom_frame:function(J){return J()}};var vt,Ye={},St=re.react_stack_bottom_frame.bind(re,v)(),He=$t(a(v)),at={};ei.Fragment=ee,ei.jsx=function(J,Oe,it){var Ke=1e4>wt.recentlyCreatedOwnerStacks++;return z(J,Oe,it,!1,Ke?Error("react-stack-top-frame"):St,Ke?$t(a(J)):He)},ei.jsxs=function(J,Oe,it){var Ke=1e4>wt.recentlyCreatedOwnerStacks++;return z(J,Oe,it,!0,Ke?Error("react-stack-top-frame"):St,Ke?$t(a(J)):He)}})()),ei}var mp;function wg(){return mp||(mp=1,process.env.NODE_ENV==="production"?Oi.exports=gg():Oi.exports=yg()),Oi.exports}var rr=wg();const hi={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},Qt={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",CLIENT_READY:"client_ready",HEARTBEAT:"heartbeat",HEARTBEAT_ACK:"heartbeat_ack",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",RECONNECT_CREDENTIAL:"reconnect_credential",RECONNECT_SUCCESS:"reconnect_success",RECONNECT_FAILED:"reconnect_failed",SESSION_EXPIRED:"session_expired",CREDITS_EXHAUSTED:"credits_exhausted",SESSION_STATE_CHANGED:"session:state_changed",AUDIO_PLAYBACK_COMPLETE:"audio:playback_complete"},mt={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",FAILED:"failed",ENDED:"ended"},dr={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},Us={IDLE:"idle",USER_SPEAKING:"user_speaking",AGENT_THINKING:"agent_thinking",AGENT_SPEAKING:"agent_speaking",TOOL_EXECUTING:"tool_executing",TERMINATING:"terminating",TERMINATED:"terminated"},Kp={enabled:!0,maxAttempts:8,initialDelayMs:500,maxDelayMs:5e3,timeoutMs:8e3},Qp={encoding:"16bitInt",channels:1,sampleRate:16e3},fo={connectionState:mt.IDLE,isConnected:!1,isSessionReady:!1,error:null,reconnectAttempt:0,isAudioPlaying:!1,isAvatarSpeaking:!1,lastHeartbeatAck:null,sessionState:Us.IDLE,cloudStream:{state:dr.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[],creditExhausted:!1,creditError:null};function gp(d,r){switch(r.type){case"SET_CONNECTION_STATE":return{...d,connectionState:r.payload,isConnected:r.payload===mt.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_RECONNECT_ATTEMPT":return{...d,reconnectAttempt:r.payload};case"SET_HEARTBEAT_ACK":return{...d,lastHeartbeatAck:r.payload};case"SET_SESSION_READY":return{...d,isSessionReady:r.payload};case"HARD_RESET":return fo;case"REPLACE_STATE":return r.payload;default:return d}}function vg(d){return{isSessionTerminated:d===Us.TERMINATED,isSessionTerminating:d===Us.TERMINATING,isAgentThinking:d===Us.AGENT_THINKING,isAgentSpeaking:d===Us.AGENT_SPEAKING,isToolExecuting:d===Us.TOOL_EXECUTING}}function _g(){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()}`,p=d.get(a)||s||"";return d.delete(a),{id:a,text:p}},clear(){d.clear()}}}function bg(){try{const d=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof d=="string"&&d.trim()?d.trim():void 0}catch{return}}async function yp(d){if(!d?.ok){let r=`HTTP ${d.status}`;try{const p=await d.json();r=p?.detail||p?.message||r}catch{}const s=new Error(r);throw s.status=d.status,s}return d.json()}function Sg({restUrl:d,log:r,withCredentials:s}){function a(){if(!d)throw new Error("Missing restUrl in RqmiiAgentProvider")}async function p({apiKey:C,publicChatId:R,agentId:S,userId:F,language:z="en"}={}){a();const ie={...C?{api_key:C}:{},...R?{public_chat_id:R}:{},...S?{agent_id:S}:{},...F?{user_id:F}:{},language:z};r("initializeSession — POST /sessions/init",ie);const X=await fetch(`${d}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ie),...s?{credentials:"include"}:{}}),re=await yp(X);if(!re?.session_id||!re?.session_token)throw new Error("Invalid initialize session response");return re}async function v({uniqueId:C}){a(),r("joinDesktopSession — POST /sessions/join",{uniqueId:C});const R=await fetch(`${d}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:C}),...s?{credentials:"include"}:{}}),S=await yp(R);if(!S?.session_id||!S?.session_token)throw new Error("Invalid join session response");return S}return{initializeSession:p,joinDesktopSession:v}}const Fr=Object.create(null);Fr.open="0";Fr.close="1";Fr.ping="2";Fr.pong="3";Fr.message="4";Fr.upgrade="5";Fr.noop="6";const Li=Object.create(null);Object.keys(Fr).forEach(d=>{Li[Fr[d]]=d});const mo={type:"error",data:"parser error"},Xp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Yp=typeof ArrayBuffer=="function",Jp=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d&&d.buffer instanceof ArrayBuffer,Co=({type:d,data:r},s,a)=>Xp&&r instanceof Blob?s?a(r):wp(r,a):Yp&&(r instanceof ArrayBuffer||Jp(r))?s?a(r):wp(new Blob([r]),a):a(Fr[d]+(r||"")),wp=(d,r)=>{const s=new FileReader;return s.onload=function(){const a=s.result.split(",")[1];r("b"+(a||""))},s.readAsDataURL(d)};function vp(d){return d instanceof Uint8Array?d:d instanceof ArrayBuffer?new Uint8Array(d):new Uint8Array(d.buffer,d.byteOffset,d.byteLength)}let eo;function Tg(d,r){if(Xp&&d.data instanceof Blob)return d.data.arrayBuffer().then(vp).then(r);if(Yp&&(d.data instanceof ArrayBuffer||Jp(d.data)))return r(vp(d.data));Co(d,!1,s=>{eo||(eo=new TextEncoder),r(eo.encode(s))})}const _p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ui=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let d=0;d<_p.length;d++)ui[_p.charCodeAt(d)]=d;const Eg=d=>{let r=d.length*.75,s=d.length,a,p=0,v,C,R,S;d[d.length-1]==="="&&(r--,d[d.length-2]==="="&&r--);const F=new ArrayBuffer(r),z=new Uint8Array(F);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[p++]=v<<2|C>>4,z[p++]=(C&15)<<4|R>>2,z[p++]=(R&3)<<6|S&63;return F},$g=typeof ArrayBuffer=="function",ko=(d,r)=>{if(typeof d!="string")return{type:"message",data:Zp(d,r)};const s=d.charAt(0);return s==="b"?{type:"message",data:xg(d.substring(1),r)}:Li[s]?d.length>1?{type:Li[s],data:d.substring(1)}:{type:Li[s]}:mo},xg=(d,r)=>{if($g){const s=Eg(d);return Zp(s,r)}else return{base64:!0,data:d}},Zp=(d,r)=>{switch(r){case"blob":return d instanceof Blob?d:new Blob([d]);case"arraybuffer":default:return d instanceof ArrayBuffer?d:d.buffer}},ef="",Cg=(d,r)=>{const s=d.length,a=new Array(s);let p=0;d.forEach((v,C)=>{Co(v,!1,R=>{a[C]=R,++p===s&&r(a.join(ef))})})},kg=(d,r)=>{const s=d.split(ef),a=[];for(let p=0;p<s.length;p++){const v=ko(s[p],r);if(a.push(v),v.type==="error")break}return a};function Rg(){return new TransformStream({transform(d,r){Tg(d,s=>{const a=s.length;let p;if(a<126)p=new Uint8Array(1),new DataView(p.buffer).setUint8(0,a);else if(a<65536){p=new Uint8Array(3);const v=new DataView(p.buffer);v.setUint8(0,126),v.setUint16(1,a)}else{p=new Uint8Array(9);const v=new DataView(p.buffer);v.setUint8(0,127),v.setBigUint64(1,BigInt(a))}d.data&&typeof d.data!="string"&&(p[0]|=128),r.enqueue(p),r.enqueue(s)})}})}let to;function Pi(d){return d.reduce((r,s)=>r+s.length,0)}function Di(d,r){if(d[0].length===r)return d.shift();const s=new Uint8Array(r);let a=0;for(let p=0;p<r;p++)s[p]=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 Ag(d,r){to||(to=new TextDecoder);const s=[];let a=0,p=-1,v=!1;return new TransformStream({transform(C,R){for(s.push(C);;){if(a===0){if(Pi(s)<1)break;const S=Di(s,1);v=(S[0]&128)===128,p=S[0]&127,p<126?a=3:p===126?a=1:a=2}else if(a===1){if(Pi(s)<2)break;const S=Di(s,2);p=new DataView(S.buffer,S.byteOffset,S.length).getUint16(0),a=3}else if(a===2){if(Pi(s)<8)break;const S=Di(s,8),F=new DataView(S.buffer,S.byteOffset,S.length),z=F.getUint32(0);if(z>Math.pow(2,21)-1){R.enqueue(mo);break}p=z*Math.pow(2,32)+F.getUint32(4),a=3}else{if(Pi(s)<p)break;const S=Di(s,p);R.enqueue(ko(v?S:to.decode(S),r)),a=0}if(p===0||p>d){R.enqueue(mo);break}}}})}const tf=4;function Dt(d){if(d)return Ig(d)}function Ig(d){for(var r in Dt.prototype)d[r]=Dt.prototype[r];return d}Dt.prototype.on=Dt.prototype.addEventListener=function(d,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+d]=this._callbacks["$"+d]||[]).push(r),this};Dt.prototype.once=function(d,r){function s(){this.off(d,s),r.apply(this,arguments)}return s.fn=r,this.on(d,s),this};Dt.prototype.off=Dt.prototype.removeListener=Dt.prototype.removeAllListeners=Dt.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,p=0;p<s.length;p++)if(a=s[p],a===r||a.fn===r){s.splice(p,1);break}return s.length===0&&delete this._callbacks["$"+d],this};Dt.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,p=s.length;a<p;++a)s[a].apply(this,r)}return this};Dt.prototype.emitReserved=Dt.prototype.emit;Dt.prototype.listeners=function(d){return this._callbacks=this._callbacks||{},this._callbacks["$"+d]||[]};Dt.prototype.hasListeners=function(d){return!!this.listeners(d).length};const Wi=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,s)=>s(r,0),yr=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Mg="arraybuffer";function rf(d,...r){return r.reduce((s,a)=>(d.hasOwnProperty(a)&&(s[a]=d[a]),s),{})}const Og=yr.setTimeout,Pg=yr.clearTimeout;function Hi(d,r){r.useNativeTimers?(d.setTimeoutFn=Og.bind(yr),d.clearTimeoutFn=Pg.bind(yr)):(d.setTimeoutFn=yr.setTimeout.bind(yr),d.clearTimeoutFn=yr.clearTimeout.bind(yr))}const Dg=1.33;function zg(d){return typeof d=="string"?Lg(d):Math.ceil((d.byteLength||d.size)*Dg)}function Lg(d){let r=0,s=0;for(let a=0,p=d.length;a<p;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 sf(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Bg(d){let r="";for(let s in d)d.hasOwnProperty(s)&&(r.length&&(r+="&"),r+=encodeURIComponent(s)+"="+encodeURIComponent(d[s]));return r}function Ng(d){let r={},s=d.split("&");for(let a=0,p=s.length;a<p;a++){let v=s[a].split("=");r[decodeURIComponent(v[0])]=decodeURIComponent(v[1])}return r}class Ug extends Error{constructor(r,s,a){super(r),this.description=s,this.context=a,this.type="TransportError"}}class Ro extends Dt{constructor(r){super(),this.writable=!1,Hi(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 Ug(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=ko(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=Bg(r);return s.length?"?"+s:""}}class Fg extends Ro{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)};kg(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,Cg(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]=sf()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(r,s)}}let nf=!1;try{nf=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Vg=nf;function Gg(){}class qg extends Fg{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",(p,v)=>{this.onError("xhr post error",p,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 Ur extends Dt{constructor(r,s,a){super(),this.createRequest=r,Hi(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=rf(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 p in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(p)&&a.setRequestHeader(p,this._opts.extraHeaders[p])}}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 p;a.readyState===3&&((p=this._opts.cookieJar)===null||p===void 0||p.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(p){this.setTimeoutFn(()=>{this._onError(p)},0);return}typeof document<"u"&&(this._index=Ur.requestsCount++,Ur.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=Gg,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Ur.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()}}Ur.requestsCount=0;Ur.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",bp);else if(typeof addEventListener=="function"){const d="onpagehide"in yr?"pagehide":"unload";addEventListener(d,bp,!1)}}function bp(){for(let d in Ur.requests)Ur.requests.hasOwnProperty(d)&&Ur.requests[d].abort()}const Wg=(function(){const d=af({xdomain:!1});return d&&d.responseType!==null})();class Hg extends qg{constructor(r){super(r);const s=r&&r.forceBase64;this.supportsBinary=Wg&&!s}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Ur(af,this.uri(),r)}}function af(d){const r=d.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||Vg))return new XMLHttpRequest}catch{}if(!r)try{return new yr[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const of=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class jg extends Ro{get name(){return"websocket"}doOpen(){const r=this.uri(),s=this.opts.protocols,a=of?{}:rf(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(p){return this.emitReserved("error",p)}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],p=s===r.length-1;Co(a,this.supportsBinary,v=>{try{this.doWrite(a,v)}catch{}p&&Wi(()=>{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]=sf()),this.supportsBinary||(s.b64=1),this.createUri(r,s)}}const ro=yr.WebSocket||yr.MozWebSocket;class Kg extends jg{createSocket(r,s,a){return of?new ro(r,s,a):s?new ro(r,s):new ro(r)}doWrite(r,s){this.ws.send(s)}}class Qg extends Ro{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=Ag(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(s).getReader(),p=Rg();p.readable.pipeTo(r.writable),this._writer=p.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],p=s===r.length-1;this._writer.write(a).then(()=>{p&&Wi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const Xg={websocket:Kg,webtransport:Qg,polling:Hg},Yg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Jg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function go(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 p=Yg.exec(d||""),v={},C=14;for(;C--;)v[Jg[C]]=p[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=Zg(v,v.path),v.queryKey=ey(v,v.query),v}function Zg(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 ey(d,r){const s={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,p,v){p&&(s[p]=v)}),s}const yo=typeof addEventListener=="function"&&typeof removeEventListener=="function",Bi=[];yo&&addEventListener("offline",()=>{Bi.forEach(d=>d())},!1);class os extends Dt{constructor(r,s){if(super(),this.binaryType=Mg,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=go(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=go(s.host).host);Hi(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 p=a.prototype.name;this.transports.push(p),this._transportsByName[p]=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=Ng(this.opts.query)),yo&&(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"})},Bi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const s=Object.assign({},this.opts.query);s.EIO=tf,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&&os.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",os.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 p=this.writeBuffer[a].data;if(p&&(s+=zg(p)),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,Wi(()=>{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,p){if(typeof s=="function"&&(p=s,s=void 0),typeof a=="function"&&(p=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),p&&this.once("flush",p),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(os.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(),yo&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=Bi.indexOf(this._offlineEventListener);a!==-1&&Bi.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,s),this.writeBuffer=[],this._prevBufferLen=0}}}os.protocol=tf;class ty extends os{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;os.priorWebsocketSuccess=!1;const p=()=>{a||(s.send([{type:"ping",data:"probe"}]),s.once("packet",ie=>{if(!a)if(ie.type==="pong"&&ie.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;os.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 X=new Error("probe error");X.transport=s.name,this.emitReserved("upgradeError",X)}}))};function v(){a||(a=!0,z(),s.close(),s=null)}const C=ie=>{const X=new Error("probe error: "+ie);X.transport=s.name,v(),this.emitReserved("upgradeError",X)};function R(){C("transport closed")}function S(){C("socket closed")}function F(ie){s&&ie.name!==s.name&&v()}const z=()=>{s.removeListener("open",p),s.removeListener("error",C),s.removeListener("close",R),this.off("close",S),this.off("upgrading",F)};s.once("open",p),s.once("error",C),s.once("close",R),this.once("close",S),this.once("upgrading",F),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 ry=class extends ty{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(p=>Xg[p]).filter(p=>!!p)),super(r,a)}};function sy(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=go(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 ny=typeof ArrayBuffer=="function",iy=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d.buffer instanceof ArrayBuffer,lf=Object.prototype.toString,ay=typeof Blob=="function"||typeof Blob<"u"&&lf.call(Blob)==="[object BlobConstructor]",oy=typeof File=="function"||typeof File<"u"&&lf.call(File)==="[object FileConstructor]";function Ao(d){return ny&&(d instanceof ArrayBuffer||iy(d))||ay&&d instanceof Blob||oy&&d instanceof File}function Ni(d,r){if(!d||typeof d!="object")return!1;if(Array.isArray(d)){for(let s=0,a=d.length;s<a;s++)if(Ni(d[s]))return!0;return!1}if(Ao(d))return!0;if(d.toJSON&&typeof d.toJSON=="function"&&arguments.length===1)return Ni(d.toJSON(),!0);for(const s in d)if(Object.prototype.hasOwnProperty.call(d,s)&&Ni(d[s]))return!0;return!1}function ly(d){const r=[],s=d.data,a=d;return a.data=wo(s,r),a.attachments=r.length,{packet:a,buffers:r}}function wo(d,r){if(!d)return d;if(Ao(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]=wo(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]=wo(d[a],r));return s}return d}function uy(d,r){return d.data=vo(d.data,r),delete d.attachments,d}function vo(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]=vo(d[s],r);else if(typeof d=="object")for(const s in d)Object.prototype.hasOwnProperty.call(d,s)&&(d[s]=vo(d[s],r));return d}const dy=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var st;(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"})(st||(st={}));class cy{constructor(r){this.replacer=r}encode(r){return(r.type===st.EVENT||r.type===st.ACK)&&Ni(r)?this.encodeAsBinary({type:r.type===st.EVENT?st.BINARY_EVENT:st.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let s=""+r.type;return(r.type===st.BINARY_EVENT||r.type===st.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=ly(r),a=this.encodeAsString(s.packet),p=s.buffers;return p.unshift(a),p}}class Io extends Dt{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===st.BINARY_EVENT;a||s.type===st.BINARY_ACK?(s.type=a?st.EVENT:st.ACK,this.reconstructor=new hy(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(Ao(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(st[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===st.BINARY_EVENT||a.type===st.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(!py(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 p=r.charAt(s+1);if(p!==""&&Number(p)==p){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(Io.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 st.CONNECT:return Sp(s);case st.DISCONNECT:return s===void 0;case st.CONNECT_ERROR:return typeof s=="string"||Sp(s);case st.EVENT:case st.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&dy.indexOf(s[0])===-1);case st.ACK:case st.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class hy{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=uy(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const py=Number.isInteger||function(d){return typeof d=="number"&&isFinite(d)&&Math.floor(d)===d};function Sp(d){return Object.prototype.toString.call(d)==="[object Object]"}const fy=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Io,Encoder:cy,get PacketType(){return st}},Symbol.toStringTag,{value:"Module"}));function Ar(d,r,s){return d.on(r,s),function(){d.off(r,s)}}const my=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class uf extends Dt{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=[Ar(r,"open",this.onopen.bind(this)),Ar(r,"packet",this.onpacket.bind(this)),Ar(r,"error",this.onerror.bind(this)),Ar(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,p,v;if(my.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:st.EVENT,data:s};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){const z=this.ids++,ie=s.pop();this._registerAckCallback(z,ie),C.id=z}const R=(p=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||p===void 0?void 0:p.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 p=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(p===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"))},p),C=(...R)=>{this.io.clearTimeoutFn(v),s.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...s){return new Promise((a,p)=>{const v=(C,R)=>C?p(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((p,...v)=>(this._queue[0],p!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),s&&s(p)):(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:st.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 st.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 st.EVENT:case st.BINARY_EVENT:this.onevent(r);break;case st.ACK:case st.BINARY_ACK:this.onack(r);break;case st.DISCONNECT:this.ondisconnect();break;case st.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(...p){a||(a=!0,s.packet({type:st.ACK,id:r,data:p}))}}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:st.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const s=this._anyListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const s=this._anyOutgoingListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const s=this._anyOutgoingListeners.slice();for(const a of s)a.apply(this,r.data)}}}function un(d){d=d||{},this.ms=d.min||100,this.max=d.max||1e4,this.factor=d.factor||2,this.jitter=d.jitter>0&&d.jitter<=1?d.jitter:0,this.attempts=0}un.prototype.duration=function(){var d=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),s=Math.floor(r*this.jitter*d);d=(Math.floor(r*10)&1)==0?d-s:d+s}return Math.min(d,this.max)|0};un.prototype.reset=function(){this.attempts=0};un.prototype.setMin=function(d){this.ms=d};un.prototype.setMax=function(d){this.max=d};un.prototype.setJitter=function(d){this.jitter=d};class _o extends Dt{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,Hi(this,s),this.reconnection(s.reconnection!==!1),this.reconnectionAttempts(s.reconnectionAttempts||1/0),this.reconnectionDelay(s.reconnectionDelay||1e3),this.reconnectionDelayMax(s.reconnectionDelayMax||5e3),this.randomizationFactor((a=s.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new un({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(s.timeout==null?2e4:s.timeout),this._readyState="closed",this.uri=r;const p=s.parser||fy;this.encoder=new p.Encoder,this.decoder=new p.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 ry(this.uri,this.opts);const s=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const p=Ar(s,"open",function(){a.onopen(),r&&r()}),v=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=Ar(s,"error",v);if(this._timeout!==!1){const R=this._timeout,S=this.setTimeoutFn(()=>{p(),v(new Error("timeout")),s.close()},R);this.opts.autoUnref&&S.unref(),this.subs.push(()=>{this.clearTimeoutFn(S)})}return this.subs.push(p),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(Ar(r,"ping",this.onping.bind(this)),Ar(r,"data",this.ondata.bind(this)),Ar(r,"error",this.onerror.bind(this)),Ar(r,"close",this.onclose.bind(this)),Ar(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){Wi(()=>{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 uf(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(p=>{p?(r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",p)):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 Ui(d,r){typeof d=="object"&&(r=d,d=void 0),r=r||{};const s=sy(d,r.path||"/socket.io"),a=s.source,p=s.id,v=s.path,C=ti[p]&&v in ti[p].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let S;return R?S=new _o(a,r):(ti[p]||(ti[p]=new _o(a,r)),S=ti[p]),s.query&&!r.query&&(r.query=s.queryKey),S.socket(s.path,r)}Object.assign(Ui,{Manager:_o,Socket:uf,io:Ui,connect:Ui});function gy({wsUrl:d,log:r}){let s=null;function a({authPayload:C,queryToken:R}){const S=Ui(d,{transports:["websocket","polling"],timeout:2e4,reconnection:!1,auth:C,query:R?{token:R}:void 0});return s=S,S}function p(){if(s){try{s.removeAllListeners(),s.connected?s.disconnect():s.close()}catch{}s=null}}function v(){return s}return{connectSocketRaw:a,cleanupSocket:p,getSocket:v}}const yy=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(p)}function p(){s.forEach(v=>r.removeEventListener(v,a))}};function Gt(d){this.init(d)}Gt.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()};Gt.prototype.getMaxValue=function(){var d={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Gt.prototype.getTypedArray=function(){var d={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Gt.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),yy(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Gt.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};Gt.prototype.isTypedArray=function(d){return d.byteLength&&d.buffer&&d.buffer.constructor==ArrayBuffer};Gt.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()}};Gt.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};Gt.prototype.volume=function(d){this.gainNode.gain.value=d};Gt.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Gt.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};Gt.prototype.setRequestStop=function(){this.flag_request_stop=!0};Gt.prototype.setOnEnd=function(d){this.onEnd=d};Gt.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};Gt.prototype.ensuredSetTimeout=(function(){let d;return function(r,s){d=performance.now();const a=p=>{p-d>=s?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Gt.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Gt.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,p,v,C,R;for(p=0;p<this.option.channels;p++)for(a=s.getChannelData(p),v=p,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 wy(d,r){const s=new Gt(d),a=s.destroy.bind(s);let p=!1;return s.destroy=()=>{if(!p){p=!0;try{a()}catch{}}},s.setOnEnd(()=>{p||r()}),s._isDestroyed=()=>p,s}function vy({enableAudio:d,pcmOptions:r,log:s,onPlaybackComplete:a}){let p=null,v=null;function C(){if(!d||p)return p;const ee={...Qp,...r||{}};return p=wy(ee,()=>{a()}),p}function R(){if(p){try{p.interrupt?.(),p.destroy?.()}catch{}p=null}}function S(ee){const _e=C();if(_e)try{_e.feed(ee)}catch(ae){s("feedAudio: player.feed() failed",ae),a()}}function F(){if(!p){a();return}try{p.setRequestStop(),p.playingBufferNode||p.scheduledBufferNode||a()}catch(ee){s("requestStop: setRequestStop() failed",ee),a()}}function z(){R()}function ie(){if(p)try{const ee=p.audioCtx;ee?.state==="running"&&ee.suspend()}catch(ee){s("pauseAudioPlayback: audioCtx.suspend() failed",ee)}}async function X(){const ee=C();if(ee)try{const _e=ee.audioCtx;_e?.state==="suspended"&&await _e.resume()}catch(_e){s("resumeAudioPlayback: audioCtx.resume() failed",_e)}}function re(ee){v=ee||null}function se(){return v}function Z(){return p?p._isDestroyed?.()??!0:!0}return{ensurePcmPlayer:C,destroyPcmPlayer:R,feedAudio:S,requestStop:F,interruptPlayback:z,pauseAudioPlayback:ie,resumeAudioPlayback:X,attachAudioElement:re,getAudioElement:se,isDestroyed:Z}}function _y({log:d,reconnectOptions:r}){let s=null,a=!1,p=!1;const v={...Kp,...r||{}};function C(X){const re=X;!re?.sessionId||!re?.reconnectToken||!re?.role||(s={sessionId:re.sessionId,reconnectToken:re.reconnectToken,role:re.role})}function R(){return s}function S(){s=null}async function F({connectSocket:X,onAttempt:re,onSuccess:se,onFailure:Z,isAborted:ee}){if(!a){if(!s){Z?.("Reconnect token unavailable. Please initialize a new session.");return}a=!0,p=!1;for(let _e=1;_e<=v.maxAttempts;_e+=1){if(ee?.()||p){a=!1;return}re?.(_e);try{await X({authPayload:{reconnectToken:s.reconnectToken,sessionId:s.sessionId,role:s.role},expectReconnectSuccess:!0}),a=!1,se?.();return}catch(ae){d(`reconnect attempt ${_e} failed`,ae);const he=Math.min(v.maxDelayMs,v.initialDelayMs*2**(_e-1));await new Promise(H=>setTimeout(H,he))}}a=!1,Z?.("Reconnect window expired. Please initialize a new session.")}}function z(){p=!0}function ie(){return a}return{storeCredential:C,getCredential:R,clearCredential:S,tryReconnect:F,abortReconnect:z,isReconnecting:ie}}function by({intervalMs:d,log:r}){let s=null;function a(C){s!==null&&(clearInterval(s),s=null),r("[HeartbeatManager] starting heartbeat, intervalMs:",d),s=setInterval(()=>{C&&C.emit(Qt.HEARTBEAT,{})},d)}function p(){s!==null&&(r("[HeartbeatManager] stopping heartbeat"),clearInterval(s),s=null)}function v(){return s!==null}return{start:a,stop:p,isRunning:v}}function Sy(d){const{wsUrl:r,restUrl:s,reconnectOptions:a,enableAudio:p,pcmOptions:v,debug:C,withCredentials:R,heartbeatIntervalSeconds:S,onPlaybackComplete:F}=d,z=ce.useCallback((...ee)=>{C&&console.log("[RqmiiSDK]",...ee)},[C]),ie=ce.useRef(null),X=ce.useRef(null),re=ce.useRef(null),se=ce.useRef(null),Z=ce.useRef(null);return ie.current||(ie.current=gy({wsUrl:r,log:z})),X.current||(X.current=vy({enableAudio:p,pcmOptions:v,log:z,onPlaybackComplete:F})),re.current||(re.current=_y({log:z,reconnectOptions:a})),se.current||(se.current=Sg({restUrl:s,log:z,withCredentials:R})),Z.current||(Z.current=by({intervalMs:S*1e3,log:z})),ce.useEffect(()=>()=>{Z.current?.stop(),ie.current?.cleanupSocket(),X.current?.destroyPcmPlayer()},[]),{socketMgrRef:ie,audioMgrRef:X,reconnectMgrRef:re,sessionMgrRef:se,heartbeatMgrRef:Z,log:z}}function so(d){return String(d||"").toLowerCase().replaceAll("-","_")}function Ty(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,p=Number.isInteger(s.byteLength)?s.byteLength:s.buffer.byteLength-a;return new Uint8Array(s.buffer,a,p)}if(r.type==="Buffer"&&Array.isArray(r.data))return new Uint8Array(r.data)}try{return new Uint8Array(d)}catch{return null}}function Ey(d){const{socket:r,dispatch:s,stateRef:a,sessionIdRef:p,sessionAgentTypeRef:v,interruptedRef:C,manualDisconnectRef:R,chunkAccumulatorRef:S,reconnectMgrRef:F,heartbeatMgrRef:z,audioMgrRef:ie,enableAudio:X,reconnectOptions:re,cbRefs:se,log:Z}=d,ee=Qt,_e=z.current,ae=ie.current;r.onAny((H,...le)=>{Z(`[event] ${H}`,le.length>0?le[0]:"")}),r.onAnyOutgoing((H,...le)=>{Z(`[emit] ${H}`,le.length>0?le[0]:"")}),r.on(ee.DISCONNECT,H=>{Z("socket disconnected",H),s({type:"SET_CONNECTION_STATE",payload:mt.IDLE}),s({type:"SET_SESSION_READY",payload:!1}),_e.stop(),se.current.onDisconnect?.(H),!R.current&&(re?.enabled!==!1?s({type:"SET_CONNECTION_STATE",payload:mt.RECONNECTING}):(s({type:"SET_CONNECTION_STATE",payload:mt.FAILED}),s({type:"SET_ERROR",payload:"Connection lost"})))}),r.on(ee.SESSION_READY,H=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null}),H?.agentType&&s({type:"UPDATE_SESSION",payload:{agentType:so(H.agentType)}}),_e.start(r)}),r.on(ee.SESSION_JOINED,()=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null}),_e.start(r)}),r.on(ee.SESSION_TERMINATED,()=>{s({type:"SET_CONNECTION_STATE",payload:mt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),_e.stop(),se.current.onSessionTerminated?.()}),r.on(ee.TRANSCRIPT,H=>{const le=H||null;s({type:"SET_TRANSCRIPT",payload:le}),le?.is_final&&le?.text?.trim()&&(s({type:"ADD_MESSAGE",payload:{id:`transcript-${Date.now()}`,role:"user",text:le.text.trim(),timestamp:new Date().toISOString()}}),s({type:"SET_PARTIAL_TRANSCRIPT",payload:null}))}),r.on(ee.PARTIAL_TRANSCRIPT,H=>{const le=typeof H=="string"?H:H?.text;typeof le=="string"&&le.length===0||s({type:"SET_PARTIAL_TRANSCRIPT",payload:H||null})}),r.on(ee.AGENT_RESPONSE_CHUNK,H=>{const{id:le,text:pe}=S.current.addChunk(H?.requestId,H?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(Ve=>Ve.id!==le),{id:le,role:"assistant",text:pe,streaming:!0,timestamp:new Date().toISOString()}]})}),r.on(ee.AGENT_RESPONSE,H=>{const{id:le,text:pe}=S.current.consume(H?.requestId,H?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(Ve=>Ve.id!==le),{id:le,role:"assistant",text:pe,streaming:!1,timestamp:new Date().toISOString()}]})}),r.on(ee.AVATAR_SPEAKING,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!0})}),r.on(ee.AVATAR_SPEAKING_DONE,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!1})}),r.on(ee.AGENT_AUDIO_CHUNK,H=>{if(!X||C.current)return;const le=so(v.current);if(le==="cloud_avatar"||le==="desktop_avatar")return;const pe=Ty(H?.audio);pe&&(ae.feedAudio(pe),s({type:"SET_AUDIO_PLAYING",payload:!0}))}),r.on(ee.AGENT_AUDIO_COMPLETE,()=>{if(!X)return;const H=so(v.current);H==="cloud_avatar"||H==="desktop_avatar"||ae.requestStop()}),r.on(ee.INTERRUPTED,()=>{const H=!ae.isDestroyed();C.current=!1,ae.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),H&&r.connected&&r.emit(ee.AUDIO_PLAYBACK_COMPLETE,{session_id:p.current})}),r.on(ee.HEARTBEAT_ACK,H=>{Z("heartbeat ack",H?.timestamp),s({type:"SET_HEARTBEAT_ACK",payload:H?.timestamp??null})});const he=H=>{F.current.storeCredential(H);const le=H;le?.sessionId&&le?.role&&s({type:"UPDATE_SESSION",payload:{sessionId:le.sessionId,role:le.role}})};r.on(ee.RECONNECT_CREDENTIAL,H=>{Z("received reconnect credential"),he(H)}),r.on(ee.RECONNECT_SUCCESS,H=>{he(H),s({type:"SET_RECONNECT_ATTEMPT",payload:0}),s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_CONNECTION_STATE",payload:mt.CONNECTED}),se.current.onReconnectSuccess?.(H)}),r.on(ee.RECONNECT_FAILED,H=>{Z("reconnect failed",H),s({type:"SET_CONNECTION_STATE",payload:mt.FAILED}),s({type:"SET_ERROR",payload:H?.reason||"Reconnect failed"}),se.current.onReconnectFailed?.(H)}),r.on(ee.AUTH_ERROR,H=>{s({type:"SET_CONNECTION_STATE",payload:mt.FAILED}),s({type:"SET_ERROR",payload:H?.message||"Authentication error"})}),r.on(ee.ERROR,H=>{const le=H?.code;if(le==="TTS_ERROR"){Z("non-fatal TTS error",H);return}if(le==="INSUFFICIENT_CREDITS"){s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:H?.message||"Insufficient credits to process this request."}}),se.current.onError?.(H);return}s({type:"SET_ERROR",payload:H?.message||H?.detail||"Server error"}),se.current.onError?.(H)}),r.on(ee.SESSION_EXPIRED,H=>{Z("session expired",H),s({type:"SET_CONNECTION_STATE",payload:mt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),_e.stop(),se.current.onSessionExpired?.(H)}),r.on(ee.CREDITS_EXHAUSTED,()=>{Z("credits exhausted — disconnecting"),s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:"This project has run out of credits."}}),s({type:"SET_CONNECTION_STATE",payload:mt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),_e.stop(),R.current=!0;try{r.disconnect()}catch{}}),r.on(ee.SESSION_STATE_CHANGED,H=>{H?.state&&(Z("session state changed",H.state),s({type:"SET_SESSION_STATE",payload:H.state}))})}class df{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=((...p)=>{this.off(r,a),s(...p)});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 p of a)try{p(s)}catch{}}removeAllListeners(){this.listeners.clear()}}const cf=ce.createContext(null);function hf({children:d,wsUrl:r,restUrl:s,reconnectOptions:a,enableAudio:p=!0,pcmOptions:v,debug:C=!1,heartbeatIntervalSeconds:R=15,withCredentials:S=!1,onSessionExpired:F,onSessionTerminated:z,onError:ie,onDisconnect:X,onReconnectSuccess:re,onReconnectFailed:se}){const[Z,ee]=ce.useReducer(gp,fo),_e=ce.useRef(Z),ae=ce.useCallback(Ne=>{_e.current=gp(_e.current,Ne),ee(Ne)},[]),he=ce.useRef(!1),H=ce.useRef(_g()),le=ce.useRef(null),pe=ce.useRef(fo.session.agentType),Ve=ce.useRef(!1),me=ce.useRef(new df),Ze=ce.useRef({onSessionExpired:F,onSessionTerminated:z,onError:ie,onDisconnect:X,onReconnectSuccess:re,onReconnectFailed:se});ce.useEffect(()=>{Ze.current={onSessionExpired:F,onSessionTerminated:z,onError:ie,onDisconnect:X,onReconnectSuccess:re,onReconnectFailed:se}},[F,z,ie,X,re,se]),ce.useEffect(()=>{pe.current=Z.session.agentType},[Z.session.agentType]),ce.useEffect(()=>{le.current=Z.session.sessionId},[Z.session.sessionId]);const tt=ce.useCallback(()=>{ae({type:"SET_AUDIO_PLAYING",payload:!1});const Ne=dt.current?.getSocket();Ne?.connected&&Ne.emit(Qt.AUDIO_PLAYBACK_COMPLETE,{session_id:le.current})},[]),{socketMgrRef:dt,audioMgrRef:wt,reconnectMgrRef:lt,sessionMgrRef:yt,heartbeatMgrRef:$t,log:vt}=Sy({wsUrl:r,restUrl:s,reconnectOptions:a,enableAudio:p,pcmOptions:v,debug:C,withCredentials:S,heartbeatIntervalSeconds:R,onPlaybackComplete:tt}),Ye=ce.useCallback(Ne=>{Ey({socket:Ne,dispatch:ae,stateRef:_e,sessionIdRef:le,sessionAgentTypeRef:pe,interruptedRef:Ve,manualDisconnectRef:he,chunkAccumulatorRef:H,reconnectMgrRef:{current:lt.current},heartbeatMgrRef:{current:$t.current},audioMgrRef:{current:wt.current},enableAudio:p,reconnectOptions:a,cbRefs:Ze,log:vt})},[p,a,vt]),St=ce.useCallback(({authPayload:Ne,queryToken:Wt,expectReconnectSuccess:Bt=!1})=>new Promise((cr,Ht)=>{dt.current?.cleanupSocket();const Nt=dt.current.connectSocketRaw({authPayload:Ne,queryToken:Wt});if(Ye(Nt),!Bt)Nt.once("connect",()=>{ae({type:"SET_CONNECTION_STATE",payload:mt.CONNECTED}),ae({type:"SET_ERROR",payload:null}),cr(Nt)}),Nt.once("connect_error",jt=>{ae({type:"SET_CONNECTION_STATE",payload:mt.FAILED}),ae({type:"SET_ERROR",payload:jt?.message||"Connection error"}),Ht(jt)});else{const jt=a?.timeoutMs??8e3,Mr=()=>{Nt.off(Qt.RECONNECT_FAILED,sr),cr(Nt)},sr=ut=>{Nt.off(Qt.RECONNECT_SUCCESS,Mr),Ht(new Error(ut?.reason||"Reconnect failed"))};Nt.once(Qt.RECONNECT_SUCCESS,Mr),Nt.once(Qt.RECONNECT_FAILED,sr),setTimeout(()=>{Nt.off(Qt.RECONNECT_SUCCESS,Mr),Nt.off(Qt.RECONNECT_FAILED,sr),Ht(new Error("Reconnect timed out"))},jt)}}),[Ye,a]);ce.useEffect(()=>{Z.connectionState===mt.RECONNECTING&&a?.enabled!==!1&<.current.tryReconnect({connectSocket:St,onAttempt:Ne=>ae({type:"SET_RECONNECT_ATTEMPT",payload:Ne}),onSuccess:()=>{},onFailure:Ne=>{ae({type:"SET_CONNECTION_STATE",payload:mt.FAILED}),ae({type:"SET_ERROR",payload:Ne}),Ze.current.onReconnectFailed?.({reason:Ne})},isAborted:()=>he.current})},[Z.connectionState,St]);const He=ce.useCallback(({keepManualDisconnect:Ne=!1}={})=>{he.current=!0,lt.current.clearCredential(),Ve.current=!1,H.current.clear(),$t.current.stop(),wt.current.destroyPcmPlayer(),dt.current.cleanupSocket(),Ne||(he.current=!1),ae({type:"HARD_RESET"})},[]),at=ce.useCallback(async({apiKey:Ne,publicChatId:Wt,agentId:Bt,userId:cr,language:Ht="en"}={})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!Ne&&!Wt&&!Bt)throw new Error("Provide one of apiKey, publicChatId, or agentId");He(),ae({type:"SET_CONNECTION_STATE",payload:mt.INITIALIZING}),ae({type:"SET_ERROR",payload:null});let Nt;try{Nt=await yt.current.initializeSession({apiKey:Ne,publicChatId:Wt,agentId:Bt,userId:cr,language:Ht})}catch(sr){const ut=sr;throw(ut.status===401||ut.status===403)&&(ae({type:"SET_CONNECTION_STATE",payload:mt.FAILED}),ae({type:"SET_ERROR",payload:ut.message||"Authentication failed"})),ut.status===402&&(ae({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:ut.message||"Insufficient credits"}}),ae({type:"SET_CONNECTION_STATE",payload:mt.FAILED})),ut.status===429&&(ae({type:"SET_CONNECTION_STATE",payload:mt.FAILED}),ae({type:"SET_ERROR",payload:ut.message||"Too many requests. Please try again later."})),sr}const jt=Nt;ae({type:"UPDATE_SESSION",payload:{sessionId:jt.session_id,agentType:jt.streaming_url?hi.CLOUD_AVATAR:Z.session.agentType,streamingUrl:jt.streaming_url||null,uniqueId:jt.unique_id||null}}),ae({type:"SET_CONNECTION_STATE",payload:mt.CONNECTING}),ae({type:"SET_CLOUD_STREAM_STATE",payload:{state:jt.streaming_url?dr.CONNECTING:dr.IDLE,error:null}});const Mr=bg();he.current=!0;try{await St({authPayload:Mr?{token:jt.session_token,timezone:Mr}:{token:jt.session_token},queryToken:jt.session_token}),he.current=!1}catch(sr){throw he.current=!1,sr}return Nt},[St,He,r,Z.session.agentType]),J=ce.useCallback(async({uniqueId:Ne})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!Ne)throw new Error("uniqueId is required");He(),ae({type:"SET_CONNECTION_STATE",payload:mt.INITIALIZING}),ae({type:"SET_ERROR",payload:null});let Wt;try{Wt=await yt.current.joinDesktopSession({uniqueId:Ne})}catch(cr){const Ht=cr;throw(Ht.status===401||Ht.status===403)&&(ae({type:"SET_CONNECTION_STATE",payload:mt.FAILED}),ae({type:"SET_ERROR",payload:Ht.message||"Authentication failed"})),Ht.status===402&&(ae({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:Ht.message||"Insufficient credits"}}),ae({type:"SET_CONNECTION_STATE",payload:mt.FAILED})),Ht.status===429&&(ae({type:"SET_CONNECTION_STATE",payload:mt.FAILED}),ae({type:"SET_ERROR",payload:Ht.message||"Too many requests. Please try again later."})),cr}const Bt=Wt;ae({type:"UPDATE_SESSION",payload:{sessionId:Bt.session_id,uniqueId:Ne,role:"user",agentType:hi.DESKTOP_AVATAR}}),ae({type:"SET_CONNECTION_STATE",payload:mt.CONNECTING}),ae({type:"SET_CLOUD_STREAM_STATE",payload:{state:dr.IDLE,error:null}}),he.current=!0;try{await St({authPayload:{token:Bt.session_token},queryToken:Bt.session_token}),he.current=!1}catch(cr){throw he.current=!1,cr}return Wt},[St,He,r]),Oe=ce.useCallback(()=>He({keepManualDisconnect:!0}),[He]),it=ce.useCallback(async()=>(Oe(),{success:!0}),[Oe]),Ke=ce.useCallback((Ne,Wt={})=>{const Bt=dt.current?.getSocket();return!Bt||!Z.isConnected?!1:(Bt.emit(Ne,Wt),!0)},[Z.isConnected]),Pe=ce.useCallback(Ne=>!Ne||!String(Ne).trim()?!1:(ae({type:"ADD_MESSAGE",payload:{id:`user-${Date.now()}`,role:"user",text:String(Ne),timestamp:new Date().toISOString()}}),Ke(Qt.USER_MESSAGE,{message:String(Ne)})),[Ke]),ot=ce.useCallback(Ne=>Ke(Qt.AUDIO_CHUNK,{audio:Ne}),[Ke]),Je=ce.useCallback(()=>Ke(Qt.AUDIO_END,{}),[Ke]),We=ce.useCallback(()=>(Ve.current=!0,wt.current.interruptPlayback(),ae({type:"SET_AUDIO_PLAYING",payload:!1}),Ke(Qt.INTERRUPT,{})),[Ke]),xt=ce.useCallback(()=>Ke(Qt.CLEAR_SESSION_HISTORY,{}),[Ke]),et=ce.useCallback(Ne=>Ne?Ke(Qt.CHANGE_SESSION_LANGUAGE,{language:Ne}):!1,[Ke]),vr=ce.useCallback((Ne={})=>Ke(Qt.CLIENT_READY,Ne),[Ke]),qt=ce.useCallback(()=>{H.current.clear(),ae({type:"SET_MESSAGES",payload:[]})},[]),Ot=ce.useCallback(()=>wt.current.resumeAudioPlayback(),[]),ct=ce.useCallback(()=>wt.current.pauseAudioPlayback(),[]),Tt=ce.useCallback(Ne=>wt.current.attachAudioElement(Ne),[]),zt=ce.useCallback((Ne,Wt=null)=>{ae({type:"SET_CLOUD_STREAM_STATE",payload:{state:Ne,error:Wt?String(Wt):null}})},[]),Lt=ce.useMemo(()=>vg(Z.sessionState),[Z.sessionState]),ls=ce.useMemo(()=>({...Z,...Lt,initializeSession:at,joinDesktopSession:J,disconnect:Oe,terminateSession:it,emit:Ke,sendTextMessage:Pe,sendAudioChunk:ot,endAudioStream:Je,interrupt:We,clearSessionHistory:xt,changeSessionLanguage:et,signalClientReady:vr,clearMessages:qt,resumeAudioPlayback:Ot,pauseAudioPlayback:ct,attachAudioElement:Tt,setCloudStreamState:zt,events:me.current,audioElement:wt.current?.getAudioElement()??null,socket:dt.current?.getSocket()??null}),[Z,Lt,at,J,Oe,it,Ke,Pe,ot,Je,We,xt,et,vr,qt,Ot,ct,Tt,zt]);return rr.jsx(cf.Provider,{value:ls,children:d})}function dn(){const d=ce.useContext(cf);if(!d)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return d}function pf(){const d=dn();return{connectionState:d.connectionState,isConnected:d.isConnected,isSessionReady:d.isSessionReady,error:d.error,reconnectAttempt:d.reconnectAttempt,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,initializeSession:d.initializeSession,joinDesktopSession:d.joinDesktopSession,disconnect:d.disconnect,terminateSession:d.terminateSession,interrupt:d.interrupt,clearSessionHistory:d.clearSessionHistory,changeSessionLanguage:d.changeSessionLanguage,signalClientReady:d.signalClientReady}}function $y(){const d=dn();return{messages:d.messages,sendTextMessage:d.sendTextMessage,clearMessages:d.clearMessages}}function xy(){const d=dn();return{sendAudioChunk:d.sendAudioChunk,endAudioStream:d.endAudioStream,isAudioPlaying:d.isAudioPlaying,transcript:d.transcript,partialTranscript:d.partialTranscript,interrupt:d.interrupt,resumeAudioPlayback:d.resumeAudioPlayback,pauseAudioPlayback:d.pauseAudioPlayback,attachAudioElement:d.attachAudioElement}}function ff(){const d=dn(),r=d.cloudStream?.state||dr.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===dr.CONNECTED,isCloudStreamLoading:r===dr.CONNECTING||r===dr.LOADING,setCloudStreamState:d.setCloudStreamState}}var no={},io={},ri={},Tp;function mf(){if(Tp)return ri;Tp=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={},Ep;function Mo(){if(Ep)return si;Ep=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 Kr={},ni={},$p;function pi(){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={},xp;function ji(){if(xp)return ii;xp=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 Cp;function Oo(){if(Cp)return Kr;Cp=1,Object.defineProperty(Kr,"__esModule",{value:!0}),Kr.FrameProcessor=Kr.validateOptions=Kr.defaultFrameProcessorOptions=void 0;const d=pi(),r=ji();Kr.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")}Kr.validateOptions=s;const a=C=>{const R=C.reduce((F,z)=>(F.push(F.at(-1)+z.length),F),[0]),S=new Float32Array(R.at(-1));return C.forEach((F,z)=>{const ie=R[z];S.set(F,ie)}),S};function p(C,R){const S=Math.floor(C.redemptionMs/R),F=Math.floor(C.preSpeechPadMs/R),z=Math.floor(C.minSpeechMs/R);return{redemptionFrames:S,preSpeechPadFrames:F,minSpeechFrames:z}}class v{constructor(R,S,F,z){this.modelProcessFunc=R,this.modelResetFunc=S,this.options=F,this.msPerFrame=z,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=se=>{this.options={...this.options,...se};const{redemptionFrames:Z,preSpeechPadFrames:ee,minSpeechFrames:_e}=p(this.options,this.msPerFrame);this.redemptionFrames=Z,this.preSpeechPadFrames=ee,this.minSpeechFrames=_e},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=se=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(se):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=se=>{const Z=this.audioBuffer;this.audioBuffer=[];const ee=this.speaking;if(this.reset(),ee)if(Z.reduce((ae,he)=>he.isSpeech?ae+1:ae,0)>=this.minSpeechFrames){const ae=a(Z.map(he=>he.frame));se({msg:r.Message.SpeechEnd,audio:ae})}else se({msg:r.Message.VADMisfire});return{}},this.process=async(se,Z)=>{if(!this.active)return;const ee=await this.modelProcessFunc(se),_e=ee.isSpeech>=this.options.positiveSpeechThreshold;if(Z({probs:ee,msg:r.Message.FrameProcessed,frame:se}),this.audioBuffer.push({frame:se,isSpeech:_e}),_e&&(this.speechFrameCount++,this.redemptionCounter=0),_e&&!this.speaking&&(this.speaking=!0,Z({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,Z({msg:r.Message.SpeechRealStart})),ee.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const ae=this.audioBuffer;if(this.audioBuffer=[],ae.reduce((H,le)=>le.isSpeech?H+1:H,0)>=this.minSpeechFrames){const H=a(ae.map(le=>le.frame));Z({msg:r.Message.SpeechEnd,audio:H})}else Z({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:ie,preSpeechPadFrames:X,minSpeechFrames:re}=p(this.options,this.msPerFrame);this.redemptionFrames=ie,this.preSpeechPadFrames=X,this.minSpeechFrames=re,this.reset()}}return Kr.FrameProcessor=v,Kr}var Qr={};function wr(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 ao={exports:{}};/*!
|
|
23
|
+
* ONNX Runtime Web v1.26.0
|
|
24
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
25
|
+
* Licensed under the MIT License.
|
|
26
|
+
*/var kp;function Cy(){return kp||(kp=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,p=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(e=>typeof wr<"u"?wr:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof wr<"u"?wr:t)[n]}):e)(function(e){if(typeof wr<"u")return wr.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),S=(e,t)=>()=>(e&&(t=e(e=0)),t),F=(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=p(t,o))||i.enumerable});return e},ie=e=>z(a({},"__esModule",{value:!0}),e),X,re,se,Z,ee,_e=S(()=>{X=new Map,re=[],se=(e,t,n)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=X.get(e);if(i===void 0)X.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=re.indexOf(e);o!==-1&&re.splice(o,1);for(let l=0;l<re.length;l++)if(X.get(re[l]).priority<=n){re.splice(l,0,e);return}re.push(e)}return}throw new TypeError("not a valid backend")},Z=async e=>{let t=X.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}}},ee=async e=>{let t=e.executionProviders||[],n=t.map(h=>typeof h=="string"?h:h.name),i=n.length===0?re:n,o,l=[],u=new Set;for(let h of i){let f=await Z(h);typeof f=="string"?l.push({name:h,err:f}):(o||(o=f),o===f&&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:f}of l)n.includes(h)&&console.warn(`removing requested execution provider "${h}" from session options because it is not available: ${f}`);let c=t.filter(h=>u.has(typeof h=="string"?h:h.name));return[o,new Proxy(e,{get:(h,f)=>f==="executionProviders"?c:Reflect.get(h,f)})]}}),ae=S(()=>{_e()}),he,H=S(()=>{he="1.26.0"}),le,pe,Ve=S(()=>{H(),le="warning",pe={wasm:{},webgl:{},webgpu:{},versions:{common:he},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}`);le=e}},get logLevel(){return le}},Object.defineProperty(pe,"logLevel",{enumerable:!0})}),me,Ze=S(()=>{Ve(),me=pe}),tt,dt,wt=S(()=>{tt=(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,f;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?f=[0,0,0,0]:typeof c.bias=="number"?f=[c.bias,c.bias,c.bias,c.bias]:(f=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(f[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++]-f[0])*h[0],$=(e.data[w++]-f[1])*h[1],O=(e.data[_++]-f[2])*h[2],I=b===-1?255:(e.data[b++]-f[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")},dt=(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,f,m;h===void 0||h.mean===void 0?f=[255,255,255,255]:typeof h.mean=="number"?f=[h.mean,h.mean,h.mean,h.mean]:(f=[h.mean[0],h.mean[1],h.mean[2],255],h.mean[3]!==void 0&&(f[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])*f[0],i.data[b]=(e.data[$++]-m[1])*f[1],i.data[x]=(e.data[O++]-m[2])*f[2],i.data[M]=I===-1?255:(e.data[I++]-m[3])*f[3]}else throw new Error("Can not access image data");return i}}),lt,yt,$t,vt,Ye,St,He=S(()=>{xt(),lt=(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",f=n*i,m=h==="RGBA"?new Float32Array(f*4):new Float32Array(f*3),g=4,w=0,_=1,b=2,x=3,M=0,k=f,$=f*2,O=-1;c==="RGB"&&(g=3,w=0,_=1,b=2,x=-1),h==="RGBA"?O=f*3:h==="RBG"?(M=0,$=f,k=f*2):h==="BGR"&&($=0,k=f,M=f*2);for(let I=0;I<f;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 We("float32",m,[1,4,n,i]):new We("float32",m,[1,3,n,i])},yt=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")},f=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=f(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 _=f(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=f(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=_,lt(u,c)}else throw new Error("Can not access image data")}else{if(l)return new Promise((m,g)=>{let w=h(),_=f(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(lt(x.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return lt(u,c);throw new Error("Input data provided is not supported - aborted tensor creation")},$t=(e,t)=>{let{width:n,height:i,download:o,dispose:l}=t,u=[1,i,n,4];return new We({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:l})},vt=(e,t)=>{let{dataType:n,dims:i,download:o,dispose:l}=t;return new We({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:i,download:o,dispose:l})},Ye=(e,t)=>{let{dataType:n,dims:i,download:o,dispose:l}=t;return new We({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:i,download:o,dispose:l})},St=(e,t,n)=>new We({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})}),at,J,Oe,it,Ke=S(()=>{at=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),J=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Oe=!1,it=()=>{if(!Oe){Oe=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;e&&(at.set("int64",BigInt64Array),J.set(BigInt64Array,"int64")),t&&(at.set("uint64",BigUint64Array),J.set(BigUint64Array,"uint64")),i?(at.set("float16",n),J.set(n,"float16")):at.set("float16",Uint16Array)}}}),Pe,ot,Je=S(()=>{xt(),Pe=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},ot=(e,t)=>{switch(e.location){case"cpu":return new We(e.type,e.data,t);case"cpu-pinned":return new We({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new We({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new We({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new We({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),We,xt=S(()=>{wt(),He(),Ke(),Je(),We=class{constructor(e,t,n){it();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=at.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=at.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=J.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=Pe(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 yt(e,t)}static fromTexture(e,t){return $t(e,t)}static fromGpuBuffer(e,t){return vt(e,t)}static fromMLTensor(e,t){return Ye(e,t)}static fromPinnedBuffer(e,t,n){return St(e,t,n)}toDataURL(e){return tt(this,e)}toImageData(e){return dt(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return ot(this,e)}}}),et,vr=S(()=>{xt(),et=We}),qt,Ot,ct,Tt,zt,Lt,ls=S(()=>{Ve(),qt=(e,t)=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ot=(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}`),qt("CPU",l);return}n[o].includes("TRACE_FUNC")&&(i=!0)}},ct=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||Ot("BEGIN",e)},Tt=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||Ot("END",e)},zt=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.time(`ORT::${e}`)},Lt=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeEnd(`ORT::${e}`)}}),Ne,Wt=S(()=>{_e(),vr(),ls(),Ne=class gf{constructor(t){this.handler=t}async run(t,n,i){ct(),zt("InferenceSession.run");let o={},l={};if(typeof t!="object"||t===null||t instanceof et||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 et)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 f of n){if(typeof f!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(f)===-1)throw new RangeError(`'fetches' contains invalid output name: ${f}.`);o[f]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let f=!1,m=Object.getOwnPropertyNames(n);for(let g of this.outputNames)if(m.indexOf(g)!==-1){let w=n[g];(w===null||w instanceof et)&&(f=!0,u=!1,o[g]=w)}if(f){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 f of this.inputNames)if(typeof t[f]>"u")throw new Error(`input '${f}' is missing in 'feeds'.`);if(u)for(let f of this.outputNames)o[f]=null;let c=await this.handler.run(t,o,l),h={};for(let f in c)if(Object.hasOwnProperty.call(c,f)){let m=c[f];m instanceof et?h[f]=m:h[f]=new et(m.type,m.data,m.dims)}return Lt("InferenceSession.run"),Tt(),h}async release(){return this.handler.dispose()}static async create(t,n,i,o){ct(),zt("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 ee(u),f=await c.createInferenceSessionHandler(l,h);return Lt("InferenceSession.create"),Tt(),new gf(f)}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}}}),Bt,cr=S(()=>{Wt(),Bt=Ne}),Ht=S(()=>{}),Nt=S(()=>{}),jt=S(()=>{}),Mr=S(()=>{}),sr={};F(sr,{InferenceSession:()=>Bt,TRACE:()=>qt,TRACE_EVENT_BEGIN:()=>zt,TRACE_EVENT_END:()=>Lt,TRACE_FUNC_BEGIN:()=>ct,TRACE_FUNC_END:()=>Tt,Tensor:()=>et,env:()=>me,registerBackend:()=>se});var ut=S(()=>{ae(),Ze(),cr(),vr(),Ht(),Nt(),ls(),jt(),Mr()}),us=S(()=>{}),hn={};F(hn,{default:()=>pn});var ds,cs,pn,Ki=S(()=>{Jh(),nr(),gs(),ds="ort-wasm-proxy-worker",cs=globalThis.self?.name===ds,cs&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":vs(n.wasm).then(()=>{Fa(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;Va(o,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=n,o=Ai(i);postMessage({type:t,out:o});break}case"create":{let{model:i,options:o}=n;qa(i,o).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":Wa(n),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:o,inputs:l,outputIndices:u,options:c}=n;ja(i,o,l,u,new Array(u.length).fill(null),c).then(h=>{h.some(f=>f[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:h},Qa([...l,...h]))},h=>{postMessage({type:t,err:h})});break}case"end-profiling":Ka(n),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),pn=cs?null:e=>new Worker(e??pt,{type:"classic",name:ds})}),fn,mn,pt,hs,Vr,gn,yn,ps,wn,fs,vn,ms,_n,gs=S(()=>{us(),fn=typeof location>"u"?void 0:location.origin,mn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,pt=mn(),hs=()=>{if(pt&&!pt.startsWith("blob:"))return pt.substring(0,pt.lastIndexOf("/")+1)},Vr=(e,t)=>{try{let n=t??pt;return(n?new URL(e,n):new URL(e)).origin===fn}catch{return!1}},gn=(e,t)=>{let n=t??pt;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},yn=(e,t)=>`${t??"./"}${e}`,ps=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},wn=async e=>(await import(e)).default,fs=(Ki(),ie(hn)).default,vn=async()=>{if(!pt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Vr(pt))return[void 0,fs()];let e=await ps(pt);return[e,fs(e)]},ms=void 0,_n=async(e,t,n,i)=>{let o=ms&&!(e||t);if(o)if(pt)o=Vr(pt)||i&&!n;else if(i&&!n)o=!0;else throw new Error("cannot determine the script source URL.");if(o)return[void 0,ms];{let l="ort-wasm-simd-threaded.jsep.mjs",u=e??gn(l,t),c=n&&u&&!Vr(u,t),h=c?await ps(u):u??yn(l,t);return[c?h:void 0,await wn(h)]}}}),ys,Gr,_r,ws,bn,Sn,Tn,vs,De,nr=S(()=>{gs(),Gr=!1,_r=!1,ws=!1,bn=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Sn=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Tn=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},vs=async e=>{if(Gr)return Promise.resolve();if(_r)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ws)throw new Error("previous call to 'initializeWebAssembly()' failed.");_r=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Tn())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Sn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=bn();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=n=1);let o=e.wasmPaths,l=typeof o=="string"?o:void 0,u=o?.mjs,c=u?.href??u,h=o?.wasm,f=h?.href??h,m=e.wasmBinary,[g,w]=await _n(c,l,n>1,!!m||!!f),_=!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(f||l)k.locateFile=$=>f??l+$;else if(c&&c.indexOf("blob:")!==0)k.locateFile=$=>new URL($,c).href;else if(g){let $=hs();$&&(k.locateFile=O=>$+O)}w(k).then($=>{_r=!1,Gr=!0,ys=$,x(),g&&URL.revokeObjectURL(g)},$=>{_r=!1,ws=!0,M($)})})),await Promise.race(b),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},De=()=>{if(Gr&&ys)return ys;throw new Error("WebAssembly is not initialized yet.")}}),Et,qr,Ce,_s=S(()=>{nr(),Et=(e,t)=>{let n=De(),i=n.lengthBytesUTF8(e)+1,o=n._malloc(i);return n.stringToUTF8(e,o,i),t.push(o),o},qr=(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")qr(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=De(),n=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetLastError(o,o+i);let l=Number(t.getValue(o,i===4?"i32":"i64")),u=t.getValue(o+i,"*"),c=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(n)}}}),En,Qi=S(()=>{nr(),_s(),En=e=>{let t=De(),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=Et(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&&qr(e.extra,"",new WeakSet,(u,c)=>{let h=Et(u,i),f=Et(c,i);t._OrtAddRunConfigEntry(n,h,f)!==0&&Ce(`Can't set a run config entry: ${u} - ${c}.`)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseRunOptions(n),i.forEach(u=>t._free(u)),l}}}),$n,xn,Cn,Jt,kn,Rn,Xi=S(()=>{nr(),_s(),$n=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},xn=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Cn=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(e.enableMemPattern=!1)},Jt=(e,t,n,i)=>{let o=Et(t,i),l=Et(n,i);De()._OrtAddSessionConfigEntry(e,o,l)!==0&&Ce(`Can't set a session config entry: ${t} - ${n}.`)},kn=async(e,t,n)=>{let i=t.executionProviders;for(let o of i){let l=typeof o=="string"?o:o.name,u=[];switch(l){case"webnn":if(l="WEBNN",Jt(e,"session.disable_quant_qdq","1",n),Jt(e,"session.disable_qdq_constant_folding","1",n),typeof o!="string"){let g=o?.deviceType;g&&Jt(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}`);Jt(e,"preferredLayout",g.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let c=Et(l,n),h=u.length,f=0,m=0;if(h>0){f=De()._malloc(h*De().PTR_SIZE),n.push(f),m=De()._malloc(h*De().PTR_SIZE),n.push(m);for(let g=0;g<h;g++)De().setValue(f+g*De().PTR_SIZE,u[g][0],"*"),De().setValue(m+g*De().PTR_SIZE,u[g][1],"*")}await De()._OrtAppendExecutionProvider(e,c,f,m,h)!==0&&Ce(`Can't append execution provider: ${l}.`)}},Rn=async e=>{let t=De(),n=0,i=[],o=e||{};Cn(o);try{let l=$n(o.graphOptimizationLevel??"all"),u=xn(o.executionMode??"sequential"),c=typeof o.logId=="string"?Et(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 f=o.logVerbosityLevel??0;if(!Number.isInteger(f)||f<0||f>4)throw new Error(`log verbosity level is not valid: ${f}`);let m=typeof o.optimizedModelFilePath=="string"?Et(o.optimizedModelFilePath,i):0;if(n=t._OrtCreateSessionOptions(l,!!o.enableCpuMemArena,!!o.enableMemPattern,u,!!o.enableProfiling,0,c,h,f,m),n===0&&Ce("Can't create session options."),o.executionProviders&&await kn(n,o,i),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);Jt(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 _=Et(g,i);t._OrtAddFreeDimensionOverride(n,_,w)!==0&&Ce(`Can't set a free dimension override: ${g} - ${w}.`)}return o.extra!==void 0&&qr(o.extra,"",new WeakSet,(g,w)=>{Jt(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}}}),ir,ar,or,bs,Ss,Ts,Es,Vs,Ie=S(()=>{ir=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}`)}},ar=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}`)}},or=(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},bs=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}`)}},Ss=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}`)}},Ts=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Es=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Vs=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),$s,An=S(()=>{us(),$s=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 f=h.byteLength;new Uint8Array(l,u,f).set(h),u+=f}return new Uint8Array(l,0,i)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),In,Gs,qs,Or,Ws,Hs,Qe,hr=S(()=>{Ie(),In=["V","I","W","E","F"],Gs=(e,t)=>{console.log(`[${In[e]},${new Date().toISOString()}]${t}`)},Ws=(e,t)=>{qs=e,Or=t},Hs=(e,t)=>{let n=Ss(e),i=Ss(qs);n>=i&&Gs(n,typeof t=="function"?t():t)},Qe=(...e)=>{Or&&Hs(...e)}}),js,Pr,j,Zr,Ks,Mn,br,ke=S(()=>{js=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Pr=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=js.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],f=o-c<0?1:t[o-c];if(h!==f&&h>1&&f>1)return;let m=Math.max(h,f);if(h&&f)u[l-c]=Math.max(h,f);else{if(m>1)return;u[l-c]=0}}return u}static isValidBroadcast(e,t){let n=e.length,i=t.length;if(n>i)return!1;for(let o=1;o<=n;o++)if(e[n-o]!==1&&e[n-o]!==t[i-o])return!1;return!0}},j=class Fi{static size(t){return Fi.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 Fi.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 Fi.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])}},Zr=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 f=0;f<n.length-2;f++)i.push(1);else for(let f=0;f<n.length-2;f++)i.push(di.adjustPadAndReturnShape(n[f+2],o[f],l[f],u[f],c,f,f+n.length-2,h))}static adjustPadAndReturnShape(t,n,i,o,l,u,c,h){let f=i*(o-1)+1;if(h&&h!=="NOTSET")switch(h){case"VALID":return l[u]=0,l[c]=0,Math.floor((t-f)/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]-f)/n+1)}},Ks=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&&!Pr.isValidBroadcast(o,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,u]}},Mn=-34028234663852886e22,br=34028234663852886e22}),Dr,es=S(()=>{Ie(),Dr=(e,t)=>new(bs(t))(e)}),Wr,ts,xs,Cs,Sr,zr,Qs,Xs,Ys,On,Pn,mi=S(()=>{Ie(),hr(),Wr=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),ts=(e,t)=>{if(t==="int32")return e;let n=Wr.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(bs(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'`)}},xs=(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}`)}},Cs=1,Sr=()=>Cs++,zr=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Qs=(e,t)=>{let n=Wr.get(e);if(!n)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,o)=>i*o)*n/8):0},Xs=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:i,dataType:o,shape:l,fallbackDataType:u}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=i,this.dataType=o,this.tensorShape=l,this.fallbackDataType=u}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Qs(this.dataType,this.tensorShape)}destroy(){Qe("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=xs(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return n.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((i,o)=>i===n[o])}setIsDataConverted(e){this.isDataConverted=e}},Ys=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,i){let o=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),u;if(!l?.input.dataTypes.includes(t)){if(u=zr.get(t),!u||l?.input.dataTypes.includes(u))throw new Error(`WebNN backend does not support data type: ${t}`);Qe("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${u}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(o,t,n))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==Qs(t,n))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let c=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,c,!0,!0,u),i&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=ts(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 Qe("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?xs(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()}},On=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=Sr();return this.tensorTrackersById.set(e,new Ys(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,i,o){Qe("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){Qe("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=Sr(),u=new Xs({sessionId:e,context:o,tensor:t,dataType:n,shape:i});return this.tensorTrackersById.set(l,new Ys(this,u)),this.externalTensors.add(u),l}async getCachedTensor(e,t,n,i,o,l,u){let c=this.getMLContext(e);for(let[f,m]of this.freeTensors.entries())if(m.canReuseTensor(c,t,n)){Qe("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${n}`);let g=this.freeTensors.splice(f,1)[0];return g.sessionId=e,g}Qe("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${n}}`);let h=await c.createTensor({dataType:u??t,shape:n,dimensions:n,usage:i,writable:o,readable:l});return new Xs({sessionId:e,context:c,tensor:h,dataType:t,shape:n,fallbackDataType:u})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Pn=(...e)=>new On(...e)}),rs,Dn,zn,Ln=S(()=>{Ie(),nr(),es(),mi(),hr(),rs=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Dn=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),i=Object.keys(t).sort();return n.length===i.length&&n.every((o,l)=>o===i[l]&&e[o]===t[o])},zn=class{constructor(e){this.tensorManager=Pn(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,Ws(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Qe("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Qe("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let n of t)Qe("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${n}}`),this.tensorManager.releaseTensorId(n);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let n=this.mlContextCache.findIndex(i=>i.gpuDevice===e);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:i}),i}}else if(e===void 0){let n=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let t=this.mlContextCache.findIndex(n=>Dn(n.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:n}),n}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let i=this.mlContextCache.findIndex(o=>o.mlContext===t);i!==-1&&this.mlContextCache.splice(i,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Qe("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,i,o){let l=rs.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){Qe("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let i=rs.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(!De().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Qe("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 Dr(n,t)}}registerMLTensor(e,t,n,i){let o=rs.get(n);if(!o)throw new Error(`Unsupported ONNX data type: ${n}`);let l=this.tensorManager.registerTensor(e,t,o,i);return Qe("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 f=h.slice(t,t+n).buffer,m;switch(o.dataType){case"float32":m=new Float32Array(f);break;case"float16":m=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(f):new Uint16Array(f);break;case"int32":m=new Int32Array(f);break;case"uint32":m=new Uint32Array(f);break;case"int64":if(u){let g=ts(new Uint8Array(f),"int64");m=new Int32Array(g.buffer),o.dataType="int32"}else m=new BigInt64Array(f);break;case"uint64":m=new BigUint64Array(f);break;case"int8":m=new Int8Array(f);break;case"int4":case"uint4":case"uint8":m=new Uint8Array(f);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return Qe("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=rs.get(ir(t)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:n?!!o?.input.dataTypes.includes(i):!!o?.output.dataTypes.includes(i)}flush(){}}}),Js=S(()=>{}),Zs,en,ks,tn,rn,sn,Bn,Nn,gi,Yi=S(()=>{hr(),Js(),Zs=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),en=[],ks=e=>Math.ceil(Number(e)/16)*16,tn=e=>{for(let t=0;t<en.length;t++){let n=en[t];if(e<=n)return n}return Math.ceil(e/16)*16},rn=1,sn=()=>rn++,Bn=async(e,t,n,i)=>{let o=ks(n),l=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let u=e.getCommandEncoder();e.endComputePass(),u.copyBufferToBuffer(t,0,l,0,o),e.flush(),await l.mapAsync(GPUMapMode.READ);let c=l.getMappedRange();if(i){let h=i();return h.set(new Uint8Array(c,0,n)),h}else return new Uint8Array(c.slice(0,n))}finally{l.destroy()}},Nn=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of Zs)en.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,i=t.byteOffset,o=t.byteLength,l=ks(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 f=this.backend.device.createCommandEncoder();f.copyBufferToBuffer(c,0,u.gpuData.buffer,0,l),this.backend.device.queue.submit([f.finish()]),c.destroy(),Qe("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=ks(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 Qe("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.
|
|
27
|
+
Please use the previous external buffer!`)}else i=sn();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:t}),Qe("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Qe("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=tn(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:sn(),type:0,buffer:i};return this.storageCache.set(u.id,{gpuData:u,originalSize:Number(e)}),Qe("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 Qe("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw new Error("data does not exist");await Bn(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=Zs.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&&(Qe("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},gi=(...e)=>new Nn(...e)}),y,E,A=S(()=>{y=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},E=e=>new y(e)}),D,P,G,N,L,V,ne,oe,Y,K,Te,U,de,ft,Ue,Ee,Fe,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]},N=(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:j.computeStrides(n)})}),t},V=e=>e%4===0?4:e%2===0?2:1,ne=(e="f32",t,n="0")=>!t||t===1?`${e}(${n})`:`vec${t}<${e}>(${n})`,oe=(e,t,n)=>e==="f32"?n:t===1?`f32(${n})`:`vec${t}<f32>(${n})`,Y=(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,K=(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}>`,f=P(t,o),m=typeof f=="string"?f:f[1],g=typeof f=="string"?f:f[0],w={indices:h,value:m,storage:g,tensor:t},_=ue=>typeof ue=="string"?ue:`${ue}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 ue=0;ue<u-1;ue++)$+=`
|
|
28
|
+
let dim${ue} = current / ${K(k,ue,u)};
|
|
29
|
+
let rest${ue} = current % ${K(k,ue,u)};
|
|
30
|
+
indices[${ue}] = dim${ue};
|
|
31
|
+
current = rest${ue};
|
|
32
|
+
`;$+=`indices[${u-1}] = current;`;let O=u<2?"":`
|
|
33
|
+
fn o2i_${e}(offset: u32) -> ${w.indices} {
|
|
34
|
+
var indices: ${w.indices};
|
|
35
|
+
var current = offset;
|
|
36
|
+
${$}
|
|
37
|
+
return indices;
|
|
38
|
+
}`,I=ue=>(b.offsetToIndices=!0,u<2?ue:`o2i_${e}(${ue})`),B=[];if(u>=2)for(let ue=u-1;ue>=0;ue--)B.push(`${K(k,ue,u)} * (indices[${ue}])`);let q=u<2?"":`
|
|
39
|
+
fn i2o_${e}(indices: ${w.indices}) -> u32 {
|
|
40
|
+
return ${B.join("+")};
|
|
41
|
+
}`,W=ue=>(b.indicesToOffset=!0,u<2?ue:`i2o_${e}(${ue})`),te=(...ue)=>u===0?"0u":`${w.indices}(${ue.map(_).join(",")})`,fe=(ue,ze)=>u<2?`${ue}`:`${K(ue,ze,u)}`,be=(ue,ze,Ae)=>u<2?`${ue}=${Ae};`:`${K(ue,ze,u)}=${Ae};`,qe={},Re=(ue,ze)=>{b.broadcastedIndicesToOffset=!0;let Ae=`${ze.name}broadcastedIndicesTo${e}Offset`;if(Ae in qe)return`${Ae}(${ue})`;let $e=[];for(let Kt=u-1;Kt>=0;Kt--){let lr=ze.indicesGet("outputIndices",Kt+ze.rank-u);$e.push(`${fe(k,Kt)} * (${lr} % ${fe(M,Kt)})`)}return qe[Ae]=`fn ${Ae}(outputIndices: ${ze.type.indices}) -> u32 {
|
|
42
|
+
return ${$e.length>0?$e.join("+"):"0u"};
|
|
43
|
+
}`,`${Ae}(${ue})`},Me=(ue,ze)=>(()=>{if(w.storage===w.value)return`${e}[${ue}]=${ze};`;if(w.storage==="vec2<u32>"&&w.value==="i32")return`${e}[${ue}]=vec2<u32>(u32(${ze}), select(0u, 0xFFFFFFFFu, ${ze} < 0));`;if(w.storage==="vec2<u32>"&&w.value==="u32")return`${e}[${ue}]=vec2<u32>(u32(${ze}), 0u);`;if(w.storage==="u32"&&w.value==="vec4<bool>")return`${e}[${ue}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${ze}));`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),rt=ue=>(()=>{if(w.storage===w.value)return`${e}[${ue}]`;if(w.storage==="vec2<u32>"&&w.value==="i32")return`i32(${e}[${ue}].x)`;if(w.storage==="vec2<u32>"&&w.value==="u32")return`u32(${e}[${ue}].x)`;if(w.storage==="u32"&&w.value==="vec4<bool>")return`vec4<bool>(bool(${e}[${ue}] & 0xFFu), bool(${e}[${ue}] & 0xFF00u), bool(${e}[${ue}] & 0xFF0000u), bool(${e}[${ue}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),ye=u<2?"":`
|
|
44
|
+
fn get_${e}ByIndices(indices: ${w.indices}) -> ${m} {
|
|
45
|
+
return ${rt(`i2o_${e}(indices)`)};
|
|
46
|
+
}`,xe=u<2?"":(()=>{let ue=c.map(Ae=>`d${Ae}: u32`).join(", "),ze=c.map(Ae=>`d${Ae}`).join(", ");return`
|
|
47
|
+
fn get_${e}(${ue}) -> ${m} {
|
|
48
|
+
return get_${e}ByIndices(${te(ze)});
|
|
49
|
+
}`})(),Be=(...ue)=>{if(ue.length!==u)throw new Error(`indices length must be ${u}`);let ze=ue.map(_).join(",");return u===0?rt("0u"):u===1?rt(ze[0]):(b.get=!0,b.getByIndices=!0,b.indicesToOffset=!0,`get_${e}(${ze})`)},je=ue=>u<2?rt(ue):(b.getByIndices=!0,b.indicesToOffset=!0,`get_${e}ByIndices(${ue})`),Le=u<2?"":`
|
|
50
|
+
fn set_${e}ByIndices(indices: ${w.indices}, value: ${m}) {
|
|
51
|
+
${Me(`i2o_${e}(indices)`,"value")}
|
|
52
|
+
}`,Xe=u<2?"":(()=>{let ue=c.map(Ae=>`d${Ae}: u32`).join(", "),ze=c.map(Ae=>`d${Ae}`).join(", ");return`
|
|
53
|
+
fn set_${e}(${ue}, value: ${m}) {
|
|
54
|
+
set_${e}ByIndices(${te(ze)}, value);
|
|
55
|
+
}`})();return{impl:()=>{let ue=[],ze=!1;return b.offsetToIndices&&(ue.push(O),ze=!0),b.indicesToOffset&&(ue.push(q),ze=!0),b.broadcastedIndicesToOffset&&(Object.values(qe).forEach(Ae=>ue.push(Ae)),ze=!0),b.set&&(ue.push(Xe),ze=!0),b.setByIndices&&(ue.push(Le),ze=!0),b.get&&(ue.push(xe),ze=!0),b.getByIndices&&(ue.push(ye),ze=!0),!l&&ze&&ue.unshift(`const ${M} = ${w.indices}(${n.join(",")});`,`const ${k} = ${w.indices}(${j.computeStrides(n).join(",")});`),ue.join(`
|
|
56
|
+
`)},type:w,offsetToIndices:I,indicesToOffset:W,broadcastedIndicesToOffset:Re,indices:te,indicesGet:fe,indicesSet:be,set:(...ue)=>{if(ue.length!==u+1)throw new Error(`indices length must be ${u}`);let ze=ue[u];if(typeof ze!="string")throw new Error("value must be string");let Ae=ue.slice(0,u).map(_).join(",");return u===0?Me("0u",ze):u===1?Me(Ae[0],ze):(b.set=!0,b.setByIndices=!0,b.indicesToOffset=!0,`set_${e}(${Ae}, ${ze})`)},setByOffset:Me,setByIndices:(ue,ze)=>u<2?Me(ue,ze):(b.setByIndices=!0,b.indicesToOffset=!0,`set_${e}ByIndices(${ue}, ${ze});`),get:Be,getByOffset:rt,getByIndices:je,usage:i,name:e,strides:k,shape:M,rank:u}},U=(e,t,n,i=1)=>Te(e,t,n,"input",i),de=(e,t,n,i=1)=>Te(e,t,n,"output",i),ft=(e,t,n)=>Te(e,t,n,"atomicOutput",1),Ue=(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>,
|
|
57
|
+
@builtin(workgroup_id) workgroup_id : vec3<u32>,
|
|
58
|
+
@builtin(local_invocation_index) local_idx : u32,
|
|
59
|
+
@builtin(local_invocation_id) local_id : vec3<u32>`:`@builtin(global_invocation_id) global_id : vec3<u32>,
|
|
60
|
+
@builtin(local_invocation_id) local_id : vec3<u32>,
|
|
61
|
+
@builtin(local_invocation_index) local_idx : u32,
|
|
62
|
+
@builtin(workgroup_id) workgroup_id : vec3<u32>,
|
|
63
|
+
@builtin(num_workgroups) num_workgroups : vec3<u32>`,u=o?`let global_idx = global_id.x;
|
|
64
|
+
let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +
|
|
65
|
+
workgroup_id.y * num_workgroups[0] + workgroup_id.x;
|
|
66
|
+
let global_idx = workgroup_index * ${t*n*i}u + local_idx;`;return`@compute @workgroup_size(${t}, ${n}, ${i})
|
|
67
|
+
fn main(${l}) {
|
|
68
|
+
${u}
|
|
69
|
+
`}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let n=e.usage==="input"?"read":"read_write",i=e.usage==="atomicOutput"?"atomic<i32>":e.type.storage;return`@group(0) @binding(${t}) var<storage, ${n}> ${e.name}: array<${i}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(`
|
|
70
|
+
`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,n=1){return this.uniforms.push({name:e,type:t,length:n}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:n,length:i}of this.uniforms)if(i&&i>4)n==="f16"?e.push(`@align(16) ${t}:array<mat2x4<${n}>, ${Math.ceil(i/8)}>`):e.push(`${t}:array<vec4<${n}>, ${Math.ceil(i/4)}>`);else{let o=i==null||i===1?n:`vec${i}<${n}>`;e.push(`${t}:${o}`)}return`
|
|
71
|
+
struct Uniforms { ${e.join(", ")} };
|
|
72
|
+
@group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(`
|
|
73
|
+
`)+this.internalVariables.map(e=>e.impl()).join(`
|
|
74
|
+
`)}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])}},Fe=(e,t)=>new Ee(e,t)}),Ut,Ft,Lr,ss,nn,Un,_t,fr,Fn,Ge=S(()=>{Ie(),ke(),A(),we(),Ut=(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}`)},Ft=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),Lr=(e,t)=>j.sortBasedOnPerm(e,Ft(e.length,t)),ss=(e,t,n,i)=>{let o=`fn perm(i: ${i.type.indices}) -> ${n.type.indices} {
|
|
75
|
+
var a: ${n.type.indices};`;for(let l=0;l<t;++l)o+=`a[${e[l]}]=i[${l}];`;return o+="return a;}"},nn=(e,t)=>{let n=[],i=[];for(let o=0;o<e.length;++o)e[o]!==1&&n.push(e[o]),e[t[o]]!==1&&i.push(t[o]);return{newShape:n,newPerm:i}},Un=(e,t)=>{let n=0;for(let i=0;i<e.length;++i)if(t[e[i]]!==1){if(e[i]<n)return!1;n=e[i]}return!0},_t=(e,t)=>{let n=e.dataType,i=e.dims.length,o=Ft(i,t),l=Lr(e.dims,o),u=e.dims,c=l,h=i<2||Un(o,e.dims),f;if(h)return f=b=>{let x=U("input",n,u,4),M=de("output",n,c,4);return`
|
|
76
|
+
${b.registerUniform("output_size","u32").declareVariables(x,M)}
|
|
77
|
+
${b.mainStart()}
|
|
78
|
+
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
79
|
+
output[global_idx] = input[global_idx];
|
|
80
|
+
}`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let b=j.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:f};let{newShape:m,newPerm:g}=nn(e.dims,o),w=j.areEqual(g,[2,3,1]),_=j.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 f=x=>{let M=U("a",n,u.length),k=de("output",n,c.length);return`
|
|
81
|
+
${x.registerUniform("output_size","u32").declareVariables(M,k)}
|
|
82
|
+
var<workgroup> tile : array<array<${k.type.value}, ${b+1}>, ${b}>;
|
|
83
|
+
${x.mainStart([b,b,1])}
|
|
84
|
+
let stride = (uniforms.output_shape[1] - 1) / ${b} + 1;
|
|
85
|
+
let workgroup_id_x = workgroup_index % stride;
|
|
86
|
+
let workgroup_id_y = workgroup_index / stride;
|
|
87
|
+
let input_col = workgroup_id_y * ${b}u + local_id.x;
|
|
88
|
+
let input_row = workgroup_id_x * ${b}u + local_id.y;
|
|
89
|
+
if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {
|
|
90
|
+
tile[local_id.y][local_id.x] = ${M.getByIndices(`${M.type.indices}(input_row, input_col)`)};
|
|
91
|
+
}
|
|
92
|
+
workgroupBarrier();
|
|
93
|
+
|
|
94
|
+
let output_col = workgroup_id_x * ${b}u + local_id.x;
|
|
95
|
+
let output_row = workgroup_id_y * ${b}u + local_id.y;
|
|
96
|
+
if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {
|
|
97
|
+
${k.setByIndices(`${k.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")}
|
|
98
|
+
}
|
|
99
|
+
}`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let x=j.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:f}}return f=b=>{let x=U("a",n,u.length),M=de("output",n,c.length);return`
|
|
100
|
+
${b.registerUniform("output_size","u32").declareVariables(x,M)}
|
|
101
|
+
|
|
102
|
+
${ss(o,i,x,M)}
|
|
103
|
+
|
|
104
|
+
${b.mainStart()}
|
|
105
|
+
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
106
|
+
|
|
107
|
+
let indices = ${M.offsetToIndices("global_idx")};
|
|
108
|
+
let aIndices = perm(indices);
|
|
109
|
+
|
|
110
|
+
${M.setByOffset("global_idx",x.getByIndices("aIndices"))}
|
|
111
|
+
}`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let b=j.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:[{type:12,data:b},...L(u,c)]}},getShaderSource:f}},fr=(e,t)=>{Ut(e.inputs,t.perm),e.compute(_t(e.inputs[0],t.perm))},Fn=e=>E({perm:e.perm})}),pr,yi,Tr,Rs,Ct,Yt,an,As,Vn,wi,Pt,Er,ns,kt,bt,mr,vi,_i,Po,Do,zo,vm=S(()=>{Ie(),ke(),we(),Zi(),Ge(),pr={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"},yi={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"},Tr={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Rs={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Ct=(e,t)=>{let n=[];for(let i=t-e;i<t;++i)n.push(i);return n},Yt=(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]},an=(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},As=(e,t)=>{for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0},Vn=(e,t)=>{let n=[];if(!As(e,t)){for(let i=0;i<t;++i)e.indexOf(i)===-1&&n.push(i);e.forEach(i=>n.push(i))}return n},wi=(e,t,n,i,o,l,u)=>{let c=n[0].dims,h=j.size(l),f=j.size(u),m=U("_A",n[0].dataType,c),g=de("output",o,l),w=64;h===1&&(w=256);let _=`
|
|
112
|
+
var<workgroup> aBestValues : array<f32, ${w}>;
|
|
113
|
+
`,b=x=>`
|
|
114
|
+
${x.registerUniform("reduceSize","u32").declareVariables(m,g)}
|
|
115
|
+
${_}
|
|
116
|
+
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
117
|
+
return ((a - 1u) / b + 1u);
|
|
118
|
+
}
|
|
119
|
+
${x.mainStart(w)}
|
|
120
|
+
|
|
121
|
+
let outputIndex = global_idx / ${w};
|
|
122
|
+
let offset = outputIndex * uniforms.reduceSize;
|
|
123
|
+
|
|
124
|
+
var bestValue = f32(${Tr[i]});
|
|
125
|
+
let Length = uniforms.reduceSize;
|
|
126
|
+
for (var k = local_idx; k < Length; k = k + ${w}) {
|
|
127
|
+
let candidate = f32(${m.getByOffset("offset + k")});
|
|
128
|
+
bestValue = ${pr[i]};
|
|
129
|
+
}
|
|
130
|
+
aBestValues[local_idx] = bestValue;
|
|
131
|
+
workgroupBarrier();
|
|
132
|
+
|
|
133
|
+
var reduceSize = min(Length, ${w}u);
|
|
134
|
+
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
|
|
135
|
+
currentSize = reduceSize / 2u) {
|
|
136
|
+
let interval = DIV_CEIL(reduceSize, 2u);
|
|
137
|
+
if (local_idx < currentSize) {
|
|
138
|
+
let candidate = aBestValues[local_idx + interval];
|
|
139
|
+
bestValue = ${yi[i]};
|
|
140
|
+
aBestValues[local_idx] = bestValue;
|
|
141
|
+
}
|
|
142
|
+
reduceSize = interval;
|
|
143
|
+
workgroupBarrier();
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (local_idx == 0u) {
|
|
147
|
+
${g.setByOffset("outputIndex",`${i==="mean"?`${g.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${g.type.storage}(${Rs[i]})`}`)};
|
|
148
|
+
}
|
|
149
|
+
}`;return{name:e,shaderCache:{hint:`${t};${w}`,inputDependencies:["type"]},getShaderSource:b,getRunData:()=>({outputs:[{dims:l,dataType:o}],dispatchGroup:{x:h},programUniforms:[{type:12,data:f}]})}},Pt=(e,t,n,i)=>{let o=e.inputs.length===1?n:Ji(e.inputs,n),l=o.axes;l.length===0&&!o.noopWithEmptyAxes&&(l=e.inputs[0].dims.map((_,b)=>b));let u=j.normalizeAxes(l,e.inputs[0].dims.length),c=u,h=e.inputs[0],f=Vn(c,e.inputs[0].dims.length);f.length>0&&(h=e.compute(_t(e.inputs[0],f),{inputs:[0],outputs:[-1]})[0],c=Ct(c.length,h.dims.length));let[m,g]=Yt(h.dims,c),w=m;o.keepDims&&(w=an(m,u)),e.compute(wi(t,o.cacheKey,[h],i,e.inputs[0].dataType,w,g),{inputs:[h]})},Er=(e,t)=>{Pt(e,"ReduceMeanShared",t,"mean")},ns=(e,t)=>{Pt(e,"ReduceL1Shared",t,"l1")},kt=(e,t)=>{Pt(e,"ReduceL2Shared",t,"l2")},bt=(e,t)=>{Pt(e,"ReduceLogSumExpShared",t,"logSumExp")},mr=(e,t)=>{Pt(e,"ReduceMaxShared",t,"max")},vi=(e,t)=>{Pt(e,"ReduceMinShared",t,"min")},_i=(e,t)=>{Pt(e,"ReduceProdShared",t,"prod")},Po=(e,t)=>{Pt(e,"ReduceSumShared",t,"sum")},Do=(e,t)=>{Pt(e,"ReduceSumSquareShared",t,"sumSquare")},zo=(e,t)=>{Pt(e,"ReduceLogSumShared",t,"logSum")}}),$r,Lo,bi,Ji,xr,Bo,No,Uo,Fo,Vo,Go,qo,Wo,Ho,jo,Cr,Ko,Qo,Xo,Yo,Jo,Zo,el,tl,rl,sl,Zi=S(()=>{Ie(),ke(),A(),we(),vm(),$r=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.")},Lo=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],bi=(e,t,n,i,o,l,u=!1,c=!1)=>{let h=[],f=n[0].dims,m=f.length,g=j.normalizeAxes(o,m),w=!c&&g.length===0;f.forEach((x,M)=>{w||g.indexOf(M)>=0?u&&h.push(1):h.push(x)});let _=h.length,b=j.size(h);return{name:e,shaderCache:t,getShaderSource:x=>{let M=[],k=U("_A",n[0].dataType,m),$=de("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} < ${f[B]}; j${B}++) {
|
|
150
|
+
${O[2].includes("last_index")?`let last_index = j${B};`:""}
|
|
151
|
+
${k.indicesSet("input_indices",B,`j${B}`)}
|
|
152
|
+
${I}
|
|
153
|
+
}`):(M.push(`${k.indicesSet("input_indices",B,$.indicesGet("output_indices",q))};`),q++);return`
|
|
154
|
+
|
|
155
|
+
${x.registerUniform("output_size","u32").declareVariables(k,$)}
|
|
156
|
+
|
|
157
|
+
${x.mainStart()}
|
|
158
|
+
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
159
|
+
var input_indices: ${k.type.indices};
|
|
160
|
+
let output_indices = ${$.offsetToIndices("global_idx")};
|
|
161
|
+
|
|
162
|
+
${M.join(`
|
|
163
|
+
`)}
|
|
164
|
+
${O[0]} // init ops for reduce max/min
|
|
165
|
+
${O[1]}
|
|
166
|
+
${I}
|
|
167
|
+
${O[3]}
|
|
168
|
+
${O.length===4?$.setByOffset("global_idx","value"):O.slice(4).join(`
|
|
169
|
+
`)}
|
|
170
|
+
}`},getRunData:()=>({outputs:[{dims:h,dataType:l}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:[{type:12,data:b},...L(f,h)]})}},Ji=(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})},xr=(e,t,n,i)=>{let o=e.inputs,l=o.length===1?n:Ji(o,n);e.compute(bi(t,{hint:l.cacheKey,inputDependencies:["rank"]},[o[0]],l.noopWithEmptyAxes&&l.axes.length===0?Lo:i,l.axes,o[0].dataType,l.keepDims,l.noopWithEmptyAxes),{inputs:[0]})},Bo=(e,t)=>{$r(e.inputs),xr(e,"ReduceLogSum",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},No=(e,t)=>{$r(e.inputs),xr(e,"ReduceL1",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},Uo=(e,t)=>{$r(e.inputs),xr(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);"])},Fo=(e,t)=>{$r(e.inputs),xr(e,"ReduceLogSumExp",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},Vo=(e,t)=>{$r(e.inputs),xr(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(`
|
|
171
|
+
`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},Go=(e,t)=>{$r(e.inputs),xr(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});`]})},qo=(e,t)=>{$r(e.inputs),xr(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(`
|
|
172
|
+
`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},Wo=(e,t)=>{$r(e.inputs),xr(e,"ReduceProd",t,(n,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},Ho=(e,t)=>{$r(e.inputs),xr(e,"ReduceSum",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},jo=(e,t)=>{$r(e.inputs),xr(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;`,""])},Cr=(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},Ko=(e,t)=>{Cr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Go(e,t):Er(e,t)},Qo=(e,t)=>{Cr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?No(e,t):ns(e,t)},Xo=(e,t)=>{Cr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Uo(e,t):kt(e,t)},Yo=(e,t)=>{Cr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fo(e,t):bt(e,t)},Jo=(e,t)=>{Cr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Vo(e,t):mr(e,t)},Zo=(e,t)=>{Cr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qo(e,t):vi(e,t)},el=(e,t)=>{Cr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Wo(e,t):_i(e,t)},tl=(e,t)=>{Cr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ho(e,t):Po(e,t)},rl=(e,t)=>{Cr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?jo(e,t):Do(e,t)},sl=(e,t)=>{Cr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bo(e,t):zo(e,t)}}),ea,nl,il,ta,_m=S(()=>{Ie(),A(),Zi(),ea=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.")},nl=(e,t)=>{ea(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(`
|
|
173
|
+
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
174
|
+
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {
|
|
175
|
+
value = ${i.getByIndices("input_indices")};
|
|
176
|
+
best_index = i32(last_index);
|
|
177
|
+
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(bi("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},il=(e,t)=>{ea(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(`
|
|
178
|
+
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
179
|
+
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {
|
|
180
|
+
value = ${i.getByIndices("input_indices")};
|
|
181
|
+
best_index = i32(last_index);
|
|
182
|
+
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(bi("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},ta=e=>E(e)}),al,Si,ol,ll,ul,Gn,dl,cl,ra=S(()=>{Ie(),ke(),Js(),we(),al=(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],f=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=f;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]!==f||c.dims[3]!==M)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:h,sequenceLength:f,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}},Si=(e,t,n)=>t&&e?`
|
|
183
|
+
let total_sequence_length_input = u32(${t.getByOffset("0")});
|
|
184
|
+
let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);
|
|
185
|
+
let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;
|
|
186
|
+
let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;
|
|
187
|
+
total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1;
|
|
188
|
+
var past_sequence_length: u32 = 0;
|
|
189
|
+
if (is_first_prompt == false) {
|
|
190
|
+
past_sequence_length = total_sequence_length - sequence_length;
|
|
191
|
+
}
|
|
192
|
+
`:`
|
|
193
|
+
${n?"let past_sequence_length = uniforms.past_sequence_length":""};
|
|
194
|
+
let present_sequence_length = total_sequence_length;
|
|
195
|
+
`,ol=(e,t,n,i,o,l,u,c)=>{let h=V(u?1:l),f=64,m=l/h;m<f&&(f=32);let g=Math.ceil(l/h/f),w=[{type:12,data:t},{type:12,data:n},{type:12,data:i},{type:12,data:o},{type:12,data:m},{type:12,data:g}],_=G(e.dataType,h),b=N(1,h),x=["type"];u&&x.push("type"),c&&x.push("type");let M=k=>{let $=de("x",e.dataType,e.dims,h),O=[$],I=u?U("seq_lens",u.dataType,u.dims):void 0;I&&O.push(I);let B=c?U("total_sequence_length_input",c.dataType,c.dims):void 0;B&&O.push(B);let q=N(e.dataType),W=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return`
|
|
196
|
+
var<workgroup> thread_max: array<f32, ${f}>;
|
|
197
|
+
var<workgroup> thread_sum: array<f32, ${f}>;
|
|
198
|
+
${k.registerUniforms(W).declareVariables(...O)}
|
|
199
|
+
${k.mainStart([f,1,1])}
|
|
200
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
201
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
202
|
+
let sequence_length = uniforms.sequence_length;
|
|
203
|
+
var total_sequence_length = uniforms.total_sequence_length;
|
|
204
|
+
${Si(I,B,!1)}
|
|
205
|
+
let local_offset = local_idx * uniforms.elements_per_thread;
|
|
206
|
+
let offset = (global_idx / ${f}) * uniforms.total_sequence_length + local_offset;
|
|
207
|
+
let seq_causal_length = ${u?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"};
|
|
208
|
+
var thread_max_vector = ${b}(-3.4028234663852886e+38f);
|
|
209
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
210
|
+
thread_max_vector = max(${b}(x[offset + i]), thread_max_vector);
|
|
211
|
+
}
|
|
212
|
+
thread_max[local_idx] = ${(()=>{switch(h){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${h}`)}})()};
|
|
213
|
+
workgroupBarrier();
|
|
214
|
+
|
|
215
|
+
var max_value = f32(-3.4028234663852886e+38f);
|
|
216
|
+
for (var i = 0u; i < ${f}; i++) {
|
|
217
|
+
max_value = max(thread_max[i], max_value);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
var sum_vector = ${b}(0);
|
|
221
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
222
|
+
sum_vector += exp(${b}(x[offset + i]) - max_value);
|
|
223
|
+
}
|
|
224
|
+
thread_sum[local_idx] = ${(()=>{switch(h){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${h}`)}})()};
|
|
225
|
+
workgroupBarrier();
|
|
226
|
+
|
|
227
|
+
var sum: f32 = 0;
|
|
228
|
+
for (var i = 0u; i < ${f}; i++) {
|
|
229
|
+
sum += thread_sum[i];
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (sum == 0) {
|
|
233
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
234
|
+
x[offset + i] = ${$.type.value}(${q}(1.0) / ${q}(seq_causal_length));
|
|
235
|
+
}
|
|
236
|
+
} else {
|
|
237
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
238
|
+
var f32input = ${b}(x[offset + i]);
|
|
239
|
+
x[offset + i] = ${$.type.value}(exp(f32input - max_value) / sum);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
${u?`
|
|
243
|
+
for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {
|
|
244
|
+
x[offset + total_seq_id] = ${$.type.value}(${q}(0));
|
|
245
|
+
}`:""};
|
|
246
|
+
}`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${f};${_};${h}`,inputDependencies:x},getShaderSource:M,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:t*n},programUniforms:w})}},ll=(e,t,n,i,o,l,u,c,h)=>{let f=u+l.kvSequenceLength,m=[l.batchSize,l.numHeads,l.sequenceLength,f],g=e>1&&i,w=l.kvNumHeads?l.kvNumHeads:l.numHeads,_=g?[l.batchSize,w,f,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(f/$),y:Math.ceil(l.sequenceLength/$),z:l.batchSize*l.numHeads},I=[{type:12,data:l.sequenceLength},{type:12,data:k},{type:12,data:f},{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&&j.size(i.dims)>0,q=["type","type"];B&&q.push("type"),o&&q.push("type"),c&&q.push("type"),h&&q.push("type");let W=[{dims:m,dataType:t.dataType,gpuDataType:0}];g&&W.push({dims:_,dataType:t.dataType,gpuDataType:0});let te=fe=>{let be=U("q",t.dataType,t.dims,M),qe=U("key",n.dataType,n.dims,M),Re=[be,qe];if(B){let Le=U("past_key",i.dataType,i.dims,M);Re.push(Le)}o&&Re.push(U("attention_bias",o.dataType,o.dims));let Me=c?U("seq_lens",c.dataType,c.dims):void 0;Me&&Re.push(Me);let rt=h?U("total_sequence_length_input",h.dataType,h.dims):void 0;rt&&Re.push(rt);let ye=de("output",t.dataType,m),xe=[ye];g&&xe.push(de("present_key",t.dataType,_,M));let Be=N(1,M),je=[{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`
|
|
247
|
+
const TILE_SIZE = ${$}u;
|
|
248
|
+
|
|
249
|
+
var<workgroup> tileQ: array<${be.type.storage}, ${$*$}>;
|
|
250
|
+
var<workgroup> tileK: array<${be.type.storage}, ${$*$}>;
|
|
251
|
+
${fe.registerUniforms(je).declareVariables(...Re,...xe)}
|
|
252
|
+
${fe.mainStart([$,$,1])}
|
|
253
|
+
// x holds the N and y holds the M
|
|
254
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
255
|
+
let kvHeadIdx = ${b===1?"headIdx":"headIdx / uniforms.n_reps"};
|
|
256
|
+
let kv_num_heads = ${b===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
|
|
257
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
258
|
+
let m = workgroup_id.y * TILE_SIZE;
|
|
259
|
+
let n = workgroup_id.x * TILE_SIZE;
|
|
260
|
+
let sequence_length = uniforms.M;
|
|
261
|
+
var total_sequence_length = uniforms.N;
|
|
262
|
+
${Si(Me,rt,!0)}
|
|
263
|
+
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;
|
|
264
|
+
let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
265
|
+
${B&&g?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};
|
|
266
|
+
let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;
|
|
267
|
+
${g?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""}
|
|
268
|
+
var value = ${Be}(0);
|
|
269
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
270
|
+
if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {
|
|
271
|
+
tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];
|
|
272
|
+
}
|
|
273
|
+
if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {
|
|
274
|
+
var idx = TILE_SIZE * local_id.y + local_id.x;
|
|
275
|
+
${B&&g?`
|
|
276
|
+
if (n + local_id.y < past_sequence_length) {
|
|
277
|
+
tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
|
|
278
|
+
} else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
|
|
279
|
+
tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];
|
|
280
|
+
}`:`
|
|
281
|
+
if (n + local_id.y < uniforms.kv_sequence_length) {
|
|
282
|
+
tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
|
|
283
|
+
}`}
|
|
284
|
+
${g?`if (n + local_id.y < present_sequence_length) {
|
|
285
|
+
present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];
|
|
286
|
+
}`:""}
|
|
287
|
+
}
|
|
288
|
+
workgroupBarrier();
|
|
289
|
+
|
|
290
|
+
for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {
|
|
291
|
+
value += ${Be}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
workgroupBarrier();
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {
|
|
298
|
+
let headOffset = workgroup_id.z * uniforms.M * uniforms.N;
|
|
299
|
+
let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;
|
|
300
|
+
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}`)}})()};
|
|
301
|
+
output[outputIdx] = ${ye.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"};
|
|
302
|
+
}
|
|
303
|
+
}`};return{name:"AttentionProbs",shaderCache:{hint:`${M};${o!==void 0};${i!==void 0};${e}`,inputDependencies:q},getRunData:()=>({outputs:W,dispatchGroup:O,programUniforms:I}),getShaderSource:te}},ul=(e,t,n,i,o,l,u=void 0,c=void 0)=>{let h=l+o.kvSequenceLength,f=o.nReps?o.nReps:1,m=o.vHiddenSize*f,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:f}],$=g&&i&&j.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 W=U("probs",t.dataType,t.dims),te=U("v",n.dataType,n.dims),fe=[W,te];$&&fe.push(U("past_value",i.dataType,i.dims));let be=u?U("seq_lens",u.dataType,u.dims):void 0;u&&fe.push(be);let qe=c?U("total_sequence_length_input",c.dataType,c.dims):void 0;c&&fe.push(qe);let Re=[de("output",t.dataType,b)];g&&Re.push(de("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`
|
|
304
|
+
const TILE_SIZE = ${x}u;
|
|
305
|
+
var<workgroup> tileQ: array<${W.type.value}, ${x*x}>;
|
|
306
|
+
var<workgroup> tileV: array<${W.type.value}, ${x*x}>;
|
|
307
|
+
${q.registerUniforms(Me).declareVariables(...fe,...Re)}
|
|
308
|
+
${q.mainStart([x,x,1])}
|
|
309
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
310
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
311
|
+
let kvHeadIdx = ${f===1?"headIdx":"headIdx / uniforms.n_reps"};
|
|
312
|
+
let kv_num_heads = ${f===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
|
|
313
|
+
let m = global_id.y;
|
|
314
|
+
let n = global_id.x;
|
|
315
|
+
let sequence_length = uniforms.M;
|
|
316
|
+
var total_sequence_length = uniforms.K;
|
|
317
|
+
${Si(be,qe,!0)}
|
|
318
|
+
let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
319
|
+
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch
|
|
320
|
+
${$&&g?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};
|
|
321
|
+
let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;
|
|
322
|
+
${g?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""}
|
|
323
|
+
var value = ${W.type.storage}(0);
|
|
324
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
325
|
+
if (m < uniforms.M && w + local_id.x < uniforms.K) {
|
|
326
|
+
tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];
|
|
327
|
+
}
|
|
328
|
+
if (n < uniforms.N && w + local_id.y < uniforms.K) {
|
|
329
|
+
var idx = TILE_SIZE * local_id.y + local_id.x;
|
|
330
|
+
${$&&g?`
|
|
331
|
+
if (w + local_id.y < past_sequence_length) {
|
|
332
|
+
tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];
|
|
333
|
+
} else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
|
|
334
|
+
tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];
|
|
335
|
+
}
|
|
336
|
+
`:`
|
|
337
|
+
if (w + local_id.y < uniforms.kv_sequence_length) {
|
|
338
|
+
tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];
|
|
339
|
+
}`}
|
|
340
|
+
${g?`
|
|
341
|
+
if (w + local_id.y < present_sequence_length) {
|
|
342
|
+
present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];
|
|
343
|
+
}`:""}
|
|
344
|
+
}
|
|
345
|
+
workgroupBarrier();
|
|
346
|
+
for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {
|
|
347
|
+
value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];
|
|
348
|
+
}
|
|
349
|
+
workgroupBarrier();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// we need to transpose output from BNSH_v to BSND_v
|
|
353
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
354
|
+
let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size
|
|
355
|
+
+ headIdx * uniforms.N + n;
|
|
356
|
+
output[outputIdx] = value;
|
|
357
|
+
}
|
|
358
|
+
}`};return{name:"AttentionScore",shaderCache:{hint:`${i!==void 0};${e}`,inputDependencies:O},getRunData:()=>({outputs:I,dispatchGroup:M,programUniforms:k}),getShaderSource:B}},Gn=(e,t,n,i,o,l,u,c,h,f,m=void 0,g=void 0)=>{let w=Math.min(e.outputCount,1+(u?1:0)+(c?1:0)),_=w>1?u:void 0,b=w>1?c:void 0,x=w>1?f.pastSequenceLength:0,M=x+f.kvSequenceLength,k=h&&j.size(h.dims)>0?h:void 0,$=[t,n];_&&j.size(_.dims)>0&&$.push(_),k&&$.push(k),m&&$.push(m),g&&$.push(g);let O=e.compute(ll(w,t,n,_,k,f,x,m,g),{inputs:$,outputs:w>1?[-1,1]:[-1]})[0];e.compute(ol(O,f.batchSize,f.numHeads,x,f.sequenceLength,M,m,g),{inputs:m&&g?[O,m,g]:[O],outputs:[]});let I=[O,i];b&&j.size(b.dims)>0&&I.push(b),m&&I.push(m),g&&I.push(g),e.compute(ul(w,O,i,b,f,x,m,g),{inputs:I,outputs:w>1?[0,2]:[0]})},dl=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],i=t.sequenceLength,o=t.inputHiddenSize,l=t.headSize,u=12,c={x:Math.ceil(t.headSize/u),y:Math.ceil(t.sequenceLength/u),z:t.batchSize*t.numHeads},h=[e.inputs[0],e.inputs[1],e.inputs[2]],f=[{type:12,data:i},{type:12,data:o},{type:12,data:l},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=g=>{let w=de("output_q",h[0].dataType,n),_=de("output_k",h[0].dataType,n),b=de("output_v",h[0].dataType,n),x=U("input",h[0].dataType,h[0].dims),M=U("weight",h[1].dataType,h[1].dims),k=U("bias",h[2].dataType,h[2].dims),$=x.type.storage,O=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return`
|
|
359
|
+
const TILE_SIZE = ${u}u;
|
|
360
|
+
var<workgroup> tileInput: array<${$}, ${u*u}>;
|
|
361
|
+
var<workgroup> tileWeightQ: array<${$}, ${u*u}>;
|
|
362
|
+
var<workgroup> tileWeightK: array<${$}, ${u*u}>;
|
|
363
|
+
var<workgroup> tileWeightV: array<${$}, ${u*u}>;
|
|
364
|
+
${g.registerUniforms(O).declareVariables(x,M,k,w,_,b)}
|
|
365
|
+
${g.mainStart([u,u,1])}
|
|
366
|
+
let batchIndex = workgroup_id.z / uniforms.num_heads;
|
|
367
|
+
let headNumber = workgroup_id.z % uniforms.num_heads;
|
|
368
|
+
let m = global_id.y;
|
|
369
|
+
let n = global_id.x;
|
|
370
|
+
|
|
371
|
+
let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;
|
|
372
|
+
let biasOffsetQ = headNumber * uniforms.head_size;
|
|
373
|
+
let biasOffsetK = uniforms.hidden_size + biasOffsetQ;
|
|
374
|
+
let biasOffsetV = uniforms.hidden_size + biasOffsetK;
|
|
375
|
+
|
|
376
|
+
var valueQ = ${$}(0);
|
|
377
|
+
var valueK = ${$}(0);
|
|
378
|
+
var valueV = ${$}(0);
|
|
379
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
380
|
+
if (m < uniforms.M && w + local_id.x < uniforms.K) {
|
|
381
|
+
tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];
|
|
382
|
+
}
|
|
383
|
+
if (n < uniforms.N && w + local_id.y < uniforms.K) {
|
|
384
|
+
let offset = n + (w + local_id.y) * uniforms.ldb;
|
|
385
|
+
tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];
|
|
386
|
+
tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];
|
|
387
|
+
tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];
|
|
388
|
+
}
|
|
389
|
+
workgroupBarrier();
|
|
390
|
+
for (var k: u32 = 0u; k<TILE_SIZE && w+k < uniforms.K; k++) {
|
|
391
|
+
let inputTileOffset = TILE_SIZE * local_id.y + k;
|
|
392
|
+
let weightTileOffset = TILE_SIZE * k + local_id.x;
|
|
393
|
+
valueQ += tileInput[inputTileOffset] * tileWeightQ[weightTileOffset];
|
|
394
|
+
valueK += tileInput[inputTileOffset] * tileWeightK[weightTileOffset];
|
|
395
|
+
valueV += tileInput[inputTileOffset] * tileWeightV[weightTileOffset];
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
workgroupBarrier();
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
let headOffset = (m * uniforms.N + n) % uniforms.head_size;
|
|
402
|
+
valueQ += bias[headOffset + biasOffsetQ];
|
|
403
|
+
valueK += bias[headOffset + biasOffsetK];
|
|
404
|
+
valueV += bias[headOffset + biasOffsetV];
|
|
405
|
+
|
|
406
|
+
let offset = workgroup_id.z * uniforms.M * uniforms.N;
|
|
407
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
408
|
+
let outputIdx = offset + m * uniforms.N + n;
|
|
409
|
+
output_q[outputIdx] = valueQ;
|
|
410
|
+
output_k[outputIdx] = valueK;
|
|
411
|
+
output_v[outputIdx] = valueV;
|
|
412
|
+
}
|
|
413
|
+
}`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:f}),getShaderSource:m},{inputs:h,outputs:[-1,-1,-1]})},cl=(e,t)=>{let n=al(e.inputs,t),[i,o,l]=dl(e,n);return Gn(e,i,o,l,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}}),hl,pl,fl,ml,bm=S(()=>{ut(),Ie(),ke(),A(),we(),hl=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let n=(i,o,l)=>{let u=o.length;if(u!==i.length)throw new Error(`${l}: num dimensions != ${u}`);o.forEach((c,h)=>{if(c!==i[h])throw new Error(`${l}: dim[${h}] do not match`)})};if(e[0].dims.length>1){let i=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);n(e[1].dims,i,"Invalid input scale"),n(e[2].dims,i,"Invalid input B"),n(e[3].dims,i,"Invalid input mean"),n(e[4].dims,i,"Invalid input var")}else n(e[1].dims,[1],"Invalid input scale"),n(e[2].dims,[1],"Invalid input B"),n(e[3].dims,[1],"Invalid input mean"),n(e[4].dims,[1],"Invalid input var")},pl=(e,t)=>{let{epsilon:n,spatial:i,format:o}=t,l=e[0].dims,u=i?V(l[l.length-1]):1,c=o==="NHWC"&&l.length>1?u:1,h=j.size(l)/u,f=i,m=f?l.length:l,g=U("x",e[0].dataType,e[0].dims,u),w=U("scale",e[1].dataType,e[1].dims,c),_=U("bias",e[2].dataType,e[2].dims,c),b=U("inputMean",e[3].dataType,e[3].dims,c),x=U("inputVar",e[4].dataType,e[4].dims,c),M=de("y",e[0].dataType,m,u),k=()=>{let O="";if(i)O=`let cOffset = ${l.length===1?"0u":o==="NHWC"?`outputIndices[${l.length-1}] / ${u}`:"outputIndices[1]"};`;else if(o==="NCHW")O=`
|
|
414
|
+
${M.indicesSet("outputIndices","0","0")}
|
|
415
|
+
let cOffset = ${M.indicesToOffset("outputIndices")};`;else{O=`var cIndices = ${w.type.indices}(0);
|
|
416
|
+
cIndices[0] = outputIndices[${l.length-1}];`;for(let I=1;I<w.rank;I++)O+=`cIndices[${I}] = outputIndices[${I}];`;O+=`let cOffset = ${w.indicesToOffset("cIndices")};`}return O},$=O=>`
|
|
417
|
+
const epsilon = ${n};
|
|
418
|
+
${O.registerUniform("outputSize","u32").declareVariables(g,w,_,b,x,M)}
|
|
419
|
+
${O.mainStart()}
|
|
420
|
+
${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
421
|
+
var outputIndices = ${M.offsetToIndices(`global_idx * ${u}`)};
|
|
422
|
+
${k()}
|
|
423
|
+
let scale = ${w.getByOffset("cOffset")};
|
|
424
|
+
let bias = ${_.getByOffset("cOffset")};
|
|
425
|
+
let inputMean = ${b.getByOffset("cOffset")};
|
|
426
|
+
let inputVar = ${x.getByOffset("cOffset")};
|
|
427
|
+
let x = ${g.getByOffset("global_idx")};
|
|
428
|
+
let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;
|
|
429
|
+
${M.setByOffset("global_idx","value")}
|
|
430
|
+
}`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${i}_${u}`,inputDependencies:f?["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:f?[{type:12,data:h},...L(l)]:[{type:12,data:h}]})}},fl=e=>E(e),ml=(e,t)=>{let{inputs:n,outputCount:i}=e,o=fl({...t,outputCount:i});if(me.webgpu.validateInputContent&&hl(n,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(pl(n,o))}}),gl,yl,wl,Sm=S(()=>{ke(),we(),gl=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")},yl=e=>{let t=e[0].dims,n=e[0].dims[2],i=j.size(t)/4,o=e[0].dataType,l=U("input",o,t,4),u=U("bias",o,[n],4),c=U("residual",o,t,4),h=de("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:f=>`
|
|
431
|
+
const channels = ${n}u / 4;
|
|
432
|
+
${f.declareVariables(l,u,c,h)}
|
|
433
|
+
|
|
434
|
+
${f.mainStart()}
|
|
435
|
+
${f.guardAgainstOutOfBoundsWorkgroupSizes(i)}
|
|
436
|
+
let value = ${l.getByOffset("global_idx")}
|
|
437
|
+
+ ${u.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")};
|
|
438
|
+
${h.setByOffset("global_idx","value")}
|
|
439
|
+
}`}},wl=e=>{gl(e.inputs),e.compute(yl(e.inputs))}}),vl,nt,_l,bl,Sl,Tl,El,$l,xl,Cl,kl,Rl,Al,Il,Ml,Ol,qn,Pl,Ti,Dl,zl,Ll,Bl,Nl,Ul,Fl,Vl,Gl,ql,Wl,Hl,jl,Kl,Ql,Xl,sa,Yl,na,ia,Jl,Zl,eu,tu,ru,su,aa=S(()=>{Ie(),ke(),A(),we(),vl=(e,t,n,i,o,l,u)=>{let c=Math.ceil(t/4),h="";typeof o=="string"?h=`${o}(a)`:h=o("a");let f=U("inputData",n,[c],4),m=de("outputData",i,[c],4),g=[{name:"vec_size",type:"u32"}];return u&&g.push(...u),`
|
|
440
|
+
${e.registerUniforms(g).declareVariables(f,m)}
|
|
441
|
+
|
|
442
|
+
${l??""}
|
|
443
|
+
|
|
444
|
+
${e.mainStart()}
|
|
445
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
446
|
+
|
|
447
|
+
let a = ${f.getByOffset("global_idx")};
|
|
448
|
+
${m.setByOffset("global_idx",h)}
|
|
449
|
+
}`},nt=(e,t,n,i,o,l=e.dataType,u,c)=>{let h=[{type:12,data:Math.ceil(j.size(e.dims)/4)}];return u&&h.push(...u),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:f=>vl(f,j.size(e.dims),e.dataType,l,n,i,c),getRunData:f=>({outputs:[{dims:e.dims,dataType:l}],dispatchGroup:{x:Math.ceil(j.size(f[0].dims)/64/4)},programUniforms:h})}},_l=e=>{e.compute(nt(e.inputs[0],"Abs","abs"))},bl=e=>{e.compute(nt(e.inputs[0],"Acos","acos"))},Sl=e=>{e.compute(nt(e.inputs[0],"Acosh","acosh"))},Tl=e=>{e.compute(nt(e.inputs[0],"Asin","asin"))},El=e=>{e.compute(nt(e.inputs[0],"Asinh","asinh"))},$l=e=>{e.compute(nt(e.inputs[0],"Atan","atan"))},xl=e=>{e.compute(nt(e.inputs[0],"Atanh","atanh"))},Cl=e=>E(e),kl=(e,t)=>{let n;switch(t.to){case 10:n="vec4<f16>";break;case 1:n="vec4<f32>";break;case 12:n="vec4<u32>";break;case 6:n="vec4<i32>";break;case 9:n="vec4<bool>";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(nt(e.inputs[0],"Cast",n,void 0,t.cacheKey,t.to))},Rl=e=>{let t,n,i=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=i?e[1].getFloat32Array()[0]:-34028234663852886e22,n=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=i?e[1].getUint16Array()[0]:64511,n=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return E({min:t,max:n})},Al=(e,t)=>{let n=t||Rl(e.inputs),i=N(e.inputs[0].dataType);e.compute(nt(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${i}>(uniforms.min), vec4<${i}>(uniforms.max))`,void 0,n.cacheKey,void 0,[{type:e.inputs[0].dataType,data:n.min},{type:e.inputs[0].dataType,data:n.max}],[{name:"min",type:i},{name:"max",type:i}]),{inputs:[0]})},Il=e=>{e.compute(nt(e.inputs[0],"Ceil","ceil"))},Ml=e=>{e.compute(nt(e.inputs[0],"Cos","cos"))},Ol=e=>{e.compute(nt(e.inputs[0],"Cosh","cosh"))},qn=e=>E(e),Pl=(e,t)=>{let n=N(e.inputs[0].dataType);e.compute(nt(e.inputs[0],"Elu",i=>`elu_vf32(${i})`,`
|
|
450
|
+
const elu_alpha_ = ${n}(${t.alpha});
|
|
451
|
+
|
|
452
|
+
fn elu_f32(a: ${n}) -> ${n} {
|
|
453
|
+
return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> {
|
|
457
|
+
return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));
|
|
458
|
+
}`,t.cacheKey))},Ti=(e="f32")=>`
|
|
459
|
+
const r0: ${e} = 0.3275911;
|
|
460
|
+
const r1: ${e} = 0.254829592;
|
|
461
|
+
const r2: ${e} = -0.284496736;
|
|
462
|
+
const r3: ${e} = 1.421413741;
|
|
463
|
+
const r4: ${e} = -1.453152027;
|
|
464
|
+
const r5: ${e} = 1.061405429;
|
|
465
|
+
|
|
466
|
+
fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {
|
|
467
|
+
let absv = abs(v);
|
|
468
|
+
let x = 1.0 / (1.0 + r0 * absv);
|
|
469
|
+
return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));
|
|
470
|
+
}`,Dl=e=>{let t=N(e.inputs[0].dataType);e.compute(nt(e.inputs[0],"Erf",n=>`erf_vf32(${n})`,Ti(t)))},zl=e=>{e.compute(nt(e.inputs[0],"Exp","exp"))},Ll=e=>{e.compute(nt(e.inputs[0],"Floor","floor"))},Bl=e=>{let t=N(e.inputs[0].dataType);e.compute(nt(e.inputs[0],"Gelu",n=>`0.5 * ${n} * (1.0 + erf_vf32(${n} * 0.7071067811865475))`,Ti(t)))},Nl=(e,t)=>{let n=N(e.inputs[0].dataType);e.compute(nt(e.inputs[0],"LeakyRelu",i=>`select(leaky_relu_alpha_ * ${i}, ${i}, ${i} >= vec4<${n}>(0.0))`,`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},Ul=e=>{e.compute(nt(e.inputs[0],"Not",t=>`!${t}`))},Fl=e=>{e.compute(nt(e.inputs[0],"Neg",t=>`-${t}`))},Vl=e=>{e.compute(nt(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Gl=e=>{let t=N(e.inputs[0].dataType);e.compute(nt(e.inputs[0],"Relu",n=>`select(vec4<${t}>(0.0), ${n}, ${n} > vec4<${t}>(0.0))`))},ql=e=>{e.compute(nt(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Wl=e=>E(e),Hl=(e,t)=>{let n=N(e.inputs[0].dataType);e.compute(nt(e.inputs[0],"HardSigmoid",i=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${i} + vec4<${n}>(${t.beta})))`,void 0,t.cacheKey))},jl=e=>{e.compute(nt(e.inputs[0],"Sin","sin"))},Kl=e=>{e.compute(nt(e.inputs[0],"Sinh","sinh"))},Ql=e=>{e.compute(nt(e.inputs[0],"Sqrt","sqrt"))},Xl=e=>{e.compute(nt(e.inputs[0],"Tan","tan"))},sa=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Yl=e=>{e.compute(nt(e.inputs[0],"Tanh",sa))},na=(e="f32")=>`
|
|
471
|
+
const fast_gelu_a: ${e} = 0.5;
|
|
472
|
+
const fast_gelu_b: ${e} = 0.7978845608028654;
|
|
473
|
+
const fast_gelu_c: ${e} = 0.035677408136300125;
|
|
474
|
+
|
|
475
|
+
fn tanh_v(v: vec4<${e}>) -> vec4<${e}> {
|
|
476
|
+
return ${sa("v")};
|
|
477
|
+
}
|
|
478
|
+
`,ia=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Jl=e=>{let t=N(e.inputs[0].dataType);e.compute(nt(e.inputs[0],"FastGelu",ia,na(t),void 0,e.inputs[0].dataType))},Zl=(e,t)=>{let n=N(e.inputs[0].dataType);return e.compute(nt(e.inputs[0],"ThresholdedRelu",i=>`select(vec4<${n}>(0.0), ${i}, ${i} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},eu=e=>{e.compute(nt(e.inputs[0],"Log","log"))},tu=(e,t)=>`
|
|
479
|
+
const alpha = vec4<${e}>(${t});
|
|
480
|
+
const one = ${e}(1.0);
|
|
481
|
+
const zero = ${e}(0.0);
|
|
482
|
+
|
|
483
|
+
fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
484
|
+
let v = x *alpha;
|
|
485
|
+
var x1 : vec4<${e}>;
|
|
486
|
+
for (var i = 0; i < 4; i = i + 1) {
|
|
487
|
+
if (v[i] >= zero) {
|
|
488
|
+
x1[i] = one / (one + exp(-v[i]));
|
|
489
|
+
} else {
|
|
490
|
+
x1[i] = one - one / (one + exp(v[i]));
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
return x * x1;
|
|
494
|
+
}
|
|
495
|
+
`,ru=e=>`quick_gelu_impl(${e})`,su=(e,t)=>{let n=N(e.inputs[0].dataType);e.compute(nt(e.inputs[0],"QuickGelu",ru,tu(n,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),nu,iu,au,Tm=S(()=>{ke(),we(),aa(),nu=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},iu=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let n=U("input",e[0].dataType,e[0].dims,4),i=U("bias",e[0].dataType,[e[0].dims[2]],4),o=de("output",e[0].dataType,t,4),l=j.size(t)/4,u=G(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)}}),getShaderSource:c=>`
|
|
496
|
+
const M_SQRT2 = sqrt(2.0);
|
|
497
|
+
const halfChannels = ${e[0].dims[2]/4/2}u;
|
|
498
|
+
|
|
499
|
+
${c.declareVariables(n,i,o)}
|
|
500
|
+
|
|
501
|
+
${Ti(u)}
|
|
502
|
+
|
|
503
|
+
${c.mainStart()}
|
|
504
|
+
${c.guardAgainstOutOfBoundsWorkgroupSizes(l)}
|
|
505
|
+
let biasIdx = global_idx % halfChannels;
|
|
506
|
+
let batchIndex = global_idx / halfChannels;
|
|
507
|
+
let inputOffset = biasIdx + batchIndex * halfChannels * 2;
|
|
508
|
+
let valueLeft = input[inputOffset] + bias[biasIdx];
|
|
509
|
+
let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];
|
|
510
|
+
let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);
|
|
511
|
+
|
|
512
|
+
${o.setByOffset("global_idx","valueLeft * geluRight")}
|
|
513
|
+
}`}},au=e=>{nu(e.inputs),e.compute(iu(e.inputs))}}),ou,lu,kr,uu,du,cu,hu,pu,fu,mu,gu,yu,wu,Em=S(()=>{Ie(),ke(),we(),ou=(e,t,n,i,o,l,u,c,h,f,m,g)=>{let w,_;typeof c=="string"?w=_=($,O)=>`${c}((${$}),(${O}))`:typeof c=="function"?w=_=c:(w=c.scalar,_=c.vector);let b=de("outputData",m,i.length,4),x=U("aData",h,t.length,4),M=U("bData",f,n.length,4),k;if(o)if(l){let $=j.size(t)===1,O=j.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=`
|
|
514
|
+
let outputIndices = ${b.offsetToIndices("global_idx * 4u")};
|
|
515
|
+
let offsetA = ${x.broadcastedIndicesToOffset("outputIndices",b)};
|
|
516
|
+
let offsetB = ${M.broadcastedIndicesToOffset("outputIndices",b)};
|
|
517
|
+
${b.setByOffset("global_idx",_(u||I?x.getByOffset("offsetA / 4u"):`${x.type.value}(${x.getByOffset("offsetA / 4u")}[offsetA % 4u])`,u||B?M.getByOffset("offsetB / 4u"):`${M.type.value}(${M.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}
|
|
518
|
+
`}else k=b.setByOffset("global_idx",_(x.getByOffset("global_idx"),M.getByOffset("global_idx")));else{if(!l)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let $=(O,I,B="")=>{let q=`aData[indexA${I}][componentA${I}]`,W=`bData[indexB${I}][componentB${I}]`;return`
|
|
519
|
+
let outputIndices${I} = ${b.offsetToIndices(`global_idx * 4u + ${I}u`)};
|
|
520
|
+
let offsetA${I} = ${x.broadcastedIndicesToOffset(`outputIndices${I}`,b)};
|
|
521
|
+
let offsetB${I} = ${M.broadcastedIndicesToOffset(`outputIndices${I}`,b)};
|
|
522
|
+
let indexA${I} = offsetA${I} / 4u;
|
|
523
|
+
let indexB${I} = offsetB${I} / 4u;
|
|
524
|
+
let componentA${I} = offsetA${I} % 4u;
|
|
525
|
+
let componentB${I} = offsetB${I} % 4u;
|
|
526
|
+
${O}[${I}] = ${B}(${w(q,W)});
|
|
527
|
+
`};m===9?k=`
|
|
528
|
+
var data = vec4<u32>(0);
|
|
529
|
+
${$("data",0,"u32")}
|
|
530
|
+
${$("data",1,"u32")}
|
|
531
|
+
${$("data",2,"u32")}
|
|
532
|
+
${$("data",3,"u32")}
|
|
533
|
+
outputData[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:k=`
|
|
534
|
+
${$("outputData[global_idx]",0)}
|
|
535
|
+
${$("outputData[global_idx]",1)}
|
|
536
|
+
${$("outputData[global_idx]",2)}
|
|
537
|
+
${$("outputData[global_idx]",3)}
|
|
538
|
+
`}return`
|
|
539
|
+
${e.registerUniform("vec_size","u32").declareVariables(x,M,b)}
|
|
540
|
+
|
|
541
|
+
${g??""}
|
|
542
|
+
|
|
543
|
+
${e.mainStart()}
|
|
544
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
545
|
+
${k}
|
|
546
|
+
}`},lu=(e,t,n,i,o,l,u=n.dataType)=>{let c=n.dims.map(Number),h=i.dims.map(Number),f=!j.areEqual(c,h),m=c,g=j.size(c),w=!1,_=!1,b=[f];if(f){let x=Pr.calcShape(c,h,!1);if(!x)throw new Error("Can't perform binary op on the given tensors");m=x.slice(),g=j.size(m);let M=j.size(c)===1,k=j.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],W=h[h.length-B];if(q===W)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=>ou(x,c,h,m,w,f,_,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(j.size(m)/4)},...L(c,h,m)]})}},kr=(e,t,n,i,o,l)=>{e.compute(lu(t,o??"",e.inputs[0],e.inputs[1],n,i,l))},uu=e=>{kr(e,"Add",(t,n)=>`${t}+${n}`)},du=e=>{kr(e,"Div",(t,n)=>`${t}/${n}`)},cu=e=>{kr(e,"Equal",{scalar:(t,n)=>`u32(${t}==${n})`,vector:(t,n)=>`vec4<u32>(${t}==${n})`},void 0,void 0,9)},hu=e=>{kr(e,"Mul",(t,n)=>`${t}*${n}`)},pu=e=>{let t=U("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;kr(e,"Pow",{scalar:(n,i)=>`pow_custom(${n},${i})`,vector:(n,i)=>`pow_vector_custom(${n},${i})`},`
|
|
547
|
+
fn pow_custom(a : ${t}, b : ${t}) -> ${t} {
|
|
548
|
+
if (b == ${t}(0.0)) {
|
|
549
|
+
return ${t}(1.0);
|
|
550
|
+
} else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {
|
|
551
|
+
return ${t}(pow(f32(a), f32(b))); // NaN
|
|
552
|
+
}
|
|
553
|
+
return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));
|
|
554
|
+
}
|
|
555
|
+
fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {
|
|
556
|
+
// TODO: implement vectorized pow
|
|
557
|
+
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));
|
|
558
|
+
}
|
|
559
|
+
`)},fu=e=>{kr(e,"Sub",(t,n)=>`${t}-${n}`)},mu=e=>{kr(e,"Greater",{scalar:(t,n)=>`u32(${t}>${n})`,vector:(t,n)=>`vec4<u32>(${t}>${n})`},void 0,void 0,9)},gu=e=>{kr(e,"Less",{scalar:(t,n)=>`u32(${t}<${n})`,vector:(t,n)=>`vec4<u32>(${t}<${n})`},void 0,void 0,9)},yu=e=>{kr(e,"GreaterOrEqual",{scalar:(t,n)=>`u32(${t}>=${n})`,vector:(t,n)=>`vec4<u32>(${t}>=${n})`},void 0,void 0,9)},wu=e=>{kr(e,"LessOrEqual",{scalar:(t,n)=>`u32(${t}<=${n})`,vector:(t,n)=>`vec4<u32>(${t}<=${n})`},void 0,void 0,9)}}),vu,_u,bu,Su,Tu,Eu,$m=S(()=>{Ie(),ke(),A(),we(),vu=(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,f)=>{if(f!==t&&h!==i.dims[f])throw new Error("non concat dimensions must match")})}})},_u=(e,t)=>`
|
|
560
|
+
fn calculateInputIndex(index: u32) -> u32 {
|
|
561
|
+
let sizeInConcatAxis = array<u32, ${e}u>(${t});
|
|
562
|
+
for (var i: u32 = 0u; i < ${e}; i += 1u ) {
|
|
563
|
+
if (index < sizeInConcatAxis[i]) {
|
|
564
|
+
return i;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return ${e}u;
|
|
568
|
+
}`,bu=(e,t)=>{let n=e.length,i=[];for(let o=0;o<n;++o){let l=t.setByOffset("global_idx",e[o].getByIndices("indices"));n===1?i.push(l):o===0?i.push(`if (inputIndex == ${o}u) { ${l} }`):o===n-1?i.push(`else { ${l} }`):i.push(`else if (inputIndex == ${o}) { ${l} }`)}return i.join(`
|
|
569
|
+
`)},Su=(e,t,n,i)=>{let o=j.size(n),l=new Array(e.length),u=new Array(e.length),c=0,h=[],f=[],m=[{type:12,data:o}];for(let x=0;x<e.length;++x)c+=e[x].dims[t],l[x]=c,f.push(e[x].dims.length),u[x]=U(`input${x}`,i,f[x]),h.push("rank"),m.push({type:12,data:l[x]});for(let x=0;x<e.length;++x)m.push(...L(e[x].dims));m.push(...L(n));let g=de("output",i,n.length),w=g.indicesGet("indices",t),_=Array.from(Array(l.length).keys()).map(x=>`uniforms.sizeInConcatAxis${x}`).join(","),b=x=>`
|
|
570
|
+
|
|
571
|
+
${(()=>{x.registerUniform("outputSize","u32");for(let M=0;M<e.length;M++)x.registerUniform(`sizeInConcatAxis${M}`,"u32");return x.declareVariables(...u,g)})()}
|
|
572
|
+
|
|
573
|
+
${_u(l.length,_)}
|
|
574
|
+
|
|
575
|
+
${x.mainStart()}
|
|
576
|
+
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
577
|
+
|
|
578
|
+
var indices = ${g.offsetToIndices("global_idx")};
|
|
579
|
+
|
|
580
|
+
let inputIndex = calculateInputIndex(${w});
|
|
581
|
+
if (inputIndex != 0u) {
|
|
582
|
+
let sizeInConcatAxis = array<u32, ${l.length}u>(${_});
|
|
583
|
+
${w} -= sizeInConcatAxis[inputIndex - 1u];
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
${bu(u,g)}
|
|
587
|
+
}`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:b}},Tu=(e,t)=>{let n=e.inputs,i=n[0].dims,o=j.normalizeAxis(t.axis,i.length);vu(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=>j.size(c.dims)>0);e.compute(Su(u,o,l,n[0].dataType),{inputs:u})},Eu=e=>E({axis:e.axis})}),Is,Ms,Os,oa,Ps=S(()=>{Ie(),ke(),Is=(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));
|
|
588
|
+
value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
|
|
589
|
+
`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Ms=(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})},Os=(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"})},oa=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[n,i]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:i}}else if(t==="Clip"){let[n,i]=e?.activation_params||[Mn,br];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}}}),Vt,$u,la=S(()=>{Vt=(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.`)}},$u=e=>`
|
|
590
|
+
${e?"value = value + getBiasByOutputCoords(coords);":""}
|
|
591
|
+
`}),xu,xm=S(()=>{xu=e=>`
|
|
592
|
+
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
|
|
593
|
+
return dot(coords, vec4<i32>(
|
|
594
|
+
shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
|
|
595
|
+
}
|
|
596
|
+
fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
|
|
597
|
+
return dot(coords, vec4<i32>(
|
|
598
|
+
i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));
|
|
599
|
+
}
|
|
600
|
+
`}),Wn,ua,da=S(()=>{Ie(),ke(),we(),Ps(),Wn=(e,t,n,i,o)=>{let l=i-n;return`
|
|
601
|
+
${Array.from({length:n}).map((u,c)=>`
|
|
602
|
+
if (${K(t.shape,c,t.rank)} != 1) {
|
|
603
|
+
${t.indicesSet(e,c,K(o,c+l,i))}
|
|
604
|
+
} else {
|
|
605
|
+
${t.indicesSet(e,c,0)}
|
|
606
|
+
}`).join("")}
|
|
607
|
+
`},ua=(e,t,n,i,o=!1,l)=>{let u=e[0].dims,c=e[1].dims,h=u[u.length-2],f=c[c.length-1],m=u[u.length-1],g=V(f),w=V(m),_=V(h),b=j.size(n)/g/_,x=e.length>2,M=i?i.slice(0,-2):n.slice(0,-2),k=[j.size(M),h,f],$=[{type:12,data:b},{type:12,data:h},{type:12,data:f},{type:12,data:m}];Ms(t,$),$.push(...L(M,u,c)),x&&$.push(...L(e[2].dims)),$.push(...L(k));let O=I=>{let B=Ue("batch_dims",e[0].dataType,M.length),q=U("a",e[0].dataType,u.length,w),W=U("b",e[1].dataType,c.length,g),te=de("output",e[0].dataType,k.length,g),fe=G(te.type.tensor),be=Is(t,te.type.value,fe),qe=[q,W],Re="";if(x){let ye=o?g:1;qe.push(U("bias",e[2].dataType,e[2].dims.length,ye)),Re=`${o?`value += bias[col / ${ye}];`:`value += ${te.type.value}(bias[row + i]);`}`}let Me=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Os(t,Me);let rt=()=>{let ye=`var a_data: ${q.type.value};`;for(let xe=0;xe<w;xe++)ye+=`
|
|
608
|
+
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 Be=0;Be<w;Be++)ye+=`
|
|
609
|
+
values[${xe}] = fma(${W.type.value}(a_data${w===1?"":`[${Be}]`}), b_data${Be}, values[${xe}]);
|
|
610
|
+
`}return ye};return`
|
|
611
|
+
${I.registerUniforms(Me).registerInternalVariables(B).declareVariables(...qe,te)}
|
|
612
|
+
${I.mainStart()}
|
|
613
|
+
${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
614
|
+
let col = (global_idx % (uniforms.N / ${g})) * ${g};
|
|
615
|
+
var index1 = global_idx / (uniforms.N / ${g});
|
|
616
|
+
let stride1 = uniforms.M / ${_};
|
|
617
|
+
let row = (index1 % stride1) * ${_};
|
|
618
|
+
let batch = index1 / stride1;
|
|
619
|
+
|
|
620
|
+
${n.length===2?"":`let batch_indices = ${B.offsetToIndices("batch")};`}
|
|
621
|
+
|
|
622
|
+
var a_indices: ${q.type.indices};
|
|
623
|
+
${Wn("a_indices",q,q.rank-2,B.rank,"batch_indices")}
|
|
624
|
+
${q.indicesSet("a_indices",q.rank-2,0)}
|
|
625
|
+
${q.indicesSet("a_indices",q.rank-1,0)}
|
|
626
|
+
let a_offset = ${q.indicesToOffset("a_indices")};
|
|
627
|
+
|
|
628
|
+
var b_indices: ${W.type.indices};
|
|
629
|
+
${Wn("b_indices",W,W.rank-2,B.rank,"batch_indices")}
|
|
630
|
+
${W.indicesSet("b_indices",W.rank-2,0)}
|
|
631
|
+
${W.indicesSet("b_indices",W.rank-1,0)}
|
|
632
|
+
let b_offset = ${W.indicesToOffset("b_indices")};
|
|
633
|
+
var values: array<${te.type.value}, ${_}>;
|
|
634
|
+
for (var k: u32 = 0u; k < uniforms.K; k = k + ${w}) {
|
|
635
|
+
${rt()}
|
|
636
|
+
}
|
|
637
|
+
for (var i = 0u; i < ${_}u; i++) {
|
|
638
|
+
var value = values[i];
|
|
639
|
+
${Re}
|
|
640
|
+
${be}
|
|
641
|
+
let cur_indices = ${te.type.indices}(batch, row + i, col);
|
|
642
|
+
let offset = ${te.indicesToOffset("cur_indices")};
|
|
643
|
+
${te.setByOffset(`offset / ${g}`,"value")};
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
`};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}}}),Cu,ku,ca,ha,Ru,pa,Au,Ei,fa=S(()=>{Ie(),ke(),we(),Ps(),da(),la(),Cu=(e,t)=>e?`
|
|
647
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
648
|
+
kStart + inputRow,
|
|
649
|
+
globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});
|
|
650
|
+
`:`
|
|
651
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
652
|
+
globalRow + innerRow,
|
|
653
|
+
kStart / innerElementSize + inputCol${t?", batchIndices":""});
|
|
654
|
+
`,ku=(e,t)=>e?`
|
|
655
|
+
let ACached0 = mm_Asub[k * innerElementSize][localRow];
|
|
656
|
+
let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];
|
|
657
|
+
let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];
|
|
658
|
+
${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}
|
|
659
|
+
for (var i = 0; i < rowPerThread; i = i + 1) {
|
|
660
|
+
acc[i] = BCached0 * ACached0[i] + acc[i];
|
|
661
|
+
acc[i] = BCached1 * ACached1[i] + acc[i];
|
|
662
|
+
acc[i] = BCached2 * ACached2[i] + acc[i];
|
|
663
|
+
${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}
|
|
664
|
+
}`:`
|
|
665
|
+
for (var i = 0; i < rowPerThread; i = i + 1) {
|
|
666
|
+
let ACached = mm_Asub[tileRow + i][k];
|
|
667
|
+
acc[i] = BCached0 * ACached.x + acc[i];
|
|
668
|
+
acc[i] = BCached1 * ACached.y + acc[i];
|
|
669
|
+
acc[i] = BCached2 * ACached.z + acc[i];
|
|
670
|
+
${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}
|
|
671
|
+
}`,ca=(e,t,n="f32",i,o=!1,l=32,u=!1,c=32)=>{let h=t[1]*e[1],f=t[0]*e[0],m=o?h:l,g=o?l:h,w=m/t[0],_=l/t[1];if(!((o&&w===4&&e[1]===4||!o&&(w===3||w===4))&&m%t[0]===0&&l%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${w} and workPerThread[1] ${e[1]} must be 4.
|
|
672
|
+
Otherwise, innerElementSize ${w} must be 3 or 4.
|
|
673
|
+
tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}. tileInner ${l} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`
|
|
674
|
+
var<workgroup> mm_Asub: array<array<vec${w}<${n}>, ${m/w}>, ${g}>;
|
|
675
|
+
var<workgroup> mm_Bsub: array<array<vec4<${n}>, ${f/e[0]}>, ${l}>;
|
|
676
|
+
|
|
677
|
+
const rowPerThread = ${e[1]};
|
|
678
|
+
const colPerThread = ${e[0]};
|
|
679
|
+
const innerElementSize = ${w};
|
|
680
|
+
const tileInner = ${l};
|
|
681
|
+
|
|
682
|
+
@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})
|
|
683
|
+
fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
684
|
+
@builtin(global_invocation_id) globalId : vec3<u32>,
|
|
685
|
+
@builtin(workgroup_id) workgroupId : vec3<u32>) {
|
|
686
|
+
let localRow = i32(localId.y);
|
|
687
|
+
let tileRow = localRow * rowPerThread;
|
|
688
|
+
let tileCol = i32(localId.x);
|
|
689
|
+
|
|
690
|
+
let globalRow =i32(globalId.y) * rowPerThread;
|
|
691
|
+
let globalCol = i32(globalId.x);
|
|
692
|
+
let batch = ${u?"0":"i32(globalId.z)"};
|
|
693
|
+
${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""}
|
|
694
|
+
let globalRowStart = i32(workgroupId.y) * ${h};
|
|
695
|
+
|
|
696
|
+
let num_tiles = ${u?`${Math.ceil(c/l)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
|
|
697
|
+
var kStart = ${u?`i32(globalId.z) * ${c}`:"0"};
|
|
698
|
+
|
|
699
|
+
var acc: array<vec4<${n}>, rowPerThread>;
|
|
700
|
+
|
|
701
|
+
// Loop over shared dimension.
|
|
702
|
+
let tileRowB = localRow * ${_};
|
|
703
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
704
|
+
// Load one tile of A into local memory.
|
|
705
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
706
|
+
let inputRow = tileRow + innerRow;
|
|
707
|
+
let inputCol = tileCol;
|
|
708
|
+
${Cu(o,i)}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// Load one tile of B into local memory.
|
|
712
|
+
for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {
|
|
713
|
+
let inputRow = tileRowB + innerRow;
|
|
714
|
+
let inputCol = tileCol;
|
|
715
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${i?", batchIndices":""});
|
|
716
|
+
}
|
|
717
|
+
kStart = kStart + tileInner;
|
|
718
|
+
workgroupBarrier();
|
|
719
|
+
|
|
720
|
+
// Compute acc values for a single thread.
|
|
721
|
+
for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {
|
|
722
|
+
let BCached0 = mm_Bsub[k * innerElementSize][tileCol];
|
|
723
|
+
let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];
|
|
724
|
+
let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];
|
|
725
|
+
${w===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}
|
|
726
|
+
|
|
727
|
+
${ku(o,w)}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
workgroupBarrier();
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
734
|
+
mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
|
|
735
|
+
}
|
|
736
|
+
}`},ha=(e,t)=>e?`
|
|
737
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
738
|
+
kStart + inputRow,
|
|
739
|
+
globalRowStart + inputCol${t?", batchIndices":""});
|
|
740
|
+
`:`
|
|
741
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
742
|
+
globalRowStart + inputRow,
|
|
743
|
+
kStart + inputCol${t?", batchIndices":""});
|
|
744
|
+
`,Ru=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",pa=(e,t,n="f32",i,o=!1,l=32,u=!1,c=32,h=!1)=>{let f=e[1]*t[1],m=e[0]*t[0],g=o?f:l,w=o?l:f;if(!(w%t[1]===0&&g%t[0]===0&&l%t[1]===0))throw new Error(`tileAHight ${w} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}, tileInner ${l} must be divisible by workgroupSize[1]${t[1]}`);let _=w/t[1],b=g/t[0],x=l/t[1],M=h?`
|
|
745
|
+
let localRow = i32(localId.y);
|
|
746
|
+
let localCol = i32(localId.x);
|
|
747
|
+
let globalRowStart = i32(workgroupId.y) * ${f};
|
|
748
|
+
let globalColStart = i32(workgroupId.x) * ${m};
|
|
749
|
+
|
|
750
|
+
// Loop over shared dimension.
|
|
751
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
752
|
+
// Load one tile of A into local memory.
|
|
753
|
+
for (var inputRow = localRow; inputRow < ${w}; inputRow = inputRow + ${t[1]}) {
|
|
754
|
+
for (var inputCol = localCol; inputCol < ${g}; inputCol = inputCol + ${t[0]}) {
|
|
755
|
+
${ha(o,i)}
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
// Load one tile of B into local memory.
|
|
759
|
+
for (var inputRow = localRow; inputRow < ${l}; inputRow = inputRow + ${t[1]}) {
|
|
760
|
+
for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) {
|
|
761
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch,
|
|
762
|
+
kStart + inputRow,
|
|
763
|
+
globalColStart + inputCol${i?", batchIndices":""});
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
kStart = kStart + tileInner;
|
|
767
|
+
workgroupBarrier();
|
|
768
|
+
|
|
769
|
+
// Compute acc values for a single thread.
|
|
770
|
+
var BCached : array<${n}, colPerThread>;
|
|
771
|
+
for (var k = 0; k < tileInner; k = k + 1) {
|
|
772
|
+
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
|
|
773
|
+
BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];
|
|
774
|
+
}
|
|
775
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
776
|
+
let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}
|
|
777
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
778
|
+
acc[innerRow][innerCol] = acc[innerRow][innerCol] +
|
|
779
|
+
ACached * BCached[innerCol];
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
workgroupBarrier();
|
|
784
|
+
}
|
|
785
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
786
|
+
let gRow = globalRowStart + localRow + innerRow * ${t[1]};
|
|
787
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
788
|
+
let gCol = globalColStart + localCol + innerCol * ${t[0]};
|
|
789
|
+
mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
`:`
|
|
793
|
+
let tileRow = i32(localId.y) * rowPerThread;
|
|
794
|
+
let tileCol = i32(localId.x) * colPerThread;
|
|
795
|
+
|
|
796
|
+
let globalRow = i32(globalId.y) * rowPerThread;
|
|
797
|
+
let globalCol = i32(globalId.x) * colPerThread;
|
|
798
|
+
let globalRowStart = i32(workgroupId.y) * ${f};
|
|
799
|
+
|
|
800
|
+
let tileRowA = i32(localId.y) * ${_};
|
|
801
|
+
let tileColA = i32(localId.x) * ${b};
|
|
802
|
+
let tileRowB = i32(localId.y) * ${x};
|
|
803
|
+
// Loop over shared dimension.
|
|
804
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
805
|
+
// Load one tile of A into local memory.
|
|
806
|
+
for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {
|
|
807
|
+
for (var innerCol = 0; innerCol < ${b}; innerCol = innerCol + 1) {
|
|
808
|
+
let inputRow = tileRowA + innerRow;
|
|
809
|
+
let inputCol = tileColA + innerCol;
|
|
810
|
+
${ha(o,i)}
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
// Load one tile of B into local memory.
|
|
815
|
+
for (var innerRow = 0; innerRow < ${x}; innerRow = innerRow + 1) {
|
|
816
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
817
|
+
let inputRow = tileRowB + innerRow;
|
|
818
|
+
let inputCol = tileCol + innerCol;
|
|
819
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch,
|
|
820
|
+
kStart + inputRow,
|
|
821
|
+
globalCol + innerCol${i?", batchIndices":""});
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
kStart = kStart + tileInner;
|
|
825
|
+
workgroupBarrier();
|
|
826
|
+
|
|
827
|
+
// Compute acc values for a single thread.
|
|
828
|
+
var BCached : array<${n}, colPerThread>;
|
|
829
|
+
for (var k = 0; k < tileInner; k = k + 1) {
|
|
830
|
+
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
|
|
831
|
+
BCached[inner] = mm_Bsub[k][tileCol + inner];
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
835
|
+
${Ru(o)}
|
|
836
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
837
|
+
acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
workgroupBarrier();
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
846
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
847
|
+
mm_write(batch, globalRow + innerRow, globalCol + innerCol,
|
|
848
|
+
acc[innerRow][innerCol]);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
`;return`
|
|
852
|
+
var<workgroup> mm_Asub : array<array<${n}, ${g}>, ${w}>;
|
|
853
|
+
var<workgroup> mm_Bsub : array<array<${n}, ${m}>, ${l}>;
|
|
854
|
+
const rowPerThread = ${e[1]};
|
|
855
|
+
const colPerThread = ${e[0]};
|
|
856
|
+
const tileInner = ${l};
|
|
857
|
+
|
|
858
|
+
@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})
|
|
859
|
+
fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
860
|
+
@builtin(global_invocation_id) globalId : vec3<u32>,
|
|
861
|
+
@builtin(workgroup_id) workgroupId : vec3<u32>) {
|
|
862
|
+
let batch = ${u?"0":"i32(globalId.z)"};
|
|
863
|
+
${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""}
|
|
864
|
+
let num_tiles = ${u?`${Math.ceil(c/l)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
|
|
865
|
+
var kStart = ${u?`i32(globalId.z) * ${c}`:"0"};
|
|
866
|
+
|
|
867
|
+
var acc : array<array<${n}, colPerThread>, rowPerThread>;
|
|
868
|
+
${M}
|
|
869
|
+
}
|
|
870
|
+
`},Au=(e,t,n,i,o=!1)=>{let[l,u,c,h]=i,f=G(i[0].type.tensor);return`
|
|
871
|
+
fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${l.type.indices}) -> ${Vt(e,f)} {
|
|
872
|
+
var value = ${Vt(e,f)}(0.0);
|
|
873
|
+
let col = colIn * ${e};
|
|
874
|
+
if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)
|
|
875
|
+
{
|
|
876
|
+
var aIndices: ${u.type.indices};
|
|
877
|
+
${Wn("aIndices",u,u.rank-2,l.rank,"batchIndices")}
|
|
878
|
+
${u.indicesSet("aIndices",u.rank-2,"u32(row)")}
|
|
879
|
+
${u.indicesSet("aIndices",u.rank-1,"u32(colIn)")}
|
|
880
|
+
value = ${u.getByIndices("aIndices")};
|
|
881
|
+
}
|
|
882
|
+
return value;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${l.type.indices}) -> ${Vt(e,f)} {
|
|
886
|
+
var value = ${Vt(e,f)}(0.0);
|
|
887
|
+
let col = colIn * ${e};
|
|
888
|
+
if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)
|
|
889
|
+
{
|
|
890
|
+
var bIndices: ${c.type.indices};
|
|
891
|
+
${Wn("bIndices",c,c.rank-2,l.rank,"batchIndices")}
|
|
892
|
+
${c.indicesSet("bIndices",c.rank-2,"u32(row)")}
|
|
893
|
+
${c.indicesSet("bIndices",c.rank-1,"u32(colIn)")}
|
|
894
|
+
value = ${c.getByIndices("bIndices")};
|
|
895
|
+
}
|
|
896
|
+
return value;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Vt(e,f)}) {
|
|
900
|
+
let col = colIn * ${e};
|
|
901
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {
|
|
902
|
+
var value = valueIn;
|
|
903
|
+
let coords = vec3<i32>(batch, row, colIn);
|
|
904
|
+
${t?`value = value + ${o?"bias[colIn]":`${Vt(e,f)}(bias[row])`};`:""}
|
|
905
|
+
${n}
|
|
906
|
+
${h.setByIndices("vec3<u32>(coords)","value")}
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
`},Ei=(e,t,n,i,o=!1,l)=>{let u=e[0].dims,c=e[1].dims,h=u.slice(0,-2),f=c.slice(0,-2),m=i?i.slice(0,-2):n.slice(0,-2),g=j.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=[...f,_,b/O],W=q.length,te=[g,w,b/O],fe=[{type:6,data:w},{type:6,data:b},{type:6,data:_}];Ms(t,fe),fe.push(...L(m,I,q));let be=["rank","rank"],qe=e.length>2;qe&&(fe.push(...L(e[2].dims)),be.push("rank")),fe.push(...L(te));let Re=Me=>{let rt=m.length,ye=Ue("batchDims",e[0].dataType,rt,1),xe=G(e[0].dataType),Be=U("a",e[0].dataType,B,O),je=U("b",e[1].dataType,W,O),Le=de("result",e[0].dataType,te.length,O),Xe=[Be,je];if(qe){let Kt=o?O:1;Xe.push(U("bias",e[2].dataType,e[2].dims.length,Kt))}let ue=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Os(t,ue);let ze=G(Le.type.tensor),Ae=Is(t,Le.type.value,ze),$e=Au(O,qe,Ae,[ye,Be,je,Le],o);return`
|
|
910
|
+
${Me.registerUniforms(ue).registerInternalVariables(ye).declareVariables(...Xe,Le)}
|
|
911
|
+
${$e}
|
|
912
|
+
${x?ca(M,k,xe,ye):pa(M,k,xe,ye)}
|
|
913
|
+
`};return{name:"MatMul",shaderCache:{hint:`${M};${t.activation};${x};${o}`,inputDependencies:be},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:$[0],y:$[1],z:$[2]},programUniforms:fe}),getShaderSource:Re}}}),Iu,Mu,Cm=S(()=>{Ie(),hr(),we(),Ps(),la(),xm(),fa(),Iu=(e,t,n,i,o=!1,l,u=4,c=4,h=4,f="f32")=>{let m=fe=>{switch(fe){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${f}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${fe} is not supported.`)}},g=fe=>{switch(fe){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 ${fe} is not supported.`)}},w=e?`
|
|
914
|
+
let coord = vec4<i32>(batch, xRow, xCol, xCh);
|
|
915
|
+
`:`
|
|
916
|
+
let coord = vec4<i32>(batch, xCh, xRow, xCol);
|
|
917
|
+
`,_=e?`
|
|
918
|
+
let coords = vec4<i32>(
|
|
919
|
+
batch,
|
|
920
|
+
row / outWidth,
|
|
921
|
+
row % outWidth,
|
|
922
|
+
col);
|
|
923
|
+
`:`
|
|
924
|
+
let coords = vec4<i32>(
|
|
925
|
+
batch,
|
|
926
|
+
row,
|
|
927
|
+
col / outWidth,
|
|
928
|
+
col % outWidth);
|
|
929
|
+
`,b=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",x=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",M=e?"row":"col",k=e?"col":"row",$=`
|
|
930
|
+
let inChannels = i32(uniforms.w_shape[2]);
|
|
931
|
+
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
|
|
932
|
+
let outRow = ${M} / outWidth;
|
|
933
|
+
let outCol = ${M} % outWidth;
|
|
934
|
+
|
|
935
|
+
let WRow = ${k} / (i32(uniforms.w_shape[1]) * inChannels);
|
|
936
|
+
let WCol = ${k} / inChannels % i32(uniforms.w_shape[1]);
|
|
937
|
+
let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];
|
|
938
|
+
let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];
|
|
939
|
+
let xCh = ${k} % inChannels;
|
|
940
|
+
var resData = ${Vt(u,f)}(0.0);
|
|
941
|
+
// The bounds checking is always needed since we use it to pad zero for
|
|
942
|
+
// the 'same' padding type.
|
|
943
|
+
if (xRow >= 0 && xRow < ${b} && xCol >= 0 && xCol < ${x}) {
|
|
944
|
+
${w}
|
|
945
|
+
let xIndex = getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape));
|
|
946
|
+
${m(u)}
|
|
947
|
+
}
|
|
948
|
+
return resData;`,O=e?t&&i?`
|
|
949
|
+
let col = colIn * ${u};
|
|
950
|
+
${$}`:`
|
|
951
|
+
let col = colIn * ${u};
|
|
952
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {
|
|
953
|
+
${$}
|
|
954
|
+
}
|
|
955
|
+
return ${Vt(u,f)}(0.0);`:i&&n?`
|
|
956
|
+
let col = colIn * ${u};
|
|
957
|
+
${$}`:`
|
|
958
|
+
let col = colIn * ${u};
|
|
959
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
|
|
960
|
+
${$}
|
|
961
|
+
}
|
|
962
|
+
return ${Vt(u,f)}(0.0);`,I=e?i&&n?g(c):`
|
|
963
|
+
let col = colIn * ${c};
|
|
964
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
|
|
965
|
+
${g(c)}
|
|
966
|
+
}
|
|
967
|
+
return ${Vt(c,f)}(0.0);`:`
|
|
968
|
+
let col = colIn * ${c};
|
|
969
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {
|
|
970
|
+
${g(c)}
|
|
971
|
+
}
|
|
972
|
+
return ${Vt(c,f)}(0.0);`,B=Vt(h,f),q=Vt(e?u:c,f),W=Vt(e?c:u,f),te=Is(l,B,f);return`
|
|
973
|
+
fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${q} {
|
|
974
|
+
${e?O:I}
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${W} {
|
|
978
|
+
${e?I:O}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${B}) {
|
|
982
|
+
let col = colIn * ${h};
|
|
983
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)
|
|
984
|
+
{
|
|
985
|
+
var value = valueIn;
|
|
986
|
+
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
|
|
987
|
+
${_}
|
|
988
|
+
${$u(o)}
|
|
989
|
+
${te}
|
|
990
|
+
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
|
|
991
|
+
}
|
|
992
|
+
}`},Mu=(e,t,n,i,o,l,u,c,h)=>{let f=t.format==="NHWC",m=f?e[0].dims[3]:e[0].dims[1],g=n[0],w=f?n[2]:n[3],_=f?n[1]:n[2],b=f?n[3]:n[1],x=f&&(m%4===0||m%3===0)&&b%4===0,M=f?b:w*_,k=f?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])];Qe("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${I}`);let B=x?f&&m%4!==0?3:4:1,q=$[1]*O[1],W=$[0]*O[0],te=Math.max($[0]*B,$[1]),fe=i%q===0,be=o%W===0,qe=l%te===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}];Ms(t,Me),Me.push(...L(e[0].dims,e[1].dims));let rt=["rank","rank"];u&&(Me.push(...L(e[2].dims)),rt.push("rank")),Me.push(...L(n));let ye=xe=>{let Be=[{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}];Os(t,Be);let je=x?4:1,Le=G(e[0].dataType),Xe=`
|
|
993
|
+
fn setOutputAtIndex(flatIndex : i32, value : ${x?`vec4<${Le}>`:Le}) {
|
|
994
|
+
result[flatIndex] = ${x?`vec4<${Le}>`:Le}(value);
|
|
995
|
+
}
|
|
996
|
+
fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${x?`vec4<${Le}>`:Le}) {
|
|
997
|
+
let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));
|
|
998
|
+
setOutputAtIndex(flatIndex ${x?"/ 4":""}, value);
|
|
999
|
+
}`,ue=U("x",e[0].dataType,e[0].dims.length,B===3?1:B),ze=U("w",e[1].dataType,e[1].dims.length,je),Ae=[ue,ze],$e=de("result",e[0].dataType,n.length,je);if(u){let Kt=U("bias",e[2].dataType,e[2].dims.length,je);Ae.push(Kt),Xe+=`
|
|
1000
|
+
fn getBiasByOutputCoords(coords : vec4<i32>) -> ${x?`vec4<${Le}>`:Le} {
|
|
1001
|
+
return bias[coords.${f?"w":"y"}${x?"/ 4":""}];
|
|
1002
|
+
}`}return`
|
|
1003
|
+
${xu("uniforms.result_strides")}
|
|
1004
|
+
//struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>,
|
|
1005
|
+
// outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>,
|
|
1006
|
+
// dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };
|
|
1007
|
+
${xe.registerUniforms(Be).declareVariables(...Ae,$e)}
|
|
1008
|
+
${Xe}
|
|
1009
|
+
${Iu(f,fe,be,qe,u,t,Re[0],Re[1],Re[2],Le)}
|
|
1010
|
+
${x?ca(O,$,Le,void 0,!f,te):pa(O,$,Le,void 0,!f,te,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${B};${x};${fe};${be};${qe};${q};${W};${te}`,inputDependencies:rt},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}}}),Ou,ma,Hn,Pu,ga,Du,zu,Lu,km=S(()=>{Ie(),hr(),ke(),we(),Ps(),la(),Ou=e=>{let t=1;for(let n=0;n<e.length;n++)t*=e[n];return t},ma=e=>typeof e=="number"?[e,e,e]:e,Hn=(e,t)=>t<=1?e:e+(e-1)*(t-1),Pu=(e,t,n,i=1)=>{let o=Hn(t,i);return Math.floor((e[0]*(n-1)-n+o)/2)},ga=(e,t,n,i,o)=>{o==null&&(o=Pu(e,t[0],i[0]));let l=[0,0,0,n];for(let u=0;u<3;u++)e[u]+2*o>=t[u]&&(l[u]=Math.trunc((e[u]-t[u]+2*o)/i[u]+1));return l},Du=(e,t,n,i,o,l,u,c,h,f)=>{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=ga([t,n,i,1],[c,h,f],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=ga([t,n,i,1],[c,h,f],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+f-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:_}},zu=(e,t,n,i,o,l=!1,u="channelsLast")=>{let c,h,f,m,g;if(u==="channelsLast")[c,h,f,m,g]=e;else if(u==="channelsFirst")[c,g,h,f,m]=e;else throw new Error(`Unknown dataFormat ${u}`);let[w,,_,b,x]=t,[M,k,$]=ma(n),[O,I,B]=ma(i),q=Hn(_,O),W=Hn(b,I),te=Hn(x,B),{padInfo:fe,outDepth:be,outHeight:qe,outWidth:Re}=Du(o,h,f,m,M,k,$,q,W,te),Me=l?w*g:w,rt=[0,0,0,0,0];return u==="channelsFirst"?rt=[c,Me,be,qe,Re]:u==="channelsLast"&&(rt=[c,be,qe,Re,Me]),{batchSize:c,dataFormat:u,inDepth:h,inHeight:f,inWidth:m,inChannels:g,outDepth:be,outHeight:qe,outWidth:Re,outChannels:Me,padInfo:fe,strideDepth:M,strideHeight:k,strideWidth:$,filterDepth:_,filterHeight:b,filterWidth:x,effectiveFilterDepth:q,effectiveFilterHeight:W,effectiveFilterWidth:te,dilationDepth:O,dilationHeight:I,dilationWidth:B,inShape:e,outShape:rt,filterShape:t}},Lu=(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)},f=[Math.ceil(Ou(h.x.map(M=>n[M]))/c[0]),1,1];Qe("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${f}`);let m=1,g=j.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}];Ms(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}];Os(t,k);let $=1,O=G(e[0].dataType),I=U("x",e[0].dataType,e[0].dims.length,m),B=U("W",e[1].dataType,e[1].dims.length,$),q=[I,B],W=de("result",e[0].dataType,n.length,$),te="";if(b){let qe=U("bias",e[2].dataType,e[2].dims.length,$);q.push(qe),te+=`
|
|
1011
|
+
fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${O} {
|
|
1012
|
+
return bias[${u?K("coords",4,5):K("coords",1,5)}];
|
|
1013
|
+
}`}let fe=Vt(m,O),be=Is(t,fe,O);return`
|
|
1014
|
+
${te}
|
|
1015
|
+
fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
|
|
1016
|
+
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
|
|
1017
|
+
return ${I.getByIndices("aIndices")};
|
|
1018
|
+
}
|
|
1019
|
+
fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
|
|
1020
|
+
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
|
|
1021
|
+
return ${B.getByIndices("aIndices")};
|
|
1022
|
+
}
|
|
1023
|
+
${M.registerUniforms(k).declareVariables(...q,W)}
|
|
1024
|
+
${M.mainStart()}
|
|
1025
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1026
|
+
let coords = ${W.offsetToIndices("global_idx")};
|
|
1027
|
+
let batch = ${K("coords",0,I.rank)};
|
|
1028
|
+
let d2 = ${u?K("coords",I.rank-1,I.rank):K("coords",1,I.rank)};
|
|
1029
|
+
let xFRCCorner = vec3<u32>(${u?K("coords",1,I.rank):K("coords",2,I.rank)},
|
|
1030
|
+
${u?K("coords",2,I.rank):K("coords",3,I.rank)},
|
|
1031
|
+
${u?K("coords",3,I.rank):K("coords",4,I.rank)}) * uniforms.strides - uniforms.pads;
|
|
1032
|
+
let xFCorner = xFRCCorner.x;
|
|
1033
|
+
let xRCorner = xFRCCorner.y;
|
|
1034
|
+
let xCCorner = xFRCCorner.z;
|
|
1035
|
+
let xShapeY = ${u?K("uniforms.x_shape",1,I.rank):K("uniforms.x_shape",2,I.rank)};
|
|
1036
|
+
let xShapeZ = ${u?K("uniforms.x_shape",2,I.rank):K("uniforms.x_shape",3,I.rank)};
|
|
1037
|
+
let xShapeW = ${u?K("uniforms.x_shape",3,I.rank):K("uniforms.x_shape",4,I.rank)};
|
|
1038
|
+
let xShapeU = ${u?K("uniforms.x_shape",4,I.rank):K("uniforms.x_shape",1,I.rank)};
|
|
1039
|
+
let inputDepthNearestVec4 = (xShapeU / 4) * 4;
|
|
1040
|
+
let inputDepthVec4Remainder = xShapeU % 4;
|
|
1041
|
+
|
|
1042
|
+
var value = 0.0;
|
|
1043
|
+
for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {
|
|
1044
|
+
let xF = xFCorner + wF * uniforms.dilations[0];
|
|
1045
|
+
if (xF < 0 || xF >= xShapeY) {
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {
|
|
1050
|
+
let xR = xRCorner + wR * uniforms.dilations[1];
|
|
1051
|
+
if (xR < 0 || xR >= xShapeZ) {
|
|
1052
|
+
continue;
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {
|
|
1056
|
+
let xC = xCCorner + wC * uniforms.dilations[2];
|
|
1057
|
+
if (xC < 0 || xC >= xShapeW) {
|
|
1058
|
+
continue;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {
|
|
1062
|
+
${u?`let xValues = vec4<f32>(
|
|
1063
|
+
getX(batch, xF, xR, xC, d1),
|
|
1064
|
+
getX(batch, xF, xR, xC, d1 + 1),
|
|
1065
|
+
getX(batch, xF, xR, xC, d1 + 2),
|
|
1066
|
+
getX(batch, xF, xR, xC, d1 + 3));
|
|
1067
|
+
`:`let xValues = vec4<f32>(
|
|
1068
|
+
getX(batch, d1, xF, xR, xC),
|
|
1069
|
+
getX(batch, d1 + 1, xF, xR, xC),
|
|
1070
|
+
getX(batch, d1 + 2, xF, xR, xC),
|
|
1071
|
+
getX(batch, d1 + 3, xF, xR, xC));
|
|
1072
|
+
`}
|
|
1073
|
+
let wValues = vec4<f32>(
|
|
1074
|
+
getW(d2, d1, wF, wR, wC),
|
|
1075
|
+
getW(d2, d1 + 1, wF, wR, wC),
|
|
1076
|
+
getW(d2, d1 + 2, wF, wR, wC),
|
|
1077
|
+
getW(d2, d1 + 3, wF, wR, wC));
|
|
1078
|
+
value += dot(xValues, wValues);
|
|
1079
|
+
}
|
|
1080
|
+
if (inputDepthVec4Remainder == 1) {
|
|
1081
|
+
${u?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4)
|
|
1082
|
+
* getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC)
|
|
1083
|
+
* getW(d2, inputDepthNearestVec4, wF, wR, wC);`}
|
|
1084
|
+
} else if (inputDepthVec4Remainder == 2) {
|
|
1085
|
+
${u?`let xValues = vec2<f32>(
|
|
1086
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4),
|
|
1087
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));
|
|
1088
|
+
`:`let xValues = vec2<f32>(
|
|
1089
|
+
getX(batch, inputDepthNearestVec4, xF, xR, xC),
|
|
1090
|
+
getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));
|
|
1091
|
+
`}
|
|
1092
|
+
let wValues = vec2<f32>(
|
|
1093
|
+
getW(d2, inputDepthNearestVec4, wF, wR, wC),
|
|
1094
|
+
getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));
|
|
1095
|
+
value += dot(xValues, wValues);
|
|
1096
|
+
} else if (inputDepthVec4Remainder == 3) {
|
|
1097
|
+
${u?`let xValues = vec3<f32>(
|
|
1098
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4),
|
|
1099
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),
|
|
1100
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));
|
|
1101
|
+
`:`let xValues = vec3<f32>(
|
|
1102
|
+
getX(batch, inputDepthNearestVec4, xF, xR, xC),
|
|
1103
|
+
getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),
|
|
1104
|
+
getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));
|
|
1105
|
+
`}
|
|
1106
|
+
let wValues = vec3<f32>(
|
|
1107
|
+
getW(d2, inputDepthNearestVec4, wF, wR, wC),
|
|
1108
|
+
getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),
|
|
1109
|
+
getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));
|
|
1110
|
+
value += dot(xValues, wValues);
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
${b?"value = value + getBiasByOutputCoords(coords)":""};
|
|
1116
|
+
${be}
|
|
1117
|
+
result[global_idx] = f32(value);
|
|
1118
|
+
}`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${u};${m};${b}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:f[0],y:f[1],z:f[2]},programUniforms:w}),getShaderSource:x}}}),Bu,Nu,Rm=S(()=>{Ie(),ke(),we(),Ps(),Bu=(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",f=h?n[3]:n[1],m=f/t.group,g=h&&m>=4?V(f):1,w=j.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}];Ms(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=de("output",e[0].dataType,n.length,g),$=G(k.type.tensor),O=Is(t,k.type.value,$),I=U("x",e[0].dataType,u.length),B=U("w",e[1].dataType,c.length,g),q=[I,B];o&&q.push(U("b",e[2].dataType,e[2].dims,g));let W=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Os(t,W);let te=h?`
|
|
1119
|
+
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {
|
|
1120
|
+
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
|
|
1121
|
+
|
|
1122
|
+
if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {
|
|
1123
|
+
continue;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {
|
|
1127
|
+
let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
|
|
1128
|
+
if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {
|
|
1129
|
+
continue;
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {
|
|
1133
|
+
let input_channel = in_channel_offset + wInChannel;
|
|
1134
|
+
let xVal = ${I.get("batch","xHeight","xWidth","input_channel")};
|
|
1135
|
+
let wVal = ${B.get("wHeight","wWidth","wInChannel","output_channel")};
|
|
1136
|
+
value += xVal * wVal;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
`:`
|
|
1141
|
+
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {
|
|
1142
|
+
let input_channel = in_channel_offset + wInChannel;
|
|
1143
|
+
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {
|
|
1144
|
+
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
|
|
1145
|
+
|
|
1146
|
+
if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {
|
|
1147
|
+
continue;
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {
|
|
1151
|
+
let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
|
|
1152
|
+
if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {
|
|
1153
|
+
continue;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
let xVal = ${I.get("batch","input_channel","xHeight","xWidth")};
|
|
1157
|
+
let wVal = ${B.get("output_channel","wInChannel","wHeight","wWidth")};
|
|
1158
|
+
value += xVal * wVal;
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
`;return`
|
|
1163
|
+
${M.registerUniforms(W).declareVariables(...q,k)}
|
|
1164
|
+
|
|
1165
|
+
${M.mainStart()}
|
|
1166
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1167
|
+
|
|
1168
|
+
let outputIndices = ${k.offsetToIndices("global_idx")};
|
|
1169
|
+
let batch: u32 = outputIndices[0];
|
|
1170
|
+
let output_channel: u32 = outputIndices[${h?3:1}];
|
|
1171
|
+
let xRCCorner: vec2<u32> = vec2<u32>(outputIndices[${h?1:2}], outputIndices[${h?2:3}]) * uniforms.strides - uniforms.pads;
|
|
1172
|
+
let group_id: u32 = output_channel * ${g} / uniforms.output_channels_per_group;
|
|
1173
|
+
var in_channel_offset = group_id * uniforms.w_shape[${h?2:1}];
|
|
1174
|
+
|
|
1175
|
+
var value: ${k.type.value} = ${k.type.value}(0);
|
|
1176
|
+
${te}
|
|
1177
|
+
${l}
|
|
1178
|
+
${O}
|
|
1179
|
+
${k.setByOffset("global_idx","value")}
|
|
1180
|
+
}`};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}},Nu=(e,t,n,i)=>{let o=e.length>2,l=V(n[3]),u=V(n[2]),c=j.size(n)/l/u,h=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/l],f=[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]]}];Ms(t,g),g.push(...L(h,f,m));let w=(u-1)*t.strides[1]+f[1],_=b=>{let x=de("output",e[0].dataType,m.length,l),M=G(x.type.tensor),k=Is(t,x.type.value,M),$=U("x",e[0].dataType,h.length,l),O=U("w",e[1].dataType,f.length,l),I=[$,O];o&&I.push(U("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 Os(t,q),`
|
|
1181
|
+
${b.registerUniforms(q).declareVariables(...I,x)}
|
|
1182
|
+
${b.mainStart()}
|
|
1183
|
+
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1184
|
+
let width0 = uniforms.output_shape[3];
|
|
1185
|
+
let output_channel = global_idx % width0;
|
|
1186
|
+
var index1 = global_idx / width0;
|
|
1187
|
+
let width1 = uniforms.output_shape[2] / ${u}u;
|
|
1188
|
+
let col = (index1 % width1) * ${u}u;
|
|
1189
|
+
index1 = index1 / width1;
|
|
1190
|
+
let row = index1 % uniforms.output_shape[1];
|
|
1191
|
+
let batch = index1 / uniforms.output_shape[1];
|
|
1192
|
+
|
|
1193
|
+
let x_corner = vec2<i32>(i32(row), i32(col)) * uniforms.strides - uniforms.pads;
|
|
1194
|
+
|
|
1195
|
+
var x_vals: array<${$.type.value}, ${w}>;
|
|
1196
|
+
var values: array<${x.type.value}, ${u}>;
|
|
1197
|
+
let input_channel = output_channel;
|
|
1198
|
+
// Use constant instead of uniform can give better performance for w's height/width.
|
|
1199
|
+
for (var w_height: u32 = 0u; w_height < ${f[0]}; w_height++) {
|
|
1200
|
+
let x_height = x_corner.x + i32(w_height);
|
|
1201
|
+
if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {
|
|
1202
|
+
for (var i = 0; i < ${w}; i++) {
|
|
1203
|
+
let x_width = x_corner.y + i;
|
|
1204
|
+
if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {
|
|
1205
|
+
x_vals[i] = ${$.get("batch","u32(x_height)","u32(x_width)","input_channel")};
|
|
1206
|
+
} else {
|
|
1207
|
+
x_vals[i] = ${$.type.value}(0);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
for (var w_width: u32 = 0u; w_width < ${f[1]}; w_width++) {
|
|
1211
|
+
let w_val = ${O.get("w_height","w_width","0","output_channel")};
|
|
1212
|
+
for (var i = 0u; i < ${u}u; i++) {
|
|
1213
|
+
values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
for (var i = 0u; i < ${u}u; i++) {
|
|
1220
|
+
var value = values[i];
|
|
1221
|
+
${B}
|
|
1222
|
+
${k}
|
|
1223
|
+
${x.set("batch","row","col + i","output_channel","value")};
|
|
1224
|
+
}
|
|
1225
|
+
}`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${l};${u};${w};${f[0]};${f[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:_}}}),Uu,$i,Fu,xi,ya,wa,Vu,Gu,va,Am=S(()=>{ke(),Cm(),km(),fa(),Rm(),Ps(),da(),Ge(),Uu=(e,t,n,i,o,l)=>{let u=e[0],c=e.slice(l?1:2,l?3:4),h=c.length,f=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,f),g},$i=[2,3,1,0],Fu=(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")},xi=(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();Zr.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},ya=e=>{let t=oa(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,f=e.w_is_const();return{autoPad:i,format:n,dilations:o,group:l,kernelShape:u,pads:c,strides:h,wIsConst:f,...t,cacheKey:`${e.format};${t.activation};`}},wa=(e,t,n,i)=>{let o=n.format==="NHWC",l=Uu(t[0].dims,t[1].dims,n.dilations,n.pads,n.strides,o);if(n.group!==1){let q=[t[0]];if(o){let W=e.kernelCustomData.wT??e.compute(_t(t[1],$i),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=W),q.push(W)}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(Nu(q,n,l,i),{inputs:q}):e.compute(Bu(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],f=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],W,te,fe,be=[];if(o){let Me=e.kernelCustomData.wT??e.compute(_t(t[1],$i),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Me),x){let rt=c*h*f;W=t[0].reshape([1,q,rt]),te=Me.reshape([1,rt,b]),fe=[1,q,b]}else W=t[0].reshape([q,c*h,f]),te=Me.reshape([1,f,b]),fe=[q,w*_,b];be.push(W),be.push(te)}else W=t[0].reshape([q,f,c*h]),te=t[1].reshape([1,b,f]),fe=[q,b,w*_],be.push(te),be.push(W);u&&be.push(t[2]);let qe=fe[2],Re=be[0].dims[be[0].dims.length-1];qe<8&&Re<8?e.compute(ua(be,n,l,fe,o,i),{inputs:be}):e.compute(Ei(be,n,l,fe,o,i),{inputs:be});return}let M=!0,k=e.kernelCustomData.wT??e.compute(_t(t[1],$i),{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*f;e.compute(Mu($,n,l,O,I,B,u,M,i),{inputs:$})},Vu=(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=xi({...t,pads:o,strides:l,dilations:u,kernelShape:c},i);wa(e,i,h,f=>n?[f[0],f[2],f[3]]:[f[0],f[1],f[3]])},Gu=(e,t,n)=>{let i=n.format==="NHWC"?"channelsLast":"channelsFirst",o=xi(n,t),l=n.autoPad==="NOTSET"?n.pads:n.autoPad,u=zu(t[0].dims,t[1].dims,n.strides,n.dilations,l,!1,i);e.compute(Lu(t,o,u.outShape,[u.filterDepth,u.filterHeight,u.filterWidth],[u.padInfo.front,u.padInfo.top,u.padInfo.left],i))},va=(e,t)=>{if(Fu(e.inputs,t),e.inputs[0].dims.length===3)Vu(e,t);else if(e.inputs[0].dims.length===5)Gu(e,e.inputs,t);else{let n=xi(t,e.inputs);wa(e,e.inputs,n)}}}),qu,Im=S(()=>{Ie(),hr(),ke(),we(),qu=(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,f=c[3],m=l?V(h):1,g=l&&f===1&&h>=4,w=g?Math.floor(h/4)*4:Math.floor(h/m)*m,_=h-w,b=l?V(f):1,x=l?f===1?m:b:1,M=j.size(o)/b,k=[Math.ceil(M/64),1,1];Qe("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))],W=[q[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),q[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],te=[{type:12,data:M},{type:12,data:O},{type:12,data:I},{type:12,data:B},{type:12,data:q},{type:6,data:W},{type:12,data:w},{type:12,data:h},{type:12,data:f},...L(e[0].dims,e[1].dims)];i&&(te.push(...L(e[2].dims)),$.push("rank")),te.push(...L(o));let fe=be=>{let qe=[{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:W.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,rt=l?2:3,ye=l?3:1,xe=U("W",e[1].dataType,e[1].dims.length,x),Be=U("Dy",e[0].dataType,e[0].dims.length,m),je=[Be,xe];i&&je.push(U("bias",e[2].dataType,[o[ye]].length,b));let Le=de("result",e[0].dataType,o.length,b),Xe=()=>{let Ae="";if(g)m===4?Ae+=`
|
|
1226
|
+
let xValue = ${Be.getByOffset("x_offset")};
|
|
1227
|
+
let wValue = ${xe.getByOffset("w_offset")};
|
|
1228
|
+
dotProd = dotProd + dot(xValue, wValue);
|
|
1229
|
+
x_offset += 1u;
|
|
1230
|
+
w_offset += 1u;`:m===2?Ae+=`
|
|
1231
|
+
dotProd = dotProd + dot(vec4<${Re}>(${Be.getByOffset("x_offset")}, ${Be.getByOffset("x_offset + 1u")}), vec4<${Re}>(${xe.getByOffset("w_offset")}, ${xe.getByOffset("w_offset + 1u")}));
|
|
1232
|
+
x_offset += 2u;
|
|
1233
|
+
w_offset += 2u;`:m===1&&(Ae+=`
|
|
1234
|
+
dotProd = dotProd + dot(vec4<${Re}>(${Be.getByOffset("x_offset")}, ${Be.getByOffset("x_offset + 1u")}, ${Be.getByOffset("x_offset + 2u")}, ${Be.getByOffset("x_offset + 3u")}), vec4<${Re}>(${xe.getByOffset("w_offset")}, ${xe.getByOffset("w_offset + 1u")}, ${xe.getByOffset("w_offset + 2u")}, ${xe.getByOffset("w_offset + 3u")}));
|
|
1235
|
+
x_offset += 4u;
|
|
1236
|
+
w_offset += 4u;`);else if(Ae+=`
|
|
1237
|
+
let xValue = ${l?Be.getByOffset(`${Be.indicesToOffset(`${Be.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${m}`):Be.get("batch","inputChannel","idyR","idyC")};
|
|
1238
|
+
`,m===1)Ae+=`
|
|
1239
|
+
let w_offset = ${xe.indicesToOffset(`${xe.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};
|
|
1240
|
+
let wValue = ${xe.getByOffset(`w_offset / ${x}`)};
|
|
1241
|
+
dotProd = dotProd + xValue * wValue;`;else for(let $e=0;$e<m;$e++)Ae+=`
|
|
1242
|
+
let wValue${$e} = ${xe.getByOffset(`${xe.indicesToOffset(`${xe.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${$e}, wOutChannel)`)} / ${x}`)};
|
|
1243
|
+
dotProd = dotProd + xValue[${$e}] * wValue${$e};`;return Ae},ue=()=>{if(_===0)return"";if(!g)throw new Error(`packInputAs4 ${g} is not true.`);let Ae="";if(m===1){Ae+="dotProd = dotProd";for(let $e=0;$e<_;$e++)Ae+=`
|
|
1244
|
+
+ ${Be.getByOffset(`x_offset + ${$e}`)} * ${xe.getByOffset(`w_offset + ${$e}`)}`;Ae+=";"}else if(m===2){if(_!==2)throw new Error(`Invalid inputChannelsRemainder ${_}.`);Ae+=`
|
|
1245
|
+
let xValue = ${Be.getByOffset("x_offset")};
|
|
1246
|
+
let wValue = ${xe.getByOffset("w_offset")};
|
|
1247
|
+
dotProd = dotProd + dot(xValue, wValue);`}return Ae},ze=`
|
|
1248
|
+
let outputIndices = ${Le.offsetToIndices(`global_idx * ${b}`)};
|
|
1249
|
+
let batch = ${Le.indicesGet("outputIndices",0)};
|
|
1250
|
+
let d1 = ${Le.indicesGet("outputIndices",ye)};
|
|
1251
|
+
let r = ${Le.indicesGet("outputIndices",Me)};
|
|
1252
|
+
let c = ${Le.indicesGet("outputIndices",rt)};
|
|
1253
|
+
let dyCorner = vec2<i32>(i32(r), i32(c)) - uniforms.pads;
|
|
1254
|
+
let dyRCorner = dyCorner.x;
|
|
1255
|
+
let dyCCorner = dyCorner.y;
|
|
1256
|
+
let groupId = d1 / uniforms.output_channels_per_group;
|
|
1257
|
+
let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;
|
|
1258
|
+
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
1259
|
+
// ? = to be determined. : = across all values in that axis.
|
|
1260
|
+
var dotProd = ${Le.type.value}(0.0);
|
|
1261
|
+
var wR: u32 = 0;
|
|
1262
|
+
if (uniforms.dilations.x == 1) {
|
|
1263
|
+
// Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0
|
|
1264
|
+
wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner);
|
|
1265
|
+
}
|
|
1266
|
+
for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {
|
|
1267
|
+
if (wR % uniforms.dilations.x != 0) {
|
|
1268
|
+
continue;
|
|
1269
|
+
}
|
|
1270
|
+
let dyR = (${Re}(dyRCorner) + ${Re}(wR)) / ${Re}(uniforms.strides[0]);
|
|
1271
|
+
let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;
|
|
1272
|
+
if (dyR < 0.0 || dyR >= ${Re}(uniforms.Dy_shape[${Me}]) || fract(dyR) > 0.0 ||
|
|
1273
|
+
wRPerm < 0) {
|
|
1274
|
+
continue;
|
|
1275
|
+
}
|
|
1276
|
+
let idyR: u32 = u32(dyR);
|
|
1277
|
+
var wC: u32 = 0;
|
|
1278
|
+
if (uniforms.dilations.y == 1) {
|
|
1279
|
+
// Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0
|
|
1280
|
+
wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner);
|
|
1281
|
+
}
|
|
1282
|
+
for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {
|
|
1283
|
+
if (wC % uniforms.dilations.y != 0) {
|
|
1284
|
+
continue;
|
|
1285
|
+
}
|
|
1286
|
+
let dyC = (${Re}(dyCCorner) + ${Re}(wC)) / ${Re}(uniforms.strides.y);
|
|
1287
|
+
let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;
|
|
1288
|
+
if (dyC < 0.0 || dyC >= ${Re}(uniforms.Dy_shape[${rt}]) ||
|
|
1289
|
+
fract(dyC) > 0.0 || wCPerm < 0) {
|
|
1290
|
+
continue;
|
|
1291
|
+
}
|
|
1292
|
+
let idyC: u32 = u32(dyC);
|
|
1293
|
+
var inputChannel = groupId * uniforms.input_channels_per_group;
|
|
1294
|
+
${g?`
|
|
1295
|
+
var x_offset = ${Be.indicesToOffset(`${Be.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${m};
|
|
1296
|
+
var w_offset = ${xe.indicesToOffset(`${xe.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${x};
|
|
1297
|
+
`:""}
|
|
1298
|
+
for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${g?4:m}) {
|
|
1299
|
+
${Xe()}
|
|
1300
|
+
inputChannel = inputChannel + ${g?4:m};
|
|
1301
|
+
}
|
|
1302
|
+
${ue()}
|
|
1303
|
+
wC = wC + uniforms.strides.y - 1;
|
|
1304
|
+
}
|
|
1305
|
+
wR = wR + uniforms.strides[0] - 1;
|
|
1306
|
+
}
|
|
1307
|
+
let value = dotProd${i?` + bias[d1 / ${b}]`:""};
|
|
1308
|
+
${Le.setByOffset("global_idx","value")};
|
|
1309
|
+
`;return`
|
|
1310
|
+
${be.registerUniforms(qe).declareVariables(...je,Le)}
|
|
1311
|
+
${be.mainStart()}
|
|
1312
|
+
${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};
|
|
1313
|
+
${ze}}`};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:te}),getShaderSource:fe}}}),Wu,Hu,ju,_a,Ku,Qu,ba,Xu,Yu,Mm=S(()=>{Im(),Ps(),Ge(),Wu=(e,t,n,i,o,l)=>(e-1)*t+n+(i-1)*o+1-l,Hu=(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)},ju=(e,t,n,i,o,l,u,c,h,f)=>{let m=e.length-2,g=f.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]:f[b],$=Wu(M,u[b],l[b],t[x],n[b],k);Hu($,i,l,b,b+m),g&&f.push(u[b]*(M-1)+h[b]+(t[x]-1)*n[b]+1-l[b]-l[b+m])}f.splice(0,0,w),f.splice(c?3:1,0,_)},_a=(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 f=e.strides.slice();if(f.reduce((g,w)=>g+w,0)===0){let g=t[0].dims.length-2;f=new Array(g).fill(1)}ju(c,n,h,e.autoPad,e.group,o,f,i,u,l);let m=Object.assign({},e);return Object.assign(m,{kernelShape:n,pads:o,outputPadding:u,outputShape:l,dilations:h,strides:f}),m},Ku=e=>{let t=oa(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,f=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:f,...t,cacheKey:`${e.format};${t.activation};`}},Qu=(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")},ba=(e,t,n,i)=>{let o=e.kernelCustomData.wT??e.compute(_t(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(qu(l,n,i),{inputs:l})},Xu=(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 f=_a({...t,pads:c,strides:u,dilations:l,kernelShape:o,outputPadding:h},i);ba(e,i,f,m=>n?[m[0],m[2],m[3]]:[m[0],m[1],m[3]])},Yu=(e,t)=>{if(Qu(e.inputs,t),e.inputs[0].dims.length===3)Xu(e,t);else{let n=_a(t,e.inputs);ba(e,e.inputs,n)}}}),Ju,Zu,ed,Om=S(()=>{Ie(),ke(),A(),we(),Ju=(e,t,n,i)=>{let o=j.size(t),l=t.length,u=U("input",e,l),c=de("output",e,l),h=n.dataType===6?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),f=j.normalizeAxis(h,l),m=g=>{let w=` i32(${u.indicesGet("inputIndices","uniforms.axis")}) `,_=K("uniforms.input_shape","uniforms.axis",l),b=i.reverse?w+(i.exclusive?" + 1":""):"0",x=i.reverse?_:w+(i.exclusive?"":" + 1");return`
|
|
1314
|
+
${g.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(u,c)}
|
|
1315
|
+
${g.mainStart()}
|
|
1316
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1317
|
+
var inputIndices = ${c.offsetToIndices("global_idx")};
|
|
1318
|
+
var sum = ${c.type.value}(0);
|
|
1319
|
+
let first : i32 = ${b};
|
|
1320
|
+
let last : i32 = ${x};
|
|
1321
|
+
for (var i : i32 = first; i < last; i++) {
|
|
1322
|
+
${u.indicesSet("inputIndices","uniforms.axis","u32(i)")};
|
|
1323
|
+
sum = sum + ${u.getByIndices("inputIndices")};
|
|
1324
|
+
}
|
|
1325
|
+
${c.setByOffset("global_idx","sum")};
|
|
1326
|
+
}`};return{name:"CumSum",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:f},...L(t,t)]}),getShaderSource:m}},Zu=(e,t)=>{let n=e.inputs[0].dims,i=e.inputs[0].dataType,o=e.inputs[1];e.compute(Ju(i,n,o,t),{inputs:[0]})},ed=e=>{let t=e.exclusive===1,n=e.reverse===1;return E({exclusive:t,reverse:n})}}),td,rd,sd,nd,id,Pm=S(()=>{Ie(),ke(),A(),we(),td=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},rd=(e,t,n,i)=>{let o=[];o.push(`fn perm(i: ${i.type.indices}) -> ${n.type.indices} {
|
|
1327
|
+
var a: ${n.type.indices};`);for(let l=0;l<t;++l)o.push(n.indicesSet("a",e[l],`i[${l}]`));return o.push("return a;}"),o.join(`
|
|
1328
|
+
`)},sd=(e,t)=>{let n,i,o,l,u,c,h=t.format==="NHWC",f=t.blocksize,m=t.mode==="DCR";h?([n,i,o,l]=e.dims,u=m?[n,i,o,f,f,l/f**2]:[n,i,o,l/f**2,f,f],c=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,i,o,l]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],u=m?[n,f,f,l/f**2,i,o]:[n,l/f**2,f,f,i,o],c=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let g=e.reshape(u),w=g.dims.length,_=e.dataType,b=U("a",_,w),x=de("output",_,w),M=k=>`
|
|
1329
|
+
${k.registerUniform("output_size","u32").declareVariables(b,x)}
|
|
1330
|
+
|
|
1331
|
+
${rd(c,w,b,x)}
|
|
1332
|
+
|
|
1333
|
+
${k.mainStart()}
|
|
1334
|
+
${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1335
|
+
|
|
1336
|
+
let indices = ${x.offsetToIndices("global_idx")};
|
|
1337
|
+
let aIndices = perm(indices);
|
|
1338
|
+
|
|
1339
|
+
${x.setByOffset("global_idx",b.getByIndices("aIndices"))}
|
|
1340
|
+
}`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:k=>{let $=h?[n,i*f,o*f,l/f**2]:[n,l/f**2,i*f,o*f],O=j.size($),I=g.dims,B=j.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}},nd=(e,t)=>{td(e.inputs),e.compute(sd(e.inputs[0],t))},id=e=>E({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Ci,jn,Sa,ad,od,ld,ud,Ta,dd,cd,hd,Dm=S(()=>{Ie(),ke(),A(),we(),Ci="[a-zA-Z]|\\.\\.\\.",jn="("+Ci+")+",Sa="^"+jn+"$",ad="("+jn+",)*"+jn,od="^"+ad+"$",ld=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)}},ud=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(od)))throw new Error("Invalid LHS term");if(n.split(",").forEach((o,l)=>{let u=e[l].dims.slice();if(!o.match(RegExp(Sa)))throw new Error("Invalid LHS term");let c=this.processTerm(o,!0,u,l);this.lhs.push(c)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([o,l])=>l.count===1||o==="...").map(([o])=>o).join("");else if(!i.match(RegExp(jn)))throw new Error("Invalid RHS");i.match(RegExp(Ci,"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(Sa))&&!t&&e!=="")throw new Error("Invalid LHS term");let h=e.match(RegExp(Ci,"g")),f=new ld(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+_);f.addSymbol(b,g+_),this.addSymbol(b,n[c++],i)}}else f.addSymbol(m,g+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(m,n[c++],i)}),f}},Ta=e=>e+"_max",dd=(e,t,n,i)=>{let o=e.map(f=>f.length).map((f,m)=>U(`input${m}`,t,f)),l=j.size(i),u=de("output",t,i.length),c=[...n.symbolToInfo.keys()].filter(f=>!n.rhs.symbolToIndices.has(f)),h=f=>{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((W,te)=>{if(I.inputIndices.includes(te)){let fe=W.symbolToIndices.get(B);if(fe===void 0)throw new Error("Invalid symbol error");fe.forEach(be=>{m.push(`${o[te].indicesSet(`input${te}Indices`,be,u.indicesGet("outputIndices",q))}`)})}})}else n.lhs.forEach((q,W)=>{if(I.inputIndices.includes(W)){let te=q.symbolToIndices.get(B);if(te===void 0)throw new Error("Invalid symbol error");te.forEach(fe=>{b.push(`${o[W].indicesSet(`input${W}Indices`,fe,`${B}`)}`)}),k.push(`prod *= ${o[W].getByIndices(`input${W}Indices`)};`)}}),x.push(`for(var ${B}: u32 = 0; ${B} < uniforms.${Ta(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`
|
|
1341
|
+
${f.registerUniforms(c.map(I=>({name:`${Ta(I)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,u)}
|
|
1342
|
+
|
|
1343
|
+
${f.mainStart()}
|
|
1344
|
+
${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1345
|
+
var outputIndices = ${u.offsetToIndices("global_idx")};
|
|
1346
|
+
${o.map((I,B)=>`var input${B}Indices: ${o[B].type.indices};`).join(`
|
|
1347
|
+
`)}
|
|
1348
|
+
${O.join(`
|
|
1349
|
+
`)};
|
|
1350
|
+
${u.setByOffset("global_idx","sum")};
|
|
1351
|
+
}`};return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let f=c.filter(g=>n.symbolToInfo.has(g)).map(g=>({type:12,data:n.symbolToInfo.get(g)?.dimValue||0}));f.push({type:12,data:l});let m=e.map((g,w)=>[...L(g)]).reduce((g,w)=>g.concat(w),f);return m.push(...L(i)),{outputs:[{dims:i,dataType:t}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:m}},getShaderSource:h}},cd=(e,t)=>{let n=new ud(e.inputs,t.equation),i=n.outputDims,o=e.inputs.map((l,u)=>l.dims);e.compute(dd(o,e.inputs[0].dataType,n,i))},hd=e=>{let t=e.equation.replace(/\s+/g,"");return E({equation:t})}}),pd,Ea,fd,md,gd,zm=S(()=>{Ie(),ke(),we(),pd=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=n.length<t.length?0:n.length-t.length,o=t.length<n.length?0:t.length-n.length;for(;i<n.length&&o<t.length;++i,++o)if(n[i]!==t[o]&&n[i]!==1&&t[o]!==1)throw new Error("Expand requires shape to be broadcastable to input")},Ea=(e,t)=>{let n=e.length-t.length,i=[];for(let o=0;o<n;++o)i.push(e[o]);for(let o=0;o<t.length;++o)i.push(t[o]===1?e[o+n]:t[o]);return i},fd=(e,t)=>e.length>t.length?Ea(e,t):Ea(t,e),md=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=fd(t,n),o=e[0].dataType,l=o===9||j.size(t)===1,u=o===9||t.length>0&&t[t.length-1]%4===0?4:1,c=l||i.length>0&&i[i.length-1]%4===0?4:1,h=Math.ceil(j.size(i)/c),f=g=>{let w=U("input",o,t.length,u),_=de("output",o,i.length,c),b;if(o===9){let x=(M,k,$="")=>`
|
|
1352
|
+
let outputIndices${k} = ${_.offsetToIndices(`outputOffset + ${k}u`)};
|
|
1353
|
+
let offset${k} = ${w.broadcastedIndicesToOffset(`outputIndices${k}`,_)};
|
|
1354
|
+
let index${k} = offset${k} / 4u;
|
|
1355
|
+
let component${k} = offset${k} % 4u;
|
|
1356
|
+
${M}[${k}] = ${$}(${w.getByOffset(`index${k}`)}[component${k}]);
|
|
1357
|
+
`;b=`
|
|
1358
|
+
let outputOffset = global_idx * ${c};
|
|
1359
|
+
var data = vec4<u32>(0);
|
|
1360
|
+
${x("data",0,"u32")}
|
|
1361
|
+
${x("data",1,"u32")}
|
|
1362
|
+
${x("data",2,"u32")}
|
|
1363
|
+
${x("data",3,"u32")}
|
|
1364
|
+
${_.setByOffset("global_idx","data")}
|
|
1365
|
+
}`}else b=`
|
|
1366
|
+
let outputIndices = ${_.offsetToIndices(`global_idx * ${c}`)};
|
|
1367
|
+
let inputOffset = ${w.broadcastedIndicesToOffset("outputIndices",_)};
|
|
1368
|
+
let data = ${_.type.value}(${w.getByOffset(`inputOffset / ${u}`)});
|
|
1369
|
+
${_.setByOffset("global_idx","data")}
|
|
1370
|
+
}`;return`
|
|
1371
|
+
${g.registerUniform("vec_size","u32").declareVariables(w,_)}
|
|
1372
|
+
${g.mainStart()}
|
|
1373
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
1374
|
+
${b}`},m=[{type:12,data:h},...L(t,i)];return{name:"Expand",shaderCache:{hint:`${i.length};${u}${c}`,inputDependencies:["rank"]},getShaderSource:f,getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:m})}},gd=e=>{pd(e.inputs),e.compute(md(e.inputs),{inputs:[0]})}}),yd,wd,Lm=S(()=>{Ie(),ke(),we(),aa(),yd=e=>{let t=e[0].dataType,n=j.size(e[0].dims),i=j.size(e[1].dims),o=i%4===0,l=u=>{let c=U("x",t,[1],4),h=U("bias",t,[1],4),f=de("y",t,[1],4),m=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],g=_=>`
|
|
1375
|
+
let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size;
|
|
1376
|
+
let bias${_} = ${h.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,w=o?`
|
|
1377
|
+
let bias = ${h.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${g(0)}${g(1)}${g(2)}${g(3)}
|
|
1378
|
+
let bias = ${c.type.value}(bias0, bias1, bias2, bias3);`;return`${u.registerUniforms(m).declareVariables(c,h,f)}
|
|
1379
|
+
|
|
1380
|
+
${na(N(t))}
|
|
1381
|
+
|
|
1382
|
+
${u.mainStart(D)}
|
|
1383
|
+
${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}
|
|
1384
|
+
|
|
1385
|
+
let x = ${c.getByOffset("global_idx")};
|
|
1386
|
+
${w}
|
|
1387
|
+
let x_in = x + bias;
|
|
1388
|
+
${f.setByOffset("global_idx",ia("x_in"))}
|
|
1389
|
+
}`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:l,getRunData:u=>({outputs:[{dims:u[0].dims,dataType:u[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:i}],dispatchGroup:{x:Math.ceil(n/D/4)}})}},wd=e=>{e.inputs.length<2||j.size(e.inputs[1].dims)===0?Jl(e):e.compute(yd(e.inputs))}}),vd,_d,bd,Sd,Bm=S(()=>{Ie(),ke(),A(),we(),vd=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},_d=(e,t)=>{let n=e[0].dims,i=e[1].dims,o=n.length,l=j.normalizeAxis(t.axis,o),u=n.slice(0);u.splice(l,1,...i);let c=n[l],h=e[0].dataType===9?4:1,f=Math.ceil(j.size(u)/h),m=[{type:12,data:f},{type:6,data:c},{type:12,data:l},...L(e[0].dims,e[1].dims,u)],g=w=>{let _=U("data",e[0].dataType,e[0].dims.length,h),b=U("inputIndices",e[1].dataType,e[1].dims.length),x=de("output",e[0].dataType,u.length,h),M=$=>{let O=i.length,I=`var indicesIndices${$} = ${b.type.indices}(0);`;for(let B=0;B<O;B++)I+=`${O>1?`indicesIndices${$}[${B}]`:`indicesIndices${$}`} = ${u.length>1?`outputIndices${$}[uniforms.axis + ${B}]`:`outputIndices${$}`};`;I+=`
|
|
1390
|
+
var idx${$} = ${b.getByIndices(`indicesIndices${$}`)};
|
|
1391
|
+
if (idx${$} < 0) {
|
|
1392
|
+
idx${$} = idx${$} + uniforms.axisDimLimit;
|
|
1393
|
+
}
|
|
1394
|
+
var dataIndices${$} : ${_.type.indices};
|
|
1395
|
+
`;for(let B=0,q=0;B<o;B++)B===l?(I+=`${o>1?`dataIndices${$}[${B}]`:`dataIndices${$}`} = u32(idx${$});`,q+=O):(I+=`${o>1?`dataIndices${$}[${B}]`:`dataIndices${$}`} = ${u.length>1?`outputIndices${$}[${q}]`:`outputIndices${$}`};`,q++);return I},k;if(e[0].dataType===9){let $=(O,I,B="")=>`
|
|
1396
|
+
let outputIndices${I} = ${x.offsetToIndices(`outputOffset + ${I}u`)};
|
|
1397
|
+
${M(I)};
|
|
1398
|
+
let offset${I} = ${_.indicesToOffset(`dataIndices${I}`)};
|
|
1399
|
+
let index${I} = offset${I} / 4u;
|
|
1400
|
+
let component${I} = offset${I} % 4u;
|
|
1401
|
+
${O}[${I}] = ${B}(${_.getByOffset(`index${I}`)}[component${I}]);
|
|
1402
|
+
`;k=`
|
|
1403
|
+
let outputOffset = global_idx * ${h};
|
|
1404
|
+
var value = vec4<u32>(0);
|
|
1405
|
+
${$("value",0,"u32")}
|
|
1406
|
+
${$("value",1,"u32")}
|
|
1407
|
+
${$("value",2,"u32")}
|
|
1408
|
+
${$("value",3,"u32")}
|
|
1409
|
+
${x.setByOffset("global_idx","value")}
|
|
1410
|
+
`}else k=`
|
|
1411
|
+
let outputIndices = ${x.offsetToIndices("global_idx")};
|
|
1412
|
+
${M("")};
|
|
1413
|
+
let value = ${_.getByIndices("dataIndices")};
|
|
1414
|
+
${x.setByOffset("global_idx","value")};
|
|
1415
|
+
`;return`
|
|
1416
|
+
${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,b,x)}
|
|
1417
|
+
${w.mainStart()}
|
|
1418
|
+
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1419
|
+
${k}
|
|
1420
|
+
}`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:m}),getShaderSource:g}},bd=e=>E({axis:e.axis}),Sd=(e,t)=>{let n=e.inputs;vd(n),e.compute(_d(e.inputs,t))}}),Td,Ed,$d,Nm=S(()=>{Ie(),ke(),we(),Td=(e,t,n,i,o,l,u,c,h)=>{let f=[{type:12,data:l},{type:12,data:i},{type:12,data:o},{type:12,data:n},{type:12,data:u},{type:12,data:c},{type:12,data:h}],m=[l];f.push(...L(t.dims,m));let g=w=>{let _=U("indices_data",t.dataType,t.dims.length),b=de("input_slice_offsets_data",12,1,1),x=[_,b],M=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:n.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return`
|
|
1421
|
+
${w.registerUniforms(M).declareVariables(...x)}
|
|
1422
|
+
${w.mainStart()}
|
|
1423
|
+
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1424
|
+
let batch_idx = global_idx / uniforms.num_slices_per_batch;
|
|
1425
|
+
let base_offset = batch_idx * uniforms.input_batch_stride;
|
|
1426
|
+
|
|
1427
|
+
let slice_indices_base_offset = global_idx * uniforms.num_slice_dims;
|
|
1428
|
+
var relative_slice_offset = 0;
|
|
1429
|
+
for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) {
|
|
1430
|
+
var index = i32(indices_data[dim_idx + slice_indices_base_offset].x);
|
|
1431
|
+
let input_dim_idx = uniforms.batch_dims + dim_idx;
|
|
1432
|
+
if (index < 0) {
|
|
1433
|
+
${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"}
|
|
1434
|
+
}
|
|
1435
|
+
${n.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"}
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset);
|
|
1439
|
+
}`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${n.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:m,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:f}),getShaderSource:g},{inputs:[t],outputs:[-1]})[0]},Ed=(e,t)=>{let n=e.inputs,i=n[0].dims,o=n[0].dataType,l=n[1].dims,u=l[l.length-1],c=j.sizeToDimension(l,l.length-1),h=j.sizeFromDimension(i,t.batchDims+u),f=j.sizeToDimension(i,t.batchDims),m=j.sizeFromDimension(i,t.batchDims),g=c/f,w=new Array(u),_=h;for(let I=0;I<u;++I)w[u-1-I]=_,_*=i[t.batchDims+u-1-I];let b=Td(e,n[1],w,t.batchDims,i,c,g,m,u),x=t.batchDims+u;if(x>i.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let M=l.slice(0,-1).concat(i.slice(x)),k=j.size(M),$=[{type:12,data:k},{type:12,data:h},...L(n[0].dims,b.dims,M)],O=I=>{let B=U("data",n[0].dataType,n[0].dims.length),q=U("slice_offsets",12,b.dims.length),W=de("output",n[0].dataType,M.length);return`
|
|
1440
|
+
${I.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(B,q,W)}
|
|
1441
|
+
${I.mainStart()}
|
|
1442
|
+
${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1443
|
+
let slice_offset = slice_offsets[global_idx / uniforms.slice_size];
|
|
1444
|
+
output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size];
|
|
1445
|
+
}`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:M,dataType:o}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:$}),getShaderSource:O},{inputs:[n[0],b]})},$d=e=>({batchDims:e.batch_dims,cacheKey:""})}),xd,Cd,kd,Rd,Um=S(()=>{Ie(),ke(),A(),we(),xd=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let n=j.normalizeAxis(t.quantizeAxis,e[0].dims.length),i=t.blockSize,o=e[0],l=e[2],u=e.length===4?e[3]:void 0;if(l.dims.length!==o.dims.length||!o.dims.map((c,h)=>h===n?Math.ceil(c/i)===l.dims[h]:c===l.dims[h]).reduce((c,h)=>c&&h,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(u){if(u.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(u.dims.length!==l.dims.length||!u.dims.map((c,h)=>c===l.dims[h]).reduce((c,h)=>c&&h,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Cd=(e,t)=>{let n=e[0].dims,i=e[1].dims,o=n.length,l=j.normalizeAxis(t.gatherAxis,o),u=j.normalizeAxis(t.quantizeAxis,o),c=n.slice(0);c.splice(l,1,...i);let h=j.size(c),f=e[2].dataType,m=e[0].dataType===22,g=[{type:12,data:h},{type:12,data:u},{type:12,data:l},{type:12,data:t.blockSize},...L(...e.map((_,b)=>_.dims),c)],w=_=>{let b=U("data",e[0].dataType,e[0].dims.length),x=U("inputIndices",e[1].dataType,e[1].dims.length),M=U("scales",e[2].dataType,e[2].dims.length),k=e.length>3?U("zeroPoint",e[3].dataType,e[3].dims.length):void 0,$=de("output",f,c.length),O=[b,x,M];k&&O.push(k);let I=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
1446
|
+
${_.registerUniforms(I).declareVariables(...O,$)}
|
|
1447
|
+
${_.mainStart()}
|
|
1448
|
+
let output_indices = ${$.offsetToIndices("global_idx")};
|
|
1449
|
+
var indices_indices = ${x.type.indices}(0);
|
|
1450
|
+
${i.length>1?`
|
|
1451
|
+
for (var i: u32 = 0; i < ${i.length}; i++) {
|
|
1452
|
+
let index = ${$.indicesGet("output_indices","uniforms.gather_axis + i")};
|
|
1453
|
+
${x.indicesSet("indices_indices","i","index")};
|
|
1454
|
+
}`:`indices_indices = ${$.indicesGet("output_indices","uniforms.gather_axis")};`};
|
|
1455
|
+
var data_indices = ${b.type.indices}(0);
|
|
1456
|
+
for (var i: u32 = 0; i < uniforms.gather_axis; i++) {
|
|
1457
|
+
let index = ${$.indicesGet("output_indices","i")};
|
|
1458
|
+
${b.indicesSet("data_indices","i","index")};
|
|
1459
|
+
}
|
|
1460
|
+
var index_from_indices = ${x.getByIndices("indices_indices")};
|
|
1461
|
+
if (index_from_indices < 0) {
|
|
1462
|
+
index_from_indices += ${n[l]};
|
|
1463
|
+
}
|
|
1464
|
+
${b.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")};
|
|
1465
|
+
for (var i = uniforms.gather_axis + 1; i < ${c.length}; i++) {
|
|
1466
|
+
let index = ${$.indicesGet("output_indices",`i + ${i.length} - 1`)};
|
|
1467
|
+
${b.indicesSet("data_indices","i","index")};
|
|
1468
|
+
}
|
|
1469
|
+
let data_offset = ${b.indicesToOffset("data_indices")};
|
|
1470
|
+
let data_index = data_offset % 8;
|
|
1471
|
+
// Convert 4-bit packed data to 8-bit packed data.
|
|
1472
|
+
let packed_4bit_quantized_data = ${b.getByOffset("data_offset / 8")};
|
|
1473
|
+
let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;
|
|
1474
|
+
let quantized_data_vec = ${m?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data));
|
|
1475
|
+
let quantized_data = quantized_data_vec[data_index / 2];
|
|
1476
|
+
var scale_indices = data_indices;
|
|
1477
|
+
let quantize_axis_index = ${M.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size;
|
|
1478
|
+
${M.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")};
|
|
1479
|
+
var scale = ${M.getByIndices("scale_indices")};
|
|
1480
|
+
${k?`
|
|
1481
|
+
let zero_point_indices = scale_indices;
|
|
1482
|
+
let zero_point_offset = ${k.indicesToOffset("zero_point_indices")};
|
|
1483
|
+
let zero_point_index = zero_point_offset % 8;
|
|
1484
|
+
let packed_4bit_zero_points = ${k.getByOffset("zero_point_offset / 8")};
|
|
1485
|
+
let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;
|
|
1486
|
+
let zero_point_vec = ${m?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points));
|
|
1487
|
+
let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};
|
|
1488
|
+
let dequantized_data = ${N(f)}(quantized_data - zero_point) * scale;
|
|
1489
|
+
${$.setByOffset("global_idx","dequantized_data")};
|
|
1490
|
+
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((_,b)=>b!==1).map(_=>_.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(_,b)=>"rank")},getRunData:()=>({outputs:[{dims:c,dataType:f}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:g}),getShaderSource:w}},kd=(e,t)=>{let n=e.inputs;xd(n,t),e.compute(Cd(e.inputs,t))},Rd=e=>E({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Ad,Id,Md,Od,Fm=S(()=>{Ie(),ke(),A(),we(),Ad=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and
|
|
1491
|
+
indices input tensors be of same rank.`)},Id=(e,t)=>{let n=e[0].dims,i=e[0].dataType,o=n.length,l=e[1].dims,u=e[1].dataType,c=j.normalizeAxis(t.axis,o),h=n[c],f=l.slice(0),m=j.size(f),g=U("input",i,o),w=U("indicesInput",u,l.length),_=de("output",i,f.length),b=[{type:12,data:m},{type:6,data:h},{type:12,data:c}];return b.push(...L(n,l,f)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:f,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:b}),getShaderSource:x=>`
|
|
1492
|
+
${x.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(g,w,_)}
|
|
1493
|
+
${x.mainStart()}
|
|
1494
|
+
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1495
|
+
|
|
1496
|
+
let outputIndices = ${_.offsetToIndices("global_idx")};
|
|
1497
|
+
|
|
1498
|
+
var idx = ${w.getByOffset("global_idx")};
|
|
1499
|
+
if (idx < 0) {
|
|
1500
|
+
idx = idx + uniforms.axisDimLimit;
|
|
1501
|
+
}
|
|
1502
|
+
var inputIndices = ${g.type.indices}(outputIndices);
|
|
1503
|
+
${g.indicesSet("inputIndices","uniforms.axis","u32(idx)")};
|
|
1504
|
+
let value = ${g.getByIndices("inputIndices")};
|
|
1505
|
+
|
|
1506
|
+
${_.setByOffset("global_idx","value")};
|
|
1507
|
+
}`}},Md=e=>E({axis:e.axis}),Od=(e,t)=>{let n=e.inputs;Ad(n),e.compute(Id(e.inputs,t))}}),Pd,Dd,zd,Ld,Vm=S(()=>{Ie(),ke(),we(),Pd=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Dd=(e,t)=>{let n=e[0].dims.slice(),i=e[1].dims.slice(),[o,l,u]=Ks.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,f=Math.ceil(l/h),m=Math.ceil(o/h);j.size(c);let g=[{type:12,data:f},{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=U("a",e[0].dataType,e[0].dims),M=U("b",e[1].dataType,e[1].dims),k=null,$=[x,M];e.length===3&&(k=U("c",e[2].dataType,e[2].dims.length),$.push(k));let O=de("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=`
|
|
1508
|
+
var col = tile_row_start + local_id.x;
|
|
1509
|
+
var row = k_start + local_id.y;
|
|
1510
|
+
if (col < uniforms.M && row < uniforms.K) {
|
|
1511
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
|
|
1512
|
+
} else {
|
|
1513
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
col = k_start + local_id.x;
|
|
1517
|
+
row = tile_col_start + local_id.y;
|
|
1518
|
+
if (col < uniforms.K && row < uniforms.N) {
|
|
1519
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
|
|
1520
|
+
} else {
|
|
1521
|
+
tile_b[local_id.y][local_id.x] = ${M.type.value}(0);
|
|
1522
|
+
}
|
|
1523
|
+
`,B="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(q=`
|
|
1524
|
+
var col = tile_row_start + local_id.x;
|
|
1525
|
+
var row = k_start + local_id.y;
|
|
1526
|
+
if (col < uniforms.M && row < uniforms.K) {
|
|
1527
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
|
|
1528
|
+
} else {
|
|
1529
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
col = tile_col_start + local_id.x;
|
|
1533
|
+
row = k_start + local_id.y;
|
|
1534
|
+
if (col < uniforms.N && row < uniforms.K) {
|
|
1535
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
|
|
1536
|
+
} else {
|
|
1537
|
+
tile_b[local_id.y][local_id.x] = ${M.type.value}(0);
|
|
1538
|
+
}
|
|
1539
|
+
`,B="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(q=`
|
|
1540
|
+
var col = k_start + local_id.x;
|
|
1541
|
+
var row = tile_row_start + local_id.y;
|
|
1542
|
+
if (col < uniforms.K && row < uniforms.M) {
|
|
1543
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
|
|
1544
|
+
} else {
|
|
1545
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
col = k_start + local_id.x;
|
|
1549
|
+
row = tile_col_start + local_id.y;
|
|
1550
|
+
if (col < uniforms.K && row < uniforms.N) {
|
|
1551
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
|
|
1552
|
+
} else {
|
|
1553
|
+
tile_b[local_id.y][local_id.x] = ${M.type.value}(0);
|
|
1554
|
+
}
|
|
1555
|
+
`,B="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(q=`
|
|
1556
|
+
var col = k_start + local_id.x;
|
|
1557
|
+
var row = tile_row_start + local_id.y;
|
|
1558
|
+
if (col < uniforms.K && row < uniforms.M) {
|
|
1559
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
|
|
1560
|
+
} else {
|
|
1561
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
col = tile_col_start + local_id.x;
|
|
1565
|
+
row = k_start + local_id.y;
|
|
1566
|
+
if (col < uniforms.N && row < uniforms.K) {
|
|
1567
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
|
|
1568
|
+
} else {
|
|
1569
|
+
tile_b[local_id.y][local_id.x] = ${M.type.value}(0);
|
|
1570
|
+
}
|
|
1571
|
+
`,B="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let W=t.alpha===1?"":"value *= uniforms.alpha;";return`
|
|
1572
|
+
${b.registerUniforms(I).declareVariables(...$)}
|
|
1573
|
+
var<workgroup> tile_a: array<array<${x.type.storage}, ${h}>, ${h}>;
|
|
1574
|
+
var<workgroup> tile_b: array<array<${M.type.storage}, ${h}>, ${h}>;
|
|
1575
|
+
${b.mainStart([h,h,1])}
|
|
1576
|
+
let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${h};
|
|
1577
|
+
let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${h};
|
|
1578
|
+
let num_tiles = (uniforms.K - 1) / ${h} + 1;
|
|
1579
|
+
var k_start = 0u;
|
|
1580
|
+
var value = ${O.type.value}(0);
|
|
1581
|
+
for (var t: u32 = 0u; t < num_tiles; t++) {
|
|
1582
|
+
${q}
|
|
1583
|
+
k_start = k_start + ${h};
|
|
1584
|
+
workgroupBarrier();
|
|
1585
|
+
|
|
1586
|
+
for (var k: u32 = 0u; k < ${h}; k++) {
|
|
1587
|
+
${B}
|
|
1588
|
+
}
|
|
1589
|
+
workgroupBarrier();
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
${W}
|
|
1593
|
+
let m = tile_row_start + local_id.y;
|
|
1594
|
+
let n = tile_col_start + local_id.x;
|
|
1595
|
+
${k!=null?`let cOffset = ${k.broadcastedIndicesToOffset("vec2(m, n)",O)}; value += ${O.type.value}(uniforms.beta) * ${k.getByOffset("cOffset")};`:""}
|
|
1596
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
1597
|
+
output[m * uniforms.N + n] = value;
|
|
1598
|
+
}
|
|
1599
|
+
}`};return{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:f*m},programUniforms:g}),getShaderSource:_}},zd=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}`}},Ld=(e,t)=>{Pd(e.inputs),e.compute(Dd(e.inputs,t))}}),Br,Hr,Ds,zs,Bd,Nd,Ud,Fd,Vd,Gd,qd,Wd,Hd,jd,Gm=S(()=>{Ie(),ke(),A(),we(),[Br,Hr,Ds,zs]=[0,1,2,3],Bd=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")},Nd=`
|
|
1600
|
+
fn gs_get_cubic_coeffs(x: f32) -> vec4<f32> {
|
|
1601
|
+
let cubic_alpha = -0.75f;
|
|
1602
|
+
let x_abs = abs(x);
|
|
1603
|
+
var coeffs: vec4<f32>;
|
|
1604
|
+
coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);
|
|
1605
|
+
coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);
|
|
1606
|
+
coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);
|
|
1607
|
+
coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);
|
|
1608
|
+
return coeffs;
|
|
1609
|
+
}
|
|
1610
|
+
`,Ud=e=>`
|
|
1611
|
+
fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {
|
|
1612
|
+
var v: vec4<f32>;
|
|
1613
|
+
var coeffs = gs_get_cubic_coeffs(x);
|
|
1614
|
+
for (var i = 0; i < 4; i++) {
|
|
1615
|
+
v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];
|
|
1616
|
+
}
|
|
1617
|
+
coeffs = gs_get_cubic_coeffs(y);
|
|
1618
|
+
let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);
|
|
1619
|
+
return pixel;
|
|
1620
|
+
}
|
|
1621
|
+
`,Fd=e=>`
|
|
1622
|
+
fn gs_denormalize(n: f32, length: i32) -> f32 {
|
|
1623
|
+
${e.alignCorners===0?`
|
|
1624
|
+
// alignCorners: false => [-1, 1] to [-0.5, length - 0.5]
|
|
1625
|
+
return ((n + 1.0) * f32(length) - 1.0) / 2.0;
|
|
1626
|
+
`:`
|
|
1627
|
+
// alignCorners: true => [-1, 1] to [0, length - 1]
|
|
1628
|
+
return (n + 1.0) / 2.0 * (f32(length - 1));
|
|
1629
|
+
`}
|
|
1630
|
+
}
|
|
1631
|
+
`,Vd=e=>`
|
|
1632
|
+
${e.paddingMode==="reflection"?`
|
|
1633
|
+
fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {
|
|
1634
|
+
var dx = 0.0;
|
|
1635
|
+
var fx = f32(x);
|
|
1636
|
+
let range = x_max - x_min;
|
|
1637
|
+
if (fx < x_min) {
|
|
1638
|
+
dx = x_min - fx;
|
|
1639
|
+
let n = u32(dx / range);
|
|
1640
|
+
let r = dx - f32(n) * range;
|
|
1641
|
+
if (n % 2 == 0) {
|
|
1642
|
+
fx = x_min + r;
|
|
1643
|
+
} else {
|
|
1644
|
+
fx = x_max - r;
|
|
1645
|
+
}
|
|
1646
|
+
} else if (fx > x_max) {
|
|
1647
|
+
dx = fx - x_max;
|
|
1648
|
+
let n = u32(dx / range);
|
|
1649
|
+
let r = dx - f32(n) * range;
|
|
1650
|
+
if (n % 2 == 0) {
|
|
1651
|
+
fx = x_max - r;
|
|
1652
|
+
} else {
|
|
1653
|
+
fx = x_min + r;
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
return u32(fx);
|
|
1657
|
+
}`:""}
|
|
1658
|
+
`,Gd=(e,t,n)=>`
|
|
1659
|
+
fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4<f32>) -> ${t} {
|
|
1660
|
+
var pixel = ${t}(0);
|
|
1661
|
+
var indices = vec4<u32>(0);
|
|
1662
|
+
indices[${Br}] = batch;
|
|
1663
|
+
indices[${Hr}] = channel;`+(()=>{switch(n.paddingMode){case"zeros":return`
|
|
1664
|
+
if (r >= 0 && r < H && c >=0 && c < W) {
|
|
1665
|
+
indices[${Ds}] = u32(r);
|
|
1666
|
+
indices[${zs}] = u32(c);
|
|
1667
|
+
} else {
|
|
1668
|
+
return ${t}(0);
|
|
1669
|
+
}
|
|
1670
|
+
`;case"border":return`
|
|
1671
|
+
indices[${Ds}] = u32(clamp(r, 0, H - 1));
|
|
1672
|
+
indices[${zs}] = u32(clamp(c, 0, W - 1));
|
|
1673
|
+
`;case"reflection":return`
|
|
1674
|
+
indices[${Ds}] = gs_reflect(r, border[1], border[3]);
|
|
1675
|
+
indices[${zs}] = gs_reflect(c, border[0], border[2]);
|
|
1676
|
+
`;default:throw new Error(`padding mode ${n.paddingMode} is not supported`)}})()+`
|
|
1677
|
+
return ${e.getByIndices("indices")};
|
|
1678
|
+
}
|
|
1679
|
+
`,qd=(e,t,n)=>(()=>{switch(n.mode){case"nearest":return`
|
|
1680
|
+
let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Br}], indices[${Hr}], border);
|
|
1681
|
+
`;case"bilinear":return`
|
|
1682
|
+
let x1 = i32(floor(x));
|
|
1683
|
+
let y1 = i32(floor(y));
|
|
1684
|
+
let x2 = x1 + 1;
|
|
1685
|
+
let y2 = y1 + 1;
|
|
1686
|
+
|
|
1687
|
+
let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Br}], indices[${Hr}], border);
|
|
1688
|
+
let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Br}], indices[${Hr}], border);
|
|
1689
|
+
let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Br}], indices[${Hr}], border);
|
|
1690
|
+
let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Br}], indices[${Hr}], border);
|
|
1691
|
+
|
|
1692
|
+
let dx2 = ${t}(f32(x2) - x);
|
|
1693
|
+
let dx1 = ${t}(x - f32(x1));
|
|
1694
|
+
let dy2 = ${t}(f32(y2) - y);
|
|
1695
|
+
let dy1 = ${t}(y - f32(y1));
|
|
1696
|
+
let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);
|
|
1697
|
+
`;case"bicubic":return`
|
|
1698
|
+
let x0 = i32(floor(x)) - 1;
|
|
1699
|
+
let y0 = i32(floor(y)) - 1;
|
|
1700
|
+
var p: mat4x4<${t}>;
|
|
1701
|
+
for (var h = 0; h < 4; h++) {
|
|
1702
|
+
for (var w = 0; w < 4; w++) {
|
|
1703
|
+
p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Br}], indices[${Hr}], border);
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
let dx = x - f32(x0 + 1);
|
|
1708
|
+
let dy = y - f32(y0 + 1);
|
|
1709
|
+
let result = gs_bicubic_interpolate(p, dx, dy);
|
|
1710
|
+
`;default:throw new Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Wd=(e,t)=>{let n=U("x",e[0].dataType,e[0].dims.length),i=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=U("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]],[Br,Hr,Ds,zs]=[0,3,1,2]);let u=de("output",e[0].dataType,l.length),c=n.type.value,h=j.size(l),f=[{type:12,data:h},...L(e[0].dims,i,l)],m=g=>`
|
|
1711
|
+
${g.registerUniform("output_size","u32").declareVariables(n,o,u)}
|
|
1712
|
+
${Nd}
|
|
1713
|
+
${Ud(c)}
|
|
1714
|
+
${Fd(t)}
|
|
1715
|
+
${Vd(t)}
|
|
1716
|
+
${Gd(n,c,t)}
|
|
1717
|
+
|
|
1718
|
+
${g.mainStart()}
|
|
1719
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1720
|
+
let H_in = i32(uniforms.x_shape[${Ds}]);
|
|
1721
|
+
let W_in = i32(uniforms.x_shape[${zs}]);
|
|
1722
|
+
|
|
1723
|
+
${t.alignCorners===0?`
|
|
1724
|
+
let x_min = -0.5;
|
|
1725
|
+
let x_max = f32(W_in) - 0.5;
|
|
1726
|
+
let y_min = -0.5;
|
|
1727
|
+
let y_max = f32(H_in) - 0.5;
|
|
1728
|
+
`:`
|
|
1729
|
+
let x_min = 0.0;
|
|
1730
|
+
let x_max = f32(W_in) - 1.0;
|
|
1731
|
+
let y_min = 0.0;
|
|
1732
|
+
let y_max = f32(H_in) - 1.0;
|
|
1733
|
+
`};
|
|
1734
|
+
let border = vec4<f32>(x_min, y_min, x_max, y_max);
|
|
1735
|
+
|
|
1736
|
+
let indices = ${u.offsetToIndices("global_idx")};
|
|
1737
|
+
var grid_indices = vec3<u32>(indices[${Br}], indices[${Ds}], indices[${zs}]);
|
|
1738
|
+
let nxy = ${o.getByIndices("grid_indices")};
|
|
1739
|
+
var x = gs_denormalize(f32(nxy[0]), W_in);
|
|
1740
|
+
var y = gs_denormalize(f32(nxy[1]), H_in);
|
|
1741
|
+
|
|
1742
|
+
${qd(u,c,t)}
|
|
1743
|
+
}`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:g=>{let w=j.size(l);return{outputs:[{dims:l,dataType:g[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:f}},getShaderSource:m}},Hd=(e,t)=>{Bd(e.inputs),e.compute(Wd(e.inputs,t))},jd=e=>E({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Zt,Kd,Qd,$a,Xd,Kn,Yd,Jd=S(()=>{Ie(),ke(),A(),Js(),ra(),we(),Ge(),Zt=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Kd=(e,t)=>{let n=e[0],i=Zt(e,1),o=Zt(e,2),l=Zt(e,3),u=Zt(e,4),c=Zt(e,5),h=Zt(e,6),f=Zt(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&&f&&j.size(h.dims)&&j.size(f.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(f.dims[0]!==m||f.dims[1]!==t.numHeads||f.dims[3]!==M)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[2]!==f.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(f.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&&j.size(h.dims)||f&&j.size(f.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let k;if(i&&j.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&&j.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&&j.size(u.dims)>0){O=8;let W=u.dims;throw W.length===1?W[0]===m?O=1:W[0]===3*m+2&&(O=3):W.length===2&&W[0]===m&&W[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&&j.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&&j.size(u.dims)>0)throw new Error("Key padding mask is not supported");if(c&&j.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}},Qd=e=>E({...e}),$a=E({perm:[0,2,1,3]}),Xd=(e,t,n,i,o,l,u)=>{let c=[i,o,l],h=j.size(c),f=[{type:12,data:h},{type:12,data:u},{type:12,data:l}],m=g=>{let w=de("qkv_with_bias",t.dataType,c),_=U("qkv",t.dataType,c),b=U("bias",n.dataType,c),x=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`
|
|
1744
|
+
${g.registerUniforms(x).declareVariables(_,b,w)}
|
|
1745
|
+
${g.mainStart()}
|
|
1746
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1747
|
+
let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
|
|
1748
|
+
|
|
1749
|
+
qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];
|
|
1750
|
+
}`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:c,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:f}),getShaderSource:m},{inputs:[t,n],outputs:[-1]})[0]},Kn=(e,t,n,i,o,l,u,c)=>{let h=l;if(u&&j.size(u.dims)>0){if(i===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return h=Xd(e,l,u,t,i,n*o,c),h=h.reshape([t,i,n,o]),n===1||i===1?h:e.compute(_t(h,$a.perm),{inputs:[h],outputs:[-1]})[0]}else return l.dims.length===3&&(h=l.reshape([t,i,n,o])),n===1||i===1?h:e.compute(_t(h,$a.perm),{inputs:[h],outputs:[-1]})[0]},Yd=(e,t)=>{let n=Kd(e.inputs,t),i=e.inputs[0],o=Zt(e.inputs,1),l=Zt(e.inputs,2),u=Zt(e.inputs,3),c=Zt(e.inputs,4),h=Zt(e.inputs,5),f=Zt(e.inputs,6),m=Zt(e.inputs,7);if(i.dims.length===5)throw new Error("Packed QKV is not implemented");if(o?.dims.length===5)throw new Error("Packed KV is not implemented");let g=o&&l&&o.dims.length===4&&l.dims.length===4,w=Kn(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,i,u,0);if(g)return Gn(e,w,o,l,c,void 0,f,m,h,n);if(!o||!l)throw new Error("key and value must be provided");let _=Kn(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,o,u,n.hiddenSize),b=Kn(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,l,u,2*n.hiddenSize);Gn(e,w,_,b,c,void 0,f,m,h,n)}}),Zd,ec,tc,rc,xa,sc,nc,ic=S(()=>{Ie(),ke(),A(),we(),Zd=e=>{if(!e||e.length<1)throw new Error("too few inputs")},ec=(e,t)=>{let n=[],i=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>n.push(Number(o))),i=n.length),E({numOutputs:i,axis:t.axis,splitSizes:n})},tc=e=>`
|
|
1751
|
+
fn calculateOutputIndex(index: u32) -> u32 {
|
|
1752
|
+
for (var i: u32 = 0u; i < ${e}u; i += 1u ) {
|
|
1753
|
+
if (index < ${K("uniforms.size_in_split_axis","i",e)}) {
|
|
1754
|
+
return i;
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
return ${e}u;
|
|
1758
|
+
}`,rc=e=>{let t=e.length,n=[];for(let i=0;i<t;++i){let o=e[i].setByIndices("indices","input[global_idx]");t===1?n.push(o):i===0?n.push(`if (output_number == ${i}u) { ${o} }`):i===t-1?n.push(`else { ${o} }`):n.push(`else if (output_number == ${i}) { ${o} }`)}return`
|
|
1759
|
+
fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) {
|
|
1760
|
+
${n.join(`
|
|
1761
|
+
`)}
|
|
1762
|
+
}`},xa=(e,t)=>{let n=e[0].dims,i=j.size(n),o=e[0].dataType,l=j.normalizeAxis(t.axis,n.length),u=new Array(t.numOutputs),c=U("input",o,n.length),h=new Array(t.numOutputs),f=[],m=[],g=0,w=[{type:12,data:i}];for(let b=0;b<t.numOutputs;b++){g+=t.splitSizes[b],h[b]=g;let x=n.slice();x[l]=t.splitSizes[b],m.push(x),u[b]=de(`output${b}`,o,x.length),f.push({dims:m[b],dataType:e[0].dataType})}w.push({type:12,data:h},...L(n,...m));let _=b=>`
|
|
1763
|
+
${b.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",h.length).declareVariables(c,...u)}
|
|
1764
|
+
${tc(h.length)}
|
|
1765
|
+
${rc(u)}
|
|
1766
|
+
|
|
1767
|
+
${b.mainStart()}
|
|
1768
|
+
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}
|
|
1769
|
+
|
|
1770
|
+
var indices = ${c.offsetToIndices("global_idx")};
|
|
1771
|
+
var index = ${c.indicesGet("indices",l)};
|
|
1772
|
+
let output_number = calculateOutputIndex(index);
|
|
1773
|
+
if (output_number != 0) {
|
|
1774
|
+
index -= ${K("uniforms.size_in_split_axis","output_number - 1u",h.length)};
|
|
1775
|
+
${c.indicesSet("indices",l,"index")};
|
|
1776
|
+
}
|
|
1777
|
+
writeBufferData(output_number, indices, global_idx);
|
|
1778
|
+
}`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:f,dispatchGroup:{x:Math.ceil(i/64)},programUniforms:w})}},sc=(e,t)=>{Zd(e.inputs);let n=e.inputs.length===1?t:ec(e.inputs,t);e.compute(xa(e.inputs,n),{inputs:[0]})},nc=e=>{let t=e.axis,n=e.splitSizes,i=e.numOutputs<0?n.length:e.numOutputs;if(i!==n.length)throw new Error("numOutputs and splitSizes length must be equal");return E({axis:t,numOutputs:i,splitSizes:n})}}),ac,ki,oc,lc=S(()=>{Ie(),ke(),A(),we(),ac=(e,t)=>{let[n,i,o,l]=e,{numHeads:u,rotaryEmbeddingDim:c}=t;if(n.dims.length!==3&&n.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!j.areEqual(i.dims,[])&&!j.areEqual(i.dims,[1])&&i.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${i.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(l.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${l.dims.length}`);if(!j.areEqual(o.dims,l.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(c>0&&u===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let h=n.dims[0],f=n.dims[n.dims.length-2],m=o.dims[0],g=j.sizeFromDimension(n.dims,1)/f,w=c===0?o.dims[1]*2:g/u;if(c>w)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(i.dims.length===2){if(h!==i.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${i.dims[0]}`);if(f!==i.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${i.dims[1]}`)}if(f>m)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported");if(w/2!==o.dims[1]&&c/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`)},ki=(e,t)=>{let{interleaved:n,numHeads:i,rotaryEmbeddingDim:o,scale:l}=t,u=e[0].dims[0],c=j.sizeFromDimension(e[0].dims,1),h=e[0].dims[e[0].dims.length-2],f=c/h,m=e[2].dims[1],g=o===0?m*2:f/i,w=new Array(u,h,f/g,g-m),_=j.computeStrides(w),b=[{type:1,data:l},{type:12,data:w},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[c,f,g,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[c,g,h*g,1]}):[],...L(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],x=M=>{let k=U("input",e[0].dataType,e[0].dims.length),$=U("position_ids",e[1].dataType,e[1].dims.length),O=U("cos_cache",e[2].dataType,e[2].dims.length),I=U("sin_cache",e[3].dataType,e[3].dims.length),B=de("output",e[0].dataType,e[0].dims.length);return M.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:w.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),`
|
|
1779
|
+
${M.declareVariables(k,$,O,I,B)}
|
|
1780
|
+
|
|
1781
|
+
${M.mainStart(D)}
|
|
1782
|
+
let half_rotary_emb_dim = uniforms.${O.name}_shape[1];
|
|
1783
|
+
let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;
|
|
1784
|
+
let size = uniforms.global_shape[0] * uniforms.global_strides[0];
|
|
1785
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("size")}
|
|
1786
|
+
|
|
1787
|
+
if (bsnh[3] < half_rotary_emb_dim) {
|
|
1788
|
+
let position_ids_idx =
|
|
1789
|
+
${$.broadcastedIndicesToOffset("bsnh.xy",de("",$.type.tensor,2))};
|
|
1790
|
+
let position_id =
|
|
1791
|
+
u32(${$.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);
|
|
1792
|
+
let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${n});
|
|
1793
|
+
let j = i + select(half_rotary_emb_dim, 1, ${n});
|
|
1794
|
+
let re = ${k.getByOffset("i")} * ${O.get("position_id","bsnh[3]")} -
|
|
1795
|
+
${k.getByOffset("j")} * ${I.get("position_id","bsnh[3]")};
|
|
1796
|
+
${B.setByOffset("i","re")}
|
|
1797
|
+
let im = ${k.getByOffset("i")} * ${I.get("position_id","bsnh[3]")} +
|
|
1798
|
+
${k.getByOffset("j")} * ${O.get("position_id","bsnh[3]")};
|
|
1799
|
+
${B.setByOffset("j","im")}
|
|
1800
|
+
} else {
|
|
1801
|
+
let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
|
|
1802
|
+
${B.setByOffset("k",k.getByOffset("k"))}
|
|
1803
|
+
}
|
|
1804
|
+
}`};return{name:"RotaryEmbedding",shaderCache:{hint:E({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(j.size(w)/D)},programUniforms:b})}},oc=(e,t)=>{ac(e.inputs,t),e.compute(ki(e.inputs,t))}}),uc,dc,Ca,cc,hc,qm=S(()=>{A(),Ie(),ra(),Jd(),ic(),Ge(),lc(),we(),uc=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let n=e[0],i=e[1],o=e[2],l=e[3],u=e[4];if(t.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=n.dims[0],h=n.dims[1],f=n.dims.length===3?n.dims[2]:t.numHeads*n.dims[4],m=h,g=0,w=!i||i.dims.length===0,_=Math.floor(w?f/(t.numHeads+2*t.kvNumHeads):f/t.numHeads);w&&(f=_*t.numHeads);let b=l&&l.dims.length!==0,x=u&&u.dims.length!==0;if(b&&l.dims.length===4&&l.dims[0]===c&&l.dims[1]!==t.kvNumHeads&&l.dims[2]===t.kvNumHeads&&l.dims[3]===_)throw new Error("BSNH pastKey/pastValue is not supported");if(b&&x){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(u.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');g=l.dims[2]}else if(b||x)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let M=1;if(i&&i.dims.length>0){if(n.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(i.dims.length<3||i.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(i.dims.length===3){if(n.dims[2]%i.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');m=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');m=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');m=i.dims[2]}}else{if(n.dims.length!==3&&n.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(n.dims.length===5&&(n.dims[2]!==t.numHeads||n.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');M=3}let k=0,$=!1,O=t.kvNumHeads?_*t.kvNumHeads:f;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(m!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');O=o.dims[2]}else{if(m!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');O=o.dims[1]*o.dims[3],$=!0}}let I=e.length>4?e[5]:void 0;if(I){if(I.dims.length===0)throw new Error("seqlens_k must be at least 1D, got scalar.");let B=I.dims.reduce((q,W)=>q*W,1);if(B!==c)throw new Error(`seqlens_k must have batch_size (${c}) elements, got ${B}.`);for(let q=0;q<I.dims.length;q++)if(I.dims[q]!==1&&I.dims[q]!==c)throw new Error(`seqlens_k has unexpected shape. Each dimension must be 1 or batch_size (${c}), got dims[${q}] = ${I.dims[q]}.`)}return{batchSize:c,sequenceLength:h,pastSequenceLength:g,kvSequenceLength:m,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:f,vHiddenSize:O,headSize:_,vHeadSize:Math.floor(O/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:k,scale:t.scale,broadcastResPosBias:!1,passPastInKv:$,qkvFormat:M}},dc=E({perm:[0,2,1,3]}),Ca=(e,t,n)=>{let i=t,o=n.kvNumHeads;return t.dims.length===3&&n.kvSequenceLength!==0&&(i=t.reshape([n.batchSize,n.kvSequenceLength,o,n.headSize]),i=e.compute(_t(i,dc.perm),{inputs:[i],outputs:[-1]})[0]),i},cc=(e,t,n,i)=>{let o=7,l=["type","type"],u=[e*t],c=e*t,h=[{type:12,data:c},{type:12,data:t},{type:12,data:e}],f=m=>{let g=U("seq_lens",n.dataType,n.dims),w=U("total_seq_lens",i.dataType,i.dims),_=de("pos_ids",o,u),b=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return`
|
|
1805
|
+
${m.registerUniforms(b).declareVariables(g,w,_)}
|
|
1806
|
+
${m.mainStart()}
|
|
1807
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1808
|
+
let total_sequence_length = u32(${w.getByOffset("0")});
|
|
1809
|
+
let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length;
|
|
1810
|
+
let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length;
|
|
1811
|
+
let batch_idx = global_idx / uniforms.sequence_length;
|
|
1812
|
+
let sequence_idx = i32(global_idx % uniforms.sequence_length);
|
|
1813
|
+
var pos_id: i32 = 0;
|
|
1814
|
+
let seqlen = ${g.getByOffset("batch_idx")};
|
|
1815
|
+
let total_seqlen = seqlen + 1;
|
|
1816
|
+
if (is_first_prompt) {
|
|
1817
|
+
if (sequence_idx < total_seqlen) {
|
|
1818
|
+
pos_id = sequence_idx;
|
|
1819
|
+
} else {
|
|
1820
|
+
pos_id = 1;
|
|
1821
|
+
}
|
|
1822
|
+
${_.setByOffset("global_idx","pos_id")}
|
|
1823
|
+
} else if (is_subsequent_prompt) {
|
|
1824
|
+
let past_seqlen = total_seqlen - i32(uniforms.sequence_length);
|
|
1825
|
+
if (past_seqlen + sequence_idx < total_seqlen) {
|
|
1826
|
+
pos_id = past_seqlen + sequence_idx;
|
|
1827
|
+
} else {
|
|
1828
|
+
pos_id = 1;
|
|
1829
|
+
}
|
|
1830
|
+
${_.setByOffset("global_idx","pos_id")}
|
|
1831
|
+
} else if (global_idx < uniforms.batch_size) {
|
|
1832
|
+
${_.setByOffset("global_idx","seqlen")}
|
|
1833
|
+
};
|
|
1834
|
+
}
|
|
1835
|
+
`};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:h}),getShaderSource:f}},hc=(e,t)=>{let n=uc(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,f=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(xa([i],g),{inputs:[i],outputs:[-1,-1,-1]}):[i,o,l],x,M;if(t.doRotary){let I=e.compute(cc(n.batchSize,n.sequenceLength,h,f),{inputs:[h,f],outputs:[-1]})[0],B=e.inputs[7],q=e.inputs[8],W=E({interleaved:t.rotaryInterleaved!==0,numHeads:n.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),te=[w,I,B,q],fe=[-1];x=e.compute(ki(te,W),{inputs:te,outputs:fe})[0],te.splice(0,1,_);let be=E({interleaved:t.rotaryInterleaved!==0,numHeads:n.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});M=e.compute(ki(te,be),{inputs:te,outputs:fe})[0]}let k=Kn(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,t.doRotary?x:w,void 0,0),$=Ca(e,t.doRotary?M:_,n),O=Ca(e,b,n);Gn(e,k,$,O,void 0,void 0,u,c,void 0,n,h,f)}}),ka,pc,fc,mc,Wm=S(()=>{Ie(),ke(),Ge(),we(),ka=(e,t,n,i,o,l,u,c)=>{let h=V(l),f=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=U("x",t.dataType,3,h),I=U("scale",n.dataType,n.dims),B=U("bias",i.dataType,i.dims),q=de("output",1,3,2),W=[O,I,B,q];return`
|
|
1836
|
+
var<workgroup> workgroup_shared : array<${m}, ${w}>;
|
|
1837
|
+
const workgroup_size = ${w}u;
|
|
1838
|
+
${$.declareVariables(...W)}
|
|
1839
|
+
${$.mainStart(w)}
|
|
1840
|
+
let batch = workgroup_index / uniforms.x_shape[1];
|
|
1841
|
+
let channel = workgroup_index % uniforms.x_shape[1];
|
|
1842
|
+
let hight = uniforms.x_shape[2];
|
|
1843
|
+
// initialize workgroup memory
|
|
1844
|
+
var sum = ${f}(0);
|
|
1845
|
+
var squared_sum = ${f}(0);
|
|
1846
|
+
for (var h = local_idx; h < hight; h += workgroup_size) {
|
|
1847
|
+
let value = ${f}(${O.get("batch","channel","h")});
|
|
1848
|
+
sum += value;
|
|
1849
|
+
squared_sum += value * value;
|
|
1850
|
+
}
|
|
1851
|
+
workgroup_shared[local_idx] = ${m}(sum, squared_sum);
|
|
1852
|
+
workgroupBarrier();
|
|
1853
|
+
|
|
1854
|
+
for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {
|
|
1855
|
+
if (local_idx < currSize) {
|
|
1856
|
+
workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];
|
|
1857
|
+
}
|
|
1858
|
+
workgroupBarrier();
|
|
1859
|
+
}
|
|
1860
|
+
if (local_idx == 0) {
|
|
1861
|
+
let sum_final = ${Y("workgroup_shared[0][0]",h)} / f32(hight * ${h});
|
|
1862
|
+
let squared_sum_final = ${Y("workgroup_shared[0][1]",h)} / f32(hight * ${h});
|
|
1863
|
+
|
|
1864
|
+
let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${c}));
|
|
1865
|
+
let channel_scale = inv_std_dev * f32(scale[channel]);
|
|
1866
|
+
let channel_shift = f32(bias[channel]) - sum_final * channel_scale;
|
|
1867
|
+
output[workgroup_index] = vec2f(channel_scale, channel_shift);
|
|
1868
|
+
}
|
|
1869
|
+
}`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${h};${c};${w}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:b,dataType:1}],dispatchGroup:{x:g},programUniforms:M}),getShaderSource:k},{inputs:[t,n,i],outputs:[-1]})[0]},pc=(e,t,n)=>{let i=t[0].dims,o=i,l=2,u=i[0],c=i[1],h=j.sizeFromDimension(i,l),f=V(h),m=j.size(o)/f,g=ka(e,t[0],t[1],t[2],u,h,c,n.epsilon),w=[u,c,h/f],_=[u,c],b=["type","none"],x=M=>{let k=U("x",t[0].dataType,w.length,f),$=U("scale_shift",1,_.length,2),O=de("output",t[0].dataType,w.length,f),I=[k,$,O];return`
|
|
1870
|
+
${M.registerUniform("output_size","u32").declareVariables(...I)}
|
|
1871
|
+
${M.mainStart()}
|
|
1872
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1873
|
+
let outputIndices = ${O.offsetToIndices("global_idx")};
|
|
1874
|
+
let batch = outputIndices[0];
|
|
1875
|
+
let channel = outputIndices[1];
|
|
1876
|
+
let scale_shift = ${$.getByIndices("vec2<u32>(batch, channel)")};
|
|
1877
|
+
let value = ${k.getByOffset("global_idx")} * ${O.type.value}(scale_shift.x) + ${O.type.value}(scale_shift.y);
|
|
1878
|
+
${O.setByOffset("global_idx","value")};
|
|
1879
|
+
}`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${f}`,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]})},fc=(e,t,n)=>{let i=t[0].dims,o=i,l=i[0],u=i[i.length-1],c=j.sizeFromDimension(i,1)/u,h=V(u),f=j.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(_t(e.inputs[0],_),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:i.length},(k,$)=>i[_[$]])),x=ka(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=W=>{let te=W===0?"x":"y",fe=h===1?"f32":`vec${h}f`;switch(h){case 1:return`${$}(${fe}(scale.${te}))`;case 2:return`vec2<${$}>(${fe}(scale[0].${te}, scale[1].${te}))`;case 4:return`vec4<${$}>(${fe}(scale[0].${te}, scale[1].${te}, scale[2].${te}, scale[3].${te}))`;default:throw new Error(`Not supported compoents ${h}`)}},B=U("input",t[0].dataType,t[0].dims,h),q=de("output",t[0].dataType,o,h);return`
|
|
1880
|
+
@group(0) @binding(0) var<storage, read> input : array<${B.type.storage}>;
|
|
1881
|
+
@group(0) @binding(1) var<storage, read> scale_input : array<${O}>;
|
|
1882
|
+
@group(0) @binding(2) var<storage, read_write> output : array<${q.type.storage}>;
|
|
1883
|
+
struct Uniforms {H: u32, C : u32};
|
|
1884
|
+
@group(0) @binding(3) var<uniform> uniforms: Uniforms;
|
|
1885
|
+
|
|
1886
|
+
${k.mainStart()}
|
|
1887
|
+
let current_image_number = global_idx / (uniforms.C * uniforms.H);
|
|
1888
|
+
let current_channel_number = global_idx % uniforms.C;
|
|
1889
|
+
|
|
1890
|
+
let scale_offset = current_image_number * uniforms.C + current_channel_number;
|
|
1891
|
+
let scale = scale_input[scale_offset];
|
|
1892
|
+
output[global_idx] = fma(input[global_idx], ${I(0)}, ${I(1)});
|
|
1893
|
+
}`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${h}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:m}),getShaderSource:M},{inputs:[t[0],x]})},mc=(e,t)=>{t.format==="NHWC"?fc(e,e.inputs,t):pc(e,e.inputs,t)}}),gc,yc,wc,Hm=S(()=>{Ie(),ke(),we(),gc=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},yc=(e,t,n)=>{let i=t.simplified,o=e[0].dims,l=e[1],u=!i&&e[2],c=o,h=j.normalizeAxis(t.axis,o.length),f=j.sizeToDimension(o,h),m=j.sizeFromDimension(o,h),g=j.size(l.dims),w=u?j.size(u.dims):0;if(g!==m||u&&w!==m)throw new Error(`Size of X.shape()[axis:] == ${m}.
|
|
1894
|
+
Size of scale and bias (if provided) must match this.
|
|
1895
|
+
Got scale size of ${g} and bias size of ${w}`);let _=[];for(let B=0;B<o.length;++B)B<h?_.push(o[B]):_.push(1);let b=V(m),x=["type","type"],M=[{type:12,data:f},{type:1,data:m},{type:12,data:Math.floor(m/b)},{type:1,data:t.epsilon}];u&&x.push("type");let k=n>1,$=n>2,O=B=>{let q=G(e[0].dataType),W=[U("x",e[0].dataType,e[0].dims,b),U("scale",l.dataType,l.dims,b)];u&&W.push(U("bias",u.dataType,u.dims,b)),W.push(de("output",e[0].dataType,c,b)),k&&W.push(de("mean_data_output",1,_)),$&&W.push(de("inv_std_output",1,_));let te=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`
|
|
1896
|
+
${B.registerUniforms(te).declareVariables(...W)}
|
|
1897
|
+
${B.mainStart()}
|
|
1898
|
+
${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}
|
|
1899
|
+
let offset = global_idx * uniforms.norm_size_vectorized;
|
|
1900
|
+
var mean_vector = ${ne("f32",b)};
|
|
1901
|
+
var mean_square_vector = ${ne("f32",b)};
|
|
1902
|
+
|
|
1903
|
+
for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {
|
|
1904
|
+
let value = ${oe(q,b,"x[h + offset]")};
|
|
1905
|
+
mean_vector += value;
|
|
1906
|
+
mean_square_vector += value * value;
|
|
1907
|
+
}
|
|
1908
|
+
let mean = ${Y("mean_vector",b)} / uniforms.norm_size;
|
|
1909
|
+
let inv_std_dev = inverseSqrt(${Y("mean_square_vector",b)} / uniforms.norm_size ${i?"":"- mean * mean"} + uniforms.epsilon);
|
|
1910
|
+
|
|
1911
|
+
for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {
|
|
1912
|
+
let f32input = ${oe(q,b,"x[j + offset]")};
|
|
1913
|
+
let f32scale = ${oe(q,b,"scale[j]")};
|
|
1914
|
+
output[j + offset] = ${W[0].type.value}((f32input ${i?"":"- mean"}) * inv_std_dev * f32scale
|
|
1915
|
+
${u?`+ ${oe(q,b,"bias[j]")}`:""}
|
|
1916
|
+
);
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
${k?"mean_data_output[global_idx] = mean":""};
|
|
1920
|
+
${$?"inv_std_output[global_idx] = inv_std_dev":""};
|
|
1921
|
+
}`},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(f/64)},programUniforms:M}),getShaderSource:O}},wc=(e,t)=>{gc(e.inputs),e.compute(yc(e.inputs,t,e.outputCount))}}),vc,_c,jm=S(()=>{ke(),da(),fa(),vc=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.")},_c=e=>{vc(e.inputs);let t=Pr.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(ua(e.inputs,{activation:""},t));else{let o=t[t.length-2],l=j.size(e.inputs[0].dims.slice(0,-2)),u=j.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]),f=[1,l,n],m=[c,h];e.compute(Ei(m,{activation:""},t,f),{inputs:m})}else e.compute(Ei(e.inputs,{activation:""},t))}}}),bc,Sc,Tc,Ec,$c,Km=S(()=>{Ie(),ke(),A(),we(),bc=(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(!j.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(j.size(c)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let h=e[3].dims,f=t.n*(t.bits===8?o:Math.floor((o*t.bits+7)/8));if(j.size(h)!==f)throw new Error("zeroPoints input size error.")}},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=j.size(c),f=e[1].dims[2]/4,m=e[0].dataType,g=V(t.k),w=V(f),_=V(u),b=c.concat([o,u]),x=o>1&&u/_%2===0?2:1,M=j.size(b)/_/x,k=64,$=[],O=[h,o,l/g],I=j.convertShape(e[1].dims).slice();I.splice(-1,1,f/w),$.push(...L(O)),$.push(...L(I)),$.push(...L(e[2].dims)),e.length===4&&$.push(...L(j.convertShape(e[3].dims)));let B=[h,o,u/_];$.push(...L(B));let q=W=>{let te=O.length,fe=U("a",e[0].dataType,te,g),be=U("b",12,I.length,w),qe=U("scales",e[2].dataType,e[2].dims.length),Re=[fe,be,qe],Me=e.length===4?U("zero_points",12,e[3].dims.length):void 0;Me&&Re.push(Me);let rt=B.length,ye=de("output",e[0].dataType,rt,_),xe=G(e[0].dataType),Be=(()=>{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.`)}})(),je=Math.floor(32/t.bits),Le=Math.floor(je/8),Xe=()=>{let Ae="";for(let $e=0;$e<Le;$e++){let Kt=$e*t.bits*4,lr=Kt+t.bits;Ae+=`
|
|
1922
|
+
// reuse a data (pass ${$e})
|
|
1923
|
+
var input_offset${$e>0?$e:""} = ${$e===0?fe.indicesToOffset(`${fe.type.indices}(batch, row, word_offset)`):"input_offset"};
|
|
1924
|
+
var a_data${$e>0?$e:""}: ${Be};
|
|
1925
|
+
for (var j${$e>0?$e:""}: u32 = 0; j${$e>0?$e:""} < ${8/g}; j${$e>0?$e:""}++) {
|
|
1926
|
+
a_data${$e>0?$e:""}[j${$e>0?$e:""}] = ${fe.getByOffset(`input_offset${$e>0?$e:""}`)};
|
|
1927
|
+
input_offset${$e>0?$e:""}++;
|
|
1928
|
+
}
|
|
1929
|
+
`;for(let Rt=0;Rt<_*x;Rt++)Ae+=`
|
|
1930
|
+
b_value = ${w===1?`b${Rt}_data`:`b${Rt}_data[i]`};
|
|
1931
|
+
${t.bits===2?`{
|
|
1932
|
+
let half_word = b_value >> ${$e*16}u;
|
|
1933
|
+
let byte_lo = half_word & 0xFFu;
|
|
1934
|
+
let byte_hi = (half_word >> 8u) & 0xFFu;
|
|
1935
|
+
let spread_word = (byte_lo & 0xFu) | ((byte_lo >> 4u) << 8u) | ((byte_hi & 0xFu) << 16u) | ((byte_hi >> 4u) << 24u);
|
|
1936
|
+
b_value_lower = unpack4xU8(spread_word & b_mask);
|
|
1937
|
+
b_value_upper = unpack4xU8((spread_word >> 2u) & b_mask);
|
|
1938
|
+
}`:`b_value_lower = unpack4xU8((b_value >> ${Kt}u) & b_mask);
|
|
1939
|
+
b_value_upper = unpack4xU8((b_value >> ${lr}u) & b_mask);`}
|
|
1940
|
+
b_quantized_values = ${Be}(${Array.from({length:4},(ur,ht)=>`${xe}(b_value_lower[${ht}]), ${xe}(b_value_upper[${ht}])`).join(", ")});
|
|
1941
|
+
b_dequantized_values = ${g===1?`${Be}(${Array.from({length:8},(ur,ht)=>`(b_quantized_values[${ht}] - ${Me?`zero_point${Rt}`:"zero_point"}) * scale${Rt}`).join(", ")});`:`(b_quantized_values - ${Be}(${Array(8).fill(`${Me?`zero_point${Rt}`:"zero_point"}`).join(",")})) * scale${Rt};`};
|
|
1942
|
+
workgroup_shared[local_id.x * ${x} + ${Math.floor(Rt/_)}]${_>1?`[${Rt%_}]`:""} += ${Array.from({length:8/g},(ur,ht)=>`${g===1?`a_data${$e>0?$e:""}[${ht}] * b_dequantized_values[${ht}]`:`dot(a_data${$e>0?$e:""}[${ht}], b_dequantized_values[${ht}])`}`).join(" + ")};
|
|
1943
|
+
`}return Ae},ue=()=>{let Ae=`
|
|
1944
|
+
var col_index = col * ${_};
|
|
1945
|
+
${Me?`
|
|
1946
|
+
let zero_point_values_per_byte: u32 = ${Math.floor(8/t.bits)}u;
|
|
1947
|
+
let zero_point_bytes_per_col = (nBlocksPerCol + zero_point_values_per_byte - 1u) / zero_point_values_per_byte;
|
|
1948
|
+
var zero_point_byte_count: u32;
|
|
1949
|
+
var zero_point_word_index: u32;
|
|
1950
|
+
var zero_point_byte_offset: u32;
|
|
1951
|
+
let zero_point_sub_offset: u32 = block % zero_point_values_per_byte;
|
|
1952
|
+
var zero_point_bits_offset: u32;
|
|
1953
|
+
var zero_point_word: u32;`:`
|
|
1954
|
+
// The default zero point is ${Math.pow(2,t.bits-1)} for unsigned ${t.bits}-bit quantization.
|
|
1955
|
+
let zero_point = ${xe}(${Math.pow(2,t.bits-1).toFixed(1)});`}
|
|
1956
|
+
`;for(let $e=0;$e<_*x;$e++)Ae+=`
|
|
1957
|
+
let scale${$e} = ${qe.getByOffset("col_index * nBlocksPerCol + block")};
|
|
1958
|
+
${Me?`
|
|
1959
|
+
zero_point_byte_count = col_index * zero_point_bytes_per_col + (block / zero_point_values_per_byte);
|
|
1960
|
+
zero_point_word_index = zero_point_byte_count >> 0x2u;
|
|
1961
|
+
zero_point_byte_offset = zero_point_byte_count & 0x3u;
|
|
1962
|
+
zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_sub_offset * ${t.bits}u);
|
|
1963
|
+
zero_point_word = ${Me.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
1964
|
+
let zero_point${$e} = ${xe}((zero_point_word) & ${t.bits===2?"0x3u":"0xFu"});`:""}
|
|
1965
|
+
col_index += 1;`;return Ae},ze=()=>{let Ae=`col_index = col * ${_};`;for(let $e=0;$e<_*x;$e++)Ae+=`
|
|
1966
|
+
let b${$e}_data = ${be.getByIndices(`${be.type.indices}(col_index, block, word)`)};
|
|
1967
|
+
col_index += 1;`;return Ae+=`
|
|
1968
|
+
var b_value: u32;
|
|
1969
|
+
let b_mask: u32 = ${t.bits===2?"0x03030303u":"0x0F0F0F0Fu"};
|
|
1970
|
+
var b_value_lower: vec4<u32>;
|
|
1971
|
+
var b_value_upper: vec4<u32>;
|
|
1972
|
+
var b_quantized_values: ${Be};
|
|
1973
|
+
var b_dequantized_values: ${Be};`,Ae};return`
|
|
1974
|
+
var<workgroup> workgroup_shared: array<${ye.type.value}, ${x*k}>;
|
|
1975
|
+
${W.declareVariables(...Re,ye)}
|
|
1976
|
+
${W.mainStart([k,1,1])}
|
|
1977
|
+
let output_indices = ${ye.offsetToIndices(`(global_idx / ${k}) * ${x}`)};
|
|
1978
|
+
let col = output_indices[2];
|
|
1979
|
+
let row = output_indices[1];
|
|
1980
|
+
let batch = output_indices[0];
|
|
1981
|
+
let nBlocksPerCol = uniforms.b_shape[1];
|
|
1982
|
+
|
|
1983
|
+
for (var block = local_id.x; block < nBlocksPerCol; block += ${k}) {
|
|
1984
|
+
//process one block
|
|
1985
|
+
var word_offset: u32 = block * ${t.blockSize/g};
|
|
1986
|
+
${ue()}
|
|
1987
|
+
for (var word: u32 = 0; word < ${f}; word += ${w}) {
|
|
1988
|
+
${ze()}
|
|
1989
|
+
for (var i: u32 = 0; i < ${w}; i++) {
|
|
1990
|
+
${Xe()}
|
|
1991
|
+
word_offset += ${je/g};
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
workgroupBarrier();
|
|
1996
|
+
|
|
1997
|
+
if (local_id.x < ${x}) {
|
|
1998
|
+
var output_value: ${ye.type.value} = ${ye.type.value}(0);
|
|
1999
|
+
var workgroup_shared_offset: u32 = local_id.x;
|
|
2000
|
+
for (var b: u32 = 0u; b < ${k}u; b++) {
|
|
2001
|
+
output_value += workgroup_shared[workgroup_shared_offset];
|
|
2002
|
+
workgroup_shared_offset += ${x};
|
|
2003
|
+
}
|
|
2004
|
+
${ye.setByIndices(`${ye.type.indices}(batch, row, col + local_id.x)`,"output_value")};
|
|
2005
|
+
}
|
|
2006
|
+
}`};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}},Tc=(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=j.size(c),f=e[1].dims[2]/4,m=e[0].dataType,g=V(t.k),w=V(f),_=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=j.size(_)/x,q=[],W=[h,o,l/g],te=j.convertShape(e[1].dims).slice();te.splice(-1,1,f/w),q.push(...L(W)),q.push(...L(te)),q.push(...L(e[2].dims)),e.length===4&&q.push(...L(j.convertShape(e[3].dims)));let fe=[h,o,u];q.push(...L(fe));let be=qe=>{let Re=W.length,Me=U("a",e[0].dataType,Re,g),rt=U("b",12,te.length,w),ye=U("scales",e[2].dataType,e[2].dims.length),xe=[Me,rt,ye],Be=e.length===4?U("zero_points",12,e[3].dims.length):void 0;Be&&xe.push(Be);let je=fe.length,Le=de("output",e[0].dataType,je),Xe=G(e[0].dataType),ue=()=>{switch(g){case 1:return`
|
|
2007
|
+
let a_data0 = vec4<${Xe}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);
|
|
2008
|
+
let a_data1 = vec4<${Xe}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`
|
|
2009
|
+
let a_data0 = vec4<${Xe}>(sub_a[word_offset], sub_a[word_offset + 1]);
|
|
2010
|
+
let a_data1 = vec4<${Xe}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`
|
|
2011
|
+
let a_data0 = sub_a[word_offset];
|
|
2012
|
+
let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${g}-component is not supported.`)}};return`
|
|
2013
|
+
var<workgroup> sub_a: array<${Me.type.value}, ${O}>;
|
|
2014
|
+
var<workgroup> inter_results: array<array<${Le.type.value}, ${M}>, ${x}>;
|
|
2015
|
+
${qe.declareVariables(...xe,Le)}
|
|
2016
|
+
${qe.mainStart([M,x,1])}
|
|
2017
|
+
let output_indices = ${Le.offsetToIndices(`workgroup_index * ${x}`)};
|
|
2018
|
+
let col = output_indices[2];
|
|
2019
|
+
let row = output_indices[1];
|
|
2020
|
+
let batch = output_indices[0];
|
|
2021
|
+
let n_blocks_per_col = uniforms.b_shape[1];
|
|
2022
|
+
let num_tiles = (n_blocks_per_col - 1) / ${I} + 1;
|
|
2023
|
+
|
|
2024
|
+
// Loop over shared dimension.
|
|
2025
|
+
for (var tile: u32 = 0; tile < num_tiles; tile += 1) {
|
|
2026
|
+
let a_col_start = tile * ${O};
|
|
2027
|
+
// load one tile A data into shared memory.
|
|
2028
|
+
for (var a_offset = local_idx; a_offset < ${O}; a_offset += ${b})
|
|
2029
|
+
{
|
|
2030
|
+
let a_col = a_col_start + a_offset;
|
|
2031
|
+
if (a_col < uniforms.a_shape[2])
|
|
2032
|
+
{
|
|
2033
|
+
sub_a[a_offset] = ${Me.getByIndices(`${Me.type.indices}(batch, row, a_col)`)};
|
|
2034
|
+
} else {
|
|
2035
|
+
sub_a[a_offset] = ${Me.type.value}(0);
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
workgroupBarrier();
|
|
2039
|
+
|
|
2040
|
+
// each thread process one block
|
|
2041
|
+
let b_row = col + local_id.y;
|
|
2042
|
+
let block = tile * ${I} + local_id.x;
|
|
2043
|
+
${Be?`
|
|
2044
|
+
let zero_point_values_per_byte: u32 = ${Math.floor(8/t.bits)}u;
|
|
2045
|
+
let zero_point_bytes_per_col = (n_blocks_per_col + zero_point_values_per_byte - 1u) / zero_point_values_per_byte;
|
|
2046
|
+
let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block / zero_point_values_per_byte);
|
|
2047
|
+
let zero_point_word_index = zero_point_byte_count >> 0x2u;
|
|
2048
|
+
let zero_point_byte_offset = zero_point_byte_count & 0x3u;
|
|
2049
|
+
let zero_point_sub_offset: u32 = block % zero_point_values_per_byte;
|
|
2050
|
+
let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_sub_offset * ${t.bits}u);
|
|
2051
|
+
let zero_point_word = ${Be.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
2052
|
+
let zero_point = ${Xe}((zero_point_word) & ${t.bits===2?"0x3u":"0xFu"});`:`
|
|
2053
|
+
// The default zero point is ${Math.pow(2,t.bits-1)} for unsigned ${t.bits}-bit quantization.
|
|
2054
|
+
let zero_point = ${Xe}(${Math.pow(2,t.bits-1).toFixed(1)});`}
|
|
2055
|
+
let scale = ${ye.getByOffset("b_row * n_blocks_per_col + block")};
|
|
2056
|
+
let b_data = ${rt.getByIndices(`${rt.type.indices}(b_row, block, 0)`)};
|
|
2057
|
+
var word_offset = local_id.x * ${t.blockSize/g};
|
|
2058
|
+
for (var i: u32 = 0; i < ${w}; i++) {
|
|
2059
|
+
let b_value = ${w===1?"b_data":"b_data[i]"};
|
|
2060
|
+
${(()=>{let ze=Math.floor(k/8),Ae="";for(let $e=0;$e<ze;$e++){let Kt=$e*t.bits*4,lr=Kt+t.bits;Ae+=`
|
|
2061
|
+
${ue()}
|
|
2062
|
+
{${t.bits===2?`
|
|
2063
|
+
let half_word = b_value >> ${$e*16}u;
|
|
2064
|
+
let byte_lo = half_word & 0xFFu;
|
|
2065
|
+
let byte_hi = (half_word >> 8u) & 0xFFu;
|
|
2066
|
+
let spread_word = (byte_lo & 0xFu) | ((byte_lo >> 4u) << 8u) | ((byte_hi & 0xFu) << 16u) | ((byte_hi >> 4u) << 24u);
|
|
2067
|
+
let b_value_lower = unpack4xU8(spread_word & 0x03030303u);
|
|
2068
|
+
let b_value_upper = unpack4xU8((spread_word >> 2u) & 0x03030303u);`:`
|
|
2069
|
+
let b_value_lower = unpack4xU8((b_value >> ${Kt}u) & 0x0F0F0F0Fu);
|
|
2070
|
+
let b_value_upper = unpack4xU8((b_value >> ${lr}u) & 0x0F0F0F0Fu);`}
|
|
2071
|
+
let b_quantized_values = mat2x4<${Xe}>(${Array.from({length:4},(Rt,ur)=>`${Xe}(b_value_lower[${ur}]), ${Xe}(b_value_upper[${ur}])`).join(", ")});
|
|
2072
|
+
let b_dequantized_values = (b_quantized_values - mat2x4<${Xe}>(${Array(8).fill("zero_point").join(",")})) * scale;
|
|
2073
|
+
inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(Rt,ur)=>`${`dot(a_data${ur}, b_dequantized_values[${ur}])`}`).join(" + ")};
|
|
2074
|
+
}
|
|
2075
|
+
word_offset += ${8/g};`}return Ae})()}
|
|
2076
|
+
}
|
|
2077
|
+
workgroupBarrier();
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
if (local_idx < ${x}) {
|
|
2081
|
+
var output_value: ${Le.type.value} = ${Le.type.value}(0);
|
|
2082
|
+
for (var b = 0u; b < ${M}; b++) {
|
|
2083
|
+
output_value += inter_results[local_idx][b];
|
|
2084
|
+
}
|
|
2085
|
+
if (col + local_idx < uniforms.output_shape[2])
|
|
2086
|
+
{
|
|
2087
|
+
${Le.setByIndices(`${Le.type.indices}(batch, row, col + local_idx)`,"output_value")}
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${g};${w};${M};${x}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:m}],dispatchGroup:{x:B},programUniforms:q}),getShaderSource:be}},Ec=(e,t)=>{bc(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Tc(e.inputs,t)):e.compute(Sc(e.inputs,t))},$c=e=>E(e)}),xc,Cc,kc,Rc,Ac,Ic,Mc,Oc,Pc,Qm=S(()=>{Ie(),ke(),we(),xc=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Cc=(e,t,n)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2091
|
+
k = i32(${e.indicesGet("indices",o)}) - ${K("uniforms.pads",o,n)};
|
|
2092
|
+
if (k < 0) {
|
|
2093
|
+
break;
|
|
2094
|
+
}
|
|
2095
|
+
if (k >= i32(${K("uniforms.x_shape",o,t)})) {
|
|
2096
|
+
break;
|
|
2097
|
+
}
|
|
2098
|
+
offset += k * i32(${K("uniforms.x_strides",o,t)});
|
|
2099
|
+
`;return`
|
|
2100
|
+
value = ${e.type.value}(uniforms.constant_value);
|
|
2101
|
+
for (var i = 0; i < 1; i++) {
|
|
2102
|
+
var offset = 0;
|
|
2103
|
+
var k = 0;
|
|
2104
|
+
${i}
|
|
2105
|
+
value = x[offset];
|
|
2106
|
+
}
|
|
2107
|
+
`},kc=(e,t,n)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2108
|
+
k = i32(${e.indicesGet("indices",o)}) - ${K("uniforms.pads",o,n)};
|
|
2109
|
+
if (k < 0) {
|
|
2110
|
+
k = -k;
|
|
2111
|
+
}
|
|
2112
|
+
{
|
|
2113
|
+
let _2n_1 = 2 * (i32(${K("uniforms.x_shape",o,t)}) - 1);
|
|
2114
|
+
k = k % _2n_1;
|
|
2115
|
+
if(k >= i32(${K("uniforms.x_shape",o,t)})) {
|
|
2116
|
+
k = _2n_1 - k;
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
offset += k * i32(${K("uniforms.x_strides",o,t)});
|
|
2120
|
+
`;return`
|
|
2121
|
+
var offset = 0;
|
|
2122
|
+
var k = 0;
|
|
2123
|
+
${i}
|
|
2124
|
+
value = x[offset];
|
|
2125
|
+
`},Rc=(e,t,n)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2126
|
+
k = i32(${e.indicesGet("indices",o)}) - ${K("uniforms.pads",o,n)};
|
|
2127
|
+
if (k < 0) {
|
|
2128
|
+
k = 0;
|
|
2129
|
+
}
|
|
2130
|
+
if (k >= i32(${K("uniforms.x_shape",o,t)})) {
|
|
2131
|
+
k = i32(${K("uniforms.x_shape",o,t)}) - 1;
|
|
2132
|
+
}
|
|
2133
|
+
offset += k * i32(${K("uniforms.x_strides",o,t)});
|
|
2134
|
+
`;return`
|
|
2135
|
+
var offset = 0;
|
|
2136
|
+
var k = 0;
|
|
2137
|
+
${i}
|
|
2138
|
+
value = x[offset];
|
|
2139
|
+
`},Ac=(e,t,n)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2140
|
+
k = i32(${e.indicesGet("indices",o)}) - ${K("uniforms.pads",o,n)};
|
|
2141
|
+
if (k < 0) {
|
|
2142
|
+
k += i32(${K("uniforms.x_shape",o,t)}]);
|
|
2143
|
+
}
|
|
2144
|
+
if (k >= i32(${K("uniforms.x_shape",o,t)})) {
|
|
2145
|
+
k -= i32(${K("uniforms.x_shape",o,t)});
|
|
2146
|
+
}
|
|
2147
|
+
offset += k * i32(${K("uniforms.x_strides",o,t)});
|
|
2148
|
+
`;return`
|
|
2149
|
+
var offset = 0;
|
|
2150
|
+
var k = 0;
|
|
2151
|
+
${i}
|
|
2152
|
+
value = x[offset];
|
|
2153
|
+
`},Ic=(e,t,n)=>{switch(n.mode){case 0:return Cc(e,t,n.pads.length);case 1:return kc(e,t,n.pads.length);case 2:return Rc(e,t,n.pads.length);case 3:return Ac(e,t,n.pads.length);default:throw new Error("Invalid mode")}},Mc=(e,t)=>{let n=j.padShape(e[0].dims.slice(),t.pads),i=e[0].dims,o=j.size(n),l=[{type:12,data:o},{type:6,data:t.pads}],u=e.length>=3&&e[2].data;t.mode===0&&l.push({type:u?e[2].dataType:1,data:t.value}),l.push(...L(e[0].dims,n));let c=["rank"],h=f=>{let m=de("output",e[0].dataType,n.length),g=U("x",e[0].dataType,i.length),w=g.type.value,_=Ic(m,i.length,t),b=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&b.push({name:"constant_value",type:u?w:"f32"}),`
|
|
2154
|
+
${f.registerUniforms(b).declareVariables(g,m)}
|
|
2155
|
+
${f.mainStart()}
|
|
2156
|
+
${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2157
|
+
|
|
2158
|
+
let indices = ${m.offsetToIndices("global_idx")};
|
|
2159
|
+
|
|
2160
|
+
var value = ${w}(0);
|
|
2161
|
+
${_}
|
|
2162
|
+
output[global_idx] = value;
|
|
2163
|
+
}`};return{name:"Pad",shaderCache:{hint:`${t.mode}${u}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(j.size(n)/64)},programUniforms:l}),getShaderSource:h}},Oc=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),i=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,l=new Int32Array(2*o).fill(0);if(e.length>=4){let c=e[3].getBigInt64Array();for(let h=0;h<c.length;h++)l[Number(c[h])]=Number(n[h]),l[Number(c[h])+o]=Number(n[h+c.length])}else n.forEach((c,h)=>l[Number(h)]=Number(c));let u=[];return l.forEach(c=>u.push(c)),{mode:t.mode,value:i,pads:u}}else return t},Pc=(e,t)=>{xc(e.inputs);let n=Oc(e.inputs,t);e.compute(Mc(e.inputs,n),{inputs:[0]})}}),Qn,Ra,Aa,Ia,Ma,Dc,zc,Oa,Pa,Lc,Bc,Da,Nc,Uc,za,Fc,Vc,Gc,qc,Xm=S(()=>{ut(),Ie(),ke(),we(),Qn=e=>{if(me.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Ra=(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():[],f=t.pads.slice();Zr.adjustPoolAttributes(n,o,u,c,h,f);let m=Zr.computePoolOutputShape(n,o,c,h,u,f,t.autoPad),g=Object.assign({},t);l?Object.assign(g,{kernelShape:u,strides:c,pads:f,dilations:h,cacheKey:t.cacheKey}):Object.assign(g,{kernelShape:u,strides:c,pads:f,cacheKey:t.cacheKey});let w=m.slice();return w.push(w.splice(1,1)[0]),[g,i?w:m]},Aa=(e,t)=>{let n=t.format==="NHWC",i=j.size(e),o=j.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],f=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],g=!!(f+m);l.push({type:12,data:c},{type:12,data:h},{type:12,data:f},{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=j.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((f,m)=>f+m);return[l,u,!!h,!1,!1]}},Ia=(e,t,n,i,o,l,u,c,h,f,m,g)=>{let w=o.format==="NHWC",_=t.type.value,b=de("output",t.type.tensor,i);if(o.kernelShape.length<=2){let x="",M="",k="",$=n-(w?2:1);if(m?x=`
|
|
2164
|
+
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2165
|
+
xIndices[${$}] = indices[${$}] * uniforms.sw - uniforms.pwStart + i;
|
|
2166
|
+
if (xIndices[${$}] < 0 || xIndices[${$}]
|
|
2167
|
+
>= uniforms.x_shape[${$}]) {
|
|
2168
|
+
pad++;
|
|
2169
|
+
continue;
|
|
2170
|
+
}
|
|
2171
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2172
|
+
${l}
|
|
2173
|
+
}`:x=`
|
|
2174
|
+
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2175
|
+
xIndices[${$}] = indices[${$}] * uniforms.sw - uniforms.pwStart + i;
|
|
2176
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2177
|
+
${l}
|
|
2178
|
+
}`,o.kernelShape.length===2){let O=n-(w?3:2);g?M=`
|
|
2179
|
+
for (var j: u32 = 0u; j < uniforms.kh; j++) {
|
|
2180
|
+
xIndices[${O}] = indices[${O}] * uniforms.sh - uniforms.phStart + j;
|
|
2181
|
+
if (xIndices[${O}] < 0 || xIndices[${O}] >= uniforms.x_shape[${O}]) {
|
|
2182
|
+
pad += i32(uniforms.kw);
|
|
2183
|
+
continue;
|
|
2184
|
+
}
|
|
2185
|
+
`:M=`
|
|
2186
|
+
for (var j: u32 = 0u; j < uniforms.kh; j++) {
|
|
2187
|
+
xIndices[${O}] = indices[${O}] * uniforms.sh - uniforms.phStart + j;
|
|
2188
|
+
`,k=`
|
|
2189
|
+
}
|
|
2190
|
+
`}return`
|
|
2191
|
+
${e.registerUniforms(h).declareVariables(t,b)}
|
|
2192
|
+
|
|
2193
|
+
${e.mainStart()}
|
|
2194
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2195
|
+
|
|
2196
|
+
let indices = ${b.offsetToIndices("global_idx")};
|
|
2197
|
+
var xIndices = ${b.offsetToIndices("global_idx")};
|
|
2198
|
+
|
|
2199
|
+
var value = ${_}(${c});
|
|
2200
|
+
var pad = 0;
|
|
2201
|
+
${M}
|
|
2202
|
+
${x}
|
|
2203
|
+
${k}
|
|
2204
|
+
${u}
|
|
2205
|
+
|
|
2206
|
+
output[global_idx] = value;
|
|
2207
|
+
}`}else{if(w)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let x=o.kernelShape.length,M=o.pads.length,k="";return f?k=`
|
|
2208
|
+
if (xIndices[j] >= uniforms.x_shape[j]) {
|
|
2209
|
+
pad++;
|
|
2210
|
+
isPad = true;
|
|
2211
|
+
break;
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
if (!isPad) {
|
|
2215
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2216
|
+
${l}
|
|
2217
|
+
}`:k=`
|
|
2218
|
+
}
|
|
2219
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2220
|
+
${l}
|
|
2221
|
+
`,`
|
|
2222
|
+
${e.registerUniforms(h).declareVariables(t,b)}
|
|
2223
|
+
|
|
2224
|
+
${e.mainStart()}
|
|
2225
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2226
|
+
let indices = ${b.offsetToIndices("global_idx")};
|
|
2227
|
+
var xIndices = ${b.offsetToIndices("global_idx")};
|
|
2228
|
+
|
|
2229
|
+
var offsets: array<u32, ${x}>;
|
|
2230
|
+
|
|
2231
|
+
var value = ${_}(${c});
|
|
2232
|
+
var pad = 0;
|
|
2233
|
+
var isPad = false;
|
|
2234
|
+
|
|
2235
|
+
for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {
|
|
2236
|
+
var offset = i;
|
|
2237
|
+
for (var j = 0u; j < ${x-1}u; j++) {
|
|
2238
|
+
offsets[j] = offset / ${K("uniforms.kernelStrides","j",x)};
|
|
2239
|
+
offset -= offsets[j] * ${K("uniforms.kernelStrides","j",x)};
|
|
2240
|
+
}
|
|
2241
|
+
offsets[${x-1}] = offset;
|
|
2242
|
+
|
|
2243
|
+
isPad = false;
|
|
2244
|
+
for (var j = ${n-x}u; j < ${n}u; j++) {
|
|
2245
|
+
xIndices[j] = indices[j] * ${K("uniforms.strides",`j - ${n-x}u`,x)}
|
|
2246
|
+
+ offsets[j - ${n-x}u] - ${K("uniforms.pads","j - 2u",M)};
|
|
2247
|
+
${k}
|
|
2248
|
+
}
|
|
2249
|
+
${u}
|
|
2250
|
+
|
|
2251
|
+
output[global_idx] = value;
|
|
2252
|
+
}`}},Ma=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Dc=e=>`${Ma(e)};${e.countIncludePad}`,zc=e=>`${Ma(e)};${e.storageOrder};${e.dilations}`,Oa=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}),Pa=(e,t,n,i)=>{let[o,l]=Ra(t,i,n),u=U("x",t.dataType,t.dims.length),c=u.type.value,h="value += x_val;",f="";o.countIncludePad?f+=`value /= ${c}(uniforms.kernelSize);`:f+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[m,g,w,_,b]=Aa(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(j.size(l)/64)},programUniforms:m}),getShaderSource:M=>Ia(M,u,t.dims.length,l.length,o,h,f,0,g,w,_,b)}},Lc=e=>{let t=e.count_include_pad!==0,n=Oa(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:Dc(i)}},Bc=(e,t)=>{Qn(e.inputs),e.compute(Pa("AveragePool",e.inputs[0],!1,t))},Da={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Nc=e=>{let t=e.format;return{format:t,...Da,cacheKey:t}},Uc=(e,t)=>{Qn(e.inputs),e.compute(Pa("GlobalAveragePool",e.inputs[0],!0,t))},za=(e,t,n,i)=>{let[o,l]=Ra(t,i,n),u=`
|
|
2253
|
+
value = max(x_val, value);
|
|
2254
|
+
`,c="",h=U("x",t.dataType,t.dims.length),f=["rank"],[m,g,w,_,b]=Aa(l,o);return m.push(...L(t.dims,l)),{name:e,shaderCache:{hint:`${i.cacheKey};${w};${_};${b}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(j.size(l)/64)},programUniforms:m}),getShaderSource:x=>Ia(x,h,t.dims.length,l.length,o,u,c,t.dataType===10?-65504:-1e5,g,w,_,b)}},Fc=(e,t)=>{Qn(e.inputs),e.compute(za("MaxPool",e.inputs[0],!1,t))},Vc=e=>{let t=e.storage_order,n=e.dilations,i=Oa(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:zc(o)}},Gc=e=>{let t=e.format;return{format:t,...Da,cacheKey:t}},qc=(e,t)=>{Qn(e.inputs),e.compute(za("GlobalMaxPool",e.inputs[0],!0,t))}}),Wc,Hc,jc,Kc,Ym=S(()=>{Ie(),ke(),A(),we(),Wc=(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)].")}},Hc=(e,t)=>{let n=j.normalizeAxis(t.axis,e[0].dims.length),i=e[0].dataType,o=i===3,l=e[0].dims,u=e[1].dataType,c=j.size(l),h=i===3||i===2,f=h?[Math.ceil(j.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(j.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=U("input",h?12:i,f.length,$),I=U("scale",u,m.length),B=g?U("zero_point",h?12:i,w.length):void 0,q=de("output",u,l.length,k),W=[O,I];B&&W.push(B);let te=[f,m];g&&te.push(w);let fe=[{type:12,data:c/k},{type:12,data:n},{type:12,data:t.blockSize},...L(...te,l)],be=qe=>{let Re=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
2255
|
+
${qe.registerUniforms(Re).declareVariables(...W,q)}
|
|
2256
|
+
${qe.mainStart()}
|
|
2257
|
+
${qe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2258
|
+
let output_indices = ${q.offsetToIndices("global_idx")};
|
|
2259
|
+
|
|
2260
|
+
// Set input x
|
|
2261
|
+
${h?`
|
|
2262
|
+
let input = ${O.getByOffset("global_idx / 4")};
|
|
2263
|
+
let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"};
|
|
2264
|
+
let x_value = ${k===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${O.getByOffset("global_idx")};`};
|
|
2265
|
+
|
|
2266
|
+
// Set scale input
|
|
2267
|
+
${_?`let scale_value= ${I.getByOffset("0")}`:b?`
|
|
2268
|
+
let scale_index = ${q.indicesGet("output_indices","uniforms.axis")};
|
|
2269
|
+
let scale_value= ${I.getByOffset("scale_index")};`:`
|
|
2270
|
+
var scale_indices: ${I.type.indices} = output_indices;
|
|
2271
|
+
let index = ${I.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size;
|
|
2272
|
+
${I.indicesSet("scale_indices","uniforms.axis","index")};
|
|
2273
|
+
let scale_value= ${I.getByIndices("scale_indices")};`};
|
|
2274
|
+
|
|
2275
|
+
// Set zero-point input
|
|
2276
|
+
${B?_?h?`
|
|
2277
|
+
let zero_point_input = ${B.getByOffset("0")};
|
|
2278
|
+
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2279
|
+
let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${B.getByOffset("0")}`:b?h?`
|
|
2280
|
+
let zero_point_index = ${q.indicesGet("output_indices","uniforms.axis")};
|
|
2281
|
+
let zero_point_input = ${B.getByOffset("zero_point_index / 4")};
|
|
2282
|
+
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2283
|
+
let zero_point_value = zero_point_vec[zero_point_index % 4]`:`
|
|
2284
|
+
let zero_point_index = ${q.indicesGet("output_indices","uniforms.axis")};
|
|
2285
|
+
let zero_point_value = ${B.getByOffset("zero_point_index")};`:h?`
|
|
2286
|
+
let zero_point_offset = ${I.indicesToOffset("scale_indices")};
|
|
2287
|
+
let zero_point_input = ${B.getByOffset("zero_point_offset / 4")};
|
|
2288
|
+
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2289
|
+
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);`};
|
|
2290
|
+
// Compute and write output
|
|
2291
|
+
${q.setByOffset("global_idx",`${q.type.value}(x_value - zero_point_value) * scale_value`)};
|
|
2292
|
+
}`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:B?["rank","rank","rank"]:["rank","rank"]},getShaderSource:be,getRunData:()=>({outputs:[{dims:l,dataType:u}],dispatchGroup:{x:Math.ceil(c/k/64),y:1,z:1},programUniforms:fe})}},jc=(e,t)=>{Wc(e.inputs,t),e.compute(Hc(e.inputs,t))},Kc=e=>E({axis:e.axis,blockSize:e.blockSize})}),Qc,Xc,Yc,Jm=S(()=>{ut(),Ie(),we(),Qc=(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.")},Xc=(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=f=>{let m=de("output",i,l.length),g=m.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:g},{name:"delta",type:g}];return`
|
|
2293
|
+
${f.registerUniforms(w).declareVariables(m)}
|
|
2294
|
+
${f.mainStart()}
|
|
2295
|
+
${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2296
|
+
output[global_idx] = uniforms.start + ${g}(global_idx) * uniforms.delta;
|
|
2297
|
+
}`};return{name:"Range",shaderCache:{hint:`${i}`},getShaderSource:h,getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c})}},Yc=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&&Qc(t,n,i),e.compute(Xc(t,n,i,e.inputs[0].dataType),{inputs:[]})}}),Jc,Zc,eh,th,Zm=S(()=>{Ie(),ke(),A(),we(),Jc=(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=`{
|
|
2298
|
+
var oldValue = 0;
|
|
2299
|
+
loop {
|
|
2300
|
+
let newValueF32 =`,l=`;
|
|
2301
|
+
let newValue = bitcast<i32>(newValueF32);
|
|
2302
|
+
let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue);
|
|
2303
|
+
if res.exchanged {
|
|
2304
|
+
break;
|
|
2305
|
+
}
|
|
2306
|
+
oldValue = res.old_value;
|
|
2307
|
+
}
|
|
2308
|
+
}`;switch(e){case"none":return`${t}=${n};`;case"add":return i==="i32"||i==="u32"?`atomicAdd(&${t}, bitcast<${i}>(${n}));`:`
|
|
2309
|
+
${o}bitcast<${i}>(oldValue) + (${n})${l}`;case"max":return i==="i32"||i==="u32"?`atomicMax(&${t}, bitcast<${i}>(${n}));`:`
|
|
2310
|
+
${o}max(bitcast<f32>(oldValue), (${n}))${l}`;case"min":return i==="i32"||i==="u32"?`atomicMin(&${t}, bitcast<${i}>(${n}));`:`${o}min(bitcast<${i}>(oldValue), (${n}))${l}`;case"mul":return`${o}(bitcast<${i}>(oldValue) * (${n}))${l}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Zc=(e,t)=>{let n=e[0].dims,i=e[1].dims,o=n,l=1,u=Math.ceil(j.sizeToDimension(i,i.length-1)/l),c=i[i.length-1],h=j.sizeFromDimension(n,c),f=[{type:12,data:u},{type:12,data:c},{type:12,data:h},...L(e[1].dims,e[2].dims,o)],m=g=>{let w=U("indices",e[1].dataType,e[1].dims.length),_=U("updates",e[2].dataType,e[2].dims.length,l),b=t.reduction!=="none"&&t.reduction!==""?ft("output",e[0].dataType,o.length):de("output",e[0].dataType,o.length,l);return`
|
|
2311
|
+
${g.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(w,_,b)}
|
|
2312
|
+
${g.mainStart()}
|
|
2313
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2314
|
+
var data_offset = 0u;
|
|
2315
|
+
let indices_start = uniforms.last_index_dimension * global_idx;
|
|
2316
|
+
let indices_end = indices_start + uniforms.last_index_dimension;
|
|
2317
|
+
for (var i = indices_start; i < indices_end; i++) {
|
|
2318
|
+
var index = i32(indices[i].x);
|
|
2319
|
+
${e[0].dims.length===1?`
|
|
2320
|
+
let element_count_dim = uniforms.output_strides;
|
|
2321
|
+
let dim_value = uniforms.output_shape;`:`
|
|
2322
|
+
let element_count_dim = uniforms.output_strides[i - indices_start];
|
|
2323
|
+
let dim_value = uniforms.output_shape[i - indices_start];`}
|
|
2324
|
+
if (index >= 0) {
|
|
2325
|
+
if (index >= i32(dim_value)) {
|
|
2326
|
+
index = i32(dim_value - 1);
|
|
2327
|
+
}
|
|
2328
|
+
} else {
|
|
2329
|
+
if (index < -i32(dim_value)) {
|
|
2330
|
+
index = 0;
|
|
2331
|
+
} else {
|
|
2332
|
+
index += i32(dim_value);
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
data_offset += u32((u32(index) * element_count_dim));
|
|
2336
|
+
}
|
|
2337
|
+
|
|
2338
|
+
for (var i = 0u; i < uniforms.num_updates_elements; i++) {
|
|
2339
|
+
let value = updates[uniforms.num_updates_elements * global_idx + i];
|
|
2340
|
+
${Jc(t.reduction,"output[data_offset + i]","value",b.type.value)}
|
|
2341
|
+
}
|
|
2342
|
+
|
|
2343
|
+
}`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:m}},eh=e=>E({reduction:e.reduction}),th=(e,t)=>{e.compute(Zc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),rh,sh,nh,La,ih,ah,oh,lh,uh,dh,ch,hh,Ba,ph,fh,mh,gh,yh,wh,vh,eg=S(()=>{Ie(),ke(),A(),we(),rh=(e,t)=>{if(e.every(n=>n>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and
|
|
2344
|
+
one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},sh=(e,t,n)=>{t.every(o=>o>=0&&o<n||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")}));let i=new Array(n).fill(1);return t.forEach((o,l)=>i[o]=e[l]),i},nh=(e,t,n,i,o,l)=>{let[u,c,h]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],f=e[0].dims.length;if(u>0&&e.length>u&&e[u].dims.length>0)e[u].getFloat32Array().forEach(m=>l.push(m));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(c>0&&e.length>c&&e[c].dims.length===1&&e[c].dims[0]>0){if(e[c].getFloat32Array().forEach(m=>i.push(m)),i.length!==0&&i.length!==f&&n>=18&&i.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");rh(i,t),t.axes.length>0&&sh(i,t.axes,f).forEach((m,g)=>i[g]=m)}if(h>0&&e.length>h&&e[h].dims.length===1&&e[h].dims[0]>0&&(e[h].getBigInt64Array().forEach(m=>o.push(Number(m))),o.length!==0&&o.length!==f&&n>=18&&o.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(i.length!==0&&i.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof i<"u"&&typeof o<"u"&&i.length>0&&o.length>f)throw new Error("Resize requires only of scales or sizes to be specified")},La=(e,t,n,i)=>`
|
|
2345
|
+
// The whole part and the fractional part are calculated separately due to inaccuracy of floating
|
|
2346
|
+
// point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
|
|
2347
|
+
// offset-by-one error later in floor().
|
|
2348
|
+
let big = (${e}) * (${t});
|
|
2349
|
+
let whole = ${i}(big / (${n}));
|
|
2350
|
+
let fract = ${i}(big % (${n})) / ${i}(${n});
|
|
2351
|
+
return whole + fract;
|
|
2352
|
+
`,ih=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,
|
|
2353
|
+
lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`
|
|
2354
|
+
if (xScale < 1.0 || floor(xScale) != xScale) {
|
|
2355
|
+
return ${t}(xResized) / ${t}(xScale);
|
|
2356
|
+
} else {
|
|
2357
|
+
${La("xResized","lengthOriginal","lengthResized",t)}
|
|
2358
|
+
}
|
|
2359
|
+
`;case"pytorch_half_pixel":return`if (lengthResized > 1) {
|
|
2360
|
+
return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;
|
|
2361
|
+
} else {
|
|
2362
|
+
return 0.0;
|
|
2363
|
+
}`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {
|
|
2364
|
+
return 0.0;
|
|
2365
|
+
} else {
|
|
2366
|
+
${La("xResized","lengthOriginal - 1","lengthResized - 1",t)}
|
|
2367
|
+
}`;case"tf_crop_and_resize":return`if (lengthResized > 1) {
|
|
2368
|
+
return ${t}(roiStart) * ${t}(lengthOriginal - 1) +
|
|
2369
|
+
(${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /
|
|
2370
|
+
${t}(lengthResized - 1);
|
|
2371
|
+
} else {
|
|
2372
|
+
return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);
|
|
2373
|
+
}`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);
|
|
2374
|
+
const adjustment = ${t}(lengthResized) / outputWidth;
|
|
2375
|
+
const center = ${t}(lengthOriginal) / 2;
|
|
2376
|
+
const offset = center * (1 - adjustment);
|
|
2377
|
+
return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",ah=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",oh=(e,t,n)=>{let i=new Array(n).fill(0).concat(new Array(n).fill(1)),o=e.length===0?i:e.slice();return t.length>0?(t.forEach((l,u)=>{i[l]=o[u],i[u+n]=o[t.length+u]}),i):o},lh=(e,t,n,i)=>{let o=[];if(n.length>0)if(i.length>0){if(e.forEach(l=>o.push(l)),Math.max(...i)>e.length)throw new Error("axes is out of bound");i.forEach((l,u)=>o[l]=n[u])}else n.forEach(l=>o.push(l));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((l,u)=>Math.round(l*t[u]))}return o},uh=(e,t,n)=>{let i=(()=>{switch(n.keepAspectRatioPolicy){case"not_larger":return n.axes.length>0?Math.min(...n.axes.map(l=>t[l]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return n.axes.length>0?Math.max(...n.axes.map(l=>t[l]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return n.axes.length>0?(n.axes.forEach(l=>t[l]=i),n.axes.forEach(l=>o[l]=Math.round(e[l]*t[l]))):(t.fill(i,0,t.length),o.forEach((l,u)=>o[u]=Math.round(l*t[u]))),o},dh=(e,t,n,i,o)=>`
|
|
2378
|
+
fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${n.length}> {
|
|
2379
|
+
var original_indices: array<${e.type.value}, ${n.length}>;
|
|
2380
|
+
for (var i:u32 = 0; i < ${n.length}; i++) {
|
|
2381
|
+
var output_index = ${e.indicesGet("output_indices","i")};
|
|
2382
|
+
var scale = ${K("uniforms.scales","i",i)};
|
|
2383
|
+
var roi_low = ${K("uniforms.roi","i",o)};
|
|
2384
|
+
var roi_hi = ${K("uniforms.roi",`i + ${t.length}`,o)};
|
|
2385
|
+
if (scale == 1.0) {
|
|
2386
|
+
original_indices[i] = ${e.type.value}(output_index);
|
|
2387
|
+
} else {
|
|
2388
|
+
var input_shape_i = ${K("uniforms.input_shape","i",t.length)};
|
|
2389
|
+
var output_shape_i = ${K("uniforms.output_shape","i",n.length)};
|
|
2390
|
+
original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
|
|
2391
|
+
input_shape_i, roi_low, roi_hi);
|
|
2392
|
+
}
|
|
2393
|
+
}
|
|
2394
|
+
return original_indices;
|
|
2395
|
+
}`,ch=(e,t,n,i,o,l,u)=>`
|
|
2396
|
+
fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
|
|
2397
|
+
var input_indices: ${e.type.indices};
|
|
2398
|
+
for (var i:u32 = 0; i < ${i.length}; i++) {
|
|
2399
|
+
var output_index = ${t.indicesGet("output_indices","i")};
|
|
2400
|
+
var input_index: u32;
|
|
2401
|
+
var scale = ${K("uniforms.scales","i",o)};
|
|
2402
|
+
if (scale == 1.0) {
|
|
2403
|
+
input_index = output_index;
|
|
2404
|
+
} else {
|
|
2405
|
+
var roi_low = ${K("uniforms.roi","i",l)};
|
|
2406
|
+
var roi_hi = ${K("uniforms.roi",`i + ${n.length}`,l)};
|
|
2407
|
+
var input_shape_i = ${K("uniforms.input_shape","i",n.length)};
|
|
2408
|
+
var output_shape_i = ${K("uniforms.output_shape","i",i.length)};
|
|
2409
|
+
var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
|
|
2410
|
+
input_shape_i, roi_low, roi_hi);
|
|
2411
|
+
if (!${u} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {
|
|
2412
|
+
if (original_idx < 0) {
|
|
2413
|
+
input_index = 0;
|
|
2414
|
+
} else if (original_idx > ${t.type.value}(input_shape_i - 1)) {
|
|
2415
|
+
input_index = input_shape_i - 1;
|
|
2416
|
+
} else {
|
|
2417
|
+
input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));
|
|
2418
|
+
}
|
|
2419
|
+
} else {
|
|
2420
|
+
input_index = u32(original_idx);
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
${e.indicesSet("input_indices","i","input_index")}
|
|
2424
|
+
}
|
|
2425
|
+
return input_indices;
|
|
2426
|
+
}`,hh=(e,t)=>`
|
|
2427
|
+
fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {
|
|
2428
|
+
for (var i:u32 = 0; i < ${t.length}; i++) {
|
|
2429
|
+
var input_index = ${e.indicesGet("input_indices","i")};
|
|
2430
|
+
if (input_index < 0 || input_index >= ${K("uniforms.input_shape","i",t.length)}) {
|
|
2431
|
+
return false;
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
return true;
|
|
2435
|
+
}`,Ba=(e,t,n,i)=>e.rank>i?`
|
|
2436
|
+
${e.indicesSet("input_indices",t,"channel")};
|
|
2437
|
+
${e.indicesSet("input_indices",n,"batch")};
|
|
2438
|
+
`:"",ph=(e,t,n,i,o)=>{let[l,u,c,h]=n.length===2?[-1,0,1,-1]:[0,2,3,1],f=e.type.value;return`
|
|
2439
|
+
fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${f} {
|
|
2440
|
+
var input_indices: ${e.type.indices};
|
|
2441
|
+
${e.indicesSet("input_indices",u,`max(0, min(row, ${n[u]} - 1))`)};
|
|
2442
|
+
${e.indicesSet("input_indices",c,`max(0, min(col, ${n[c]} - 1))`)};
|
|
2443
|
+
${Ba(e,h,l,2)}
|
|
2444
|
+
return ${e.getByIndices("input_indices")};
|
|
2445
|
+
}
|
|
2446
|
+
|
|
2447
|
+
fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${f} {
|
|
2448
|
+
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
|
|
2449
|
+
var row:${f} = originalIndices[${u}];
|
|
2450
|
+
var col:${f} = originalIndices[${c}];
|
|
2451
|
+
${i?`if (row < 0 || row > (${n[u]} - 1) || col < 0 || col > (${n[c]} - 1)) {
|
|
2452
|
+
return ${o};
|
|
2453
|
+
}`:""};
|
|
2454
|
+
row = max(0, min(row, ${n[u]} - 1));
|
|
2455
|
+
col = max(0, min(col, ${n[c]} - 1));
|
|
2456
|
+
var row1: u32 = u32(row);
|
|
2457
|
+
var col1: u32 = u32(col);
|
|
2458
|
+
var row2: u32 = u32(row + 1);
|
|
2459
|
+
var col2: u32 = u32(col + 1);
|
|
2460
|
+
var channel: u32 = ${n.length>2?`u32(originalIndices[${h}])`:"0"};
|
|
2461
|
+
var batch: u32 = ${n.length>2?`u32(originalIndices[${l}])`:"0"};
|
|
2462
|
+
var x11: ${f} = getInputValue(batch, channel, row1, col1);
|
|
2463
|
+
var x12: ${f} = getInputValue(batch, channel, row1, col2);
|
|
2464
|
+
var x21: ${f} = getInputValue(batch, channel, row2, col1);
|
|
2465
|
+
var x22: ${f} = getInputValue(batch, channel, row2, col2);
|
|
2466
|
+
var dx1: ${f} = abs(row - ${f}(row1));
|
|
2467
|
+
var dx2: ${f} = abs(${f}(row2) - row);
|
|
2468
|
+
var dy1: ${f} = abs(col - ${f}(col1));
|
|
2469
|
+
var dy2: ${f} = abs(${f}(col2) - col);
|
|
2470
|
+
if (row1 == row2) {
|
|
2471
|
+
dx1 = 0.5;
|
|
2472
|
+
dx2 = 0.5;
|
|
2473
|
+
}
|
|
2474
|
+
if (col1 == col2) {
|
|
2475
|
+
dy1 = 0.5;
|
|
2476
|
+
dy2 = 0.5;
|
|
2477
|
+
}
|
|
2478
|
+
return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);
|
|
2479
|
+
}`},fh=(e,t,n,i,o,l,u,c,h,f)=>{let m=n.length===2,[g,w]=m?[0,1]:[2,3],_=e.type.value,b=x=>{let M=x===g?"row":"col";return`
|
|
2480
|
+
fn ${M}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${_} {
|
|
2481
|
+
var output_index = ${t.indicesGet("output_indices",x)};
|
|
2482
|
+
var originalIdx: ${_} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[x]},
|
|
2483
|
+
${i[x]}, ${n[x]}, ${l[x]}, ${l[x]} + ${n.length});
|
|
2484
|
+
var fractOriginalIdx: ${_} = originalIdx - floor(originalIdx);
|
|
2485
|
+
var coefs = getCubicInterpolationCoefs(fractOriginalIdx);
|
|
2486
|
+
|
|
2487
|
+
if (${c} && (originalIdx < 0 || originalIdx > (${n[x]} - 1))) {
|
|
2488
|
+
return ${h};
|
|
2489
|
+
}
|
|
2490
|
+
var data: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0);
|
|
2491
|
+
for (var i: i32 = -1; i < 3; i++) {
|
|
2492
|
+
var ${M}: ${_} = originalIdx + ${_}(i);
|
|
2493
|
+
if (${M} < 0 || ${M} >= ${n[x]}) {
|
|
2494
|
+
${f?`coefs[i + 1] = 0.0;
|
|
2495
|
+
continue;`:c?`return ${h};`:`${M} = max(0, min(${M}, ${n[x]} - 1));`};
|
|
2496
|
+
}
|
|
2497
|
+
var input_indices_copy: ${e.type.indices} = input_indices;
|
|
2498
|
+
${e.indicesSet("input_indices_copy",x,`u32(${M})`)};
|
|
2499
|
+
data[i + 1] = ${x===g?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};
|
|
2500
|
+
}
|
|
2501
|
+
return cubicInterpolation1D(data, coefs);
|
|
2502
|
+
}`};return`
|
|
2503
|
+
${b(g)};
|
|
2504
|
+
${b(w)};
|
|
2505
|
+
fn getCubicInterpolationCoefs(s: ${_}) -> array<${_}, 4> {
|
|
2506
|
+
var absS = abs(s);
|
|
2507
|
+
var coeffs: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0);
|
|
2508
|
+
var oneMinusAbsS: ${_} = 1.0 - absS;
|
|
2509
|
+
var twoMinusAbsS: ${_} = 2.0 - absS;
|
|
2510
|
+
var onePlusAbsS: ${_} = 1.0 + absS;
|
|
2511
|
+
coeffs[0] = ((${u} * onePlusAbsS - 5 * ${u}) * onePlusAbsS + 8 * ${u}) * onePlusAbsS - 4 * ${u};
|
|
2512
|
+
coeffs[1] = ((${u} + 2) * absS - (${u} + 3)) * absS * absS + 1;
|
|
2513
|
+
coeffs[2] = ((${u} + 2) * oneMinusAbsS - (${u} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;
|
|
2514
|
+
coeffs[3] = ((${u} * twoMinusAbsS - 5 * ${u}) * twoMinusAbsS + 8 * ${u}) * twoMinusAbsS - 4 * ${u};
|
|
2515
|
+
return coeffs;
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2518
|
+
fn cubicInterpolation1D(x: array<${_}, 4>, coefs: array<${_}, 4>) -> ${_} {
|
|
2519
|
+
var coefsSum: ${_} = coefs[0] + coefs[1] + coefs[2] + coefs[3];
|
|
2520
|
+
return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${_} {
|
|
2524
|
+
var input_indices: ${e.type.indices} = output_indices;
|
|
2525
|
+
return colCubicInterpolation(input_indices, output_indices);
|
|
2526
|
+
}
|
|
2527
|
+
`},mh=(e,t,n,i,o)=>{let[l,u,c,h,f]=n.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],m=e.type.value;return`
|
|
2528
|
+
fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${m} {
|
|
2529
|
+
var input_indices: ${e.type.indices};
|
|
2530
|
+
${e.indicesSet("input_indices",u,`max(0, min(depth, ${n[u]} - 1))`)};
|
|
2531
|
+
${e.indicesSet("input_indices",c,`max(0, min(height, ${n[c]} - 1))`)};
|
|
2532
|
+
${e.indicesSet("input_indices",h,`max(0, min(width, ${n[h]} - 1))`)};
|
|
2533
|
+
${Ba(e,f,l,3)}
|
|
2534
|
+
return ${e.getByIndices("input_indices")};
|
|
2535
|
+
}
|
|
2536
|
+
|
|
2537
|
+
fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} {
|
|
2538
|
+
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
|
|
2539
|
+
var depth:${m} = originalIndices[${u}];
|
|
2540
|
+
var height:${m} = originalIndices[${c}];
|
|
2541
|
+
var width:${m} = originalIndices[${h}];
|
|
2542
|
+
${i?`if (depth < 0 || depth > (${n[u]} - 1) || height < 0 || height > (${n[c]} - 1) || width < 0 || (width > ${n[h]} - 1)) {
|
|
2543
|
+
return ${o};
|
|
2544
|
+
}`:""};
|
|
2545
|
+
|
|
2546
|
+
depth = max(0, min(depth, ${n[u]} - 1));
|
|
2547
|
+
height = max(0, min(height, ${n[c]} - 1));
|
|
2548
|
+
width = max(0, min(width, ${n[h]} - 1));
|
|
2549
|
+
var depth1: u32 = u32(depth);
|
|
2550
|
+
var height1: u32 = u32(height);
|
|
2551
|
+
var width1: u32 = u32(width);
|
|
2552
|
+
var depth2: u32 = u32(depth + 1);
|
|
2553
|
+
var height2: u32 = u32(height + 1);
|
|
2554
|
+
var width2: u32 = u32(width + 1);
|
|
2555
|
+
var channel: u32 = ${n.length>3?`u32(originalIndices[${f}])`:"0"};
|
|
2556
|
+
var batch: u32 = ${n.length>3?`u32(originalIndices[${l}])`:"0"};
|
|
2557
|
+
|
|
2558
|
+
var x111: ${m} = getInputValue(batch, channel, depth1, height1, width1);
|
|
2559
|
+
var x112: ${m} = getInputValue(batch, channel, depth1, height1, width2);
|
|
2560
|
+
var x121: ${m} = getInputValue(batch, channel, depth1, height2, width1);
|
|
2561
|
+
var x122: ${m} = getInputValue(batch, channel, depth1, height2, width2);
|
|
2562
|
+
var x211: ${m} = getInputValue(batch, channel, depth2, height1, width1);
|
|
2563
|
+
var x212: ${m} = getInputValue(batch, channel, depth2, height1, width2);
|
|
2564
|
+
var x221: ${m} = getInputValue(batch, channel, depth2, height2, width1);
|
|
2565
|
+
var x222: ${m} = getInputValue(batch, channel, depth2, height2, width2);
|
|
2566
|
+
var dx1: ${m} = abs(depth - ${m}(depth1));
|
|
2567
|
+
var dx2: ${m} = abs(${m}(depth2) - depth);
|
|
2568
|
+
var dy1: ${m} = abs(height - ${m}(height1));
|
|
2569
|
+
var dy2: ${m} = abs(${m}(height2) - height);
|
|
2570
|
+
var dz1: ${m} = abs(width - ${m}(width1));
|
|
2571
|
+
var dz2: ${m} = abs(${m}(width2) - width);
|
|
2572
|
+
if (depth1 == depth2) {
|
|
2573
|
+
dx1 = 0.5;
|
|
2574
|
+
dx2 = 0.5;
|
|
2575
|
+
}
|
|
2576
|
+
if (height1 == height2) {
|
|
2577
|
+
dy1 = 0.5;
|
|
2578
|
+
dy2 = 0.5;
|
|
2579
|
+
}
|
|
2580
|
+
if (width1 == width2) {
|
|
2581
|
+
dz1 = 0.5;
|
|
2582
|
+
dz2 = 0.5;
|
|
2583
|
+
}
|
|
2584
|
+
return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +
|
|
2585
|
+
x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);
|
|
2586
|
+
}`},gh=(e,t,n,i,o,l)=>{let u=e.dims,c=oh(l,t.axes,u.length),h=lh(u,i,o,t.axes),f=i.slice();i.length===0&&(f=u.map(($,O)=>$===0?1:h[O]/$),t.keepAspectRatioPolicy!=="stretch"&&(h=uh(u,f,t)));let m=de("output",e.dataType,h.length),g=U("input",e.dataType,u.length),w=j.size(h),_=u.length===h.length&&u.every(($,O)=>$===h[O]),b=t.coordinateTransformMode==="tf_crop_and_resize",x=t.extrapolationValue,M=g.type.value,k=$=>`
|
|
2587
|
+
${_?"":`
|
|
2588
|
+
${ih(t.coordinateTransformMode,M)};
|
|
2589
|
+
${(()=>{switch(t.mode){case"nearest":return`
|
|
2590
|
+
${hh(g,u)};
|
|
2591
|
+
${ah(t.nearestMode,n,M)};
|
|
2592
|
+
${ch(g,m,u,h,f.length,c.length,b)};
|
|
2593
|
+
`;case"linear":return`
|
|
2594
|
+
${dh(m,u,h,f.length,c.length)};
|
|
2595
|
+
${(()=>{if(u.length===2||u.length===4)return`${ph(g,m,u,b,x)}`;if(u.length===3||u.length===5)return`${mh(g,m,u,b,x)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};
|
|
2596
|
+
`;case"cubic":return`
|
|
2597
|
+
${(()=>{if(u.length===2||u.length===4)return`${fh(g,m,u,h,f,c,t.cubicCoeffA,b,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};
|
|
2598
|
+
`;default:throw Error("Invalid resize mode")}})()};
|
|
2599
|
+
`}
|
|
2600
|
+
${$.registerUniform("output_size","u32").registerUniform("scales","f32",f.length).registerUniform("roi","f32",c.length).declareVariables(g,m)}
|
|
2601
|
+
${$.mainStart()}
|
|
2602
|
+
${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2603
|
+
${_?"output[global_idx] = input[global_idx];":`
|
|
2604
|
+
let output_indices = ${m.offsetToIndices("global_idx")};
|
|
2605
|
+
var input_indices: ${g.type.indices};
|
|
2606
|
+
${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);
|
|
2607
|
+
if (checkInputIndices(input_indices)) {
|
|
2608
|
+
output[global_idx] = ${g.getByIndices("input_indices")};
|
|
2609
|
+
} else {
|
|
2610
|
+
output[global_idx] = ${t.extrapolationValue};
|
|
2611
|
+
}`;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}`)}})()};
|
|
2612
|
+
`}
|
|
2613
|
+
}`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${f.length>0?t.mode==="cubic"?f:f.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:f},{type:1,data:c},...L(u,h)]})}},yh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},wh=(e,t)=>{let n=[],i=[],o=[],l=yh(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");nh(e.inputs,t,l,n,i,o),e.compute(gh(e.inputs[0],t,l,n,i,o),{inputs:[0]})},vh=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,f=e.nearestMode===""?"simple":e.nearestMode;return E({antialias:t,axes:n,coordinateTransformMode:i,cubicCoeffA:o,excludeOutside:l,extrapolationValue:u,keepAspectRatioPolicy:c,mode:h,nearestMode:f})}}),_h,bh,Sh,tg=S(()=>{Ie(),ke(),we(),_h=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")}},bh=(e,t,n,i)=>{let o=t.simplified,l=e[0].dims,u=j.size(l),c=l,h=u,f=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(f),$=[{type:12,data:h},{type:12,data:k},{type:12,data:f},{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"}],W=[U("x",e[0].dataType,e[0].dims,k),U("skip",e[1].dataType,e[1].dims,k),U("gamma",e[2].dataType,e[2].dims,k)];g&&W.push(U("beta",e[3].dataType,e[3].dims,k)),w&&W.push(U("bias",e[4].dataType,e[4].dims,k)),W.push(de("output",e[0].dataType,c,k)),_&&W.push(de("mean_output",1,m)),b&&W.push(de("inv_std_output",1,m)),x&&W.push(de("input_skip_bias_sum",e[0].dataType,c,k));let te=G(e[0].dataType),fe=G(1,k);return`
|
|
2614
|
+
|
|
2615
|
+
${B.registerUniforms(q).declareVariables(...W)}
|
|
2616
|
+
var<workgroup> sum_shared : array<${fe}, ${M}>;
|
|
2617
|
+
var<workgroup> sum_squared_shared : array<${fe}, ${M}>;
|
|
2618
|
+
|
|
2619
|
+
${B.mainStart([M,1,1])}
|
|
2620
|
+
let ix = local_id.x;
|
|
2621
|
+
let iy = global_id.x / ${M};
|
|
2622
|
+
|
|
2623
|
+
let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;
|
|
2624
|
+
var stride = hidden_size_vectorized / ${M};
|
|
2625
|
+
let offset = ix * stride + iy * hidden_size_vectorized;
|
|
2626
|
+
let offset1d = stride * ix;
|
|
2627
|
+
if (ix == ${M-1}) {
|
|
2628
|
+
stride = hidden_size_vectorized - stride * ix;
|
|
2629
|
+
}
|
|
2630
|
+
for (var i: u32 = 0; i < stride; i++) {
|
|
2631
|
+
let skip_value = skip[offset + i];
|
|
2632
|
+
let bias_value = ${w?"bias[offset1d + i]":te+"(0.0)"};
|
|
2633
|
+
let input_value = x[offset + i];
|
|
2634
|
+
let value = input_value + skip_value + bias_value;
|
|
2635
|
+
${x?"input_skip_bias_sum[offset + i] = value;":""}
|
|
2636
|
+
output[offset + i] = value;
|
|
2637
|
+
let f32_value = ${oe(te,k,"value")};
|
|
2638
|
+
sum_shared[ix] += f32_value;
|
|
2639
|
+
sum_squared_shared[ix] += f32_value * f32_value;
|
|
2640
|
+
}
|
|
2641
|
+
workgroupBarrier();
|
|
2642
|
+
|
|
2643
|
+
var reduce_size : u32 = ${M};
|
|
2644
|
+
for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {
|
|
2645
|
+
reduce_size = curr_size + (reduce_size & 1);
|
|
2646
|
+
if (ix < curr_size) {
|
|
2647
|
+
sum_shared[ix] += sum_shared[ix + reduce_size];
|
|
2648
|
+
sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];
|
|
2649
|
+
}
|
|
2650
|
+
workgroupBarrier();
|
|
2651
|
+
}
|
|
2652
|
+
|
|
2653
|
+
let sum = sum_shared[0];
|
|
2654
|
+
let square_sum = sum_squared_shared[0];
|
|
2655
|
+
let mean = ${Y("sum",k)} / f32(uniforms.hidden_size);
|
|
2656
|
+
let inv_std_dev = inverseSqrt(${Y("square_sum",k)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon);
|
|
2657
|
+
${_?"mean_output[global_idx] = mean;":""}
|
|
2658
|
+
${b?"inv_std_output[global_idx] = inv_std_dev;":""}
|
|
2659
|
+
|
|
2660
|
+
for (var i: u32 = 0; i < stride; i++) {
|
|
2661
|
+
output[offset + i] = (output[offset + i] ${o?"":`- ${te}(mean)`}) *
|
|
2662
|
+
${te}(inv_std_dev) * gamma[offset1d + i]
|
|
2663
|
+
${g?"+ beta[offset1d + i]":""};
|
|
2664
|
+
}
|
|
2665
|
+
}`},I=[{dims:c,dataType:e[0].dataType}];return n>1&&I.push({dims:m,dataType:1}),n>2&&I.push({dims:m,dataType:1}),n>3&&I.push({dims:l,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${k};${_};${b};${x}`,inputDependencies:e.map((B,q)=>"type")},getShaderSource:O,getRunData:()=>({outputs:I,dispatchGroup:{x:Math.ceil(h/f)},programUniforms:$})}},Sh=(e,t)=>{_h(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(bh(e.inputs,t,e.outputCount,!1),{outputs:n})}}),Th,Xn,Eh,Na,$h,xh,Ch,kh,rg=S(()=>{Ie(),ke(),A(),we(),Th=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((n,i)=>{if(e[i+1].dataType!==6&&e[i+1].dataType!==7)throw new Error(`Input ${i} must be an array of int32 or int64`)})},Xn=(e,t)=>{let n=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(i=>n.push(Number(i)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(i=>n.push(Number(i)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return n},Eh=(e,t)=>{if(e.length>1){let n=Xn(e,1),i=Xn(e,2),o=Xn(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),E({starts:n,ends:i,axes:o})}else return t},Na=(e,t,n,i,o)=>{let l=e;return e<0&&(l+=n[i[t]]),o[t]<0?Math.max(0,Math.min(l,n[i[t]]-1)):Math.max(0,Math.min(l,n[i[t]]))},$h=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
|
|
2666
|
+
var input_indices: ${e.type.indices};
|
|
2667
|
+
var carry = 0u;
|
|
2668
|
+
for (var i = ${n.length-1}; i >= 0; i--) {
|
|
2669
|
+
let input_shape_i = ${K("uniforms.input_shape","i",n.length)};
|
|
2670
|
+
let steps_i = ${K("uniforms.steps","i",n.length)};
|
|
2671
|
+
let signs_i = ${K("uniforms.signs","i",n.length)};
|
|
2672
|
+
let starts_i = ${K("uniforms.starts","i",n.length)};
|
|
2673
|
+
var output_index = ${t.indicesGet("output_indices","i")};
|
|
2674
|
+
var input_index = output_index * steps_i + starts_i + carry;
|
|
2675
|
+
carry = input_index / input_shape_i;
|
|
2676
|
+
input_index = input_index % input_shape_i;
|
|
2677
|
+
if (signs_i < 0) {
|
|
2678
|
+
input_index = input_shape_i - input_index - 1u + starts_i;
|
|
2679
|
+
}
|
|
2680
|
+
${e.indicesSet("input_indices","i","input_index")};
|
|
2681
|
+
}
|
|
2682
|
+
return input_indices;
|
|
2683
|
+
}`,xh=(e,t)=>{let n=e[0].dims,i=j.size(n),o=t.axes.length>0?j.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],l=Xn(e,4);l.forEach(k=>k!==0||(()=>{throw new Error("step cannot be 0")})),l.length===0&&(l=Array(o.length).fill(1));let u=t.starts.map((k,$)=>Na(k,$,n,o,l)),c=t.ends.map((k,$)=>Na(k,$,n,o,l));if(o.length!==u.length||o.length!==c.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==n.length)for(let k=0;k<n.length;++k)o.includes(k)||(u.splice(k,0,0),c.splice(k,0,n[k]),l.splice(k,0,1));let h=l.map(k=>Math.sign(k));l.forEach((k,$,O)=>{if(k<0){let I=(c[$]-u[$])/k,B=u[$],q=B+I*l[$];u[$]=q,c[$]=B,O[$]=-k}});let f=n.slice(0);o.forEach((k,$)=>{f[k]=Math.ceil((c[k]-u[k])/l[k])});let m={dims:f,dataType:e[0].dataType},g=de("output",e[0].dataType,f.length),w=U("input",e[0].dataType,e[0].dims.length),_=j.size(f),b=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:u.length},{name:"signs",type:"i32",length:h.length},{name:"steps",type:"u32",length:l.length}],x=[{type:12,data:_},{type:12,data:u},{type:6,data:h},{type:12,data:l},...L(e[0].dims,f)],M=k=>`
|
|
2684
|
+
${k.registerUniforms(b).declareVariables(w,g)}
|
|
2685
|
+
${$h(w,g,n)}
|
|
2686
|
+
${k.mainStart()}
|
|
2687
|
+
${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2688
|
+
let output_indices = ${g.offsetToIndices("global_idx")};
|
|
2689
|
+
let input_indices = calculateInputIndices(output_indices);
|
|
2690
|
+
${g.setByOffset("global_idx",w.getByIndices("input_indices"))}
|
|
2691
|
+
}`;return{name:"Slice",shaderCache:{hint:`${h.length}_${u.length}_${l.length}`,inputDependencies:["rank"]},getShaderSource:M,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:x})}},Ch=(e,t)=>{Th(e.inputs,t);let n=Eh(e.inputs,t);e.compute(xh(e.inputs,n),{inputs:[0]})},kh=e=>{let t=e.starts,n=e.ends,i=e.axes;return E({starts:t,ends:n,axes:i})}}),Rh,Ah,Ih,Mh,sg=S(()=>{Ie(),ke(),A(),Ge(),we(),Rh=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Ah=(e,t)=>{let n=e.inputs[0],i=n.dims,o=j.size(i),l=i.length,u=j.normalizeAxis(t.axis,l),c=u<i.length-1,h,f=[];c?(f=Array.from({length:l},(W,te)=>te),f[u]=l-1,f[l-1]=u,h=e.compute(_t(n,f),{inputs:[n],outputs:[-1]})[0]):h=n;let m=h.dims,g=m[l-1],w=o/g,_=V(g),b=g/_,x=64;w===1&&(x=256);let M=(W,te)=>te===4?`max(max(${W}.x, ${W}.y), max(${W}.z, ${W}.w))`:te===2?`max(${W}.x, ${W}.y)`:te===3?`max(max(${W}.x, ${W}.y), ${W}.z)`:W,k=U("x",h.dataType,h.dims,_),$=de("result",h.dataType,h.dims,_),O=k.type.value,I=G(h.dataType)==="f32"?`var threadMax = ${O}(-3.4028234663852886e+38f);`:`var threadMax = ${O}(-65504.0h);`,B=W=>`
|
|
2692
|
+
var<workgroup> rowMaxShared : ${O};
|
|
2693
|
+
var<workgroup> rowSumShared : ${O};
|
|
2694
|
+
var<workgroup> threadShared : array<${O}, ${x}>;
|
|
2695
|
+
|
|
2696
|
+
fn getValue(row: i32, col: i32, row_stride: i32) -> ${O} {
|
|
2697
|
+
let index = row * row_stride + col;
|
|
2698
|
+
return x[index];
|
|
2699
|
+
}
|
|
2700
|
+
|
|
2701
|
+
fn setValue(row: i32, col: i32, row_stride: i32, value: ${O}) {
|
|
2702
|
+
let index = row * row_stride + col;
|
|
2703
|
+
result[index] = value;
|
|
2704
|
+
}
|
|
2705
|
+
${W.registerUniform("packedCols","i32").declareVariables(k,$)}
|
|
2706
|
+
${W.mainStart(x)}
|
|
2707
|
+
let gindex = i32(global_idx);
|
|
2708
|
+
let lindex = i32(local_idx);
|
|
2709
|
+
const wg = ${x};
|
|
2710
|
+
let row = gindex / wg;
|
|
2711
|
+
let cols = uniforms.packedCols;
|
|
2712
|
+
let row_stride : i32 = uniforms.packedCols;
|
|
2713
|
+
|
|
2714
|
+
// find the rows max
|
|
2715
|
+
${I}
|
|
2716
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2717
|
+
let value = getValue(row, col, row_stride);
|
|
2718
|
+
threadMax = max(threadMax, value);
|
|
2719
|
+
}
|
|
2720
|
+
if (lindex < cols) {
|
|
2721
|
+
threadShared[lindex] = threadMax;
|
|
2722
|
+
}
|
|
2723
|
+
workgroupBarrier();
|
|
2724
|
+
|
|
2725
|
+
var reduceSize = min(cols, wg);
|
|
2726
|
+
for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {
|
|
2727
|
+
reduceSize = currSize + (reduceSize & 1);
|
|
2728
|
+
if (lindex < currSize) {
|
|
2729
|
+
threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);
|
|
2730
|
+
}
|
|
2731
|
+
workgroupBarrier();
|
|
2732
|
+
}
|
|
2733
|
+
if (lindex == 0) {
|
|
2734
|
+
rowMaxShared = ${O}(${M("threadShared[0]",_)});
|
|
2735
|
+
}
|
|
2736
|
+
workgroupBarrier();
|
|
2737
|
+
|
|
2738
|
+
// find the rows sum
|
|
2739
|
+
var threadSum = ${O}(0.0);
|
|
2740
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2741
|
+
let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);
|
|
2742
|
+
threadSum += subExp;
|
|
2743
|
+
}
|
|
2744
|
+
threadShared[lindex] = threadSum;
|
|
2745
|
+
workgroupBarrier();
|
|
2746
|
+
|
|
2747
|
+
for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {
|
|
2748
|
+
if (lindex < currSize) {
|
|
2749
|
+
threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];
|
|
2750
|
+
}
|
|
2751
|
+
workgroupBarrier();
|
|
2752
|
+
}
|
|
2753
|
+
if (lindex == 0) {
|
|
2754
|
+
rowSumShared = ${O}(${Y("threadShared[0]",_)});
|
|
2755
|
+
}
|
|
2756
|
+
workgroupBarrier();
|
|
2757
|
+
|
|
2758
|
+
// calculate final value for each element in the row
|
|
2759
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2760
|
+
var value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;
|
|
2761
|
+
// max operation protects against NaN since all values should be >=0
|
|
2762
|
+
value = max(value, ${O}(0.0));
|
|
2763
|
+
setValue(row, col, row_stride, value);
|
|
2764
|
+
}
|
|
2765
|
+
}`,q=e.compute({name:"Softmax",shaderCache:{hint:`${_};${x}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:m,dataType:h.dataType}],dispatchGroup:{x:w},programUniforms:[{type:6,data:b}]}),getShaderSource:B},{inputs:[h],outputs:[c?-1:0]})[0];c&&e.compute(_t(q,f),{inputs:[q]})},Ih=(e,t)=>{Rh(e.inputs),Ah(e,t)},Mh=e=>E({axis:e.axis})}),Ua,Oh,Ph,Dh,zh,ng=S(()=>{Ie(),ke(),we(),Ua=e=>Array.from(e.getBigInt64Array(),Number),Oh=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Ua(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Ph=(e,t)=>{let n=[];for(let i=0;i<e.length;++i)n.push(e[i]*t[i]);return n},Dh=(e,t)=>{let n=e[0].dims,i=t??Ua(e[1]),o=Ph(n,i),l=j.size(o),u=e[0].dataType,c=U("input",u,n.length),h=de("output",u,o.length),f=m=>`
|
|
2766
|
+
const inputShape = ${c.indices(...n)};
|
|
2767
|
+
${m.registerUniform("output_size","u32").declareVariables(c,h)}
|
|
2768
|
+
${m.mainStart()}
|
|
2769
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2770
|
+
let output_indices = ${h.offsetToIndices("global_idx")};
|
|
2771
|
+
var input_indices: ${c.type.indices};
|
|
2772
|
+
for (var i = 0; i < ${n.length}; i++) {
|
|
2773
|
+
let input_dim_i = ${c.indicesGet("uniforms.input_shape","i")};
|
|
2774
|
+
let input_dim_value = ${h.indicesGet("output_indices","i")} % input_dim_i;
|
|
2775
|
+
|
|
2776
|
+
${c.indicesSet("input_indices","i","input_dim_value")}
|
|
2777
|
+
}
|
|
2778
|
+
${h.setByOffset("global_idx",c.getByIndices("input_indices"))}
|
|
2779
|
+
}`;return{name:"Tile",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},...L(e[0].dims,o)]}),getShaderSource:f}},zh=e=>{Oh(e.inputs),e.compute(Dh(e.inputs),{inputs:[0]})}}),Lh,Bh,Nh,ig=S(()=>{Ie(),ke(),we(),Lh=(e,t,n,i,o)=>{let l=de("output_data",o,n.length,4),u=U("a_data",t[1].dataType,t[1].dims.length,4),c=U("b_data",t[2].dataType,t[2].dims.length,4),h=U("c_data",t[0].dataType,t[0].dims.length,4),f,m=(g,w,_)=>`select(${w}, ${g}, ${_})`;if(!i)f=l.setByOffset("global_idx",m(u.getByOffset("global_idx"),c.getByOffset("global_idx"),h.getByOffset("global_idx")));else{let g=(w,_,b="")=>{let x=`a_data[index_a${_}][component_a${_}]`,M=`b_data[index_b${_}][component_b${_}]`,k=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return`
|
|
2780
|
+
let output_indices${_} = ${l.offsetToIndices(`global_idx * 4u + ${_}u`)};
|
|
2781
|
+
let offset_a${_} = ${u.broadcastedIndicesToOffset(`output_indices${_}`,l)};
|
|
2782
|
+
let offset_b${_} = ${c.broadcastedIndicesToOffset(`output_indices${_}`,l)};
|
|
2783
|
+
let offset_c${_} = ${h.broadcastedIndicesToOffset(`output_indices${_}`,l)};
|
|
2784
|
+
let index_a${_} = offset_a${_} / 4u;
|
|
2785
|
+
let index_b${_} = offset_b${_} / 4u;
|
|
2786
|
+
let index_c${_} = offset_c${_} / 4u;
|
|
2787
|
+
let component_a${_} = offset_a${_} % 4u;
|
|
2788
|
+
let component_b${_} = offset_b${_} % 4u;
|
|
2789
|
+
let component_c${_} = offset_c${_} % 4u;
|
|
2790
|
+
${w}[${_}] = ${b}(${m(x,M,k)});
|
|
2791
|
+
`};o===9?f=`
|
|
2792
|
+
var data = vec4<u32>(0);
|
|
2793
|
+
${g("data",0,"u32")}
|
|
2794
|
+
${g("data",1,"u32")}
|
|
2795
|
+
${g("data",2,"u32")}
|
|
2796
|
+
${g("data",3,"u32")}
|
|
2797
|
+
output_data[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:f=`
|
|
2798
|
+
${g("output_data[global_idx]",0)}
|
|
2799
|
+
${g("output_data[global_idx]",1)}
|
|
2800
|
+
${g("output_data[global_idx]",2)}
|
|
2801
|
+
${g("output_data[global_idx]",3)}
|
|
2802
|
+
`}return`
|
|
2803
|
+
${e.registerUniform("vec_size","u32").declareVariables(h,u,c,l)}
|
|
2804
|
+
${e.mainStart()}
|
|
2805
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
2806
|
+
${f}
|
|
2807
|
+
}`},Bh=e=>{let t=e[1].dims,n=e[2].dims,i=e[0].dims,o=e[1].dataType,l=!(j.areEqual(t,n)&&j.areEqual(n,i)),u=t,c=j.size(t);if(l){let f=Pr.calcShape(Pr.calcShape(t,n,!1),i,!1);if(!f)throw new Error("Can't perform where op on the given tensors");u=f,c=j.size(u)}let h=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:f=>Lh(f,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)]})}},Nh=e=>{e.compute(Bh(e.inputs))}}),Uh,ag=S(()=>{_m(),ra(),bm(),Sm(),Tm(),Em(),$m(),Am(),Mm(),Om(),Pm(),Dm(),zm(),Lm(),Bm(),Nm(),Um(),Fm(),Vm(),Gm(),qm(),Wm(),Hm(),jm(),Km(),Jd(),Qm(),Xm(),Ym(),Jm(),Zm(),Zi(),eg(),lc(),tg(),rg(),sg(),ic(),ng(),Ge(),aa(),ig(),Uh=new Map([["Abs",[_l]],["Acos",[bl]],["Acosh",[Sl]],["Add",[uu]],["ArgMax",[il,ta]],["ArgMin",[nl,ta]],["Asin",[Tl]],["Asinh",[El]],["Atan",[$l]],["Atanh",[xl]],["Attention",[cl]],["AveragePool",[Bc,Lc]],["BatchNormalization",[ml]],["BiasAdd",[wl]],["BiasSplitGelu",[au]],["Cast",[kl,Cl]],["Ceil",[Il]],["Clip",[Al]],["Concat",[Tu,Eu]],["Conv",[va,ya]],["ConvTranspose",[Yu,Ku]],["Cos",[Ml]],["Cosh",[Ol]],["CumSum",[Zu,ed]],["DepthToSpace",[nd,id]],["DequantizeLinear",[jc,Kc]],["Div",[du]],["Einsum",[cd,hd]],["Elu",[Pl,qn]],["Equal",[cu]],["Erf",[Dl]],["Exp",[zl]],["Expand",[gd]],["FastGelu",[wd]],["Floor",[Ll]],["FusedConv",[va,ya]],["Gather",[Sd,bd]],["GatherElements",[Od,Md]],["GatherBlockQuantized",[kd,Rd]],["GatherND",[Ed,$d]],["Gelu",[Bl]],["Gemm",[Ld,zd]],["GlobalAveragePool",[Uc,Nc]],["GlobalMaxPool",[qc,Gc]],["Greater",[mu]],["GreaterOrEqual",[yu]],["GridSample",[Hd,jd]],["GroupQueryAttention",[hc]],["HardSigmoid",[Hl,Wl]],["InstanceNormalization",[mc]],["LayerNormalization",[wc]],["LeakyRelu",[Nl,qn]],["Less",[gu]],["LessOrEqual",[wu]],["Log",[eu]],["MatMul",[_c]],["MatMulNBits",[Ec,$c]],["MaxPool",[Fc,Vc]],["Mul",[hu]],["MultiHeadAttention",[Yd,Qd]],["Neg",[Fl]],["Not",[Ul]],["Pad",[Pc]],["Pow",[pu]],["QuickGelu",[su,qn]],["Range",[Yc]],["Reciprocal",[Vl]],["ReduceMin",[Zo]],["ReduceMean",[Ko]],["ReduceMax",[Jo]],["ReduceSum",[tl]],["ReduceProd",[el]],["ReduceL1",[Qo]],["ReduceL2",[Xo]],["ReduceLogSum",[sl]],["ReduceLogSumExp",[Yo]],["ReduceSumSquare",[rl]],["Relu",[Gl]],["Resize",[wh,vh]],["RotaryEmbedding",[oc]],["ScatterND",[th,eh]],["Sigmoid",[ql]],["Sin",[jl]],["Sinh",[Kl]],["Slice",[Ch,kh]],["SkipLayerNormalization",[Sh]],["Split",[sc,nc]],["Sqrt",[Ql]],["Softmax",[Ih,Mh]],["Sub",[fu]],["Tan",[Xl]],["Tanh",[Yl]],["ThresholdedRelu",[Zl,qn]],["Tile",[zh]],["Transpose",[fr,Fn]],["Where",[Nh]]])}),Fh,og=S(()=>{ut(),hr(),we(),Fh=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){ct(e.programInfo.name);let l=this.backend.device,u=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let c=[];for(let f of t)c.push({binding:c.length,resource:{buffer:f.buffer}});for(let f of n)c.push({binding:c.length,resource:{buffer:f.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 f={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:h,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(f)}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(),Tt(e.programInfo.name)}dispose(){}build(e,t){ct(e.name);let n=this.backend.device,i=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(f=>{n.features.has(f.feature)&&i.push(`enable ${f.extension};`)});let o=Fe(t,this.backend.device.limits),l=e.getShaderSource(o),u=`${i.join(`
|
|
2808
|
+
`)}
|
|
2809
|
+
${o.additionalImplementations}
|
|
2810
|
+
${l}`,c=n.createShaderModule({code:u,label:e.name});Qe("verbose",()=>`[WebGPU] ${e.name} shader code: ${u}`);let h=n.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:e.name});return Tt(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]}}}),Vh={};F(Vh,{WebGpuBackend:()=>Hh});var Gh,qh,Wh,Hh,lg=S(()=>{ut(),Ie(),hr(),es(),Yi(),ag(),og(),Gh=(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("|")},qh=(e,t,n)=>{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+n+`:${Gh(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},Wh=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Hh=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 Wh(t.info||await t.requestAdapterInfo()),this.gpuDataManager=gi(this),this.programManager=new Fh(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ws(e.logLevel,!!e.debug),this.device.onuncapturederror=l=>{l.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${l.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&this.env?.webgpu&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;ct(),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,f=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:ar(M.dataType)})),outputsMetadata:g.map(M=>({dims:M.dims,dataType:ar(M.dataType)})),kernelId:l,kernelType:c,kernelName:h,programName:f,startTime:b,endTime:x});else{let M="";m.forEach(($,O)=>{M+=`input[${O}]: [${$.dims}] | ${ar($.dataType)}, `});let k="";g.forEach(($,O)=>{k+=`output[${O}]: [${$.dims}] | ${ar($.dataType)}, `}),console.log(`[profiling] kernel "${l}|${c}|${h}|${f}" ${M}${k}start time: ${b} ns, execution time: ${x-b} ns`)}qt("GPU",`${f}::${w}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),Tt()}run(e,t,n,i,o,l){ct(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:f}=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 W=this.kernelPersistentData.get(this.currentKernelId);W||(W=[],this.kernelPersistentData.set(this.currentKernelId,W)),W.push(q)}w.push(q)}if(u.length!==t.length||w.length!==g.length){if(w.length===0)return Tt(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(f){let $=0,O=[];f.forEach(W=>{let te=typeof W.data=="number"?[W.data]:W.data;if(te.length===0)return;let fe=W.type===10?2:4,be,qe;W.type===10?(qe=te.length>4?16:te.length>2?8:te.length*fe,be=te.length>4?16:fe*te.length):(qe=te.length<=2?te.length*fe:16,be=16),$=Math.ceil($/qe)*qe,O.push($);let Re=W.type===10?8:4;$+=te.length>4?Math.ceil(te.length/Re)*be:te.length*fe});let I=16;$=Math.ceil($/I)*I;let B=new ArrayBuffer($);f.forEach((W,te)=>{let fe=O[te],be=typeof W.data=="number"?[W.data]:W.data;if(W.type===6)new Int32Array(B,fe,be.length).set(be);else if(W.type===12)new Uint32Array(B,fe,be.length).set(be);else if(W.type===10)new Uint16Array(B,fe,be.length).set(be);else if(W.type===1)new Float32Array(B,fe,be.length).set(be);else throw new Error(`Unsupported uniform type: ${ar(W.type)}`)});let q=this.gpuDataManager.create($,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(q.buffer,0,B,0,$),this.gpuDataManager.release(q.id),_={offset:0,size:$,buffer:q.buffer}}let b=this.programManager.normalizeDispatchGroupSize(h),x=b[1]===1&&b[2]===1,M=qh(e,t,x),k=this.programManager.getArtifact(M);if(k||(k=this.programManager.build(e,b),this.programManager.setArtifact(M,k),Qe("info",()=>`[artifact] key: ${M}, programName: ${e.name}`)),f&&k.uniformVariablesInfo){if(f.length!==k.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${k.uniformVariablesInfo.length}, got ${f.length} in program "${k.programInfo.name}".`);for(let $=0;$<f.length;$++){let O=f[$],I=O.type,B=typeof O.data=="number"?1:O.data.length,[q,W]=k.uniformVariablesInfo[$];if(I!==q||B!==W)throw new Error(`Uniform variable ${$} mismatch: expect type ${q} with size ${W}, got type ${I} with size ${B} in program "${k.programInfo.name}".`)}}if(Qe("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,_),Tt(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=Uh.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),Qe("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(f){return n.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${l}" failed. ${f}`)),1}finally{h&&n.push(this.device.popErrorScope().then(f=>f?`GPU validation error for kernel "[${o}] ${l}": ${f.message}`:null));for(let f of this.temporaryData)this.gpuDataManager.release(f.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,i){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let l=o.get(t),u=this.gpuDataManager.registerExternalBuffer(n,i,l);return o.set(t,[u,n]),u}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let i=await Bn(this,e,t);return Dr(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(){Qe("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(){Qe("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Qe("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()}}}),jh={};F(jh,{init:()=>Qh});var Ri,Kh,Qh,ug=S(()=>{Ie(),hr(),ke(),Ln(),Ri=class yf{constructor(t,n,i,o){this.module=t,this.dataType=n,this.data=i,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=j.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=j.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=j.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=j.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(j.size(t)!==j.size(this.dims))throw new Error("Invalid new shape");return new yf(this.module,this.dataType,this.data,t)}},Kh=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,o=n/e.PTR_SIZE,l=i===4?"i32":"i64";this.opKernelContext=Number(e.getValue(i*o++,l));let u=Number(e.getValue(i*o++,l));this.outputCount=Number(e.getValue(i*o++,l)),this.customDataOffset=Number(e.getValue(i*o++,"*")),this.customDataSize=Number(e.getValue(i*o++,l));let c=[];for(let h=0;h<u;h++){let f=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 Ri(e,f,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 Ri(this.module,c,this.output(u,h),h),l=(u,c)=>{let h=or(u,c);if(!h)throw new Error(`Unsupported data type: ${u}`);let f=h>0?this.backend.gpuDataManager.create(h).id:0;return new Ri(this.module,u,f,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)}}},Qh=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=(lg(),ie(Vh)).WebGpuBackend,u=new l;await u.initialize(n,i),o("webgpu",[u,c=>u.alloc(Number(c)),c=>u.free(c),(c,h,f,m=!1)=>{if(m)Qe("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(c)}, dst=${Number(h)}, size=${Number(f)}`),u.memcpy(Number(c),Number(h));else{Qe("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(c)}, gpuDataId=${Number(h)}, size=${Number(f)}`);let g=t.HEAPU8.subarray(Number(c>>>0),Number(c>>>0)+Number(f));u.upload(Number(h),g)}},async(c,h,f)=>{Qe("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${c}, dataOffset=${h}, size=${f}`),await u.download(Number(c),()=>t.HEAPU8.subarray(Number(h)>>>0,Number(h+f)>>>0))},(c,h,f)=>u.createKernel(c,Number(h),f,t.UTF8ToString(t._JsepGetNodeName(Number(h)))),c=>u.releaseKernel(c),(c,h,f,m)=>{Qe("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${f}, kernel=${c}, contextDataOffset=${h}`);let g=new Kh(t,u,Number(h));return u.computeKernel(Number(c),g,m)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else{let l=new zn(n);o("webnn",[l,()=>l.reserveTensorId(),u=>l.releaseTensorId(u),async(u,c,h,f,m)=>l.ensureTensor(u,c,h,f,m),(u,c)=>{l.uploadTensor(u,c)},async(u,c)=>l.downloadTensor(u,c),(u,c)=>l.registerMLContext(u,c),!!n.trace])}}}),Xh,Fa,Va,is,Yh,Ga,Ai,qa,Wa,Ha,ja,Ka,Qa,Jh=S(()=>{ut(),Qi(),Xi(),Ie(),nr(),_s(),An(),Xh=(e,t)=>{De()._OrtInit(e,t)!==0&&Ce("Can't initialize onnxruntime.")},Fa=async e=>{Xh(e.wasm.numThreads,Ss(e.logLevel))},Va=async(e,t)=>{De().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=(ug(),ie(jh)).init;t==="webgpu"&&await i("webgpu",De(),e,n),t==="webnn"&&await i("webnn",De(),e)}},is=new Map,Yh=e=>{let t=De(),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)}},Ga=(e,t)=>{let n=De(),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 f=n.HEAPU32[o/4+1],m=[];for(let g=0;g<f;g++){let w=Number(n.getValue(o+8+g*l,"*"));m.push(w!==0?n.UTF8ToString(w):Number(n.getValue(o+8+(g+f)*l,"*")))}return[c,h,m]}finally{n.stackRestore(i),o!==0&&n._OrtFree(o)}},Ai=e=>{let t=De(),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]},qa=async(e,t)=>{let n,i,o=De();Array.isArray(e)?[n,i]=e:e.buffer===o.HEAPU8.buffer?[n,i]=[e.byteOffset,e.byteLength]:[n,i]=Ai(e);let l=0,u=0,c=0,h=[],f=[],m=[];try{if([u,h]=await Rn(t),t?.externalData&&o.mountExternalData){let I=[];for(let B of t.externalData){let q=typeof B=="string"?B:B.path;I.push($s(typeof B=="string"?B:B.data).then(W=>{o.mountExternalData(q,W)}))}await Promise.all(I)}for(let I of t?.executionProviders??[])if((typeof I=="string"?I:I.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof I!="string"){let B=I,q=B?.context,W=B?.gpuDevice,te=B?.deviceType,fe=B?.powerPreference;q?o.currentContext=q:W?o.currentContext=await o.webnnCreateMLContext(W):o.currentContext=await o.webnnCreateMLContext({deviceType:te,powerPreference:fe})}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]=Yh(l),_=!!t?.enableGraphCapture,b=[],x=[],M=[],k=[],$=[];for(let I=0;I<g;I++){let[B,q,W]=Ga(l,I);B===0&&Ce("Can't get an input name."),f.push(B);let te=o.UTF8ToString(B);b.push(te),M.push(q===0?{name:te,isTensor:!1}:{name:te,isTensor:!0,type:ar(q),shape:W})}for(let I=0;I<w;I++){let[B,q,W]=Ga(l,I+g);B===0&&Ce("Can't get an output name."),m.push(B);let te=o.UTF8ToString(B);x.push(te),k.push(q===0?{name:te,isTensor:!1}:{name:te,isTensor:!0,type:ar(q),shape:W});{if(_&&t?.preferredOutputLocation===void 0){$.push("gpu-buffer");continue}let fe=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[te]??"cpu",be=o.webnnIsGraphOutput;if(fe==="cpu"&&be&&be(l,te)){$.push("ml-tensor-cpu-output");continue}if(fe!=="cpu"&&fe!=="cpu-pinned"&&fe!=="gpu-buffer"&&fe!=="ml-tensor")throw new Error(`Not supported preferred output location: ${fe}.`);if(_&&fe!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${fe}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);$.push(fe)}}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=>Vs(I))}),is.set(l,[l,f,m,O,_,!1]),[l,b,x,M,k]}catch(g){throw f.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?.()}},Wa=e=>{let t=De(),n=is.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."),is.delete(e)},Ha=async(e,t,n,i,o,l,u=!1)=>{if(!e){t.push(0);return}let c=De(),h=c.PTR_SIZE,f=e[0],m=e[1],g=e[3],w=g,_,b;if(f==="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=or(ir(f),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=or(ir(f),m);let $=c.webnnRegisterMLTensor;if(!$)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=$(i,k,ir(f),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,Et(k[$],n),"*")}}else{let $=c.webnnIsGraphInput,O=c.webnnIsGraphOutput;if(f!=="string"&&$&&O){let I=c.UTF8ToString(o);if($(i,I)||O(i,I)){let B=ir(f);b=or(B,m),w="ml-tensor";let q=c.webnnCreateTemporaryTensor,W=c.webnnUploadTensor;if(!q||!W)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let te=await q(i,B,m);W(te,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),_=te}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(ir(f),_,b,M,m.length,Vs(w));k===0&&Ce(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(k)}finally{c.stackRestore(x)}},ja=async(e,t,n,i,o,l)=>{let u=De(),c=u.PTR_SIZE,h=is.get(e);if(!h)throw new Error(`cannot run inference. invalid session id: ${e}`);let f=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=[],W=u.stackSave(),te=u.stackAlloc(x*c),fe=u.stackAlloc(x*c),be=u.stackAlloc(M*c),qe=u.stackAlloc(M*c);try{[k,$]=En(l),zt("wasm prepareInputOutputTensor");for(let ye=0;ye<x;ye++)await Ha(n[ye],O,B,e,m[t[ye]],t[ye],_);for(let ye=0;ye<M;ye++)await Ha(o[ye],I,B,e,g[i[ye]],x+i[ye],_);Lt("wasm prepareInputOutputTensor");for(let ye=0;ye<x;ye++)u.setValue(te+ye*c,O[ye],"*"),u.setValue(fe+ye*c,m[t[ye]],"*");for(let ye=0;ye<M;ye++)u.setValue(be+ye*c,I[ye],"*"),u.setValue(qe+ye*c,g[i[ye]],"*");if(w&&!b){let{handle:ye,outputPreferredLocations:xe,outputPreferredLocationsEncoded:Be}=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}).`);zt("wasm bindInputsOutputs");for(let je=0;je<x;je++){let Le=t[je];await u._OrtBindInput(ye,m[Le],O[je])!==0&&Ce(`Can't bind input[${je}] for session=${e}.`)}for(let je=0;je<M;je++){let Le=i[je];o[je]?.[3]?(q.push(I[je]),u._OrtBindOutput(ye,g[Le],I[je],0)!==0&&Ce(`Can't bind pre-allocated output[${je}] for session=${e}.`)):u._OrtBindOutput(ye,g[Le],0,Be[Le])!==0&&Ce(`Can't bind output[${je}] to ${xe[je]} for session=${e}.`)}Lt("wasm bindInputsOutputs"),is.set(e,[f,m,g,w,_,!0])}u.jsepOnRunStart?.(f),u.webnnOnRunStart?.(f);let Re;w?Re=await u._OrtRunWithBinding(f,w.handle,M,be,k):Re=await u._OrtRun(f,fe,te,x,qe,M,be,k),Re!==0&&Ce("failed to call OrtRun().");let Me=[],rt=[];zt("wasm ProcessOutputTensor");for(let ye=0;ye<M;ye++){let xe=Number(u.getValue(be+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 Be=u.stackSave(),je=u.stackAlloc(4*c),Le=!1,Xe,ue=0;try{u._OrtGetTensorData(xe,je,je+c,je+2*c,je+3*c)!==0&&Ce(`Can't access output tensor data on index ${ye}.`);let ze=c===4?"i32":"i64",Ae=Number(u.getValue(je,ze));ue=u.getValue(je+c,"*");let $e=u.getValue(je+c*2,"*"),Kt=Number(u.getValue(je+c*3,ze)),lr=[];for(let ht=0;ht<Kt;ht++)lr.push(Number(u.getValue($e+ht*c,ze)));u._OrtFree($e)!==0&&Ce("Can't free memory for tensor dims.");let Rt=lr.reduce((ht,At)=>ht*At,1);Xe=ar(Ae);let ur=w?.outputPreferredLocations[i[ye]];if(Xe==="string"){if(ur==="gpu-buffer"||ur==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ht=[];for(let At=0;At<Rt;At++){let jr=u.getValue(ue+At*c,"*"),fg=u.getValue(ue+(At+1)*c,"*"),mg=At===Rt-1?void 0:fg-jr;ht.push(u.UTF8ToString(jr,mg))}Me.push([Xe,lr,ht,"cpu"])}else if(ur==="gpu-buffer"&&Rt>0){let ht=u.jsepGetBuffer;if(!ht)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let At=ht(ue),jr=or(Ae,Rt);if(jr===void 0||!Ts(Xe))throw new Error(`Unsupported data type: ${Xe}`);Le=!0,Me.push([Xe,lr,{gpuBuffer:At,download:u.jsepCreateDownloader(At,jr,Xe),dispose:()=>{u._OrtReleaseTensor(xe)!==0&&Ce("Can't release tensor.")}},"gpu-buffer"])}else if(ur==="ml-tensor"&&Rt>0){let ht=u.webnnEnsureTensor,At=u.webnnIsGraphInputOutputTypeSupported;if(!ht||!At)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(or(Ae,Rt)===void 0||!Es(Xe))throw new Error(`Unsupported data type: ${Xe}`);if(!At(e,Xe,!1))throw new Error(`preferredLocation "ml-tensor" for ${Xe} output is not supported by current WebNN Context.`);let jr=await ht(e,ue,Ae,lr,!1);Le=!0,Me.push([Xe,lr,{mlTensor:jr,download:u.webnnCreateMLTensorDownloader(ue,Xe),dispose:()=>{u.webnnReleaseTensorId(ue),u._OrtReleaseTensor(xe)}},"ml-tensor"])}else if(ur==="ml-tensor-cpu-output"&&Rt>0){let ht=u.webnnCreateMLTensorDownloader(ue,Xe)(),At=Me.length;Le=!0,rt.push((async()=>{let jr=[At,await ht];return u.webnnReleaseTensorId(ue),u._OrtReleaseTensor(xe),jr})()),Me.push([Xe,lr,[],"cpu"])}else{let ht=bs(Xe),At=new ht(Rt);new Uint8Array(At.buffer,At.byteOffset,At.byteLength).set(u.HEAPU8.subarray(ue,ue+At.byteLength)),Me.push([Xe,lr,At,"cpu"])}}finally{u.stackRestore(Be),Xe==="string"&&ue&&u._free(ue),Le||u._OrtReleaseTensor(xe)}}w&&!_&&(u._OrtClearBoundOutputs(w.handle)!==0&&Ce("Can't clear bound outputs."),is.set(e,[f,m,g,w,_,!1]));for(let[ye,xe]of await Promise.all(rt))Me[ye][2]=xe;return Lt("wasm ProcessOutputTensor"),Me}finally{u.webnnOnRunEnd?.(f),u.stackRestore(W),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))}},Ka=e=>{let t=De(),n=is.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)},Qa=e=>{let t=[];for(let n of e){let i=n[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),as,gr,on,Yn,Jn,Ii,Xa,Mi,Ls,Bs,Zh,ep,tp,rp,sp,np,ip,ap,op=S(()=>{ut(),Jh(),nr(),gs(),as=()=>!!me.wasm.proxy&&typeof document<"u",on=!1,Yn=!1,Jn=!1,Mi=new Map,Ls=(e,t)=>{let n=Mi.get(e);n?n.push(t):Mi.set(e,[t])},Bs=()=>{if(on||!Yn||Jn||!gr)throw new Error("worker not ready")},Zh=e=>{switch(e.data.type){case"init-wasm":on=!1,e.data.err?(Jn=!0,Xa[1](e.data.err)):(Yn=!0,Xa[0]()),Ii&&(URL.revokeObjectURL(Ii),Ii=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Mi.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},ep=async()=>{if(!Yn){if(on)throw new Error("multiple calls to 'initWasm()' detected.");if(Jn)throw new Error("previous call to 'initWasm()' failed.");if(on=!0,as())return new Promise((e,t)=>{gr?.terminate(),vn().then(([n,i])=>{try{gr=i,gr.onerror=l=>t(l),gr.onmessage=Zh,Xa=[e,t];let o={type:"init-wasm",in:me};if(!o.in.wasm.wasmPaths&&n){let l=hs();l&&(o.in.wasm.wasmPaths=l)}gr.postMessage(o),Ii=n}catch(o){t(o)}},t)});try{await vs(me.wasm),await Fa(me),Yn=!0}catch(e){throw Jn=!0,e}finally{on=!1}}},tp=async e=>{if(as())return Bs(),new Promise((t,n)=>{Ls("init-ep",[t,n]);let i={type:"init-ep",in:{epName:e,env:me}};gr.postMessage(i)});await Va(me,e)},rp=async e=>as()?(Bs(),new Promise((t,n)=>{Ls("copy-from",[t,n]);let i={type:"copy-from",in:{buffer:e}};gr.postMessage(i,[e.buffer])})):Ai(e),sp=async(e,t)=>{if(as()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Bs(),new Promise((n,i)=>{Ls("create",[n,i]);let o={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),gr.postMessage(o,l)})}else return qa(e,t)},np=async e=>{if(as())return Bs(),new Promise((t,n)=>{Ls("release",[t,n]);let i={type:"release",in:e};gr.postMessage(i)});Wa(e)},ip=async(e,t,n,i,o,l)=>{if(as()){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 Bs(),new Promise((u,c)=>{Ls("run",[u,c]);let h=n,f={type:"run",in:{sessionId:e,inputIndices:t,inputs:h,outputIndices:i,options:l}};gr.postMessage(f,Qa(h))})}else return ja(e,t,n,i,o,l)},ap=async e=>{if(as())return Bs(),new Promise((t,n)=>{Ls("end-profiling",[t,n]);let i={type:"end-profiling",in:e};gr.postMessage(i)});Ka(e)}}),Ya,lp,up,dg=S(()=>{ut(),op(),Ie(),us(),An(),Ya=(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()}`)}},lp=e=>{switch(e[3]){case"cpu":return new et(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Ts(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:o}=e[2];return et.fromGpuBuffer(n,{dataType:t,dims:e[1],download:i,dispose:o})}case"ml-tensor":{let t=e[0];if(!Es(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:o}=e[2];return et.fromMLTensor(n,{dataType:t,dims:e[1],download:i,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},up=class{async fetchModelAndCopyToWasmMemory(e){return rp(await $s(e))}async loadModel(e,t){ct();let n;typeof e=="string"?n=await this.fetchModelAndCopyToWasmMemory(e):n=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await sp(n,t),Tt()}async dispose(){return np(this.sessionId)}async run(e,t,n){ct();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)=>Ya(g,()=>`input "${this.inputNames[o[w]]}"`)),h=l.map((g,w)=>g?Ya(g,()=>`output "${this.outputNames[u[w]]}"`):null),f=await ip(this.sessionId,o,c,u,h,n),m={};for(let g=0;g<f.length;g++)m[this.outputNames[u[g]]]=l[g]??lp(f[g]);return Tt(),m}startProfiling(){}endProfiling(){ap(this.sessionId)}}}),dp={};F(dp,{OnnxruntimeWebAssemblyBackend:()=>Za,initializeFlags:()=>Ja,wasmBackend:()=>cp});var Ja,Za,cp,cg=S(()=>{ut(),op(),dg(),Ja=()=>{(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))}},Za=class{async init(e){Ja(),await ep(),await tp(e)}async createInferenceSessionHandler(e,t){let n=new up;return await n.loadModel(e,t),n}},cp=new Za}),hp={};F(hp,{InferenceSession:()=>Bt,TRACE:()=>qt,TRACE_EVENT_BEGIN:()=>zt,TRACE_EVENT_END:()=>Lt,TRACE_FUNC_BEGIN:()=>ct,TRACE_FUNC_END:()=>Tt,Tensor:()=>et,default:()=>pg,env:()=>me,registerBackend:()=>se}),ut(),ut(),ut();var hg="1.26.0",pg=sr;{let e=(cg(),ie(dp)).wasmBackend;se("webgpu",e,5),se("webnn",e,5),se("cpu",e,10),se("wasm",e,10)}return Object.defineProperty(me.versions,"web",{value:hg,enumerable:!0}),ie(hp)})();/**
|
|
2811
|
+
* @license
|
|
2812
|
+
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
2813
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2814
|
+
* you may not use this file except in compliance with the License.
|
|
2815
|
+
* You may obtain a copy of the License at
|
|
2816
|
+
*
|
|
2817
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2818
|
+
*
|
|
2819
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2820
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2821
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2822
|
+
* See the License for the specific language governing permissions and
|
|
2823
|
+
* limitations under the License.
|
|
2824
|
+
* =============================================================================
|
|
2825
|
+
*//**
|
|
2826
|
+
* @license
|
|
2827
|
+
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
2828
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2829
|
+
* you may not use this file except in compliance with the License.
|
|
2830
|
+
* You may obtain a copy of the License at
|
|
2831
|
+
*
|
|
2832
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2833
|
+
*
|
|
2834
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2835
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2836
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2837
|
+
* See the License for the specific language governing permissions and
|
|
2838
|
+
* limitations under the License.
|
|
2839
|
+
* =============================================================================
|
|
2840
|
+
*//**
|
|
2841
|
+
* @license
|
|
2842
|
+
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
2843
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2844
|
+
* you may not use this file except in compliance with the License.
|
|
2845
|
+
* You may obtain a copy of the License at
|
|
2846
|
+
*
|
|
2847
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2848
|
+
*
|
|
2849
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2850
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2851
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2852
|
+
* See the License for the specific language governing permissions and
|
|
2853
|
+
* limitations under the License.
|
|
2854
|
+
* =============================================================================
|
|
2855
|
+
*/d.exports=s})(ao)),ao.exports}var Ns={},oo={},Rp;function ky(){return Rp||(Rp=1,Object.defineProperty(oo,"__esModule",{value:!0})),oo}var ai={},Ap;function Ry(){if(Ap)return ai;Ap=1;var d;Object.defineProperty(ai,"__esModule",{value:!0}),ai.SileroLegacy=void 0;const r=pi();class s{constructor(p,v,C,R,S){this.ortInstance=p,this._session=v,this._h=C,this._c=R,this._sr=S,this.reset_state=()=>{const F=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",F,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",F,[2,1,64])},this.process=async F=>{const ie={input:new this.ortInstance.Tensor("float32",F,[1,F.length]),h:this._h,c:this._c,sr:this._sr},X=await this._session.run(ie);this._h=X.hn,this._c=X.cn;const[re]=X.output?.data;return{notSpeech:1-re,isSpeech:re}},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,p)=>{r.log.debug("initializing vad");const v=await p(),C=await a.InferenceSession.create(v),R=new a.Tensor("int64",[16000n]),S=Array(128).fill(0),F=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,F,z,R)},ai}var oi={},Ip;function Ay(){if(Ip)return oi;Ip=1;var d;Object.defineProperty(oi,"__esModule",{value:!0}),oi.SileroV5=void 0;const r=pi();function s(p){const v=Array(256).fill(0);return new p.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 F=>{const ie={input:new this.ortInstance.Tensor("float32",F,[1,F.length]),state:this._state,sr:this._sr},X=await this._session.run(ie);if(!X.stateN)throw new Error("No state from model");if(this._state=X.stateN,!X.output?.data)throw new Error("No output from model");const re=X.output.data[0];if(typeof re!="number")throw new Error("Weird output data");return{notSpeech:1-re,isSpeech:re}},this.release=async()=>{await this._session.release(),this._state.dispose(),this._sr.dispose()}}}return oi.SileroV5=a,d=a,a.new=async(p,v)=>{r.log.debug("Loading VAD...");const C=await v(),R=await p.InferenceSession.create(C),S=new p.Tensor("int64",[16000n]),F=s(p);return r.log.debug("...finished loading VAD"),new d(R,F,S,p)},oi}var Mp;function wf(){return Mp||(Mp=1,(function(d){var r=Ns&&Ns.__createBinding||(Object.create?(function(v,C,R,S){S===void 0&&(S=R);var F=Object.getOwnPropertyDescriptor(C,R);(!F||("get"in F?!C.__esModule:F.writable||F.configurable))&&(F={enumerable:!0,get:function(){return C[R]}}),Object.defineProperty(v,S,F)}):(function(v,C,R,S){S===void 0&&(S=R),v[S]=C[R]})),s=Ns&&Ns.__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(ky(),d);var a=Ry();Object.defineProperty(d,"SileroLegacy",{enumerable:!0,get:function(){return a.SileroLegacy}});var p=Ay();Object.defineProperty(d,"SileroV5",{enumerable:!0,get:function(){return p.SileroV5}})})(Ns)),Ns}var li={},Op;function vf(){if(Op)return li;Op=1,Object.defineProperty(li,"__esModule",{value:!0}),li.Resampler=void 0;const d=pi();class r{constructor(a){this.options=a,this.process=p=>{const v=[];for(const C of p)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 p of a)for(this.inputBuffer.push(p);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 p=0,v=0;for(;p<this.options.targetFrameSize;){let C=0,R=0;for(;v<Math.min(this.inputBuffer.length,(p+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const S=this.inputBuffer[v];S!==void 0&&(C+=S,R++),v++}a[p]=C/R,p++}return this.inputBuffer=this.inputBuffer.slice(v),a}}return li.Resampler=r,li}var Pp;function Iy(){return Pp||(Pp=1,(function(d){var r=Qr&&Qr.__createBinding||(Object.create?(function(X,re,se,Z){Z===void 0&&(Z=se);var ee=Object.getOwnPropertyDescriptor(re,se);(!ee||("get"in ee?!re.__esModule:ee.writable||ee.configurable))&&(ee={enumerable:!0,get:function(){return re[se]}}),Object.defineProperty(X,Z,ee)}):(function(X,re,se,Z){Z===void 0&&(Z=se),X[Z]=re[se]})),s=Qr&&Qr.__setModuleDefault||(Object.create?(function(X,re){Object.defineProperty(X,"default",{enumerable:!0,value:re})}):function(X,re){X.default=re}),a=Qr&&Qr.__importStar||function(X){if(X&&X.__esModule)return X;var re={};if(X!=null)for(var se in X)se!=="default"&&Object.prototype.hasOwnProperty.call(X,se)&&r(re,X,se);return s(re,X),re};Object.defineProperty(d,"__esModule",{value:!0}),d.NonRealTimeVAD=d.defaultNonRealTimeVADOptions=void 0;const p=a(Cy()),v=mf(),C=Mo(),R=Oo(),S=ji(),F=wf(),z=vf();d.defaultNonRealTimeVADOptions={...R.defaultFrameProcessorOptions,modelURL:v.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:C.defaultModelFetcher};class ie{static async new(re={}){const se={...d.defaultNonRealTimeVADOptions,...re};(0,R.validateOptions)(se),se.ortConfig!==void 0&&se.ortConfig(p);const Z=()=>se.modelFetcher(se.modelURL),ee=await F.SileroLegacy.new(p,Z),_e=new R.FrameProcessor(ee.process,ee.reset_state,{positiveSpeechThreshold:se.positiveSpeechThreshold,negativeSpeechThreshold:se.negativeSpeechThreshold,redemptionMs:se.redemptionMs,preSpeechPadMs:se.preSpeechPadMs,minSpeechMs:se.minSpeechMs,submitUserSpeechOnPause:se.submitUserSpeechOnPause},1536/16);return _e.resume(),new this(Z,p,se,_e)}constructor(re,se,Z,ee){this.modelFetcher=re,this.ort=se,this.options=Z,this.frameProcessor=ee,this.frameSamples=1536}async*run(re,se){const Z={nativeSampleRate:se,targetSampleRate:16e3,targetFrameSize:this.frameSamples},ee=new z.Resampler(Z);let _e=0,ae=0,he=0;for await(const le of ee.stream(re)){const pe=[];await this.frameProcessor.process(le,Ve=>{pe.push(Ve)});for(const Ve of pe)switch(Ve.msg){case S.Message.SpeechStart:_e=he*this.frameSamples/16;break;case S.Message.SpeechEnd:ae=(he+1)*this.frameSamples/16,yield{audio:Ve.audio,start:_e,end:ae};break}he++}const H=[];this.frameProcessor.endSegment(le=>{H.push(le)});for(const le of H)switch(le.msg){case S.Message.SpeechEnd:yield{audio:le.audio,start:_e,end:he*this.frameSamples/16}}}}d.NonRealTimeVAD=ie})(Qr)),Qr}var Rr={},Dp;function My(){if(Dp)return Rr;Dp=1,Object.defineProperty(Rr,"__esModule",{value:!0}),Rr.audioFileToArray=Rr.encodeWAV=Rr.arrayBufferToBase64=Rr.minFramesForTargetMS=void 0;function d(R,S,F=16e3){return Math.ceil(R*F/1e3/S)}Rr.minFramesForTargetMS=d;function r(R){const S=new Uint8Array(R),F=S.byteLength,z=new Array(F);for(let ie=0;ie<F;ie++){const X=S[ie];if(X===void 0)break;z[ie]=String.fromCharCode(X)}return btoa(z.join(""))}Rr.arrayBufferToBase64=r;function s(R,S=3,F=16e3,z=1,ie=32){const X=ie/8,re=z*X,se=new ArrayBuffer(44+R.length*X),Z=new DataView(se);return v(Z,0,"RIFF"),Z.setUint32(4,36+R.length*X,!0),v(Z,8,"WAVE"),v(Z,12,"fmt "),Z.setUint32(16,16,!0),Z.setUint16(20,S,!0),Z.setUint16(22,z,!0),Z.setUint32(24,F,!0),Z.setUint32(28,F*re,!0),Z.setUint16(32,re,!0),Z.setUint16(34,ie,!0),v(Z,36,"data"),Z.setUint32(40,R.length*X,!0),S===1?p(Z,44,R):a(Z,44,R),se}Rr.encodeWAV=s;function a(R,S,F){for(let z=0;z<F.length;z++,S+=4)R.setFloat32(S,F[z],!0)}function p(R,S,F){for(let z=0;z<F.length;z++,S+=2){const ie=Math.max(-1,Math.min(1,F[z]));R.setInt16(S,ie<0?ie*32768:ie*32767,!0)}}function v(R,S,F){for(let z=0;z<F.length;z++)R.setUint8(S+z,F.charCodeAt(z))}async function C(R){const S=new OfflineAudioContext(1,1,44100),F=new FileReader;let z=null;if(await new Promise(re=>{F.addEventListener("loadend",()=>{const se=F.result;S.decodeAudioData(se,Z=>{z=Z,S.startRendering().then(()=>{console.log("Rendering completed successfully"),re()}).catch(ee=>{console.error("Rendering failed: ",ee)})},Z=>{console.log("Error with decoding audio data: ",Z)})}),F.readAsArrayBuffer(R)}),z===null)throw Error("some shit");const ie=z,X=new Float32Array(ie.length);for(let re=0;re<ie.length;re++)for(let se=0;se<ie.numberOfChannels;se++){const Z=ie.getChannelData(se)[re],ee=X[re];if(Z===void 0||ee===void 0)throw new Error("sample or out[i] is undefined");X[re]=ee+Z}return{audio:X,sampleRate:ie.sampleRate}}return Rr.audioFileToArray=C,Rr}var Xr={},lo={exports:{}};/*!
|
|
2856
|
+
* ONNX Runtime Web v1.26.0
|
|
2857
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2858
|
+
* Licensed under the MIT License.
|
|
2859
|
+
*/var zp;function Oy(){return zp||(zp=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,p=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(y=>typeof wr<"u"?wr:typeof Proxy<"u"?new Proxy(y,{get:(E,A)=>(typeof wr<"u"?wr:E)[A]}):y)(function(y){if(typeof wr<"u")return wr.apply(this,arguments);throw Error('Dynamic require of "'+y+'" is not supported')}),S=(y,E)=>()=>(y&&(E=y(y=0)),E),F=(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=p(E,P))||D.enumerable});return y},ie=y=>z(a({},"__esModule",{value:!0}),y),X,re,se,Z,ee,_e=S(()=>{X=new Map,re=[],se=(y,E,A)=>{if(E&&typeof E.init=="function"&&typeof E.createInferenceSessionHandler=="function"){let D=X.get(y);if(D===void 0)X.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=re.indexOf(y);P!==-1&&re.splice(P,1);for(let G=0;G<re.length;G++)if(X.get(re[G]).priority<=A){re.splice(G,0,y);return}re.push(y)}return}throw new TypeError("not a valid backend")},Z=async y=>{let E=X.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}}},ee=async y=>{let E=y.executionProviders||[],A=E.map(V=>typeof V=="string"?V:V.name),D=A.length===0?re:A,P,G=[],N=new Set;for(let V of D){let ne=await Z(V);typeof ne=="string"?G.push({name:V,err:ne}):(P||(P=ne),P===ne&&N.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:ne}of G)A.includes(V)&&console.warn(`removing requested execution provider "${V}" from session options because it is not available: ${ne}`);let L=E.filter(V=>N.has(typeof V=="string"?V:V.name));return[P,new Proxy(y,{get:(V,ne)=>ne==="executionProviders"?L:Reflect.get(V,ne)})]}}),ae=S(()=>{_e()}),he,H=S(()=>{he="1.26.0"}),le,pe,Ve=S(()=>{H(),le="warning",pe={wasm:{},webgl:{},webgpu:{},versions:{common:he},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}`);le=y}},get logLevel(){return le}},Object.defineProperty(pe,"logLevel",{enumerable:!0})}),me,Ze=S(()=>{Ve(),me=pe}),tt,dt,wt=S(()=>{tt=(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 N=E?.format!==void 0?E.format:"RGB",L=E?.norm,V,ne;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?ne=[0,0,0,0]:typeof L.bias=="number"?ne=[L.bias,L.bias,L.bias,L.bias]:(ne=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(ne[3]=L.bias[3]));let oe=G*P,Y=0,K=oe,Te=oe*2,U=-1;N==="RGBA"?(Y=0,K=oe,Te=oe*2,U=oe*3):N==="RGB"?(Y=0,K=oe,Te=oe*2):N==="RBG"&&(Y=0,Te=oe,K=oe*2);for(let de=0;de<G;de++)for(let ft=0;ft<P;ft++){let Ue=(y.data[Y++]-ne[0])*V[0],Ee=(y.data[K++]-ne[1])*V[1],Fe=(y.data[Te++]-ne[2])*V[2],we=U===-1?255:(y.data[U++]-ne[3])*V[3];D.fillStyle="rgba("+Ue+","+Ee+","+Fe+","+we+")",D.fillRect(ft,de,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")},dt=(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,N;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[1],N=y.dims[3]):(P=y.dims[3],G=y.dims[2],N=y.dims[1]);let L=E!==void 0&&E.format!==void 0?E.format:"RGB",V=E?.norm,ne,oe;V===void 0||V.mean===void 0?ne=[255,255,255,255]:typeof V.mean=="number"?ne=[V.mean,V.mean,V.mean,V.mean]:(ne=[V.mean[0],V.mean[1],V.mean[2],255],V.mean[3]!==void 0&&(ne[3]=V.mean[3])),V===void 0||V.bias===void 0?oe=[0,0,0,0]:typeof V.bias=="number"?oe=[V.bias,V.bias,V.bias,V.bias]:(oe=[V.bias[0],V.bias[1],V.bias[2],0],V.bias[3]!==void 0&&(oe[3]=V.bias[3]));let Y=G*P;if(E!==void 0&&(E.format!==void 0&&N===4&&E.format!=="RGBA"||N===3&&E.format!=="RGB"&&E.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let K=4,Te=0,U=1,de=2,ft=3,Ue=0,Ee=Y,Fe=Y*2,we=-1;L==="RGBA"?(Ue=0,Ee=Y,Fe=Y*2,we=Y*3):L==="RGB"?(Ue=0,Ee=Y,Fe=Y*2):L==="RBG"&&(Ue=0,Fe=Y,Ee=Y*2),D=A.createImageData(P,G);for(let Ut=0;Ut<G*P;Te+=K,U+=K,de+=K,ft+=K,Ut++)D.data[Te]=(y.data[Ue++]-oe[0])*ne[0],D.data[U]=(y.data[Ee++]-oe[1])*ne[1],D.data[de]=(y.data[Fe++]-oe[2])*ne[2],D.data[ft]=we===-1?255:(y.data[we++]-oe[3])*ne[3]}else throw new Error("Can not access image data");return D}}),lt,yt,$t,vt,Ye,St,He=S(()=>{xt(),lt=(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,N;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"?N=[P.bias,P.bias,P.bias,P.bias]:N=[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",ne=A*D,oe=V==="RGBA"?new Float32Array(ne*4):new Float32Array(ne*3),Y=4,K=0,Te=1,U=2,de=3,ft=0,Ue=ne,Ee=ne*2,Fe=-1;L==="RGB"&&(Y=3,K=0,Te=1,U=2,de=-1),V==="RGBA"?Fe=ne*3:V==="RBG"?(ft=0,Ee=ne,Ue=ne*2):V==="BGR"&&(Ee=0,Ue=ne,ft=ne*2);for(let we=0;we<ne;we++,K+=Y,U+=Y,Te+=Y,de+=Y)oe[ft++]=(y[K]+N[0])/G[0],oe[Ue++]=(y[Te]+N[1])/G[1],oe[Ee++]=(y[U]+N[2])/G[2],Fe!==-1&&de!==-1&&(oe[Fe++]=(y[de]+N[3])/G[3]);return V==="RGBA"?new We("float32",oe,[1,4,A,D]):new We("float32",oe,[1,3,A,D])},yt=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",N,L=E??{},V=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},ne=oe=>typeof HTMLCanvasElement<"u"&&oe instanceof HTMLCanvasElement||oe instanceof OffscreenCanvas?oe.getContext("2d"):null;if(A){let oe=V();oe.width=y.width,oe.height=y.height;let Y=ne(oe);if(Y!=null){let K=y.height,Te=y.width;if(E!==void 0&&E.resizedHeight!==void 0&&E.resizedWidth!==void 0&&(K=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=K,L.width=Te}else L.tensorFormat="RGBA",L.height=K,L.width=Te;Y.drawImage(y,0,0),N=Y.getImageData(0,0,Te,K).data}else throw new Error("Can not access image data")}else if(D){let oe,Y;if(E!==void 0&&E.resizedWidth!==void 0&&E.resizedHeight!==void 0?(oe=E.resizedHeight,Y=E.resizedWidth):(oe=y.height,Y=y.width),E!==void 0&&(L=E),L.format="RGBA",L.height=oe,L.width=Y,E!==void 0){let K=V();K.width=Y,K.height=oe;let Te=ne(K);if(Te!=null)Te.putImageData(y,0,0),N=Te.getImageData(0,0,Y,oe).data;else throw new Error("Can not access image data")}else N=y.data}else if(P){if(E===void 0)throw new Error("Please provide image config with format for Imagebitmap");let oe=V();oe.width=y.width,oe.height=y.height;let Y=ne(oe);if(Y!=null){let K=y.height,Te=y.width;return Y.drawImage(y,0,0,Te,K),N=Y.getImageData(0,0,Te,K).data,L.height=K,L.width=Te,lt(N,L)}else throw new Error("Can not access image data")}else{if(G)return new Promise((oe,Y)=>{let K=V(),Te=ne(K);if(!y||!Te)return Y();let U=new Image;U.crossOrigin="Anonymous",U.src=y,U.onload=()=>{K.width=U.width,K.height=U.height,Te.drawImage(U,0,0,K.width,K.height);let de=Te.getImageData(0,0,K.width,K.height);L.height=K.height,L.width=K.width,oe(lt(de.data,L))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(N!==void 0)return lt(N,L);throw new Error("Input data provided is not supported - aborted tensor creation")},$t=(y,E)=>{let{width:A,height:D,download:P,dispose:G}=E,N=[1,D,A,4];return new We({location:"texture",type:"float32",texture:y,dims:N,download:P,dispose:G})},vt=(y,E)=>{let{dataType:A,dims:D,download:P,dispose:G}=E;return new We({location:"gpu-buffer",type:A??"float32",gpuBuffer:y,dims:D,download:P,dispose:G})},Ye=(y,E)=>{let{dataType:A,dims:D,download:P,dispose:G}=E;return new We({location:"ml-tensor",type:A??"float32",mlTensor:y,dims:D,download:P,dispose:G})},St=(y,E,A)=>new We({location:"cpu-pinned",type:y,data:E,dims:A??[E.length]})}),at,J,Oe,it,Ke=S(()=>{at=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),J=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Oe=!1,it=()=>{if(!Oe){Oe=!0;let y=typeof BigInt64Array<"u"&&BigInt64Array.from,E=typeof BigUint64Array<"u"&&BigUint64Array.from,A=globalThis.Float16Array,D=typeof A<"u"&&A.from;y&&(at.set("int64",BigInt64Array),J.set(BigInt64Array,"int64")),E&&(at.set("uint64",BigUint64Array),J.set(BigUint64Array,"uint64")),D?(at.set("float16",A),J.set(A,"float16")):at.set("float16",Uint16Array)}}}),Pe,ot,Je=S(()=>{xt(),Pe=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},ot=(y,E)=>{switch(y.location){case"cpu":return new We(y.type,y.data,E);case"cpu-pinned":return new We({location:"cpu-pinned",data:y.data,type:y.type,dims:E});case"texture":return new We({location:"texture",texture:y.texture,type:y.type,dims:E});case"gpu-buffer":return new We({location:"gpu-buffer",gpuBuffer:y.gpuBuffer,type:y.type,dims:E});case"ml-tensor":return new We({location:"ml-tensor",mlTensor:y.mlTensor,type:y.type,dims:E});default:throw new Error(`tensorReshape: tensor location ${y.location} is not supported`)}}}),We,xt=S(()=>{wt(),He(),Ke(),Je(),We=class{constructor(y,E,A){it();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 N=at.get(D);if(!N)throw new TypeError(`unsupported type "${D}" to create tensor from pinned buffer`);if(!(y.data instanceof N))throw new TypeError(`buffer should be of type ${N.name}`);this.cpuData=y.data;break}case"texture":{if(D!=="float32")throw new TypeError(`unsupported type "${D}" to create tensor from texture`);this.gpuTextureData=y.texture,this.downloader=y.download,this.disposer=y.dispose;break}case"gpu-buffer":{if(D!=="float32"&&D!=="float16"&&D!=="int32"&&D!=="int64"&&D!=="uint32"&&D!=="uint8"&&D!=="bool"&&D!=="uint4"&&D!=="int4")throw new TypeError(`unsupported type "${D}" to create tensor from gpu buffer`);this.gpuBufferData=y.gpuBuffer,this.downloader=y.download,this.disposer=y.dispose;break}case"ml-tensor":{if(D!=="float32"&&D!=="float16"&&D!=="int32"&&D!=="int64"&&D!=="uint32"&&D!=="uint64"&&D!=="int8"&&D!=="uint8"&&D!=="bool"&&D!=="uint4"&&D!=="int4")throw new TypeError(`unsupported type "${D}" to create tensor from MLTensor`);this.mlTensorData=y.mlTensor,this.downloader=y.download,this.disposer=y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let N,L;if(typeof y=="string")if(D=y,L=A,y==="string"){if(!Array.isArray(E))throw new TypeError("A string tensor's data must be a string array.");N=E}else{let V=at.get(y);if(V===void 0)throw new TypeError(`Unsupported tensor type: ${y}.`);if(Array.isArray(E)){if(y==="float16"&&V===Uint16Array||y==="uint4"||y==="int4")throw new TypeError(`Creating a ${y} tensor from number array is not supported. Please use ${V.name} as data.`);y==="uint64"||y==="int64"?N=V.from(E,BigInt):N=V.from(E)}else if(E instanceof V)N=E;else if(E instanceof Uint8ClampedArray)if(y==="uint8")N=Uint8Array.from(E);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(y==="float16"&&E instanceof Uint16Array&&V!==Uint16Array)N=new globalThis.Float16Array(E.buffer,E.byteOffset,E.length);else throw new TypeError(`A ${D} tensor's data must be type of ${V}`)}else if(L=E,Array.isArray(y)){if(y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let V=typeof y[0];if(V==="string")D="string",N=y;else if(V==="boolean")D="bool",N=Uint8Array.from(y);else throw new TypeError(`Invalid element type of data array: ${V}.`)}else if(y instanceof Uint8ClampedArray)D="uint8",N=Uint8Array.from(y);else{let V=J.get(y.constructor);if(V===void 0)throw new TypeError(`Unsupported type for tensor data: ${y.constructor}.`);D=V,N=y}if(L===void 0)L=[N.length];else if(!Array.isArray(L))throw new TypeError("A tensor's dims must be a number array");P=L,this.cpuData=N,this.dataLocation="cpu"}let G=Pe(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 yt(y,E)}static fromTexture(y,E){return $t(y,E)}static fromGpuBuffer(y,E){return vt(y,E)}static fromMLTensor(y,E){return Ye(y,E)}static fromPinnedBuffer(y,E,A){return St(y,E,A)}toDataURL(y){return tt(this,y)}toImageData(y){return dt(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 ot(this,y)}}}),et,vr=S(()=>{xt(),et=We}),qt,Ot,ct,Tt,zt,Lt,ls=S(()=>{Ve(),qt=(y,E)=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeStamp(`${y}::ORT::${E}`)},Ot=(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}`),qt("CPU",G);return}A[P].includes("TRACE_FUNC")&&(D=!0)}},ct=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||Ot("BEGIN",y)},Tt=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||Ot("END",y)},zt=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.time(`ORT::${y}`)},Lt=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeEnd(`ORT::${y}`)}}),Ne,Wt=S(()=>{_e(),vr(),ls(),Ne=class _f{constructor(E){this.handler=E}async run(E,A,D){ct(),zt("InferenceSession.run");let P={},G={};if(typeof E!="object"||E===null||E instanceof et||Array.isArray(E))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let N=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof et)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");N=!1;for(let ne of A){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);P[ne]=null}if(typeof D=="object"&&D!==null)G=D;else if(typeof D<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1,oe=Object.getOwnPropertyNames(A);for(let Y of this.outputNames)if(oe.indexOf(Y)!==-1){let K=A[Y];(K===null||K instanceof et)&&(ne=!0,N=!1,P[Y]=K)}if(ne){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 ne of this.inputNames)if(typeof E[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(N)for(let ne of this.outputNames)P[ne]=null;let L=await this.handler.run(E,P,G),V={};for(let ne in L)if(Object.hasOwnProperty.call(L,ne)){let oe=L[ne];oe instanceof et?V[ne]=oe:V[ne]=new et(oe.type,oe.data,oe.dims)}return Lt("InferenceSession.run"),Tt(),V}async release(){return this.handler.dispose()}static async create(E,A,D,P){ct(),zt("InferenceSession.create");let G,N={};if(typeof E=="string"){if(G=E,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(E instanceof Uint8Array){if(G=E,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(E instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&E instanceof SharedArrayBuffer){let oe=E,Y=0,K=E.byteLength;if(typeof A=="object"&&A!==null)N=A;else if(typeof A=="number"){if(Y=A,!Number.isSafeInteger(Y))throw new RangeError("'byteOffset' must be an integer.");if(Y<0||Y>=oe.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${oe.byteLength}).`);if(K=E.byteLength-Y,typeof D=="number"){if(K=D,!Number.isSafeInteger(K))throw new RangeError("'byteLength' must be an integer.");if(K<=0||Y+K>oe.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${oe.byteLength-Y}].`);if(typeof P=="object"&&P!==null)N=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(oe,Y,K)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[L,V]=await ee(N),ne=await L.createInferenceSessionHandler(G,V);return Lt("InferenceSession.create"),Tt(),new _f(ne)}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}}}),Bt,cr=S(()=>{Wt(),Bt=Ne}),Ht=S(()=>{}),Nt=S(()=>{}),jt=S(()=>{}),Mr=S(()=>{}),sr={};F(sr,{InferenceSession:()=>Bt,TRACE:()=>qt,TRACE_EVENT_BEGIN:()=>zt,TRACE_EVENT_END:()=>Lt,TRACE_FUNC_BEGIN:()=>ct,TRACE_FUNC_END:()=>Tt,Tensor:()=>et,env:()=>me,registerBackend:()=>se});var ut=S(()=>{ae(),Ze(),cr(),vr(),Ht(),Nt(),ls(),jt(),Mr()}),us=S(()=>{}),hn={};F(hn,{default:()=>pn});var ds,cs,pn,Ki=S(()=>{Mn(),nr(),gs(),ds="ort-wasm-proxy-worker",cs=globalThis.self?.name===ds,cs&&(self.onmessage=y=>{let{type:E,in:A}=y.data;try{switch(E){case"init-wasm":vs(A.wasm).then(()=>{Gs(A).then(()=>{postMessage({type:E})},D=>{postMessage({type:E,err:D})})},D=>{postMessage({type:E,err:D})});break;case"init-ep":{let{epName:D,env:P}=A;qs(P,D).then(()=>{postMessage({type:E})},G=>{postMessage({type:E,err:G})});break}case"copy-from":{let{buffer:D}=A,P=Qe(D);postMessage({type:E,out:P});break}case"create":{let{model:D,options:P}=A;hr(D,P).then(G=>{postMessage({type:E,out:G})},G=>{postMessage({type:E,err:G})});break}case"release":js(A),postMessage({type:E});break;case"run":{let{sessionId:D,inputIndices:P,inputs:G,outputIndices:N,options:L}=A;j(D,P,G,N,new Array(N.length).fill(null),L).then(V=>{V.some(ne=>ne[3]!=="cpu")?postMessage({type:E,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:E,out:V},Ks([...G,...V]))},V=>{postMessage({type:E,err:V})});break}case"end-profiling":Zr(A),postMessage({type:E});break;default:}}catch(D){postMessage({type:E,err:D})}}),pn=cs?null:y=>new Worker(y??pt,{type:"classic",name:ds})}),fn,mn,pt,hs,Vr,gn,yn,ps,wn,fs,vn,ms,_n,gs=S(()=>{us(),fn=typeof location>"u"?void 0:location.origin,mn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,pt=mn(),hs=()=>{if(pt&&!pt.startsWith("blob:"))return pt.substring(0,pt.lastIndexOf("/")+1)},Vr=(y,E)=>{try{let A=E??pt;return(A?new URL(y,A):new URL(y)).origin===fn}catch{return!1}},gn=(y,E)=>{let A=E??pt;try{return(A?new URL(y,A):new URL(y)).href}catch{return}},yn=(y,E)=>`${E??"./"}${y}`,ps=async y=>{let E=await(await fetch(y,{credentials:"same-origin"})).blob();return URL.createObjectURL(E)},wn=async y=>(await import(y)).default,fs=(Ki(),ie(hn)).default,vn=async()=>{if(!pt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Vr(pt))return[void 0,fs()];let y=await ps(pt);return[y,fs(y)]},ms=void 0,_n=async(y,E,A,D)=>{let P=ms&&!(y||E);if(P)if(pt)P=Vr(pt)||D&&!A;else if(D&&!A)P=!0;else throw new Error("cannot determine the script source URL.");if(P)return[void 0,ms];{let G="ort-wasm-simd-threaded.mjs",N=y??gn(G,E),L=A&&N&&!Vr(N,E),V=L?await ps(N):N??yn(G,E);return[L?V:void 0,await wn(V)]}}}),ys,Gr,_r,ws,bn,Sn,Tn,vs,De,nr=S(()=>{gs(),Gr=!1,_r=!1,ws=!1,bn=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Sn=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Tn=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},vs=async y=>{if(Gr)return Promise.resolve();if(_r)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ws)throw new Error("previous call to 'initializeWebAssembly()' failed.");_r=!0;let E=y.initTimeout,A=y.numThreads;if(y.simd!==!1){if(y.simd==="relaxed"){if(!Tn())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Sn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let D=bn();A>1&&!D&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+A+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),y.numThreads=A=1);let P=y.wasmPaths,G=typeof P=="string"?P:void 0,N=P?.mjs,L=N?.href??N,V=P?.wasm,ne=V?.href??V,oe=y.wasmBinary,[Y,K]=await _n(L,G,A>1,!!oe||!!ne),Te=!1,U=[];if(E>0&&U.push(new Promise(de=>{setTimeout(()=>{Te=!0,de()},E)})),U.push(new Promise((de,ft)=>{let Ue={numThreads:A};if(oe)Ue.wasmBinary=oe,Ue.locateFile=Ee=>Ee;else if(ne||G)Ue.locateFile=Ee=>ne??G+Ee;else if(L&&L.indexOf("blob:")!==0)Ue.locateFile=Ee=>new URL(Ee,L).href;else if(Y){let Ee=hs();Ee&&(Ue.locateFile=Fe=>Ee+Fe)}K(Ue).then(Ee=>{_r=!1,Gr=!0,ys=Ee,de(),Y&&URL.revokeObjectURL(Y)},Ee=>{_r=!1,ws=!0,ft(Ee)})})),await Promise.race(U),Te)throw new Error(`WebAssembly backend initializing failed due to timeout: ${E}ms`)},De=()=>{if(Gr&&ys)return ys;throw new Error("WebAssembly is not initialized yet.")}}),Et,qr,Ce,_s=S(()=>{nr(),Et=(y,E)=>{let A=De(),D=A.lengthBytesUTF8(y)+1,P=A._malloc(D);return A.stringToUTF8(y,P,D),E.push(P),P},qr=(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 N=E?E+P:P;if(typeof G=="object")qr(G,N+".",A,D);else if(typeof G=="string"||typeof G=="number")D(N,G.toString());else if(typeof G=="boolean")D(N,G?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof G}`)})},Ce=y=>{let E=De(),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")),N=E.getValue(P+D,"*"),L=N?E.UTF8ToString(N):"";throw new Error(`${y} ERROR_CODE: ${G}, ERROR_MESSAGE: ${L}`)}finally{E.stackRestore(A)}}}),En,Qi=S(()=>{nr(),_s(),En=y=>{let E=De(),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=Et(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&&qr(y.extra,"",new WeakSet,(N,L)=>{let V=Et(N,D),ne=Et(L,D);E._OrtAddRunConfigEntry(A,V,ne)!==0&&Ce(`Can't set a run config entry: ${N} - ${L}.`)}),[A,D]}catch(G){throw A!==0&&E._OrtReleaseRunOptions(A),D.forEach(N=>E._free(N)),G}}}),$n,xn,Cn,Jt,kn,Rn,Xi=S(()=>{nr(),_s(),$n=y=>{switch(y){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${y}`)}},xn=y=>{switch(y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${y}`)}},Cn=y=>{y.extra||(y.extra={}),y.extra.session||(y.extra.session={});let E=y.extra.session;E.use_ort_model_bytes_directly||(E.use_ort_model_bytes_directly="1"),y.executionProviders&&y.executionProviders.some(A=>(typeof A=="string"?A:A.name)==="webgpu")&&(y.enableMemPattern=!1)},Jt=(y,E,A,D)=>{let P=Et(E,D),G=Et(A,D);De()._OrtAddSessionConfigEntry(y,P,G)!==0&&Ce(`Can't set a session config entry: ${E} - ${A}.`)},kn=async(y,E,A)=>{let D=E.executionProviders;for(let P of D){let G=typeof P=="string"?P:P.name,N=[];switch(G){case"webnn":if(G="WEBNN",Jt(y,"session.disable_quant_qdq","1",A),Jt(y,"session.disable_qdq_constant_folding","1",A),typeof P!="string"){let Y=P?.deviceType;Y&&Jt(y,"deviceType",Y,A)}break;case"webgpu":if(G="JS",typeof P!="string"){let Y=P;if(Y?.preferredLayout){if(Y.preferredLayout!=="NCHW"&&Y.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${Y.preferredLayout}`);Jt(y,"preferredLayout",Y.preferredLayout,A)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${G}`)}let L=Et(G,A),V=N.length,ne=0,oe=0;if(V>0){ne=De()._malloc(V*De().PTR_SIZE),A.push(ne),oe=De()._malloc(V*De().PTR_SIZE),A.push(oe);for(let Y=0;Y<V;Y++)De().setValue(ne+Y*De().PTR_SIZE,N[Y][0],"*"),De().setValue(oe+Y*De().PTR_SIZE,N[Y][1],"*")}await De()._OrtAppendExecutionProvider(y,L,ne,oe,V)!==0&&Ce(`Can't append execution provider: ${G}.`)}},Rn=async y=>{let E=De(),A=0,D=[],P=y||{};Cn(P);try{let G=$n(P.graphOptimizationLevel??"all"),N=xn(P.executionMode??"sequential"),L=typeof P.logId=="string"?Et(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 ne=P.logVerbosityLevel??0;if(!Number.isInteger(ne)||ne<0||ne>4)throw new Error(`log verbosity level is not valid: ${ne}`);let oe=typeof P.optimizedModelFilePath=="string"?Et(P.optimizedModelFilePath,D):0;if(A=E._OrtCreateSessionOptions(G,!!P.enableCpuMemArena,!!P.enableMemPattern,N,!!P.enableProfiling,0,L,V,ne,oe),A===0&&Ce("Can't create session options."),P.executionProviders&&await kn(A,P,D),P.enableGraphCapture!==void 0){if(typeof P.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${P.enableGraphCapture}`);Jt(A,"enableGraphCapture",P.enableGraphCapture.toString(),D)}if(P.freeDimensionOverrides)for(let[Y,K]of Object.entries(P.freeDimensionOverrides)){if(typeof Y!="string")throw new Error(`free dimension override name must be a string: ${Y}`);if(typeof K!="number"||!Number.isInteger(K)||K<0)throw new Error(`free dimension override value must be a non-negative integer: ${K}`);let Te=Et(Y,D);E._OrtAddFreeDimensionOverride(A,Te,K)!==0&&Ce(`Can't set a free dimension override: ${Y} - ${K}.`)}return P.extra!==void 0&&qr(P.extra,"",new WeakSet,(Y,K)=>{Jt(A,Y,K,D)}),[A,D]}catch(G){throw A!==0&&E._OrtReleaseSessionOptions(A)!==0&&Ce("Can't release session options."),D.forEach(N=>E._free(N)),G}}}),ir,ar,or,bs,Ss,Ts,Es,Vs,Ie=S(()=>{ir=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}`)}},ar=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}`)}},or=(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},bs=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}`)}},Ss=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}`)}},Ts=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Es=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint64"||y==="int8"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Vs=y=>{switch(y){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${y}`)}}}),$s,An=S(()=>{us(),$s=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 N=0;for(;;){let{done:L,value:V}=await P.read();if(L)break;let ne=V.byteLength;new Uint8Array(G,N,ne).set(V),N+=ne}return new Uint8Array(G,0,D)}}else return y instanceof Blob?new Uint8Array(await y.arrayBuffer()):y instanceof Uint8Array?y:new Uint8Array(y)}}),In,Gs,qs,Or,Ws,Hs,Qe,hr,js,Pr,j,Zr,Ks,Mn=S(()=>{ut(),Qi(),Xi(),Ie(),nr(),_s(),An(),In=(y,E)=>{De()._OrtInit(y,E)!==0&&Ce("Can't initialize onnxruntime.")},Gs=async y=>{In(y.wasm.numThreads,Ss(y.logLevel))},qs=async(y,E)=>{De().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")},Or=new Map,Ws=y=>{let E=De(),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)}},Hs=(y,E)=>{let A=De(),D=A.stackSave(),P=0;try{let G=A.PTR_SIZE,N=A.stackAlloc(2*G);A._OrtGetInputOutputMetadata(y,E,N,N+G)!==0&&Ce("Can't get session input/output metadata.");let L=Number(A.getValue(N,"*"));P=Number(A.getValue(N+G,"*"));let V=A.HEAP32[P/4];if(V===0)return[L,0];let ne=A.HEAPU32[P/4+1],oe=[];for(let Y=0;Y<ne;Y++){let K=Number(A.getValue(P+8+Y*G,"*"));oe.push(K!==0?A.UTF8ToString(K):Number(A.getValue(P+8+(Y+ne)*G,"*")))}return[L,V,oe]}finally{A.stackRestore(D),P!==0&&A._OrtFree(P)}},Qe=y=>{let E=De(),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]},hr=async(y,E)=>{let A,D,P=De();Array.isArray(y)?[A,D]=y:y.buffer===P.HEAPU8.buffer?[A,D]=[y.byteOffset,y.byteLength]:[A,D]=Qe(y);let G=0,N=0,L=[],V=[],ne=[];try{if([N,L]=await Rn(E),E?.externalData&&P.mountExternalData){let Ee=[];for(let Fe of E.externalData){let we=typeof Fe=="string"?Fe:Fe.path;Ee.push($s(typeof Fe=="string"?Fe:Fe.data).then(Ut=>{P.mountExternalData(we,Ut)}))}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 Fe=Ee,we=Fe?.context,Ut=Fe?.gpuDevice,Ft=Fe?.deviceType,Lr=Fe?.powerPreference;we?P.currentContext=we:Ut?P.currentContext=await P.webnnCreateMLContext(Ut):P.currentContext=await P.webnnCreateMLContext({deviceType:Ft,powerPreference:Lr})}else P.currentContext=await P.webnnCreateMLContext();break}G=await P._OrtCreateSession(A,D,N),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[oe,Y]=Ws(G),K=!!E?.enableGraphCapture,Te=[],U=[],de=[],ft=[],Ue=[];for(let Ee=0;Ee<oe;Ee++){let[Fe,we,Ut]=Hs(G,Ee);Fe===0&&Ce("Can't get an input name."),V.push(Fe);let Ft=P.UTF8ToString(Fe);Te.push(Ft),de.push(we===0?{name:Ft,isTensor:!1}:{name:Ft,isTensor:!0,type:ar(we),shape:Ut})}for(let Ee=0;Ee<Y;Ee++){let[Fe,we,Ut]=Hs(G,Ee+oe);Fe===0&&Ce("Can't get an output name."),ne.push(Fe);let Ft=P.UTF8ToString(Fe);U.push(Ft),ft.push(we===0?{name:Ft,isTensor:!1}:{name:Ft,isTensor:!0,type:ar(we),shape:Ut})}return Or.set(G,[G,V,ne,null,K,!1]),[G,Te,U,de,ft]}catch(oe){throw V.forEach(Y=>P._OrtFree(Y)),ne.forEach(Y=>P._OrtFree(Y)),G!==0&&P._OrtReleaseSession(G)!==0&&Ce("Can't release session."),oe}finally{P._free(A),N!==0&&P._OrtReleaseSessionOptions(N)!==0&&Ce("Can't release session options."),L.forEach(oe=>P._free(oe)),P.unmountExternalData?.()}},js=y=>{let E=De(),A=Or.get(y);if(!A)throw new Error(`cannot release session. invalid session id: ${y}`);let[D,P,G,N,L]=A;N&&(L&&E._OrtClearBoundOutputs(N.handle)!==0&&Ce("Can't clear bound outputs."),E._OrtReleaseBinding(N.handle)!==0&&Ce("Can't release IO binding.")),E.jsepOnReleaseSession?.(y),E.webnnOnReleaseSession?.(y),E.webgpuOnReleaseSession?.(y),P.forEach(V=>E._OrtFree(V)),G.forEach(V=>E._OrtFree(V)),E._OrtReleaseSession(D)!==0&&Ce("Can't release session."),Or.delete(y)},Pr=async(y,E,A,D,P,G,N=!1)=>{if(!y){E.push(0);return}let L=De(),V=L.PTR_SIZE,ne=y[0],oe=y[1],Y=y[3],K=Y,Te,U;if(ne==="string"&&(Y==="gpu-buffer"||Y==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(N&&Y!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${G} when enableGraphCapture is true.`);if(Y==="gpu-buffer"){let Ue=y[2].gpuBuffer;U=or(ir(ne),oe);{let Ee=L.jsepRegisterBuffer;if(!Ee)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Te=Ee(D,G,Ue,U)}}else if(Y==="ml-tensor"){let Ue=y[2].mlTensor;U=or(ir(ne),oe);let Ee=L.webnnRegisterMLTensor;if(!Ee)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Te=Ee(D,Ue,ir(ne),oe)}else{let Ue=y[2];if(Array.isArray(Ue)){U=V*Ue.length,Te=L._malloc(U),A.push(Te);for(let Ee=0;Ee<Ue.length;Ee++){if(typeof Ue[Ee]!="string")throw new TypeError(`tensor data at index ${Ee} is not a string`);L.setValue(Te+Ee*V,Et(Ue[Ee],A),"*")}}else{let Ee=L.webnnIsGraphInput,Fe=L.webnnIsGraphOutput;if(ne!=="string"&&Ee&&Fe){let we=L.UTF8ToString(P);if(Ee(D,we)||Fe(D,we)){let Ut=ir(ne);U=or(Ut,oe),K="ml-tensor";let Ft=L.webnnCreateTemporaryTensor,Lr=L.webnnUploadTensor;if(!Ft||!Lr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let ss=await Ft(D,Ut,oe);Lr(ss,new Uint8Array(Ue.buffer,Ue.byteOffset,Ue.byteLength)),Te=ss}else U=Ue.byteLength,Te=L._malloc(U),A.push(Te),L.HEAPU8.set(new Uint8Array(Ue.buffer,Ue.byteOffset,U),Te)}else U=Ue.byteLength,Te=L._malloc(U),A.push(Te),L.HEAPU8.set(new Uint8Array(Ue.buffer,Ue.byteOffset,U),Te)}}let de=L.stackSave(),ft=L.stackAlloc(4*oe.length);try{oe.forEach((Ee,Fe)=>L.setValue(ft+Fe*V,Ee,V===4?"i32":"i64"));let Ue=L._OrtCreateTensor(ir(ne),Te,U,ft,oe.length,Vs(K));Ue===0&&Ce(`Can't create tensor for input/output. session=${D}, index=${G}.`),E.push(Ue)}finally{L.stackRestore(de)}},j=async(y,E,A,D,P,G)=>{let N=De(),L=N.PTR_SIZE,V=Or.get(y);if(!V)throw new Error(`cannot run inference. invalid session id: ${y}`);let ne=V[0],oe=V[1],Y=V[2],K=V[3],Te=V[4];V[5];let U=E.length,de=D.length,ft=0,Ue=[],Ee=[],Fe=[],we=[],Ut=[],Ft=N.stackSave(),Lr=N.stackAlloc(U*L),ss=N.stackAlloc(U*L),nn=N.stackAlloc(de*L),Un=N.stackAlloc(de*L);try{[ft,Ue]=En(G),zt("wasm prepareInputOutputTensor");for(let Ge=0;Ge<U;Ge++)await Pr(A[Ge],Ee,we,y,oe[E[Ge]],E[Ge],Te);for(let Ge=0;Ge<de;Ge++)await Pr(P[Ge],Fe,we,y,Y[D[Ge]],U+D[Ge],Te);Lt("wasm prepareInputOutputTensor");for(let Ge=0;Ge<U;Ge++)N.setValue(Lr+Ge*L,Ee[Ge],"*"),N.setValue(ss+Ge*L,oe[E[Ge]],"*");for(let Ge=0;Ge<de;Ge++)N.setValue(nn+Ge*L,Fe[Ge],"*"),N.setValue(Un+Ge*L,Y[D[Ge]],"*");N.jsepOnRunStart?.(ne),N.webnnOnRunStart?.(ne);let _t;_t=await N._OrtRun(ne,ss,Lr,U,Un,de,nn,ft),_t!==0&&Ce("failed to call OrtRun().");let fr=[],Fn=[];zt("wasm ProcessOutputTensor");for(let Ge=0;Ge<de;Ge++){let pr=Number(N.getValue(nn+Ge*L,"*"));if(pr===Fe[Ge]||Ut.includes(Fe[Ge])){fr.push(P[Ge]),pr!==Fe[Ge]&&N._OrtReleaseTensor(pr)!==0&&Ce("Can't release tensor.");continue}let yi=N.stackSave(),Tr=N.stackAlloc(4*L),Rs=!1,Ct,Yt=0;try{N._OrtGetTensorData(pr,Tr,Tr+L,Tr+2*L,Tr+3*L)!==0&&Ce(`Can't access output tensor data on index ${Ge}.`);let an=L===4?"i32":"i64",As=Number(N.getValue(Tr,an));Yt=N.getValue(Tr+L,"*");let Vn=N.getValue(Tr+L*2,"*"),wi=Number(N.getValue(Tr+L*3,an)),Pt=[];for(let kt=0;kt<wi;kt++)Pt.push(Number(N.getValue(Vn+kt*L,an)));N._OrtFree(Vn)!==0&&Ce("Can't free memory for tensor dims.");let Er=Pt.reduce((kt,bt)=>kt*bt,1);Ct=ar(As);let ns=K?.outputPreferredLocations[D[Ge]];if(Ct==="string"){if(ns==="gpu-buffer"||ns==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let kt=[];for(let bt=0;bt<Er;bt++){let mr=N.getValue(Yt+bt*L,"*"),vi=N.getValue(Yt+(bt+1)*L,"*"),_i=bt===Er-1?void 0:vi-mr;kt.push(N.UTF8ToString(mr,_i))}fr.push([Ct,Pt,kt,"cpu"])}else if(ns==="gpu-buffer"&&Er>0){let kt=N.jsepGetBuffer;if(!kt)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let bt=kt(Yt),mr=or(As,Er);if(mr===void 0||!Ts(Ct))throw new Error(`Unsupported data type: ${Ct}`);Rs=!0,fr.push([Ct,Pt,{gpuBuffer:bt,download:N.jsepCreateDownloader(bt,mr,Ct),dispose:()=>{N._OrtReleaseTensor(pr)!==0&&Ce("Can't release tensor.")}},"gpu-buffer"])}else if(ns==="ml-tensor"&&Er>0){let kt=N.webnnEnsureTensor,bt=N.webnnIsGraphInputOutputTypeSupported;if(!kt||!bt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(or(As,Er)===void 0||!Es(Ct))throw new Error(`Unsupported data type: ${Ct}`);if(!bt(y,Ct,!1))throw new Error(`preferredLocation "ml-tensor" for ${Ct} output is not supported by current WebNN Context.`);let mr=await kt(y,Yt,As,Pt,!1);Rs=!0,fr.push([Ct,Pt,{mlTensor:mr,download:N.webnnCreateMLTensorDownloader(Yt,Ct),dispose:()=>{N.webnnReleaseTensorId(Yt),N._OrtReleaseTensor(pr)}},"ml-tensor"])}else if(ns==="ml-tensor-cpu-output"&&Er>0){let kt=N.webnnCreateMLTensorDownloader(Yt,Ct)(),bt=fr.length;Rs=!0,Fn.push((async()=>{let mr=[bt,await kt];return N.webnnReleaseTensorId(Yt),N._OrtReleaseTensor(pr),mr})()),fr.push([Ct,Pt,[],"cpu"])}else{let kt=bs(Ct),bt=new kt(Er);new Uint8Array(bt.buffer,bt.byteOffset,bt.byteLength).set(N.HEAPU8.subarray(Yt,Yt+bt.byteLength)),fr.push([Ct,Pt,bt,"cpu"])}}finally{N.stackRestore(yi),Ct==="string"&&Yt&&N._free(Yt),Rs||N._OrtReleaseTensor(pr)}}K&&!Te&&(N._OrtClearBoundOutputs(K.handle)!==0&&Ce("Can't clear bound outputs."),Or.set(y,[ne,oe,Y,K,Te,!1]));for(let[Ge,pr]of await Promise.all(Fn))fr[Ge][2]=pr;return Lt("wasm ProcessOutputTensor"),fr}finally{N.webnnOnRunEnd?.(ne),N.stackRestore(Ft),Ee.forEach(_t=>N._OrtReleaseTensor(_t)),Fe.forEach(_t=>N._OrtReleaseTensor(_t)),we.forEach(_t=>N._free(_t)),ft!==0&&N._OrtReleaseRunOptions(ft),Ue.forEach(_t=>N._free(_t))}},Zr=y=>{let E=De(),A=Or.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)},Ks=y=>{let E=[];for(let A of y){let D=A[2];!Array.isArray(D)&&"buffer"in D&&E.push(D.buffer)}return E}}),br,ke,Dr,es,Wr,ts,xs,Cs,Sr,zr,Qs,Xs,Ys,On,Pn,mi,rs,Dn,zn=S(()=>{ut(),Mn(),nr(),gs(),br=()=>!!me.wasm.proxy&&typeof document<"u",Dr=!1,es=!1,Wr=!1,Cs=new Map,Sr=(y,E)=>{let A=Cs.get(y);A?A.push(E):Cs.set(y,[E])},zr=()=>{if(Dr||!es||Wr||!ke)throw new Error("worker not ready")},Qs=y=>{switch(y.data.type){case"init-wasm":Dr=!1,y.data.err?(Wr=!0,xs[1](y.data.err)):(es=!0,xs[0]()),ts&&(URL.revokeObjectURL(ts),ts=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let E=Cs.get(y.data.type);y.data.err?E.shift()[1](y.data.err):E.shift()[0](y.data.out);break}}},Xs=async()=>{if(!es){if(Dr)throw new Error("multiple calls to 'initWasm()' detected.");if(Wr)throw new Error("previous call to 'initWasm()' failed.");if(Dr=!0,br())return new Promise((y,E)=>{ke?.terminate(),vn().then(([A,D])=>{try{ke=D,ke.onerror=G=>E(G),ke.onmessage=Qs,xs=[y,E];let P={type:"init-wasm",in:me};if(!P.in.wasm.wasmPaths&&A){let G=hs();G&&(P.in.wasm.wasmPaths=G)}ke.postMessage(P),ts=A}catch(P){E(P)}},E)});try{await vs(me.wasm),await Gs(me),es=!0}catch(y){throw Wr=!0,y}finally{Dr=!1}}},Ys=async y=>{if(br())return zr(),new Promise((E,A)=>{Sr("init-ep",[E,A]);let D={type:"init-ep",in:{epName:y,env:me}};ke.postMessage(D)});await qs(me,y)},On=async y=>br()?(zr(),new Promise((E,A)=>{Sr("copy-from",[E,A]);let D={type:"copy-from",in:{buffer:y}};ke.postMessage(D,[y.buffer])})):Qe(y),Pn=async(y,E)=>{if(br()){if(E?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return zr(),new Promise((A,D)=>{Sr("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 hr(y,E)},mi=async y=>{if(br())return zr(),new Promise((E,A)=>{Sr("release",[E,A]);let D={type:"release",in:y};ke.postMessage(D)});js(y)},rs=async(y,E,A,D,P,G)=>{if(br()){if(A.some(N=>N[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(P.some(N=>N))throw new Error("pre-allocated output tensor is not supported for proxy.");return zr(),new Promise((N,L)=>{Sr("run",[N,L]);let V=A,ne={type:"run",in:{sessionId:y,inputIndices:E,inputs:V,outputIndices:D,options:G}};ke.postMessage(ne,Ks(V))})}else return j(y,E,A,D,P,G)},Dn=async y=>{if(br())return zr(),new Promise((E,A)=>{Sr("end-profiling",[E,A]);let D={type:"end-profiling",in:y};ke.postMessage(D)});Zr(y)}}),Ln,Js,Zs,en=S(()=>{ut(),zn(),Ie(),us(),An(),Ln=(y,E)=>{switch(y.location){case"cpu":return[y.type,y.dims,y.data,"cpu"];case"gpu-buffer":return[y.type,y.dims,{gpuBuffer:y.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[y.type,y.dims,{mlTensor:y.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${y.location} for ${E()}`)}},Js=y=>{switch(y[3]){case"cpu":return new et(y[0],y[2],y[1]);case"gpu-buffer":{let E=y[0];if(!Ts(E))throw new Error(`not supported data type: ${E} for deserializing GPU tensor`);let{gpuBuffer:A,download:D,dispose:P}=y[2];return et.fromGpuBuffer(A,{dataType:E,dims:y[1],download:D,dispose:P})}case"ml-tensor":{let E=y[0];if(!Es(E))throw new Error(`not supported data type: ${E} for deserializing MLTensor tensor`);let{mlTensor:A,download:D,dispose:P}=y[2];return et.fromMLTensor(A,{dataType:E,dims:y[1],download:D,dispose:P})}default:throw new Error(`invalid data location: ${y[3]}`)}},Zs=class{async fetchModelAndCopyToWasmMemory(y){return On(await $s(y))}async loadModel(y,E){ct();let A;typeof y=="string"?A=await this.fetchModelAndCopyToWasmMemory(y):A=y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Pn(A,E),Tt()}async dispose(){return mi(this.sessionId)}async run(y,E,A){ct();let D=[],P=[];Object.entries(y).forEach(Y=>{let K=Y[0],Te=Y[1],U=this.inputNames.indexOf(K);if(U===-1)throw new Error(`invalid input '${K}'`);D.push(Te),P.push(U)});let G=[],N=[];Object.entries(E).forEach(Y=>{let K=Y[0],Te=Y[1],U=this.outputNames.indexOf(K);if(U===-1)throw new Error(`invalid output '${K}'`);G.push(Te),N.push(U)});let L=D.map((Y,K)=>Ln(Y,()=>`input "${this.inputNames[P[K]]}"`)),V=G.map((Y,K)=>Y?Ln(Y,()=>`output "${this.outputNames[N[K]]}"`):null),ne=await rs(this.sessionId,P,L,N,V,A),oe={};for(let Y=0;Y<ne.length;Y++)oe[this.outputNames[N[Y]]]=G[Y]??Js(ne[Y]);return Tt(),oe}startProfiling(){}endProfiling(){Dn(this.sessionId)}}}),ks={};F(ks,{OnnxruntimeWebAssemblyBackend:()=>rn,initializeFlags:()=>tn,wasmBackend:()=>sn});var tn,rn,sn,Bn=S(()=>{ut(),zn(),en(),tn=()=>{(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))}},rn=class{async init(y){tn(),await Xs(),await Ys(y)}async createInferenceSessionHandler(y,E){let A=new Zs;return await A.loadModel(y,E),A}},sn=new rn}),Nn={};F(Nn,{InferenceSession:()=>Bt,TRACE:()=>qt,TRACE_EVENT_BEGIN:()=>zt,TRACE_EVENT_END:()=>Lt,TRACE_FUNC_BEGIN:()=>ct,TRACE_FUNC_END:()=>Tt,Tensor:()=>et,default:()=>Yi,env:()=>me,registerBackend:()=>se}),ut(),ut(),ut();var gi="1.26.0",Yi=sr;{let y=(Bn(),ie(ks)).wasmBackend;se("cpu",y,10),se("wasm",y,10)}return Object.defineProperty(me.versions,"web",{value:gi,enumerable:!0}),ie(Nn)})();d.exports=s})(lo)),lo.exports}var Lp;function Py(){return Lp||(Lp=1,(function(d){var r=Xr&&Xr.__createBinding||(Object.create?(function(he,H,le,pe){pe===void 0&&(pe=le);var Ve=Object.getOwnPropertyDescriptor(H,le);(!Ve||("get"in Ve?!H.__esModule:Ve.writable||Ve.configurable))&&(Ve={enumerable:!0,get:function(){return H[le]}}),Object.defineProperty(he,pe,Ve)}):(function(he,H,le,pe){pe===void 0&&(pe=le),he[pe]=H[le]})),s=Xr&&Xr.__setModuleDefault||(Object.create?(function(he,H){Object.defineProperty(he,"default",{enumerable:!0,value:H})}):function(he,H){he.default=H}),a=Xr&&Xr.__importStar||function(he){if(he&&he.__esModule)return he;var H={};if(he!=null)for(var le in he)le!=="default"&&Object.prototype.hasOwnProperty.call(he,le)&&r(H,he,le);return s(H,he),H};Object.defineProperty(d,"__esModule",{value:!0}),d.MicVAD=d.getDefaultRealTimeVADOptions=d.ort=d.DEFAULT_MODEL=void 0;const p=a(Oy()),v=Mo(),C=Oo(),R=pi(),S=ji(),F=wf(),z=vf();d.DEFAULT_MODEL="legacy",d.ort=p;const ie="vad.worklet.bundle.min.js",X="silero_vad_v5.onnx",re="silero_vad_legacy.onnx",se=he=>({...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:he,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async H=>{H.getTracks().forEach(le=>{le.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:H=>{H.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});d.getDefaultRealTimeVADOptions=se;const Z=he=>"audioWorklet"in he&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function ee(he,H,le,pe,Ve){await le.audioWorklet.addModule(he),H.processorOptions={...H.processorOptions??{},frameSamples:pe};const me=new AudioWorkletNode(le,"vad-helper-worklet",H);return me.port.onmessage=async Ze=>{const tt=Ze.data;if(!(typeof tt=="object"&&tt&&"message"in tt)){console.error("Invalid message event",tt);return}switch(tt.message){case S.Message.AudioFrame:{if(!("data"in tt&&tt.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const dt=new Float32Array(tt.data);await Ve(dt);break}}},me}async function _e(he,H,le){const pe=new z.Resampler({nativeSampleRate:he.sampleRate,targetSampleRate:16e3,targetFrameSize:H});R.log.debug("using script processor");const me=he.createScriptProcessor(4096,1,1);let Ze=!1;return me.onaudioprocess=async tt=>{if(!Ze){Ze=!0;try{const dt=tt.inputBuffer.getChannelData(0);tt.outputBuffer.getChannelData(0).fill(0);const lt=pe.process(dt);for(const yt of lt)await le(yt)}catch(dt){console.error("Error processing audio:",dt)}finally{Ze=!1}}},me.connect(he.destination),me}class ae{constructor(H,le,pe,Ve,me=!1,Ze=null,tt=null,dt=null,wt=null,lt=null,yt=null,$t="uninitialized",vt=!1){this.options=H,this.frameProcessor=le,this.model=pe,this.frameSamples=Ve,this.listening=me,this.errored=Ze,this._stream=tt,this._audioContext=dt,this._vadNode=wt,this._mediaStreamAudioSourceNode=lt,this._audioProcessorAdapterType=yt,this.initializationState=$t,this.ownsAudioContext=vt,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=Ye=>{this.initializationState="errored",this.errored=Ye},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(Ye){throw Ye instanceof Error?this.setErrored(Ye.message):this.setErrored(String(Ye)),Ye}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"?Z(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await ee(this.options.baseAssetPath+ie,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await _e(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:Ye,audioContext:St,vadNode:He}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ye);const at=new MediaStreamAudioSourceNode(St,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=at,at.connect(He);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:Ye,mediaStreamAudioSourceNode:St}=this.getAudioInstances();await this.options.pauseStream(Ye),St.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{R.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ye}=this.getAudioInstances();Ye instanceof AudioWorkletNode&&Ye.port.postMessage(S.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await this._audioContext?.close()},this.setOptions=Ye=>{this.frameProcessor.setOptions(Ye)},this.processFrame=async Ye=>{await this.frameProcessor.process(Ye,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ye=>{switch(Ye.msg){case S.Message.FrameProcessed:this.options.onFrameProcessed(Ye.probs,Ye.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(Ye.audio);break}}}static async new(H={}){const le={...(0,d.getDefaultRealTimeVADOptions)(H.model??d.DEFAULT_MODEL),...H};(0,C.validateOptions)(le),d.ort.env.wasm.wasmPaths=le.onnxWASMBasePath,le.ortConfig!==void 0&&le.ortConfig(d.ort);const pe=le.model==="v5"?X:re,Ve=le.baseAssetPath+pe,me=le.model==="v5"?F.SileroV5.new:F.SileroLegacy.new;let Ze;try{Ze=await me(d.ort,()=>(0,v.defaultModelFetcher)(Ve))}catch(yt){throw console.error(`Encountered an error while loading model file ${Ve}`),yt}const tt=le.model==="v5"?512:1536,dt=tt/16,wt=new C.FrameProcessor(Ze.process,Ze.reset_state,{positiveSpeechThreshold:le.positiveSpeechThreshold,negativeSpeechThreshold:le.negativeSpeechThreshold,redemptionMs:le.redemptionMs,preSpeechPadMs:le.preSpeechPadMs,minSpeechMs:le.minSpeechMs,submitUserSpeechOnPause:le.submitUserSpeechOnPause},dt),lt=new ae(le,wt,Ze,tt);if(le.startOnLoad)try{await lt.start()}catch(yt){throw console.error("Error starting micVad",yt),yt}return lt}}d.MicVAD=ae})(Xr)),Xr}var Bp;function Np(){return Bp||(Bp=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=mf();Object.defineProperty(d,"baseAssetPath",{enumerable:!0,get:function(){return r.baseAssetPath}});var s=Mo();Object.defineProperty(d,"defaultModelFetcher",{enumerable:!0,get:function(){return s.defaultModelFetcher}});var a=Oo();Object.defineProperty(d,"FrameProcessor",{enumerable:!0,get:function(){return a.FrameProcessor}});var p=ji();Object.defineProperty(d,"Message",{enumerable:!0,get:function(){return p.Message}});var v=Iy();Object.defineProperty(d,"NonRealTimeVAD",{enumerable:!0,get:function(){return v.NonRealTimeVAD}});const C=My();d.utils={audioFileToArray:C.audioFileToArray,minFramesForTargetMS:C.minFramesForTargetMS,arrayBufferToBase64:C.arrayBufferToBase64,encodeWAV:C.encodeWAV};var R=Py();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}})})(io)),io}var Up;function Dy(){return Up||(Up=1,(function(d){Object.defineProperty(d,"__esModule",{value:!0}),d.useMicVAD=d.getDefaultReactRealTimeVADOptions=d.utils=void 0;const r=Np(),s=ce;var a=Np();Object.defineProperty(d,"utils",{enumerable:!0,get:function(){return a.utils}});const p={userSpeakingThreshold:.6},v=S=>({...(0,r.getDefaultRealTimeVADOptions)(S),...p});d.getDefaultReactRealTimeVADOptions=v;function C(S){const F=S.model??r.DEFAULT_MODEL,z={...(0,d.getDefaultReactRealTimeVADOptions)(F),...S},ie={userSpeakingThreshold:z.userSpeakingThreshold},X={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&&(X.ortConfig=z.ortConfig),z.audioContext&&(X.audioContext=z.audioContext),[ie,X]}function R(S){const[F,z]=C(S),ie=S.model??r.DEFAULT_MODEL,[X,re]=(0,s.useState)(!1),[se,Z]=(0,s.useState)(!0),[ee,_e]=(0,s.useState)(!1),[ae,he]=(0,s.useState)(!1),[H,le]=(0,s.useState)(null),pe=(0,s.useRef)(z.onFrameProcessed),Ve=(0,s.useRef)(z.onSpeechEnd),me=(0,s.useRef)(z.onSpeechStart),Ze=(0,s.useRef)(z.onSpeechRealStart),tt=(0,s.useRef)(z.onVADMisfire),dt=(0,s.useRef)(z.getStream);(0,s.useEffect)(()=>{pe.current=z.onFrameProcessed,Ve.current=z.onSpeechEnd,me.current=z.onSpeechStart,Ze.current=z.onSpeechRealStart,tt.current=z.onVADMisfire},[z.onFrameProcessed,z.onSpeechEnd,z.onSpeechStart,z.onSpeechRealStart,z.onVADMisfire]),(0,s.useEffect)(()=>{dt.current=z.getStream},[z.getStream]);const wt=z.getStream.toString();(0,s.useEffect)(()=>{let vt=null,Ye=!1;return(async()=>{try{Z(!0),_e(!1);const He={...z,onFrameProcessed:(at,J)=>{const Oe=at.isSpeech>F.userSpeakingThreshold;re(Oe),pe.current(at,J)},onSpeechEnd:at=>{Ve.current(at)},onSpeechStart:()=>{me.current()},onSpeechRealStart:()=>{Ze.current()},onVADMisfire:()=>{tt.current()},getStream:()=>dt.current()};if(vt=await r.MicVAD.new(He),Ye){await vt.destroy();return}le(vt),z.startOnLoad&&(await vt.start(),he(!0)),Z(!1)}catch(He){Z(!1),He instanceof Error?_e(He.message):_e(String(He))}})().catch(()=>{}),function(){Ye=!0,vt&&vt.destroy(),!se&&!ee&&he(!1)}},[wt,ie]);const lt=(0,s.useCallback)(async()=>{!se&&!ee&&(await H?.pause(),he(!1))},[se,ee,H]),yt=(0,s.useCallback)(async()=>{!se&&!ee&&(await H?.start(),he(!0))},[se,ee,H]),$t=(0,s.useCallback)(async()=>{ae?await lt():await yt()},[ae,lt,yt]);return{listening:ae,errored:ee,loading:se,userSpeaking:X,pause:lt,start:yt,toggle:$t}}d.useMicVAD=R})(no)),no}var zy=Dy();const Fp={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},Vi=16e3,bf=512,Sf=700,Ly=300,By=bf/Vi*1e3,Ny=Math.ceil(Sf/By);function Uy(d={}){const{onAudioChunk:r,onAudioEnd:s,onSpeechStart:a,onSpeechEnd:p,onVADMisfire:v,onError:C,enabled:R=!0,interruptOnSpeechStart:S=!0,forceAudioMp4:F=!1,preloadStream:z=!0}=d,{sendAudioChunk:ie,endAudioStream:X,interrupt:re}=dn(),[se,Z]=ce.useState(!1),[ee,_e]=ce.useState(null),ae=ce.useRef(null),he=ce.useRef(null),H=ce.useRef(null),le=ce.useRef(!1),pe=ce.useRef(null),Ve=ce.useRef([]),me=ce.useRef(!1),Ze=ce.useCallback(()=>{if(!(typeof window>"u")){if(!H.current){const Pe=window.AudioContext||window.webkitAudioContext;if(!Pe)return;H.current=new Pe({sampleRate:Vi})}H.current.state==="suspended"&&H.current.resume().catch(()=>{}),me.current=!0}},[]);ce.useEffect(()=>{!R||!z||typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||navigator.mediaDevices.getUserMedia({audio:Fp}).then(Pe=>{ae.current=Pe,_e(null)}).catch(Pe=>{_e("permission_denied"),C?.(Pe)})},[R,C,z]);const tt=ce.useCallback(async()=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone APIs are unavailable in this browser");if(ae.current&&ae.current.getTracks()[0]?.readyState==="live")return ae.current;const Pe=await navigator.mediaDevices.getUserMedia({audio:Fp});return ae.current=Pe,_e(null),Pe},[]),dt=ce.useCallback(async Pe=>{Pe.getTracks().forEach(ot=>{ot.enabled=!1})},[]),wt=ce.useCallback(async()=>ae.current&&ae.current.getTracks()[0]?.readyState==="live"?(ae.current.getTracks().forEach(Pe=>{Pe.enabled=!0}),ae.current):tt(),[tt]),lt=ce.useCallback(()=>{const Pe=Ve.current;if(!Pe.length)return{samples:new Float32Array(0),duration:0};const ot=Pe.reduce((xt,et)=>xt+et.length,0),Je=new Float32Array(ot);let We=0;for(const xt of Pe)Je.set(xt,We),We+=xt.length;return{samples:Je,duration:ot/Vi}},[]),yt=ce.useCallback(()=>{const Pe=ae.current,ot=H.current;if(!Pe||!ot||he.current)return;const{samples:Je,duration:We}=lt();Ve.current=[];const xt=!F&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/mp4")?"audio/mp4":"";try{const et=ot.createMediaStreamDestination();if(Je.length>0){const Ot=ot.createBuffer(1,Je.length,Vi);Ot.getChannelData(0).set(Je);const ct=ot.createBufferSource();ct.buffer=Ot,ct.connect(et),ct.start(0)}const vr=ot.createMediaStreamSource(Pe);if(We>0){const Ot=ot.createDelay(We+.1);Ot.delayTime.value=We,vr.connect(Ot).connect(et)}else vr.connect(et);const qt=new MediaRecorder(et.stream,xt?{mimeType:xt}:{});qt.ondataavailable=async Ot=>{if(!Ot.data||Ot.data.size<=0)return;const ct=await Ot.data.arrayBuffer();r?r(ct):ie(ct)},he.current=qt,qt.start(100)}catch(et){C?.(et)}},[lt,F,r,C,ie]),$t=ce.useCallback(()=>{const Pe=he.current;if(Pe){if(he.current=null,Pe.state==="inactive"){s?s():X();return}Pe.onstop=()=>{s?s():X()},Pe.stop()}},[X,s]),vt=ce.useCallback(()=>{const Pe=he.current;if(Pe&&(he.current=null,Pe.state!=="inactive"))try{Pe.stop()}catch{}},[]),Ye=ce.useCallback(()=>{H.current&&(H.current.close().catch(()=>{}),H.current=null)},[]),St=ce.useCallback(()=>{ae.current&&(ae.current.getTracks().forEach(Pe=>Pe.stop()),ae.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 He=zy.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:Sf,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:bf}},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:Pe=>{Pe.env.wasm.numThreads=1,Pe.env.logLevel="error"},getStream:tt,pauseStream:dt,resumeStream:wt,onFrameProcessed:(Pe,ot)=>{if(!ot)return;const Je=Ve.current;Je.push(new Float32Array(ot)),Je.length>Ny&&Je.shift()},onSpeechStart:()=>{le.current||(pe.current&&(clearTimeout(pe.current),pe.current=null),Z(!0),S&&re(),yt(),a?.())},onSpeechEnd:()=>{pe.current=setTimeout(()=>{Z(!1),$t(),le.current=!0,setTimeout(()=>{le.current=!1},300),p?.()},Ly)},onVADMisfire:()=>{pe.current&&(clearTimeout(pe.current),pe.current=null),Z(!1),vt(),v?.()}}),at=ce.useCallback(async()=>!R||He.loading||He.errored?!1:(He.listening&&(pe.current&&(clearTimeout(pe.current),pe.current=null),Z(!1),$t(),await He.pause()),!0),[R,$t,He]),J=ce.useCallback(async()=>{try{await He.start()}catch(Pe){const ot=Pe instanceof Error?Pe.message:String(Pe);if(ot.includes("null stream")||ot.includes("audio context")||ot.includes("processor adapter"))await new Promise(Je=>setTimeout(Je,100)),await He.start();else throw Pe}},[He]),Oe=ce.useCallback(async()=>!R||He.loading||He.errored?!1:(Ze(),He.listening?(pe.current&&(clearTimeout(pe.current),pe.current=null),Z(!1),$t(),await He.pause()):await J(),!0),[R,$t,Ze,J]),it=ce.useCallback(async()=>R?(Ze(),tt()):null,[R,tt,Ze]),Ke=ce.useCallback(async()=>!R||He.loading||He.errored?!1:(He.listening||(Ze(),await J()),!0),[R,Ze,J]);return ce.useEffect(()=>()=>{pe.current&&clearTimeout(pe.current),vt(),Ye(),St()},[Ye,St,vt]),{isListening:He.listening,isLoading:He.loading,isErrored:!!He.errored,isSpeaking:se,micError:ee,toggle:Oe,prepare:it,start:Ke,stop:at,pause:He.pause,userSpeaking:He.userSpeaking}}function Fy({connect:d=!0,session:r,onError:s,onInitialized:a,children:p}){const{initializeSession:v,joinDesktopSession:C,disconnect:R}=pf(),S=ce.useRef(!1),F=ce.useRef(!1),z=ce.useRef(v),ie=ce.useRef(C),X=ce.useRef(R),re=ce.useRef(s),se=ce.useRef(a);return ce.useEffect(()=>{z.current=v}),ce.useEffect(()=>{ie.current=C}),ce.useEffect(()=>{X.current=R}),ce.useEffect(()=>{re.current=s}),ce.useEffect(()=>{se.current=a}),ce.useEffect(()=>{if(!d||S.current)return;S.current=!0,F.current=!1;let Z=!1;return(async()=>{try{if(r?.mode==="join_desktop"){const ae=await ie.current({uniqueId:r.uniqueId});Z||se.current?.(ae);return}const _e=await z.current({apiKey:r?.apiKey,publicChatId:r?.publicChatId,agentId:r?.agentId,language:r?.language||"en"});Z||se.current?.(_e)}catch(_e){Z||(F.current=!0,re.current?.(_e))}})(),()=>{Z=!0,!F.current&&(X.current(),S.current=!1)}},[d,r]),rr.jsx(rr.Fragment,{children:p})}function Vy({children:d,wsUrl:r,restUrl:s,session:a,connect:p=!0,reconnectOptions:v,enableAudio:C=!0,pcmOptions:R,debug:S=!1,withCredentials:F=!1,onError:z,onInitialized:ie}){return rr.jsx(hf,{wsUrl:r,restUrl:s,reconnectOptions:v,enableAudio:C,pcmOptions:R,debug:S,withCredentials:F,children:rr.jsx(Fy,{connect:p,session:a,onError:z,onInitialized:ie,children:d})})}var uo={exports:{}},Vp;function Gy(){return Vp||(Vp=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(`
|
|
2860
|
+
`).map(a=>a.trim())},r.splitSections=function(s){return s.split(`
|
|
2861
|
+
m=`).map((p,v)=>(v>0?"m="+p:p).trim()+`\r
|
|
2862
|
+
`)},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(p=>p.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 p={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":p.relatedAddress=a[v+1];break;case"rport":p.relatedPort=parseInt(a[v+1],10);break;case"tcptype":p.tcpType=a[v+1];break;case"ufrag":p.ufrag=a[v+1],p.usernameFragment=a[v+1];break;default:p[a[v]]===void 0&&(p[a[v]]=a[v+1]);break}return p},r.writeCandidate=function(s){const a=[];a.push(s.foundation);const p=s.component;p==="rtp"?a.push(1):p==="rtcp"?a.push(2):a.push(p),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 p={payloadType:parseInt(a.shift(),10)};return a=a[0].split("/"),p.name=a[0],p.clockRate=parseInt(a[1],10),p.channels=a.length===3?parseInt(a[2],10):1,p.numChannels=p.channels,p},r.writeRtpMap=function(s){let a=s.payloadType;s.preferredPayloadType!==void 0&&(a=s.preferredPayloadType);const p=s.channels||s.numChannels||1;return"a=rtpmap:"+a+" "+s.name+"/"+s.clockRate+(p!==1?"/"+p:"")+`\r
|
|
2863
|
+
`},r.parseExtmap=function(s){const a=s.substring(9).split(" ");return{id:parseInt(a[0],10),direction:a[0].indexOf("/")>0?a[0].split("/")[1]:"sendrecv",uri:a[1],attributes:a.slice(2).join(" ")}},r.writeExtmap=function(s){return"a=extmap:"+(s.id||s.preferredId)+(s.direction&&s.direction!=="sendrecv"?"/"+s.direction:"")+" "+s.uri+(s.attributes?" "+s.attributes:"")+`\r
|
|
2864
|
+
`},r.parseFmtp=function(s){const a={};let p;const v=s.substring(s.indexOf(" ")+1).split(";");for(let C=0;C<v.length;C++)p=v[C].trim().split("="),a[p[0].trim()]=p[1];return a},r.writeFmtp=function(s){let a="",p=s.payloadType;if(s.preferredPayloadType!==void 0&&(p=s.preferredPayloadType),s.parameters&&Object.keys(s.parameters).length){const v=[];Object.keys(s.parameters).forEach(C=>{s.parameters[C]!==void 0?v.push(C+"="+s.parameters[C]):v.push(C)}),a+="a=fmtp:"+p+" "+v.join(";")+`\r
|
|
2865
|
+
`}return a},r.parseRtcpFb=function(s){const a=s.substring(s.indexOf(" ")+1).split(" ");return{type:a.shift(),parameter:a.join(" ")}},r.writeRtcpFb=function(s){let a="",p=s.payloadType;return s.preferredPayloadType!==void 0&&(p=s.preferredPayloadType),s.rtcpFeedback&&s.rtcpFeedback.length&&s.rtcpFeedback.forEach(v=>{a+="a=rtcp-fb:"+p+" "+v.type+(v.parameter&&v.parameter.length?" "+v.parameter:"")+`\r
|
|
2866
|
+
`}),a},r.parseSsrcMedia=function(s){const a=s.indexOf(" "),p={ssrc:parseInt(s.substring(7,a),10)},v=s.indexOf(":",a);return v>-1?(p.attribute=s.substring(a+1,v),p.value=s.substring(v+1)):p.attribute=s.substring(a+1),p},r.parseSsrcGroup=function(s){const a=s.substring(13).split(" ");return{semantics:a.shift(),ssrcs:a.map(p=>parseInt(p,10))}},r.getMid=function(s){const a=r.matchPrefix(s,"a=mid:")[0];if(a)return a.substring(6)},r.parseFingerprint=function(s){const a=s.substring(14).split(" ");return{algorithm:a[0].toLowerCase(),value:a[1].toUpperCase()}},r.getDtlsParameters=function(s,a){return{role:"auto",fingerprints:r.matchPrefix(s+a,"a=fingerprint:").map(r.parseFingerprint)}},r.writeDtlsParameters=function(s,a){let p="a=setup:"+a+`\r
|
|
2867
|
+
`;return s.fingerprints.forEach(v=>{p+="a=fingerprint:"+v.algorithm+" "+v.value+`\r
|
|
2868
|
+
`}),p},r.parseCryptoLine=function(s){const a=s.substring(9).split(" ");return{tag:parseInt(a[0],10),cryptoSuite:a[1],keyParams:a[2],sessionParams:a.slice(3)}},r.writeCryptoLine=function(s){return"a=crypto:"+s.tag+" "+s.cryptoSuite+" "+(typeof s.keyParams=="object"?r.writeCryptoKeyParams(s.keyParams):s.keyParams)+(s.sessionParams?" "+s.sessionParams.join(" "):"")+`\r
|
|
2869
|
+
`},r.parseCryptoKeyParams=function(s){if(s.indexOf("inline:")!==0)return null;const a=s.substring(7).split("|");return{keyMethod:"inline",keySalt:a[0],lifeTime:a[1],mkiValue:a[2]?a[2].split(":")[0]:void 0,mkiLength:a[2]?a[2].split(":")[1]:void 0}},r.writeCryptoKeyParams=function(s){return s.keyMethod+":"+s.keySalt+(s.lifeTime?"|"+s.lifeTime:"")+(s.mkiValue&&s.mkiLength?"|"+s.mkiValue+":"+s.mkiLength:"")},r.getCryptoParameters=function(s,a){return r.matchPrefix(s+a,"a=crypto:").map(r.parseCryptoLine)},r.getIceParameters=function(s,a){const p=r.matchPrefix(s+a,"a=ice-ufrag:")[0],v=r.matchPrefix(s+a,"a=ice-pwd:")[0];return p&&v?{usernameFragment:p.substring(12),password:v.substring(10)}:null},r.writeIceParameters=function(s){let a="a=ice-ufrag:"+s.usernameFragment+`\r
|
|
2870
|
+
a=ice-pwd:`+s.password+`\r
|
|
2871
|
+
`;return s.iceLite&&(a+=`a=ice-lite\r
|
|
2872
|
+
`),a},r.parseRtpParameters=function(s){const a={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},v=r.splitLines(s)[0].split(" ");a.profile=v[2];for(let R=3;R<v.length;R++){const S=v[R],F=r.matchPrefix(s,"a=rtpmap:"+S+" ")[0];if(F){const z=r.parseRtpMap(F),ie=r.matchPrefix(s,"a=fmtp:"+S+" ");switch(z.parameters=ie.length?r.parseFmtp(ie[0]):{},z.rtcpFeedback=r.matchPrefix(s,"a=rtcp-fb:"+S+" ").map(r.parseRtcpFb),a.codecs.push(z),z.name.toUpperCase()){case"RED":case"ULPFEC":a.fecMechanisms.push(z.name.toUpperCase());break}}}r.matchPrefix(s,"a=extmap:").forEach(R=>{a.headerExtensions.push(r.parseExtmap(R))});const C=r.matchPrefix(s,"a=rtcp-fb:* ").map(r.parseRtcpFb);return a.codecs.forEach(R=>{C.forEach(S=>{R.rtcpFeedback.find(z=>z.type===S.type&&z.parameter===S.parameter)||R.rtcpFeedback.push(S)})}),a},r.writeRtpDescription=function(s,a){let p="";p+="m="+s+" ",p+=a.codecs.length>0?"9":"0",p+=" "+(a.profile||"UDP/TLS/RTP/SAVPF")+" ",p+=a.codecs.map(C=>C.preferredPayloadType!==void 0?C.preferredPayloadType:C.payloadType).join(" ")+`\r
|
|
2873
|
+
`,p+=`c=IN IP4 0.0.0.0\r
|
|
2874
|
+
`,p+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
2875
|
+
`,a.codecs.forEach(C=>{p+=r.writeRtpMap(C),p+=r.writeFmtp(C),p+=r.writeRtcpFb(C)});let v=0;return a.codecs.forEach(C=>{C.maxptime>v&&(v=C.maxptime)}),v>0&&(p+="a=maxptime:"+v+`\r
|
|
2876
|
+
`),a.headerExtensions&&a.headerExtensions.forEach(C=>{p+=r.writeExtmap(C)}),p},r.parseRtpEncodingParameters=function(s){const a=[],p=r.parseRtpParameters(s),v=p.fecMechanisms.indexOf("RED")!==-1,C=p.fecMechanisms.indexOf("ULPFEC")!==-1,R=r.matchPrefix(s,"a=ssrc:").map(X=>r.parseSsrcMedia(X)).filter(X=>X.attribute==="cname"),S=R.length>0&&R[0].ssrc;let F;const z=r.matchPrefix(s,"a=ssrc-group:FID").map(X=>X.substring(17).split(" ").map(se=>parseInt(se,10)));z.length>0&&z[0].length>1&&z[0][0]===S&&(F=z[0][1]),p.codecs.forEach(X=>{if(X.name.toUpperCase()==="RTX"&&X.parameters.apt){let re={ssrc:S,codecPayloadType:parseInt(X.parameters.apt,10)};S&&F&&(re.rtx={ssrc:F}),a.push(re),v&&(re=JSON.parse(JSON.stringify(re)),re.fec={ssrc:S,mechanism:C?"red+ulpfec":"red"},a.push(re))}}),a.length===0&&S&&a.push({ssrc:S});let ie=r.matchPrefix(s,"b=");return ie.length&&(ie[0].indexOf("b=TIAS:")===0?ie=parseInt(ie[0].substring(7),10):ie[0].indexOf("b=AS:")===0?ie=parseInt(ie[0].substring(5),10)*1e3*.95-2e3*8:ie=void 0,a.forEach(X=>{X.maxBitrate=ie})),a},r.parseRtcpParameters=function(s){const a={},p=r.matchPrefix(s,"a=ssrc:").map(R=>r.parseSsrcMedia(R)).filter(R=>R.attribute==="cname")[0];p&&(a.cname=p.value,a.ssrc=p.ssrc);const v=r.matchPrefix(s,"a=rtcp-rsize");a.reducedSize=v.length>0,a.compound=v.length===0;const C=r.matchPrefix(s,"a=rtcp-mux");return a.mux=C.length>0,a},r.writeRtcpParameters=function(s){let a="";return s.reducedSize&&(a+=`a=rtcp-rsize\r
|
|
2877
|
+
`),s.mux&&(a+=`a=rtcp-mux\r
|
|
2878
|
+
`),s.ssrc!==void 0&&s.cname&&(a+="a=ssrc:"+s.ssrc+" cname:"+s.cname+`\r
|
|
2879
|
+
`),a},r.parseMsid=function(s){let a;const p=r.matchPrefix(s,"a=msid:");if(p.length===1)return a=p[0].substring(7).split(" "),{stream:a[0],track:a[1]};const v=r.matchPrefix(s,"a=ssrc:").map(C=>r.parseSsrcMedia(C)).filter(C=>C.attribute==="msid");if(v.length>0)return a=v[0].value.split(" "),{stream:a[0],track:a[1]}},r.parseSctpDescription=function(s){const a=r.parseMLine(s),p=r.matchPrefix(s,"a=max-message-size:");let v;p.length>0&&(v=parseInt(p[0].substring(19),10)),isNaN(v)&&(v=65536);const C=r.matchPrefix(s,"a=sctp-port:");if(C.length>0)return{port:parseInt(C[0].substring(12),10),protocol:a.fmt,maxMessageSize:v};const R=r.matchPrefix(s,"a=sctpmap:");if(R.length>0){const S=R[0].substring(10).split(" ");return{port:parseInt(S[0],10),protocol:S[1],maxMessageSize:v}}},r.writeSctpDescription=function(s,a){let p=[];return s.protocol!=="DTLS/SCTP"?p=["m="+s.kind+" 9 "+s.protocol+" "+a.protocol+`\r
|
|
2880
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
2881
|
+
`,"a=sctp-port:"+a.port+`\r
|
|
2882
|
+
`]:p=["m="+s.kind+" 9 "+s.protocol+" "+a.port+`\r
|
|
2883
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
2884
|
+
`,"a=sctpmap:"+a.port+" "+a.protocol+` 65535\r
|
|
2885
|
+
`],a.maxMessageSize!==void 0&&p.push("a=max-message-size:"+a.maxMessageSize+`\r
|
|
2886
|
+
`),p.join("")},r.generateSessionId=function(){return Math.random().toString().substr(2,22)},r.writeSessionBoilerplate=function(s,a,p){let v;const C=a!==void 0?a:2;return s?v=s:v=r.generateSessionId(),`v=0\r
|
|
2887
|
+
o=`+(p||"thisisadapterortc")+" "+v+" "+C+` IN IP4 127.0.0.1\r
|
|
2888
|
+
s=-\r
|
|
2889
|
+
t=0 0\r
|
|
2890
|
+
`},r.getDirection=function(s,a){const p=r.splitLines(s);for(let v=0;v<p.length;v++)switch(p[v]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return p[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 p=r.splitLines(s)[0].substring(2).split(" ");return{kind:p[0],port:parseInt(p[1],10),protocol:p[2],fmt:p.slice(3).join(" ")}},r.parseOLine=function(s){const p=r.matchPrefix(s,"o=")[0].substring(2).split(" ");return{username:p[0],sessionId:p[1],sessionVersion:parseInt(p[2],10),netType:p[3],addressType:p[4],address:p[5]}},r.isValidSDP=function(s){if(typeof s!="string"||s.length===0)return!1;const a=r.splitLines(s);for(let p=0;p<a.length;p++)if(a[p].length<2||a[p].charAt(1)!=="=")return!1;return!0},d.exports=r})(uo)),uo.exports}var Gp=Gy(),Ir,Mt,Gi={d:(d,r)=>{for(var s in r)Gi.o(r,s)&&!Gi.o(d,s)&&Object.defineProperty(d,s,{enumerable:!0,get:r[s]})},o:(d,r)=>Object.prototype.hasOwnProperty.call(d,r)},ve={};Gi.d(ve,{Dz:()=>im,g$:()=>kf,Lt:()=>xf,Q9:()=>Cf,qf:()=>To,hV:()=>dm,z$:()=>zw,J0:()=>$o,De:()=>uw,$C:()=>Fs,al:()=>Lf,_W:()=>Bf,Gv:()=>Jf,m:()=>Zf,tz:()=>zf,Nu:()=>lm,zg:()=>pm,vp:()=>nm,vU:()=>Q,wF:()=>jf,rv:()=>am,Nh:()=>om,ss:()=>hm,qW:()=>em,QL:()=>Yf,cf:()=>mm,eM:()=>Hf,Yd:()=>T,Tk:()=>Se,iM:()=>Tf,qy:()=>Jr,ce:()=>Zy,sK:()=>ge,Ok:()=>gt,q5:()=>um,g:()=>Dw,xl:()=>qf,I:()=>Wf,bx:()=>Eo,dD:()=>rm,Ib:()=>fi,Az:()=>It,Iw:()=>Nr,qY:()=>So,db:()=>$f,mR:()=>ci,Tn:()=>bo,rV:()=>Kf,gh:()=>Uf,Mi:()=>Ff,j:()=>Vf,YB:()=>Gf,Yt:()=>Xf,i5:()=>Qf,x_:()=>Yr,Am:()=>xo,eR:()=>Rf,r8:()=>Nf,u3:()=>fm,vd:()=>If,iV:()=>Of,jZ:()=>Mf,SW:()=>Df,ZH:()=>Pf,Ni:()=>gm,lh:()=>Af,ZP:()=>sm,bq:()=>Ef,$f:()=>ym,eu:()=>tm,Ax:()=>nw,Mc:()=>sw});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 p=`Level: Log
|
|
2891
|
+
Msg: ${s}
|
|
2892
|
+
Caller: ${r}`;console.log(p)}static Info(r,s,a){if(a>this.verboseLogLevel)return;const p=`Level: Info
|
|
2893
|
+
Msg: ${s}`;console.info(p)}static Error(r,s){const a=`Level: Error
|
|
2894
|
+
Msg: ${s}
|
|
2895
|
+
Caller: ${r}`;console.error(a)}static Warning(r,s){const a=`Level: Warning
|
|
2896
|
+
Caller: ${r}
|
|
2897
|
+
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"})(Ir||(Ir={}));class Jr{sendFilter(r,s){return s}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2898
|
+
`+JSON.stringify(this,this.sendFilter,4),6),JSON.stringify(this,this.sendFilter)}}class qy extends Jr{constructor(){super(),this.type=Ir.LIST_STREAMERS}}class Wy extends Jr{constructor(r){super(),this.type=Ir.SUBSCRIBE,this.streamerId=r}}class Hy extends Jr{constructor(){super(),this.type=Ir.UNSUBSCRIBE}}class jy extends Jr{constructor(r){super(),this.type=Ir.PONG,this.time=r}}class Ky extends Jr{constructor(r,s){super(),this.type=Ir.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 Qy extends Jr{constructor(r,s){super(),this.type=Ir.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 Xy extends Jr{constructor(){super(),this.type=Ir.DATACHANNELREQUEST}}class Yy extends Jr{constructor(){super(),this.type=Ir.SFURECVDATACHANNELREADY}}class Jy{constructor(r){this.type=Ir.ICE_CANDIDATE,this.candidate=r}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2899
|
+
`+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"})(Mt||(Mt={}));class Tf{}class Zy extends Tf{}class bo{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(Mt.PING,(s=>{const a=new jy(new Date().getTime()).payload();T.Log(T.GetStackTrace(),Mt.PING+": "+s,6),r.webSocket.send(a)})),r.signallingProtocol.addMessageHandler(Mt.CONFIG,(s=>{T.Log(T.GetStackTrace(),Mt.CONFIG,6);const a=JSON.parse(s);r.onConfig(a)})),r.signallingProtocol.addMessageHandler(Mt.STREAMER_LIST,(s=>{T.Log(T.GetStackTrace(),Mt.STREAMER_LIST,6);const a=JSON.parse(s);r.onStreamerList(a)})),r.signallingProtocol.addMessageHandler(Mt.STREAMER_ID_CHANGED,(s=>{T.Log(T.GetStackTrace(),Mt.STREAMER_ID_CHANGED,6);const a=JSON.parse(s);r.onStreamerIDChanged(a)})),r.signallingProtocol.addMessageHandler(Mt.PLAYER_COUNT,(s=>{T.Log(T.GetStackTrace(),Mt.PLAYER_COUNT,6);const a=JSON.parse(s);T.Log(T.GetStackTrace(),"Player Count: "+a.count,6),r.onPlayerCount(a)})),r.signallingProtocol.addMessageHandler(Mt.ANSWER,(s=>{T.Log(T.GetStackTrace(),Mt.ANSWER,6);const a=JSON.parse(s);r.onWebRtcAnswer(a)})),r.signallingProtocol.addMessageHandler(Mt.OFFER,(s=>{T.Log(T.GetStackTrace(),Mt.OFFER,6);const a=JSON.parse(s);r.onWebRtcOffer(a)})),r.signallingProtocol.addMessageHandler(Mt.ICE_CANDIDATE,(s=>{T.Log(T.GetStackTrace(),Mt.ICE_CANDIDATE,6);const a=JSON.parse(s);r.onIceCandidate(a.candidate)})),r.signallingProtocol.addMessageHandler(Mt.WARNING,(s=>{T.Warning(T.GetStackTrace(),`Warning received: ${s}`)})),r.signallingProtocol.addMessageHandler(Mt.PEER_DATA_CHANNELS,(s=>{T.Log(T.GetStackTrace(),Mt.PEER_DATA_CHANNELS,6);const a=JSON.parse(s);r.onWebRtcPeerDataChannels(a)}))}}class Ef{constructor(){this.WS_OPEN_STATE=1,this.onOpen=new EventTarget,this.onClose=new EventTarget,this.signallingProtocol=new bo,bo.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 =>
|
|
2900
|
+
`+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 qy;this.webSocket.send(r.payload())}sendSubscribe(r){const s=new Wy(r);this.webSocket.send(s.payload())}sendUnsubscribe(){const r=new Hy;this.webSocket.send(r.payload())}sendWebRtcOffer(r,s){const a=new Ky(r,s);this.webSocket.send(a.payload())}sendWebRtcAnswer(r,s){const a=new Qy(r,s);this.webSocket.send(a.payload())}sendWebRtcDatachannelRequest(){const r=new Xy;this.webSocket.send(r.payload())}sendSFURecvDataChannelReady(){const r=new Yy;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 Jy(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 ew{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 tw{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,p)=>a+String.fromCharCode(p)),""));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,p=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)),p=0):(r=Math.floor(this.rootDiv.clientHeight*C),s=this.rootDiv.clientHeight,a=0,p=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=p+"px",this.imageElement.style.top=a+"px"}}}class rw{constructor(r){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new tw(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 p=new Uint8Array(this.jpeg.length+a.length);p.set(this.jpeg,0),p.set(a,this.jpeg.length),this.jpeg=p}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 fi{constructor(r,s,a,p,v=(()=>{})){this.onChange=v,this.onChangeEmit=()=>{},this.id=r,this.description=a,this.label=s,this.value=p}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 It extends fi{constructor(r,s,a,p,v,C=(()=>{})){super(r,s,a,p,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const S=this.getUrlParamFlag();this.flag=S}else this.flag=p;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 Nr extends fi{constructor(r,s,a,p,v,C,R,S=(()=>{})){super(r,s,a,C,S),this._min=p,this._max=v;const F=new URLSearchParams(window.location.search);if(R&&F.has(this.id)){const z=Number.parseFloat(F.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 $f extends fi{constructor(r,s,a,p,v,C=(()=>{})){super(r,s,a,p,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const S=this.getUrlParamText();this.text=S}else this.text=p;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 So extends fi{constructor(r,s,a,p,v,C,R=(()=>{})){super(r,s,a,p,R),this.options=v;const S=new URLSearchParams(window.location.search),F=C&&S.has(this.id)?this.getUrlParamText():p;this.selected=F,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 xf extends Event{constructor(r){super("afkWarningActivate"),this.data=r}}class To extends Event{constructor(r){super("afkWarningUpdate"),this.data=r}}class Cf extends Event{constructor(){super("afkWarningDeactivate")}}class kf extends Event{constructor(){super("afkTimedOut")}}class Rf extends Event{constructor(r){super("videoEncoderAvgQP"),this.data=r}}class Af extends Event{constructor(){super("webRtcSdp")}}class If extends Event{constructor(){super("webRtcAutoConnect")}}class Mf extends Event{constructor(){super("webRtcConnecting")}}class Of extends Event{constructor(){super("webRtcConnected")}}class Pf extends Event{constructor(){super("webRtcFailed")}}class Df extends Event{constructor(r){super("webRtcDisconnected"),this.data=r}}class zf extends Event{constructor(r){super("dataChannelOpen"),this.data=r}}class Lf extends Event{constructor(r){super("dataChannelClose"),this.data=r}}class Bf extends Event{constructor(r){super("dataChannelError"),this.data=r}}class Nf extends Event{constructor(){super("videoInitialized")}}class Uf extends Event{constructor(){super("streamLoading")}}class Ff extends Event{constructor(){super("streamConnect")}}class Vf extends Event{constructor(){super("streamDisconnect")}}class Gf extends Event{constructor(){super("streamReconnect")}}class qf extends Event{constructor(r){super("playStreamError"),this.data=r}}class Wf extends Event{constructor(){super("playStream")}}class Eo extends Event{constructor(r){super("playStreamRejected"),this.data=r}}class Hf extends Event{constructor(r){super("loadFreezeFrame"),this.data=r}}class jf extends Event{constructor(){super("hideFreezeFrame")}}class Kf extends Event{constructor(r){super("statsReceived"),this.data=r}}class Qf extends Event{constructor(r){super("streamerListMessage"),this.data=r}}class Xf extends Event{constructor(r){super("StreamerIDChangedMessage"),this.data=r}}class Yf extends Event{constructor(r){super("latencyTestResult"),this.data=r}}class Jf extends Event{constructor(r){super("dataChannelLatencyTestResponse"),this.data=r}}class Zf extends Event{constructor(r){super("dataChannelLatencyTestResult"),this.data=r}}class em extends Event{constructor(r){super("initialSettings"),this.data=r}}class ci extends Event{constructor(r){super("settingsChanged"),this.data=r}}class sw extends Event{constructor(){super("xrSessionStarted")}}class nw extends Event{constructor(){super("xrSessionEnded")}}class tm extends Event{constructor(r){super("xrFrame"),this.data=r}}class rm extends Event{constructor(r){super("playerCount"),this.data=r}}class sm extends Event{constructor(){super("webRtcTCPRelayDetected")}}class nm extends EventTarget{dispatchEvent(r){return super.dispatchEvent(r)}addEventListener(r,s){super.addEventListener(r,s)}removeEventListener(r,s){super.removeEventListener(r,s)}}class Q{}Q.AutoConnect="AutoConnect",Q.AutoPlayVideo="AutoPlayVideo",Q.AFKDetection="TimeoutIfIdle",Q.BrowserSendOffer="OfferToReceive",Q.HoveringMouseMode="HoveringMouse",Q.ForceMonoAudio="ForceMonoAudio",Q.ForceTURN="ForceTURN",Q.FakeMouseWithTouches="FakeMouseWithTouches",Q.IsQualityController="ControlsQuality",Q.MatchViewportResolution="MatchViewportRes",Q.StartVideoMuted="StartVideoMuted",Q.SuppressBrowserKeys="SuppressBrowserKeys",Q.UseMic="UseMic",Q.KeyboardInput="KeyboardInput",Q.MouseInput="MouseInput",Q.TouchInput="TouchInput",Q.GamepadInput="GamepadInput",Q.XRControllerInput="XRControllerInput",Q.WaitForStreamer="WaitForStreamer",Q.HideUI="HideUI";const iw=d=>Object.getOwnPropertyNames(Q).some((r=>Q[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 aw=d=>Object.getOwnPropertyNames(ge).some((r=>ge[r]===d));class Yr{}Yr.SignallingServerUrl="ss";const ow=d=>Object.getOwnPropertyNames(Yr).some((r=>Yr[r]===d));class gt{}gt.PreferredCodec="PreferredCodec",gt.StreamerId="StreamerId";const lw=d=>Object.getOwnPropertyNames(gt).some((r=>gt[r]===d));class uw{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(Yr.SignallingServerUrl,new $f(Yr.SignallingServerUrl,"Signalling url","Url of the signalling server",s&&s.hasOwnProperty(Yr.SignallingServerUrl)?s[Yr.SignallingServerUrl]:(location.protocol==="https:"?"wss://":"ws://")+window.location.hostname+(window.location.port==="80"||window.location.port===""?"":`:${window.location.port}`),r)),this.optionParameters.set(gt.StreamerId,new So(gt.StreamerId,"Streamer ID","The ID of the streamer to stream.",s&&s.hasOwnProperty(gt.StreamerId)?s[gt.StreamerId]:"",[],r)),this.optionParameters.set(gt.PreferredCodec,new So(gt.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(gt.PreferredCodec)?[s[gt.PreferredCodec]]:(function(){const a=[];if(!RTCRtpReceiver.getCapabilities)return a.push("Only available on Chrome"),a;const p=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((v=>{const C=v.mimeType.split("/")[1]+" "+(v.sdpFmtpLine||"");p.exec(C)!==null&&a.push(C)})),a})(),r)),this.flags.set(Q.AutoConnect,new It(Q.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(Q.AutoConnect))&&s[Q.AutoConnect],r)),this.flags.set(Q.AutoPlayVideo,new It(Q.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!s||!s.hasOwnProperty(Q.AutoPlayVideo)||s[Q.AutoPlayVideo],r)),this.flags.set(Q.BrowserSendOffer,new It(Q.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!s||!s.hasOwnProperty(Q.BrowserSendOffer))&&s[Q.BrowserSendOffer],r)),this.flags.set(Q.UseMic,new It(Q.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!s||!s.hasOwnProperty(Q.UseMic))&&s[Q.UseMic],r)),this.flags.set(Q.StartVideoMuted,new It(Q.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!s||!s.hasOwnProperty(Q.StartVideoMuted))&&s[Q.StartVideoMuted],r)),this.flags.set(Q.SuppressBrowserKeys,new It(Q.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(Q.SuppressBrowserKeys)||s[Q.SuppressBrowserKeys],r)),this.flags.set(Q.IsQualityController,new It(Q.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!s||!s.hasOwnProperty(Q.IsQualityController)||s[Q.IsQualityController],r)),this.flags.set(Q.ForceMonoAudio,new It(Q.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!s||!s.hasOwnProperty(Q.ForceMonoAudio))&&s[Q.ForceMonoAudio],r)),this.flags.set(Q.ForceTURN,new It(Q.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!s||!s.hasOwnProperty(Q.ForceTURN))&&s[Q.ForceTURN],r)),this.flags.set(Q.AFKDetection,new It(Q.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!s||!s.hasOwnProperty(Q.AFKDetection))&&s[Q.AFKDetection],r)),this.flags.set(Q.MatchViewportResolution,new It(Q.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(Q.MatchViewportResolution))&&s[Q.MatchViewportResolution],r)),this.flags.set(Q.HoveringMouseMode,new It(Q.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(Q.HoveringMouseMode))&&s[Q.HoveringMouseMode],r,((a,p)=>{p.label=`Control Scheme: ${a?"Hovering":"Locked"} Mouse`}))),this.flags.set(Q.FakeMouseWithTouches,new It(Q.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(Q.FakeMouseWithTouches))&&s[Q.FakeMouseWithTouches],r)),this.flags.set(Q.KeyboardInput,new It(Q.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!s||!s.hasOwnProperty(Q.KeyboardInput)||s[Q.KeyboardInput],r)),this.flags.set(Q.MouseInput,new It(Q.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!s||!s.hasOwnProperty(Q.MouseInput)||s[Q.MouseInput],r)),this.flags.set(Q.TouchInput,new It(Q.TouchInput,"Touch input","If enabled, send touch events to streamer",!s||!s.hasOwnProperty(Q.TouchInput)||s[Q.TouchInput],r)),this.flags.set(Q.GamepadInput,new It(Q.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!s||!s.hasOwnProperty(Q.GamepadInput)||s[Q.GamepadInput],r)),this.flags.set(Q.XRControllerInput,new It(Q.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!s||!s.hasOwnProperty(Q.XRControllerInput)||s[Q.XRControllerInput],r)),this.flags.set(Q.WaitForStreamer,new It(Q.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!s||!s.hasOwnProperty(Q.WaitForStreamer)||s[Q.WaitForStreamer],r)),this.flags.set(Q.HideUI,new It(Q.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!s||!s.hasOwnProperty(Q.HideUI))&&s[Q.HideUI],r)),this.numericParameters.set(ge.AFKTimeoutSecs,new Nr(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 Nr(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 Nr(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 Nr(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 Nr(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 Nr(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 Nr(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 Nr(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 Nr(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),p=a.options;p.includes(s)||(p.push(s),a.options=p),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))iw(s)?this.setFlagEnabled(s,r[s]):aw(s)?this.setNumericSetting(s,r[s]):ow(s)?this.setTextSetting(s,r[s]):lw(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=p=>r.dispatchEvent(new ci({id:a.id,type:"flag",value:p,target:a})))}for(const s of this.numericParameters.keys()){const a=this.numericParameters.get(s);a&&(a.onChangeEmit=p=>r.dispatchEvent(new ci({id:a.id,type:"number",value:p,target:a})))}for(const s of this.textParameters.keys()){const a=this.textParameters.get(s);a&&(a.onChangeEmit=p=>r.dispatchEvent(new ci({id:a.id,type:"text",value:p,target:a})))}for(const s of this.optionParameters.keys()){const a=this.optionParameters.get(s);a&&(a.onChangeEmit=p=>r.dispatchEvent(new ci({id:a.id,type:"option",value:p,target:a})))}}}var Fs;(function(d){d[d.LockedMouse=0]="LockedMouse",d[d.HoveringMouse=1]="HoveringMouse"})(Fs||(Fs={}));class im{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 Cf))}startAfkWarningTimer(){this.config.getNumericSettingValue(ge.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(Q.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(Q.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(ge.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new xf({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(ge.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new To({countDown:this.countDown})),this.config.isFlagEnabled(Q.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new kf),this.onAFKTimedOutCallback(),T.Log(T.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new To({countDown:this.countDown}))}),1e3)}}class qp{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 am{}class om{}class lm{}class $o{}class um{}class dw{}class cw{}class dm{constructor(){this.inboundVideoStats=new om,this.inboundAudioStats=new am,this.DataChannelStats=new lm,this.outBoundVideoStats=new um,this.sessionStats=new dw,this.streamStats=new cw,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 $o;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 $o;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 p=Date.now()-r;this.sessionStats.runTime=new Date(p).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 Wp=(Hp={parseRtpParameters:()=>Gp.parseRtpParameters,splitSections:()=>Gp.splitSections},co={},Gi.d(co,Hp),co);var Hp,co;class cm{static isVideoTransciever(r){return this.canTransceiverReceiveVideo(r)||this.canTransceiverSendVideo(r)}static canTransceiverReceiveVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="video"}static canTransceiverSendVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="video"}static isAudioTransciever(r){return this.canTransceiverReceiveAudio(r)||this.canTransceiverSendAudio(r)}static canTransceiverReceiveAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="audio"}static canTransceiverSendAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="audio"}}var ln,Se,ho=function(d,r,s,a){return new(s||(s=Promise))((function(p,v){function C(F){try{S(a.next(F))}catch(z){v(z)}}function R(F){try{S(a.throw(F))}catch(z){v(z)}}function S(F){var z;F.done?p(F.value):(z=F.value,z instanceof s?z:new s((function(ie){ie(z)}))).then(C,R)}S((a=a.apply(d,[])).next())}))};class hw{constructor(r,s,a){this.config=s,this.createPeerConnection(r,a)}createPeerConnection(r,s){this.config.isFlagEnabled(Q.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 dm,this.preferredCodec=s,this.updateCodecSelection=!0}createOffer(r,s){return ho(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Create Offer",6);const a=location.hostname==="localhost"||location.hostname==="127.0.0.1",p=location.protocol==="https:";let v=s.isFlagEnabled(Q.UseMic);!v||a||p||(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 ho(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 p=location.hostname==="localhost"||location.hostname==="127.0.0.1",v=location.protocol==="https:";let C=s.isFlagEnabled(Q.UseMic);!C||p||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(gt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r)),this.setupTransceiversAsync(C).finally((()=>{var R;(R=this.peerConnection)===null||R===void 0||R.createAnswer().then((S=>{var F;return S.sdp=this.mungeSDP(S.sdp,C),(F=this.peerConnection)===null||F===void 0?void 0:F.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(gt.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(gt.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
|
|
2901
|
+
`),p="maxaveragebitrate=510000;";return s&&(p+="sprop-maxcapturerate=48000;"),p+=this.config.isFlagEnabled(Q.ForceMonoAudio)?"stereo=0;":"stereo=1;",p+="useinbandfec=1",a=a.replace("useinbandfec=1",p),a}handleOnIce(r){var s;T.Log(T.GetStackTrace(),"peerconnection handleOnIce",6),this.config.isFlagEnabled(Q.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),p=this.config.getSettingOption(gt.PreferredCodec).options;for(const v of a)if(p.includes(v))s.push(v);else{const C=v.split(" ")[0];for(const R of p)if(R.includes(C)){s.push(R);break}}return s}setupTransceiversAsync(r){var s,a,p,v,C,R,S,F,z,ie,X,re;return ho(this,void 0,void 0,(function*(){let se=!1;for(const ee of(a=(s=this.peerConnection)===null||s===void 0?void 0:s.getTransceivers())!==null&&a!==void 0?a:[])if(ee&&ee.receiver&&ee.receiver.track&&ee.receiver.track.kind==="video"){se=!0;break}if(se||(p=this.peerConnection)===null||p===void 0||p.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&this.preferredCodec!=""){for(const ee of(C=(v=this.peerConnection)===null||v===void 0?void 0:v.getTransceivers())!==null&&C!==void 0?C:[])if(ee&&ee.receiver&&ee.receiver.track&&ee.receiver.track.kind==="video"&&ee.setCodecPreferences){const _e=this.preferredCodec.split(" "),ae={mimeType:"video/"+_e[0],clockRate:9e4,sdpFmtpLine:_e[1]?_e[1]:""},he=[ae];RTCRtpReceiver.getCapabilities("video").codecs.forEach((H=>{(H.mimeType!=ae.mimeType||H?.sdpFmtpLine!=ae?.sdpFmtpLine)&&he.push(H)}));for(const H of he)H?.sdpFmtpLine!==void 0&&H.sdpFmtpLine!==""||delete H.sdpFmtpLine;ee.setCodecPreferences(he)}}let Z=!1;for(const ee of(S=(R=this.peerConnection)===null||R===void 0?void 0:R.getTransceivers())!==null&&S!==void 0?S:[])if(ee&&ee.receiver&&ee.receiver.track&&ee.receiver.track.kind==="audio"){Z=!0;break}if(r){const ee={video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}},_e=yield navigator.mediaDevices.getUserMedia(ee);if(_e)if(Z){for(const ae of(ie=(z=this.peerConnection)===null||z===void 0?void 0:z.getTransceivers())!==null&&ie!==void 0?ie:[])if(cm.canTransceiverReceiveAudio(ae))for(const he of _e.getTracks())he.kind&&he.kind=="audio"&&(ae.sender.replaceTrack(he),ae.direction="sendrecv")}else for(const ae of _e.getTracks())ae.kind&&ae.kind=="audio"&&((X=this.peerConnection)===null||X===void 0||X.addTransceiver(ae,{direction:"sendrecv"}));else Z||(re=this.peerConnection)===null||re===void 0||re.addTransceiver("audio",{direction:"recvonly"})}else Z||(F=this.peerConnection)===null||F===void 0||F.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,Wp.splitSections)(r.sdp);return a.shift(),a.forEach((p=>{const{codecs:v}=(0,Wp.parseRtpParameters)(p),C=/(VP\d|H26\d|AV1).*/;v.forEach((R=>{const S=R.name+" "+Object.keys(R.parameters||{}).map((F=>F+"="+R.parameters[F])).join(";");if(C.exec(S)!==null){R.name=="VP9"&&(R.parameters={"profile-id":"0"});const F=R.name+" "+Object.keys(R.parameters||{}).map((z=>z+"="+R.parameters[z])).join(";");s.push(F)}}))})),s}}class hm{constructor(){this.PixelStreamingSettings=new pw,this.EncoderSettings=new pm,this.WebRTCSettings=new fm}ueCompatible(){this.WebRTCSettings.MaxFPS!=null&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class pw{}class pm{}class fm{}class mm{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
|
|
2902
|
+
${this.PostEncodeTimeMs}
|
|
2903
|
+
${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
|
|
2904
|
+
${this.PostCaptureTimeMs}
|
|
2905
|
+
${this.PreCaptureTimeMs}`,6),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class po{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 p=new Date().getTime()-s.timestampStart,v=Math.round(16384*s.chunks/p);T.Log(T.GetStackTrace(),`Average transfer bitrate: ${v}kb/s over ${p/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 fw{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}}class Xt{}Xt.mainButton=0,Xt.auxiliaryButton=1,Xt.secondaryButton=2,Xt.fourthButton=3,Xt.fifthButton=4;class er{}er.primaryButton=1,er.secondaryButton=2,er.auxiliaryButton=4,er.fourthButton=8,er.fifthButton=16;class cn{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(r){this.unregisterCallbacks.push(r)}unregisterAll(){for(const r of this.unregisterCallbacks)r();this.unregisterCallbacks=[]}}class mw{constructor(r,s,a){this.touchEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a;const p=R=>this.onTouchStart(R),v=R=>this.onTouchEnd(R),C=R=>this.onTouchMove(R);document.addEventListener("touchstart",p,{passive:!1}),document.addEventListener("touchend",v,{passive:!1}),document.addEventListener("touchmove",C,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",p))),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 gw(s.identifier,s.clientX-this.videoElementParentClientRect.left,s.clientY-this.videoElementParentClientRect.top);const a=this.videoElementProvider.getVideoParentElement(),p=new MouseEvent("mouseenter",s);a.dispatchEvent(p);const v=this.coordinateConverter.normalizeAndQuantizeUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([Xt.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 p=0;p<r.changedTouches.length;p++){const v=r.changedTouches[p];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")([Xt.mainButton,S.x,S.y]);const F=new MouseEvent("mouseleave",v);s.dispatchEvent(F),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 p=r.touches[a];if(p.identifier===this.fakeTouchFinger.id){const v=p.clientX-this.videoElementParentClientRect.left,C=p.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 gw{constructor(r,s,a){this.id=r,this.x=s,this.y=a}}class tr{}tr.backSpace=8,tr.shift=16,tr.control=17,tr.alt=18,tr.rightShift=253,tr.rightControl=254,tr.rightAlt=255;class yw{constructor(r,s,a){this.keyboardEventListenerTracker=new cn,this.CodeToKeyCode={Escape:27,Digit0:48,Digit1:49,Digit2:50,Digit3:51,Digit4:52,Digit5:53,Digit6:54,Digit7:55,Digit8:56,Digit9:57,Minus:173,Equal:187,Backspace:8,Tab:9,KeyQ:81,KeyW:87,KeyE:69,KeyR:82,KeyT:84,KeyY:89,KeyU:85,KeyI:73,KeyO:79,KeyP:80,BracketLeft:219,BracketRight:221,Enter:13,ControlLeft:17,KeyA:65,KeyS:83,KeyD:68,KeyF:70,KeyG:71,KeyH:72,KeyJ:74,KeyK:75,KeyL:76,Semicolon:186,Quote:222,Backquote:192,ShiftLeft:16,Backslash:220,KeyZ:90,KeyX:88,KeyC:67,KeyV:86,KeyB:66,KeyN:78,KeyM:77,Comma:188,Period:190,Slash:191,ShiftRight:253,AltLeft:18,Space:32,CapsLock:20,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,Pause:19,ScrollLock:145,NumpadDivide:111,NumpadMultiply:106,NumpadSubtract:109,NumpadAdd:107,NumpadDecimal:110,Numpad9:105,Numpad8:104,Numpad7:103,Numpad6:102,Numpad5:101,Numpad4:100,Numpad3:99,Numpad2:98,Numpad1:97,Numpad0:96,NumLock:144,ControlRight:254,AltRight:255,Home:36,End:35,ArrowUp:38,ArrowLeft:37,ArrowRight:39,ArrowDown:40,PageUp:33,PageDown:34,Insert:45,Delete:46,ContextMenu:93},this.toStreamerMessagesProvider=r,this.config=s,this.activeKeysProvider=a}registerKeyBoardEvents(){const r=v=>this.handleOnCompositionEnd(v),s=v=>this.handleOnKeyDown(v),a=v=>this.handleOnKeyUp(v),p=v=>this.handleOnKeyPress(v);document.addEventListener("compositionend",r),document.addEventListener("keydown",s),document.addEventListener("keyup",a),document.addEventListener("keypress",p),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",p)))}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===tr.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:tr.backSpace})),this.config.isFlagEnabled(Q.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(Q.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===tr.shift&&r.code==="ShiftRight"?tr.rightShift:r.keyCode===tr.control&&r.code==="ControlRight"?tr.rightControl:r.keyCode===tr.alt&&r.code==="AltRight"?tr.rightAlt:r.keyCode}isKeyCodeBrowserKey(r){return r>=112&&r<=123||r===9}}class ww{constructor(r,s,a){this.x=0,this.y=0,this.updateMouseMovePositionEvent=v=>{this.updateMouseMovePosition(v)},this.mouseEventListenerTracker=new cn,this.videoElementProvider=r,this.mouseController=s,this.activeKeysProvider=a;const p=this.videoElementProvider.getVideoParentElement();this.x=p.getBoundingClientRect().width/2,this.y=p.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 p=new Set(a),v=[];p.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,p=this.videoElementProvider.getVideoParentElement().clientHeight;this.x+=r.movementX,this.y+=r.movementY,this.x>a&&(this.x-=a),this.y>p&&(this.y-=p),this.x<0&&(this.x=a+this.x),this.y<0&&(this.y=p-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 vw{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 _w{constructor(r,s,a,p){this.mouseEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.coordinateConverter=a,this.videoElementProvider=s,this.activeKeysProvider=p,this.registerMouseEnterAndLeaveEvents()}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}registerLockedMouseEvents(r){const s=this.videoElementProvider.getVideoParentElement(),a=new ww(this.videoElementProvider,r,this.activeKeysProvider);if(s.requestPointerLock=s.requestPointerLock||s.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,s.requestPointerLock){const F=()=>{s.requestPointerLock()};s.addEventListener("click",F),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("click",F)))}const p=()=>a.lockStateChange();document.addEventListener("pointerlockchange",p,!1),document.addEventListener("mozpointerlockchange",p,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("pointerlockchange",p,!1))),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mozpointerlockchange",p,!1)));const v=F=>a.handleMouseDown(F),C=F=>a.handleMouseUp(F),R=F=>a.handleMouseWheel(F),S=F=>a.handleMouseDouble(F);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 vw(r),p=z=>a.updateMouseMovePosition(z),v=z=>a.handleMouseDown(z),C=z=>a.handleMouseUp(z),R=z=>a.handleContextMenu(z),S=z=>a.handleMouseWheel(z),F=z=>a.handleMouseDouble(z);s.addEventListener("mousemove",p),s.addEventListener("mousedown",v),s.addEventListener("mouseup",C),s.addEventListener("contextmenu",R),s.addEventListener("wheel",S),s.addEventListener("dblclick",F),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousemove",p))),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",F))),this.mouseEventListenerTracker.addUnregisterCallback((()=>a.unregisterMouseEvents()))}registerMouseEnterAndLeaveEvents(){const r=this.videoElementProvider.getVideoParentElement(),s=p=>{this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"Mouse Entered",6),this.sendMouseEnter(),this.pressMouseButtons(p.buttons,p.x,p.y))},a=p=>{this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"Mouse Left",6),this.sendMouseLeave(),this.releaseMouseButtons(p.buttons,p.x,p.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 p=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);r&er.primaryButton&&this.sendMouseUp(Xt.mainButton,p.x,p.y),r&er.secondaryButton&&this.sendMouseUp(Xt.secondaryButton,p.x,p.y),r&er.auxiliaryButton&&this.sendMouseUp(Xt.auxiliaryButton,p.x,p.y),r&er.fourthButton&&this.sendMouseUp(Xt.fourthButton,p.x,p.y),r&er.fifthButton&&this.sendMouseUp(Xt.fifthButton,p.x,p.y)}pressMouseButtons(r,s,a){if(!this.videoElementProvider.isVideoReady())return;const p=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);r&er.primaryButton&&this.sendMouseDown(Xt.mainButton,p.x,p.y),r&er.secondaryButton&&this.sendMouseDown(Xt.secondaryButton,p.x,p.y),r&er.auxiliaryButton&&this.sendMouseDown(Xt.auxiliaryButton,p.x,p.y),r&er.fourthButton&&this.sendMouseDown(Xt.fourthButton,p.x,p.y),r&er.fifthButton&&this.sendMouseDown(Xt.fifthButton,p.x,p.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 p=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r,p.x,p.y])}}class bw{constructor(r,s,a){this.fingers=[9,8,7,6,5,4,3,2,1,0],this.fingerIds=new Map,this.maxByteValue=255,this.touchEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a,this.videoElementParent=s.getVideoElement();const p=S=>this.onTouchStart(S),v=S=>this.onTouchEnd(S),C=S=>this.onTouchMove(S);this.videoElementParent.addEventListener("touchstart",p),this.videoElementParent.addEventListener("touchend",v),this.videoElementParent.addEventListener("touchmove",C),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",p))),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(),p=this.toStreamerMessagesProvider.toStreamerHandlers;for(let v=0;v<s.length;v++){const R=s[v],S=R.clientX-a.left,F=R.clientY-a.top;T.Log(T.GetStackTrace(),`F${this.fingerIds.get(R.identifier)}=(${S}, ${F})`,6);const z=this.coordinateConverter.normalizeAndQuantizeUnsigned(S,F);switch(r){case"TouchStart":p.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":p.get("TouchEnd")([1,z.x,z.y,this.fingerIds.get(R.identifier),this.maxByteValue*R.force,z.inRange?1:0]);break;case"TouchMove":p.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 Sw{constructor(r){this.gamePadEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.requestAnimationFrame=(window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.requestAnimationFrame).bind(window);const s=window;if(window.addEventListener("beforeunload",(a=>this.onBeforeUnload(a))),"GamepadEvent"in s){const a=v=>this.gamePadConnectHandler(v),p=v=>this.gamePadDisconnectHandler(v);window.addEventListener("gamepadconnected",a),window.addEventListener("gamepaddisconnected",p),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepadconnected",a))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepaddisconnected",p)))}else if("WebKitGamepadEvent"in s){const a=v=>this.gamePadConnectHandler(v),p=v=>this.gamePadDisconnectHandler(v);window.addEventListener("webkitgamepadconnected",a),window.addEventListener("webkitgamepaddisconnected",p),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepadconnected",a))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepaddisconnected",p)))}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,p=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==ln.LeftTrigger?r.get("GamepadAnalog")([a,5,C.value]):v==ln.RightTrigger?r.get("GamepadAnalog")([a,6,C.value]):r.get("GamepadButtonPressed")([a,v,R.pressed?1:0]):!C.pressed&&R.pressed&&(v==ln.LeftTrigger?r.get("GamepadAnalog")([a,5,0]):v==ln.RightTrigger?r.get("GamepadAnalog")([a,6,0]):r.get("GamepadButtonReleased")([a,v,0]))}for(let v=0;v<p.axes.length;v+=2){const C=parseFloat(p.axes[v].toFixed(4)),R=-parseFloat(p.axes[v+1].toFixed(4));r.get("GamepadAnalog")([a,v+1,C]),r.get("GamepadAnalog")([a,v+2,R])}this.controllers[a].prevState=p}this.controllers.length>0&&this.requestAnimationFrame((()=>this.updateStatus()))}onGamepadResponseReceived(r){for(const s of this.controllers)if(s.id===void 0){s.id=r;break}}onGamepadConnected(){}onGamepadDisconnected(r){}onBeforeUnload(r){for(const s of this.controllers)this.onGamepadDisconnected(s.id)}}(function(d){d[d.RightClusterBottomButton=0]="RightClusterBottomButton",d[d.RightClusterRightButton=1]="RightClusterRightButton",d[d.RightClusterLeftButton=2]="RightClusterLeftButton",d[d.RightClusterTopButton=3]="RightClusterTopButton",d[d.LeftShoulder=4]="LeftShoulder",d[d.RightShoulder=5]="RightShoulder",d[d.LeftTrigger=6]="LeftTrigger",d[d.RightTrigger=7]="RightTrigger",d[d.SelectOrBack=8]="SelectOrBack",d[d.StartOrForward=9]="StartOrForward",d[d.LeftAnalogPress=10]="LeftAnalogPress",d[d.RightAnalogPress=11]="RightAnalogPress",d[d.LeftClusterTopButton=12]="LeftClusterTopButton",d[d.LeftClusterBottomButton=13]="LeftClusterBottomButton",d[d.LeftClusterLeftButton=14]="LeftClusterLeftButton",d[d.LeftClusterRightButton=15]="LeftClusterRightButton",d[d.CentreButton=16]="CentreButton",d[d.LeftStickHorizontal=0]="LeftStickHorizontal",d[d.LeftStickVertical=1]="LeftStickVertical",d[d.RightStickHorizontal=2]="RightStickHorizontal",d[d.RightStickVertical=3]="RightStickVertical"})(ln||(ln={}));class Tw{constructor(r,s,a){this.activeKeys=new Ew,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a}registerKeyBoard(r){T.Log(T.GetStackTrace(),"Register Keyboard Events",7);const s=new yw(this.toStreamerMessagesProvider,r,this.activeKeys);return s.registerKeyBoardEvents(),s}registerMouse(r){T.Log(T.GetStackTrace(),"Register Mouse Events",7);const s=new _w(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys);switch(r){case Fs.LockedMouse:s.registerLockedMouseEvents(s);break;case Fs.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 mw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return a.setVideoElementParentClientRect(s),a}return new bw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return T.Log(T.GetStackTrace(),"Register Game Pad",7),new Sw(this.toStreamerMessagesProvider)}}class Ew{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class $w{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(Q.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(Q.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(Q.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 xw{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 Cw{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 kw{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 p=0;const v=new TextEncoder;s.forEach(((S,F)=>{switch(a.structure[F]){case"uint8":p+=1;break;case"uint16":case"int16":p+=2;break;case"float":p+=4;break;case"double":p+=8;break;case"string":p+=2,p+=2*v.encode(S).length}}));const C=new DataView(new ArrayBuffer(p+1));C.setUint8(0,a.id);let R=1;s.forEach(((S,F)=>{switch(a.structure[F]){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 Rw{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 Aw{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 Iw{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,p=s/r,v=(this.videoElement.videoHeight||1)/a;p>v?(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio > videoAspectRatio",6),this.ratio=p/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/p,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,p=this.ratio*(s/this.videoElementParent.clientHeight-.5)+.5;return a<0||a>1||p<0||p>1?new zi(!1,65535,65535):new zi(!0,65536*a,65536*p)}denormalizeAndUnquantizeUnsignedPlayerBigger(r,s){const a=r/65536,p=(s/65536-.5)/this.ratio+.5;return new xo(a*this.videoElementParent.clientWidth,p*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerBigger(r,s){const a=r/(.5*this.videoElementParent.clientWidth),p=this.ratio*s/(.5*this.videoElementParent.clientHeight);return new jp(32767*a,32767*p)}normalizeAndQuantizeUnsignedPlayerSmaller(r,s){const a=this.ratio*(r/this.videoElementParent.clientWidth-.5)+.5,p=s/this.videoElementParent.clientHeight;return a<0||a>1||p<0||p>1?new zi(!1,65535,65535):new zi(!0,65536*a,65536*p)}denormalizeAndUnquantizeUnsignedPlayerSmaller(r,s){const a=(r/65536-.5)/this.ratio+.5,p=s/65536;return new xo(a*this.videoElementParent.clientWidth,p*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerSmaller(r,s){const a=this.ratio*r/(.5*this.videoElementParent.clientWidth),p=s/(.5*this.videoElementParent.clientHeight);return new jp(32767*a,32767*p)}}class zi{constructor(r,s,a){this.inRange=r,this.x=s,this.y=a}}class xo{constructor(r,s){this.x=r,this.y=s}}class jp{constructor(r,s){this.x=r,this.y=s}}class gm{constructor(r,s){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=r,this.pixelStreaming=s,this.responseController=new Cw,this.file=new fw,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new im(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new rw(this.pixelStreaming.videoElementParent),this.videoPlayer=new $w(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(a,p)=>{const v={"Resolution.Width":a,"Resolution.Height":p};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(v)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new ew(this.videoPlayer),this.coordinateConverter=new Iw(this.videoPlayer),this.sendrecvDataChannelController=new qp,this.recvDataChannelController=new qp,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new Aw(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new xw,this.webSocketController=new Ef,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(Q.BrowserSendOffer)||this.webSocketController.requestStreamerList()})),this.webSocketController.onClose.addEventListener("close",(a=>{const p=this.shouldReconnect&&a.detail.code!=1001&&this.config.getNumericSettingValue(ge.MaxReconnectAttempts)>0,v=this.disconnectMessage?this.disconnectMessage:a.detail.reason;this.pixelStreaming._onDisconnect(v,!p&&!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),p&&setTimeout((()=>{this.isReconnecting=!0,this.reconnectAttempt++,this.tryReconnect(a.detail.reason)}),2e3)})),this.sendMessageController=new kw(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new Rw(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new Tw(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(gt.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(Yr.SignallingServerUrl);return this.config.isFlagEnabled(Q.BrowserSendOffer)&&(a+="?"+Q.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 p=a.Direction;delete a.Direction,T.Log(T.GetStackTrace(),`Received new ${p==Se.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(a).forEach((v=>{const C=a[v];switch(p){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
|
|
2906
|
+
|
|
2907
|
+
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
|
|
2908
|
+
|
|
2909
|
+
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: ${p}`)}})),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 Hf({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 jf),this.freezeFrameController.hideFreezeFrame()}),this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(r){const s=new Uint8Array(r);po.setExtensionFromBytes(s,this.file)}onFileMimeType(r){const s=new Uint8Array(r);po.setMimeTypeFromBytes(s,this.file)}onFileContents(r){const s=new Uint8Array(r);po.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 qf({message:r})),T.Error(T.GetStackTrace(),r),void this.closeSignalingServer("Stream not initialized correctly")}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(Q.TouchInput)),this.pixelStreaming.dispatchEvent(new Wf),this.streamController.audioElement.srcObject){const r=this.config.isFlagEnabled(Q.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 Eo({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 Eo({reason:r}))}))}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(Q.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(Q.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 hw(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(Q.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(gt.StreamerId);a.selected.toString().trim()&&(s=a.selected);const p=[...r.ids];p.unshift(""),this.config.setOptionSettingOptions(gt.StreamerId,p);let v=null;const C=this.config.isFlagEnabled(Q.WaitForStreamer),R=this.config.getNumericSettingValue(ge.MaxReconnectAttempts),S=this.config.getNumericSettingValue(ge.StreamerAutoJoinInterval),F=this.config.useUrlParams,z=new URLSearchParams(window.location.search);F&&z.has(gt.StreamerId)?s=z.get(gt.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(gt.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 Qf({messageStreamerList:r,autoSelectedStreamerId:v,wantedStreamerId:s}))}handleStreamerIDChangedMessage(r){const s=r.newID;var a=this.config.getSettingOption(gt.StreamerId),p=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=p,this.subscribedStream=r.newID,this.pixelStreaming.dispatchEvent(new Xf({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 p={ordered:!0,negotiated:!0,id:r.recvStreamId};this.recvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"recv-datachannel",p),this.recvDataChannelController.handleOnOpen=()=>this.webSocketController.sendSFURecvDataChannelReady(),this.recvDataChannelController.handleOnMessage=v=>this.handleOnMessage(v)}else this.sendrecvDataChannelController.handleOnMessage=p=>this.handleOnMessage(p)}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(Q.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(Q.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(Q.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}
|
|
2910
|
+
`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQP":r})])}sendEncoderMaxQP(r){T.Log(T.GetStackTrace(),`MaxQP=${r}
|
|
2911
|
+
`,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 mm;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),p=new hm;a.Encoder&&(p.EncoderSettings=a.Encoder),a.WebRTC&&(p.WebRTCSettings=a.WebRTC),a.PixelStreaming&&(p.PixelStreamingSettings=a.PixelStreaming),a.ConfigOptions&&a.ConfigOptions.DefaultToHover!==void 0&&this.config.setFlagEnabled(Q.HoveringMouseMode,!!a.ConfigOptions.DefaultToHover),p.ueCompatible(),T.Log(T.GetStackTrace(),s,6),this.pixelStreaming._onInitialSettings(p)}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(Q.HoveringMouseMode)?Fs.HoveringMouse:Fs.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(Q.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 zf({label:s,event:a})),r.onClose=(s,a)=>this.pixelStreaming.dispatchEvent(new Lf({label:s,event:a})),r.onError=(s,a)=>this.pixelStreaming.dispatchEvent(new Bf({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,(p=>a===void 0&&s===Se.ToStreamer?this.sendMessageController.sendMessageToStreamer(r,p):a(p)))}}class qi{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 p=s.getPose(r.gripSpace,a);if(!p)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=p.transform.matrix,S=[];for(let X=0;X<16;X++)S[X]=new Float32Array([R[X]])[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=qi.deepCopyGamepad(r.gamepad)),this.controllers[C].currentState=qi.deepCopyGamepad(r.gamepad);const F=this.controllers[C],z=F.currentState,ie=F.prevState;for(let X=0;X<z.buttons.length;X++){const re=z.buttons[X],se=ie.buttons[X];if(re.pressed){let Z=se.pressed?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonPressed")([C,X,Z])}else se.pressed&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonReleased")([C,X,0]);if(re.touched){let Z=se.touched?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouched")([C,X,Z])}else se.touched&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouchReleased")([C,X,0])}for(let X=0;X<z.axes.length;X++){let re=z.axes[X];re!=ie.axes[X]&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRAnalog")([C,X,re])}this.controllers[C].prevState=z}}}class ym{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 qi(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,`
|
|
2912
|
+
attribute vec2 a_position;
|
|
2913
|
+
attribute vec2 a_texCoord;
|
|
2914
|
+
|
|
2915
|
+
// varyings
|
|
2916
|
+
varying vec2 v_texCoord;
|
|
2917
|
+
|
|
2918
|
+
void main() {
|
|
2919
|
+
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
2920
|
+
// pass the texCoord to the fragment shader
|
|
2921
|
+
// The GPU will interpolate this value between points.
|
|
2922
|
+
v_texCoord = a_texCoord;
|
|
2923
|
+
}
|
|
2924
|
+
`),this.gl.compileShader(r);const s=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(s,`
|
|
2925
|
+
precision mediump float;
|
|
2926
|
+
|
|
2927
|
+
// our texture
|
|
2928
|
+
uniform sampler2D u_image;
|
|
2929
|
+
|
|
2930
|
+
// the texCoords passed in from the vertex shader.
|
|
2931
|
+
varying vec2 v_texCoord;
|
|
2932
|
+
|
|
2933
|
+
void main() {
|
|
2934
|
+
gl_FragColor = texture2D(u_image, v_texCoord);
|
|
2935
|
+
}
|
|
2936
|
+
`),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,p=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],p[0],p[4],p[8],p[12],p[1],p[5],p[9],p[13],p[2],p[6],p[10],p[14],p[3],p[7],p[11],p[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(Q.XRControllerInput)&&this.xrSession.inputSources.forEach(((a,p,v)=>{this.xrGamepadController.updateStatus(a,s,this.xrRefSpace)}),this),this.xrSession.requestAnimationFrame(((a,p)=>this.onXrFrame(a,p))),this.onFrame.dispatchEvent(new tm({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 Mw{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 Ow{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 Pw{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;
|
|
2937
|
+
`;return r.forEach((a=>{s+=a.playerSentTimestamp+";",s+=a.playerReceivedTimestamp-a.playerSentTimestamp+";",s+=a.streamerReceivedTimestamp-a.playerSentTimestamp+";",s+=a.playerReceivedTimestamp-a.streamerSentTimestamp+";",s+=`
|
|
2938
|
+
`})),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),p=new Ow(a);this.records.set(p.seq,p),this.sink(a)}createRequest(r,s){return{Seq:this.seq++,FillResponseSize:s,Filler:r?"A".repeat(r):""}}}class Dw{constructor(r,s){this.allowConsoleCommands=!1,this.config=r,s?.videoElementParent&&(this._videoElementParent=s.videoElementParent),this._eventEmitter=new nm,this.configureSettings(),this.setWebRtcPlayerController(new gm(this.config,this)),this.onScreenKeyboardHelper=new Mw(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(a,p)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(a,p),this._activateOnScreenKeyboard=a=>this.onScreenKeyboardHelper.showOnScreenKeyboard(a),this._webXrController=new ym(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(Q.IsQualityController,(r=>{r!==!0||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(Q.AFKDetection,(r=>{this._webRtcController.setAfkEnabled(r)})),this.config._addOnSettingChangedListener(Q.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(Q.HoveringMouseMode,(r=>{this.config.setFlagLabel(Q.HoveringMouseMode,`Control Scheme: ${r?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(Q.MouseInput))})),this.config._addOnSettingChangedListener(Q.KeyboardInput,(r=>{this._webRtcController.setKeyboardInputEnabled(r)})),this.config._addOnSettingChangedListener(Q.MouseInput,(r=>{this._webRtcController.setMouseInputEnabled(r)})),this.config._addOnSettingChangedListener(Q.FakeMouseWithTouches,(r=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(Q.TouchInput))})),this.config._addOnSettingChangedListener(Q.TouchInput,(r=>{this._webRtcController.setTouchInputEnabled(r)})),this.config._addOnSettingChangedListener(Q.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(gt.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(gt.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Ff),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Gf),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Vf),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(Q.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,p,v;for(const C of(v=(p=(a=(s=this._webRtcController)===null||s===void 0?void 0:s.peerConnectionController)===null||a===void 0?void 0:a.peerConnection)===null||p===void 0?void 0:p.getTransceivers())!==null&&v!==void 0?v:[])cm.canTransceiverSendAudio(C)&&(C.sender.track.enabled=!r)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new If)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new Af)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new Uf)}_onDisconnect(r,s){this._eventEmitter.dispatchEvent(new Df({eventString:r,allowClickToReconnect:s}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new Mf)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Of)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new Pf)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new Nf),this._videoStartTime=Date.now()}_onLatencyTestResult(r){this._eventEmitter.dispatchEvent(new Yf({latencyTimings:r}))}_onDataChannelLatencyTestResponse(r){this._eventEmitter.dispatchEvent(new Jf({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 Kf({aggregatedStats:r}))}_onVideoEncoderAvgQP(r){this._eventEmitter.dispatchEvent(new Rf({avgQP:r}))}_onInitialSettings(r){var s;this._eventEmitter.dispatchEvent(new em({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,p=new URLSearchParams(window.location.search);T.Info(T.GetStackTrace(),`using URL parameters ${a}`),r.EncoderSettings&&(this.config.setNumericSetting(ge.MinQP,a&&p.has(ge.MinQP)?Number.parseFloat(p.get(ge.MinQP)):r.EncoderSettings.MinQP),this.config.setNumericSetting(ge.MaxQP,a&&p.has(ge.MaxQP)?Number.parseFloat(p.get(ge.MaxQP)):r.EncoderSettings.MaxQP)),r.WebRTCSettings&&(this.config.setNumericSetting(ge.WebRTCMinBitrate,a&&p.has(ge.WebRTCMinBitrate)?Number.parseFloat(p.get(ge.WebRTCMinBitrate)):r.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(ge.WebRTCMaxBitrate,a&&p.has(ge.WebRTCMaxBitrate)?Number.parseFloat(p.get(ge.WebRTCMaxBitrate)):r.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(ge.WebRTCFPS,a&&p.has(ge.WebRTCFPS)?Number.parseFloat(p.get(ge.WebRTCFPS)):r.WebRTCSettings.FPS))}_onQualityControlOwnership(r){this.config.setFlagEnabled(Q.IsQualityController,r)}_onPlayerCount(r){this._eventEmitter.dispatchEvent(new rm({count:r}))}_setupWebRtcTCPRelayDetection(r){let s=r.data.aggregatedStats.getActiveCandidatePair();if(s!=null){let a=r.data.aggregatedStats.localCandidates.find((p=>p.id==s.localCandidateId),null);a!=null&&a.candidateType=="relay"&&a.relayProtocol=="tcp"&&this._eventEmitter.dispatchEvent(new sm),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 Pw(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(s=>{this._eventEmitter.dispatchEvent(new Zf({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,(p=>this._webRtcController.sendMessageController.sendMessageToStreamer(r,p))):this._webRtcController.streamMessageController.registerMessageHandler(s,r,(p=>a(p))):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 zw{}ve.Dz;ve.g$;ve.Lt;ve.Q9;ve.qf;ve.hV;ve.z$;ve.J0;var Lw=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 Bw=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 wm=({signallingUrl:d,autoConnect:r=!0,width:s,height:a,onConnecting:p,onLoading:v,onConnected:C,onDisconnected:R,onError:S,muted:F=!1})=>{const z=ce.useRef(null),ie=ce.useRef(null),X=ce.useRef(!1),[re,se]=ce.useState(!1),[Z,ee]=ce.useState(!1),[_e,ae]=ce.useState(null);return ce.useEffect(()=>{if(!(!z.current||!d)){p&&p(),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 he=new Lw({useUrlParams:!1,initialSettings:{ss:d,AutoConnect:r,AutoPlayVideo:!0,StartVideoMuted:F,UseMic:!1,HoveringMouse:!1,FakeMouseWithTouches:!0,TouchInput:!1,MouseInput:!1,KeyboardInput:!1,WaitForStreamer:!0}}),H=new Bw(he,{videoElementParent:z.current});H.addEventListener("webRtcConnected",()=>{X.current=!0,se(!0),ee(!1),ae(null),C?.()}),H.addEventListener("webRtcDisconnected",()=>{X.current=!1,se(!1),R?.()}),H.addEventListener("streamLoading",()=>{ee(!0),v?.()}),H.addEventListener("playStreamError",()=>{ae("Failed to play stream"),ee(!1),S?.("Failed to play stream")}),H.addEventListener("playStream",()=>{ee(!1),X.current||(X.current=!0,se(!0),C?.())}),H.addEventListener("videoInitialized",()=>{ee(!1)}),ie.current=H}catch(he){process.env.NODE_ENV==="development"&&console.error("Failed to initialize Pixel Streaming:",he),ae("Failed to initialize streaming: "+he.message),ee(!1),S?.(he.message)}return()=>{if(ie.current){try{const he=ie.current;he._webSocketController&&he._webSocketController.close(),ie.current.disconnect()}catch(he){process.env.NODE_ENV==="development"&&console.error("Error during cleanup:",he)}ie.current=null}}}},[d,r,p,v,C,R,S]),ce.useEffect(()=>{if(ie.current)try{const H=ie.current._webRtcController?.videoPlayer;if(!H)return;let le=!1;if(H.audioElement){const Ve=H.audioElement.srcObject;if(Ve){const me=Ve.getAudioTracks();me.length>0&&(me.forEach(Ze=>{Ze.enabled=!F}),le=!0)}}const pe=H.getVideoElement();if(pe&&pe.srcObject&&pe.srcObject instanceof MediaStream){const me=pe.srcObject.getAudioTracks();me.length>0&&(me.forEach(Ze=>{Ze.enabled=!F}),le=!0)}!le&&pe&&(pe.muted=F)}catch(he){process.env.NODE_ENV==="development"&&console.error("Error controlling audio:",he)}},[F]),rr.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:[rr.jsx("div",{ref:z,className:"player-container",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"hidden",touchAction:"none"}}),Z&&rr.jsxs("div",{className:"loading-overlay",children:[rr.jsx("div",{className:"loading-spinner"}),rr.jsx("div",{className:"loading-text",children:"Connecting to stream..."})]}),!re&&!Z&&_e&&rr.jsx("div",{className:"connection-overlay",children:rr.jsx("div",{className:"error-message",children:_e})})]})};function Nw({className:d,style:r,autoConnect:s=!0,muted:a=!1,onConnected:p,onDisconnected:v,onError:C}){const{streamingUrl:R,setCloudStreamState:S}=ff();if(!R)return null;const F=()=>{S(dr.CONNECTING)},z=()=>{S(dr.LOADING)},ie=()=>{S(dr.CONNECTED),p?.()},X=()=>{S(dr.DISCONNECTED),v?.()},re=se=>{S(dr.ERROR,se),C?.(se)};return rr.jsx("div",{className:d,style:r,children:rr.jsx(wm,{signallingUrl:R,autoConnect:s,muted:a,onConnecting:F,onLoading:z,onConnected:ie,onDisconnected:X,onError:re})})}exports.AGENT_TYPES=hi;exports.CLOUD_STREAM_STATE=dr;exports.CONNECTION_STATE=mt;exports.DEFAULT_PCM_OPTIONS=Qp;exports.DEFAULT_RECONNECT_OPTIONS=Kp;exports.EpicPixelStreamingPlayer=wm;exports.EventEmitter=df;exports.RqmiiAgentProvider=hf;exports.RqmiiAgentRoom=Vy;exports.RqmiiCloudAvatarPlayer=Nw;exports.SESSION_STATE=Us;exports.SOCKET_EVENTS=Qt;exports.jsxRuntimeExports=rr;exports.useRqmiiAgentContext=dn;exports.useRqmiiAvatar=ff;exports.useRqmiiConnection=pf;exports.useRqmiiMessages=$y;exports.useRqmiiVAD=Uy;exports.useRqmiiVoice=xy;
|
|
2939
|
+
//# sourceMappingURL=RqmiiCloudAvatarPlayer-D5npgPcs.cjs.map
|