@rqmii_immersive/agent-react-sdk 4.0.1 → 5.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/dist/RqmiiCloudAvatarPlayer-BI7Uz7DP.cjs +2918 -0
- package/dist/RqmiiCloudAvatarPlayer-BI7Uz7DP.cjs.map +1 -0
- package/dist/{RqmiiCloudAvatarPlayer-CESlcAGy.js → RqmiiCloudAvatarPlayer-D5aXKUuO.js} +6569 -6932
- package/dist/RqmiiCloudAvatarPlayer-D5aXKUuO.js.map +1 -0
- package/dist/agent-react-sdk.css +1 -1
- package/dist/capture/capture.d.ts +32 -0
- package/dist/capture/capture.d.ts.map +1 -0
- package/dist/components/RqmiiAgentRoom.d.ts +1 -1
- package/dist/components/RqmiiAgentRoom.d.ts.map +1 -1
- package/dist/core/constants.d.ts +3 -13
- package/dist/core/constants.d.ts.map +1 -1
- package/dist/core/managers/session.d.ts +10 -1
- package/dist/core/managers/session.d.ts.map +1 -1
- package/dist/core/state/reducer.d.ts.map +1 -1
- package/dist/core/state/types.d.ts +3 -6
- package/dist/core/state/types.d.ts.map +1 -1
- package/dist/hooks/use-rqmii-connection.d.ts +10 -1
- package/dist/hooks/use-rqmii-connection.d.ts.map +1 -1
- package/dist/hooks/use-rqmii-messages.d.ts +2 -0
- package/dist/hooks/use-rqmii-messages.d.ts.map +1 -1
- package/dist/hooks/use-rqmii-press-to-talk.d.ts.map +1 -1
- package/dist/hooks/use-rqmii-sdk.d.ts +0 -2
- package/dist/hooks/use-rqmii-sdk.d.ts.map +1 -1
- package/dist/hooks/use-rqmii-vad.d.ts.map +1 -1
- package/dist/index.cjs +49 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +297 -218
- package/dist/index.js.map +1 -1
- package/dist/provider/RqmiiAgentProvider.d.ts +1 -1
- package/dist/provider/RqmiiAgentProvider.d.ts.map +1 -1
- package/dist/provider/socket-handlers.d.ts +5 -22
- package/dist/provider/socket-handlers.d.ts.map +1 -1
- package/dist/provider/use-manager-lifecycle.d.ts +11 -27
- package/dist/provider/use-manager-lifecycle.d.ts.map +1 -1
- package/dist/types/index.d.ts +84 -31
- package/dist/types/index.d.ts.map +1 -1
- package/dist/ui/Orb.d.ts.map +1 -1
- package/dist/ui/RqmiiAgentChat.d.ts +1 -1
- package/dist/ui/RqmiiAgentChat.d.ts.map +1 -1
- package/dist/ui/agent-data.d.ts +20 -1
- package/dist/ui/agent-data.d.ts.map +1 -1
- package/dist/ui/agent-data.test.d.ts +2 -0
- package/dist/ui/agent-data.test.d.ts.map +1 -0
- package/dist/ui/chat/ChatBox.d.ts +1 -1
- package/dist/ui/chat/ChatBox.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-avatar.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-content.d.ts +20 -10
- package/dist/ui/chat/chat-box-content.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-content.test.d.ts +2 -0
- package/dist/ui/chat/chat-box-content.test.d.ts.map +1 -0
- package/dist/ui/chat/chat-box-shared.d.ts +20 -0
- package/dist/ui/chat/chat-box-shared.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-shared.test.d.ts +2 -0
- package/dist/ui/chat/chat-box-shared.test.d.ts.map +1 -0
- package/dist/ui/chat/chat-box-text-and-voice.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-text-and-voice.test.d.ts +2 -0
- package/dist/ui/chat/chat-box-text-and-voice.test.d.ts.map +1 -0
- package/dist/ui/chat/chat-box-text.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-text.test.d.ts +2 -0
- package/dist/ui/chat/chat-box-text.test.d.ts.map +1 -0
- package/dist/ui/chat/chat-box-types.d.ts +35 -1
- package/dist/ui/chat/chat-box-types.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-voice.d.ts.map +1 -1
- package/dist/ui/chat/components.d.ts +3 -2
- package/dist/ui/chat/components.d.ts.map +1 -1
- package/dist/ui/chat/consent-dialog.d.ts +10 -0
- package/dist/ui/chat/consent-dialog.d.ts.map +1 -0
- package/dist/ui/chat/feedback.d.ts +21 -0
- package/dist/ui/chat/feedback.d.ts.map +1 -0
- package/dist/ui/chat/panels.d.ts +50 -7
- package/dist/ui/chat/panels.d.ts.map +1 -1
- package/dist/ui/chat/primitives.d.ts +29 -2
- package/dist/ui/chat/primitives.d.ts.map +1 -1
- package/dist/ui/chat/utils.d.ts +10 -0
- package/dist/ui/chat/utils.d.ts.map +1 -1
- package/dist/ui/enable-audio.test.d.ts +2 -0
- package/dist/ui/enable-audio.test.d.ts.map +1 -0
- package/dist/ui/languages/index.d.ts +5 -0
- package/dist/ui/languages/index.d.ts.map +1 -0
- package/dist/ui/languages/list.d.ts +7 -0
- package/dist/ui/languages/list.d.ts.map +1 -0
- package/dist/ui/languages/text.d.ts +3 -0
- package/dist/ui/languages/text.d.ts.map +1 -0
- package/dist/ui/languages/translations/af.d.ts +4 -0
- package/dist/ui/languages/translations/af.d.ts.map +1 -0
- package/dist/ui/languages/translations/ar.d.ts +4 -0
- package/dist/ui/languages/translations/ar.d.ts.map +1 -0
- package/dist/ui/languages/translations/az.d.ts +4 -0
- package/dist/ui/languages/translations/az.d.ts.map +1 -0
- package/dist/ui/languages/translations/be.d.ts +4 -0
- package/dist/ui/languages/translations/be.d.ts.map +1 -0
- package/dist/ui/languages/translations/bg.d.ts +4 -0
- package/dist/ui/languages/translations/bg.d.ts.map +1 -0
- package/dist/ui/languages/translations/bn.d.ts +4 -0
- package/dist/ui/languages/translations/bn.d.ts.map +1 -0
- package/dist/ui/languages/translations/bs.d.ts +4 -0
- package/dist/ui/languages/translations/bs.d.ts.map +1 -0
- package/dist/ui/languages/translations/ca.d.ts +4 -0
- package/dist/ui/languages/translations/ca.d.ts.map +1 -0
- package/dist/ui/languages/translations/cs.d.ts +4 -0
- package/dist/ui/languages/translations/cs.d.ts.map +1 -0
- package/dist/ui/languages/translations/cy.d.ts +4 -0
- package/dist/ui/languages/translations/cy.d.ts.map +1 -0
- package/dist/ui/languages/translations/da.d.ts +4 -0
- package/dist/ui/languages/translations/da.d.ts.map +1 -0
- package/dist/ui/languages/translations/de.d.ts +4 -0
- package/dist/ui/languages/translations/de.d.ts.map +1 -0
- package/dist/ui/languages/translations/el.d.ts +4 -0
- package/dist/ui/languages/translations/el.d.ts.map +1 -0
- package/dist/ui/languages/translations/en.d.ts +4 -0
- package/dist/ui/languages/translations/en.d.ts.map +1 -0
- package/dist/ui/languages/translations/es.d.ts +4 -0
- package/dist/ui/languages/translations/es.d.ts.map +1 -0
- package/dist/ui/languages/translations/et.d.ts +4 -0
- package/dist/ui/languages/translations/et.d.ts.map +1 -0
- package/dist/ui/languages/translations/eu.d.ts +4 -0
- package/dist/ui/languages/translations/eu.d.ts.map +1 -0
- package/dist/ui/languages/translations/fa.d.ts +4 -0
- package/dist/ui/languages/translations/fa.d.ts.map +1 -0
- package/dist/ui/languages/translations/fi.d.ts +4 -0
- package/dist/ui/languages/translations/fi.d.ts.map +1 -0
- package/dist/ui/languages/translations/fr.d.ts +4 -0
- package/dist/ui/languages/translations/fr.d.ts.map +1 -0
- package/dist/ui/languages/translations/gl.d.ts +4 -0
- package/dist/ui/languages/translations/gl.d.ts.map +1 -0
- package/dist/ui/languages/translations/gu.d.ts +4 -0
- package/dist/ui/languages/translations/gu.d.ts.map +1 -0
- package/dist/ui/languages/translations/hi.d.ts +4 -0
- package/dist/ui/languages/translations/hi.d.ts.map +1 -0
- package/dist/ui/languages/translations/hr.d.ts +4 -0
- package/dist/ui/languages/translations/hr.d.ts.map +1 -0
- package/dist/ui/languages/translations/hu.d.ts +4 -0
- package/dist/ui/languages/translations/hu.d.ts.map +1 -0
- package/dist/ui/languages/translations/id.d.ts +4 -0
- package/dist/ui/languages/translations/id.d.ts.map +1 -0
- package/dist/ui/languages/translations/it.d.ts +4 -0
- package/dist/ui/languages/translations/it.d.ts.map +1 -0
- package/dist/ui/languages/translations/ja.d.ts +4 -0
- package/dist/ui/languages/translations/ja.d.ts.map +1 -0
- package/dist/ui/languages/translations/kk.d.ts +4 -0
- package/dist/ui/languages/translations/kk.d.ts.map +1 -0
- package/dist/ui/languages/translations/kn.d.ts +4 -0
- package/dist/ui/languages/translations/kn.d.ts.map +1 -0
- package/dist/ui/languages/translations/ko.d.ts +4 -0
- package/dist/ui/languages/translations/ko.d.ts.map +1 -0
- package/dist/ui/languages/translations/lt.d.ts +4 -0
- package/dist/ui/languages/translations/lt.d.ts.map +1 -0
- package/dist/ui/languages/translations/lv.d.ts +4 -0
- package/dist/ui/languages/translations/lv.d.ts.map +1 -0
- package/dist/ui/languages/translations/mk.d.ts +4 -0
- package/dist/ui/languages/translations/mk.d.ts.map +1 -0
- package/dist/ui/languages/translations/ml.d.ts +4 -0
- package/dist/ui/languages/translations/ml.d.ts.map +1 -0
- package/dist/ui/languages/translations/mr.d.ts +4 -0
- package/dist/ui/languages/translations/mr.d.ts.map +1 -0
- package/dist/ui/languages/translations/ms.d.ts +4 -0
- package/dist/ui/languages/translations/ms.d.ts.map +1 -0
- package/dist/ui/languages/translations/nl.d.ts +4 -0
- package/dist/ui/languages/translations/nl.d.ts.map +1 -0
- package/dist/ui/languages/translations/no.d.ts +4 -0
- package/dist/ui/languages/translations/no.d.ts.map +1 -0
- package/dist/ui/languages/translations/pa.d.ts +4 -0
- package/dist/ui/languages/translations/pa.d.ts.map +1 -0
- package/dist/ui/languages/translations/pl.d.ts +4 -0
- package/dist/ui/languages/translations/pl.d.ts.map +1 -0
- package/dist/ui/languages/translations/pt.d.ts +4 -0
- package/dist/ui/languages/translations/pt.d.ts.map +1 -0
- package/dist/ui/languages/translations/ro.d.ts +4 -0
- package/dist/ui/languages/translations/ro.d.ts.map +1 -0
- package/dist/ui/languages/translations/ru.d.ts +4 -0
- package/dist/ui/languages/translations/ru.d.ts.map +1 -0
- package/dist/ui/languages/translations/sk.d.ts +4 -0
- package/dist/ui/languages/translations/sk.d.ts.map +1 -0
- package/dist/ui/languages/translations/sl.d.ts +4 -0
- package/dist/ui/languages/translations/sl.d.ts.map +1 -0
- package/dist/ui/languages/translations/sq.d.ts +4 -0
- package/dist/ui/languages/translations/sq.d.ts.map +1 -0
- package/dist/ui/languages/translations/sr.d.ts +4 -0
- package/dist/ui/languages/translations/sr.d.ts.map +1 -0
- package/dist/ui/languages/translations/sv.d.ts +4 -0
- package/dist/ui/languages/translations/sv.d.ts.map +1 -0
- package/dist/ui/languages/translations/sw.d.ts +4 -0
- package/dist/ui/languages/translations/sw.d.ts.map +1 -0
- package/dist/ui/languages/translations/ta.d.ts +4 -0
- package/dist/ui/languages/translations/ta.d.ts.map +1 -0
- package/dist/ui/languages/translations/te.d.ts +4 -0
- package/dist/ui/languages/translations/te.d.ts.map +1 -0
- package/dist/ui/languages/translations/th.d.ts +4 -0
- package/dist/ui/languages/translations/th.d.ts.map +1 -0
- package/dist/ui/languages/translations/tl.d.ts +4 -0
- package/dist/ui/languages/translations/tl.d.ts.map +1 -0
- package/dist/ui/languages/translations/tr.d.ts +4 -0
- package/dist/ui/languages/translations/tr.d.ts.map +1 -0
- package/dist/ui/languages/translations/translations.test.d.ts +2 -0
- package/dist/ui/languages/translations/translations.test.d.ts.map +1 -0
- package/dist/ui/languages/translations/uk.d.ts +4 -0
- package/dist/ui/languages/translations/uk.d.ts.map +1 -0
- package/dist/ui/languages/translations/ur.d.ts +4 -0
- package/dist/ui/languages/translations/ur.d.ts.map +1 -0
- package/dist/ui/languages/translations/vi.d.ts +4 -0
- package/dist/ui/languages/translations/vi.d.ts.map +1 -0
- package/dist/ui/languages/translations/zh.d.ts +4 -0
- package/dist/ui/languages/translations/zh.d.ts.map +1 -0
- package/dist/ui/languages/types.d.ts +37 -0
- package/dist/ui/languages/types.d.ts.map +1 -0
- package/dist/ui/{languages.d.ts → languages/utils.d.ts} +2 -7
- package/dist/ui/languages/utils.d.ts.map +1 -0
- package/dist/ui.cjs +4502 -3
- package/dist/ui.cjs.map +1 -1
- package/dist/ui.d.ts +4 -3
- package/dist/ui.d.ts.map +1 -1
- package/dist/ui.js +52415 -1401
- package/dist/ui.js.map +1 -1
- package/package.json +11 -2
- package/dist/RqmiiCloudAvatarPlayer-CESlcAGy.js.map +0 -1
- package/dist/RqmiiCloudAvatarPlayer-D5npgPcs.cjs +0 -2939
- package/dist/RqmiiCloudAvatarPlayer-D5npgPcs.cjs.map +0 -1
- package/dist/core/managers/heartbeat.d.ts +0 -13
- package/dist/core/managers/heartbeat.d.ts.map +0 -1
- package/dist/core/managers/reconnect.d.ts +0 -29
- package/dist/core/managers/reconnect.d.ts.map +0 -1
- package/dist/ui/languages.d.ts.map +0 -1
|
@@ -0,0 +1,2918 @@
|
|
|
1
|
+
"use strict";const oe=require("react"),Jt=require("react/jsx-runtime"),di={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},_r={CONNECT:"connect",DISCONNECT:"disconnect",CONNECT_ERROR:"connect_error",SESSION_READY:"session_ready",SESSION_JOINED:"session_joined",SESSION_TERMINATED:"session_terminated",USER_MESSAGE:"user_message",AUDIO_CHUNK:"audio_chunk",AUDIO_END:"audio_end",INTERRUPT:"interrupt",CHANGE_SESSION_LANGUAGE:"change_session_language",LANGUAGE_CHANGED:"language_changed",CLIENT_READY:"client_ready",CLIENT_TOOL_REQUEST:"client_tool_request",CLIENT_TOOL_RESULT:"client_tool_result",CLEAR_SESSION_HISTORY:"clear_session_history",TRANSCRIPT:"transcript",PARTIAL_TRANSCRIPT:"partial_transcript",AGENT_RESPONSE_CHUNK:"agent_response_chunk",AGENT_RESPONSE:"agent_response",AGENT_AUDIO_CHUNK:"agent_audio_chunk",AGENT_AUDIO_COMPLETE:"agent_audio_complete",AVATAR_SPEAKING:"avatar_speaking",AVATAR_SPEAKING_DONE:"avatar_speaking_done",INTERRUPTED:"interrupted",ERROR:"error",AUTH_ERROR:"auth_error",SESSION_EXPIRED:"session_expired",CREDITS_EXHAUSTED:"credits_exhausted",SESSION_STATE_CHANGED:"session:state_changed",AUDIO_PLAYBACK_COMPLETE:"audio:playback_complete"},ft={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",FAILED:"failed",ENDED:"ended"},Zt={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},Bs={IDLE:"idle",USER_SPEAKING:"user_speaking",AGENT_THINKING:"agent_thinking",AGENT_SPEAKING:"agent_speaking",TOOL_EXECUTING:"tool_executing",TERMINATING:"terminating",TERMINATED:"terminated"},Gp={encoding:"16bitInt",channels:1,sampleRate:16e3},po={connectionState:ft.IDLE,isConnected:!1,isSessionReady:!1,error:null,isAudioPlaying:!1,isAvatarSpeaking:!1,sessionState:Bs.IDLE,cloudStream:{state:Zt.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[],creditExhausted:!1,creditError:null,agentConfig:null};function hp(d,r){switch(r.type){case"SET_CONNECTION_STATE":return{...d,connectionState:r.payload,isConnected:r.payload===ft.CONNECTED};case"SET_ERROR":return{...d,error:r.payload};case"SET_CLOUD_STREAM_STATE":return{...d,cloudStream:r.payload};case"SET_SESSION_STATE":return{...d,sessionState:r.payload};case"UPDATE_SESSION":return{...d,session:{...d.session,...r.payload}};case"ADD_MESSAGE":return{...d,messages:[...d.messages,r.payload]};case"SET_AUDIO_PLAYING":return{...d,isAudioPlaying:r.payload};case"SET_AVATAR_SPEAKING":return{...d,isAvatarSpeaking:r.payload};case"SET_CREDIT_EXHAUSTED":return{...d,creditExhausted:r.payload.exhausted,creditError:r.payload.error};case"SET_TRANSCRIPT":return{...d,transcript:r.payload};case"SET_PARTIAL_TRANSCRIPT":return{...d,partialTranscript:r.payload};case"SET_MESSAGES":return{...d,messages:r.payload};case"SET_SESSION_READY":return{...d,isSessionReady:r.payload};case"SET_AGENT_CONFIG":return{...d,agentConfig:r.payload};case"HARD_RESET":return po;case"REPLACE_STATE":return r.payload;default:return d}}function dg(d){return{isSessionTerminated:d===Bs.TERMINATED,isSessionTerminating:d===Bs.TERMINATING,isAgentThinking:d===Bs.AGENT_THINKING,isAgentSpeaking:d===Bs.AGENT_SPEAKING,isToolExecuting:d===Bs.TOOL_EXECUTING}}function cg(){const d=new Map;return{addChunk(r,s){const a=r||`request-${Date.now()}`,_=`${d.get(a)||""}${s||""}`;return d.set(a,_),{id:a,text:_}},consume(r,s=""){const a=r||`request-${Date.now()}`,f=d.get(a)||s||"";return d.delete(a),{id:a,text:f}},clear(){d.clear()}}}function hg(){try{const d=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof d=="string"&&d.trim()?d.trim():void 0}catch{return}}async function Ii(d){if(!d?.ok){let r=`HTTP ${d.status}`;try{const f=await d.json();r=f?.detail||f?.message||r}catch{}const s=new Error(r);throw s.status=d.status,s}return d.json()}function pg({restUrl:d,log:r,withCredentials:s}){function a(){if(!d)throw new Error("Missing restUrl in RqmiiAgentProvider")}async function f({apiKey:b,publicChatId:U,agentId:z,userId:re,language:K="en",timezone:ie,config:J}={}){a();const Y={...b?{api_key:b}:{},...U?{public_chat_id:U}:{},...z?{agent_id:z}:{},...re?{user_id:re}:{},language:K,...ie?{timezone:ie}:{},...J?{config:J}:{}};r("initializeSession — POST /sessions/init",Y);const H=await fetch(`${d}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y),...s?{credentials:"include"}:{}}),se=await Ii(H);if(!se?.session_id||!se?.session_token)throw new Error("Invalid initialize session response");return se}async function _({uniqueId:b}){a(),r("joinDesktopSession — POST /sessions/join",{uniqueId:b});const U=await fetch(`${d}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:b}),...s?{credentials:"include"}:{}}),z=await Ii(U);if(!z?.session_id||!z?.session_token)throw new Error("Invalid join session response");return z}async function C(b){a(),r("fetchAgentConfig — GET /agent/{publicChatId}",{publicChatId:b});const U=await fetch(`${d}/agent/${encodeURIComponent(b)}`,{method:"GET",headers:{"Content-Type":"application/json"},...s?{credentials:"include"}:{}});return Ii(U)}async function R({sessionId:b,rating:U,feedback:z,endedBy:re}){if(a(),!b)throw new Error("sessionId is required");const K={...typeof U=="number"?{rating:U}:{},...z?{feedback:z}:{},...re?{ended_by:re}:{}};r("submitFeedback — PATCH /conversations/{sessionId}/feedback",{sessionId:b,payload:K});const ie=await fetch(`${d}/conversations/${encodeURIComponent(b)}/feedback`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(K),...s?{credentials:"include"}:{}});return Ii(ie)}return{initializeSession:f,joinDesktopSession:_,fetchAgentConfig:C,submitFeedback:R}}const Or=Object.create(null);Or.open="0";Or.close="1";Or.ping="2";Or.pong="3";Or.message="4";Or.upgrade="5";Or.noop="6";const Di=Object.create(null);Object.keys(Or).forEach(d=>{Di[Or[d]]=d});const fo={type:"error",data:"parser error"},qp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Wp=typeof ArrayBuffer=="function",Hp=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d&&d.buffer instanceof ArrayBuffer,xo=({type:d,data:r},s,a)=>qp&&r instanceof Blob?s?a(r):pp(r,a):Wp&&(r instanceof ArrayBuffer||Hp(r))?s?a(r):pp(new Blob([r]),a):a(Or[d]+(r||"")),pp=(d,r)=>{const s=new FileReader;return s.onload=function(){const a=s.result.split(",")[1];r("b"+(a||""))},s.readAsDataURL(d)};function fp(d){return d instanceof Uint8Array?d:d instanceof ArrayBuffer?new Uint8Array(d):new Uint8Array(d.buffer,d.byteOffset,d.byteLength)}let Ya;function fg(d,r){if(qp&&d.data instanceof Blob)return d.data.arrayBuffer().then(fp).then(r);if(Wp&&(d.data instanceof ArrayBuffer||Hp(d.data)))return r(fp(d.data));xo(d,!1,s=>{Ya||(Ya=new TextEncoder),r(Ya.encode(s))})}const mp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oi=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let d=0;d<mp.length;d++)oi[mp.charCodeAt(d)]=d;const mg=d=>{let r=d.length*.75,s=d.length,a,f=0,_,C,R,b;d[d.length-1]==="="&&(r--,d[d.length-2]==="="&&r--);const U=new ArrayBuffer(r),z=new Uint8Array(U);for(a=0;a<s;a+=4)_=oi[d.charCodeAt(a)],C=oi[d.charCodeAt(a+1)],R=oi[d.charCodeAt(a+2)],b=oi[d.charCodeAt(a+3)],z[f++]=_<<2|C>>4,z[f++]=(C&15)<<4|R>>2,z[f++]=(R&3)<<6|b&63;return U},gg=typeof ArrayBuffer=="function",Co=(d,r)=>{if(typeof d!="string")return{type:"message",data:Kp(d,r)};const s=d.charAt(0);return s==="b"?{type:"message",data:yg(d.substring(1),r)}:Di[s]?d.length>1?{type:Di[s],data:d.substring(1)}:{type:Di[s]}:fo},yg=(d,r)=>{if(gg){const s=mg(d);return Kp(s,r)}else return{base64:!0,data:d}},Kp=(d,r)=>{switch(r){case"blob":return d instanceof Blob?d:new Blob([d]);case"arraybuffer":default:return d instanceof ArrayBuffer?d:d.buffer}},jp="",wg=(d,r)=>{const s=d.length,a=new Array(s);let f=0;d.forEach((_,C)=>{xo(_,!1,R=>{a[C]=R,++f===s&&r(a.join(jp))})})},vg=(d,r)=>{const s=d.split(jp),a=[];for(let f=0;f<s.length;f++){const _=Co(s[f],r);if(a.push(_),_.type==="error")break}return a};function _g(){return new TransformStream({transform(d,r){fg(d,s=>{const a=s.length;let f;if(a<126)f=new Uint8Array(1),new DataView(f.buffer).setUint8(0,a);else if(a<65536){f=new Uint8Array(3);const _=new DataView(f.buffer);_.setUint8(0,126),_.setUint16(1,a)}else{f=new Uint8Array(9);const _=new DataView(f.buffer);_.setUint8(0,127),_.setBigUint64(1,BigInt(a))}d.data&&typeof d.data!="string"&&(f[0]|=128),r.enqueue(f),r.enqueue(s)})}})}let Ja;function Mi(d){return d.reduce((r,s)=>r+s.length,0)}function Pi(d,r){if(d[0].length===r)return d.shift();const s=new Uint8Array(r);let a=0;for(let f=0;f<r;f++)s[f]=d[0][a++],a===d[0].length&&(d.shift(),a=0);return d.length&&a<d[0].length&&(d[0]=d[0].slice(a)),s}function bg(d,r){Ja||(Ja=new TextDecoder);const s=[];let a=0,f=-1,_=!1;return new TransformStream({transform(C,R){for(s.push(C);;){if(a===0){if(Mi(s)<1)break;const b=Pi(s,1);_=(b[0]&128)===128,f=b[0]&127,f<126?a=3:f===126?a=1:a=2}else if(a===1){if(Mi(s)<2)break;const b=Pi(s,2);f=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(Mi(s)<8)break;const b=Pi(s,8),U=new DataView(b.buffer,b.byteOffset,b.length),z=U.getUint32(0);if(z>Math.pow(2,21)-1){R.enqueue(fo);break}f=z*Math.pow(2,32)+U.getUint32(4),a=3}else{if(Mi(s)<f)break;const b=Pi(s,f);R.enqueue(Co(_?b:Ja.decode(b),r)),a=0}if(f===0||f>d){R.enqueue(fo);break}}}})}const Qp=4;function $t(d){if(d)return Sg(d)}function Sg(d){for(var r in $t.prototype)d[r]=$t.prototype[r];return d}$t.prototype.on=$t.prototype.addEventListener=function(d,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+d]=this._callbacks["$"+d]||[]).push(r),this};$t.prototype.once=function(d,r){function s(){this.off(d,s),r.apply(this,arguments)}return s.fn=r,this.on(d,s),this};$t.prototype.off=$t.prototype.removeListener=$t.prototype.removeAllListeners=$t.prototype.removeEventListener=function(d,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var s=this._callbacks["$"+d];if(!s)return this;if(arguments.length==1)return delete this._callbacks["$"+d],this;for(var a,f=0;f<s.length;f++)if(a=s[f],a===r||a.fn===r){s.splice(f,1);break}return s.length===0&&delete this._callbacks["$"+d],this};$t.prototype.emit=function(d){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),s=this._callbacks["$"+d],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if(s){s=s.slice(0);for(var a=0,f=s.length;a<f;++a)s[a].apply(this,r)}return this};$t.prototype.emitReserved=$t.prototype.emit;$t.prototype.listeners=function(d){return this._callbacks=this._callbacks||{},this._callbacks["$"+d]||[]};$t.prototype.hasListeners=function(d){return!!this.listeners(d).length};const Vi=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,s)=>s(r,0),lr=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Tg="arraybuffer";function Xp(d,...r){return r.reduce((s,a)=>(d.hasOwnProperty(a)&&(s[a]=d[a]),s),{})}const Eg=lr.setTimeout,$g=lr.clearTimeout;function Gi(d,r){r.useNativeTimers?(d.setTimeoutFn=Eg.bind(lr),d.clearTimeoutFn=$g.bind(lr)):(d.setTimeoutFn=lr.setTimeout.bind(lr),d.clearTimeoutFn=lr.clearTimeout.bind(lr))}const xg=1.33;function Cg(d){return typeof d=="string"?kg(d):Math.ceil((d.byteLength||d.size)*xg)}function kg(d){let r=0,s=0;for(let a=0,f=d.length;a<f;a++)r=d.charCodeAt(a),r<128?s+=1:r<2048?s+=2:r<55296||r>=57344?s+=3:(a++,s+=4);return s}function Yp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Rg(d){let r="";for(let s in d)d.hasOwnProperty(s)&&(r.length&&(r+="&"),r+=encodeURIComponent(s)+"="+encodeURIComponent(d[s]));return r}function Ag(d){let r={},s=d.split("&");for(let a=0,f=s.length;a<f;a++){let _=s[a].split("=");r[decodeURIComponent(_[0])]=decodeURIComponent(_[1])}return r}class Ig extends Error{constructor(r,s,a){super(r),this.description=s,this.context=a,this.type="TransportError"}}class ko extends $t{constructor(r){super(),this.writable=!1,Gi(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,s,a){return super.emitReserved("error",new Ig(r,s,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(r){this.readyState==="open"&&this.write(r)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(r){const s=Co(r,this.socket.binaryType);this.onPacket(s)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,s={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(s)}_hostname(){const r=this.opts.hostname;return r.indexOf(":")===-1?r:"["+r+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(r){const s=Rg(r);return s.length?"?"+s:""}}class Mg extends ko{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const s=()=>{this.readyState="paused",r()};if(this._polling||!this.writable){let a=0;this._polling&&(a++,this.once("pollComplete",function(){--a||s()})),this.writable||(a++,this.once("drain",function(){--a||s()}))}else s()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){const s=a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)};vg(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,wg(r,s=>{this.doWrite(s,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",s=this.query||{};return this.opts.timestampRequests!==!1&&(s[this.opts.timestampParam]=Yp()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(r,s)}}let Jp=!1;try{Jp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Pg=Jp;function Og(){}class Dg extends Mg{constructor(r){if(super(r),typeof location<"u"){const s=location.protocol==="https:";let a=location.port;a||(a=s?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||a!==r.port}}doWrite(r,s){const a=this.request({method:"POST",data:r});a.on("success",s),a.on("error",(f,_)=>{this.onError("xhr post error",f,_)})}doPoll(){const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(s,a)=>{this.onError("xhr poll error",s,a)}),this.pollXhr=r}}class Pr extends $t{constructor(r,s,a){super(),this.createRequest=r,Gi(this,a),this._opts=a,this._method=a.method||"GET",this._uri=s,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var r;const s=Xp(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this._opts.xd;const a=this._xhr=this.createRequest(s);try{a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let f in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(f)&&a.setRequestHeader(f,this._opts.extraHeaders[f])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(r=this._opts.cookieJar)===null||r===void 0||r.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var f;a.readyState===3&&((f=this._opts.cookieJar)===null||f===void 0||f.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},a.send(this._data)}catch(f){this.setTimeoutFn(()=>{this._onError(f)},0);return}typeof document<"u"&&(this._index=Pr.requestsCount++,Pr.requests[this._index]=this)}_onError(r){this.emitReserved("error",r,this._xhr),this._cleanup(!0)}_cleanup(r){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Og,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Pr.requests[this._index],this._xhr=null}}_onLoad(){const r=this._xhr.responseText;r!==null&&(this.emitReserved("data",r),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Pr.requestsCount=0;Pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",gp);else if(typeof addEventListener=="function"){const d="onpagehide"in lr?"pagehide":"unload";addEventListener(d,gp,!1)}}function gp(){for(let d in Pr.requests)Pr.requests.hasOwnProperty(d)&&Pr.requests[d].abort()}const zg=(function(){const d=Zp({xdomain:!1});return d&&d.responseType!==null})();class Lg extends Dg{constructor(r){super(r);const s=r&&r.forceBase64;this.supportsBinary=zg&&!s}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Pr(Zp,this.uri(),r)}}function Zp(d){const r=d.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||Pg))return new XMLHttpRequest}catch{}if(!r)try{return new lr[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ef=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Bg extends ko{get name(){return"websocket"}doOpen(){const r=this.uri(),s=this.opts.protocols,a=ef?{}:Xp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(r,s,a)}catch(f){return this.emitReserved("error",f)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=r=>this.onClose({description:"websocket connection closed",context:r}),this.ws.onmessage=r=>this.onData(r.data),this.ws.onerror=r=>this.onError("websocket error",r)}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],f=s===r.length-1;xo(a,this.supportsBinary,_=>{try{this.doWrite(a,_)}catch{}f&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const r=this.opts.secure?"wss":"ws",s=this.query||{};return this.opts.timestampRequests&&(s[this.opts.timestampParam]=Yp()),this.supportsBinary||(s.b64=1),this.createUri(r,s)}}const Za=lr.WebSocket||lr.MozWebSocket;class Ng extends Bg{createSocket(r,s,a){return ef?new Za(r,s,a):s?new Za(r,s):new Za(r)}doWrite(r,s){this.ws.send(s)}}class Ug extends ko{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(r){return this.emitReserved("error",r)}this._transport.closed.then(()=>{this.onClose()}).catch(r=>{this.onError("webtransport error",r)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(r=>{const s=bg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(s).getReader(),f=_g();f.readable.pipeTo(r.writable),this._writer=f.writable.getWriter();const _=()=>{a.read().then(({done:R,value:b})=>{R||(this.onPacket(b),_())}).catch(R=>{})};_();const C={type:"open"};this.query.sid&&(C.data=`{"sid":"${this.query.sid}"}`),this._writer.write(C).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],f=s===r.length-1;this._writer.write(a).then(()=>{f&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const Fg={websocket:Ng,webtransport:Ug,polling:Lg},Vg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Gg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mo(d){if(d.length>8e3)throw"URI too long";const r=d,s=d.indexOf("["),a=d.indexOf("]");s!=-1&&a!=-1&&(d=d.substring(0,s)+d.substring(s,a).replace(/:/g,";")+d.substring(a,d.length));let f=Vg.exec(d||""),_={},C=14;for(;C--;)_[Gg[C]]=f[C]||"";return s!=-1&&a!=-1&&(_.source=r,_.host=_.host.substring(1,_.host.length-1).replace(/;/g,":"),_.authority=_.authority.replace("[","").replace("]","").replace(/;/g,":"),_.ipv6uri=!0),_.pathNames=qg(_,_.path),_.queryKey=Wg(_,_.query),_}function qg(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 Wg(d,r){const s={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,_){f&&(s[f]=_)}),s}const go=typeof addEventListener=="function"&&typeof removeEventListener=="function",zi=[];go&&addEventListener("offline",()=>{zi.forEach(d=>d())},!1);class as extends $t{constructor(r,s){if(super(),this.binaryType=Tg,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(s=r,r=null),r){const a=mo(r);s.hostname=a.host,s.secure=a.protocol==="https"||a.protocol==="wss",s.port=a.port,a.query&&(s.query=a.query)}else s.host&&(s.hostname=mo(s.host).host);Gi(this,s),this.secure=s.secure!=null?s.secure:typeof location<"u"&&location.protocol==="https:",s.hostname&&!s.port&&(s.port=this.secure?"443":"80"),this.hostname=s.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=s.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},s.transports.forEach(a=>{const f=a.prototype.name;this.transports.push(f),this._transportsByName[f]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},s),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ag(this.opts.query)),go&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},zi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const s=Object.assign({},this.opts.query);s.EIO=Qp,s.transport=r,this.id&&(s.sid=this.id);const a=Object.assign({},this.opts,{query:s,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[r]);return new this._transportsByName[r](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const r=this.opts.rememberUpgrade&&as.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const s=this.createTransport(r);s.open(),this.setTransport(s)}setTransport(r){this.transport&&this.transport.removeAllListeners(),this.transport=r,r.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",s=>this._onClose("transport close",s))}onOpen(){this.readyState="open",as.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",r),this.emitReserved("heartbeat"),r.type){case"open":this.onHandshake(JSON.parse(r.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const s=new Error("server error");s.code=r.data,this._onError(s);break;case"message":this.emitReserved("data",r.data),this.emitReserved("message",r.data);break}}onHandshake(r){this.emitReserved("handshake",r),this.id=r.sid,this.transport.query.sid=r.sid,this._pingInterval=r.pingInterval,this._pingTimeout=r.pingTimeout,this._maxPayload=r.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const r=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+r,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},r),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const r=this._getWritablePackets();this.transport.send(r),this._prevBufferLen=r.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let s=1;for(let a=0;a<this.writeBuffer.length;a++){const f=this.writeBuffer[a].data;if(f&&(s+=Cg(f)),a>0&&s>this._maxPayload)return this.writeBuffer.slice(0,a);s+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(this._pingTimeoutTime=0,Vi(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,s,a){return this._sendPacket("message",r,s,a),this}send(r,s,a){return this._sendPacket("message",r,s,a),this}_sendPacket(r,s,a,f){if(typeof s=="function"&&(f=s,s=void 0),typeof a=="function"&&(f=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;const _={type:r,data:s,options:a};this.emitReserved("packetCreate",_),this.writeBuffer.push(_),f&&this.once("flush",f),this.flush()}close(){const r=()=>{this._onClose("forced close"),this.transport.close()},s=()=>{this.off("upgrade",s),this.off("upgradeError",s),r()},a=()=>{this.once("upgrade",s),this.once("upgradeError",s)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():r()}):this.upgrading?a():r()),this}_onError(r){if(as.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",r),this._onClose("transport error",r)}_onClose(r,s){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),go&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=zi.indexOf(this._offlineEventListener);a!==-1&&zi.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,s),this.writeBuffer=[],this._prevBufferLen=0}}}as.protocol=Qp;class Hg extends as{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let r=0;r<this._upgrades.length;r++)this._probe(this._upgrades[r])}_probe(r){let s=this.createTransport(r),a=!1;as.priorWebsocketSuccess=!1;const f=()=>{a||(s.send([{type:"ping",data:"probe"}]),s.once("packet",re=>{if(!a)if(re.type==="pong"&&re.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;as.priorWebsocketSuccess=s.name==="websocket",this.transport.pause(()=>{a||this.readyState!=="closed"&&(z(),this.setTransport(s),s.send([{type:"upgrade"}]),this.emitReserved("upgrade",s),s=null,this.upgrading=!1,this.flush())})}else{const K=new Error("probe error");K.transport=s.name,this.emitReserved("upgradeError",K)}}))};function _(){a||(a=!0,z(),s.close(),s=null)}const C=re=>{const K=new Error("probe error: "+re);K.transport=s.name,_(),this.emitReserved("upgradeError",K)};function R(){C("transport closed")}function b(){C("socket closed")}function U(re){s&&re.name!==s.name&&_()}const z=()=>{s.removeListener("open",f),s.removeListener("error",C),s.removeListener("close",R),this.off("close",b),this.off("upgrading",U)};s.once("open",f),s.once("error",C),s.once("close",R),this.once("close",b),this.once("upgrading",U),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{a||s.open()},200):s.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const s=[];for(let a=0;a<r.length;a++)~this.transports.indexOf(r[a])&&s.push(r[a]);return s}}let Kg=class extends Hg{constructor(r,s={}){const a=typeof r=="object"?r:s;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(f=>Fg[f]).filter(f=>!!f)),super(r,a)}};function jg(d,r="",s){let a=d;s=s||typeof location<"u"&&location,d==null&&(d=s.protocol+"//"+s.host),typeof d=="string"&&(d.charAt(0)==="/"&&(d.charAt(1)==="/"?d=s.protocol+d:d=s.host+d),/^(https?|wss?):\/\//.test(d)||(typeof s<"u"?d=s.protocol+"//"+d:d="https://"+d),a=mo(d)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";const _=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+_+":"+a.port+r,a.href=a.protocol+"://"+_+(s&&s.port===a.port?"":":"+a.port),a}const Qg=typeof ArrayBuffer=="function",Xg=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d.buffer instanceof ArrayBuffer,tf=Object.prototype.toString,Yg=typeof Blob=="function"||typeof Blob<"u"&&tf.call(Blob)==="[object BlobConstructor]",Jg=typeof File=="function"||typeof File<"u"&&tf.call(File)==="[object FileConstructor]";function Ro(d){return Qg&&(d instanceof ArrayBuffer||Xg(d))||Yg&&d instanceof Blob||Jg&&d instanceof File}function Li(d,r){if(!d||typeof d!="object")return!1;if(Array.isArray(d)){for(let s=0,a=d.length;s<a;s++)if(Li(d[s]))return!0;return!1}if(Ro(d))return!0;if(d.toJSON&&typeof d.toJSON=="function"&&arguments.length===1)return Li(d.toJSON(),!0);for(const s in d)if(Object.prototype.hasOwnProperty.call(d,s)&&Li(d[s]))return!0;return!1}function Zg(d){const r=[],s=d.data,a=d;return a.data=yo(s,r),a.attachments=r.length,{packet:a,buffers:r}}function yo(d,r){if(!d)return d;if(Ro(d)){const s={_placeholder:!0,num:r.length};return r.push(d),s}else if(Array.isArray(d)){const s=new Array(d.length);for(let a=0;a<d.length;a++)s[a]=yo(d[a],r);return s}else if(typeof d=="object"&&!(d instanceof Date)){const s={};for(const a in d)Object.prototype.hasOwnProperty.call(d,a)&&(s[a]=yo(d[a],r));return s}return d}function ey(d,r){return d.data=wo(d.data,r),delete d.attachments,d}function wo(d,r){if(!d)return d;if(d&&d._placeholder===!0){if(typeof d.num=="number"&&d.num>=0&&d.num<r.length)return r[d.num];throw new Error("illegal attachments")}else if(Array.isArray(d))for(let s=0;s<d.length;s++)d[s]=wo(d[s],r);else if(typeof d=="object")for(const s in d)Object.prototype.hasOwnProperty.call(d,s)&&(d[s]=wo(d[s],r));return d}const ty=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Ye;(function(d){d[d.CONNECT=0]="CONNECT",d[d.DISCONNECT=1]="DISCONNECT",d[d.EVENT=2]="EVENT",d[d.ACK=3]="ACK",d[d.CONNECT_ERROR=4]="CONNECT_ERROR",d[d.BINARY_EVENT=5]="BINARY_EVENT",d[d.BINARY_ACK=6]="BINARY_ACK"})(Ye||(Ye={}));class ry{constructor(r){this.replacer=r}encode(r){return(r.type===Ye.EVENT||r.type===Ye.ACK)&&Li(r)?this.encodeAsBinary({type:r.type===Ye.EVENT?Ye.BINARY_EVENT:Ye.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let s=""+r.type;return(r.type===Ye.BINARY_EVENT||r.type===Ye.BINARY_ACK)&&(s+=r.attachments+"-"),r.nsp&&r.nsp!=="/"&&(s+=r.nsp+","),r.id!=null&&(s+=r.id),r.data!=null&&(s+=JSON.stringify(r.data,this.replacer)),s}encodeAsBinary(r){const s=Zg(r),a=this.encodeAsString(s.packet),f=s.buffers;return f.unshift(a),f}}class Ao extends $t{constructor(r){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof r=="function"?{reviver:r}:r)}add(r){let s;if(typeof r=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");s=this.decodeString(r);const a=s.type===Ye.BINARY_EVENT;a||s.type===Ye.BINARY_ACK?(s.type=a?Ye.EVENT:Ye.ACK,this.reconstructor=new sy(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(Ro(r)||r.base64)if(this.reconstructor)s=this.reconstructor.takeBinaryData(r),s&&(this.reconstructor=null,super.emitReserved("decoded",s));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+r)}decodeString(r){let s=0;const a={type:Number(r.charAt(0))};if(Ye[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===Ye.BINARY_EVENT||a.type===Ye.BINARY_ACK){const _=s+1;for(;r.charAt(++s)!=="-"&&s!=r.length;);const C=r.substring(_,s);if(C!=Number(C)||r.charAt(s)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!ny(R)||R<0)throw new Error("Illegal attachments");if(R>this.opts.maxAttachments)throw new Error("too many attachments");a.attachments=R}if(r.charAt(s+1)==="/"){const _=s+1;for(;++s&&!(r.charAt(s)===","||s===r.length););a.nsp=r.substring(_,s)}else a.nsp="/";const f=r.charAt(s+1);if(f!==""&&Number(f)==f){const _=s+1;for(;++s;){const C=r.charAt(s);if(C==null||Number(C)!=C){--s;break}if(s===r.length)break}a.id=Number(r.substring(_,s+1))}if(r.charAt(++s)){const _=this.tryParse(r.substr(s));if(Ao.isPayloadValid(a.type,_))a.data=_;else throw new Error("invalid payload")}return a}tryParse(r){try{return JSON.parse(r,this.opts.reviver)}catch{return!1}}static isPayloadValid(r,s){switch(r){case Ye.CONNECT:return yp(s);case Ye.DISCONNECT:return s===void 0;case Ye.CONNECT_ERROR:return typeof s=="string"||yp(s);case Ye.EVENT:case Ye.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&ty.indexOf(s[0])===-1);case Ye.ACK:case Ye.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class sy{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=ey(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ny=Number.isInteger||function(d){return typeof d=="number"&&isFinite(d)&&Math.floor(d)===d};function yp(d){return Object.prototype.toString.call(d)==="[object Object]"}const iy=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ao,Encoder:ry,get PacketType(){return Ye}},Symbol.toStringTag,{value:"Module"}));function br(d,r,s){return d.on(r,s),function(){d.off(r,s)}}const ay=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class rf extends $t{constructor(r,s,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=r,this.nsp=s,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const r=this.io;this.subs=[br(r,"open",this.onopen.bind(this)),br(r,"packet",this.onpacket.bind(this)),br(r,"error",this.onerror.bind(this)),br(r,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...s){var a,f,_;if(ay.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(s.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(s),this;const C={type:Ye.EVENT,data:s};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){const z=this.ids++,re=s.pop();this._registerAckCallback(z,re),C.id=z}const R=(f=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||f===void 0?void 0:f.writable,b=this.connected&&!(!((_=this.io.engine)===null||_===void 0)&&_._hasPingExpired());return this.flags.volatile&&!R||(b?(this.notifyOutgoingListeners(C),this.packet(C)):this.sendBuffer.push(C)),this.flags={},this}_registerAckCallback(r,s){var a;const f=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(f===void 0){this.acks[r]=s;return}const _=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let R=0;R<this.sendBuffer.length;R++)this.sendBuffer[R].id===r&&this.sendBuffer.splice(R,1);s.call(this,new Error("operation has timed out"))},f),C=(...R)=>{this.io.clearTimeoutFn(_),s.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...s){return new Promise((a,f)=>{const _=(C,R)=>C?f(C):a(R);_.withError=!0,s.push(_),this.emit(r,...s)})}_addToQueue(r){let s;typeof r[r.length-1]=="function"&&(s=r.pop());const a={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((f,..._)=>(this._queue[0],f!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),s&&s(f)):(this._queue.shift(),s&&s(null,..._)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(r=!1){if(!this.connected||this._queue.length===0)return;const s=this._queue[0];s.pending&&!r||(s.pending=!0,s.tryCount++,this.flags=s.flags,this.emit.apply(this,s.args))}packet(r){r.nsp=this.nsp,this.io._packet(r)}onopen(){typeof this.auth=="function"?this.auth(r=>{this._sendConnectPacket(r)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(r){this.packet({type:Ye.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},r):r})}onerror(r){this.connected||this.emitReserved("connect_error",r)}onclose(r,s){this.connected=!1,delete this.id,this.emitReserved("disconnect",r,s),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(r=>{if(!this.sendBuffer.some(a=>String(a.id)===r)){const a=this.acks[r];delete this.acks[r],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(r){if(r.nsp===this.nsp)switch(r.type){case Ye.CONNECT:r.data&&r.data.sid?this.onconnect(r.data.sid,r.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ye.EVENT:case Ye.BINARY_EVENT:this.onevent(r);break;case Ye.ACK:case Ye.BINARY_ACK:this.onack(r);break;case Ye.DISCONNECT:this.ondisconnect();break;case Ye.CONNECT_ERROR:this.destroy();const a=new Error(r.data.message);a.data=r.data.data,this.emitReserved("connect_error",a);break}}onevent(r){const s=r.data||[];r.id!=null&&s.push(this.ack(r.id)),this.connected?this.emitEvent(s):this.receiveBuffer.push(Object.freeze(s))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const s=this._anyListeners.slice();for(const a of s)a.apply(this,r)}super.emit.apply(this,r),this._pid&&r.length&&typeof r[r.length-1]=="string"&&(this._lastOffset=r[r.length-1])}ack(r){const s=this;let a=!1;return function(...f){a||(a=!0,s.packet({type:Ye.ACK,id:r,data:f}))}}onack(r){const s=this.acks[r.id];typeof s=="function"&&(delete this.acks[r.id],s.withError&&r.data.unshift(null),s.apply(this,r.data))}onconnect(r,s){this.id=r,this.recovered=s&&this._pid===s,this._pid=s,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(r=>this.emitEvent(r)),this.receiveBuffer=[],this.sendBuffer.forEach(r=>{this.notifyOutgoingListeners(r),this.packet(r)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(r=>r()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Ye.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const s=this._anyListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const s=this._anyOutgoingListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const s=this._anyOutgoingListeners.slice();for(const a of s)a.apply(this,r.data)}}}function un(d){d=d||{},this.ms=d.min||100,this.max=d.max||1e4,this.factor=d.factor||2,this.jitter=d.jitter>0&&d.jitter<=1?d.jitter:0,this.attempts=0}un.prototype.duration=function(){var d=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),s=Math.floor(r*this.jitter*d);d=(Math.floor(r*10)&1)==0?d-s:d+s}return Math.min(d,this.max)|0};un.prototype.reset=function(){this.attempts=0};un.prototype.setMin=function(d){this.ms=d};un.prototype.setMax=function(d){this.max=d};un.prototype.setJitter=function(d){this.jitter=d};class vo extends $t{constructor(r,s){var a;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(s=r,r=void 0),s=s||{},s.path=s.path||"/socket.io",this.opts=s,Gi(this,s),this.reconnection(s.reconnection!==!1),this.reconnectionAttempts(s.reconnectionAttempts||1/0),this.reconnectionDelay(s.reconnectionDelay||1e3),this.reconnectionDelayMax(s.reconnectionDelayMax||5e3),this.randomizationFactor((a=s.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new un({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(s.timeout==null?2e4:s.timeout),this._readyState="closed",this.uri=r;const f=s.parser||iy;this.encoder=new f.Encoder,this.decoder=new f.Decoder,this._autoConnect=s.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(r){return arguments.length?(this._reconnection=!!r,r||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(r){return r===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=r,this)}reconnectionDelay(r){var s;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(s=this.backoff)===null||s===void 0||s.setMin(r),this)}randomizationFactor(r){var s;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(s=this.backoff)===null||s===void 0||s.setJitter(r),this)}reconnectionDelayMax(r){var s;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(s=this.backoff)===null||s===void 0||s.setMax(r),this)}timeout(r){return arguments.length?(this._timeout=r,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(r){if(~this._readyState.indexOf("open"))return this;this.engine=new Kg(this.uri,this.opts);const s=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const f=br(s,"open",function(){a.onopen(),r&&r()}),_=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=br(s,"error",_);if(this._timeout!==!1){const R=this._timeout,b=this.setTimeoutFn(()=>{f(),_(new Error("timeout")),s.close()},R);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(f),this.subs.push(C),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(br(r,"ping",this.onping.bind(this)),br(r,"data",this.ondata.bind(this)),br(r,"error",this.onerror.bind(this)),br(r,"close",this.onclose.bind(this)),br(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(s){this.onclose("parse error",s)}}ondecoded(r){Vi(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){this.emitReserved("error",r)}socket(r,s){let a=this.nsps[r];return a?this._autoConnect&&!a.active&&a.connect():(a=new rf(this,r,s),this.nsps[r]=a),a}_destroy(r){const s=Object.keys(this.nsps);for(const a of s)if(this.nsps[a].active)return;this._close()}_packet(r){const s=this.encoder.encode(r);for(let a=0;a<s.length;a++)this.engine.write(s[a],r.options)}cleanup(){this.subs.forEach(r=>r()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(r,s){var a;this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,s),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const r=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const s=this.backoff.duration();this._reconnecting=!0;const a=this.setTimeoutFn(()=>{r.skipReconnect||(this.emitReserved("reconnect_attempt",r.backoff.attempts),!r.skipReconnect&&r.open(f=>{f?(r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",f)):r.onreconnect()}))},s);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){const r=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",r)}}const Zn={};function Bi(d,r){typeof d=="object"&&(r=d,d=void 0),r=r||{};const s=jg(d,r.path||"/socket.io"),a=s.source,f=s.id,_=s.path,C=Zn[f]&&_ in Zn[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let b;return R?b=new vo(a,r):(Zn[f]||(Zn[f]=new vo(a,r)),b=Zn[f]),s.query&&!r.query&&(r.query=s.queryKey),b.socket(s.path,r)}Object.assign(Bi,{Manager:vo,Socket:rf,io:Bi,connect:Bi});function oy({wsUrl:d,log:r}){let s=null;function a({authPayload:C,queryToken:R}){const b=Bi(d,{transports:["polling"],timeout:2e4,reconnection:!1,auth:C,query:R?{token:R}:void 0});return s=b,b}function f(){if(s){try{s.removeAllListeners(),s.connected?s.disconnect():s.close()}catch{}s=null}}function _(){return s}return{connectSocketRaw:a,cleanupSocket:f,getSocket:_}}const ly=d=>{if(window.audioCtx=d,d.state!=="suspended")return;const r=document.body,s=["touchstart","touchend","mousedown","keydown"];s.forEach(_=>r.addEventListener(_,a,!1));function a(){d.resume().then(f)}function f(){s.forEach(_=>r.removeEventListener(_,a))}};function Ot(d){this.init(d)}Ot.prototype.init=function(d){var r={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},r,d),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};Ot.prototype.getMaxValue=function(){var d={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ot.prototype.getTypedArray=function(){var d={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ot.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),ly(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Ot.prototype.resetState=function(){this.playingStartTime=-1,this.lastGotTimestamp=0,this.samples=new Float32Array,this.timeout=void 0,this.flag_request_stop=!1,this.startTime=0};Ot.prototype.isTypedArray=function(d){return d.byteLength&&d.buffer&&d.buffer.constructor==ArrayBuffer};Ot.prototype.feed=function(d){if(this.isTypedArray(d)){d=this.getFormatedValue(d);var r=new Float32Array(this.samples.length+d.length);r.set(this.samples,0),r.set(d,this.samples.length),this.samples=r,this.timeout||this.flush()}};Ot.prototype.getFormatedValue=function(r){var r=new this.typedArray(r.buffer),s=new Float32Array(r.length),a;for(a=0;a<r.length;a++)s[a]=r[a]/this.maxValue;return s};Ot.prototype.volume=function(d){this.gainNode.gain.value=d};Ot.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Ot.prototype.getTimestamp=function(d){if(this.playingStartTime>=0){if(!d)return this.audioCtx.currentTime-this.playingStartTime;const r=this.lastGotTimestamp;return this.lastGotTimestamp+=d/1e3,r}return 0};Ot.prototype.setRequestStop=function(){this.flag_request_stop=!0};Ot.prototype.setOnEnd=function(d){this.onEnd=d};Ot.prototype.interrupt=function(d){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};Ot.prototype.ensuredSetTimeout=(function(){let d;return function(r,s){d=performance.now();const a=f=>{f-d>=s?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Ot.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Ot.prototype.flush=function(){if(this.samples.length){var d=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,s=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,f,_,C,R;for(f=0;f<this.option.channels;f++)for(a=s.getChannelData(f),_=f,R=50,C=0;C<r;C++)a[C]=this.samples[_],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),_+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,d.buffer=s,d.connect(this.gainNode),d.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=d,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=s.duration,this.flag_request_stop)this.flag_request_stop=!1,d.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const b=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,b-50)}}};function uy(d,r){const s=new Ot(d),a=s.destroy.bind(s);let f=!1;return s.destroy=()=>{if(!f){f=!0;try{a()}catch{}}},s.setOnEnd(()=>{f||r()}),s._isDestroyed=()=>f,s}function dy({enableAudio:d,pcmOptions:r,log:s,onPlaybackComplete:a}){let f=null,_=null;function C(){if(!d||f)return f;const H={...Gp,...r||{}};return f=uy(H,()=>{a()}),f}function R(){if(f){try{f.interrupt?.(),f.destroy?.()}catch{}f=null}}function b(H){const se=C();if(se)try{se.feed(H)}catch(ve){s("feedAudio: player.feed() failed",ve),a()}}function U(){if(!f){a();return}try{f.setRequestStop(),f.playingBufferNode||f.scheduledBufferNode||a()}catch(H){s("requestStop: setRequestStop() failed",H),a()}}function z(){R()}function re(){if(f)try{const H=f.audioCtx;H?.state==="running"&&H.suspend()}catch(H){s("pauseAudioPlayback: audioCtx.suspend() failed",H)}}async function K(){const H=C();if(H)try{const se=H.audioCtx;se?.state==="suspended"&&await se.resume()}catch(se){s("resumeAudioPlayback: audioCtx.resume() failed",se)}}function ie(H){_=H||null}function J(){return _}function Y(){return f?f._isDestroyed?.()??!0:!0}return{ensurePcmPlayer:C,destroyPcmPlayer:R,feedAudio:b,requestStop:U,interruptPlayback:z,pauseAudioPlayback:re,resumeAudioPlayback:K,attachAudioElement:ie,getAudioElement:J,isDestroyed:Y}}function cy(d){const{wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:_,withCredentials:C,onPlaybackComplete:R}=d,b=oe.useCallback((...K)=>{_&&console.log("[RqmiiSDK]",...K)},[_]),U=oe.useRef(null),z=oe.useRef(null),re=oe.useRef(null);return U.current||(U.current=oy({wsUrl:r,log:b})),z.current||(z.current=dy({enableAudio:a,pcmOptions:f,log:b,onPlaybackComplete:R})),re.current||(re.current=pg({restUrl:s,log:b,withCredentials:C})),oe.useEffect(()=>()=>{U.current?.cleanupSocket(),z.current?.destroyPcmPlayer()},[]),{socketMgrRef:U,audioMgrRef:z,sessionMgrRef:re,log:b}}function eo(d){return String(d||"").toLowerCase().replaceAll("-","_")}function hy(d){if(!d)return null;if(d instanceof Uint8Array)return d;if(d instanceof ArrayBuffer)return new Uint8Array(d);if(typeof d=="object"&&d!==null){const r=d;if(r.buffer instanceof ArrayBuffer){const s=d,a=Number.isInteger(s.byteOffset)?s.byteOffset:0,f=Number.isInteger(s.byteLength)?s.byteLength:s.buffer.byteLength-a;return new Uint8Array(s.buffer,a,f)}if(r.type==="Buffer"&&Array.isArray(r.data))return new Uint8Array(r.data)}try{return new Uint8Array(d)}catch{return null}}function py(d){const{socket:r,dispatch:s,stateRef:a,sessionIdRef:f,sessionAgentTypeRef:_,interruptedRef:C,manualDisconnectRef:R,chunkAccumulatorRef:b,clientToolsRef:U,audioMgrRef:z,enableAudio:re,cbRefs:K,eventsEmitter:ie}=d,J=_r,Y=z.current;r.on(J.DISCONNECT,H=>{if(s({type:"SET_CONNECTION_STATE",payload:ft.IDLE}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onDisconnect?.(H),H==="io server disconnect"||H==="io client disconnect"||R.current){s({type:"SET_CONNECTION_STATE",payload:ft.ENDED});return}s({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),s({type:"SET_ERROR",payload:"Connection lost"})}),r.on(J.SESSION_READY,H=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null}),H?.agentType&&s({type:"UPDATE_SESSION",payload:{agentType:eo(H.agentType)}})}),r.on(J.SESSION_JOINED,()=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null})}),r.on(J.SESSION_TERMINATED,()=>{Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onSessionTerminated?.(),r.disconnect()}),r.on(J.TRANSCRIPT,H=>{const se=H||null;s({type:"SET_TRANSCRIPT",payload:se}),se?.is_final&&se?.text?.trim()&&(s({type:"ADD_MESSAGE",payload:{id:`transcript-${Date.now()}`,role:"user",text:se.text.trim(),timestamp:new Date().toISOString()}}),s({type:"SET_PARTIAL_TRANSCRIPT",payload:null})),ie.emit("transcript",se??void 0),ie.emit("partial_transcript",void 0)}),r.on(J.PARTIAL_TRANSCRIPT,H=>{const se=typeof H=="string"?H:H?.text;if(typeof se=="string"&&se.length===0)return;const ve=H||null;s({type:"SET_PARTIAL_TRANSCRIPT",payload:ve}),ie.emit("partial_transcript",ve??void 0)}),r.on(J.AGENT_RESPONSE_CHUNK,H=>{const{id:se,text:ve}=b.current.addChunk(H?.requestId,H?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==se),{id:se,role:"assistant",text:ve,streaming:!0,timestamp:new Date().toISOString()}]})}),r.on(J.AGENT_RESPONSE,H=>{const{id:se,text:ve}=b.current.consume(H?.requestId,H?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==se),{id:se,role:"assistant",text:ve,streaming:!1,timestamp:new Date().toISOString()}]})}),r.on(J.AVATAR_SPEAKING,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!0})}),r.on(J.AVATAR_SPEAKING_DONE,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!1})}),r.on(J.AGENT_AUDIO_CHUNK,H=>{if(!re||C.current)return;const se=eo(_.current);if(se==="cloud_avatar"||se==="desktop_avatar"||se==="text")return;const ve=hy(H?.audio);ve&&(Y.feedAudio(ve),s({type:"SET_AUDIO_PLAYING",payload:!0}))}),r.on(J.AGENT_AUDIO_COMPLETE,()=>{if(!re)return;const H=eo(_.current);H==="cloud_avatar"||H==="desktop_avatar"||H==="text"||Y.requestStop()}),r.on(J.INTERRUPTED,()=>{const H=!Y.isDestroyed();C.current=!1,Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),H&&r.connected&&r.emit(J.AUDIO_PLAYBACK_COMPLETE,{session_id:f.current})}),r.on(J.AUTH_ERROR,H=>{s({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),s({type:"SET_ERROR",payload:H?.message||"Authentication error"})}),r.on(J.ERROR,H=>{const se=H?.code;if(!(se==="TTS_ERROR"||se==="STT_ERROR")){if(se==="INSUFFICIENT_CREDITS"){s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:H?.message||"Insufficient credits to process this request."}}),K.current.onError?.(H);return}s({type:"SET_ERROR",payload:H?.message||H?.detail||"Server error"}),K.current.onError?.(H)}}),r.on(J.SESSION_EXPIRED,H=>{s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onSessionExpired?.(H)}),r.on(J.CREDITS_EXHAUSTED,()=>{s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:"This project has run out of credits."}}),s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),R.current=!0;try{r.disconnect()}catch{}}),r.on(J.SESSION_STATE_CHANGED,H=>{H?.state&&s({type:"SET_SESSION_STATE",payload:H.state})}),r.on(J.LANGUAGE_CHANGED,H=>{const se=H?.language;se&&ie.emit("language_changed",{language:se})}),r.on(J.CLIENT_TOOL_REQUEST,H=>{const se=H?.executionId,ve=H?.toolName,de=H?.parameters??{},he=H?.waitForResponse!==!1;if(!ve)return;const pe=U.current[ve];pe&&(he&&se?pe(de).then(ce=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:se,result:ce})}).catch(ce=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:se,result:{error:ce instanceof Error?ce.message:String(ce)}})}):pe(de).catch(()=>{}))})}class sf{listeners=new Map;on(r,s){return this.listeners.has(r)||this.listeners.set(r,new Set),this.listeners.get(r).add(s),()=>this.off(r,s)}once(r,s){const a=((...f)=>{this.off(r,a),s(...f)});return this.on(r,a)}off(r,s){this.listeners.get(r)?.delete(s)}emit(r,s){const a=this.listeners.get(r);if(a)for(const f of a)try{f(s)}catch{}}removeAllListeners(){this.listeners.clear()}}const nf=oe.createContext(null);function af({children:d,wsUrl:r,restUrl:s,enableAudio:a=!0,pcmOptions:f,debug:_=!1,heartbeatIntervalSeconds:C=15,withCredentials:R=!1,onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re}){const[K,ie]=oe.useReducer(hp,po),J=oe.useRef(K),Y=oe.useCallback(xe=>{J.current=hp(J.current,xe),ie(xe)},[]),H=oe.useRef(!1),se=oe.useRef(cg()),ve=oe.useRef(null),de=oe.useRef(po.session.agentType),he=oe.useRef(!1),pe=oe.useRef(new sf),ce=oe.useRef({}),Ke=oe.useRef({onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re});oe.useEffect(()=>{Ke.current={onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re}},[b,U,z,re]),oe.useEffect(()=>{de.current=K.session.agentType},[K.session.agentType]),oe.useEffect(()=>{ve.current=K.session.sessionId},[K.session.sessionId]);const fe=oe.useCallback(()=>{Y({type:"SET_AUDIO_PLAYING",payload:!1});const xe=Je.current?.getSocket();xe?.connected&&xe.emit(_r.AUDIO_PLAYBACK_COMPLETE,{session_id:ve.current})},[]),{socketMgrRef:Je,audioMgrRef:Ge,sessionMgrRef:ot}=cy({wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:_,withCredentials:R,onPlaybackComplete:fe}),Ze=oe.useCallback(xe=>{py({socket:xe,dispatch:Y,stateRef:J,sessionIdRef:ve,sessionAgentTypeRef:de,interruptedRef:he,manualDisconnectRef:H,chunkAccumulatorRef:se,clientToolsRef:ce,audioMgrRef:{current:Ge.current},enableAudio:a,cbRefs:Ke,eventsEmitter:pe.current})},[a]),it=oe.useCallback(({authPayload:xe,queryToken:Qe})=>new Promise((Nt,nr)=>{Je.current?.cleanupSocket();const It=Je.current.connectSocketRaw({authPayload:xe,queryToken:Qe});Ze(It),It.once("connect",()=>{Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTED}),Y({type:"SET_ERROR",payload:null}),Nt(It)}),It.once("connect_error",Yr=>{Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Yr?.message||"Connection error"}),nr(Yr)})}),[Ze]),tt=oe.useCallback(({keepManualDisconnect:xe=!1}={})=>{H.current=!0,he.current=!1,se.current.clear(),Ge.current.destroyPcmPlayer(),Je.current.cleanupSocket(),xe||(H.current=!1),Y({type:"HARD_RESET"})},[]),Wt=oe.useCallback(async({apiKey:xe,publicChatId:Qe,agentId:Nt,userId:nr,language:It="en",clientTools:Yr,config:hn}={})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!xe&&!Qe&&!Nt)throw new Error("Provide one of apiKey, publicChatId, or agentId");tt(),ce.current=Yr??{},Y({type:"SET_CONNECTION_STATE",payload:ft.INITIALIZING}),Y({type:"SET_ERROR",payload:null});const ls=hg();let ct;try{ct=await ot.current.initializeSession({apiKey:xe,publicChatId:Qe,agentId:Nt,userId:nr,language:It,timezone:ls,config:hn})}catch($r){const Lt=$r;throw Lt.status===401||Lt.status===403?(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Authentication failed"})):Lt.status===402?(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:Lt.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED})):Lt.status===429?(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Too many requests. Please try again later."})):(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Failed to initialize session"})),$r}const Ut=ct;Y({type:"UPDATE_SESSION",payload:{sessionId:Ut.session_id,agentType:Ut.streaming_url?di.CLOUD_AVATAR:K.session.agentType,streamingUrl:Ut.streaming_url||null,uniqueId:Ut.unique_id||null}}),Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Ut.streaming_url?Zt.CONNECTING:Zt.IDLE,error:null}}),H.current=!0;try{await it({authPayload:{token:Ut.session_token},queryToken:Ut.session_token}),H.current=!1}catch($r){throw H.current=!1,$r}return ct},[it,tt,r,K.session.agentType]),xt=oe.useCallback(async({uniqueId:xe})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!xe)throw new Error("uniqueId is required");tt(),Y({type:"SET_CONNECTION_STATE",payload:ft.INITIALIZING}),Y({type:"SET_ERROR",payload:null});let Qe;try{Qe=await ot.current.joinDesktopSession({uniqueId:xe})}catch(nr){const It=nr;throw(It.status===401||It.status===403)&&(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Authentication failed"})),It.status===402&&(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:It.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED})),It.status===429&&(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Too many requests. Please try again later."})),nr}const Nt=Qe;Y({type:"UPDATE_SESSION",payload:{sessionId:Nt.session_id,uniqueId:xe,role:"user",agentType:di.DESKTOP_AVATAR}}),Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Zt.IDLE,error:null}}),H.current=!0;try{await it({authPayload:{token:Nt.session_token},queryToken:Nt.session_token}),H.current=!1}catch(nr){throw H.current=!1,nr}return Qe},[it,tt,r]),je=oe.useCallback(()=>tt({keepManualDisconnect:!0}),[tt]),qe=oe.useCallback(async()=>{const xe=Je.current?.getSocket();return xe&&K.isConnected&&(xe.emit("end_session"),await new Promise(Qe=>setTimeout(Qe,150))),je(),{success:!0}},[je,K.isConnected]),st=oe.useCallback(()=>{const xe=Je.current?.getSocket();xe?.connected?xe.emit("end_session"):(Y({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),Y({type:"SET_SESSION_READY",payload:!1}))},[]),ze=oe.useCallback((xe,Qe={})=>{const Nt=Je.current?.getSocket();return!Nt||!K.isConnected?!1:(Nt.emit(xe,Qe),!0)},[K.isConnected]),At=oe.useCallback(xe=>!xe||!String(xe).trim()?!1:(Y({type:"ADD_MESSAGE",payload:{id:`user-${Date.now()}`,role:"user",text:String(xe),timestamp:new Date().toISOString()}}),ze(_r.USER_MESSAGE,{message:String(xe)})),[ze]),sr=oe.useCallback((xe,Qe)=>{!Qe||!String(Qe).trim()||Y({type:"ADD_MESSAGE",payload:{id:`${xe}-${Date.now()}`,role:xe,text:String(Qe),timestamp:new Date().toISOString()}})},[]),Hr=oe.useCallback(xe=>!xe||!String(xe).trim()?!1:ze(_r.USER_MESSAGE,{message:String(xe)}),[ze]),Us=oe.useCallback(xe=>ze(_r.AUDIO_CHUNK,{audio:xe}),[ze]),Kr=oe.useCallback(()=>ze(_r.AUDIO_END,{}),[ze]),jr=oe.useCallback(()=>(he.current=!0,Ge.current.interruptPlayback(),Y({type:"SET_AUDIO_PLAYING",payload:!1}),ze(_r.INTERRUPT,{})),[ze]),Fs=oe.useCallback(()=>ze(_r.CLEAR_SESSION_HISTORY,{}),[ze]),rt=oe.useCallback(xe=>xe?ze(_r.CHANGE_SESSION_LANGUAGE,{language:xe}):!1,[ze]),Tr=oe.useCallback((xe={})=>ze(_r.CLIENT_READY,xe),[ze]),lt=oe.useCallback(()=>{se.current.clear(),Y({type:"SET_MESSAGES",payload:[]})},[]),Qr=oe.useCallback(()=>Ge.current.resumeAudioPlayback(),[]),er=oe.useCallback(()=>Ge.current.pauseAudioPlayback(),[]),Er=oe.useCallback(xe=>Ge.current.attachAudioElement(xe),[]),gt=oe.useCallback((xe,Qe=null)=>{Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:xe,error:Qe?String(Qe):null}})},[]),yt=oe.useCallback(async xe=>{if(!s)throw new Error("Missing restUrl in RqmiiAgentProvider");try{const Qe=await ot.current.fetchAgentConfig(xe);return Y({type:"SET_AGENT_CONFIG",payload:Qe}),Qe}catch(Qe){throw Y({type:"SET_AGENT_CONFIG",payload:null}),Qe}},[s]),Ct=oe.useCallback(xe=>{ce.current={...ce.current,...xe}},[]),kt=oe.useCallback(xe=>{const Qe=xe.sessionId||ve.current;return Qe?ot.current.submitFeedback({sessionId:Qe,rating:xe.rating,feedback:xe.feedback,endedBy:xe.endedBy}):Promise.reject(new Error("No session id available for feedback"))},[]),Xr=oe.useMemo(()=>dg(K.sessionState),[K.sessionState]),os=oe.useMemo(()=>({...K,...Xr,initializeSession:Wt,joinDesktopSession:xt,disconnect:je,terminateSession:qe,endSession:st,emit:ze,sendTextMessage:At,addLocalMessage:sr,emitUserMessage:Hr,sendAudioChunk:Us,endAudioStream:Kr,interrupt:jr,clearSessionHistory:Fs,changeSessionLanguage:rt,signalClientReady:Tr,clearMessages:lt,resumeAudioPlayback:Qr,pauseAudioPlayback:er,attachAudioElement:Er,fetchAgentConfig:yt,submitFeedback:kt,setCloudStreamState:gt,registerClientTools:Ct,events:pe.current,audioElement:Ge.current?.getAudioElement()??null,socket:Je.current?.getSocket()??null}),[K,Xr,Wt,xt,je,qe,st,ze,At,sr,Hr,Us,Kr,jr,Fs,rt,Tr,lt,Qr,er,Er,gt,Ct,kt]);return Jt.jsx(nf.Provider,{value:os,children:d})}function dn(){const d=oe.useContext(nf);if(!d)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return d}function of(){const d=dn();return{connectionState:d.connectionState,isConnected:d.isConnected,isSessionReady:d.isSessionReady,error:d.error,session:d.session,creditExhausted:d.creditExhausted,creditError:d.creditError,sessionState:d.sessionState,isSessionTerminated:d.isSessionTerminated,isSessionTerminating:d.isSessionTerminating,isAgentThinking:d.isAgentThinking,isAgentSpeaking:d.isAgentSpeaking,isToolExecuting:d.isToolExecuting,agentConfig:d.agentConfig,initializeSession:d.initializeSession,joinDesktopSession:d.joinDesktopSession,disconnect:d.disconnect,terminateSession:d.terminateSession,endSession:d.endSession,interrupt:d.interrupt,clearSessionHistory:d.clearSessionHistory,changeSessionLanguage:d.changeSessionLanguage,signalClientReady:d.signalClientReady,fetchAgentConfig:d.fetchAgentConfig,submitFeedback:d.submitFeedback,registerClientTools:d.registerClientTools}}function fy(){const d=dn();return{messages:d.messages,sendTextMessage:d.sendTextMessage,addLocalMessage:d.addLocalMessage,emitUserMessage:d.emitUserMessage,clearMessages:d.clearMessages}}function my(){const d=dn();return{sendAudioChunk:d.sendAudioChunk,endAudioStream:d.endAudioStream,isAudioPlaying:d.isAudioPlaying,transcript:d.transcript,partialTranscript:d.partialTranscript,interrupt:d.interrupt,resumeAudioPlayback:d.resumeAudioPlayback,pauseAudioPlayback:d.pauseAudioPlayback,attachAudioElement:d.attachAudioElement}}function lf(){const d=dn(),r=d.cloudStream?.state||Zt.IDLE;return{streamingUrl:d.session.streamingUrl,isAvatarSpeaking:d.isAvatarSpeaking,speakingSource:"avatar_events",isCloudAvatar:d.session.agentType===di.CLOUD_AVATAR,isDesktopAvatar:d.session.agentType===di.DESKTOP_AVATAR,cloudStreamState:r,cloudStreamError:d.cloudStream?.error||null,isCloudStreamConnected:r===Zt.CONNECTED,isCloudStreamLoading:r===Zt.CONNECTING||r===Zt.LOADING,setCloudStreamState:d.setCloudStreamState}}var to={},ro={},ei={},wp;function uf(){if(wp)return ei;wp=1,Object.defineProperty(ei,"__esModule",{value:!0}),ei.baseAssetPath=void 0;const r=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let s="/";return r&&(s=r.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),ei.baseAssetPath=s,ei}var ti={},vp;function Io(){if(vp)return ti;vp=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.defaultModelFetcher=void 0;const d=r=>fetch(r).then(s=>s.arrayBuffer());return ti.defaultModelFetcher=d,ti}var Fr={},ri={},_p;function ci(){if(_p)return ri;_p=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.log=void 0;const d=r=>s=>{console.log(`VAD | ${r} >`,s)};return ri.log={error:d("error"),debug:d("debug"),warn:d("warn")},ri}var si={},bp;function qi(){if(bp)return si;bp=1,Object.defineProperty(si,"__esModule",{value:!0}),si.Message=void 0;var d;return(function(r){r.AudioFrame="AUDIO_FRAME",r.SpeechStart="SPEECH_START",r.VADMisfire="VAD_MISFIRE",r.SpeechEnd="SPEECH_END",r.SpeechStop="SPEECH_STOP",r.SpeechRealStart="SPEECH_REAL_START",r.FrameProcessed="FRAME_PROCESSED"})(d||(si.Message=d={})),si}var Sp;function Mo(){if(Sp)return Fr;Sp=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.FrameProcessor=Fr.validateOptions=Fr.defaultFrameProcessorOptions=void 0;const d=ci(),r=qi();Fr.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function s(C){(C.positiveSpeechThreshold<0||C.positiveSpeechThreshold>1)&&d.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(C.negativeSpeechThreshold<0||C.negativeSpeechThreshold>C.positiveSpeechThreshold)&&d.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),C.preSpeechPadMs<0&&d.log.error("preSpeechPadMs should be positive"),C.redemptionMs<0&&d.log.error("redemptionMs should be positive"),C.minSpeechMs<0&&d.log.error("minSpeechMs should be positive")}Fr.validateOptions=s;const a=C=>{const R=C.reduce((U,z)=>(U.push(U.at(-1)+z.length),U),[0]),b=new Float32Array(R.at(-1));return C.forEach((U,z)=>{const re=R[z];b.set(U,re)}),b};function f(C,R){const b=Math.floor(C.redemptionMs/R),U=Math.floor(C.preSpeechPadMs/R),z=Math.floor(C.minSpeechMs/R);return{redemptionFrames:b,preSpeechPadFrames:U,minSpeechFrames:z}}class _{constructor(R,b,U,z){this.modelProcessFunc=R,this.modelResetFunc=b,this.options=U,this.msPerFrame=z,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=J=>{this.options={...this.options,...J};const{redemptionFrames:Y,preSpeechPadFrames:H,minSpeechFrames:se}=f(this.options,this.msPerFrame);this.redemptionFrames=Y,this.preSpeechPadFrames=H,this.minSpeechFrames=se},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=J=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(J):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=J=>{const Y=this.audioBuffer;this.audioBuffer=[];const H=this.speaking;if(this.reset(),H)if(Y.reduce((ve,de)=>de.isSpeech?ve+1:ve,0)>=this.minSpeechFrames){const ve=a(Y.map(de=>de.frame));J({msg:r.Message.SpeechEnd,audio:ve})}else J({msg:r.Message.VADMisfire});return{}},this.process=async(J,Y)=>{if(!this.active)return;const H=await this.modelProcessFunc(J),se=H.isSpeech>=this.options.positiveSpeechThreshold;if(Y({probs:H,msg:r.Message.FrameProcessed,frame:J}),this.audioBuffer.push({frame:J,isSpeech:se}),se&&(this.speechFrameCount++,this.redemptionCounter=0),se&&!this.speaking&&(this.speaking=!0,Y({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,Y({msg:r.Message.SpeechRealStart})),H.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const ve=this.audioBuffer;if(this.audioBuffer=[],ve.reduce((he,pe)=>pe.isSpeech?he+1:he,0)>=this.minSpeechFrames){const he=a(ve.map(pe=>pe.frame));Y({msg:r.Message.SpeechEnd,audio:he})}else Y({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:re,preSpeechPadFrames:K,minSpeechFrames:ie}=f(this.options,this.msPerFrame);this.redemptionFrames=re,this.preSpeechPadFrames=K,this.minSpeechFrames=ie,this.reset()}}return Fr.FrameProcessor=_,Fr}var Vr={};function ur(d){throw new Error('Could not dynamically require "'+d+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var so={exports:{}};/*!
|
|
2
|
+
* ONNX Runtime Web v1.26.0
|
|
3
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
4
|
+
* Licensed under the MIT License.
|
|
5
|
+
*/var Tp;function gy(){return Tp||(Tp=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,_=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(e=>typeof ur<"u"?ur:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof ur<"u"?ur:t)[n]}):e)(function(e){if(typeof ur<"u")return ur.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),b=(e,t)=>()=>(e&&(t=e(e=0)),t),U=(e,t)=>{for(var n in t)a(e,n,{get:t[n],enumerable:!0})},z=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _(t))!C.call(e,o)&&o!==n&&a(e,o,{get:()=>t[o],enumerable:!(i=f(t,o))||i.enumerable});return e},re=e=>z(a({},"__esModule",{value:!0}),e),K,ie,J,Y,H,se=b(()=>{K=new Map,ie=[],J=(e,t,n)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=K.get(e);if(i===void 0)K.set(e,{backend:t,priority:n});else{if(i.priority>n)return;if(i.priority===n&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let o=ie.indexOf(e);o!==-1&&ie.splice(o,1);for(let l=0;l<ie.length;l++)if(K.get(ie[l]).priority<=n){ie.splice(l,0,e);return}ie.push(e)}return}throw new TypeError("not a valid backend")},Y=async e=>{let t=K.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return n||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},H=async e=>{let t=e.executionProviders||[],n=t.map(h=>typeof h=="string"?h:h.name),i=n.length===0?ie:n,o,l=[],u=new Set;for(let h of i){let p=await Y(h);typeof p=="string"?l.push({name:h,err:p}):(o||(o=p),o===p&&u.add(h))}if(!o)throw new Error(`no available backend found. ERR: ${l.map(h=>`[${h.name}] ${h.err}`).join(", ")}`);for(let{name:h,err:p}of l)n.includes(h)&&console.warn(`removing requested execution provider "${h}" from session options because it is not available: ${p}`);let c=t.filter(h=>u.has(typeof h=="string"?h:h.name));return[o,new Proxy(e,{get:(h,p)=>p==="executionProviders"?c:Reflect.get(h,p)})]}}),ve=b(()=>{se()}),de,he=b(()=>{de="1.26.0"}),pe,ce,Ke=b(()=>{he(),pe="warning",ce={wasm:{},webgl:{},webgpu:{},versions:{common:de},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);pe=e}},get logLevel(){return pe}},Object.defineProperty(ce,"logLevel",{enumerable:!0})}),fe,Je=b(()=>{Ke(),fe=ce}),Ge,ot,Ze=b(()=>{Ge=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let i=n.getContext("2d");if(i!=null){let o,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[3]):(o=e.dims[3],l=e.dims[2]);let u=t?.format!==void 0?t.format:"RGB",c=t?.norm,h,p;c===void 0||c.mean===void 0?h=[255,255,255,255]:typeof c.mean=="number"?h=[c.mean,c.mean,c.mean,c.mean]:(h=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(h[3]=c.mean[3])),c===void 0||c.bias===void 0?p=[0,0,0,0]:typeof c.bias=="number"?p=[c.bias,c.bias,c.bias,c.bias]:(p=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(p[3]=c.bias[3]));let m=l*o,g=0,w=m,v=m*2,S=-1;u==="RGBA"?(g=0,w=m,v=m*2,S=m*3):u==="RGB"?(g=0,w=m,v=m*2):u==="RBG"&&(g=0,v=m,w=m*2);for(let x=0;x<l;x++)for(let M=0;M<o;M++){let k=(e.data[g++]-p[0])*h[0],$=(e.data[w++]-p[1])*h[1],P=(e.data[v++]-p[2])*h[2],I=S===-1?255:(e.data[S++]-p[3])*h[3];i.fillStyle="rgba("+k+","+$+","+P+","+I+")",i.fillRect(M,x,1,1)}if("toDataURL"in n)return n.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},ot=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(n!=null){let o,l,u;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[1],u=e.dims[3]):(o=e.dims[3],l=e.dims[2],u=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",h=t?.norm,p,m;h===void 0||h.mean===void 0?p=[255,255,255,255]:typeof h.mean=="number"?p=[h.mean,h.mean,h.mean,h.mean]:(p=[h.mean[0],h.mean[1],h.mean[2],255],h.mean[3]!==void 0&&(p[3]=h.mean[3])),h===void 0||h.bias===void 0?m=[0,0,0,0]:typeof h.bias=="number"?m=[h.bias,h.bias,h.bias,h.bias]:(m=[h.bias[0],h.bias[1],h.bias[2],0],h.bias[3]!==void 0&&(m[3]=h.bias[3]));let g=l*o;if(t!==void 0&&(t.format!==void 0&&u===4&&t.format!=="RGBA"||u===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let w=4,v=0,S=1,x=2,M=3,k=0,$=g,P=g*2,I=-1;c==="RGBA"?(k=0,$=g,P=g*2,I=g*3):c==="RGB"?(k=0,$=g,P=g*2):c==="RBG"&&(k=0,P=g,$=g*2),i=n.createImageData(o,l);for(let B=0;B<l*o;v+=w,S+=w,x+=w,M+=w,B++)i.data[v]=(e.data[k++]-m[0])*p[0],i.data[S]=(e.data[$++]-m[1])*p[1],i.data[x]=(e.data[P++]-m[2])*p[2],i.data[M]=I===-1?255:(e.data[I++]-m[3])*p[3]}else throw new Error("Can not access image data");return i}}),it,tt,Wt,xt,je,qe,st=b(()=>{Tr(),it=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:n,width:i}=t,o=t.norm??{mean:255,bias:0},l,u;typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:l=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?u=[o.bias,o.bias,o.bias,o.bias]:u=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let c=t.format!==void 0?t.format:"RGBA",h=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=n*i,m=h==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),g=4,w=0,v=1,S=2,x=3,M=0,k=p,$=p*2,P=-1;c==="RGB"&&(g=3,w=0,v=1,S=2,x=-1),h==="RGBA"?P=p*3:h==="RBG"?(M=0,$=p,k=p*2):h==="BGR"&&($=0,k=p,M=p*2);for(let I=0;I<p;I++,w+=g,S+=g,v+=g,x+=g)m[M++]=(e[w]+u[0])/l[0],m[k++]=(e[v]+u[1])/l[1],m[$++]=(e[S]+u[2])/l[2],P!==-1&&x!==-1&&(m[P++]=(e[x]+u[3])/l[3]);return h==="RGBA"?new rt("float32",m,[1,4,n,i]):new rt("float32",m,[1,3,n,i])},tt=async(e,t)=>{let n=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,l=typeof e=="string",u,c=t??{},h=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=m=>typeof HTMLCanvasElement<"u"&&m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext("2d"):null;if(n){let m=h();m.width=e.width,m.height=e.height;let g=p(m);if(g!=null){let w=e.height,v=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(w=t.resizedHeight,v=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=w,c.width=v}else c.tensorFormat="RGBA",c.height=w,c.width=v;g.drawImage(e,0,0),u=g.getImageData(0,0,v,w).data}else throw new Error("Can not access image data")}else if(i){let m,g;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(m=t.resizedHeight,g=t.resizedWidth):(m=e.height,g=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=m,c.width=g,t!==void 0){let w=h();w.width=g,w.height=m;let v=p(w);if(v!=null)v.putImageData(e,0,0),u=v.getImageData(0,0,g,m).data;else throw new Error("Can not access image data")}else u=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let m=h();m.width=e.width,m.height=e.height;let g=p(m);if(g!=null){let w=e.height,v=e.width;return g.drawImage(e,0,0,v,w),u=g.getImageData(0,0,v,w).data,c.height=w,c.width=v,it(u,c)}else throw new Error("Can not access image data")}else{if(l)return new Promise((m,g)=>{let w=h(),v=p(w);if(!e||!v)return g();let S=new Image;S.crossOrigin="Anonymous",S.src=e,S.onload=()=>{w.width=S.width,w.height=S.height,v.drawImage(S,0,0,w.width,w.height);let x=v.getImageData(0,0,w.width,w.height);c.height=w.height,c.width=w.width,m(it(x.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return it(u,c);throw new Error("Input data provided is not supported - aborted tensor creation")},Wt=(e,t)=>{let{width:n,height:i,download:o,dispose:l}=t,u=[1,i,n,4];return new rt({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:l})},xt=(e,t)=>{let{dataType:n,dims:i,download:o,dispose:l}=t;return new rt({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:i,download:o,dispose:l})},je=(e,t)=>{let{dataType:n,dims:i,download:o,dispose:l}=t;return new rt({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:i,download:o,dispose:l})},qe=(e,t,n)=>new rt({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})}),ze,At,sr,Hr,Us=b(()=>{ze=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),At=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),sr=!1,Hr=()=>{if(!sr){sr=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;e&&(ze.set("int64",BigInt64Array),At.set(BigInt64Array,"int64")),t&&(ze.set("uint64",BigUint64Array),At.set(BigUint64Array,"uint64")),i?(ze.set("float16",n),At.set(n,"float16")):ze.set("float16",Uint16Array)}}}),Kr,jr,Fs=b(()=>{Tr(),Kr=e=>{let t=1;for(let n=0;n<e.length;n++){let i=e[n];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${n}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${i}`);t*=i}return t},jr=(e,t)=>{switch(e.location){case"cpu":return new rt(e.type,e.data,t);case"cpu-pinned":return new rt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new rt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new rt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new rt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),rt,Tr=b(()=>{Ze(),st(),Us(),Fs(),rt=class{constructor(e,t,n){Hr();let i,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,o=e.dims,e.location){case"cpu-pinned":{let u=ze.get(i);if(!u)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof u))throw new TypeError(`buffer should be of type ${u.name}`);this.cpuData=e.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let u,c;if(typeof e=="string")if(i=e,c=n,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");u=t}else{let h=ze.get(e);if(h===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&h===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${h.name} as data.`);e==="uint64"||e==="int64"?u=h.from(t,BigInt):u=h.from(t)}else if(t instanceof h)u=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")u=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&h!==Uint16Array)u=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${h}`)}else if(c=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let h=typeof e[0];if(h==="string")i="string",u=e;else if(h==="boolean")i="bool",u=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${h}.`)}else if(e instanceof Uint8ClampedArray)i="uint8",u=Uint8Array.from(e);else{let h=At.get(e.constructor);if(h===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=h,u=e}if(c===void 0)c=[u.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");o=c,this.cpuData=u,this.dataLocation="cpu"}let l=Kr(o);if(this.cpuData&&l!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(l/2)===this.cpuData.length))throw new Error(`Tensor's size(${l}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=o,this.size=l}static async fromImage(e,t){return tt(e,t)}static fromTexture(e,t){return Wt(e,t)}static fromGpuBuffer(e,t){return xt(e,t)}static fromMLTensor(e,t){return je(e,t)}static fromPinnedBuffer(e,t,n){return qe(e,t,n)}toDataURL(e){return Ge(this,e)}toImageData(e){return ot(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return jr(this,e)}}}),lt,Qr=b(()=>{Tr(),lt=rt}),er,Er,gt,yt,Ct,kt,Xr=b(()=>{Ke(),er=(e,t)=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.timeStamp(`${e}::ORT::${t}`)},Er=(e,t)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let o=0;o<n.length;o++){if(i&&!n[o].includes("TRACE_FUNC")){let l=`FUNC_${e}::${n[o].trim().split(" ")[1]}`;t&&(l+=`::${t}`),er("CPU",l);return}n[o].includes("TRACE_FUNC")&&(i=!0)}},gt=e=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||Er("BEGIN",e)},yt=e=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||Er("END",e)},Ct=e=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.time(`ORT::${e}`)},kt=e=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.timeEnd(`ORT::${e}`)}}),os,xe=b(()=>{se(),Qr(),Xr(),os=class df{constructor(t){this.handler=t}async run(t,n,i){gt(),Ct("InferenceSession.run");let o={},l={};if(typeof t!="object"||t===null||t instanceof lt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let u=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof lt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");u=!1;for(let p of n){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);o[p]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,m=Object.getOwnPropertyNames(n);for(let g of this.outputNames)if(m.indexOf(g)!==-1){let w=n[g];(w===null||w instanceof lt)&&(p=!0,u=!1,o[g]=w)}if(p){if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else l=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(u)for(let p of this.outputNames)o[p]=null;let c=await this.handler.run(t,o,l),h={};for(let p in c)if(Object.hasOwnProperty.call(c,p)){let m=c[p];m instanceof lt?h[p]=m:h[p]=new lt(m.type,m.data,m.dims)}return kt("InferenceSession.run"),yt(),h}async release(){return this.handler.dispose()}static async create(t,n,i,o){gt(),Ct("InferenceSession.create");let l,u={};if(typeof t=="string"){if(l=t,typeof n=="object"&&n!==null)u=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(l=t,typeof n=="object"&&n!==null)u=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let m=t,g=0,w=t.byteLength;if(typeof n=="object"&&n!==null)u=n;else if(typeof n=="number"){if(g=n,!Number.isSafeInteger(g))throw new RangeError("'byteOffset' must be an integer.");if(g<0||g>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(w=t.byteLength-g,typeof i=="number"){if(w=i,!Number.isSafeInteger(w))throw new RangeError("'byteLength' must be an integer.");if(w<=0||g+w>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-g}].`);if(typeof o=="object"&&o!==null)u=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");l=new Uint8Array(m,g,w)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,h]=await H(u),p=await c.createInferenceSessionHandler(l,h);return kt("InferenceSession.create"),yt(),new df(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Qe,Nt=b(()=>{xe(),Qe=os}),nr=b(()=>{}),It=b(()=>{}),Yr=b(()=>{}),hn=b(()=>{}),ls={};U(ls,{InferenceSession:()=>Qe,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>Ct,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>yt,Tensor:()=>lt,env:()=>fe,registerBackend:()=>J});var ct=b(()=>{ve(),Je(),Nt(),Qr(),nr(),It(),Xr(),Yr(),hn()}),Ut=b(()=>{}),$r={};U($r,{default:()=>pn});var Lt,us,pn,Wi=b(()=>{Yh(),Ht(),fs(),Lt="ort-wasm-proxy-worker",us=globalThis.self?.name===Lt,us&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":ys(n.wasm).then(()=>{Ba(n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:o}=n;Na(o,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=n,o=ki(i);postMessage({type:t,out:o});break}case"create":{let{model:i,options:o}=n;Fa(i,o).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":Va(n),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:o,inputs:l,outputIndices:u,options:c}=n;qa(i,o,l,u,new Array(u.length).fill(null),c).then(h=>{h.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:h},Ha([...l,...h]))},h=>{postMessage({type:t,err:h})});break}case"end-profiling":Wa(n),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),pn=us?null:e=>new Worker(e??at,{type:"classic",name:Lt})}),fn,mn,at,ds,Dr,gn,yn,cs,wn,hs,vn,ps,_n,fs=b(()=>{Ut(),fn=typeof location>"u"?void 0:location.origin,mn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,at=mn(),ds=()=>{if(at&&!at.startsWith("blob:"))return at.substring(0,at.lastIndexOf("/")+1)},Dr=(e,t)=>{try{let n=t??at;return(n?new URL(e,n):new URL(e)).origin===fn}catch{return!1}},gn=(e,t)=>{let n=t??at;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},yn=(e,t)=>`${t??"./"}${e}`,cs=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},wn=async e=>(await import(e)).default,hs=(Wi(),re($r)).default,vn=async()=>{if(!at)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Dr(at))return[void 0,hs()];let e=await cs(at);return[e,hs(e)]},ps=void 0,_n=async(e,t,n,i)=>{let o=ps&&!(e||t);if(o)if(at)o=Dr(at)||i&&!n;else if(i&&!n)o=!0;else throw new Error("cannot determine the script source URL.");if(o)return[void 0,ps];{let l="ort-wasm-simd-threaded.jsep.mjs",u=e??gn(l,t),c=n&&u&&!Dr(u,t),h=c?await cs(u):u??yn(l,t);return[c?h:void 0,await wn(h)]}}}),ms,zr,dr,gs,bn,Sn,Tn,ys,Pe,Ht=b(()=>{fs(),zr=!1,dr=!1,gs=!1,bn=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Sn=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Tn=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},ys=async e=>{if(zr)return Promise.resolve();if(dr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(gs)throw new Error("previous call to 'initializeWebAssembly()' failed.");dr=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Tn())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Sn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=bn();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=n=1);let o=e.wasmPaths,l=typeof o=="string"?o:void 0,u=o?.mjs,c=u?.href??u,h=o?.wasm,p=h?.href??h,m=e.wasmBinary,[g,w]=await _n(c,l,n>1,!!m||!!p),v=!1,S=[];if(t>0&&S.push(new Promise(x=>{setTimeout(()=>{v=!0,x()},t)})),S.push(new Promise((x,M)=>{let k={numThreads:n};if(m)k.wasmBinary=m,k.locateFile=$=>$;else if(p||l)k.locateFile=$=>p??l+$;else if(c&&c.indexOf("blob:")!==0)k.locateFile=$=>new URL($,c).href;else if(g){let $=ds();$&&(k.locateFile=P=>$+P)}w(k).then($=>{dr=!1,zr=!0,ms=$,x(),g&&URL.revokeObjectURL(g)},$=>{dr=!1,gs=!0,M($)})})),await Promise.race(S),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Pe=()=>{if(zr&&ms)return ms;throw new Error("WebAssembly is not initialized yet.")}}),mt,Lr,Ce,ws=b(()=>{Ht(),mt=(e,t)=>{let n=Pe(),i=n.lengthBytesUTF8(e)+1,o=n._malloc(i);return n.stringToUTF8(e,o,i),t.push(o),o},Lr=(e,t,n,i)=>{if(typeof e=="object"&&e!==null){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach(([o,l])=>{let u=t?t+o:o;if(typeof l=="object")Lr(l,u+".",n,i);else if(typeof l=="string"||typeof l=="number")i(u,l.toString());else if(typeof l=="boolean")i(u,l?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof l}`)})},Ce=e=>{let t=Pe(),n=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetLastError(o,o+i);let l=Number(t.getValue(o,i===4?"i32":"i64")),u=t.getValue(o+i,"*"),c=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(n)}}}),En,Hi=b(()=>{Ht(),ws(),En=e=>{let t=Pe(),n=0,i=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let l=0;return e?.tag!==void 0&&(l=mt(e.tag,i)),n=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,l),n===0&&Ce("Can't create run options."),e?.extra!==void 0&&Lr(e.extra,"",new WeakSet,(u,c)=>{let h=mt(u,i),p=mt(c,i);t._OrtAddRunConfigEntry(n,h,p)!==0&&Ce(`Can't set a run config entry: ${u} - ${c}.`)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseRunOptions(n),i.forEach(u=>t._free(u)),l}}}),$n,xn,Cn,Ft,kn,Rn,Ki=b(()=>{Ht(),ws(),$n=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},xn=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Cn=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(e.enableMemPattern=!1)},Ft=(e,t,n,i)=>{let o=mt(t,i),l=mt(n,i);Pe()._OrtAddSessionConfigEntry(e,o,l)!==0&&Ce(`Can't set a session config entry: ${t} - ${n}.`)},kn=async(e,t,n)=>{let i=t.executionProviders;for(let o of i){let l=typeof o=="string"?o:o.name,u=[];switch(l){case"webnn":if(l="WEBNN",Ft(e,"session.disable_quant_qdq","1",n),Ft(e,"session.disable_qdq_constant_folding","1",n),typeof o!="string"){let g=o?.deviceType;g&&Ft(e,"deviceType",g,n)}break;case"webgpu":if(l="JS",typeof o!="string"){let g=o;if(g?.preferredLayout){if(g.preferredLayout!=="NCHW"&&g.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${g.preferredLayout}`);Ft(e,"preferredLayout",g.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let c=mt(l,n),h=u.length,p=0,m=0;if(h>0){p=Pe()._malloc(h*Pe().PTR_SIZE),n.push(p),m=Pe()._malloc(h*Pe().PTR_SIZE),n.push(m);for(let g=0;g<h;g++)Pe().setValue(p+g*Pe().PTR_SIZE,u[g][0],"*"),Pe().setValue(m+g*Pe().PTR_SIZE,u[g][1],"*")}await Pe()._OrtAppendExecutionProvider(e,c,p,m,h)!==0&&Ce(`Can't append execution provider: ${l}.`)}},Rn=async e=>{let t=Pe(),n=0,i=[],o=e||{};Cn(o);try{let l=$n(o.graphOptimizationLevel??"all"),u=xn(o.executionMode??"sequential"),c=typeof o.logId=="string"?mt(o.logId,i):0,h=o.logSeverityLevel??2;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log severity level is not valid: ${h}`);let p=o.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let m=typeof o.optimizedModelFilePath=="string"?mt(o.optimizedModelFilePath,i):0;if(n=t._OrtCreateSessionOptions(l,!!o.enableCpuMemArena,!!o.enableMemPattern,u,!!o.enableProfiling,0,c,h,p,m),n===0&&Ce("Can't create session options."),o.executionProviders&&await kn(n,o,i),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);Ft(n,"enableGraphCapture",o.enableGraphCapture.toString(),i)}if(o.freeDimensionOverrides)for(let[g,w]of Object.entries(o.freeDimensionOverrides)){if(typeof g!="string")throw new Error(`free dimension override name must be a string: ${g}`);if(typeof w!="number"||!Number.isInteger(w)||w<0)throw new Error(`free dimension override value must be a non-negative integer: ${w}`);let v=mt(g,i);t._OrtAddFreeDimensionOverride(n,v,w)!==0&&Ce(`Can't set a free dimension override: ${g} - ${w}.`)}return o.extra!==void 0&&Lr(o.extra,"",new WeakSet,(g,w)=>{Ft(n,g,w,i)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&Ce("Can't release session options."),i.forEach(u=>t._free(u)),l}}}),Kt,jt,Qt,vs,_s,bs,Ss,Vs,Ie=b(()=>{Kt=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},jt=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},Qt=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i=typeof t=="number"?t:t.reduce((o,l)=>o*l,1);return n>0?Math.ceil(i*n):void 0},vs=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},_s=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},bs=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ss=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Vs=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),Ts,An=b(()=>{Ut(),Ts=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),i=n?parseInt(n,10):0;if(i<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),l;try{l=new ArrayBuffer(i)}catch(c){if(c instanceof RangeError){let h=Math.ceil(i/65536);l=new WebAssembly.Memory({initial:h,maximum:h}).buffer}else throw c}let u=0;for(;;){let{done:c,value:h}=await o.read();if(c)break;let p=h.byteLength;new Uint8Array(l,u,p).set(h),u+=p}return new Uint8Array(l,0,i)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),In,Gs,qs,xr,Ws,Hs,We,tr=b(()=>{Ie(),In=["V","I","W","E","F"],Gs=(e,t)=>{console.log(`[${In[e]},${new Date().toISOString()}]${t}`)},Ws=(e,t)=>{qs=e,xr=t},Hs=(e,t)=>{let n=_s(e),i=_s(qs);n>=i&&Gs(n,typeof t=="function"?t():t)},We=(...e)=>{xr&&Hs(...e)}}),Ks,Cr,j,Jr,js,Mn,cr,ke=b(()=>{Ks=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Cr=class{static calcShape(e,t,n=!1){let i=e.length,o=t.length;if(i===0)return t;if(o===0)return e;let l=Math.max(e.length,t.length),u=new Array(l);if(n){if(i<2||o<2)return;let c=Ks.calcMatMulShape([e[i-2],e[i-1]],[t[o-2],t[o-1]]);if(c===void 0)return;[u[l-2],u[l-1]]=c}for(let c=n?3:1;c<=l;c++){let h=i-c<0?1:e[i-c],p=o-c<0?1:t[o-c];if(h!==p&&h>1&&p>1)return;let m=Math.max(h,p);if(h&&p)u[l-c]=Math.max(h,p);else{if(m>1)return;u[l-c]=0}}return u}static isValidBroadcast(e,t){let n=e.length,i=t.length;if(n>i)return!1;for(let o=1;o<=n;o++)if(e[n-o]!==1&&e[n-o]!==t[i-o])return!1;return!0}},j=class Ni{static size(t){return Ni.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,n=4){let i=t.length;if(i===0)return[];let o=new Array(i),l=i-1;for(;l>=0;){if(t[l]%n===0){o[l]=t[l]/n;break}if(n%t[l]!==0)throw new Error("cannot convert shape");o[l]=1,n/=t[l],l--}for(l--;l>=0;l--)o[l]=t[l];return o}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Ni.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Ni.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,i){let o=1;for(let l=n;l<i;l++){if(t[l]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");o*=Number(t[l])}return o}static computeStrides(t){let n=t.length;if(n===0)return[];if(n===1)return[1];let i=new Array(n);i[n-1]=1,i[n-2]=t[n-1];for(let o=n-3;o>=0;--o)i[o]=i[o+1]*t[o+1];return i}static normalizeAxis(t,n){if(t<-n&&t>=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(i=>this.normalizeAxis(i,n??t.length))}static sortBasedOnPerm(t,n){return n?n.map(i=>t[i]):t.slice().reverse()}static padShape(t,n){let i=t.length;return t.map((o,l)=>o+n[l]+n[l+i])}static areEqual(t,n){return t.length!==n.length?!1:t.every((i,o)=>i===n[o])}},Jr=class li{static adjustPoolAttributes(t,n,i,o,l,u){if(!t&&i.length!==n.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let c=0;c<n.length-2;c++)c>=i.length?i.push(n[c+2]):i[c]=n[c+2];for(let c=0;c<i.length;c++)if(c<o.length){if(o[c]<0)throw new Error("strides should be greater than or equal to 1")}else o.push(1);for(let c=0;c<i.length;c++)if(c<l.length){if(l[c]<0)throw new Error("dilations should be greater than or equal to 1")}else l.push(1);for(let c=0;c<i.length*2;c++)if(c<u.length){if(u[c]<0)throw new Error("pad should be greater than or equal to 1")}else u.push(0);for(let c=0;c<i.length;c++){if(i[c]<=0)throw new Error("kernel shapes need to be greater than 0");if(u[c]>=i[c]||u[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,o,l,u,c){if(c){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let h=0;h<t.length-2;h++)li.adjustPadAndReturnShape(t[h+(u?1:2)],n[h],i[h],o[h],l,h,h+t.length-2,c)}}static computePoolOutputShape(t,n,i,o,l,u,c){if(n.length<=0)throw new Error("input shape must be of size greater than 0");let h=[n[0],n[1]];return li.computeShapeHelper(t,n,h,i,o,l,u,c),h}static computeConvOutputShape(t,n,i,o,l,u,c){if(t.length<=0||n.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let h=[t[0],n[0]];return li.computeShapeHelper(!1,t,h,i,o,l,u,c),h}static computeShapeHelper(t,n,i,o,l,u,c,h){if(t)for(let p=0;p<n.length-2;p++)i.push(1);else for(let p=0;p<n.length-2;p++)i.push(li.adjustPadAndReturnShape(n[p+2],o[p],l[p],u[p],c,p,p+n.length-2,h))}static adjustPadAndReturnShape(t,n,i,o,l,u,c,h){let p=i*(o-1)+1;if(h&&h!=="NOTSET")switch(h){case"VALID":return l[u]=0,l[c]=0,Math.floor((t-p)/n+1);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let m=((t+n-1)/n-1)*n+o-t;return l[u]=Math.floor(h==="SAME_LOWER"?(m+1)/2:m/2),l[c]=m-l[u],Math.floor((t+m-o)/n+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((t+l[u]+l[c]-p)/n+1)}},js=class{static getShapeOfGemmResult(e,t,n,i,o){if(e.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let l,u,c;t?(l=e[1],u=e[0]):(l=e[0],u=e[1]);let h=-1;if(i?(c=n[0],h=1):(c=n[1],h=0),n[h]!==u)throw new Error("dimension mismatch");if(l<=0||c<=0||u<=0)throw new Error("invalid shape specified");if(o&&!Cr.isValidBroadcast(o,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,u]}},Mn=-34028234663852886e22,cr=34028234663852886e22}),kr,Zr=b(()=>{Ie(),kr=(e,t)=>new(vs(t))(e)}),Br,es,Es,$s,hr,Rr,Qs,Xs,Ys,Pn,On,pi=b(()=>{Ie(),tr(),Br=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),es=(e,t)=>{if(t==="int32")return e;let n=Br.get(t);if(!n)throw new Error(`WebNN backend does not support data type: ${t}`);let i=n/8;if(e.byteLength%i!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${i}.`);let o=e.byteLength/i,l=new(vs(t))(e.buffer,e.byteOffset,o);switch(t){case"int64":case"uint64":{let u=new Int32Array(o);for(let c=0;c<o;c++){let h=l[c];if(h>2147483647n||h<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");u[c]=Number(h)}return new Uint8Array(u.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(c=>c>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let u=Int32Array.from(l,Number);return new Uint8Array(u.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Es=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let n=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case"int64":{let o=BigInt64Array.from(i,BigInt);return new Uint8Array(o.buffer)}case"uint64":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let o=BigUint64Array.from(i,BigInt);return new Uint8Array(o.buffer)}case"int8":{if(i.some(l=>l<-128||l>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let o=Int8Array.from(i,Number);return new Uint8Array(o.buffer)}case"uint8":{if(i.some(o=>o<0||o>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(i,Number)}case"uint32":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let o=Uint32Array.from(i,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},$s=1,hr=()=>$s++,Rr=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Qs=(e,t)=>{let n=Br.get(e);if(!n)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,o)=>i*o)*n/8):0},Xs=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:i,dataType:o,shape:l,fallbackDataType:u}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=i,this.dataType=o,this.tensorShape=l,this.fallbackDataType=u}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Qs(this.dataType,this.tensorShape)}destroy(){We("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Es(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return n.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((i,o)=>i===n[o])}setIsDataConverted(e){this.isDataConverted=e}},Ys=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,i){let o=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),u;if(!l?.input.dataTypes.includes(t)){if(u=Rr.get(t),!u||l?.input.dataTypes.includes(u))throw new Error(`WebNN backend does not support data type: ${t}`);We("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${u}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(o,t,n))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==Qs(t,n))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let c=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,c,!0,!0,u),i&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=es(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else We("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Es(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Pn=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=hr();return this.tensorTrackersById.set(e,new Ys(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,i,o){We("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){We("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,i){let o=this.getMLContext(e),l=hr(),u=new Xs({sessionId:e,context:o,tensor:t,dataType:n,shape:i});return this.tensorTrackersById.set(l,new Ys(this,u)),this.externalTensors.add(u),l}async getCachedTensor(e,t,n,i,o,l,u){let c=this.getMLContext(e);for(let[p,m]of this.freeTensors.entries())if(m.canReuseTensor(c,t,n)){We("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${n}`);let g=this.freeTensors.splice(p,1)[0];return g.sessionId=e,g}We("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${n}}`);let h=await c.createTensor({dataType:u??t,shape:n,dimensions:n,usage:i,writable:o,readable:l});return new Xs({sessionId:e,context:c,tensor:h,dataType:t,shape:n,fallbackDataType:u})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},On=(...e)=>new Pn(...e)}),ts,Dn,zn,Ln=b(()=>{Ie(),Ht(),Zr(),pi(),tr(),ts=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Dn=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),i=Object.keys(t).sort();return n.length===i.length&&n.every((o,l)=>o===i[l]&&e[o]===t[o])},zn=class{constructor(e){this.tensorManager=On(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,Ws(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){We("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){We("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let n of t)We("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){We("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,i,o){let l=ts.get(n);if(!l)throw new Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,l,i,o)}async createTemporaryTensor(e,t,n){We("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let i=ts.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,i,n,!1);let l=this.temporarySessionTensorIds.get(e);return l?l.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,t){if(!Pe().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");We("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return kr(n,t)}}registerMLTensor(e,t,n,i){let o=ts.get(n);if(!o)throw new Error(`Unsupported ONNX data type: ${n}`);let l=this.tensorManager.registerTensor(e,t,o,i);return We("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${i}} -> {tensorId: ${l}}`),l}registerMLConstant(e,t,n,i,o,l,u=!1){if(!l)throw new Error("External mounted files are not available.");let c=e;e.startsWith("./")&&(c=e.substring(2));let h=l.get(c);if(!h)throw new Error(`File with name ${c} not found in preloaded files.`);if(t+n>h.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=h.slice(t,t+n).buffer,m;switch(o.dataType){case"float32":m=new Float32Array(p);break;case"float16":m=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(p):new Uint16Array(p);break;case"int32":m=new Int32Array(p);break;case"uint32":m=new Uint32Array(p);break;case"int64":if(u){let g=es(new Uint8Array(p),"int64");m=new Int32Array(g.buffer),o.dataType="int32"}else m=new BigInt64Array(p);break;case"uint64":m=new BigUint64Array(p);break;case"int8":m=new Int8Array(p);break;case"int4":case"uint4":case"uint8":m=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return We("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${u?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),i.constant(o,m)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let i=ts.get(Kt(t)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:n?!!o?.input.dataTypes.includes(i):!!o?.output.dataTypes.includes(i)}flush(){}}}),Js=b(()=>{}),Zs,en,xs,tn,rn,sn,Bn,Nn,fi,ji=b(()=>{tr(),Js(),Zs=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),en=[],xs=e=>Math.ceil(Number(e)/16)*16,tn=e=>{for(let t=0;t<en.length;t++){let n=en[t];if(e<=n)return n}return Math.ceil(e/16)*16},rn=1,sn=()=>rn++,Bn=async(e,t,n,i)=>{let o=xs(n),l=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let u=e.getCommandEncoder();e.endComputePass(),u.copyBufferToBuffer(t,0,l,0,o),e.flush(),await l.mapAsync(GPUMapMode.READ);let c=l.getMappedRange();if(i){let h=i();return h.set(new Uint8Array(c,0,n)),h}else return new Uint8Array(c.slice(0,n))}finally{l.destroy()}},Nn=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of Zs)en.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,i=t.byteOffset,o=t.byteLength,l=xs(o),u=this.storageCache.get(e);if(!u)throw new Error("gpu data for uploading does not exist");if(Number(u.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${u.originalSize}, data size=${o}`);let c=this.backend.device.createBuffer({mappedAtCreation:!0,size:l,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),h=c.getMappedRange();new Uint8Array(h).set(new Uint8Array(n,i,o)),c.unmap();let p=this.backend.device.createCommandEncoder();p.copyBufferToBuffer(c,0,u.gpuData.buffer,0,l),this.backend.device.queue.submit([p.finish()]),c.destroy(),We("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(t);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=xs(n.originalSize),l=this.backend.getCommandEncoder();this.backend.endComputePass(),l.copyBufferToBuffer(n.gpuData.buffer,0,i.gpuData.buffer,0,o)}registerExternalBuffer(e,t,n){let i;if(n){if(i=n[0],e===n[1])return We("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.
|
|
6
|
+
Please use the previous external buffer!`)}else i=sn();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:t}),We("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),We("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)}),We("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 We("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&&(We("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},fi=(...e)=>new Nn(...e)}),y,E,A=b(()=>{y=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},E=e=>new y(e)}),D,O,G,N,L,V,te,ne,Z,Q,Se,F,le,ut,Be,Te,Ne,ye=b(()=>{Ie(),ke(),D=64,O=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}<f16>`:"f16";case 1:return t>1?`vec${t}<f32>`:"f32";case 6:return t>1?`vec${t}<i32>`:"i32";case 12:return t>1?`vec${t}<u32>`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4<bool>"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},G=(e,t=1)=>{let n=O(e,t);return typeof n=="string"?n:n[0]},N=(e,t=1)=>{let n=O(e,t);return typeof n=="string"?n:n[1]},L=(...e)=>{let t=[];return e.forEach(n=>{n.length!==0&&t.push({type:12,data:n},{type:12,data:j.computeStrides(n)})}),t},V=e=>e%4===0?4:e%2===0?2:1,te=(e="f32",t,n="0")=>!t||t===1?`${e}(${n})`:`vec${t}<${e}>(${n})`,ne=(e,t,n)=>e==="f32"?n:t===1?`f32(${n})`:`vec${t}<f32>(${n})`,Z=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,Q=(e,t,n,i)=>e.startsWith("uniforms.")&&n>4?typeof t=="string"?i==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:i==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,Se=(e,t,n,i,o)=>{let l=typeof n=="number",u=l?n:n.length,c=[...new Array(u).keys()],h=u<2?"u32":u<=4?`vec${u}<u32>`:`array<u32, ${u}>`,p=O(t,o),m=typeof p=="string"?p:p[1],g=typeof p=="string"?p:p[0],w={indices:h,value:m,storage:g,tensor:t},v=ae=>typeof ae=="string"?ae:`${ae}u`,S={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 ae=0;ae<u-1;ae++)$+=`
|
|
7
|
+
let dim${ae} = current / ${Q(k,ae,u)};
|
|
8
|
+
let rest${ae} = current % ${Q(k,ae,u)};
|
|
9
|
+
indices[${ae}] = dim${ae};
|
|
10
|
+
current = rest${ae};
|
|
11
|
+
`;$+=`indices[${u-1}] = current;`;let P=u<2?"":`
|
|
12
|
+
fn o2i_${e}(offset: u32) -> ${w.indices} {
|
|
13
|
+
var indices: ${w.indices};
|
|
14
|
+
var current = offset;
|
|
15
|
+
${$}
|
|
16
|
+
return indices;
|
|
17
|
+
}`,I=ae=>(S.offsetToIndices=!0,u<2?ae:`o2i_${e}(${ae})`),B=[];if(u>=2)for(let ae=u-1;ae>=0;ae--)B.push(`${Q(k,ae,u)} * (indices[${ae}])`);let q=u<2?"":`
|
|
18
|
+
fn i2o_${e}(indices: ${w.indices}) -> u32 {
|
|
19
|
+
return ${B.join("+")};
|
|
20
|
+
}`,W=ae=>(S.indicesToOffset=!0,u<2?ae:`i2o_${e}(${ae})`),ee=(...ae)=>u===0?"0u":`${w.indices}(${ae.map(v).join(",")})`,ue=(ae,Oe)=>u<2?`${ae}`:`${Q(ae,Oe,u)}`,_e=(ae,Oe,Ae)=>u<2?`${ae}=${Ae};`:`${Q(ae,Oe,u)}=${Ae};`,Fe={},Re=(ae,Oe)=>{S.broadcastedIndicesToOffset=!0;let Ae=`${Oe.name}broadcastedIndicesTo${e}Offset`;if(Ae in Fe)return`${Ae}(${ae})`;let Ee=[];for(let Dt=u-1;Dt>=0;Dt--){let Xt=Oe.indicesGet("outputIndices",Dt+Oe.rank-u);Ee.push(`${ue(k,Dt)} * (${Xt} % ${ue(M,Dt)})`)}return Fe[Ae]=`fn ${Ae}(outputIndices: ${Oe.type.indices}) -> u32 {
|
|
21
|
+
return ${Ee.length>0?Ee.join("+"):"0u"};
|
|
22
|
+
}`,`${Ae}(${ae})`},Me=(ae,Oe)=>(()=>{if(w.storage===w.value)return`${e}[${ae}]=${Oe};`;if(w.storage==="vec2<u32>"&&w.value==="i32")return`${e}[${ae}]=vec2<u32>(u32(${Oe}), select(0u, 0xFFFFFFFFu, ${Oe} < 0));`;if(w.storage==="vec2<u32>"&&w.value==="u32")return`${e}[${ae}]=vec2<u32>(u32(${Oe}), 0u);`;if(w.storage==="u32"&&w.value==="vec4<bool>")return`${e}[${ae}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${Oe}));`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),Xe=ae=>(()=>{if(w.storage===w.value)return`${e}[${ae}]`;if(w.storage==="vec2<u32>"&&w.value==="i32")return`i32(${e}[${ae}].x)`;if(w.storage==="vec2<u32>"&&w.value==="u32")return`u32(${e}[${ae}].x)`;if(w.storage==="u32"&&w.value==="vec4<bool>")return`vec4<bool>(bool(${e}[${ae}] & 0xFFu), bool(${e}[${ae}] & 0xFF00u), bool(${e}[${ae}] & 0xFF0000u), bool(${e}[${ae}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),ge=u<2?"":`
|
|
23
|
+
fn get_${e}ByIndices(indices: ${w.indices}) -> ${m} {
|
|
24
|
+
return ${Xe(`i2o_${e}(indices)`)};
|
|
25
|
+
}`,$e=u<2?"":(()=>{let ae=c.map(Ae=>`d${Ae}: u32`).join(", "),Oe=c.map(Ae=>`d${Ae}`).join(", ");return`
|
|
26
|
+
fn get_${e}(${ae}) -> ${m} {
|
|
27
|
+
return get_${e}ByIndices(${ee(Oe)});
|
|
28
|
+
}`})(),Le=(...ae)=>{if(ae.length!==u)throw new Error(`indices length must be ${u}`);let Oe=ae.map(v).join(",");return u===0?Xe("0u"):u===1?Xe(Oe[0]):(S.get=!0,S.getByIndices=!0,S.indicesToOffset=!0,`get_${e}(${Oe})`)},Ve=ae=>u<2?Xe(ae):(S.getByIndices=!0,S.indicesToOffset=!0,`get_${e}ByIndices(${ae})`),De=u<2?"":`
|
|
29
|
+
fn set_${e}ByIndices(indices: ${w.indices}, value: ${m}) {
|
|
30
|
+
${Me(`i2o_${e}(indices)`,"value")}
|
|
31
|
+
}`,He=u<2?"":(()=>{let ae=c.map(Ae=>`d${Ae}: u32`).join(", "),Oe=c.map(Ae=>`d${Ae}`).join(", ");return`
|
|
32
|
+
fn set_${e}(${ae}, value: ${m}) {
|
|
33
|
+
set_${e}ByIndices(${ee(Oe)}, value);
|
|
34
|
+
}`})();return{impl:()=>{let ae=[],Oe=!1;return S.offsetToIndices&&(ae.push(P),Oe=!0),S.indicesToOffset&&(ae.push(q),Oe=!0),S.broadcastedIndicesToOffset&&(Object.values(Fe).forEach(Ae=>ae.push(Ae)),Oe=!0),S.set&&(ae.push(He),Oe=!0),S.setByIndices&&(ae.push(De),Oe=!0),S.get&&(ae.push($e),Oe=!0),S.getByIndices&&(ae.push(ge),Oe=!0),!l&&Oe&&ae.unshift(`const ${M} = ${w.indices}(${n.join(",")});`,`const ${k} = ${w.indices}(${j.computeStrides(n).join(",")});`),ae.join(`
|
|
35
|
+
`)},type:w,offsetToIndices:I,indicesToOffset:W,broadcastedIndicesToOffset:Re,indices:ee,indicesGet:ue,indicesSet:_e,set:(...ae)=>{if(ae.length!==u+1)throw new Error(`indices length must be ${u}`);let Oe=ae[u];if(typeof Oe!="string")throw new Error("value must be string");let Ae=ae.slice(0,u).map(v).join(",");return u===0?Me("0u",Oe):u===1?Me(Ae[0],Oe):(S.set=!0,S.setByIndices=!0,S.indicesToOffset=!0,`set_${e}(${Ae}, ${Oe})`)},setByOffset:Me,setByIndices:(ae,Oe)=>u<2?Me(ae,Oe):(S.setByIndices=!0,S.indicesToOffset=!0,`set_${e}ByIndices(${ae}, ${Oe});`),get:Le,getByOffset:Xe,getByIndices:Ve,usage:i,name:e,strides:k,shape:M,rank:u}},F=(e,t,n,i=1)=>Se(e,t,n,"input",i),le=(e,t,n,i=1)=>Se(e,t,n,"output",i),ut=(e,t,n)=>Se(e,t,n,"atomicOutput",1),Be=(e,t,n,i=1)=>Se(e,t,n,"internal",i),Te=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=D){let t=typeof e=="number"?e:e[0],n=typeof e=="number"?1:e[1],i=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${n}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*n*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${n}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,l=o?`@builtin(global_invocation_id) global_id : vec3<u32>,
|
|
36
|
+
@builtin(workgroup_id) workgroup_id : vec3<u32>,
|
|
37
|
+
@builtin(local_invocation_index) local_idx : u32,
|
|
38
|
+
@builtin(local_invocation_id) local_id : vec3<u32>`:`@builtin(global_invocation_id) global_id : vec3<u32>,
|
|
39
|
+
@builtin(local_invocation_id) local_id : vec3<u32>,
|
|
40
|
+
@builtin(local_invocation_index) local_idx : u32,
|
|
41
|
+
@builtin(workgroup_id) workgroup_id : vec3<u32>,
|
|
42
|
+
@builtin(num_workgroups) num_workgroups : vec3<u32>`,u=o?`let global_idx = global_id.x;
|
|
43
|
+
let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +
|
|
44
|
+
workgroup_id.y * num_workgroups[0] + workgroup_id.x;
|
|
45
|
+
let global_idx = workgroup_index * ${t*n*i}u + local_idx;`;return`@compute @workgroup_size(${t}, ${n}, ${i})
|
|
46
|
+
fn main(${l}) {
|
|
47
|
+
${u}
|
|
48
|
+
`}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let 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(`
|
|
49
|
+
`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,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`
|
|
50
|
+
struct Uniforms { ${e.join(", ")} };
|
|
51
|
+
@group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(`
|
|
52
|
+
`)+this.internalVariables.map(e=>e.impl()).join(`
|
|
53
|
+
`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},Ne=(e,t)=>new Te(e,t)}),Rt,Mt,Ar,rs,nn,Un,ht,ir,Fn,Ue=b(()=>{Ie(),ke(),A(),ye(),Rt=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},Mt=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),Ar=(e,t)=>j.sortBasedOnPerm(e,Mt(e.length,t)),rs=(e,t,n,i)=>{let o=`fn perm(i: ${i.type.indices}) -> ${n.type.indices} {
|
|
54
|
+
var a: ${n.type.indices};`;for(let l=0;l<t;++l)o+=`a[${e[l]}]=i[${l}];`;return o+="return a;}"},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},ht=(e,t)=>{let n=e.dataType,i=e.dims.length,o=Mt(i,t),l=Ar(e.dims,o),u=e.dims,c=l,h=i<2||Un(o,e.dims),p;if(h)return p=S=>{let x=F("input",n,u,4),M=le("output",n,c,4);return`
|
|
55
|
+
${S.registerUniform("output_size","u32").declareVariables(x,M)}
|
|
56
|
+
${S.mainStart()}
|
|
57
|
+
${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
58
|
+
output[global_idx] = input[global_idx];
|
|
59
|
+
}`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let S=j.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(S/64/4)},programUniforms:[{type:12,data:Math.ceil(S/4)}]}},getShaderSource:p};let{newShape:m,newPerm:g}=nn(e.dims,o),w=j.areEqual(g,[2,3,1]),v=j.areEqual(g,[3,1,2]);if(m.length===2||w||v){u=w?[m[0],m[1]*m[2]]:v?[m[0]*m[1],m[2]]:m,c=[u[1],u[0]];let S=16;return p=x=>{let M=F("a",n,u.length),k=le("output",n,c.length);return`
|
|
60
|
+
${x.registerUniform("output_size","u32").declareVariables(M,k)}
|
|
61
|
+
var<workgroup> tile : array<array<${k.type.value}, ${S+1}>, ${S}>;
|
|
62
|
+
${x.mainStart([S,S,1])}
|
|
63
|
+
let stride = (uniforms.output_shape[1] - 1) / ${S} + 1;
|
|
64
|
+
let workgroup_id_x = workgroup_index % stride;
|
|
65
|
+
let workgroup_id_y = workgroup_index / stride;
|
|
66
|
+
let input_col = workgroup_id_y * ${S}u + local_id.x;
|
|
67
|
+
let input_row = workgroup_id_x * ${S}u + local_id.y;
|
|
68
|
+
if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {
|
|
69
|
+
tile[local_id.y][local_id.x] = ${M.getByIndices(`${M.type.indices}(input_row, input_col)`)};
|
|
70
|
+
}
|
|
71
|
+
workgroupBarrier();
|
|
72
|
+
|
|
73
|
+
let output_col = workgroup_id_x * ${S}u + local_id.x;
|
|
74
|
+
let output_row = workgroup_id_y * ${S}u + local_id.y;
|
|
75
|
+
if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {
|
|
76
|
+
${k.setByIndices(`${k.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")}
|
|
77
|
+
}
|
|
78
|
+
}`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let x=j.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c[1]/S),y:Math.ceil(c[0]/S)},programUniforms:[{type:12,data:x},...L(u,c)]}},getShaderSource:p}}return p=S=>{let x=F("a",n,u.length),M=le("output",n,c.length);return`
|
|
79
|
+
${S.registerUniform("output_size","u32").declareVariables(x,M)}
|
|
80
|
+
|
|
81
|
+
${rs(o,i,x,M)}
|
|
82
|
+
|
|
83
|
+
${S.mainStart()}
|
|
84
|
+
${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
85
|
+
|
|
86
|
+
let indices = ${M.offsetToIndices("global_idx")};
|
|
87
|
+
let aIndices = perm(indices);
|
|
88
|
+
|
|
89
|
+
${M.setByOffset("global_idx",x.getByIndices("aIndices"))}
|
|
90
|
+
}`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let S=j.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...L(u,c)]}},getShaderSource:p}},ir=(e,t)=>{Rt(e.inputs,t.perm),e.compute(ht(e.inputs[0],t.perm))},Fn=e=>E({perm:e.perm})}),rr,mi,pr,Cs,wt,Bt,an,ks,Vn,gi,Et,fr,ss,vt,pt,ar,yi,wi,Po,Oo,Do,pm=b(()=>{Ie(),ke(),ye(),Xi(),Ue(),rr={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},mi={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"},pr={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Cs={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},wt=(e,t)=>{let n=[];for(let i=t-e;i<t;++i)n.push(i);return n},Bt=(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},ks=(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(!ks(e,t)){for(let i=0;i<t;++i)e.indexOf(i)===-1&&n.push(i);e.forEach(i=>n.push(i))}return n},gi=(e,t,n,i,o,l,u)=>{let c=n[0].dims,h=j.size(l),p=j.size(u),m=F("_A",n[0].dataType,c),g=le("output",o,l),w=64;h===1&&(w=256);let v=`
|
|
91
|
+
var<workgroup> aBestValues : array<f32, ${w}>;
|
|
92
|
+
`,S=x=>`
|
|
93
|
+
${x.registerUniform("reduceSize","u32").declareVariables(m,g)}
|
|
94
|
+
${v}
|
|
95
|
+
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
96
|
+
return ((a - 1u) / b + 1u);
|
|
97
|
+
}
|
|
98
|
+
${x.mainStart(w)}
|
|
99
|
+
|
|
100
|
+
let outputIndex = global_idx / ${w};
|
|
101
|
+
let offset = outputIndex * uniforms.reduceSize;
|
|
102
|
+
|
|
103
|
+
var bestValue = f32(${pr[i]});
|
|
104
|
+
let Length = uniforms.reduceSize;
|
|
105
|
+
for (var k = local_idx; k < Length; k = k + ${w}) {
|
|
106
|
+
let candidate = f32(${m.getByOffset("offset + k")});
|
|
107
|
+
bestValue = ${rr[i]};
|
|
108
|
+
}
|
|
109
|
+
aBestValues[local_idx] = bestValue;
|
|
110
|
+
workgroupBarrier();
|
|
111
|
+
|
|
112
|
+
var reduceSize = min(Length, ${w}u);
|
|
113
|
+
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
|
|
114
|
+
currentSize = reduceSize / 2u) {
|
|
115
|
+
let interval = DIV_CEIL(reduceSize, 2u);
|
|
116
|
+
if (local_idx < currentSize) {
|
|
117
|
+
let candidate = aBestValues[local_idx + interval];
|
|
118
|
+
bestValue = ${mi[i]};
|
|
119
|
+
aBestValues[local_idx] = bestValue;
|
|
120
|
+
}
|
|
121
|
+
reduceSize = interval;
|
|
122
|
+
workgroupBarrier();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (local_idx == 0u) {
|
|
126
|
+
${g.setByOffset("outputIndex",`${i==="mean"?`${g.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${g.type.storage}(${Cs[i]})`}`)};
|
|
127
|
+
}
|
|
128
|
+
}`;return{name:e,shaderCache:{hint:`${t};${w}`,inputDependencies:["type"]},getShaderSource:S,getRunData:()=>({outputs:[{dims:l,dataType:o}],dispatchGroup:{x:h},programUniforms:[{type:12,data:p}]})}},Et=(e,t,n,i)=>{let o=e.inputs.length===1?n:Qi(e.inputs,n),l=o.axes;l.length===0&&!o.noopWithEmptyAxes&&(l=e.inputs[0].dims.map((v,S)=>S));let u=j.normalizeAxes(l,e.inputs[0].dims.length),c=u,h=e.inputs[0],p=Vn(c,e.inputs[0].dims.length);p.length>0&&(h=e.compute(ht(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],c=wt(c.length,h.dims.length));let[m,g]=Bt(h.dims,c),w=m;o.keepDims&&(w=an(m,u)),e.compute(gi(t,o.cacheKey,[h],i,e.inputs[0].dataType,w,g),{inputs:[h]})},fr=(e,t)=>{Et(e,"ReduceMeanShared",t,"mean")},ss=(e,t)=>{Et(e,"ReduceL1Shared",t,"l1")},vt=(e,t)=>{Et(e,"ReduceL2Shared",t,"l2")},pt=(e,t)=>{Et(e,"ReduceLogSumExpShared",t,"logSumExp")},ar=(e,t)=>{Et(e,"ReduceMaxShared",t,"max")},yi=(e,t)=>{Et(e,"ReduceMinShared",t,"min")},wi=(e,t)=>{Et(e,"ReduceProdShared",t,"prod")},Po=(e,t)=>{Et(e,"ReduceSumShared",t,"sum")},Oo=(e,t)=>{Et(e,"ReduceSumSquareShared",t,"sumSquare")},Do=(e,t)=>{Et(e,"ReduceLogSumShared",t,"logSum")}}),mr,zo,vi,Qi,gr,Lo,Bo,No,Uo,Fo,Vo,Go,qo,Wo,Ho,yr,Ko,jo,Qo,Xo,Yo,Jo,Zo,el,tl,rl,Xi=b(()=>{Ie(),ke(),A(),ye(),pm(),mr=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},zo=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],vi=(e,t,n,i,o,l,u=!1,c=!1)=>{let h=[],p=n[0].dims,m=p.length,g=j.normalizeAxes(o,m),w=!c&&g.length===0;p.forEach((x,M)=>{w||g.indexOf(M)>=0?u&&h.push(1):h.push(x)});let v=h.length,S=j.size(h);return{name:e,shaderCache:t,getShaderSource:x=>{let M=[],k=F("_A",n[0].dataType,m),$=le("output",l,v),P=i(k,$,g),I=P[2];for(let B=0,q=0;B<m;B++)w||g.indexOf(B)>=0?(u&&q++,I=`for(var j${B}: u32 = 0; j${B} < ${p[B]}; j${B}++) {
|
|
129
|
+
${P[2].includes("last_index")?`let last_index = j${B};`:""}
|
|
130
|
+
${k.indicesSet("input_indices",B,`j${B}`)}
|
|
131
|
+
${I}
|
|
132
|
+
}`):(M.push(`${k.indicesSet("input_indices",B,$.indicesGet("output_indices",q))};`),q++);return`
|
|
133
|
+
|
|
134
|
+
${x.registerUniform("output_size","u32").declareVariables(k,$)}
|
|
135
|
+
|
|
136
|
+
${x.mainStart()}
|
|
137
|
+
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
138
|
+
var input_indices: ${k.type.indices};
|
|
139
|
+
let output_indices = ${$.offsetToIndices("global_idx")};
|
|
140
|
+
|
|
141
|
+
${M.join(`
|
|
142
|
+
`)}
|
|
143
|
+
${P[0]} // init ops for reduce max/min
|
|
144
|
+
${P[1]}
|
|
145
|
+
${I}
|
|
146
|
+
${P[3]}
|
|
147
|
+
${P.length===4?$.setByOffset("global_idx","value"):P.slice(4).join(`
|
|
148
|
+
`)}
|
|
149
|
+
}`},getRunData:()=>({outputs:[{dims:h,dataType:l}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...L(p,h)]})}},Qi=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(i=>n.push(Number(i))),E({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},gr=(e,t,n,i)=>{let o=e.inputs,l=o.length===1?n:Qi(o,n);e.compute(vi(t,{hint:l.cacheKey,inputDependencies:["rank"]},[o[0]],l.noopWithEmptyAxes&&l.axes.length===0?zo:i,l.axes,o[0].dataType,l.keepDims,l.noopWithEmptyAxes),{inputs:[0]})},Lo=(e,t)=>{mr(e.inputs),gr(e,"ReduceLogSum",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},Bo=(e,t)=>{mr(e.inputs),gr(e,"ReduceL1",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},No=(e,t)=>{mr(e.inputs),gr(e,"ReduceL2",t,(n,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Uo=(e,t)=>{mr(e.inputs),gr(e,"ReduceLogSumExp",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},Fo=(e,t)=>{mr(e.inputs),gr(e,"ReduceMax",t,(n,i,o)=>{let l=[];for(let u=0;u<n.rank;u++)(o.indexOf(u)>=0||o.length===0)&&l.push(n.indicesSet("input_indices",u,0));return[`${l.join(`
|
|
150
|
+
`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},Vo=(e,t)=>{mr(e.inputs),gr(e,"ReduceMean",t,(n,i,o)=>{let l=1;for(let u=0;u<n.rank;u++)(o.indexOf(u)>=0||o.length===0)&&(l*=e.inputs[0].dims[u]);return["var sum = f32(0);","",`sum += f32(${n.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${l});`]})},Go=(e,t)=>{mr(e.inputs),gr(e,"ReduceMin",t,(n,i,o)=>{let l=[];for(let u=0;u<n.rank;u++)(o.indexOf(u)>=0||o.length===0)&&l.push(`input_indices[${u}] = 0;`);return[`${l.join(`
|
|
151
|
+
`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},qo=(e,t)=>{mr(e.inputs),gr(e,"ReduceProd",t,(n,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},Wo=(e,t)=>{mr(e.inputs),gr(e,"ReduceSum",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},Ho=(e,t)=>{mr(e.inputs),gr(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;`,""])},yr=(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)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Vo(e,t):fr(e,t)},jo=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bo(e,t):ss(e,t)},Qo=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?No(e,t):vt(e,t)},Xo=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Uo(e,t):pt(e,t)},Yo=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fo(e,t):ar(e,t)},Jo=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Go(e,t):yi(e,t)},Zo=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qo(e,t):wi(e,t)},el=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Wo(e,t):Po(e,t)},tl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ho(e,t):Oo(e,t)},rl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Lo(e,t):Do(e,t)}}),Yi,sl,nl,Ji,fm=b(()=>{Ie(),A(),Xi(),Yi=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},sl=(e,t)=>{Yi(e.inputs);let n=(i,o,l)=>{let u=[];for(let c=0;c<i.rank;c++)(l.indexOf(c)>=0||l.length===0)&&u.push(`input_indices[${c}] = 0;`);return[`${u.join(`
|
|
152
|
+
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
153
|
+
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {
|
|
154
|
+
value = ${i.getByIndices("input_indices")};
|
|
155
|
+
best_index = i32(last_index);
|
|
156
|
+
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(vi("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},nl=(e,t)=>{Yi(e.inputs);let n=(i,o,l)=>{let u=[];for(let c=0;c<i.rank;c++)(l.indexOf(c)>=0||l.length===0)&&u.push(`input_indices[${c}] = 0;`);return[`${u.join(`
|
|
157
|
+
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
158
|
+
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {
|
|
159
|
+
value = ${i.getByIndices("input_indices")};
|
|
160
|
+
best_index = i32(last_index);
|
|
161
|
+
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(vi("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},Ji=e=>E(e)}),il,_i,al,ol,ll,Gn,ul,dl,Zi=b(()=>{Ie(),ke(),Js(),ye(),il=(e,t)=>{let n=e[0],i=e[1],o=e[2],l=e[3],u=e[4],c=e[5];if(u&&c)throw new Error("Attention cannot have both past and attention_bias");if(n.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let h=n.dims[0],p=n.dims[1],m=n.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(i.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(i.dims[0]!==m)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==i.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let g=o.dims[0]/3,w=g,v=w;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let P of t.qkvHiddenSizes)if(P%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");g=t.qkvHiddenSizes[0],w=t.qkvHiddenSizes[1],v=t.qkvHiddenSizes[2]}let S=p;if(g!==w)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==g+w+v)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let x=0;if(u){if(w!==v)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(u.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(u.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(u.dims[1]!==h)throw new Error('Input "past" second dimension must be batch_size');if(u.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(u.dims[4]!==w/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(x=u.dims[3])}let M=S+x,k=-1,$=0;if(l)throw new Error("Mask not supported");if(u)throw new Error("past is not supported");if(c){if(c.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(c.dims[0]!==h||c.dims[1]!==t.numHeads||c.dims[2]!==p||c.dims[3]!==M)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:h,sequenceLength:p,pastSequenceLength:x,kvSequenceLength:S,totalSequenceLength:M,maxSequenceLength:k,inputHiddenSize:m,hiddenSize:g,vHiddenSize:v,headSize:Math.floor(g/t.numHeads),vHeadSize:Math.floor(v/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:$,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},_i=(e,t,n)=>t&&e?`
|
|
162
|
+
let total_sequence_length_input = u32(${t.getByOffset("0")});
|
|
163
|
+
let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);
|
|
164
|
+
let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;
|
|
165
|
+
let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;
|
|
166
|
+
total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1;
|
|
167
|
+
var past_sequence_length: u32 = 0;
|
|
168
|
+
if (is_first_prompt == false) {
|
|
169
|
+
past_sequence_length = total_sequence_length - sequence_length;
|
|
170
|
+
}
|
|
171
|
+
`:`
|
|
172
|
+
${n?"let past_sequence_length = uniforms.past_sequence_length":""};
|
|
173
|
+
let present_sequence_length = total_sequence_length;
|
|
174
|
+
`,al=(e,t,n,i,o,l,u,c)=>{let h=V(u?1:l),p=64,m=l/h;m<p&&(p=32);let g=Math.ceil(l/h/p),w=[{type:12,data:t},{type:12,data:n},{type:12,data:i},{type:12,data:o},{type:12,data:m},{type:12,data:g}],v=G(e.dataType,h),S=N(1,h),x=["type"];u&&x.push("type"),c&&x.push("type");let M=k=>{let $=le("x",e.dataType,e.dims,h),P=[$],I=u?F("seq_lens",u.dataType,u.dims):void 0;I&&P.push(I);let B=c?F("total_sequence_length_input",c.dataType,c.dims):void 0;B&&P.push(B);let q=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`
|
|
175
|
+
var<workgroup> thread_max: array<f32, ${p}>;
|
|
176
|
+
var<workgroup> thread_sum: array<f32, ${p}>;
|
|
177
|
+
${k.registerUniforms(W).declareVariables(...P)}
|
|
178
|
+
${k.mainStart([p,1,1])}
|
|
179
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
180
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
181
|
+
let sequence_length = uniforms.sequence_length;
|
|
182
|
+
var total_sequence_length = uniforms.total_sequence_length;
|
|
183
|
+
${_i(I,B,!1)}
|
|
184
|
+
let local_offset = local_idx * uniforms.elements_per_thread;
|
|
185
|
+
let offset = (global_idx / ${p}) * uniforms.total_sequence_length + local_offset;
|
|
186
|
+
let seq_causal_length = ${u?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"};
|
|
187
|
+
var thread_max_vector = ${S}(-3.4028234663852886e+38f);
|
|
188
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
189
|
+
thread_max_vector = max(${S}(x[offset + i]), thread_max_vector);
|
|
190
|
+
}
|
|
191
|
+
thread_max[local_idx] = ${(()=>{switch(h){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${h}`)}})()};
|
|
192
|
+
workgroupBarrier();
|
|
193
|
+
|
|
194
|
+
var max_value = f32(-3.4028234663852886e+38f);
|
|
195
|
+
for (var i = 0u; i < ${p}; i++) {
|
|
196
|
+
max_value = max(thread_max[i], max_value);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
var sum_vector = ${S}(0);
|
|
200
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
201
|
+
sum_vector += exp(${S}(x[offset + i]) - max_value);
|
|
202
|
+
}
|
|
203
|
+
thread_sum[local_idx] = ${(()=>{switch(h){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${h}`)}})()};
|
|
204
|
+
workgroupBarrier();
|
|
205
|
+
|
|
206
|
+
var sum: f32 = 0;
|
|
207
|
+
for (var i = 0u; i < ${p}; i++) {
|
|
208
|
+
sum += thread_sum[i];
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (sum == 0) {
|
|
212
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
213
|
+
x[offset + i] = ${$.type.value}(${q}(1.0) / ${q}(seq_causal_length));
|
|
214
|
+
}
|
|
215
|
+
} else {
|
|
216
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
217
|
+
var f32input = ${S}(x[offset + i]);
|
|
218
|
+
x[offset + i] = ${$.type.value}(exp(f32input - max_value) / sum);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
${u?`
|
|
222
|
+
for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {
|
|
223
|
+
x[offset + total_seq_id] = ${$.type.value}(${q}(0));
|
|
224
|
+
}`:""};
|
|
225
|
+
}`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${p};${v};${h}`,inputDependencies:x},getShaderSource:M,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:t*n},programUniforms:w})}},ol=(e,t,n,i,o,l,u,c,h)=>{let p=u+l.kvSequenceLength,m=[l.batchSize,l.numHeads,l.sequenceLength,p],g=e>1&&i,w=l.kvNumHeads?l.kvNumHeads:l.numHeads,v=g?[l.batchSize,w,p,l.headSize]:void 0,S=l.nReps?l.nReps:1,x=l.scale===0?1/Math.sqrt(l.headSize):l.scale,M=V(l.headSize),k=l.headSize/M,$=12,P={x:Math.ceil(p/$),y:Math.ceil(l.sequenceLength/$),z:l.batchSize*l.numHeads},I=[{type:12,data:l.sequenceLength},{type:12,data:k},{type:12,data:p},{type:12,data:l.numHeads},{type:12,data:l.headSize},{type:1,data:x},{type:12,data:u},{type:12,data:l.kvSequenceLength},{type:12,data:S}],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:v,dataType:t.dataType,gpuDataType:0});let ee=ue=>{let _e=F("q",t.dataType,t.dims,M),Fe=F("key",n.dataType,n.dims,M),Re=[_e,Fe];if(B){let De=F("past_key",i.dataType,i.dims,M);Re.push(De)}o&&Re.push(F("attention_bias",o.dataType,o.dims));let Me=c?F("seq_lens",c.dataType,c.dims):void 0;Me&&Re.push(Me);let Xe=h?F("total_sequence_length_input",h.dataType,h.dims):void 0;Xe&&Re.push(Xe);let ge=le("output",t.dataType,m),$e=[ge];g&&$e.push(le("present_key",t.dataType,v,M));let Le=N(1,M),Ve=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return`
|
|
226
|
+
const TILE_SIZE = ${$}u;
|
|
227
|
+
|
|
228
|
+
var<workgroup> tileQ: array<${_e.type.storage}, ${$*$}>;
|
|
229
|
+
var<workgroup> tileK: array<${_e.type.storage}, ${$*$}>;
|
|
230
|
+
${ue.registerUniforms(Ve).declareVariables(...Re,...$e)}
|
|
231
|
+
${ue.mainStart([$,$,1])}
|
|
232
|
+
// x holds the N and y holds the M
|
|
233
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
234
|
+
let kvHeadIdx = ${S===1?"headIdx":"headIdx / uniforms.n_reps"};
|
|
235
|
+
let kv_num_heads = ${S===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
|
|
236
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
237
|
+
let m = workgroup_id.y * TILE_SIZE;
|
|
238
|
+
let n = workgroup_id.x * TILE_SIZE;
|
|
239
|
+
let sequence_length = uniforms.M;
|
|
240
|
+
var total_sequence_length = uniforms.N;
|
|
241
|
+
${_i(Me,Xe,!0)}
|
|
242
|
+
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;
|
|
243
|
+
let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
244
|
+
${B&&g?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};
|
|
245
|
+
let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;
|
|
246
|
+
${g?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""}
|
|
247
|
+
var value = ${Le}(0);
|
|
248
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
249
|
+
if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {
|
|
250
|
+
tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];
|
|
251
|
+
}
|
|
252
|
+
if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {
|
|
253
|
+
var idx = TILE_SIZE * local_id.y + local_id.x;
|
|
254
|
+
${B&&g?`
|
|
255
|
+
if (n + local_id.y < past_sequence_length) {
|
|
256
|
+
tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
|
|
257
|
+
} else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
|
|
258
|
+
tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];
|
|
259
|
+
}`:`
|
|
260
|
+
if (n + local_id.y < uniforms.kv_sequence_length) {
|
|
261
|
+
tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
|
|
262
|
+
}`}
|
|
263
|
+
${g?`if (n + local_id.y < present_sequence_length) {
|
|
264
|
+
present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];
|
|
265
|
+
}`:""}
|
|
266
|
+
}
|
|
267
|
+
workgroupBarrier();
|
|
268
|
+
|
|
269
|
+
for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {
|
|
270
|
+
value += ${Le}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
workgroupBarrier();
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {
|
|
277
|
+
let headOffset = workgroup_id.z * uniforms.M * uniforms.N;
|
|
278
|
+
let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;
|
|
279
|
+
var sum: f32 = ${(()=>{switch(M){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${M}`)}})()};
|
|
280
|
+
output[outputIdx] = ${ge.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"};
|
|
281
|
+
}
|
|
282
|
+
}`};return{name:"AttentionProbs",shaderCache:{hint:`${M};${o!==void 0};${i!==void 0};${e}`,inputDependencies:q},getRunData:()=>({outputs:W,dispatchGroup:P,programUniforms:I}),getShaderSource:ee}},ll=(e,t,n,i,o,l,u=void 0,c=void 0)=>{let h=l+o.kvSequenceLength,p=o.nReps?o.nReps:1,m=o.vHiddenSize*p,g=e>1&&i,w=o.kvNumHeads?o.kvNumHeads:o.numHeads,v=g?[o.batchSize,w,h,o.headSize]:void 0,S=[o.batchSize,o.sequenceLength,m],x=12,M={x:Math.ceil(o.vHeadSize/x),y:Math.ceil(o.sequenceLength/x),z:o.batchSize*o.numHeads},k=[{type:12,data:o.sequenceLength},{type:12,data:h},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:m},{type:12,data:l},{type:12,data:o.kvSequenceLength},{type:12,data:p}],$=g&&i&&j.size(i.dims)>0,P=["type","type"];$&&P.push("type"),u&&P.push("type"),c&&P.push("type");let I=[{dims:S,dataType:t.dataType,gpuDataType:0}];g&&I.push({dims:v,dataType:t.dataType,gpuDataType:0});let B=q=>{let W=F("probs",t.dataType,t.dims),ee=F("v",n.dataType,n.dims),ue=[W,ee];$&&ue.push(F("past_value",i.dataType,i.dims));let _e=u?F("seq_lens",u.dataType,u.dims):void 0;u&&ue.push(_e);let Fe=c?F("total_sequence_length_input",c.dataType,c.dims):void 0;c&&ue.push(Fe);let Re=[le("output",t.dataType,S)];g&&Re.push(le("present_value",t.dataType,v));let Me=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return`
|
|
283
|
+
const TILE_SIZE = ${x}u;
|
|
284
|
+
var<workgroup> tileQ: array<${W.type.value}, ${x*x}>;
|
|
285
|
+
var<workgroup> tileV: array<${W.type.value}, ${x*x}>;
|
|
286
|
+
${q.registerUniforms(Me).declareVariables(...ue,...Re)}
|
|
287
|
+
${q.mainStart([x,x,1])}
|
|
288
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
289
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
290
|
+
let kvHeadIdx = ${p===1?"headIdx":"headIdx / uniforms.n_reps"};
|
|
291
|
+
let kv_num_heads = ${p===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
|
|
292
|
+
let m = global_id.y;
|
|
293
|
+
let n = global_id.x;
|
|
294
|
+
let sequence_length = uniforms.M;
|
|
295
|
+
var total_sequence_length = uniforms.K;
|
|
296
|
+
${_i(_e,Fe,!0)}
|
|
297
|
+
let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
298
|
+
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch
|
|
299
|
+
${$&&g?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};
|
|
300
|
+
let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;
|
|
301
|
+
${g?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""}
|
|
302
|
+
var value = ${W.type.storage}(0);
|
|
303
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
304
|
+
if (m < uniforms.M && w + local_id.x < uniforms.K) {
|
|
305
|
+
tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];
|
|
306
|
+
}
|
|
307
|
+
if (n < uniforms.N && w + local_id.y < uniforms.K) {
|
|
308
|
+
var idx = TILE_SIZE * local_id.y + local_id.x;
|
|
309
|
+
${$&&g?`
|
|
310
|
+
if (w + local_id.y < past_sequence_length) {
|
|
311
|
+
tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];
|
|
312
|
+
} else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
|
|
313
|
+
tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];
|
|
314
|
+
}
|
|
315
|
+
`:`
|
|
316
|
+
if (w + local_id.y < uniforms.kv_sequence_length) {
|
|
317
|
+
tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];
|
|
318
|
+
}`}
|
|
319
|
+
${g?`
|
|
320
|
+
if (w + local_id.y < present_sequence_length) {
|
|
321
|
+
present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];
|
|
322
|
+
}`:""}
|
|
323
|
+
}
|
|
324
|
+
workgroupBarrier();
|
|
325
|
+
for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {
|
|
326
|
+
value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];
|
|
327
|
+
}
|
|
328
|
+
workgroupBarrier();
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// we need to transpose output from BNSH_v to BSND_v
|
|
332
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
333
|
+
let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size
|
|
334
|
+
+ headIdx * uniforms.N + n;
|
|
335
|
+
output[outputIdx] = value;
|
|
336
|
+
}
|
|
337
|
+
}`};return{name:"AttentionScore",shaderCache:{hint:`${i!==void 0};${e}`,inputDependencies:P},getRunData:()=>({outputs:I,dispatchGroup:M,programUniforms:k}),getShaderSource:B}},Gn=(e,t,n,i,o,l,u,c,h,p,m=void 0,g=void 0)=>{let w=Math.min(e.outputCount,1+(u?1:0)+(c?1:0)),v=w>1?u:void 0,S=w>1?c:void 0,x=w>1?p.pastSequenceLength:0,M=x+p.kvSequenceLength,k=h&&j.size(h.dims)>0?h:void 0,$=[t,n];v&&j.size(v.dims)>0&&$.push(v),k&&$.push(k),m&&$.push(m),g&&$.push(g);let P=e.compute(ol(w,t,n,v,k,p,x,m,g),{inputs:$,outputs:w>1?[-1,1]:[-1]})[0];e.compute(al(P,p.batchSize,p.numHeads,x,p.sequenceLength,M,m,g),{inputs:m&&g?[P,m,g]:[P],outputs:[]});let I=[P,i];S&&j.size(S.dims)>0&&I.push(S),m&&I.push(m),g&&I.push(g),e.compute(ll(w,P,i,S,p,x,m,g),{inputs:I,outputs:w>1?[0,2]:[0]})},ul=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],i=t.sequenceLength,o=t.inputHiddenSize,l=t.headSize,u=12,c={x:Math.ceil(t.headSize/u),y:Math.ceil(t.sequenceLength/u),z:t.batchSize*t.numHeads},h=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:i},{type:12,data:o},{type:12,data:l},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=g=>{let w=le("output_q",h[0].dataType,n),v=le("output_k",h[0].dataType,n),S=le("output_v",h[0].dataType,n),x=F("input",h[0].dataType,h[0].dims),M=F("weight",h[1].dataType,h[1].dims),k=F("bias",h[2].dataType,h[2].dims),$=x.type.storage,P=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return`
|
|
338
|
+
const TILE_SIZE = ${u}u;
|
|
339
|
+
var<workgroup> tileInput: array<${$}, ${u*u}>;
|
|
340
|
+
var<workgroup> tileWeightQ: array<${$}, ${u*u}>;
|
|
341
|
+
var<workgroup> tileWeightK: array<${$}, ${u*u}>;
|
|
342
|
+
var<workgroup> tileWeightV: array<${$}, ${u*u}>;
|
|
343
|
+
${g.registerUniforms(P).declareVariables(x,M,k,w,v,S)}
|
|
344
|
+
${g.mainStart([u,u,1])}
|
|
345
|
+
let batchIndex = workgroup_id.z / uniforms.num_heads;
|
|
346
|
+
let headNumber = workgroup_id.z % uniforms.num_heads;
|
|
347
|
+
let m = global_id.y;
|
|
348
|
+
let n = global_id.x;
|
|
349
|
+
|
|
350
|
+
let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;
|
|
351
|
+
let biasOffsetQ = headNumber * uniforms.head_size;
|
|
352
|
+
let biasOffsetK = uniforms.hidden_size + biasOffsetQ;
|
|
353
|
+
let biasOffsetV = uniforms.hidden_size + biasOffsetK;
|
|
354
|
+
|
|
355
|
+
var valueQ = ${$}(0);
|
|
356
|
+
var valueK = ${$}(0);
|
|
357
|
+
var valueV = ${$}(0);
|
|
358
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
359
|
+
if (m < uniforms.M && w + local_id.x < uniforms.K) {
|
|
360
|
+
tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];
|
|
361
|
+
}
|
|
362
|
+
if (n < uniforms.N && w + local_id.y < uniforms.K) {
|
|
363
|
+
let offset = n + (w + local_id.y) * uniforms.ldb;
|
|
364
|
+
tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];
|
|
365
|
+
tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];
|
|
366
|
+
tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];
|
|
367
|
+
}
|
|
368
|
+
workgroupBarrier();
|
|
369
|
+
for (var k: u32 = 0u; k<TILE_SIZE && w+k < uniforms.K; k++) {
|
|
370
|
+
let inputTileOffset = TILE_SIZE * local_id.y + k;
|
|
371
|
+
let weightTileOffset = TILE_SIZE * k + local_id.x;
|
|
372
|
+
valueQ += tileInput[inputTileOffset] * tileWeightQ[weightTileOffset];
|
|
373
|
+
valueK += tileInput[inputTileOffset] * tileWeightK[weightTileOffset];
|
|
374
|
+
valueV += tileInput[inputTileOffset] * tileWeightV[weightTileOffset];
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
workgroupBarrier();
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
let headOffset = (m * uniforms.N + n) % uniforms.head_size;
|
|
381
|
+
valueQ += bias[headOffset + biasOffsetQ];
|
|
382
|
+
valueK += bias[headOffset + biasOffsetK];
|
|
383
|
+
valueV += bias[headOffset + biasOffsetV];
|
|
384
|
+
|
|
385
|
+
let offset = workgroup_id.z * uniforms.M * uniforms.N;
|
|
386
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
387
|
+
let outputIdx = offset + m * uniforms.N + n;
|
|
388
|
+
output_q[outputIdx] = valueQ;
|
|
389
|
+
output_k[outputIdx] = valueK;
|
|
390
|
+
output_v[outputIdx] = valueV;
|
|
391
|
+
}
|
|
392
|
+
}`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:p}),getShaderSource:m},{inputs:h,outputs:[-1,-1,-1]})},dl=(e,t)=>{let n=il(e.inputs,t),[i,o,l]=ul(e,n);return Gn(e,i,o,l,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}}),cl,hl,pl,fl,mm=b(()=>{ct(),Ie(),ke(),A(),ye(),cl=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let n=(i,o,l)=>{let u=o.length;if(u!==i.length)throw new Error(`${l}: num dimensions != ${u}`);o.forEach((c,h)=>{if(c!==i[h])throw new Error(`${l}: dim[${h}] do not match`)})};if(e[0].dims.length>1){let i=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);n(e[1].dims,i,"Invalid input scale"),n(e[2].dims,i,"Invalid input B"),n(e[3].dims,i,"Invalid input mean"),n(e[4].dims,i,"Invalid input var")}else n(e[1].dims,[1],"Invalid input scale"),n(e[2].dims,[1],"Invalid input B"),n(e[3].dims,[1],"Invalid input mean"),n(e[4].dims,[1],"Invalid input var")},hl=(e,t)=>{let{epsilon:n,spatial:i,format:o}=t,l=e[0].dims,u=i?V(l[l.length-1]):1,c=o==="NHWC"&&l.length>1?u:1,h=j.size(l)/u,p=i,m=p?l.length:l,g=F("x",e[0].dataType,e[0].dims,u),w=F("scale",e[1].dataType,e[1].dims,c),v=F("bias",e[2].dataType,e[2].dims,c),S=F("inputMean",e[3].dataType,e[3].dims,c),x=F("inputVar",e[4].dataType,e[4].dims,c),M=le("y",e[0].dataType,m,u),k=()=>{let P="";if(i)P=`let cOffset = ${l.length===1?"0u":o==="NHWC"?`outputIndices[${l.length-1}] / ${u}`:"outputIndices[1]"};`;else if(o==="NCHW")P=`
|
|
393
|
+
${M.indicesSet("outputIndices","0","0")}
|
|
394
|
+
let cOffset = ${M.indicesToOffset("outputIndices")};`;else{P=`var cIndices = ${w.type.indices}(0);
|
|
395
|
+
cIndices[0] = outputIndices[${l.length-1}];`;for(let I=1;I<w.rank;I++)P+=`cIndices[${I}] = outputIndices[${I}];`;P+=`let cOffset = ${w.indicesToOffset("cIndices")};`}return P},$=P=>`
|
|
396
|
+
const epsilon = ${n};
|
|
397
|
+
${P.registerUniform("outputSize","u32").declareVariables(g,w,v,S,x,M)}
|
|
398
|
+
${P.mainStart()}
|
|
399
|
+
${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
400
|
+
var outputIndices = ${M.offsetToIndices(`global_idx * ${u}`)};
|
|
401
|
+
${k()}
|
|
402
|
+
let scale = ${w.getByOffset("cOffset")};
|
|
403
|
+
let bias = ${v.getByOffset("cOffset")};
|
|
404
|
+
let inputMean = ${S.getByOffset("cOffset")};
|
|
405
|
+
let inputVar = ${x.getByOffset("cOffset")};
|
|
406
|
+
let x = ${g.getByOffset("global_idx")};
|
|
407
|
+
let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;
|
|
408
|
+
${M.setByOffset("global_idx","value")}
|
|
409
|
+
}`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${i}_${u}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:$,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p?[{type:12,data:h},...L(l)]:[{type:12,data:h}]})}},pl=e=>E(e),fl=(e,t)=>{let{inputs:n,outputCount:i}=e,o=pl({...t,outputCount:i});if(fe.webgpu.validateInputContent&&cl(n,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(hl(n,o))}}),ml,gl,yl,gm=b(()=>{ke(),ye(),ml=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},gl=e=>{let t=e[0].dims,n=e[0].dims[2],i=j.size(t)/4,o=e[0].dataType,l=F("input",o,t,4),u=F("bias",o,[n],4),c=F("residual",o,t,4),h=le("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:p=>`
|
|
410
|
+
const channels = ${n}u / 4;
|
|
411
|
+
${p.declareVariables(l,u,c,h)}
|
|
412
|
+
|
|
413
|
+
${p.mainStart()}
|
|
414
|
+
${p.guardAgainstOutOfBoundsWorkgroupSizes(i)}
|
|
415
|
+
let value = ${l.getByOffset("global_idx")}
|
|
416
|
+
+ ${u.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")};
|
|
417
|
+
${h.setByOffset("global_idx","value")}
|
|
418
|
+
}`}},yl=e=>{ml(e.inputs),e.compute(gl(e.inputs))}}),wl,et,vl,_l,bl,Sl,Tl,El,$l,xl,Cl,kl,Rl,Al,Il,Ml,qn,Pl,bi,Ol,Dl,zl,Ll,Bl,Nl,Ul,Fl,Vl,Gl,ql,Wl,Hl,Kl,jl,Ql,ea,Xl,ta,ra,Yl,Jl,Zl,eu,tu,ru,sa=b(()=>{Ie(),ke(),A(),ye(),wl=(e,t,n,i,o,l,u)=>{let c=Math.ceil(t/4),h="";typeof o=="string"?h=`${o}(a)`:h=o("a");let p=F("inputData",n,[c],4),m=le("outputData",i,[c],4),g=[{name:"vec_size",type:"u32"}];return u&&g.push(...u),`
|
|
419
|
+
${e.registerUniforms(g).declareVariables(p,m)}
|
|
420
|
+
|
|
421
|
+
${l??""}
|
|
422
|
+
|
|
423
|
+
${e.mainStart()}
|
|
424
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
425
|
+
|
|
426
|
+
let a = ${p.getByOffset("global_idx")};
|
|
427
|
+
${m.setByOffset("global_idx",h)}
|
|
428
|
+
}`},et=(e,t,n,i,o,l=e.dataType,u,c)=>{let h=[{type:12,data:Math.ceil(j.size(e.dims)/4)}];return u&&h.push(...u),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:p=>wl(p,j.size(e.dims),e.dataType,l,n,i,c),getRunData:p=>({outputs:[{dims:e.dims,dataType:l}],dispatchGroup:{x:Math.ceil(j.size(p[0].dims)/64/4)},programUniforms:h})}},vl=e=>{e.compute(et(e.inputs[0],"Abs","abs"))},_l=e=>{e.compute(et(e.inputs[0],"Acos","acos"))},bl=e=>{e.compute(et(e.inputs[0],"Acosh","acosh"))},Sl=e=>{e.compute(et(e.inputs[0],"Asin","asin"))},Tl=e=>{e.compute(et(e.inputs[0],"Asinh","asinh"))},El=e=>{e.compute(et(e.inputs[0],"Atan","atan"))},$l=e=>{e.compute(et(e.inputs[0],"Atanh","atanh"))},xl=e=>E(e),Cl=(e,t)=>{let n;switch(t.to){case 10:n="vec4<f16>";break;case 1:n="vec4<f32>";break;case 12:n="vec4<u32>";break;case 6:n="vec4<i32>";break;case 9:n="vec4<bool>";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(et(e.inputs[0],"Cast",n,void 0,t.cacheKey,t.to))},kl=e=>{let t,n,i=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=i?e[1].getFloat32Array()[0]:-34028234663852886e22,n=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=i?e[1].getUint16Array()[0]:64511,n=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return E({min:t,max:n})},Rl=(e,t)=>{let n=t||kl(e.inputs),i=N(e.inputs[0].dataType);e.compute(et(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${i}>(uniforms.min), vec4<${i}>(uniforms.max))`,void 0,n.cacheKey,void 0,[{type:e.inputs[0].dataType,data:n.min},{type:e.inputs[0].dataType,data:n.max}],[{name:"min",type:i},{name:"max",type:i}]),{inputs:[0]})},Al=e=>{e.compute(et(e.inputs[0],"Ceil","ceil"))},Il=e=>{e.compute(et(e.inputs[0],"Cos","cos"))},Ml=e=>{e.compute(et(e.inputs[0],"Cosh","cosh"))},qn=e=>E(e),Pl=(e,t)=>{let n=N(e.inputs[0].dataType);e.compute(et(e.inputs[0],"Elu",i=>`elu_vf32(${i})`,`
|
|
429
|
+
const elu_alpha_ = ${n}(${t.alpha});
|
|
430
|
+
|
|
431
|
+
fn elu_f32(a: ${n}) -> ${n} {
|
|
432
|
+
return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> {
|
|
436
|
+
return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));
|
|
437
|
+
}`,t.cacheKey))},bi=(e="f32")=>`
|
|
438
|
+
const r0: ${e} = 0.3275911;
|
|
439
|
+
const r1: ${e} = 0.254829592;
|
|
440
|
+
const r2: ${e} = -0.284496736;
|
|
441
|
+
const r3: ${e} = 1.421413741;
|
|
442
|
+
const r4: ${e} = -1.453152027;
|
|
443
|
+
const r5: ${e} = 1.061405429;
|
|
444
|
+
|
|
445
|
+
fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {
|
|
446
|
+
let absv = abs(v);
|
|
447
|
+
let x = 1.0 / (1.0 + r0 * absv);
|
|
448
|
+
return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));
|
|
449
|
+
}`,Ol=e=>{let t=N(e.inputs[0].dataType);e.compute(et(e.inputs[0],"Erf",n=>`erf_vf32(${n})`,bi(t)))},Dl=e=>{e.compute(et(e.inputs[0],"Exp","exp"))},zl=e=>{e.compute(et(e.inputs[0],"Floor","floor"))},Ll=e=>{let t=N(e.inputs[0].dataType);e.compute(et(e.inputs[0],"Gelu",n=>`0.5 * ${n} * (1.0 + erf_vf32(${n} * 0.7071067811865475))`,bi(t)))},Bl=(e,t)=>{let n=N(e.inputs[0].dataType);e.compute(et(e.inputs[0],"LeakyRelu",i=>`select(leaky_relu_alpha_ * ${i}, ${i}, ${i} >= vec4<${n}>(0.0))`,`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},Nl=e=>{e.compute(et(e.inputs[0],"Not",t=>`!${t}`))},Ul=e=>{e.compute(et(e.inputs[0],"Neg",t=>`-${t}`))},Fl=e=>{e.compute(et(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Vl=e=>{let t=N(e.inputs[0].dataType);e.compute(et(e.inputs[0],"Relu",n=>`select(vec4<${t}>(0.0), ${n}, ${n} > vec4<${t}>(0.0))`))},Gl=e=>{e.compute(et(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},ql=e=>E(e),Wl=(e,t)=>{let n=N(e.inputs[0].dataType);e.compute(et(e.inputs[0],"HardSigmoid",i=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${i} + vec4<${n}>(${t.beta})))`,void 0,t.cacheKey))},Hl=e=>{e.compute(et(e.inputs[0],"Sin","sin"))},Kl=e=>{e.compute(et(e.inputs[0],"Sinh","sinh"))},jl=e=>{e.compute(et(e.inputs[0],"Sqrt","sqrt"))},Ql=e=>{e.compute(et(e.inputs[0],"Tan","tan"))},ea=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Xl=e=>{e.compute(et(e.inputs[0],"Tanh",ea))},ta=(e="f32")=>`
|
|
450
|
+
const fast_gelu_a: ${e} = 0.5;
|
|
451
|
+
const fast_gelu_b: ${e} = 0.7978845608028654;
|
|
452
|
+
const fast_gelu_c: ${e} = 0.035677408136300125;
|
|
453
|
+
|
|
454
|
+
fn tanh_v(v: vec4<${e}>) -> vec4<${e}> {
|
|
455
|
+
return ${ea("v")};
|
|
456
|
+
}
|
|
457
|
+
`,ra=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Yl=e=>{let t=N(e.inputs[0].dataType);e.compute(et(e.inputs[0],"FastGelu",ra,ta(t),void 0,e.inputs[0].dataType))},Jl=(e,t)=>{let n=N(e.inputs[0].dataType);return e.compute(et(e.inputs[0],"ThresholdedRelu",i=>`select(vec4<${n}>(0.0), ${i}, ${i} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},Zl=e=>{e.compute(et(e.inputs[0],"Log","log"))},eu=(e,t)=>`
|
|
458
|
+
const alpha = vec4<${e}>(${t});
|
|
459
|
+
const one = ${e}(1.0);
|
|
460
|
+
const zero = ${e}(0.0);
|
|
461
|
+
|
|
462
|
+
fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
463
|
+
let v = x *alpha;
|
|
464
|
+
var x1 : vec4<${e}>;
|
|
465
|
+
for (var i = 0; i < 4; i = i + 1) {
|
|
466
|
+
if (v[i] >= zero) {
|
|
467
|
+
x1[i] = one / (one + exp(-v[i]));
|
|
468
|
+
} else {
|
|
469
|
+
x1[i] = one - one / (one + exp(v[i]));
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
return x * x1;
|
|
473
|
+
}
|
|
474
|
+
`,tu=e=>`quick_gelu_impl(${e})`,ru=(e,t)=>{let n=N(e.inputs[0].dataType);e.compute(et(e.inputs[0],"QuickGelu",tu,eu(n,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),su,nu,iu,ym=b(()=>{ke(),ye(),sa(),su=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},nu=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let n=F("input",e[0].dataType,e[0].dims,4),i=F("bias",e[0].dataType,[e[0].dims[2]],4),o=le("output",e[0].dataType,t,4),l=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=>`
|
|
475
|
+
const M_SQRT2 = sqrt(2.0);
|
|
476
|
+
const halfChannels = ${e[0].dims[2]/4/2}u;
|
|
477
|
+
|
|
478
|
+
${c.declareVariables(n,i,o)}
|
|
479
|
+
|
|
480
|
+
${bi(u)}
|
|
481
|
+
|
|
482
|
+
${c.mainStart()}
|
|
483
|
+
${c.guardAgainstOutOfBoundsWorkgroupSizes(l)}
|
|
484
|
+
let biasIdx = global_idx % halfChannels;
|
|
485
|
+
let batchIndex = global_idx / halfChannels;
|
|
486
|
+
let inputOffset = biasIdx + batchIndex * halfChannels * 2;
|
|
487
|
+
let valueLeft = input[inputOffset] + bias[biasIdx];
|
|
488
|
+
let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];
|
|
489
|
+
let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);
|
|
490
|
+
|
|
491
|
+
${o.setByOffset("global_idx","valueLeft * geluRight")}
|
|
492
|
+
}`}},iu=e=>{su(e.inputs),e.compute(nu(e.inputs))}}),au,ou,wr,lu,uu,du,cu,hu,pu,fu,mu,gu,yu,wm=b(()=>{Ie(),ke(),ye(),au=(e,t,n,i,o,l,u,c,h,p,m,g)=>{let w,v;typeof c=="string"?w=v=($,P)=>`${c}((${$}),(${P}))`:typeof c=="function"?w=v=c:(w=c.scalar,v=c.vector);let S=le("outputData",m,i.length,4),x=F("aData",h,t.length,4),M=F("bData",p,n.length,4),k;if(o)if(l){let $=j.size(t)===1,P=j.size(n)===1,I=t.length>0&&t[t.length-1]%4===0,B=n.length>0&&n[n.length-1]%4===0;$||P?k=S.setByOffset("global_idx",v($?`${x.type.value}(${x.getByOffset("0")}.x)`:x.getByOffset("global_idx"),P?`${M.type.value}(${M.getByOffset("0")}.x)`:M.getByOffset("global_idx"))):k=`
|
|
493
|
+
let outputIndices = ${S.offsetToIndices("global_idx * 4u")};
|
|
494
|
+
let offsetA = ${x.broadcastedIndicesToOffset("outputIndices",S)};
|
|
495
|
+
let offsetB = ${M.broadcastedIndicesToOffset("outputIndices",S)};
|
|
496
|
+
${S.setByOffset("global_idx",v(u||I?x.getByOffset("offsetA / 4u"):`${x.type.value}(${x.getByOffset("offsetA / 4u")}[offsetA % 4u])`,u||B?M.getByOffset("offsetB / 4u"):`${M.type.value}(${M.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}
|
|
497
|
+
`}else k=S.setByOffset("global_idx",v(x.getByOffset("global_idx"),M.getByOffset("global_idx")));else{if(!l)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let $=(P,I,B="")=>{let q=`aData[indexA${I}][componentA${I}]`,W=`bData[indexB${I}][componentB${I}]`;return`
|
|
498
|
+
let outputIndices${I} = ${S.offsetToIndices(`global_idx * 4u + ${I}u`)};
|
|
499
|
+
let offsetA${I} = ${x.broadcastedIndicesToOffset(`outputIndices${I}`,S)};
|
|
500
|
+
let offsetB${I} = ${M.broadcastedIndicesToOffset(`outputIndices${I}`,S)};
|
|
501
|
+
let indexA${I} = offsetA${I} / 4u;
|
|
502
|
+
let indexB${I} = offsetB${I} / 4u;
|
|
503
|
+
let componentA${I} = offsetA${I} % 4u;
|
|
504
|
+
let componentB${I} = offsetB${I} % 4u;
|
|
505
|
+
${P}[${I}] = ${B}(${w(q,W)});
|
|
506
|
+
`};m===9?k=`
|
|
507
|
+
var data = vec4<u32>(0);
|
|
508
|
+
${$("data",0,"u32")}
|
|
509
|
+
${$("data",1,"u32")}
|
|
510
|
+
${$("data",2,"u32")}
|
|
511
|
+
${$("data",3,"u32")}
|
|
512
|
+
outputData[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:k=`
|
|
513
|
+
${$("outputData[global_idx]",0)}
|
|
514
|
+
${$("outputData[global_idx]",1)}
|
|
515
|
+
${$("outputData[global_idx]",2)}
|
|
516
|
+
${$("outputData[global_idx]",3)}
|
|
517
|
+
`}return`
|
|
518
|
+
${e.registerUniform("vec_size","u32").declareVariables(x,M,S)}
|
|
519
|
+
|
|
520
|
+
${g??""}
|
|
521
|
+
|
|
522
|
+
${e.mainStart()}
|
|
523
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
524
|
+
${k}
|
|
525
|
+
}`},ou=(e,t,n,i,o,l,u=n.dataType)=>{let c=n.dims.map(Number),h=i.dims.map(Number),p=!j.areEqual(c,h),m=c,g=j.size(c),w=!1,v=!1,S=[p];if(p){let x=Cr.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,P=h.length>0&&h[h.length-1]%4===0;S.push(M),S.push(k),S.push($),S.push(P);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?(v=!0,w=!0):(M||k||$||P)&&(w=!0)}else w=!0;return S.push(w),{name:e,shaderCache:{hint:t+S.map(x=>x.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:x=>au(x,c,h,m,w,p,v,o,n.dataType,i.dataType,u,l),getRunData:()=>({outputs:[{dims:m,dataType:u}],dispatchGroup:{x:Math.ceil(g/64/4)},programUniforms:[{type:12,data:Math.ceil(j.size(m)/4)},...L(c,h,m)]})}},wr=(e,t,n,i,o,l)=>{e.compute(ou(t,o??"",e.inputs[0],e.inputs[1],n,i,l))},lu=e=>{wr(e,"Add",(t,n)=>`${t}+${n}`)},uu=e=>{wr(e,"Div",(t,n)=>`${t}/${n}`)},du=e=>{wr(e,"Equal",{scalar:(t,n)=>`u32(${t}==${n})`,vector:(t,n)=>`vec4<u32>(${t}==${n})`},void 0,void 0,9)},cu=e=>{wr(e,"Mul",(t,n)=>`${t}*${n}`)},hu=e=>{let t=F("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;wr(e,"Pow",{scalar:(n,i)=>`pow_custom(${n},${i})`,vector:(n,i)=>`pow_vector_custom(${n},${i})`},`
|
|
526
|
+
fn pow_custom(a : ${t}, b : ${t}) -> ${t} {
|
|
527
|
+
if (b == ${t}(0.0)) {
|
|
528
|
+
return ${t}(1.0);
|
|
529
|
+
} else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {
|
|
530
|
+
return ${t}(pow(f32(a), f32(b))); // NaN
|
|
531
|
+
}
|
|
532
|
+
return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));
|
|
533
|
+
}
|
|
534
|
+
fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {
|
|
535
|
+
// TODO: implement vectorized pow
|
|
536
|
+
return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));
|
|
537
|
+
}
|
|
538
|
+
`)},pu=e=>{wr(e,"Sub",(t,n)=>`${t}-${n}`)},fu=e=>{wr(e,"Greater",{scalar:(t,n)=>`u32(${t}>${n})`,vector:(t,n)=>`vec4<u32>(${t}>${n})`},void 0,void 0,9)},mu=e=>{wr(e,"Less",{scalar:(t,n)=>`u32(${t}<${n})`,vector:(t,n)=>`vec4<u32>(${t}<${n})`},void 0,void 0,9)},gu=e=>{wr(e,"GreaterOrEqual",{scalar:(t,n)=>`u32(${t}>=${n})`,vector:(t,n)=>`vec4<u32>(${t}>=${n})`},void 0,void 0,9)},yu=e=>{wr(e,"LessOrEqual",{scalar:(t,n)=>`u32(${t}<=${n})`,vector:(t,n)=>`vec4<u32>(${t}<=${n})`},void 0,void 0,9)}}),wu,vu,_u,bu,Su,Tu,vm=b(()=>{Ie(),ke(),A(),ye(),wu=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let n=0,i=e[n],o=i.dataType,l=i.dims.length;e.forEach((u,c)=>{if(c!==n){if(u.dataType!==o)throw new Error("input tensors should be one type");if(u.dims.length!==l)throw new Error("input tensors should have the same shape");u.dims.forEach((h,p)=>{if(p!==t&&h!==i.dims[p])throw new Error("non concat dimensions must match")})}})},vu=(e,t)=>`
|
|
539
|
+
fn calculateInputIndex(index: u32) -> u32 {
|
|
540
|
+
let sizeInConcatAxis = array<u32, ${e}u>(${t});
|
|
541
|
+
for (var i: u32 = 0u; i < ${e}; i += 1u ) {
|
|
542
|
+
if (index < sizeInConcatAxis[i]) {
|
|
543
|
+
return i;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
return ${e}u;
|
|
547
|
+
}`,_u=(e,t)=>{let n=e.length,i=[];for(let o=0;o<n;++o){let l=t.setByOffset("global_idx",e[o].getByIndices("indices"));n===1?i.push(l):o===0?i.push(`if (inputIndex == ${o}u) { ${l} }`):o===n-1?i.push(`else { ${l} }`):i.push(`else if (inputIndex == ${o}) { ${l} }`)}return i.join(`
|
|
548
|
+
`)},bu=(e,t,n,i)=>{let o=j.size(n),l=new Array(e.length),u=new Array(e.length),c=0,h=[],p=[],m=[{type:12,data:o}];for(let x=0;x<e.length;++x)c+=e[x].dims[t],l[x]=c,p.push(e[x].dims.length),u[x]=F(`input${x}`,i,p[x]),h.push("rank"),m.push({type:12,data:l[x]});for(let x=0;x<e.length;++x)m.push(...L(e[x].dims));m.push(...L(n));let g=le("output",i,n.length),w=g.indicesGet("indices",t),v=Array.from(Array(l.length).keys()).map(x=>`uniforms.sizeInConcatAxis${x}`).join(","),S=x=>`
|
|
549
|
+
|
|
550
|
+
${(()=>{x.registerUniform("outputSize","u32");for(let M=0;M<e.length;M++)x.registerUniform(`sizeInConcatAxis${M}`,"u32");return x.declareVariables(...u,g)})()}
|
|
551
|
+
|
|
552
|
+
${vu(l.length,v)}
|
|
553
|
+
|
|
554
|
+
${x.mainStart()}
|
|
555
|
+
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
556
|
+
|
|
557
|
+
var indices = ${g.offsetToIndices("global_idx")};
|
|
558
|
+
|
|
559
|
+
let inputIndex = calculateInputIndex(${w});
|
|
560
|
+
if (inputIndex != 0u) {
|
|
561
|
+
let sizeInConcatAxis = array<u32, ${l.length}u>(${v});
|
|
562
|
+
${w} -= sizeInConcatAxis[inputIndex - 1u];
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
${_u(u,g)}
|
|
566
|
+
}`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:S}},Su=(e,t)=>{let n=e.inputs,i=n[0].dims,o=j.normalizeAxis(t.axis,i.length);wu(n,o);let l=i.slice();l[o]=n.reduce((c,h)=>c+(h.dims.length>o?h.dims[o]:0),0);let u=n.filter(c=>j.size(c.dims)>0);e.compute(bu(u,o,l,n[0].dataType),{inputs:u})},Tu=e=>E({axis:e.axis})}),Rs,As,Is,na,Ms=b(()=>{Ie(),ke(),Rs=(e,t,n="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value));
|
|
567
|
+
value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
|
|
568
|
+
`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},As=(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})},Is=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},na=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[n,i]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:i}}else if(t==="Clip"){let[n,i]=e?.activation_params||[Mn,cr];return{activation:t,clipMax:i,clipMin:n}}else if(t==="LeakyRelu"){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}}),Pt,Eu,ia=b(()=>{Pt=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Eu=e=>`
|
|
569
|
+
${e?"value = value + getBiasByOutputCoords(coords);":""}
|
|
570
|
+
`}),$u,_m=b(()=>{$u=e=>`
|
|
571
|
+
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
|
|
572
|
+
return dot(coords, vec4<i32>(
|
|
573
|
+
shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
|
|
574
|
+
}
|
|
575
|
+
fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
|
|
576
|
+
return dot(coords, vec4<i32>(
|
|
577
|
+
i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));
|
|
578
|
+
}
|
|
579
|
+
`}),Wn,aa,oa=b(()=>{Ie(),ke(),ye(),Ms(),Wn=(e,t,n,i,o)=>{let l=i-n;return`
|
|
580
|
+
${Array.from({length:n}).map((u,c)=>`
|
|
581
|
+
if (${Q(t.shape,c,t.rank)} != 1) {
|
|
582
|
+
${t.indicesSet(e,c,Q(o,c+l,i))}
|
|
583
|
+
} else {
|
|
584
|
+
${t.indicesSet(e,c,0)}
|
|
585
|
+
}`).join("")}
|
|
586
|
+
`},aa=(e,t,n,i,o=!1,l)=>{let u=e[0].dims,c=e[1].dims,h=u[u.length-2],p=c[c.length-1],m=u[u.length-1],g=V(p),w=V(m),v=V(h),S=j.size(n)/g/v,x=e.length>2,M=i?i.slice(0,-2):n.slice(0,-2),k=[j.size(M),h,p],$=[{type:12,data:S},{type:12,data:h},{type:12,data:p},{type:12,data:m}];As(t,$),$.push(...L(M,u,c)),x&&$.push(...L(e[2].dims)),$.push(...L(k));let P=I=>{let B=Be("batch_dims",e[0].dataType,M.length),q=F("a",e[0].dataType,u.length,w),W=F("b",e[1].dataType,c.length,g),ee=le("output",e[0].dataType,k.length,g),ue=G(ee.type.tensor),_e=Rs(t,ee.type.value,ue),Fe=[q,W],Re="";if(x){let ge=o?g:1;Fe.push(F("bias",e[2].dataType,e[2].dims.length,ge)),Re=`${o?`value += bias[col / ${ge}];`:`value += ${ee.type.value}(bias[row + i]);`}`}let Me=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Is(t,Me);let Xe=()=>{let ge=`var a_data: ${q.type.value};`;for(let $e=0;$e<w;$e++)ge+=`
|
|
587
|
+
let b_data${$e} = b[(b_offset + (k + ${$e}) * uniforms.N + col) / ${g}];`;for(let $e=0;$e<v;$e++){ge+=`a_data = a[(a_offset + (row + ${$e}) * uniforms.K + k) / ${w}];`;for(let Le=0;Le<w;Le++)ge+=`
|
|
588
|
+
values[${$e}] = fma(${W.type.value}(a_data${w===1?"":`[${Le}]`}), b_data${Le}, values[${$e}]);
|
|
589
|
+
`}return ge};return`
|
|
590
|
+
${I.registerUniforms(Me).registerInternalVariables(B).declareVariables(...Fe,ee)}
|
|
591
|
+
${I.mainStart()}
|
|
592
|
+
${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
593
|
+
let col = (global_idx % (uniforms.N / ${g})) * ${g};
|
|
594
|
+
var index1 = global_idx / (uniforms.N / ${g});
|
|
595
|
+
let stride1 = uniforms.M / ${v};
|
|
596
|
+
let row = (index1 % stride1) * ${v};
|
|
597
|
+
let batch = index1 / stride1;
|
|
598
|
+
|
|
599
|
+
${n.length===2?"":`let batch_indices = ${B.offsetToIndices("batch")};`}
|
|
600
|
+
|
|
601
|
+
var a_indices: ${q.type.indices};
|
|
602
|
+
${Wn("a_indices",q,q.rank-2,B.rank,"batch_indices")}
|
|
603
|
+
${q.indicesSet("a_indices",q.rank-2,0)}
|
|
604
|
+
${q.indicesSet("a_indices",q.rank-1,0)}
|
|
605
|
+
let a_offset = ${q.indicesToOffset("a_indices")};
|
|
606
|
+
|
|
607
|
+
var b_indices: ${W.type.indices};
|
|
608
|
+
${Wn("b_indices",W,W.rank-2,B.rank,"batch_indices")}
|
|
609
|
+
${W.indicesSet("b_indices",W.rank-2,0)}
|
|
610
|
+
${W.indicesSet("b_indices",W.rank-1,0)}
|
|
611
|
+
let b_offset = ${W.indicesToOffset("b_indices")};
|
|
612
|
+
var values: array<${ee.type.value}, ${v}>;
|
|
613
|
+
for (var k: u32 = 0u; k < uniforms.K; k = k + ${w}) {
|
|
614
|
+
${Xe()}
|
|
615
|
+
}
|
|
616
|
+
for (var i = 0u; i < ${v}u; i++) {
|
|
617
|
+
var value = values[i];
|
|
618
|
+
${Re}
|
|
619
|
+
${_e}
|
|
620
|
+
let cur_indices = ${ee.type.indices}(batch, row + i, col);
|
|
621
|
+
let offset = ${ee.indicesToOffset("cur_indices")};
|
|
622
|
+
${ee.setByOffset(`offset / ${g}`,"value")};
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
`};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${g};${w};${v};${o}`,inputDependencies:x?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:$}),getShaderSource:P}}}),xu,Cu,la,ua,ku,da,Ru,Si,ca=b(()=>{Ie(),ke(),ye(),Ms(),oa(),ia(),xu=(e,t)=>e?`
|
|
626
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
627
|
+
kStart + inputRow,
|
|
628
|
+
globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});
|
|
629
|
+
`:`
|
|
630
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
631
|
+
globalRow + innerRow,
|
|
632
|
+
kStart / innerElementSize + inputCol${t?", batchIndices":""});
|
|
633
|
+
`,Cu=(e,t)=>e?`
|
|
634
|
+
let ACached0 = mm_Asub[k * innerElementSize][localRow];
|
|
635
|
+
let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];
|
|
636
|
+
let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];
|
|
637
|
+
${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}
|
|
638
|
+
for (var i = 0; i < rowPerThread; i = i + 1) {
|
|
639
|
+
acc[i] = BCached0 * ACached0[i] + acc[i];
|
|
640
|
+
acc[i] = BCached1 * ACached1[i] + acc[i];
|
|
641
|
+
acc[i] = BCached2 * ACached2[i] + acc[i];
|
|
642
|
+
${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}
|
|
643
|
+
}`:`
|
|
644
|
+
for (var i = 0; i < rowPerThread; i = i + 1) {
|
|
645
|
+
let ACached = mm_Asub[tileRow + i][k];
|
|
646
|
+
acc[i] = BCached0 * ACached.x + acc[i];
|
|
647
|
+
acc[i] = BCached1 * ACached.y + acc[i];
|
|
648
|
+
acc[i] = BCached2 * ACached.z + acc[i];
|
|
649
|
+
${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}
|
|
650
|
+
}`,la=(e,t,n="f32",i,o=!1,l=32,u=!1,c=32)=>{let h=t[1]*e[1],p=t[0]*e[0],m=o?h:l,g=o?l:h,w=m/t[0],v=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.
|
|
651
|
+
Otherwise, innerElementSize ${w} must be 3 or 4.
|
|
652
|
+
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`
|
|
653
|
+
var<workgroup> mm_Asub: array<array<vec${w}<${n}>, ${m/w}>, ${g}>;
|
|
654
|
+
var<workgroup> mm_Bsub: array<array<vec4<${n}>, ${p/e[0]}>, ${l}>;
|
|
655
|
+
|
|
656
|
+
const rowPerThread = ${e[1]};
|
|
657
|
+
const colPerThread = ${e[0]};
|
|
658
|
+
const innerElementSize = ${w};
|
|
659
|
+
const tileInner = ${l};
|
|
660
|
+
|
|
661
|
+
@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})
|
|
662
|
+
fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
663
|
+
@builtin(global_invocation_id) globalId : vec3<u32>,
|
|
664
|
+
@builtin(workgroup_id) workgroupId : vec3<u32>) {
|
|
665
|
+
let localRow = i32(localId.y);
|
|
666
|
+
let tileRow = localRow * rowPerThread;
|
|
667
|
+
let tileCol = i32(localId.x);
|
|
668
|
+
|
|
669
|
+
let globalRow =i32(globalId.y) * rowPerThread;
|
|
670
|
+
let globalCol = i32(globalId.x);
|
|
671
|
+
let batch = ${u?"0":"i32(globalId.z)"};
|
|
672
|
+
${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""}
|
|
673
|
+
let globalRowStart = i32(workgroupId.y) * ${h};
|
|
674
|
+
|
|
675
|
+
let num_tiles = ${u?`${Math.ceil(c/l)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
|
|
676
|
+
var kStart = ${u?`i32(globalId.z) * ${c}`:"0"};
|
|
677
|
+
|
|
678
|
+
var acc: array<vec4<${n}>, rowPerThread>;
|
|
679
|
+
|
|
680
|
+
// Loop over shared dimension.
|
|
681
|
+
let tileRowB = localRow * ${v};
|
|
682
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
683
|
+
// Load one tile of A into local memory.
|
|
684
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
685
|
+
let inputRow = tileRow + innerRow;
|
|
686
|
+
let inputCol = tileCol;
|
|
687
|
+
${xu(o,i)}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// Load one tile of B into local memory.
|
|
691
|
+
for (var innerRow = 0; innerRow < ${v}; innerRow = innerRow + 1) {
|
|
692
|
+
let inputRow = tileRowB + innerRow;
|
|
693
|
+
let inputCol = tileCol;
|
|
694
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${i?", batchIndices":""});
|
|
695
|
+
}
|
|
696
|
+
kStart = kStart + tileInner;
|
|
697
|
+
workgroupBarrier();
|
|
698
|
+
|
|
699
|
+
// Compute acc values for a single thread.
|
|
700
|
+
for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {
|
|
701
|
+
let BCached0 = mm_Bsub[k * innerElementSize][tileCol];
|
|
702
|
+
let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];
|
|
703
|
+
let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];
|
|
704
|
+
${w===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}
|
|
705
|
+
|
|
706
|
+
${Cu(o,w)}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
workgroupBarrier();
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
713
|
+
mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
|
|
714
|
+
}
|
|
715
|
+
}`},ua=(e,t)=>e?`
|
|
716
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
717
|
+
kStart + inputRow,
|
|
718
|
+
globalRowStart + inputCol${t?", batchIndices":""});
|
|
719
|
+
`:`
|
|
720
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
721
|
+
globalRowStart + inputRow,
|
|
722
|
+
kStart + inputCol${t?", batchIndices":""});
|
|
723
|
+
`,ku=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",da=(e,t,n="f32",i,o=!1,l=32,u=!1,c=32,h=!1)=>{let p=e[1]*t[1],m=e[0]*t[0],g=o?p:l,w=o?l:p;if(!(w%t[1]===0&&g%t[0]===0&&l%t[1]===0))throw new Error(`tileAHight ${w} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}, tileInner ${l} must be divisible by workgroupSize[1]${t[1]}`);let v=w/t[1],S=g/t[0],x=l/t[1],M=h?`
|
|
724
|
+
let localRow = i32(localId.y);
|
|
725
|
+
let localCol = i32(localId.x);
|
|
726
|
+
let globalRowStart = i32(workgroupId.y) * ${p};
|
|
727
|
+
let globalColStart = i32(workgroupId.x) * ${m};
|
|
728
|
+
|
|
729
|
+
// Loop over shared dimension.
|
|
730
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
731
|
+
// Load one tile of A into local memory.
|
|
732
|
+
for (var inputRow = localRow; inputRow < ${w}; inputRow = inputRow + ${t[1]}) {
|
|
733
|
+
for (var inputCol = localCol; inputCol < ${g}; inputCol = inputCol + ${t[0]}) {
|
|
734
|
+
${ua(o,i)}
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
// Load one tile of B into local memory.
|
|
738
|
+
for (var inputRow = localRow; inputRow < ${l}; inputRow = inputRow + ${t[1]}) {
|
|
739
|
+
for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) {
|
|
740
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch,
|
|
741
|
+
kStart + inputRow,
|
|
742
|
+
globalColStart + inputCol${i?", batchIndices":""});
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
kStart = kStart + tileInner;
|
|
746
|
+
workgroupBarrier();
|
|
747
|
+
|
|
748
|
+
// Compute acc values for a single thread.
|
|
749
|
+
var BCached : array<${n}, colPerThread>;
|
|
750
|
+
for (var k = 0; k < tileInner; k = k + 1) {
|
|
751
|
+
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
|
|
752
|
+
BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];
|
|
753
|
+
}
|
|
754
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
755
|
+
let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}
|
|
756
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
757
|
+
acc[innerRow][innerCol] = acc[innerRow][innerCol] +
|
|
758
|
+
ACached * BCached[innerCol];
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
workgroupBarrier();
|
|
763
|
+
}
|
|
764
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
765
|
+
let gRow = globalRowStart + localRow + innerRow * ${t[1]};
|
|
766
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
767
|
+
let gCol = globalColStart + localCol + innerCol * ${t[0]};
|
|
768
|
+
mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
`:`
|
|
772
|
+
let tileRow = i32(localId.y) * rowPerThread;
|
|
773
|
+
let tileCol = i32(localId.x) * colPerThread;
|
|
774
|
+
|
|
775
|
+
let globalRow = i32(globalId.y) * rowPerThread;
|
|
776
|
+
let globalCol = i32(globalId.x) * colPerThread;
|
|
777
|
+
let globalRowStart = i32(workgroupId.y) * ${p};
|
|
778
|
+
|
|
779
|
+
let tileRowA = i32(localId.y) * ${v};
|
|
780
|
+
let tileColA = i32(localId.x) * ${S};
|
|
781
|
+
let tileRowB = i32(localId.y) * ${x};
|
|
782
|
+
// Loop over shared dimension.
|
|
783
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
784
|
+
// Load one tile of A into local memory.
|
|
785
|
+
for (var innerRow = 0; innerRow < ${v}; innerRow = innerRow + 1) {
|
|
786
|
+
for (var innerCol = 0; innerCol < ${S}; innerCol = innerCol + 1) {
|
|
787
|
+
let inputRow = tileRowA + innerRow;
|
|
788
|
+
let inputCol = tileColA + innerCol;
|
|
789
|
+
${ua(o,i)}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
// Load one tile of B into local memory.
|
|
794
|
+
for (var innerRow = 0; innerRow < ${x}; innerRow = innerRow + 1) {
|
|
795
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
796
|
+
let inputRow = tileRowB + innerRow;
|
|
797
|
+
let inputCol = tileCol + innerCol;
|
|
798
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch,
|
|
799
|
+
kStart + inputRow,
|
|
800
|
+
globalCol + innerCol${i?", batchIndices":""});
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
kStart = kStart + tileInner;
|
|
804
|
+
workgroupBarrier();
|
|
805
|
+
|
|
806
|
+
// Compute acc values for a single thread.
|
|
807
|
+
var BCached : array<${n}, colPerThread>;
|
|
808
|
+
for (var k = 0; k < tileInner; k = k + 1) {
|
|
809
|
+
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
|
|
810
|
+
BCached[inner] = mm_Bsub[k][tileCol + inner];
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
814
|
+
${ku(o)}
|
|
815
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
816
|
+
acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
workgroupBarrier();
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
825
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
826
|
+
mm_write(batch, globalRow + innerRow, globalCol + innerCol,
|
|
827
|
+
acc[innerRow][innerCol]);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
`;return`
|
|
831
|
+
var<workgroup> mm_Asub : array<array<${n}, ${g}>, ${w}>;
|
|
832
|
+
var<workgroup> mm_Bsub : array<array<${n}, ${m}>, ${l}>;
|
|
833
|
+
const rowPerThread = ${e[1]};
|
|
834
|
+
const colPerThread = ${e[0]};
|
|
835
|
+
const tileInner = ${l};
|
|
836
|
+
|
|
837
|
+
@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})
|
|
838
|
+
fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
839
|
+
@builtin(global_invocation_id) globalId : vec3<u32>,
|
|
840
|
+
@builtin(workgroup_id) workgroupId : vec3<u32>) {
|
|
841
|
+
let batch = ${u?"0":"i32(globalId.z)"};
|
|
842
|
+
${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""}
|
|
843
|
+
let num_tiles = ${u?`${Math.ceil(c/l)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
|
|
844
|
+
var kStart = ${u?`i32(globalId.z) * ${c}`:"0"};
|
|
845
|
+
|
|
846
|
+
var acc : array<array<${n}, colPerThread>, rowPerThread>;
|
|
847
|
+
${M}
|
|
848
|
+
}
|
|
849
|
+
`},Ru=(e,t,n,i,o=!1)=>{let[l,u,c,h]=i,p=G(i[0].type.tensor);return`
|
|
850
|
+
fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${l.type.indices}) -> ${Pt(e,p)} {
|
|
851
|
+
var value = ${Pt(e,p)}(0.0);
|
|
852
|
+
let col = colIn * ${e};
|
|
853
|
+
if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)
|
|
854
|
+
{
|
|
855
|
+
var aIndices: ${u.type.indices};
|
|
856
|
+
${Wn("aIndices",u,u.rank-2,l.rank,"batchIndices")}
|
|
857
|
+
${u.indicesSet("aIndices",u.rank-2,"u32(row)")}
|
|
858
|
+
${u.indicesSet("aIndices",u.rank-1,"u32(colIn)")}
|
|
859
|
+
value = ${u.getByIndices("aIndices")};
|
|
860
|
+
}
|
|
861
|
+
return value;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${l.type.indices}) -> ${Pt(e,p)} {
|
|
865
|
+
var value = ${Pt(e,p)}(0.0);
|
|
866
|
+
let col = colIn * ${e};
|
|
867
|
+
if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)
|
|
868
|
+
{
|
|
869
|
+
var bIndices: ${c.type.indices};
|
|
870
|
+
${Wn("bIndices",c,c.rank-2,l.rank,"batchIndices")}
|
|
871
|
+
${c.indicesSet("bIndices",c.rank-2,"u32(row)")}
|
|
872
|
+
${c.indicesSet("bIndices",c.rank-1,"u32(colIn)")}
|
|
873
|
+
value = ${c.getByIndices("bIndices")};
|
|
874
|
+
}
|
|
875
|
+
return value;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Pt(e,p)}) {
|
|
879
|
+
let col = colIn * ${e};
|
|
880
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {
|
|
881
|
+
var value = valueIn;
|
|
882
|
+
let coords = vec3<i32>(batch, row, colIn);
|
|
883
|
+
${t?`value = value + ${o?"bias[colIn]":`${Pt(e,p)}(bias[row])`};`:""}
|
|
884
|
+
${n}
|
|
885
|
+
${h.setByIndices("vec3<u32>(coords)","value")}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
`},Si=(e,t,n,i,o=!1,l)=>{let u=e[0].dims,c=e[1].dims,h=u.slice(0,-2),p=c.slice(0,-2),m=i?i.slice(0,-2):n.slice(0,-2),g=j.size(m),w=u[u.length-2],v=u[u.length-1],S=c[c.length-1],x=v%4===0&&S%4===0,M=w<=8?[4,1,1]:[4,4,1],k=[8,8,1],$=[Math.ceil(S/k[0]/M[0]),Math.ceil(w/k[1]/M[1]),Math.ceil(g/k[2]/M[2])],P=x?4:1,I=[...h,w,v/P],B=I.length,q=[...p,v,S/P],W=q.length,ee=[g,w,S/P],ue=[{type:6,data:w},{type:6,data:S},{type:6,data:v}];As(t,ue),ue.push(...L(m,I,q));let _e=["rank","rank"],Fe=e.length>2;Fe&&(ue.push(...L(e[2].dims)),_e.push("rank")),ue.push(...L(ee));let Re=Me=>{let Xe=m.length,ge=Be("batchDims",e[0].dataType,Xe,1),$e=G(e[0].dataType),Le=F("a",e[0].dataType,B,P),Ve=F("b",e[1].dataType,W,P),De=le("result",e[0].dataType,ee.length,P),He=[Le,Ve];if(Fe){let Dt=o?P:1;He.push(F("bias",e[2].dataType,e[2].dims.length,Dt))}let ae=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Is(t,ae);let Oe=G(De.type.tensor),Ae=Rs(t,De.type.value,Oe),Ee=Ru(P,Fe,Ae,[ge,Le,Ve,De],o);return`
|
|
889
|
+
${Me.registerUniforms(ae).registerInternalVariables(ge).declareVariables(...He,De)}
|
|
890
|
+
${Ee}
|
|
891
|
+
${x?la(M,k,$e,ge):da(M,k,$e,ge)}
|
|
892
|
+
`};return{name:"MatMul",shaderCache:{hint:`${M};${t.activation};${x};${o}`,inputDependencies:_e},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:$[0],y:$[1],z:$[2]},programUniforms:ue}),getShaderSource:Re}}}),Au,Iu,bm=b(()=>{Ie(),tr(),ye(),Ms(),ia(),_m(),ca(),Au=(e,t,n,i,o=!1,l,u=4,c=4,h=4,p="f32")=>{let m=ue=>{switch(ue){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${ue} is not supported.`)}},g=ue=>{switch(ue){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${ue} is not supported.`)}},w=e?`
|
|
893
|
+
let coord = vec4<i32>(batch, xRow, xCol, xCh);
|
|
894
|
+
`:`
|
|
895
|
+
let coord = vec4<i32>(batch, xCh, xRow, xCol);
|
|
896
|
+
`,v=e?`
|
|
897
|
+
let coords = vec4<i32>(
|
|
898
|
+
batch,
|
|
899
|
+
row / outWidth,
|
|
900
|
+
row % outWidth,
|
|
901
|
+
col);
|
|
902
|
+
`:`
|
|
903
|
+
let coords = vec4<i32>(
|
|
904
|
+
batch,
|
|
905
|
+
row,
|
|
906
|
+
col / outWidth,
|
|
907
|
+
col % outWidth);
|
|
908
|
+
`,S=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",x=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",M=e?"row":"col",k=e?"col":"row",$=`
|
|
909
|
+
let inChannels = i32(uniforms.w_shape[2]);
|
|
910
|
+
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
|
|
911
|
+
let outRow = ${M} / outWidth;
|
|
912
|
+
let outCol = ${M} % outWidth;
|
|
913
|
+
|
|
914
|
+
let WRow = ${k} / (i32(uniforms.w_shape[1]) * inChannels);
|
|
915
|
+
let WCol = ${k} / inChannels % i32(uniforms.w_shape[1]);
|
|
916
|
+
let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];
|
|
917
|
+
let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];
|
|
918
|
+
let xCh = ${k} % inChannels;
|
|
919
|
+
var resData = ${Pt(u,p)}(0.0);
|
|
920
|
+
// The bounds checking is always needed since we use it to pad zero for
|
|
921
|
+
// the 'same' padding type.
|
|
922
|
+
if (xRow >= 0 && xRow < ${S} && xCol >= 0 && xCol < ${x}) {
|
|
923
|
+
${w}
|
|
924
|
+
let xIndex = getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape));
|
|
925
|
+
${m(u)}
|
|
926
|
+
}
|
|
927
|
+
return resData;`,P=e?t&&i?`
|
|
928
|
+
let col = colIn * ${u};
|
|
929
|
+
${$}`:`
|
|
930
|
+
let col = colIn * ${u};
|
|
931
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {
|
|
932
|
+
${$}
|
|
933
|
+
}
|
|
934
|
+
return ${Pt(u,p)}(0.0);`:i&&n?`
|
|
935
|
+
let col = colIn * ${u};
|
|
936
|
+
${$}`:`
|
|
937
|
+
let col = colIn * ${u};
|
|
938
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
|
|
939
|
+
${$}
|
|
940
|
+
}
|
|
941
|
+
return ${Pt(u,p)}(0.0);`,I=e?i&&n?g(c):`
|
|
942
|
+
let col = colIn * ${c};
|
|
943
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
|
|
944
|
+
${g(c)}
|
|
945
|
+
}
|
|
946
|
+
return ${Pt(c,p)}(0.0);`:`
|
|
947
|
+
let col = colIn * ${c};
|
|
948
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {
|
|
949
|
+
${g(c)}
|
|
950
|
+
}
|
|
951
|
+
return ${Pt(c,p)}(0.0);`,B=Pt(h,p),q=Pt(e?u:c,p),W=Pt(e?c:u,p),ee=Rs(l,B,p);return`
|
|
952
|
+
fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${q} {
|
|
953
|
+
${e?P:I}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${W} {
|
|
957
|
+
${e?I:P}
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${B}) {
|
|
961
|
+
let col = colIn * ${h};
|
|
962
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)
|
|
963
|
+
{
|
|
964
|
+
var value = valueIn;
|
|
965
|
+
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
|
|
966
|
+
${v}
|
|
967
|
+
${Eu(o)}
|
|
968
|
+
${ee}
|
|
969
|
+
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
|
|
970
|
+
}
|
|
971
|
+
}`},Iu=(e,t,n,i,o,l,u,c,h)=>{let p=t.format==="NHWC",m=p?e[0].dims[3]:e[0].dims[1],g=n[0],w=p?n[2]:n[3],v=p?n[1]:n[2],S=p?n[3]:n[1],x=p&&(m%4===0||m%3===0)&&S%4===0,M=p?S:w*v,k=p?w*v:S,$=[8,8,1],P=i<=8?[4,1,1]:[4,4,1],I=[Math.ceil(M/$[0]/P[0]),Math.ceil(k/$[1]/P[1]),Math.ceil(g/$[2]/P[2])];We("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${I}`);let B=x?p&&m%4!==0?3:4:1,q=$[1]*P[1],W=$[0]*P[0],ee=Math.max($[0]*B,$[1]),ue=i%q===0,_e=o%W===0,Fe=l%ee===0,Re=x?[B,4,4]:[1,1,1],Me=[{type:6,data:i},{type:6,data:o},{type:6,data:l},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];As(t,Me),Me.push(...L(e[0].dims,e[1].dims));let Xe=["rank","rank"];u&&(Me.push(...L(e[2].dims)),Xe.push("rank")),Me.push(...L(n));let ge=$e=>{let Le=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];Is(t,Le);let Ve=x?4:1,De=G(e[0].dataType),He=`
|
|
972
|
+
fn setOutputAtIndex(flatIndex : i32, value : ${x?`vec4<${De}>`:De}) {
|
|
973
|
+
result[flatIndex] = ${x?`vec4<${De}>`:De}(value);
|
|
974
|
+
}
|
|
975
|
+
fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${x?`vec4<${De}>`:De}) {
|
|
976
|
+
let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));
|
|
977
|
+
setOutputAtIndex(flatIndex ${x?"/ 4":""}, value);
|
|
978
|
+
}`,ae=F("x",e[0].dataType,e[0].dims.length,B===3?1:B),Oe=F("w",e[1].dataType,e[1].dims.length,Ve),Ae=[ae,Oe],Ee=le("result",e[0].dataType,n.length,Ve);if(u){let Dt=F("bias",e[2].dataType,e[2].dims.length,Ve);Ae.push(Dt),He+=`
|
|
979
|
+
fn getBiasByOutputCoords(coords : vec4<i32>) -> ${x?`vec4<${De}>`:De} {
|
|
980
|
+
return bias[coords.${p?"w":"y"}${x?"/ 4":""}];
|
|
981
|
+
}`}return`
|
|
982
|
+
${$u("uniforms.result_strides")}
|
|
983
|
+
//struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>,
|
|
984
|
+
// outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>,
|
|
985
|
+
// dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };
|
|
986
|
+
${$e.registerUniforms(Le).declareVariables(...Ae,Ee)}
|
|
987
|
+
${He}
|
|
988
|
+
${Au(p,ue,_e,Fe,u,t,Re[0],Re[1],Re[2],De)}
|
|
989
|
+
${x?la(P,$,De,void 0,!p,ee):da(P,$,De,void 0,!p,ee,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${B};${x};${ue};${_e};${Fe};${q};${W};${ee}`,inputDependencies:Xe},getRunData:()=>({outputs:[{dims:h?h(n):n,dataType:e[0].dataType}],dispatchGroup:{x:I[0],y:I[1],z:I[2]},programUniforms:Me}),getShaderSource:ge}}}),Mu,ha,Hn,Pu,pa,Ou,Du,zu,Sm=b(()=>{Ie(),tr(),ke(),ye(),Ms(),ia(),Mu=e=>{let t=1;for(let n=0;n<e.length;n++)t*=e[n];return t},ha=e=>typeof e=="number"?[e,e,e]:e,Hn=(e,t)=>t<=1?e:e+(e-1)*(t-1),Pu=(e,t,n,i=1)=>{let o=Hn(t,i);return Math.floor((e[0]*(n-1)-n+o)/2)},pa=(e,t,n,i,o)=>{o==null&&(o=Pu(e,t[0],i[0]));let l=[0,0,0,n];for(let u=0;u<3;u++)e[u]+2*o>=t[u]&&(l[u]=Math.trunc((e[u]-t[u]+2*o)/i[u]+1));return l},Ou=(e,t,n,i,o,l,u,c,h,p)=>{let m,g,w,v;if(e==="VALID"&&(e=0),typeof e=="number"){m={top:e,bottom:e,left:e,right:e,front:e,back:e};let S=pa([t,n,i,1],[c,h,p],1,[o,l,u],e);g=S[0],w=S[1],v=S[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 S=pa([t,n,i,1],[c,h,p],1,[o,l,u],e[0]);g=S[0],w=S[1],v=S[2]}else if(e==="SAME_UPPER"){g=Math.ceil(t/o),w=Math.ceil(n/l),v=Math.ceil(i/u);let S=(g-1)*o+c-t,x=(w-1)*l+h-n,M=(v-1)*u+p-i,k=Math.floor(S/2),$=S-k,P=Math.floor(x/2),I=x-P,B=Math.floor(M/2),q=M-B;m={top:P,bottom:I,left:B,right:q,front:k,back:$}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:m,outDepth:g,outHeight:w,outWidth:v}},Du=(e,t,n,i,o,l=!1,u="channelsLast")=>{let c,h,p,m,g;if(u==="channelsLast")[c,h,p,m,g]=e;else if(u==="channelsFirst")[c,g,h,p,m]=e;else throw new Error(`Unknown dataFormat ${u}`);let[w,,v,S,x]=t,[M,k,$]=ha(n),[P,I,B]=ha(i),q=Hn(v,P),W=Hn(S,I),ee=Hn(x,B),{padInfo:ue,outDepth:_e,outHeight:Fe,outWidth:Re}=Ou(o,h,p,m,M,k,$,q,W,ee),Me=l?w*g:w,Xe=[0,0,0,0,0];return u==="channelsFirst"?Xe=[c,Me,_e,Fe,Re]:u==="channelsLast"&&(Xe=[c,_e,Fe,Re,Me]),{batchSize:c,dataFormat:u,inDepth:h,inHeight:p,inWidth:m,inChannels:g,outDepth:_e,outHeight:Fe,outWidth:Re,outChannels:Me,padInfo:ue,strideDepth:M,strideHeight:k,strideWidth:$,filterDepth:v,filterHeight:S,filterWidth:x,effectiveFilterDepth:q,effectiveFilterHeight:W,effectiveFilterWidth:ee,dilationDepth:P,dilationHeight:I,dilationWidth:B,inShape:e,outShape:Xe,filterShape:t}},zu=(e,t,n,i,o,l)=>{let u=l==="channelsLast";u?e[0].dims[3]:e[0].dims[1];let c=[64,1,1],h={x:n.map((M,k)=>k)},p=[Math.ceil(Mu(h.x.map(M=>n[M]))/c[0]),1,1];We("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${p}`);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}];As(t,w),w.push(...L(e[0].dims,e[1].dims));let v=["rank","rank"],S=e.length===3;S&&(w.push(...L(e[2].dims)),v.push("rank")),w.push(...L(n));let x=M=>{let k=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:i.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Is(t,k);let $=1,P=G(e[0].dataType),I=F("x",e[0].dataType,e[0].dims.length,m),B=F("W",e[1].dataType,e[1].dims.length,$),q=[I,B],W=le("result",e[0].dataType,n.length,$),ee="";if(S){let Fe=F("bias",e[2].dataType,e[2].dims.length,$);q.push(Fe),ee+=`
|
|
990
|
+
fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${P} {
|
|
991
|
+
return bias[${u?Q("coords",4,5):Q("coords",1,5)}];
|
|
992
|
+
}`}let ue=Pt(m,P),_e=Rs(t,ue,P);return`
|
|
993
|
+
${ee}
|
|
994
|
+
fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
|
|
995
|
+
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
|
|
996
|
+
return ${I.getByIndices("aIndices")};
|
|
997
|
+
}
|
|
998
|
+
fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
|
|
999
|
+
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
|
|
1000
|
+
return ${B.getByIndices("aIndices")};
|
|
1001
|
+
}
|
|
1002
|
+
${M.registerUniforms(k).declareVariables(...q,W)}
|
|
1003
|
+
${M.mainStart()}
|
|
1004
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1005
|
+
let coords = ${W.offsetToIndices("global_idx")};
|
|
1006
|
+
let batch = ${Q("coords",0,I.rank)};
|
|
1007
|
+
let d2 = ${u?Q("coords",I.rank-1,I.rank):Q("coords",1,I.rank)};
|
|
1008
|
+
let xFRCCorner = vec3<u32>(${u?Q("coords",1,I.rank):Q("coords",2,I.rank)},
|
|
1009
|
+
${u?Q("coords",2,I.rank):Q("coords",3,I.rank)},
|
|
1010
|
+
${u?Q("coords",3,I.rank):Q("coords",4,I.rank)}) * uniforms.strides - uniforms.pads;
|
|
1011
|
+
let xFCorner = xFRCCorner.x;
|
|
1012
|
+
let xRCorner = xFRCCorner.y;
|
|
1013
|
+
let xCCorner = xFRCCorner.z;
|
|
1014
|
+
let xShapeY = ${u?Q("uniforms.x_shape",1,I.rank):Q("uniforms.x_shape",2,I.rank)};
|
|
1015
|
+
let xShapeZ = ${u?Q("uniforms.x_shape",2,I.rank):Q("uniforms.x_shape",3,I.rank)};
|
|
1016
|
+
let xShapeW = ${u?Q("uniforms.x_shape",3,I.rank):Q("uniforms.x_shape",4,I.rank)};
|
|
1017
|
+
let xShapeU = ${u?Q("uniforms.x_shape",4,I.rank):Q("uniforms.x_shape",1,I.rank)};
|
|
1018
|
+
let inputDepthNearestVec4 = (xShapeU / 4) * 4;
|
|
1019
|
+
let inputDepthVec4Remainder = xShapeU % 4;
|
|
1020
|
+
|
|
1021
|
+
var value = 0.0;
|
|
1022
|
+
for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {
|
|
1023
|
+
let xF = xFCorner + wF * uniforms.dilations[0];
|
|
1024
|
+
if (xF < 0 || xF >= xShapeY) {
|
|
1025
|
+
continue;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {
|
|
1029
|
+
let xR = xRCorner + wR * uniforms.dilations[1];
|
|
1030
|
+
if (xR < 0 || xR >= xShapeZ) {
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {
|
|
1035
|
+
let xC = xCCorner + wC * uniforms.dilations[2];
|
|
1036
|
+
if (xC < 0 || xC >= xShapeW) {
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {
|
|
1041
|
+
${u?`let xValues = vec4<f32>(
|
|
1042
|
+
getX(batch, xF, xR, xC, d1),
|
|
1043
|
+
getX(batch, xF, xR, xC, d1 + 1),
|
|
1044
|
+
getX(batch, xF, xR, xC, d1 + 2),
|
|
1045
|
+
getX(batch, xF, xR, xC, d1 + 3));
|
|
1046
|
+
`:`let xValues = vec4<f32>(
|
|
1047
|
+
getX(batch, d1, xF, xR, xC),
|
|
1048
|
+
getX(batch, d1 + 1, xF, xR, xC),
|
|
1049
|
+
getX(batch, d1 + 2, xF, xR, xC),
|
|
1050
|
+
getX(batch, d1 + 3, xF, xR, xC));
|
|
1051
|
+
`}
|
|
1052
|
+
let wValues = vec4<f32>(
|
|
1053
|
+
getW(d2, d1, wF, wR, wC),
|
|
1054
|
+
getW(d2, d1 + 1, wF, wR, wC),
|
|
1055
|
+
getW(d2, d1 + 2, wF, wR, wC),
|
|
1056
|
+
getW(d2, d1 + 3, wF, wR, wC));
|
|
1057
|
+
value += dot(xValues, wValues);
|
|
1058
|
+
}
|
|
1059
|
+
if (inputDepthVec4Remainder == 1) {
|
|
1060
|
+
${u?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4)
|
|
1061
|
+
* getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC)
|
|
1062
|
+
* getW(d2, inputDepthNearestVec4, wF, wR, wC);`}
|
|
1063
|
+
} else if (inputDepthVec4Remainder == 2) {
|
|
1064
|
+
${u?`let xValues = vec2<f32>(
|
|
1065
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4),
|
|
1066
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));
|
|
1067
|
+
`:`let xValues = vec2<f32>(
|
|
1068
|
+
getX(batch, inputDepthNearestVec4, xF, xR, xC),
|
|
1069
|
+
getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));
|
|
1070
|
+
`}
|
|
1071
|
+
let wValues = vec2<f32>(
|
|
1072
|
+
getW(d2, inputDepthNearestVec4, wF, wR, wC),
|
|
1073
|
+
getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));
|
|
1074
|
+
value += dot(xValues, wValues);
|
|
1075
|
+
} else if (inputDepthVec4Remainder == 3) {
|
|
1076
|
+
${u?`let xValues = vec3<f32>(
|
|
1077
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4),
|
|
1078
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),
|
|
1079
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));
|
|
1080
|
+
`:`let xValues = vec3<f32>(
|
|
1081
|
+
getX(batch, inputDepthNearestVec4, xF, xR, xC),
|
|
1082
|
+
getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),
|
|
1083
|
+
getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));
|
|
1084
|
+
`}
|
|
1085
|
+
let wValues = vec3<f32>(
|
|
1086
|
+
getW(d2, inputDepthNearestVec4, wF, wR, wC),
|
|
1087
|
+
getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),
|
|
1088
|
+
getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));
|
|
1089
|
+
value += dot(xValues, wValues);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
${S?"value = value + getBiasByOutputCoords(coords)":""};
|
|
1095
|
+
${_e}
|
|
1096
|
+
result[global_idx] = f32(value);
|
|
1097
|
+
}`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${u};${m};${S}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:p[0],y:p[1],z:p[2]},programUniforms:w}),getShaderSource:x}}}),Lu,Bu,Tm=b(()=>{Ie(),ke(),ye(),Ms(),Lu=(e,t,n,i)=>{let o=e.length>2,l=o?"value += b[output_channel];":"",u=e[0].dims,c=e[1].dims,h=t.format==="NHWC",p=h?n[3]:n[1],m=p/t.group,g=h&&m>=4?V(p):1,w=j.size(n)/g,v=[{type:12,data:w},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:m}];As(t,v),v.push(...L(u,[c[0],c[1],c[2],c[3]/g]));let S=o?["rank","rank","rank"]:["rank","rank"];v.push(...L([n[0],n[1],n[2],n[3]/g]));let x=M=>{let k=le("output",e[0].dataType,n.length,g),$=G(k.type.tensor),P=Rs(t,k.type.value,$),I=F("x",e[0].dataType,u.length),B=F("w",e[1].dataType,c.length,g),q=[I,B];o&&q.push(F("b",e[2].dataType,e[2].dims,g));let 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"}];Is(t,W);let ee=h?`
|
|
1098
|
+
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {
|
|
1099
|
+
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
|
|
1100
|
+
|
|
1101
|
+
if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {
|
|
1102
|
+
continue;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {
|
|
1106
|
+
let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
|
|
1107
|
+
if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {
|
|
1108
|
+
continue;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {
|
|
1112
|
+
let input_channel = in_channel_offset + wInChannel;
|
|
1113
|
+
let xVal = ${I.get("batch","xHeight","xWidth","input_channel")};
|
|
1114
|
+
let wVal = ${B.get("wHeight","wWidth","wInChannel","output_channel")};
|
|
1115
|
+
value += xVal * wVal;
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
`:`
|
|
1120
|
+
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {
|
|
1121
|
+
let input_channel = in_channel_offset + wInChannel;
|
|
1122
|
+
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {
|
|
1123
|
+
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
|
|
1124
|
+
|
|
1125
|
+
if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {
|
|
1126
|
+
continue;
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {
|
|
1130
|
+
let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
|
|
1131
|
+
if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {
|
|
1132
|
+
continue;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
let xVal = ${I.get("batch","input_channel","xHeight","xWidth")};
|
|
1136
|
+
let wVal = ${B.get("output_channel","wInChannel","wHeight","wWidth")};
|
|
1137
|
+
value += xVal * wVal;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
`;return`
|
|
1142
|
+
${M.registerUniforms(W).declareVariables(...q,k)}
|
|
1143
|
+
|
|
1144
|
+
${M.mainStart()}
|
|
1145
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1146
|
+
|
|
1147
|
+
let outputIndices = ${k.offsetToIndices("global_idx")};
|
|
1148
|
+
let batch: u32 = outputIndices[0];
|
|
1149
|
+
let output_channel: u32 = outputIndices[${h?3:1}];
|
|
1150
|
+
let xRCCorner: vec2<u32> = vec2<u32>(outputIndices[${h?1:2}], outputIndices[${h?2:3}]) * uniforms.strides - uniforms.pads;
|
|
1151
|
+
let group_id: u32 = output_channel * ${g} / uniforms.output_channels_per_group;
|
|
1152
|
+
var in_channel_offset = group_id * uniforms.w_shape[${h?2:1}];
|
|
1153
|
+
|
|
1154
|
+
var value: ${k.type.value} = ${k.type.value}(0);
|
|
1155
|
+
${ee}
|
|
1156
|
+
${l}
|
|
1157
|
+
${P}
|
|
1158
|
+
${k.setByOffset("global_idx","value")}
|
|
1159
|
+
}`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${g}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:v}),getShaderSource:x}},Bu=(e,t,n,i)=>{let o=e.length>2,l=V(n[3]),u=V(n[2]),c=j.size(n)/l/u,h=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/l],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/l],m=[n[0],n[1],n[2],n[3]/l],g=[{type:12,data:c},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];As(t,g),g.push(...L(h,p,m));let w=(u-1)*t.strides[1]+p[1],v=S=>{let x=le("output",e[0].dataType,m.length,l),M=G(x.type.tensor),k=Rs(t,x.type.value,M),$=F("x",e[0].dataType,h.length,l),P=F("w",e[1].dataType,p.length,l),I=[$,P];o&&I.push(F("b",e[2].dataType,e[2].dims,l));let B=o?"value += b[output_channel];":"",q=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Is(t,q),`
|
|
1160
|
+
${S.registerUniforms(q).declareVariables(...I,x)}
|
|
1161
|
+
${S.mainStart()}
|
|
1162
|
+
${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1163
|
+
let width0 = uniforms.output_shape[3];
|
|
1164
|
+
let output_channel = global_idx % width0;
|
|
1165
|
+
var index1 = global_idx / width0;
|
|
1166
|
+
let width1 = uniforms.output_shape[2] / ${u}u;
|
|
1167
|
+
let col = (index1 % width1) * ${u}u;
|
|
1168
|
+
index1 = index1 / width1;
|
|
1169
|
+
let row = index1 % uniforms.output_shape[1];
|
|
1170
|
+
let batch = index1 / uniforms.output_shape[1];
|
|
1171
|
+
|
|
1172
|
+
let x_corner = vec2<i32>(i32(row), i32(col)) * uniforms.strides - uniforms.pads;
|
|
1173
|
+
|
|
1174
|
+
var x_vals: array<${$.type.value}, ${w}>;
|
|
1175
|
+
var values: array<${x.type.value}, ${u}>;
|
|
1176
|
+
let input_channel = output_channel;
|
|
1177
|
+
// Use constant instead of uniform can give better performance for w's height/width.
|
|
1178
|
+
for (var w_height: u32 = 0u; w_height < ${p[0]}; w_height++) {
|
|
1179
|
+
let x_height = x_corner.x + i32(w_height);
|
|
1180
|
+
if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {
|
|
1181
|
+
for (var i = 0; i < ${w}; i++) {
|
|
1182
|
+
let x_width = x_corner.y + i;
|
|
1183
|
+
if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {
|
|
1184
|
+
x_vals[i] = ${$.get("batch","u32(x_height)","u32(x_width)","input_channel")};
|
|
1185
|
+
} else {
|
|
1186
|
+
x_vals[i] = ${$.type.value}(0);
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) {
|
|
1190
|
+
let w_val = ${P.get("w_height","w_width","0","output_channel")};
|
|
1191
|
+
for (var i = 0u; i < ${u}u; i++) {
|
|
1192
|
+
values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
for (var i = 0u; i < ${u}u; i++) {
|
|
1199
|
+
var value = values[i];
|
|
1200
|
+
${B}
|
|
1201
|
+
${k}
|
|
1202
|
+
${x.set("batch","row","col + i","output_channel","value")};
|
|
1203
|
+
}
|
|
1204
|
+
}`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${l};${u};${w};${p[0]};${p[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:v}}}),Nu,Ti,Uu,Ei,fa,ma,Fu,Vu,ga,Em=b(()=>{ke(),bm(),Sm(),ca(),Tm(),Ms(),oa(),Ue(),Nu=(e,t,n,i,o,l)=>{let u=e[0],c=e.slice(l?1:2,l?3:4),h=c.length,p=t[0],m=t.slice(2).map((w,v)=>w+(w-1)*(n[v]-1)),g=c.map((w,v)=>w+i[v]+i[v+h]).map((w,v)=>Math.floor((w-m[v]+o[v])/o[v]));return g.splice(0,0,u),g.splice(l?3:1,0,p),g},Ti=[2,3,1,0],Uu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let n=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[1]*t.group;if(n!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},Ei=(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();Jr.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,n,i,e.format==="NHWC",e.autoPad);let o=Object.assign({},e);return Object.assign(o,{kernelShape:n,pads:i}),o},fa=e=>{let t=na(e),n=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,l=e.group,u=e.kernel_shape,c=e.pads,h=e.strides,p=e.w_is_const();return{autoPad:i,format:n,dilations:o,group:l,kernelShape:u,pads:c,strides:h,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},ma=(e,t,n,i)=>{let o=n.format==="NHWC",l=Nu(t[0].dims,t[1].dims,n.dilations,n.pads,n.strides,o);if(n.group!==1){let q=[t[0]];if(o){let W=e.kernelCustomData.wT??e.compute(ht(t[1],Ti),{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(Bu(q,n,l,i),{inputs:q}):e.compute(Lu(q,n,l,i),{inputs:q});return}let u=t.length===3,c=t[0].dims[o?1:2],h=t[0].dims[o?2:3],p=t[0].dims[o?3:1],m=t[1].dims[2],g=t[1].dims[3],w=l[o?1:2],v=l[o?2:3],S=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,ee,ue,_e=[];if(o){let Me=e.kernelCustomData.wT??e.compute(ht(t[1],Ti),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Me),x){let Xe=c*h*p;W=t[0].reshape([1,q,Xe]),ee=Me.reshape([1,Xe,S]),ue=[1,q,S]}else W=t[0].reshape([q,c*h,p]),ee=Me.reshape([1,p,S]),ue=[q,w*v,S];_e.push(W),_e.push(ee)}else W=t[0].reshape([q,p,c*h]),ee=t[1].reshape([1,S,p]),ue=[q,S,w*v],_e.push(ee),_e.push(W);u&&_e.push(t[2]);let Fe=ue[2],Re=_e[0].dims[_e[0].dims.length-1];Fe<8&&Re<8?e.compute(aa(_e,n,l,ue,o,i),{inputs:_e}):e.compute(Si(_e,n,l,ue,o,i),{inputs:_e});return}let M=!0,k=e.kernelCustomData.wT??e.compute(ht(t[1],Ti),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=k);let $=[t[0],k];u&&$.push(t[2]);let P=o?w*v:S,I=o?S:w*v,B=m*g*p;e.compute(Iu($,n,l,P,I,B,u,M,i),{inputs:$})},Fu=(e,t)=>{let n=t.format==="NHWC",i=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&i.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],l=[1].concat(t.strides),u=[1].concat(t.dilations),c=[1].concat(t.kernelShape),h=Ei({...t,pads:o,strides:l,dilations:u,kernelShape:c},i);ma(e,i,h,p=>n?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Vu=(e,t,n)=>{let i=n.format==="NHWC"?"channelsLast":"channelsFirst",o=Ei(n,t),l=n.autoPad==="NOTSET"?n.pads:n.autoPad,u=Du(t[0].dims,t[1].dims,n.strides,n.dilations,l,!1,i);e.compute(zu(t,o,u.outShape,[u.filterDepth,u.filterHeight,u.filterWidth],[u.padInfo.front,u.padInfo.top,u.padInfo.left],i))},ga=(e,t)=>{if(Uu(e.inputs,t),e.inputs[0].dims.length===3)Fu(e,t);else if(e.inputs[0].dims.length===5)Vu(e,e.inputs,t);else{let n=Ei(t,e.inputs);ma(e,e.inputs,n)}}}),Gu,$m=b(()=>{Ie(),tr(),ke(),ye(),Gu=(e,t,n)=>{let i=e.length>2,o=t.outputShape,l=t.format==="NHWC",u=t.group,c=e[1].dims,h=c[2]/u,p=c[3],m=l?V(h):1,g=l&&p===1&&h>=4,w=g?Math.floor(h/4)*4:Math.floor(h/m)*m,v=h-w,S=l?V(p):1,x=l?p===1?m:S:1,M=j.size(o)/S,k=[Math.ceil(M/64),1,1];We("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${k}`);let $=["rank","rank"],P=[t.strides[0],t.strides[1]],I=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],B=[t.dilations[0],t.dilations[1]],q=[I[0]+(t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)),I[1]+(t.dilations[1]<=1?0:(t.kernelShape[l?2:3]-1)*(t.dilations[1]-1))],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)],ee=[{type:12,data:M},{type:12,data:P},{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:p},...L(e[0].dims,e[1].dims)];i&&(ee.push(...L(e[2].dims)),$.push("rank")),ee.push(...L(o));let ue=_e=>{let Fe=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:P.length},{name:"filter_dims",type:"u32",length:I.length},{name:"dilations",type:"u32",length:I.length},{name:"effective_filter_dims",type:"u32",length:q.length},{name:"pads",type:"i32",length: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,Xe=l?2:3,ge=l?3:1,$e=F("W",e[1].dataType,e[1].dims.length,x),Le=F("Dy",e[0].dataType,e[0].dims.length,m),Ve=[Le,$e];i&&Ve.push(F("bias",e[2].dataType,[o[ge]].length,S));let De=le("result",e[0].dataType,o.length,S),He=()=>{let Ae="";if(g)m===4?Ae+=`
|
|
1205
|
+
let xValue = ${Le.getByOffset("x_offset")};
|
|
1206
|
+
let wValue = ${$e.getByOffset("w_offset")};
|
|
1207
|
+
dotProd = dotProd + dot(xValue, wValue);
|
|
1208
|
+
x_offset += 1u;
|
|
1209
|
+
w_offset += 1u;`:m===2?Ae+=`
|
|
1210
|
+
dotProd = dotProd + dot(vec4<${Re}>(${Le.getByOffset("x_offset")}, ${Le.getByOffset("x_offset + 1u")}), vec4<${Re}>(${$e.getByOffset("w_offset")}, ${$e.getByOffset("w_offset + 1u")}));
|
|
1211
|
+
x_offset += 2u;
|
|
1212
|
+
w_offset += 2u;`:m===1&&(Ae+=`
|
|
1213
|
+
dotProd = dotProd + dot(vec4<${Re}>(${Le.getByOffset("x_offset")}, ${Le.getByOffset("x_offset + 1u")}, ${Le.getByOffset("x_offset + 2u")}, ${Le.getByOffset("x_offset + 3u")}), vec4<${Re}>(${$e.getByOffset("w_offset")}, ${$e.getByOffset("w_offset + 1u")}, ${$e.getByOffset("w_offset + 2u")}, ${$e.getByOffset("w_offset + 3u")}));
|
|
1214
|
+
x_offset += 4u;
|
|
1215
|
+
w_offset += 4u;`);else if(Ae+=`
|
|
1216
|
+
let xValue = ${l?Le.getByOffset(`${Le.indicesToOffset(`${Le.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${m}`):Le.get("batch","inputChannel","idyR","idyC")};
|
|
1217
|
+
`,m===1)Ae+=`
|
|
1218
|
+
let w_offset = ${$e.indicesToOffset(`${$e.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};
|
|
1219
|
+
let wValue = ${$e.getByOffset(`w_offset / ${x}`)};
|
|
1220
|
+
dotProd = dotProd + xValue * wValue;`;else for(let Ee=0;Ee<m;Ee++)Ae+=`
|
|
1221
|
+
let wValue${Ee} = ${$e.getByOffset(`${$e.indicesToOffset(`${$e.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${Ee}, wOutChannel)`)} / ${x}`)};
|
|
1222
|
+
dotProd = dotProd + xValue[${Ee}] * wValue${Ee};`;return Ae},ae=()=>{if(v===0)return"";if(!g)throw new Error(`packInputAs4 ${g} is not true.`);let Ae="";if(m===1){Ae+="dotProd = dotProd";for(let Ee=0;Ee<v;Ee++)Ae+=`
|
|
1223
|
+
+ ${Le.getByOffset(`x_offset + ${Ee}`)} * ${$e.getByOffset(`w_offset + ${Ee}`)}`;Ae+=";"}else if(m===2){if(v!==2)throw new Error(`Invalid inputChannelsRemainder ${v}.`);Ae+=`
|
|
1224
|
+
let xValue = ${Le.getByOffset("x_offset")};
|
|
1225
|
+
let wValue = ${$e.getByOffset("w_offset")};
|
|
1226
|
+
dotProd = dotProd + dot(xValue, wValue);`}return Ae},Oe=`
|
|
1227
|
+
let outputIndices = ${De.offsetToIndices(`global_idx * ${S}`)};
|
|
1228
|
+
let batch = ${De.indicesGet("outputIndices",0)};
|
|
1229
|
+
let d1 = ${De.indicesGet("outputIndices",ge)};
|
|
1230
|
+
let r = ${De.indicesGet("outputIndices",Me)};
|
|
1231
|
+
let c = ${De.indicesGet("outputIndices",Xe)};
|
|
1232
|
+
let dyCorner = vec2<i32>(i32(r), i32(c)) - uniforms.pads;
|
|
1233
|
+
let dyRCorner = dyCorner.x;
|
|
1234
|
+
let dyCCorner = dyCorner.y;
|
|
1235
|
+
let groupId = d1 / uniforms.output_channels_per_group;
|
|
1236
|
+
let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;
|
|
1237
|
+
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
1238
|
+
// ? = to be determined. : = across all values in that axis.
|
|
1239
|
+
var dotProd = ${De.type.value}(0.0);
|
|
1240
|
+
var wR: u32 = 0;
|
|
1241
|
+
if (uniforms.dilations.x == 1) {
|
|
1242
|
+
// Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0
|
|
1243
|
+
wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner);
|
|
1244
|
+
}
|
|
1245
|
+
for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {
|
|
1246
|
+
if (wR % uniforms.dilations.x != 0) {
|
|
1247
|
+
continue;
|
|
1248
|
+
}
|
|
1249
|
+
let dyR = (${Re}(dyRCorner) + ${Re}(wR)) / ${Re}(uniforms.strides[0]);
|
|
1250
|
+
let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;
|
|
1251
|
+
if (dyR < 0.0 || dyR >= ${Re}(uniforms.Dy_shape[${Me}]) || fract(dyR) > 0.0 ||
|
|
1252
|
+
wRPerm < 0) {
|
|
1253
|
+
continue;
|
|
1254
|
+
}
|
|
1255
|
+
let idyR: u32 = u32(dyR);
|
|
1256
|
+
var wC: u32 = 0;
|
|
1257
|
+
if (uniforms.dilations.y == 1) {
|
|
1258
|
+
// Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0
|
|
1259
|
+
wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner);
|
|
1260
|
+
}
|
|
1261
|
+
for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {
|
|
1262
|
+
if (wC % uniforms.dilations.y != 0) {
|
|
1263
|
+
continue;
|
|
1264
|
+
}
|
|
1265
|
+
let dyC = (${Re}(dyCCorner) + ${Re}(wC)) / ${Re}(uniforms.strides.y);
|
|
1266
|
+
let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;
|
|
1267
|
+
if (dyC < 0.0 || dyC >= ${Re}(uniforms.Dy_shape[${Xe}]) ||
|
|
1268
|
+
fract(dyC) > 0.0 || wCPerm < 0) {
|
|
1269
|
+
continue;
|
|
1270
|
+
}
|
|
1271
|
+
let idyC: u32 = u32(dyC);
|
|
1272
|
+
var inputChannel = groupId * uniforms.input_channels_per_group;
|
|
1273
|
+
${g?`
|
|
1274
|
+
var x_offset = ${Le.indicesToOffset(`${Le.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${m};
|
|
1275
|
+
var w_offset = ${$e.indicesToOffset(`${$e.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${x};
|
|
1276
|
+
`:""}
|
|
1277
|
+
for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${g?4:m}) {
|
|
1278
|
+
${He()}
|
|
1279
|
+
inputChannel = inputChannel + ${g?4:m};
|
|
1280
|
+
}
|
|
1281
|
+
${ae()}
|
|
1282
|
+
wC = wC + uniforms.strides.y - 1;
|
|
1283
|
+
}
|
|
1284
|
+
wR = wR + uniforms.strides[0] - 1;
|
|
1285
|
+
}
|
|
1286
|
+
let value = dotProd${i?` + bias[d1 / ${S}]`:""};
|
|
1287
|
+
${De.setByOffset("global_idx","value")};
|
|
1288
|
+
`;return`
|
|
1289
|
+
${_e.registerUniforms(Fe).declareVariables(...Ve,De)}
|
|
1290
|
+
${_e.mainStart()}
|
|
1291
|
+
${_e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};
|
|
1292
|
+
${Oe}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${m}${x}${S}${g}${v}`,inputDependencies:$},getRunData:()=>({dispatchGroup:{x:k[0],y:k[1],z:k[2]},outputs:[{dims:n?n(o):o,dataType:e[0].dataType}],programUniforms:ee}),getShaderSource:ue}}}),qu,Wu,Hu,ya,Ku,ju,wa,Qu,Xu,xm=b(()=>{$m(),Ms(),Ue(),qu=(e,t,n,i,o,l)=>(e-1)*t+n+(i-1)*o+1-l,Wu=(e,t,n,i,o)=>{let l=Math.floor(e/2);t==="SAME_UPPER"?(n[i]=l,n[o]=e-l):t==="SAME_LOWER"&&(n[i]=e-l,n[o]=l)},Hu=(e,t,n,i,o,l,u,c,h,p)=>{let m=e.length-2,g=p.length===0;h.length<m&&h.push(...Array(m-h.length).fill(0));let w=e[0],v=t[c?3:1]*o;for(let S=0,x=e.length-m-(c?1:0);S<m;++S,++x){let M=e[x],k=g?M*u[S]:p[S],$=qu(M,u[S],l[S],t[x],n[S],k);Wu($,i,l,S,S+m),g&&p.push(u[S]*(M-1)+h[S]+(t[x]-1)*n[S]+1-l[S]-l[S+m])}p.splice(0,0,w),p.splice(c?3:1,0,v)},ya=(e,t)=>{let n=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((g,w)=>g*w,1)===0){n.length=0;for(let g=2;g<t[1].dims.length;++g)n.push(t[1].dims[g])}let i=e.format==="NHWC";n.splice(0,0,t[1].dims[0]),n.splice(i?3:1,0,t[1].dims[1]);let o=e.pads.slice(),l=e.outputShape.slice(),u=e.outputPadding.slice(),c=t[0].dims,h=e.dilations.slice();if(h.reduce((g,w)=>g+w,0)===0){let g=t[0].dims.length-2;h=new Array(g).fill(1)}let p=e.strides.slice();if(p.reduce((g,w)=>g+w,0)===0){let g=t[0].dims.length-2;p=new Array(g).fill(1)}Hu(c,n,h,e.autoPad,e.group,o,p,i,u,l);let m=Object.assign({},e);return Object.assign(m,{kernelShape:n,pads:o,outputPadding:u,outputShape:l,dilations:h,strides:p}),m},Ku=e=>{let t=na(e),n=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,l=e.group??1,u=e.kernelShape,c=e.pads,h=e.strides,p=e.wIsConst(),m=e.outputPadding,g=e.outputShape;return{autoPad:i,format:n,dilations:o,group:l,kernelShape:u,outputPadding:m,outputShape:g,pads:c,strides:h,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},ju=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let n=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[0];if(n!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let l=e[0].dims.length-2;if(t.dilations.reduce((u,c)=>u+c,0)>0&&t.dilations.length!==l)throw new Error(`dilations should be ${l}D`);if(t.strides.reduce((u,c)=>u+c,0)>0&&t.strides.length!==l)throw new Error(`strides should be ${l}D`);if(t.pads.reduce((u,c)=>u+c,0)>0&&t.pads.length!==l*2)throw new Error(`pads should be ${l*2}D`);if(t.outputPadding.length!==l&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${l}D`);if(t.kernelShape.reduce((u,c)=>u+c,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},wa=(e,t,n,i)=>{let o=e.kernelCustomData.wT??e.compute(ht(t[1],[2,3,0,1]),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let l=[t[0],o];t.length===3&&l.push(t[2]),e.compute(Gu(l,n,i),{inputs:l})},Qu=(e,t)=>{let n=t.format==="NHWC",i=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&i.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let l=t.dilations;(l.length===0||l[0]===0)&&(l=[1]);let u=t.strides;(u.length===0||u[0]===0)&&(u=[1]);let c=t.pads;c.length===0&&(c=[0,0]),c=[0,c[0],0,c[1]],u=[1].concat(u),l=[1].concat(l),o=[1].concat(o);let h=t.outputPadding;h=[0].concat(h);let p=ya({...t,pads:c,strides:u,dilations:l,kernelShape:o,outputPadding:h},i);wa(e,i,p,m=>n?[m[0],m[2],m[3]]:[m[0],m[1],m[3]])},Xu=(e,t)=>{if(ju(e.inputs,t),e.inputs[0].dims.length===3)Qu(e,t);else{let n=ya(t,e.inputs);wa(e,e.inputs,n)}}}),Yu,Ju,Zu,Cm=b(()=>{Ie(),ke(),A(),ye(),Yu=(e,t,n,i)=>{let o=j.size(t),l=t.length,u=F("input",e,l),c=le("output",e,l),h=n.dataType===6?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),p=j.normalizeAxis(h,l),m=g=>{let w=` i32(${u.indicesGet("inputIndices","uniforms.axis")}) `,v=Q("uniforms.input_shape","uniforms.axis",l),S=i.reverse?w+(i.exclusive?" + 1":""):"0",x=i.reverse?v:w+(i.exclusive?"":" + 1");return`
|
|
1293
|
+
${g.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(u,c)}
|
|
1294
|
+
${g.mainStart()}
|
|
1295
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1296
|
+
var inputIndices = ${c.offsetToIndices("global_idx")};
|
|
1297
|
+
var sum = ${c.type.value}(0);
|
|
1298
|
+
let first : i32 = ${S};
|
|
1299
|
+
let last : i32 = ${x};
|
|
1300
|
+
for (var i : i32 = first; i < last; i++) {
|
|
1301
|
+
${u.indicesSet("inputIndices","uniforms.axis","u32(i)")};
|
|
1302
|
+
sum = sum + ${u.getByIndices("inputIndices")};
|
|
1303
|
+
}
|
|
1304
|
+
${c.setByOffset("global_idx","sum")};
|
|
1305
|
+
}`};return{name:"CumSum",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:p},...L(t,t)]}),getShaderSource:m}},Ju=(e,t)=>{let n=e.inputs[0].dims,i=e.inputs[0].dataType,o=e.inputs[1];e.compute(Yu(i,n,o,t),{inputs:[0]})},Zu=e=>{let t=e.exclusive===1,n=e.reverse===1;return E({exclusive:t,reverse:n})}}),ed,td,rd,sd,nd,km=b(()=>{Ie(),ke(),A(),ye(),ed=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},td=(e,t,n,i)=>{let o=[];o.push(`fn perm(i: ${i.type.indices}) -> ${n.type.indices} {
|
|
1306
|
+
var a: ${n.type.indices};`);for(let l=0;l<t;++l)o.push(n.indicesSet("a",e[l],`i[${l}]`));return o.push("return a;}"),o.join(`
|
|
1307
|
+
`)},rd=(e,t)=>{let n,i,o,l,u,c,h=t.format==="NHWC",p=t.blocksize,m=t.mode==="DCR";h?([n,i,o,l]=e.dims,u=m?[n,i,o,p,p,l/p**2]:[n,i,o,l/p**2,p,p],c=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,i,o,l]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],u=m?[n,p,p,l/p**2,i,o]:[n,l/p**2,p,p,i,o],c=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let g=e.reshape(u),w=g.dims.length,v=e.dataType,S=F("a",v,w),x=le("output",v,w),M=k=>`
|
|
1308
|
+
${k.registerUniform("output_size","u32").declareVariables(S,x)}
|
|
1309
|
+
|
|
1310
|
+
${td(c,w,S,x)}
|
|
1311
|
+
|
|
1312
|
+
${k.mainStart()}
|
|
1313
|
+
${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1314
|
+
|
|
1315
|
+
let indices = ${x.offsetToIndices("global_idx")};
|
|
1316
|
+
let aIndices = perm(indices);
|
|
1317
|
+
|
|
1318
|
+
${x.setByOffset("global_idx",S.getByIndices("aIndices"))}
|
|
1319
|
+
}`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:k=>{let $=h?[n,i*p,o*p,l/p**2]:[n,l/p**2,i*p,o*p],P=j.size($),I=g.dims,B=j.sortBasedOnPerm(I,c);return{outputs:[{dims:$,dataType:k[0].dataType}],dispatchGroup:{x:Math.ceil(P/64)},programUniforms:[{type:12,data:P},...L(I,B)]}},getShaderSource:M}},sd=(e,t)=>{ed(e.inputs),e.compute(rd(e.inputs[0],t))},nd=e=>E({blocksize:e.blocksize,mode:e.mode,format:e.format})}),$i,Kn,va,id,ad,od,ld,_a,ud,dd,cd,Rm=b(()=>{Ie(),ke(),A(),ye(),$i="[a-zA-Z]|\\.\\.\\.",Kn="("+$i+")+",va="^"+Kn+"$",id="("+Kn+",)*"+Kn,ad="^"+id+"$",od=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);n===void 0?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},ld=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,i]=t.includes("->")?t.split("->",2):[t,""];if(!n.match(RegExp(ad)))throw new Error("Invalid LHS term");if(n.split(",").forEach((o,l)=>{let u=e[l].dims.slice();if(!o.match(RegExp(va)))throw new Error("Invalid LHS term");let c=this.processTerm(o,!0,u,l);this.lhs.push(c)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([o,l])=>l.count===1||o==="...").map(([o])=>o).join("");else if(!i.match(RegExp(Kn)))throw new Error("Invalid RHS");i.match(RegExp($i,"g"))?.forEach(o=>{if(o==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let l=this.symbolToInfo.get(o);if(l===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(l.dimValue)}}),this.rhs=this.processTerm(i,!1,this.outputDims)}addSymbol(e,t,n){let i=this.symbolToInfo.get(e);if(i!==void 0){if(i.dimValue!==t&&i.count!==1)throw new Error("Dimension mismatch");i.count++,i.inputIndices.push(n)}else i={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,i)}processTerm(e,t,n,i=-1){let o=n.length,l=!1,u=[],c=0;if(!e.match(RegExp(va))&&!t&&e!=="")throw new Error("Invalid LHS term");let h=e.match(RegExp($i,"g")),p=new od(i);return h?.forEach((m,g)=>{if(m==="..."){if(l)throw new Error("Only one ellipsis is allowed per input term");l=!0;let w=o-h.length+1;if(w<0)throw new Error("Ellipsis out of bounds");if(u=n.slice(c,c+w),this.hasEllipsis){if(this.ellipsisDims.length!==u.length||this.ellipsisDims.toString()!==u.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=u;else throw new Error("Ellipsis must be specified in the LHS");for(let v=0;v<u.length;v++){let S=String.fromCharCode(48+v);p.addSymbol(S,g+v),this.addSymbol(S,n[c++],i)}}else p.addSymbol(m,g+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(m,n[c++],i)}),p}},_a=e=>e+"_max",ud=(e,t,n,i)=>{let o=e.map(p=>p.length).map((p,m)=>F(`input${m}`,t,p)),l=j.size(i),u=le("output",t,i.length),c=[...n.symbolToInfo.keys()].filter(p=>!n.rhs.symbolToIndices.has(p)),h=p=>{let m=[],g="var prod = 1.0;",w="var sum = 0.0;",v="sum += prod;",S=[],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,ee)=>{if(I.inputIndices.includes(ee)){let ue=W.symbolToIndices.get(B);if(ue===void 0)throw new Error("Invalid symbol error");ue.forEach(_e=>{m.push(`${o[ee].indicesSet(`input${ee}Indices`,_e,u.indicesGet("outputIndices",q))}`)})}})}else n.lhs.forEach((q,W)=>{if(I.inputIndices.includes(W)){let ee=q.symbolToIndices.get(B);if(ee===void 0)throw new Error("Invalid symbol error");ee.forEach(ue=>{S.push(`${o[W].indicesSet(`input${W}Indices`,ue,`${B}`)}`)}),k.push(`prod *= ${o[W].getByIndices(`input${W}Indices`)};`)}}),x.push(`for(var ${B}: u32 = 0; ${B} < uniforms.${_a(B)}; ${B}++) {`),M.push("}")});let P=$?[...m,`let sum = ${o.map((I,B)=>I.getByIndices(`input${B}Indices`)).join(" * ")};`]:[...m,w,...x,...S,g,...k,v,...M];return`
|
|
1320
|
+
${p.registerUniforms(c.map(I=>({name:`${_a(I)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,u)}
|
|
1321
|
+
|
|
1322
|
+
${p.mainStart()}
|
|
1323
|
+
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1324
|
+
var outputIndices = ${u.offsetToIndices("global_idx")};
|
|
1325
|
+
${o.map((I,B)=>`var input${B}Indices: ${o[B].type.indices};`).join(`
|
|
1326
|
+
`)}
|
|
1327
|
+
${P.join(`
|
|
1328
|
+
`)};
|
|
1329
|
+
${u.setByOffset("global_idx","sum")};
|
|
1330
|
+
}`};return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=c.filter(g=>n.symbolToInfo.has(g)).map(g=>({type:12,data:n.symbolToInfo.get(g)?.dimValue||0}));p.push({type:12,data:l});let m=e.map((g,w)=>[...L(g)]).reduce((g,w)=>g.concat(w),p);return m.push(...L(i)),{outputs:[{dims:i,dataType:t}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:m}},getShaderSource:h}},dd=(e,t)=>{let n=new ld(e.inputs,t.equation),i=n.outputDims,o=e.inputs.map((l,u)=>l.dims);e.compute(ud(o,e.inputs[0].dataType,n,i))},cd=e=>{let t=e.equation.replace(/\s+/g,"");return E({equation:t})}}),hd,ba,pd,fd,md,Am=b(()=>{Ie(),ke(),ye(),hd=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=n.length<t.length?0:n.length-t.length,o=t.length<n.length?0:t.length-n.length;for(;i<n.length&&o<t.length;++i,++o)if(n[i]!==t[o]&&n[i]!==1&&t[o]!==1)throw new Error("Expand requires shape to be broadcastable to input")},ba=(e,t)=>{let n=e.length-t.length,i=[];for(let o=0;o<n;++o)i.push(e[o]);for(let o=0;o<t.length;++o)i.push(t[o]===1?e[o+n]:t[o]);return i},pd=(e,t)=>e.length>t.length?ba(e,t):ba(t,e),fd=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=pd(t,n),o=e[0].dataType,l=o===9||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),p=g=>{let w=F("input",o,t.length,u),v=le("output",o,i.length,c),S;if(o===9){let x=(M,k,$="")=>`
|
|
1331
|
+
let outputIndices${k} = ${v.offsetToIndices(`outputOffset + ${k}u`)};
|
|
1332
|
+
let offset${k} = ${w.broadcastedIndicesToOffset(`outputIndices${k}`,v)};
|
|
1333
|
+
let index${k} = offset${k} / 4u;
|
|
1334
|
+
let component${k} = offset${k} % 4u;
|
|
1335
|
+
${M}[${k}] = ${$}(${w.getByOffset(`index${k}`)}[component${k}]);
|
|
1336
|
+
`;S=`
|
|
1337
|
+
let outputOffset = global_idx * ${c};
|
|
1338
|
+
var data = vec4<u32>(0);
|
|
1339
|
+
${x("data",0,"u32")}
|
|
1340
|
+
${x("data",1,"u32")}
|
|
1341
|
+
${x("data",2,"u32")}
|
|
1342
|
+
${x("data",3,"u32")}
|
|
1343
|
+
${v.setByOffset("global_idx","data")}
|
|
1344
|
+
}`}else S=`
|
|
1345
|
+
let outputIndices = ${v.offsetToIndices(`global_idx * ${c}`)};
|
|
1346
|
+
let inputOffset = ${w.broadcastedIndicesToOffset("outputIndices",v)};
|
|
1347
|
+
let data = ${v.type.value}(${w.getByOffset(`inputOffset / ${u}`)});
|
|
1348
|
+
${v.setByOffset("global_idx","data")}
|
|
1349
|
+
}`;return`
|
|
1350
|
+
${g.registerUniform("vec_size","u32").declareVariables(w,v)}
|
|
1351
|
+
${g.mainStart()}
|
|
1352
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
1353
|
+
${S}`},m=[{type:12,data:h},...L(t,i)];return{name:"Expand",shaderCache:{hint:`${i.length};${u}${c}`,inputDependencies:["rank"]},getShaderSource:p,getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:m})}},md=e=>{hd(e.inputs),e.compute(fd(e.inputs),{inputs:[0]})}}),gd,yd,Im=b(()=>{Ie(),ke(),ye(),sa(),gd=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=F("x",t,[1],4),h=F("bias",t,[1],4),p=le("y",t,[1],4),m=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],g=v=>`
|
|
1354
|
+
let bias${v}_offset: u32 = (global_idx * 4 + ${v}) % uniforms.bias_size;
|
|
1355
|
+
let bias${v} = ${h.getByOffset(`bias${v}_offset / 4`)}[bias${v}_offset % 4];`,w=o?`
|
|
1356
|
+
let bias = ${h.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${g(0)}${g(1)}${g(2)}${g(3)}
|
|
1357
|
+
let bias = ${c.type.value}(bias0, bias1, bias2, bias3);`;return`${u.registerUniforms(m).declareVariables(c,h,p)}
|
|
1358
|
+
|
|
1359
|
+
${ta(N(t))}
|
|
1360
|
+
|
|
1361
|
+
${u.mainStart(D)}
|
|
1362
|
+
${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}
|
|
1363
|
+
|
|
1364
|
+
let x = ${c.getByOffset("global_idx")};
|
|
1365
|
+
${w}
|
|
1366
|
+
let x_in = x + bias;
|
|
1367
|
+
${p.setByOffset("global_idx",ra("x_in"))}
|
|
1368
|
+
}`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:l,getRunData:u=>({outputs:[{dims:u[0].dims,dataType:u[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:i}],dispatchGroup:{x:Math.ceil(n/D/4)}})}},yd=e=>{e.inputs.length<2||j.size(e.inputs[1].dims)===0?Yl(e):e.compute(gd(e.inputs))}}),wd,vd,_d,bd,Mm=b(()=>{Ie(),ke(),A(),ye(),wd=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},vd=(e,t)=>{let n=e[0].dims,i=e[1].dims,o=n.length,l=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,p=Math.ceil(j.size(u)/h),m=[{type:12,data:p},{type:6,data:c},{type:12,data:l},...L(e[0].dims,e[1].dims,u)],g=w=>{let v=F("data",e[0].dataType,e[0].dims.length,h),S=F("inputIndices",e[1].dataType,e[1].dims.length),x=le("output",e[0].dataType,u.length,h),M=$=>{let P=i.length,I=`var indicesIndices${$} = ${S.type.indices}(0);`;for(let B=0;B<P;B++)I+=`${P>1?`indicesIndices${$}[${B}]`:`indicesIndices${$}`} = ${u.length>1?`outputIndices${$}[uniforms.axis + ${B}]`:`outputIndices${$}`};`;I+=`
|
|
1369
|
+
var idx${$} = ${S.getByIndices(`indicesIndices${$}`)};
|
|
1370
|
+
if (idx${$} < 0) {
|
|
1371
|
+
idx${$} = idx${$} + uniforms.axisDimLimit;
|
|
1372
|
+
}
|
|
1373
|
+
var dataIndices${$} : ${v.type.indices};
|
|
1374
|
+
`;for(let B=0,q=0;B<o;B++)B===l?(I+=`${o>1?`dataIndices${$}[${B}]`:`dataIndices${$}`} = u32(idx${$});`,q+=P):(I+=`${o>1?`dataIndices${$}[${B}]`:`dataIndices${$}`} = ${u.length>1?`outputIndices${$}[${q}]`:`outputIndices${$}`};`,q++);return I},k;if(e[0].dataType===9){let $=(P,I,B="")=>`
|
|
1375
|
+
let outputIndices${I} = ${x.offsetToIndices(`outputOffset + ${I}u`)};
|
|
1376
|
+
${M(I)};
|
|
1377
|
+
let offset${I} = ${v.indicesToOffset(`dataIndices${I}`)};
|
|
1378
|
+
let index${I} = offset${I} / 4u;
|
|
1379
|
+
let component${I} = offset${I} % 4u;
|
|
1380
|
+
${P}[${I}] = ${B}(${v.getByOffset(`index${I}`)}[component${I}]);
|
|
1381
|
+
`;k=`
|
|
1382
|
+
let outputOffset = global_idx * ${h};
|
|
1383
|
+
var value = vec4<u32>(0);
|
|
1384
|
+
${$("value",0,"u32")}
|
|
1385
|
+
${$("value",1,"u32")}
|
|
1386
|
+
${$("value",2,"u32")}
|
|
1387
|
+
${$("value",3,"u32")}
|
|
1388
|
+
${x.setByOffset("global_idx","value")}
|
|
1389
|
+
`}else k=`
|
|
1390
|
+
let outputIndices = ${x.offsetToIndices("global_idx")};
|
|
1391
|
+
${M("")};
|
|
1392
|
+
let value = ${v.getByIndices("dataIndices")};
|
|
1393
|
+
${x.setByOffset("global_idx","value")};
|
|
1394
|
+
`;return`
|
|
1395
|
+
${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(v,S,x)}
|
|
1396
|
+
${w.mainStart()}
|
|
1397
|
+
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1398
|
+
${k}
|
|
1399
|
+
}`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:g}},_d=e=>E({axis:e.axis}),bd=(e,t)=>{let n=e.inputs;wd(n),e.compute(vd(e.inputs,t))}}),Sd,Td,Ed,Pm=b(()=>{Ie(),ke(),ye(),Sd=(e,t,n,i,o,l,u,c,h)=>{let p=[{type:12,data:l},{type:12,data:i},{type:12,data:o},{type:12,data:n},{type:12,data:u},{type:12,data:c},{type:12,data:h}],m=[l];p.push(...L(t.dims,m));let g=w=>{let v=F("indices_data",t.dataType,t.dims.length),S=le("input_slice_offsets_data",12,1,1),x=[v,S],M=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:n.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return`
|
|
1400
|
+
${w.registerUniforms(M).declareVariables(...x)}
|
|
1401
|
+
${w.mainStart()}
|
|
1402
|
+
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1403
|
+
let batch_idx = global_idx / uniforms.num_slices_per_batch;
|
|
1404
|
+
let base_offset = batch_idx * uniforms.input_batch_stride;
|
|
1405
|
+
|
|
1406
|
+
let slice_indices_base_offset = global_idx * uniforms.num_slice_dims;
|
|
1407
|
+
var relative_slice_offset = 0;
|
|
1408
|
+
for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) {
|
|
1409
|
+
var index = i32(indices_data[dim_idx + slice_indices_base_offset].x);
|
|
1410
|
+
let input_dim_idx = uniforms.batch_dims + dim_idx;
|
|
1411
|
+
if (index < 0) {
|
|
1412
|
+
${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"}
|
|
1413
|
+
}
|
|
1414
|
+
${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]);"}
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset);
|
|
1418
|
+
}`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${n.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:m,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p}),getShaderSource:g},{inputs:[t],outputs:[-1]})[0]},Td=(e,t)=>{let n=e.inputs,i=n[0].dims,o=n[0].dataType,l=n[1].dims,u=l[l.length-1],c=j.sizeToDimension(l,l.length-1),h=j.sizeFromDimension(i,t.batchDims+u),p=j.sizeToDimension(i,t.batchDims),m=j.sizeFromDimension(i,t.batchDims),g=c/p,w=new Array(u),v=h;for(let I=0;I<u;++I)w[u-1-I]=v,v*=i[t.batchDims+u-1-I];let S=Sd(e,n[1],w,t.batchDims,i,c,g,m,u),x=t.batchDims+u;if(x>i.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let M=l.slice(0,-1).concat(i.slice(x)),k=j.size(M),$=[{type:12,data:k},{type:12,data:h},...L(n[0].dims,S.dims,M)],P=I=>{let B=F("data",n[0].dataType,n[0].dims.length),q=F("slice_offsets",12,S.dims.length),W=le("output",n[0].dataType,M.length);return`
|
|
1419
|
+
${I.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(B,q,W)}
|
|
1420
|
+
${I.mainStart()}
|
|
1421
|
+
${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1422
|
+
let slice_offset = slice_offsets[global_idx / uniforms.slice_size];
|
|
1423
|
+
output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size];
|
|
1424
|
+
}`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:M,dataType:o}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:$}),getShaderSource:P},{inputs:[n[0],S]})},Ed=e=>({batchDims:e.batch_dims,cacheKey:""})}),$d,xd,Cd,kd,Om=b(()=>{Ie(),ke(),A(),ye(),$d=(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.")}},xd=(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),p=e[2].dataType,m=e[0].dataType===22,g=[{type:12,data:h},{type:12,data:u},{type:12,data:l},{type:12,data:t.blockSize},...L(...e.map((v,S)=>v.dims),c)],w=v=>{let S=F("data",e[0].dataType,e[0].dims.length),x=F("inputIndices",e[1].dataType,e[1].dims.length),M=F("scales",e[2].dataType,e[2].dims.length),k=e.length>3?F("zeroPoint",e[3].dataType,e[3].dims.length):void 0,$=le("output",p,c.length),P=[S,x,M];k&&P.push(k);let I=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
1425
|
+
${v.registerUniforms(I).declareVariables(...P,$)}
|
|
1426
|
+
${v.mainStart()}
|
|
1427
|
+
let output_indices = ${$.offsetToIndices("global_idx")};
|
|
1428
|
+
var indices_indices = ${x.type.indices}(0);
|
|
1429
|
+
${i.length>1?`
|
|
1430
|
+
for (var i: u32 = 0; i < ${i.length}; i++) {
|
|
1431
|
+
let index = ${$.indicesGet("output_indices","uniforms.gather_axis + i")};
|
|
1432
|
+
${x.indicesSet("indices_indices","i","index")};
|
|
1433
|
+
}`:`indices_indices = ${$.indicesGet("output_indices","uniforms.gather_axis")};`};
|
|
1434
|
+
var data_indices = ${S.type.indices}(0);
|
|
1435
|
+
for (var i: u32 = 0; i < uniforms.gather_axis; i++) {
|
|
1436
|
+
let index = ${$.indicesGet("output_indices","i")};
|
|
1437
|
+
${S.indicesSet("data_indices","i","index")};
|
|
1438
|
+
}
|
|
1439
|
+
var index_from_indices = ${x.getByIndices("indices_indices")};
|
|
1440
|
+
if (index_from_indices < 0) {
|
|
1441
|
+
index_from_indices += ${n[l]};
|
|
1442
|
+
}
|
|
1443
|
+
${S.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")};
|
|
1444
|
+
for (var i = uniforms.gather_axis + 1; i < ${c.length}; i++) {
|
|
1445
|
+
let index = ${$.indicesGet("output_indices",`i + ${i.length} - 1`)};
|
|
1446
|
+
${S.indicesSet("data_indices","i","index")};
|
|
1447
|
+
}
|
|
1448
|
+
let data_offset = ${S.indicesToOffset("data_indices")};
|
|
1449
|
+
let data_index = data_offset % 8;
|
|
1450
|
+
// Convert 4-bit packed data to 8-bit packed data.
|
|
1451
|
+
let packed_4bit_quantized_data = ${S.getByOffset("data_offset / 8")};
|
|
1452
|
+
let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;
|
|
1453
|
+
let quantized_data_vec = ${m?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data));
|
|
1454
|
+
let quantized_data = quantized_data_vec[data_index / 2];
|
|
1455
|
+
var scale_indices = data_indices;
|
|
1456
|
+
let quantize_axis_index = ${M.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size;
|
|
1457
|
+
${M.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")};
|
|
1458
|
+
var scale = ${M.getByIndices("scale_indices")};
|
|
1459
|
+
${k?`
|
|
1460
|
+
let zero_point_indices = scale_indices;
|
|
1461
|
+
let zero_point_offset = ${k.indicesToOffset("zero_point_indices")};
|
|
1462
|
+
let zero_point_index = zero_point_offset % 8;
|
|
1463
|
+
let packed_4bit_zero_points = ${k.getByOffset("zero_point_offset / 8")};
|
|
1464
|
+
let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;
|
|
1465
|
+
let zero_point_vec = ${m?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points));
|
|
1466
|
+
let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};
|
|
1467
|
+
let dequantized_data = ${N(p)}(quantized_data - zero_point) * scale;
|
|
1468
|
+
${$.setByOffset("global_idx","dequantized_data")};
|
|
1469
|
+
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((v,S)=>S!==1).map(v=>v.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(v,S)=>"rank")},getRunData:()=>({outputs:[{dims:c,dataType:p}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:g}),getShaderSource:w}},Cd=(e,t)=>{let n=e.inputs;$d(n,t),e.compute(xd(e.inputs,t))},kd=e=>E({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Rd,Ad,Id,Md,Dm=b(()=>{Ie(),ke(),A(),ye(),Rd=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and
|
|
1470
|
+
indices input tensors be of same rank.`)},Ad=(e,t)=>{let n=e[0].dims,i=e[0].dataType,o=n.length,l=e[1].dims,u=e[1].dataType,c=j.normalizeAxis(t.axis,o),h=n[c],p=l.slice(0),m=j.size(p),g=F("input",i,o),w=F("indicesInput",u,l.length),v=le("output",i,p.length),S=[{type:12,data:m},{type:6,data:h},{type:12,data:c}];return S.push(...L(n,l,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:S}),getShaderSource:x=>`
|
|
1471
|
+
${x.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(g,w,v)}
|
|
1472
|
+
${x.mainStart()}
|
|
1473
|
+
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1474
|
+
|
|
1475
|
+
let outputIndices = ${v.offsetToIndices("global_idx")};
|
|
1476
|
+
|
|
1477
|
+
var idx = ${w.getByOffset("global_idx")};
|
|
1478
|
+
if (idx < 0) {
|
|
1479
|
+
idx = idx + uniforms.axisDimLimit;
|
|
1480
|
+
}
|
|
1481
|
+
var inputIndices = ${g.type.indices}(outputIndices);
|
|
1482
|
+
${g.indicesSet("inputIndices","uniforms.axis","u32(idx)")};
|
|
1483
|
+
let value = ${g.getByIndices("inputIndices")};
|
|
1484
|
+
|
|
1485
|
+
${v.setByOffset("global_idx","value")};
|
|
1486
|
+
}`}},Id=e=>E({axis:e.axis}),Md=(e,t)=>{let n=e.inputs;Rd(n),e.compute(Ad(e.inputs,t))}}),Pd,Od,Dd,zd,zm=b(()=>{Ie(),ke(),ye(),Pd=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Od=(e,t)=>{let n=e[0].dims.slice(),i=e[1].dims.slice(),[o,l,u]=js.getShapeOfGemmResult(n,t.transA,i,t.transB,e.length===3?e[2].dims:void 0),c=[o,l];if(!c)throw new Error("Can't use gemm on the given tensors");let h=16,p=Math.ceil(l/h),m=Math.ceil(o/h);j.size(c);let g=[{type:12,data:p},{type:12,data:o},{type:12,data:l},{type:12,data:u},{type:1,data:t.alpha},{type:1,data:t.beta}],w=["type","type"];e.length===3&&(g.push(...L(e[2].dims)),w.push("rank")),g.push(...L(c));let v=S=>{let x=F("a",e[0].dataType,e[0].dims),M=F("b",e[1].dataType,e[1].dims),k=null,$=[x,M];e.length===3&&(k=F("c",e[2].dataType,e[2].dims.length),$.push(k));let P=le("output",e[0].dataType,c.length);$.push(P);let I=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],B="",q="";t.transA&&t.transB?(q=`
|
|
1487
|
+
var col = tile_row_start + local_id.x;
|
|
1488
|
+
var row = k_start + local_id.y;
|
|
1489
|
+
if (col < uniforms.M && row < uniforms.K) {
|
|
1490
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
|
|
1491
|
+
} else {
|
|
1492
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
col = k_start + local_id.x;
|
|
1496
|
+
row = tile_col_start + local_id.y;
|
|
1497
|
+
if (col < uniforms.K && row < uniforms.N) {
|
|
1498
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
|
|
1499
|
+
} else {
|
|
1500
|
+
tile_b[local_id.y][local_id.x] = ${M.type.value}(0);
|
|
1501
|
+
}
|
|
1502
|
+
`,B="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(q=`
|
|
1503
|
+
var col = tile_row_start + local_id.x;
|
|
1504
|
+
var row = k_start + local_id.y;
|
|
1505
|
+
if (col < uniforms.M && row < uniforms.K) {
|
|
1506
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
|
|
1507
|
+
} else {
|
|
1508
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
col = tile_col_start + local_id.x;
|
|
1512
|
+
row = k_start + local_id.y;
|
|
1513
|
+
if (col < uniforms.N && row < uniforms.K) {
|
|
1514
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
|
|
1515
|
+
} else {
|
|
1516
|
+
tile_b[local_id.y][local_id.x] = ${M.type.value}(0);
|
|
1517
|
+
}
|
|
1518
|
+
`,B="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(q=`
|
|
1519
|
+
var col = k_start + local_id.x;
|
|
1520
|
+
var row = tile_row_start + local_id.y;
|
|
1521
|
+
if (col < uniforms.K && row < uniforms.M) {
|
|
1522
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
|
|
1523
|
+
} else {
|
|
1524
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
col = k_start + local_id.x;
|
|
1528
|
+
row = tile_col_start + local_id.y;
|
|
1529
|
+
if (col < uniforms.K && row < uniforms.N) {
|
|
1530
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
|
|
1531
|
+
} else {
|
|
1532
|
+
tile_b[local_id.y][local_id.x] = ${M.type.value}(0);
|
|
1533
|
+
}
|
|
1534
|
+
`,B="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(q=`
|
|
1535
|
+
var col = k_start + local_id.x;
|
|
1536
|
+
var row = tile_row_start + local_id.y;
|
|
1537
|
+
if (col < uniforms.K && row < uniforms.M) {
|
|
1538
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
|
|
1539
|
+
} else {
|
|
1540
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
col = tile_col_start + local_id.x;
|
|
1544
|
+
row = k_start + local_id.y;
|
|
1545
|
+
if (col < uniforms.N && row < uniforms.K) {
|
|
1546
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
|
|
1547
|
+
} else {
|
|
1548
|
+
tile_b[local_id.y][local_id.x] = ${M.type.value}(0);
|
|
1549
|
+
}
|
|
1550
|
+
`,B="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let W=t.alpha===1?"":"value *= uniforms.alpha;";return`
|
|
1551
|
+
${S.registerUniforms(I).declareVariables(...$)}
|
|
1552
|
+
var<workgroup> tile_a: array<array<${x.type.storage}, ${h}>, ${h}>;
|
|
1553
|
+
var<workgroup> tile_b: array<array<${M.type.storage}, ${h}>, ${h}>;
|
|
1554
|
+
${S.mainStart([h,h,1])}
|
|
1555
|
+
let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${h};
|
|
1556
|
+
let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${h};
|
|
1557
|
+
let num_tiles = (uniforms.K - 1) / ${h} + 1;
|
|
1558
|
+
var k_start = 0u;
|
|
1559
|
+
var value = ${P.type.value}(0);
|
|
1560
|
+
for (var t: u32 = 0u; t < num_tiles; t++) {
|
|
1561
|
+
${q}
|
|
1562
|
+
k_start = k_start + ${h};
|
|
1563
|
+
workgroupBarrier();
|
|
1564
|
+
|
|
1565
|
+
for (var k: u32 = 0u; k < ${h}; k++) {
|
|
1566
|
+
${B}
|
|
1567
|
+
}
|
|
1568
|
+
workgroupBarrier();
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
${W}
|
|
1572
|
+
let m = tile_row_start + local_id.y;
|
|
1573
|
+
let n = tile_col_start + local_id.x;
|
|
1574
|
+
${k!=null?`let cOffset = ${k.broadcastedIndicesToOffset("vec2(m, n)",P)}; value += ${P.type.value}(uniforms.beta) * ${k.getByOffset("cOffset")};`:""}
|
|
1575
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
1576
|
+
output[m * uniforms.N + n] = value;
|
|
1577
|
+
}
|
|
1578
|
+
}`};return{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:p*m},programUniforms:g}),getShaderSource:v}},Dd=e=>{let t=e.transA,n=e.transB,i=e.alpha,o=e.beta;return{transA:t,transB:n,alpha:i,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},zd=(e,t)=>{Pd(e.inputs),e.compute(Od(e.inputs,t))}}),Ir,Nr,Ps,Os,Ld,Bd,Nd,Ud,Fd,Vd,Gd,qd,Wd,Hd,Lm=b(()=>{Ie(),ke(),A(),ye(),[Ir,Nr,Ps,Os]=[0,1,2,3],Ld=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},Bd=`
|
|
1579
|
+
fn gs_get_cubic_coeffs(x: f32) -> vec4<f32> {
|
|
1580
|
+
let cubic_alpha = -0.75f;
|
|
1581
|
+
let x_abs = abs(x);
|
|
1582
|
+
var coeffs: vec4<f32>;
|
|
1583
|
+
coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);
|
|
1584
|
+
coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);
|
|
1585
|
+
coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);
|
|
1586
|
+
coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);
|
|
1587
|
+
return coeffs;
|
|
1588
|
+
}
|
|
1589
|
+
`,Nd=e=>`
|
|
1590
|
+
fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {
|
|
1591
|
+
var v: vec4<f32>;
|
|
1592
|
+
var coeffs = gs_get_cubic_coeffs(x);
|
|
1593
|
+
for (var i = 0; i < 4; i++) {
|
|
1594
|
+
v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];
|
|
1595
|
+
}
|
|
1596
|
+
coeffs = gs_get_cubic_coeffs(y);
|
|
1597
|
+
let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);
|
|
1598
|
+
return pixel;
|
|
1599
|
+
}
|
|
1600
|
+
`,Ud=e=>`
|
|
1601
|
+
fn gs_denormalize(n: f32, length: i32) -> f32 {
|
|
1602
|
+
${e.alignCorners===0?`
|
|
1603
|
+
// alignCorners: false => [-1, 1] to [-0.5, length - 0.5]
|
|
1604
|
+
return ((n + 1.0) * f32(length) - 1.0) / 2.0;
|
|
1605
|
+
`:`
|
|
1606
|
+
// alignCorners: true => [-1, 1] to [0, length - 1]
|
|
1607
|
+
return (n + 1.0) / 2.0 * (f32(length - 1));
|
|
1608
|
+
`}
|
|
1609
|
+
}
|
|
1610
|
+
`,Fd=e=>`
|
|
1611
|
+
${e.paddingMode==="reflection"?`
|
|
1612
|
+
fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {
|
|
1613
|
+
var dx = 0.0;
|
|
1614
|
+
var fx = f32(x);
|
|
1615
|
+
let range = x_max - x_min;
|
|
1616
|
+
if (fx < x_min) {
|
|
1617
|
+
dx = x_min - fx;
|
|
1618
|
+
let n = u32(dx / range);
|
|
1619
|
+
let r = dx - f32(n) * range;
|
|
1620
|
+
if (n % 2 == 0) {
|
|
1621
|
+
fx = x_min + r;
|
|
1622
|
+
} else {
|
|
1623
|
+
fx = x_max - r;
|
|
1624
|
+
}
|
|
1625
|
+
} else if (fx > x_max) {
|
|
1626
|
+
dx = fx - x_max;
|
|
1627
|
+
let n = u32(dx / range);
|
|
1628
|
+
let r = dx - f32(n) * range;
|
|
1629
|
+
if (n % 2 == 0) {
|
|
1630
|
+
fx = x_max - r;
|
|
1631
|
+
} else {
|
|
1632
|
+
fx = x_min + r;
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
return u32(fx);
|
|
1636
|
+
}`:""}
|
|
1637
|
+
`,Vd=(e,t,n)=>`
|
|
1638
|
+
fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4<f32>) -> ${t} {
|
|
1639
|
+
var pixel = ${t}(0);
|
|
1640
|
+
var indices = vec4<u32>(0);
|
|
1641
|
+
indices[${Ir}] = batch;
|
|
1642
|
+
indices[${Nr}] = channel;`+(()=>{switch(n.paddingMode){case"zeros":return`
|
|
1643
|
+
if (r >= 0 && r < H && c >=0 && c < W) {
|
|
1644
|
+
indices[${Ps}] = u32(r);
|
|
1645
|
+
indices[${Os}] = u32(c);
|
|
1646
|
+
} else {
|
|
1647
|
+
return ${t}(0);
|
|
1648
|
+
}
|
|
1649
|
+
`;case"border":return`
|
|
1650
|
+
indices[${Ps}] = u32(clamp(r, 0, H - 1));
|
|
1651
|
+
indices[${Os}] = u32(clamp(c, 0, W - 1));
|
|
1652
|
+
`;case"reflection":return`
|
|
1653
|
+
indices[${Ps}] = gs_reflect(r, border[1], border[3]);
|
|
1654
|
+
indices[${Os}] = gs_reflect(c, border[0], border[2]);
|
|
1655
|
+
`;default:throw new Error(`padding mode ${n.paddingMode} is not supported`)}})()+`
|
|
1656
|
+
return ${e.getByIndices("indices")};
|
|
1657
|
+
}
|
|
1658
|
+
`,Gd=(e,t,n)=>(()=>{switch(n.mode){case"nearest":return`
|
|
1659
|
+
let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Ir}], indices[${Nr}], border);
|
|
1660
|
+
`;case"bilinear":return`
|
|
1661
|
+
let x1 = i32(floor(x));
|
|
1662
|
+
let y1 = i32(floor(y));
|
|
1663
|
+
let x2 = x1 + 1;
|
|
1664
|
+
let y2 = y1 + 1;
|
|
1665
|
+
|
|
1666
|
+
let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Ir}], indices[${Nr}], border);
|
|
1667
|
+
let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Ir}], indices[${Nr}], border);
|
|
1668
|
+
let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Ir}], indices[${Nr}], border);
|
|
1669
|
+
let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Ir}], indices[${Nr}], border);
|
|
1670
|
+
|
|
1671
|
+
let dx2 = ${t}(f32(x2) - x);
|
|
1672
|
+
let dx1 = ${t}(x - f32(x1));
|
|
1673
|
+
let dy2 = ${t}(f32(y2) - y);
|
|
1674
|
+
let dy1 = ${t}(y - f32(y1));
|
|
1675
|
+
let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);
|
|
1676
|
+
`;case"bicubic":return`
|
|
1677
|
+
let x0 = i32(floor(x)) - 1;
|
|
1678
|
+
let y0 = i32(floor(y)) - 1;
|
|
1679
|
+
var p: mat4x4<${t}>;
|
|
1680
|
+
for (var h = 0; h < 4; h++) {
|
|
1681
|
+
for (var w = 0; w < 4; w++) {
|
|
1682
|
+
p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Ir}], indices[${Nr}], border);
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
let dx = x - f32(x0 + 1);
|
|
1687
|
+
let dy = y - f32(y0 + 1);
|
|
1688
|
+
let result = gs_bicubic_interpolate(p, dx, dy);
|
|
1689
|
+
`;default:throw new Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,qd=(e,t)=>{let n=F("x",e[0].dataType,e[0].dims.length),i=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=F("grid",e[1].dataType,i.length,2),l=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(l=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Ir,Nr,Ps,Os]=[0,3,1,2]);let u=le("output",e[0].dataType,l.length),c=n.type.value,h=j.size(l),p=[{type:12,data:h},...L(e[0].dims,i,l)],m=g=>`
|
|
1690
|
+
${g.registerUniform("output_size","u32").declareVariables(n,o,u)}
|
|
1691
|
+
${Bd}
|
|
1692
|
+
${Nd(c)}
|
|
1693
|
+
${Ud(t)}
|
|
1694
|
+
${Fd(t)}
|
|
1695
|
+
${Vd(n,c,t)}
|
|
1696
|
+
|
|
1697
|
+
${g.mainStart()}
|
|
1698
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1699
|
+
let H_in = i32(uniforms.x_shape[${Ps}]);
|
|
1700
|
+
let W_in = i32(uniforms.x_shape[${Os}]);
|
|
1701
|
+
|
|
1702
|
+
${t.alignCorners===0?`
|
|
1703
|
+
let x_min = -0.5;
|
|
1704
|
+
let x_max = f32(W_in) - 0.5;
|
|
1705
|
+
let y_min = -0.5;
|
|
1706
|
+
let y_max = f32(H_in) - 0.5;
|
|
1707
|
+
`:`
|
|
1708
|
+
let x_min = 0.0;
|
|
1709
|
+
let x_max = f32(W_in) - 1.0;
|
|
1710
|
+
let y_min = 0.0;
|
|
1711
|
+
let y_max = f32(H_in) - 1.0;
|
|
1712
|
+
`};
|
|
1713
|
+
let border = vec4<f32>(x_min, y_min, x_max, y_max);
|
|
1714
|
+
|
|
1715
|
+
let indices = ${u.offsetToIndices("global_idx")};
|
|
1716
|
+
var grid_indices = vec3<u32>(indices[${Ir}], indices[${Ps}], indices[${Os}]);
|
|
1717
|
+
let nxy = ${o.getByIndices("grid_indices")};
|
|
1718
|
+
var x = gs_denormalize(f32(nxy[0]), W_in);
|
|
1719
|
+
var y = gs_denormalize(f32(nxy[1]), H_in);
|
|
1720
|
+
|
|
1721
|
+
${Gd(u,c,t)}
|
|
1722
|
+
}`;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:p}},getShaderSource:m}},Wd=(e,t)=>{Ld(e.inputs),e.compute(qd(e.inputs,t))},Hd=e=>E({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Vt,Kd,jd,Sa,Qd,jn,Xd,Yd=b(()=>{Ie(),ke(),A(),Js(),Zi(),ye(),Ue(),Vt=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Kd=(e,t)=>{let n=e[0],i=Vt(e,1),o=Vt(e,2),l=Vt(e,3),u=Vt(e,4),c=Vt(e,5),h=Vt(e,6),p=Vt(e,7);if(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let m=n.dims[0],g=n.dims[1],w=n.dims.length===3?n.dims[2]:t.numHeads*n.dims[4],v=g,S=0,x=0,M=Math.floor(w/t.numHeads);if(h&&p&&j.size(h.dims)&&j.size(p.dims)){if(h.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(h.dims[0]!==m||h.dims[1]!==t.numHeads||h.dims[3]!==M)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[0]!==m||p.dims[1]!==t.numHeads||p.dims[3]!==M)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[2]!==p.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(p.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');S=h.dims[2],x=h.dims[2]}else if(h&&j.size(h.dims)||p&&j.size(p.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,v=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==M)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');k=5,v=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==M)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');k=0,v=i.dims[2]}}else{if(n.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(n.dims[2]!==t.numHeads||n.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');k=3}if(l&&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 $=S+v,P=0;if(u&&j.size(u.dims)>0){P=8;let W=u.dims;throw W.length===1?W[0]===m?P=1:W[0]===3*m+2&&(P=3):W.length===2&&W[0]===m&&W[1]===$&&(P=5),P===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let I=!1,B=w;if(o&&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(v!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');B=o.dims[2]}else{if(v!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');B=o.dims[1]*o.dims[3],I=!0}}let q=!1;if(u&&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:S,kvSequenceLength:v,totalSequenceLength:$,maxSequenceLength:x,inputHiddenSize:0,hiddenSize:w,vHiddenSize:B,headSize:M,vHeadSize:Math.floor(B/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:P,scale:t.scale,broadcastResPosBias:q,passPastInKv:I,qkvFormat:k}},jd=e=>E({...e}),Sa=E({perm:[0,2,1,3]}),Qd=(e,t,n,i,o,l,u)=>{let c=[i,o,l],h=j.size(c),p=[{type:12,data:h},{type:12,data:u},{type:12,data:l}],m=g=>{let w=le("qkv_with_bias",t.dataType,c),v=F("qkv",t.dataType,c),S=F("bias",n.dataType,c),x=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`
|
|
1723
|
+
${g.registerUniforms(x).declareVariables(v,S,w)}
|
|
1724
|
+
${g.mainStart()}
|
|
1725
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1726
|
+
let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
|
|
1727
|
+
|
|
1728
|
+
qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];
|
|
1729
|
+
}`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:c,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p}),getShaderSource:m},{inputs:[t,n],outputs:[-1]})[0]},jn=(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=Qd(e,l,u,t,i,n*o,c),h=h.reshape([t,i,n,o]),n===1||i===1?h:e.compute(ht(h,Sa.perm),{inputs:[h],outputs:[-1]})[0]}else return l.dims.length===3&&(h=l.reshape([t,i,n,o])),n===1||i===1?h:e.compute(ht(h,Sa.perm),{inputs:[h],outputs:[-1]})[0]},Xd=(e,t)=>{let n=Kd(e.inputs,t),i=e.inputs[0],o=Vt(e.inputs,1),l=Vt(e.inputs,2),u=Vt(e.inputs,3),c=Vt(e.inputs,4),h=Vt(e.inputs,5),p=Vt(e.inputs,6),m=Vt(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=jn(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,i,u,0);if(g)return Gn(e,w,o,l,c,void 0,p,m,h,n);if(!o||!l)throw new Error("key and value must be provided");let v=jn(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,o,u,n.hiddenSize),S=jn(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,l,u,2*n.hiddenSize);Gn(e,w,v,S,c,void 0,p,m,h,n)}}),Jd,Zd,ec,tc,Ta,rc,sc,nc=b(()=>{Ie(),ke(),A(),ye(),Jd=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Zd=(e,t)=>{let n=[],i=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>n.push(Number(o))),i=n.length),E({numOutputs:i,axis:t.axis,splitSizes:n})},ec=e=>`
|
|
1730
|
+
fn calculateOutputIndex(index: u32) -> u32 {
|
|
1731
|
+
for (var i: u32 = 0u; i < ${e}u; i += 1u ) {
|
|
1732
|
+
if (index < ${Q("uniforms.size_in_split_axis","i",e)}) {
|
|
1733
|
+
return i;
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
return ${e}u;
|
|
1737
|
+
}`,tc=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`
|
|
1738
|
+
fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) {
|
|
1739
|
+
${n.join(`
|
|
1740
|
+
`)}
|
|
1741
|
+
}`},Ta=(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=F("input",o,n.length),h=new Array(t.numOutputs),p=[],m=[],g=0,w=[{type:12,data:i}];for(let S=0;S<t.numOutputs;S++){g+=t.splitSizes[S],h[S]=g;let x=n.slice();x[l]=t.splitSizes[S],m.push(x),u[S]=le(`output${S}`,o,x.length),p.push({dims:m[S],dataType:e[0].dataType})}w.push({type:12,data:h},...L(n,...m));let v=S=>`
|
|
1742
|
+
${S.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",h.length).declareVariables(c,...u)}
|
|
1743
|
+
${ec(h.length)}
|
|
1744
|
+
${tc(u)}
|
|
1745
|
+
|
|
1746
|
+
${S.mainStart()}
|
|
1747
|
+
${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}
|
|
1748
|
+
|
|
1749
|
+
var indices = ${c.offsetToIndices("global_idx")};
|
|
1750
|
+
var index = ${c.indicesGet("indices",l)};
|
|
1751
|
+
let output_number = calculateOutputIndex(index);
|
|
1752
|
+
if (output_number != 0) {
|
|
1753
|
+
index -= ${Q("uniforms.size_in_split_axis","output_number - 1u",h.length)};
|
|
1754
|
+
${c.indicesSet("indices",l,"index")};
|
|
1755
|
+
}
|
|
1756
|
+
writeBufferData(output_number, indices, global_idx);
|
|
1757
|
+
}`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:v,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(i/64)},programUniforms:w})}},rc=(e,t)=>{Jd(e.inputs);let n=e.inputs.length===1?t:Zd(e.inputs,t);e.compute(Ta(e.inputs,n),{inputs:[0]})},sc=e=>{let t=e.axis,n=e.splitSizes,i=e.numOutputs<0?n.length:e.numOutputs;if(i!==n.length)throw new Error("numOutputs and splitSizes length must be equal");return E({axis:t,numOutputs:i,splitSizes:n})}}),ic,xi,ac,oc=b(()=>{Ie(),ke(),A(),ye(),ic=(e,t)=>{let[n,i,o,l]=e,{numHeads:u,rotaryEmbeddingDim:c}=t;if(n.dims.length!==3&&n.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!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],p=n.dims[n.dims.length-2],m=o.dims[0],g=j.sizeFromDimension(n.dims,1)/p,w=c===0?o.dims[1]*2:g/u;if(c>w)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(i.dims.length===2){if(h!==i.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${i.dims[0]}`);if(p!==i.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${i.dims[1]}`)}if(p>m)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported");if(w/2!==o.dims[1]&&c/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`)},xi=(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],p=c/h,m=e[2].dims[1],g=o===0?m*2:p/i,w=new Array(u,h,p/g,g-m),v=j.computeStrides(w),S=[{type:1,data:l},{type:12,data:w},{type:12,data:v},...e[0].dims.length===3?new Array({type:12,data:[c,p,g,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[c,g,h*g,1]}):[],...L(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],x=M=>{let k=F("input",e[0].dataType,e[0].dims.length),$=F("position_ids",e[1].dataType,e[1].dims.length),P=F("cos_cache",e[2].dataType,e[2].dims.length),I=F("sin_cache",e[3].dataType,e[3].dims.length),B=le("output",e[0].dataType,e[0].dims.length);return M.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:w.length},{name:"global_strides",type:"u32",length:v.length},{name:"input_output_strides",type:"u32",length:v.length}]),`
|
|
1758
|
+
${M.declareVariables(k,$,P,I,B)}
|
|
1759
|
+
|
|
1760
|
+
${M.mainStart(D)}
|
|
1761
|
+
let half_rotary_emb_dim = uniforms.${P.name}_shape[1];
|
|
1762
|
+
let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;
|
|
1763
|
+
let size = uniforms.global_shape[0] * uniforms.global_strides[0];
|
|
1764
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("size")}
|
|
1765
|
+
|
|
1766
|
+
if (bsnh[3] < half_rotary_emb_dim) {
|
|
1767
|
+
let position_ids_idx =
|
|
1768
|
+
${$.broadcastedIndicesToOffset("bsnh.xy",le("",$.type.tensor,2))};
|
|
1769
|
+
let position_id =
|
|
1770
|
+
u32(${$.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);
|
|
1771
|
+
let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${n});
|
|
1772
|
+
let j = i + select(half_rotary_emb_dim, 1, ${n});
|
|
1773
|
+
let re = ${k.getByOffset("i")} * ${P.get("position_id","bsnh[3]")} -
|
|
1774
|
+
${k.getByOffset("j")} * ${I.get("position_id","bsnh[3]")};
|
|
1775
|
+
${B.setByOffset("i","re")}
|
|
1776
|
+
let im = ${k.getByOffset("i")} * ${I.get("position_id","bsnh[3]")} +
|
|
1777
|
+
${k.getByOffset("j")} * ${P.get("position_id","bsnh[3]")};
|
|
1778
|
+
${B.setByOffset("j","im")}
|
|
1779
|
+
} else {
|
|
1780
|
+
let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
|
|
1781
|
+
${B.setByOffset("k",k.getByOffset("k"))}
|
|
1782
|
+
}
|
|
1783
|
+
}`};return{name:"RotaryEmbedding",shaderCache:{hint:E({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(j.size(w)/D)},programUniforms:S})}},ac=(e,t)=>{ic(e.inputs,t),e.compute(xi(e.inputs,t))}}),lc,uc,Ea,dc,cc,Bm=b(()=>{A(),Ie(),Zi(),Yd(),nc(),Ue(),oc(),ye(),lc=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let n=e[0],i=e[1],o=e[2],l=e[3],u=e[4];if(t.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=n.dims[0],h=n.dims[1],p=n.dims.length===3?n.dims[2]:t.numHeads*n.dims[4],m=h,g=0,w=!i||i.dims.length===0,v=Math.floor(w?p/(t.numHeads+2*t.kvNumHeads):p/t.numHeads);w&&(p=v*t.numHeads);let S=l&&l.dims.length!==0,x=u&&u.dims.length!==0;if(S&&l.dims.length===4&&l.dims[0]===c&&l.dims[1]!==t.kvNumHeads&&l.dims[2]===t.kvNumHeads&&l.dims[3]===v)throw new Error("BSNH pastKey/pastValue is not supported");if(S&&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(S||x)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let M=1;if(i&&i.dims.length>0){if(n.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(i.dims.length<3||i.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(i.dims.length===3){if(n.dims[2]%i.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');m=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==v)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');m=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==v)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');m=i.dims[2]}}else{if(n.dims.length!==3&&n.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(n.dims.length===5&&(n.dims[2]!==t.numHeads||n.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');M=3}let k=0,$=!1,P=t.kvNumHeads?v*t.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(m!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');P=o.dims[2]}else{if(m!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');P=o.dims[1]*o.dims[3],$=!0}}let I=e.length>4?e[5]:void 0;if(I){if(I.dims.length===0)throw new Error("seqlens_k must be at least 1D, got scalar.");let B=I.dims.reduce((q,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:p,vHiddenSize:P,headSize:v,vHeadSize:Math.floor(P/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:k,scale:t.scale,broadcastResPosBias:!1,passPastInKv:$,qkvFormat:M}},uc=E({perm:[0,2,1,3]}),Ea=(e,t,n)=>{let i=t,o=n.kvNumHeads;return t.dims.length===3&&n.kvSequenceLength!==0&&(i=t.reshape([n.batchSize,n.kvSequenceLength,o,n.headSize]),i=e.compute(ht(i,uc.perm),{inputs:[i],outputs:[-1]})[0]),i},dc=(e,t,n,i)=>{let o=7,l=["type","type"],u=[e*t],c=e*t,h=[{type:12,data:c},{type:12,data:t},{type:12,data:e}],p=m=>{let g=F("seq_lens",n.dataType,n.dims),w=F("total_seq_lens",i.dataType,i.dims),v=le("pos_ids",o,u),S=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return`
|
|
1784
|
+
${m.registerUniforms(S).declareVariables(g,w,v)}
|
|
1785
|
+
${m.mainStart()}
|
|
1786
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1787
|
+
let total_sequence_length = u32(${w.getByOffset("0")});
|
|
1788
|
+
let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length;
|
|
1789
|
+
let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length;
|
|
1790
|
+
let batch_idx = global_idx / uniforms.sequence_length;
|
|
1791
|
+
let sequence_idx = i32(global_idx % uniforms.sequence_length);
|
|
1792
|
+
var pos_id: i32 = 0;
|
|
1793
|
+
let seqlen = ${g.getByOffset("batch_idx")};
|
|
1794
|
+
let total_seqlen = seqlen + 1;
|
|
1795
|
+
if (is_first_prompt) {
|
|
1796
|
+
if (sequence_idx < total_seqlen) {
|
|
1797
|
+
pos_id = sequence_idx;
|
|
1798
|
+
} else {
|
|
1799
|
+
pos_id = 1;
|
|
1800
|
+
}
|
|
1801
|
+
${v.setByOffset("global_idx","pos_id")}
|
|
1802
|
+
} else if (is_subsequent_prompt) {
|
|
1803
|
+
let past_seqlen = total_seqlen - i32(uniforms.sequence_length);
|
|
1804
|
+
if (past_seqlen + sequence_idx < total_seqlen) {
|
|
1805
|
+
pos_id = past_seqlen + sequence_idx;
|
|
1806
|
+
} else {
|
|
1807
|
+
pos_id = 1;
|
|
1808
|
+
}
|
|
1809
|
+
${v.setByOffset("global_idx","pos_id")}
|
|
1810
|
+
} else if (global_idx < uniforms.batch_size) {
|
|
1811
|
+
${v.setByOffset("global_idx","seqlen")}
|
|
1812
|
+
};
|
|
1813
|
+
}
|
|
1814
|
+
`};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:h}),getShaderSource:p}},cc=(e,t)=>{let n=lc(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let i=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,l=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,u=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,c=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,h=e.inputs.length>4?e.inputs[5]:void 0,p=e.inputs.length>5?e.inputs[6]:void 0,m=n.kvNumHeads?n.kvNumHeads:n.numHeads,g=E({axis:2,numOutputs:3,splitSizes:[n.numHeads*n.headSize,m*n.headSize,m*n.headSize]}),[w,v,S]=!o&&!l?e.compute(Ta([i],g),{inputs:[i],outputs:[-1,-1,-1]}):[i,o,l],x,M;if(t.doRotary){let I=e.compute(dc(n.batchSize,n.sequenceLength,h,p),{inputs:[h,p],outputs:[-1]})[0],B=e.inputs[7],q=e.inputs[8],W=E({interleaved:t.rotaryInterleaved!==0,numHeads:n.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),ee=[w,I,B,q],ue=[-1];x=e.compute(xi(ee,W),{inputs:ee,outputs:ue})[0],ee.splice(0,1,v);let _e=E({interleaved:t.rotaryInterleaved!==0,numHeads:n.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});M=e.compute(xi(ee,_e),{inputs:ee,outputs:ue})[0]}let k=jn(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,t.doRotary?x:w,void 0,0),$=Ea(e,t.doRotary?M:v,n),P=Ea(e,S,n);Gn(e,k,$,P,void 0,void 0,u,c,void 0,n,h,p)}}),$a,hc,pc,fc,Nm=b(()=>{Ie(),ke(),Ue(),ye(),$a=(e,t,n,i,o,l,u,c)=>{let h=V(l),p=h===1?"f32":`vec${h}f`,m=h===1?"vec2f":`mat2x${h}f`,g=o*u,w=64;g===1&&(w=256);let v=[o,u,l/h],S=[o,u,2],x=["rank","type","type"],M=[];M.push(...L(v,S));let k=$=>{let P=F("x",t.dataType,3,h),I=F("scale",n.dataType,n.dims),B=F("bias",i.dataType,i.dims),q=le("output",1,3,2),W=[P,I,B,q];return`
|
|
1815
|
+
var<workgroup> workgroup_shared : array<${m}, ${w}>;
|
|
1816
|
+
const workgroup_size = ${w}u;
|
|
1817
|
+
${$.declareVariables(...W)}
|
|
1818
|
+
${$.mainStart(w)}
|
|
1819
|
+
let batch = workgroup_index / uniforms.x_shape[1];
|
|
1820
|
+
let channel = workgroup_index % uniforms.x_shape[1];
|
|
1821
|
+
let hight = uniforms.x_shape[2];
|
|
1822
|
+
// initialize workgroup memory
|
|
1823
|
+
var sum = ${p}(0);
|
|
1824
|
+
var squared_sum = ${p}(0);
|
|
1825
|
+
for (var h = local_idx; h < hight; h += workgroup_size) {
|
|
1826
|
+
let value = ${p}(${P.get("batch","channel","h")});
|
|
1827
|
+
sum += value;
|
|
1828
|
+
squared_sum += value * value;
|
|
1829
|
+
}
|
|
1830
|
+
workgroup_shared[local_idx] = ${m}(sum, squared_sum);
|
|
1831
|
+
workgroupBarrier();
|
|
1832
|
+
|
|
1833
|
+
for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {
|
|
1834
|
+
if (local_idx < currSize) {
|
|
1835
|
+
workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];
|
|
1836
|
+
}
|
|
1837
|
+
workgroupBarrier();
|
|
1838
|
+
}
|
|
1839
|
+
if (local_idx == 0) {
|
|
1840
|
+
let sum_final = ${Z("workgroup_shared[0][0]",h)} / f32(hight * ${h});
|
|
1841
|
+
let squared_sum_final = ${Z("workgroup_shared[0][1]",h)} / f32(hight * ${h});
|
|
1842
|
+
|
|
1843
|
+
let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${c}));
|
|
1844
|
+
let channel_scale = inv_std_dev * f32(scale[channel]);
|
|
1845
|
+
let channel_shift = f32(bias[channel]) - sum_final * channel_scale;
|
|
1846
|
+
output[workgroup_index] = vec2f(channel_scale, channel_shift);
|
|
1847
|
+
}
|
|
1848
|
+
}`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${h};${c};${w}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:S,dataType:1}],dispatchGroup:{x:g},programUniforms:M}),getShaderSource:k},{inputs:[t,n,i],outputs:[-1]})[0]},hc=(e,t,n)=>{let i=t[0].dims,o=i,l=2,u=i[0],c=i[1],h=j.sizeFromDimension(i,l),p=V(h),m=j.size(o)/p,g=$a(e,t[0],t[1],t[2],u,h,c,n.epsilon),w=[u,c,h/p],v=[u,c],S=["type","none"],x=M=>{let k=F("x",t[0].dataType,w.length,p),$=F("scale_shift",1,v.length,2),P=le("output",t[0].dataType,w.length,p),I=[k,$,P];return`
|
|
1849
|
+
${M.registerUniform("output_size","u32").declareVariables(...I)}
|
|
1850
|
+
${M.mainStart()}
|
|
1851
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1852
|
+
let outputIndices = ${P.offsetToIndices("global_idx")};
|
|
1853
|
+
let batch = outputIndices[0];
|
|
1854
|
+
let channel = outputIndices[1];
|
|
1855
|
+
let scale_shift = ${$.getByIndices("vec2<u32>(batch, channel)")};
|
|
1856
|
+
let value = ${k.getByOffset("global_idx")} * ${P.type.value}(scale_shift.x) + ${P.type.value}(scale_shift.y);
|
|
1857
|
+
${P.setByOffset("global_idx","value")};
|
|
1858
|
+
}`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${p}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...L(w,v,w)]}),getShaderSource:x},{inputs:[t[0],g]})},pc=(e,t,n)=>{let i=t[0].dims,o=i,l=i[0],u=i[i.length-1],c=j.sizeFromDimension(i,1)/u,h=V(u),p=j.size(o)/h,m=[{type:12,data:c},{type:12,data:Math.floor(u/h)}],g=["type","type"],w=!1,v=[0,i.length-1];for(let k=0;k<i.length-2;k++)w=w||i[k+1]!==1,v.push(k+1);w=w&&i[i.length-1]!==1;let S=w?e.compute(ht(e.inputs[0],v),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:i.length},(k,$)=>i[v[$]])),x=$a(e,S,t[1],t[2],l,c,u,n.epsilon),M=k=>{let $=G(t[0].dataType),P=h===1?"vec2f":`mat${h}x2f`,I=W=>{let ee=W===0?"x":"y",ue=h===1?"f32":`vec${h}f`;switch(h){case 1:return`${$}(${ue}(scale.${ee}))`;case 2:return`vec2<${$}>(${ue}(scale[0].${ee}, scale[1].${ee}))`;case 4:return`vec4<${$}>(${ue}(scale[0].${ee}, scale[1].${ee}, scale[2].${ee}, scale[3].${ee}))`;default:throw new Error(`Not supported compoents ${h}`)}},B=F("input",t[0].dataType,t[0].dims,h),q=le("output",t[0].dataType,o,h);return`
|
|
1859
|
+
@group(0) @binding(0) var<storage, read> input : array<${B.type.storage}>;
|
|
1860
|
+
@group(0) @binding(1) var<storage, read> scale_input : array<${P}>;
|
|
1861
|
+
@group(0) @binding(2) var<storage, read_write> output : array<${q.type.storage}>;
|
|
1862
|
+
struct Uniforms {H: u32, C : u32};
|
|
1863
|
+
@group(0) @binding(3) var<uniform> uniforms: Uniforms;
|
|
1864
|
+
|
|
1865
|
+
${k.mainStart()}
|
|
1866
|
+
let current_image_number = global_idx / (uniforms.C * uniforms.H);
|
|
1867
|
+
let current_channel_number = global_idx % uniforms.C;
|
|
1868
|
+
|
|
1869
|
+
let scale_offset = current_image_number * uniforms.C + current_channel_number;
|
|
1870
|
+
let scale = scale_input[scale_offset];
|
|
1871
|
+
output[global_idx] = fma(input[global_idx], ${I(0)}, ${I(1)});
|
|
1872
|
+
}`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${h}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:M},{inputs:[t[0],x]})},fc=(e,t)=>{t.format==="NHWC"?pc(e,e.inputs,t):hc(e,e.inputs,t)}}),mc,gc,yc,Um=b(()=>{Ie(),ke(),ye(),mc=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},gc=(e,t,n)=>{let i=t.simplified,o=e[0].dims,l=e[1],u=!i&&e[2],c=o,h=j.normalizeAxis(t.axis,o.length),p=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}.
|
|
1873
|
+
Size of scale and bias (if provided) must match this.
|
|
1874
|
+
Got scale size of ${g} and bias size of ${w}`);let v=[];for(let B=0;B<o.length;++B)B<h?v.push(o[B]):v.push(1);let S=V(m),x=["type","type"],M=[{type:12,data:p},{type:1,data:m},{type:12,data:Math.floor(m/S)},{type:1,data:t.epsilon}];u&&x.push("type");let k=n>1,$=n>2,P=B=>{let q=G(e[0].dataType),W=[F("x",e[0].dataType,e[0].dims,S),F("scale",l.dataType,l.dims,S)];u&&W.push(F("bias",u.dataType,u.dims,S)),W.push(le("output",e[0].dataType,c,S)),k&&W.push(le("mean_data_output",1,v)),$&&W.push(le("inv_std_output",1,v));let ee=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`
|
|
1875
|
+
${B.registerUniforms(ee).declareVariables(...W)}
|
|
1876
|
+
${B.mainStart()}
|
|
1877
|
+
${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}
|
|
1878
|
+
let offset = global_idx * uniforms.norm_size_vectorized;
|
|
1879
|
+
var mean_vector = ${te("f32",S)};
|
|
1880
|
+
var mean_square_vector = ${te("f32",S)};
|
|
1881
|
+
|
|
1882
|
+
for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {
|
|
1883
|
+
let value = ${ne(q,S,"x[h + offset]")};
|
|
1884
|
+
mean_vector += value;
|
|
1885
|
+
mean_square_vector += value * value;
|
|
1886
|
+
}
|
|
1887
|
+
let mean = ${Z("mean_vector",S)} / uniforms.norm_size;
|
|
1888
|
+
let inv_std_dev = inverseSqrt(${Z("mean_square_vector",S)} / uniforms.norm_size ${i?"":"- mean * mean"} + uniforms.epsilon);
|
|
1889
|
+
|
|
1890
|
+
for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {
|
|
1891
|
+
let f32input = ${ne(q,S,"x[j + offset]")};
|
|
1892
|
+
let f32scale = ${ne(q,S,"scale[j]")};
|
|
1893
|
+
output[j + offset] = ${W[0].type.value}((f32input ${i?"":"- mean"}) * inv_std_dev * f32scale
|
|
1894
|
+
${u?`+ ${ne(q,S,"bias[j]")}`:""}
|
|
1895
|
+
);
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
${k?"mean_data_output[global_idx] = mean":""};
|
|
1899
|
+
${$?"inv_std_output[global_idx] = inv_std_dev":""};
|
|
1900
|
+
}`},I=[{dims:c,dataType:e[0].dataType}];return k&&I.push({dims:v,dataType:1}),$&&I.push({dims:v,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${S};${n};${i}`,inputDependencies:x},getRunData:()=>({outputs:I,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:M}),getShaderSource:P}},yc=(e,t)=>{mc(e.inputs),e.compute(gc(e.inputs,t,e.outputCount))}}),wc,vc,Fm=b(()=>{ke(),oa(),ca(),wc=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},vc=e=>{wc(e.inputs);let t=Cr.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let n=t[t.length-1],i=e.inputs[0].dims[e.inputs[0].dims.length-1];if(n<8&&i<8)e.compute(aa(e.inputs,{activation:""},t));else{let o=t[t.length-2],l=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]),p=[1,l,n],m=[c,h];e.compute(Si(m,{activation:""},t,p),{inputs:m})}else e.compute(Si(e.inputs,{activation:""},t))}}}),_c,bc,Sc,Tc,Ec,Vm=b(()=>{Ie(),ke(),A(),ye(),_c=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let n=e[0],i=n.dims.length;if(n.dims[i-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),l=t.blockSize/8*t.bits,u=e[1];if(!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,p=t.n*(t.bits===8?o:Math.floor((o*t.bits+7)/8));if(j.size(h)!==p)throw new Error("zeroPoints input size error.")}},bc=(e,t)=>{let n=e[0].dims,i=n.length,o=n[i-2],l=t.k,u=t.n,c=n.slice(0,i-2),h=j.size(c),p=e[1].dims[2]/4,m=e[0].dataType,g=V(t.k),w=V(p),v=V(u),S=c.concat([o,u]),x=o>1&&u/v%2===0?2:1,M=j.size(S)/v/x,k=64,$=[],P=[h,o,l/g],I=j.convertShape(e[1].dims).slice();I.splice(-1,1,p/w),$.push(...L(P)),$.push(...L(I)),$.push(...L(e[2].dims)),e.length===4&&$.push(...L(j.convertShape(e[3].dims)));let B=[h,o,u/v];$.push(...L(B));let q=W=>{let ee=P.length,ue=F("a",e[0].dataType,ee,g),_e=F("b",12,I.length,w),Fe=F("scales",e[2].dataType,e[2].dims.length),Re=[ue,_e,Fe],Me=e.length===4?F("zero_points",12,e[3].dims.length):void 0;Me&&Re.push(Me);let Xe=B.length,ge=le("output",e[0].dataType,Xe,v),$e=G(e[0].dataType),Le=(()=>{switch(g){case 1:return`array<${$e}, 8>`;case 2:return`mat4x2<${$e}>`;case 4:return`mat2x4<${$e}>`;default:throw new Error(`${g}-component is not supported.`)}})(),Ve=Math.floor(32/t.bits),De=Math.floor(Ve/8),He=()=>{let Ae="";for(let Ee=0;Ee<De;Ee++){let Dt=Ee*t.bits*4,Xt=Dt+t.bits;Ae+=`
|
|
1901
|
+
// reuse a data (pass ${Ee})
|
|
1902
|
+
var input_offset${Ee>0?Ee:""} = ${Ee===0?ue.indicesToOffset(`${ue.type.indices}(batch, row, word_offset)`):"input_offset"};
|
|
1903
|
+
var a_data${Ee>0?Ee:""}: ${Le};
|
|
1904
|
+
for (var j${Ee>0?Ee:""}: u32 = 0; j${Ee>0?Ee:""} < ${8/g}; j${Ee>0?Ee:""}++) {
|
|
1905
|
+
a_data${Ee>0?Ee:""}[j${Ee>0?Ee:""}] = ${ue.getByOffset(`input_offset${Ee>0?Ee:""}`)};
|
|
1906
|
+
input_offset${Ee>0?Ee:""}++;
|
|
1907
|
+
}
|
|
1908
|
+
`;for(let _t=0;_t<v*x;_t++)Ae+=`
|
|
1909
|
+
b_value = ${w===1?`b${_t}_data`:`b${_t}_data[i]`};
|
|
1910
|
+
${t.bits===2?`{
|
|
1911
|
+
let half_word = b_value >> ${Ee*16}u;
|
|
1912
|
+
let byte_lo = half_word & 0xFFu;
|
|
1913
|
+
let byte_hi = (half_word >> 8u) & 0xFFu;
|
|
1914
|
+
let spread_word = (byte_lo & 0xFu) | ((byte_lo >> 4u) << 8u) | ((byte_hi & 0xFu) << 16u) | ((byte_hi >> 4u) << 24u);
|
|
1915
|
+
b_value_lower = unpack4xU8(spread_word & b_mask);
|
|
1916
|
+
b_value_upper = unpack4xU8((spread_word >> 2u) & b_mask);
|
|
1917
|
+
}`:`b_value_lower = unpack4xU8((b_value >> ${Dt}u) & b_mask);
|
|
1918
|
+
b_value_upper = unpack4xU8((b_value >> ${Xt}u) & b_mask);`}
|
|
1919
|
+
b_quantized_values = ${Le}(${Array.from({length:4},(Yt,nt)=>`${$e}(b_value_lower[${nt}]), ${$e}(b_value_upper[${nt}])`).join(", ")});
|
|
1920
|
+
b_dequantized_values = ${g===1?`${Le}(${Array.from({length:8},(Yt,nt)=>`(b_quantized_values[${nt}] - ${Me?`zero_point${_t}`:"zero_point"}) * scale${_t}`).join(", ")});`:`(b_quantized_values - ${Le}(${Array(8).fill(`${Me?`zero_point${_t}`:"zero_point"}`).join(",")})) * scale${_t};`};
|
|
1921
|
+
workgroup_shared[local_id.x * ${x} + ${Math.floor(_t/v)}]${v>1?`[${_t%v}]`:""} += ${Array.from({length:8/g},(Yt,nt)=>`${g===1?`a_data${Ee>0?Ee:""}[${nt}] * b_dequantized_values[${nt}]`:`dot(a_data${Ee>0?Ee:""}[${nt}], b_dequantized_values[${nt}])`}`).join(" + ")};
|
|
1922
|
+
`}return Ae},ae=()=>{let Ae=`
|
|
1923
|
+
var col_index = col * ${v};
|
|
1924
|
+
${Me?`
|
|
1925
|
+
let zero_point_values_per_byte: u32 = ${Math.floor(8/t.bits)}u;
|
|
1926
|
+
let zero_point_bytes_per_col = (nBlocksPerCol + zero_point_values_per_byte - 1u) / zero_point_values_per_byte;
|
|
1927
|
+
var zero_point_byte_count: u32;
|
|
1928
|
+
var zero_point_word_index: u32;
|
|
1929
|
+
var zero_point_byte_offset: u32;
|
|
1930
|
+
let zero_point_sub_offset: u32 = block % zero_point_values_per_byte;
|
|
1931
|
+
var zero_point_bits_offset: u32;
|
|
1932
|
+
var zero_point_word: u32;`:`
|
|
1933
|
+
// The default zero point is ${Math.pow(2,t.bits-1)} for unsigned ${t.bits}-bit quantization.
|
|
1934
|
+
let zero_point = ${$e}(${Math.pow(2,t.bits-1).toFixed(1)});`}
|
|
1935
|
+
`;for(let Ee=0;Ee<v*x;Ee++)Ae+=`
|
|
1936
|
+
let scale${Ee} = ${Fe.getByOffset("col_index * nBlocksPerCol + block")};
|
|
1937
|
+
${Me?`
|
|
1938
|
+
zero_point_byte_count = col_index * zero_point_bytes_per_col + (block / zero_point_values_per_byte);
|
|
1939
|
+
zero_point_word_index = zero_point_byte_count >> 0x2u;
|
|
1940
|
+
zero_point_byte_offset = zero_point_byte_count & 0x3u;
|
|
1941
|
+
zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_sub_offset * ${t.bits}u);
|
|
1942
|
+
zero_point_word = ${Me.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
1943
|
+
let zero_point${Ee} = ${$e}((zero_point_word) & ${t.bits===2?"0x3u":"0xFu"});`:""}
|
|
1944
|
+
col_index += 1;`;return Ae},Oe=()=>{let Ae=`col_index = col * ${v};`;for(let Ee=0;Ee<v*x;Ee++)Ae+=`
|
|
1945
|
+
let b${Ee}_data = ${_e.getByIndices(`${_e.type.indices}(col_index, block, word)`)};
|
|
1946
|
+
col_index += 1;`;return Ae+=`
|
|
1947
|
+
var b_value: u32;
|
|
1948
|
+
let b_mask: u32 = ${t.bits===2?"0x03030303u":"0x0F0F0F0Fu"};
|
|
1949
|
+
var b_value_lower: vec4<u32>;
|
|
1950
|
+
var b_value_upper: vec4<u32>;
|
|
1951
|
+
var b_quantized_values: ${Le};
|
|
1952
|
+
var b_dequantized_values: ${Le};`,Ae};return`
|
|
1953
|
+
var<workgroup> workgroup_shared: array<${ge.type.value}, ${x*k}>;
|
|
1954
|
+
${W.declareVariables(...Re,ge)}
|
|
1955
|
+
${W.mainStart([k,1,1])}
|
|
1956
|
+
let output_indices = ${ge.offsetToIndices(`(global_idx / ${k}) * ${x}`)};
|
|
1957
|
+
let col = output_indices[2];
|
|
1958
|
+
let row = output_indices[1];
|
|
1959
|
+
let batch = output_indices[0];
|
|
1960
|
+
let nBlocksPerCol = uniforms.b_shape[1];
|
|
1961
|
+
|
|
1962
|
+
for (var block = local_id.x; block < nBlocksPerCol; block += ${k}) {
|
|
1963
|
+
//process one block
|
|
1964
|
+
var word_offset: u32 = block * ${t.blockSize/g};
|
|
1965
|
+
${ae()}
|
|
1966
|
+
for (var word: u32 = 0; word < ${p}; word += ${w}) {
|
|
1967
|
+
${Oe()}
|
|
1968
|
+
for (var i: u32 = 0; i < ${w}; i++) {
|
|
1969
|
+
${He()}
|
|
1970
|
+
word_offset += ${Ve/g};
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
workgroupBarrier();
|
|
1975
|
+
|
|
1976
|
+
if (local_id.x < ${x}) {
|
|
1977
|
+
var output_value: ${ge.type.value} = ${ge.type.value}(0);
|
|
1978
|
+
var workgroup_shared_offset: u32 = local_id.x;
|
|
1979
|
+
for (var b: u32 = 0u; b < ${k}u; b++) {
|
|
1980
|
+
output_value += workgroup_shared[workgroup_shared_offset];
|
|
1981
|
+
workgroup_shared_offset += ${x};
|
|
1982
|
+
}
|
|
1983
|
+
${ge.setByIndices(`${ge.type.indices}(batch, row, col + local_id.x)`,"output_value")};
|
|
1984
|
+
}
|
|
1985
|
+
}`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${g};${w};${v};${x};${k}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:S,dataType:m}],dispatchGroup:{x:M},programUniforms:$}),getShaderSource:q}},Sc=(e,t)=>{let n=e[0].dims,i=n.length,o=n[i-2],l=t.k,u=t.n,c=n.slice(0,i-2),h=j.size(c),p=e[1].dims[2]/4,m=e[0].dataType,g=V(t.k),w=V(p),v=c.concat([o,u]),S=128,x=u%8===0?8:u%4===0?4:1,M=S/x,k=Math.floor(32/t.bits),$=M*w*k,P=$/g,I=$/t.blockSize,B=j.size(v)/x,q=[],W=[h,o,l/g],ee=j.convertShape(e[1].dims).slice();ee.splice(-1,1,p/w),q.push(...L(W)),q.push(...L(ee)),q.push(...L(e[2].dims)),e.length===4&&q.push(...L(j.convertShape(e[3].dims)));let ue=[h,o,u];q.push(...L(ue));let _e=Fe=>{let Re=W.length,Me=F("a",e[0].dataType,Re,g),Xe=F("b",12,ee.length,w),ge=F("scales",e[2].dataType,e[2].dims.length),$e=[Me,Xe,ge],Le=e.length===4?F("zero_points",12,e[3].dims.length):void 0;Le&&$e.push(Le);let Ve=ue.length,De=le("output",e[0].dataType,Ve),He=G(e[0].dataType),ae=()=>{switch(g){case 1:return`
|
|
1986
|
+
let a_data0 = vec4<${He}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);
|
|
1987
|
+
let a_data1 = vec4<${He}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`
|
|
1988
|
+
let a_data0 = vec4<${He}>(sub_a[word_offset], sub_a[word_offset + 1]);
|
|
1989
|
+
let a_data1 = vec4<${He}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`
|
|
1990
|
+
let a_data0 = sub_a[word_offset];
|
|
1991
|
+
let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${g}-component is not supported.`)}};return`
|
|
1992
|
+
var<workgroup> sub_a: array<${Me.type.value}, ${P}>;
|
|
1993
|
+
var<workgroup> inter_results: array<array<${De.type.value}, ${M}>, ${x}>;
|
|
1994
|
+
${Fe.declareVariables(...$e,De)}
|
|
1995
|
+
${Fe.mainStart([M,x,1])}
|
|
1996
|
+
let output_indices = ${De.offsetToIndices(`workgroup_index * ${x}`)};
|
|
1997
|
+
let col = output_indices[2];
|
|
1998
|
+
let row = output_indices[1];
|
|
1999
|
+
let batch = output_indices[0];
|
|
2000
|
+
let n_blocks_per_col = uniforms.b_shape[1];
|
|
2001
|
+
let num_tiles = (n_blocks_per_col - 1) / ${I} + 1;
|
|
2002
|
+
|
|
2003
|
+
// Loop over shared dimension.
|
|
2004
|
+
for (var tile: u32 = 0; tile < num_tiles; tile += 1) {
|
|
2005
|
+
let a_col_start = tile * ${P};
|
|
2006
|
+
// load one tile A data into shared memory.
|
|
2007
|
+
for (var a_offset = local_idx; a_offset < ${P}; a_offset += ${S})
|
|
2008
|
+
{
|
|
2009
|
+
let a_col = a_col_start + a_offset;
|
|
2010
|
+
if (a_col < uniforms.a_shape[2])
|
|
2011
|
+
{
|
|
2012
|
+
sub_a[a_offset] = ${Me.getByIndices(`${Me.type.indices}(batch, row, a_col)`)};
|
|
2013
|
+
} else {
|
|
2014
|
+
sub_a[a_offset] = ${Me.type.value}(0);
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
workgroupBarrier();
|
|
2018
|
+
|
|
2019
|
+
// each thread process one block
|
|
2020
|
+
let b_row = col + local_id.y;
|
|
2021
|
+
let block = tile * ${I} + local_id.x;
|
|
2022
|
+
${Le?`
|
|
2023
|
+
let zero_point_values_per_byte: u32 = ${Math.floor(8/t.bits)}u;
|
|
2024
|
+
let zero_point_bytes_per_col = (n_blocks_per_col + zero_point_values_per_byte - 1u) / zero_point_values_per_byte;
|
|
2025
|
+
let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block / zero_point_values_per_byte);
|
|
2026
|
+
let zero_point_word_index = zero_point_byte_count >> 0x2u;
|
|
2027
|
+
let zero_point_byte_offset = zero_point_byte_count & 0x3u;
|
|
2028
|
+
let zero_point_sub_offset: u32 = block % zero_point_values_per_byte;
|
|
2029
|
+
let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_sub_offset * ${t.bits}u);
|
|
2030
|
+
let zero_point_word = ${Le.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
2031
|
+
let zero_point = ${He}((zero_point_word) & ${t.bits===2?"0x3u":"0xFu"});`:`
|
|
2032
|
+
// The default zero point is ${Math.pow(2,t.bits-1)} for unsigned ${t.bits}-bit quantization.
|
|
2033
|
+
let zero_point = ${He}(${Math.pow(2,t.bits-1).toFixed(1)});`}
|
|
2034
|
+
let scale = ${ge.getByOffset("b_row * n_blocks_per_col + block")};
|
|
2035
|
+
let b_data = ${Xe.getByIndices(`${Xe.type.indices}(b_row, block, 0)`)};
|
|
2036
|
+
var word_offset = local_id.x * ${t.blockSize/g};
|
|
2037
|
+
for (var i: u32 = 0; i < ${w}; i++) {
|
|
2038
|
+
let b_value = ${w===1?"b_data":"b_data[i]"};
|
|
2039
|
+
${(()=>{let Oe=Math.floor(k/8),Ae="";for(let Ee=0;Ee<Oe;Ee++){let Dt=Ee*t.bits*4,Xt=Dt+t.bits;Ae+=`
|
|
2040
|
+
${ae()}
|
|
2041
|
+
{${t.bits===2?`
|
|
2042
|
+
let half_word = b_value >> ${Ee*16}u;
|
|
2043
|
+
let byte_lo = half_word & 0xFFu;
|
|
2044
|
+
let byte_hi = (half_word >> 8u) & 0xFFu;
|
|
2045
|
+
let spread_word = (byte_lo & 0xFu) | ((byte_lo >> 4u) << 8u) | ((byte_hi & 0xFu) << 16u) | ((byte_hi >> 4u) << 24u);
|
|
2046
|
+
let b_value_lower = unpack4xU8(spread_word & 0x03030303u);
|
|
2047
|
+
let b_value_upper = unpack4xU8((spread_word >> 2u) & 0x03030303u);`:`
|
|
2048
|
+
let b_value_lower = unpack4xU8((b_value >> ${Dt}u) & 0x0F0F0F0Fu);
|
|
2049
|
+
let b_value_upper = unpack4xU8((b_value >> ${Xt}u) & 0x0F0F0F0Fu);`}
|
|
2050
|
+
let b_quantized_values = mat2x4<${He}>(${Array.from({length:4},(_t,Yt)=>`${He}(b_value_lower[${Yt}]), ${He}(b_value_upper[${Yt}])`).join(", ")});
|
|
2051
|
+
let b_dequantized_values = (b_quantized_values - mat2x4<${He}>(${Array(8).fill("zero_point").join(",")})) * scale;
|
|
2052
|
+
inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(_t,Yt)=>`${`dot(a_data${Yt}, b_dequantized_values[${Yt}])`}`).join(" + ")};
|
|
2053
|
+
}
|
|
2054
|
+
word_offset += ${8/g};`}return Ae})()}
|
|
2055
|
+
}
|
|
2056
|
+
workgroupBarrier();
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
if (local_idx < ${x}) {
|
|
2060
|
+
var output_value: ${De.type.value} = ${De.type.value}(0);
|
|
2061
|
+
for (var b = 0u; b < ${M}; b++) {
|
|
2062
|
+
output_value += inter_results[local_idx][b];
|
|
2063
|
+
}
|
|
2064
|
+
if (col + local_idx < uniforms.output_shape[2])
|
|
2065
|
+
{
|
|
2066
|
+
${De.setByIndices(`${De.type.indices}(batch, row, col + local_idx)`,"output_value")}
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${g};${w};${M};${x}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:v,dataType:m}],dispatchGroup:{x:B},programUniforms:q}),getShaderSource:_e}},Tc=(e,t)=>{_c(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Sc(e.inputs,t)):e.compute(bc(e.inputs,t))},Ec=e=>E(e)}),$c,xc,Cc,kc,Rc,Ac,Ic,Mc,Pc,Gm=b(()=>{Ie(),ke(),ye(),$c=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},xc=(e,t,n)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2070
|
+
k = i32(${e.indicesGet("indices",o)}) - ${Q("uniforms.pads",o,n)};
|
|
2071
|
+
if (k < 0) {
|
|
2072
|
+
break;
|
|
2073
|
+
}
|
|
2074
|
+
if (k >= i32(${Q("uniforms.x_shape",o,t)})) {
|
|
2075
|
+
break;
|
|
2076
|
+
}
|
|
2077
|
+
offset += k * i32(${Q("uniforms.x_strides",o,t)});
|
|
2078
|
+
`;return`
|
|
2079
|
+
value = ${e.type.value}(uniforms.constant_value);
|
|
2080
|
+
for (var i = 0; i < 1; i++) {
|
|
2081
|
+
var offset = 0;
|
|
2082
|
+
var k = 0;
|
|
2083
|
+
${i}
|
|
2084
|
+
value = x[offset];
|
|
2085
|
+
}
|
|
2086
|
+
`},Cc=(e,t,n)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2087
|
+
k = i32(${e.indicesGet("indices",o)}) - ${Q("uniforms.pads",o,n)};
|
|
2088
|
+
if (k < 0) {
|
|
2089
|
+
k = -k;
|
|
2090
|
+
}
|
|
2091
|
+
{
|
|
2092
|
+
let _2n_1 = 2 * (i32(${Q("uniforms.x_shape",o,t)}) - 1);
|
|
2093
|
+
k = k % _2n_1;
|
|
2094
|
+
if(k >= i32(${Q("uniforms.x_shape",o,t)})) {
|
|
2095
|
+
k = _2n_1 - k;
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
offset += k * i32(${Q("uniforms.x_strides",o,t)});
|
|
2099
|
+
`;return`
|
|
2100
|
+
var offset = 0;
|
|
2101
|
+
var k = 0;
|
|
2102
|
+
${i}
|
|
2103
|
+
value = x[offset];
|
|
2104
|
+
`},kc=(e,t,n)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2105
|
+
k = i32(${e.indicesGet("indices",o)}) - ${Q("uniforms.pads",o,n)};
|
|
2106
|
+
if (k < 0) {
|
|
2107
|
+
k = 0;
|
|
2108
|
+
}
|
|
2109
|
+
if (k >= i32(${Q("uniforms.x_shape",o,t)})) {
|
|
2110
|
+
k = i32(${Q("uniforms.x_shape",o,t)}) - 1;
|
|
2111
|
+
}
|
|
2112
|
+
offset += k * i32(${Q("uniforms.x_strides",o,t)});
|
|
2113
|
+
`;return`
|
|
2114
|
+
var offset = 0;
|
|
2115
|
+
var k = 0;
|
|
2116
|
+
${i}
|
|
2117
|
+
value = x[offset];
|
|
2118
|
+
`},Rc=(e,t,n)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2119
|
+
k = i32(${e.indicesGet("indices",o)}) - ${Q("uniforms.pads",o,n)};
|
|
2120
|
+
if (k < 0) {
|
|
2121
|
+
k += i32(${Q("uniforms.x_shape",o,t)}]);
|
|
2122
|
+
}
|
|
2123
|
+
if (k >= i32(${Q("uniforms.x_shape",o,t)})) {
|
|
2124
|
+
k -= i32(${Q("uniforms.x_shape",o,t)});
|
|
2125
|
+
}
|
|
2126
|
+
offset += k * i32(${Q("uniforms.x_strides",o,t)});
|
|
2127
|
+
`;return`
|
|
2128
|
+
var offset = 0;
|
|
2129
|
+
var k = 0;
|
|
2130
|
+
${i}
|
|
2131
|
+
value = x[offset];
|
|
2132
|
+
`},Ac=(e,t,n)=>{switch(n.mode){case 0:return xc(e,t,n.pads.length);case 1:return Cc(e,t,n.pads.length);case 2:return kc(e,t,n.pads.length);case 3:return Rc(e,t,n.pads.length);default:throw new Error("Invalid mode")}},Ic=(e,t)=>{let n=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=p=>{let m=le("output",e[0].dataType,n.length),g=F("x",e[0].dataType,i.length),w=g.type.value,v=Ac(m,i.length,t),S=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&S.push({name:"constant_value",type:u?w:"f32"}),`
|
|
2133
|
+
${p.registerUniforms(S).declareVariables(g,m)}
|
|
2134
|
+
${p.mainStart()}
|
|
2135
|
+
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2136
|
+
|
|
2137
|
+
let indices = ${m.offsetToIndices("global_idx")};
|
|
2138
|
+
|
|
2139
|
+
var value = ${w}(0);
|
|
2140
|
+
${v}
|
|
2141
|
+
output[global_idx] = value;
|
|
2142
|
+
}`};return{name:"Pad",shaderCache:{hint:`${t.mode}${u}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(j.size(n)/64)},programUniforms:l}),getShaderSource:h}},Mc=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),i=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,l=new Int32Array(2*o).fill(0);if(e.length>=4){let c=e[3].getBigInt64Array();for(let h=0;h<c.length;h++)l[Number(c[h])]=Number(n[h]),l[Number(c[h])+o]=Number(n[h+c.length])}else n.forEach((c,h)=>l[Number(h)]=Number(c));let u=[];return l.forEach(c=>u.push(c)),{mode:t.mode,value:i,pads:u}}else return t},Pc=(e,t)=>{$c(e.inputs);let n=Mc(e.inputs,t);e.compute(Ic(e.inputs,n),{inputs:[0]})}}),Qn,xa,Ca,ka,Ra,Oc,Dc,Aa,Ia,zc,Lc,Ma,Bc,Nc,Pa,Uc,Fc,Vc,Gc,qm=b(()=>{ct(),Ie(),ke(),ye(),Qn=e=>{if(fe.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},xa=(e,t,n)=>{let i=t.format==="NHWC",o=e.dims.slice();i&&o.splice(1,0,o.pop());let l=Object.hasOwnProperty.call(t,"dilations"),u=t.kernelShape.slice(),c=t.strides.slice(),h=l?t.dilations.slice():[],p=t.pads.slice();Jr.adjustPoolAttributes(n,o,u,c,h,p);let m=Jr.computePoolOutputShape(n,o,c,h,u,p,t.autoPad),g=Object.assign({},t);l?Object.assign(g,{kernelShape:u,strides:c,pads:p,dilations:h,cacheKey:t.cacheKey}):Object.assign(g,{kernelShape:u,strides:c,pads:p,cacheKey:t.cacheKey});let w=m.slice();return w.push(w.splice(1,1)[0]),[g,i?w:m]},Ca=(e,t)=>{let n=t.format==="NHWC",i=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],p=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],g=!!(p+m);l.push({type:12,data:c},{type:12,data:h},{type:12,data:p},{type:12,data:m}),u.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let w=!1;if(t.kernelShape.length===2){let v=t.kernelShape[t.kernelShape.length-2],S=t.strides[t.strides.length-2],x=t.pads[t.pads.length/2-2],M=t.pads[t.pads.length-2];w=!!(x+M),l.push({type:12,data:v},{type:12,data:S},{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((p,m)=>p+m);return[l,u,!!h,!1,!1]}},ka=(e,t,n,i,o,l,u,c,h,p,m,g)=>{let w=o.format==="NHWC",v=t.type.value,S=le("output",t.type.tensor,i);if(o.kernelShape.length<=2){let x="",M="",k="",$=n-(w?2:1);if(m?x=`
|
|
2143
|
+
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2144
|
+
xIndices[${$}] = indices[${$}] * uniforms.sw - uniforms.pwStart + i;
|
|
2145
|
+
if (xIndices[${$}] < 0 || xIndices[${$}]
|
|
2146
|
+
>= uniforms.x_shape[${$}]) {
|
|
2147
|
+
pad++;
|
|
2148
|
+
continue;
|
|
2149
|
+
}
|
|
2150
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2151
|
+
${l}
|
|
2152
|
+
}`:x=`
|
|
2153
|
+
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2154
|
+
xIndices[${$}] = indices[${$}] * uniforms.sw - uniforms.pwStart + i;
|
|
2155
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2156
|
+
${l}
|
|
2157
|
+
}`,o.kernelShape.length===2){let P=n-(w?3:2);g?M=`
|
|
2158
|
+
for (var j: u32 = 0u; j < uniforms.kh; j++) {
|
|
2159
|
+
xIndices[${P}] = indices[${P}] * uniforms.sh - uniforms.phStart + j;
|
|
2160
|
+
if (xIndices[${P}] < 0 || xIndices[${P}] >= uniforms.x_shape[${P}]) {
|
|
2161
|
+
pad += i32(uniforms.kw);
|
|
2162
|
+
continue;
|
|
2163
|
+
}
|
|
2164
|
+
`:M=`
|
|
2165
|
+
for (var j: u32 = 0u; j < uniforms.kh; j++) {
|
|
2166
|
+
xIndices[${P}] = indices[${P}] * uniforms.sh - uniforms.phStart + j;
|
|
2167
|
+
`,k=`
|
|
2168
|
+
}
|
|
2169
|
+
`}return`
|
|
2170
|
+
${e.registerUniforms(h).declareVariables(t,S)}
|
|
2171
|
+
|
|
2172
|
+
${e.mainStart()}
|
|
2173
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2174
|
+
|
|
2175
|
+
let indices = ${S.offsetToIndices("global_idx")};
|
|
2176
|
+
var xIndices = ${S.offsetToIndices("global_idx")};
|
|
2177
|
+
|
|
2178
|
+
var value = ${v}(${c});
|
|
2179
|
+
var pad = 0;
|
|
2180
|
+
${M}
|
|
2181
|
+
${x}
|
|
2182
|
+
${k}
|
|
2183
|
+
${u}
|
|
2184
|
+
|
|
2185
|
+
output[global_idx] = value;
|
|
2186
|
+
}`}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 p?k=`
|
|
2187
|
+
if (xIndices[j] >= uniforms.x_shape[j]) {
|
|
2188
|
+
pad++;
|
|
2189
|
+
isPad = true;
|
|
2190
|
+
break;
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
if (!isPad) {
|
|
2194
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2195
|
+
${l}
|
|
2196
|
+
}`:k=`
|
|
2197
|
+
}
|
|
2198
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2199
|
+
${l}
|
|
2200
|
+
`,`
|
|
2201
|
+
${e.registerUniforms(h).declareVariables(t,S)}
|
|
2202
|
+
|
|
2203
|
+
${e.mainStart()}
|
|
2204
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2205
|
+
let indices = ${S.offsetToIndices("global_idx")};
|
|
2206
|
+
var xIndices = ${S.offsetToIndices("global_idx")};
|
|
2207
|
+
|
|
2208
|
+
var offsets: array<u32, ${x}>;
|
|
2209
|
+
|
|
2210
|
+
var value = ${v}(${c});
|
|
2211
|
+
var pad = 0;
|
|
2212
|
+
var isPad = false;
|
|
2213
|
+
|
|
2214
|
+
for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {
|
|
2215
|
+
var offset = i;
|
|
2216
|
+
for (var j = 0u; j < ${x-1}u; j++) {
|
|
2217
|
+
offsets[j] = offset / ${Q("uniforms.kernelStrides","j",x)};
|
|
2218
|
+
offset -= offsets[j] * ${Q("uniforms.kernelStrides","j",x)};
|
|
2219
|
+
}
|
|
2220
|
+
offsets[${x-1}] = offset;
|
|
2221
|
+
|
|
2222
|
+
isPad = false;
|
|
2223
|
+
for (var j = ${n-x}u; j < ${n}u; j++) {
|
|
2224
|
+
xIndices[j] = indices[j] * ${Q("uniforms.strides",`j - ${n-x}u`,x)}
|
|
2225
|
+
+ offsets[j - ${n-x}u] - ${Q("uniforms.pads","j - 2u",M)};
|
|
2226
|
+
${k}
|
|
2227
|
+
}
|
|
2228
|
+
${u}
|
|
2229
|
+
|
|
2230
|
+
output[global_idx] = value;
|
|
2231
|
+
}`}},Ra=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Oc=e=>`${Ra(e)};${e.countIncludePad}`,Dc=e=>`${Ra(e)};${e.storageOrder};${e.dilations}`,Aa=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Ia=(e,t,n,i)=>{let[o,l]=xa(t,i,n),u=F("x",t.dataType,t.dims.length),c=u.type.value,h="value += x_val;",p="";o.countIncludePad?p+=`value /= ${c}(uniforms.kernelSize);`:p+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[m,g,w,v,S]=Ca(l,o);m.push(...L(t.dims,l));let x=["rank"];return{name:e,shaderCache:{hint:`${i.cacheKey};${w};${v};${S}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(j.size(l)/64)},programUniforms:m}),getShaderSource:M=>ka(M,u,t.dims.length,l.length,o,h,p,0,g,w,v,S)}},zc=e=>{let t=e.count_include_pad!==0,n=Aa(e);if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let i={countIncludePad:t,...n,cacheKey:""};return{...i,cacheKey:Oc(i)}},Lc=(e,t)=>{Qn(e.inputs),e.compute(Ia("AveragePool",e.inputs[0],!1,t))},Ma={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Bc=e=>{let t=e.format;return{format:t,...Ma,cacheKey:t}},Nc=(e,t)=>{Qn(e.inputs),e.compute(Ia("GlobalAveragePool",e.inputs[0],!0,t))},Pa=(e,t,n,i)=>{let[o,l]=xa(t,i,n),u=`
|
|
2232
|
+
value = max(x_val, value);
|
|
2233
|
+
`,c="",h=F("x",t.dataType,t.dims.length),p=["rank"],[m,g,w,v,S]=Ca(l,o);return m.push(...L(t.dims,l)),{name:e,shaderCache:{hint:`${i.cacheKey};${w};${v};${S}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(j.size(l)/64)},programUniforms:m}),getShaderSource:x=>ka(x,h,t.dims.length,l.length,o,u,c,t.dataType===10?-65504:-1e5,g,w,v,S)}},Uc=(e,t)=>{Qn(e.inputs),e.compute(Pa("MaxPool",e.inputs[0],!1,t))},Fc=e=>{let t=e.storage_order,n=e.dilations,i=Aa(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(i.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:t,dilations:n,...i,cacheKey:""};return{...o,cacheKey:Dc(o)}},Vc=e=>{let t=e.format;return{format:t,...Ma,cacheKey:t}},Gc=(e,t)=>{Qn(e.inputs),e.compute(Pa("GlobalMaxPool",e.inputs[0],!0,t))}}),qc,Wc,Hc,Kc,Wm=b(()=>{Ie(),ke(),A(),ye(),qc=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((n,i)=>n===e[2].dims[i]).reduce((n,i)=>n&&i,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,l)=>l===t.axis||o===e[0].dims[l]).reduce((o,l)=>o&&l,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let n=e[0].dims[t.axis],i=e[1].dims[t.axis];if(t.blockSize<Math.ceil(n/i)||t.blockSize>Math.ceil(n/(i-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Wc=(e,t)=>{let n=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,p=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,v=m.length===0||m.length===1&&m[0]===1,S=v===!1&&m.length===1,x=V(c),M=v&&(!h||x===4),k=M?x:1,$=M&&!h?x:1,P=F("input",h?12:i,p.length,$),I=F("scale",u,m.length),B=g?F("zero_point",h?12:i,w.length):void 0,q=le("output",u,l.length,k),W=[P,I];B&&W.push(B);let ee=[p,m];g&&ee.push(w);let ue=[{type:12,data:c/k},{type:12,data:n},{type:12,data:t.blockSize},...L(...ee,l)],_e=Fe=>{let Re=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
2234
|
+
${Fe.registerUniforms(Re).declareVariables(...W,q)}
|
|
2235
|
+
${Fe.mainStart()}
|
|
2236
|
+
${Fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2237
|
+
let output_indices = ${q.offsetToIndices("global_idx")};
|
|
2238
|
+
|
|
2239
|
+
// Set input x
|
|
2240
|
+
${h?`
|
|
2241
|
+
let input = ${P.getByOffset("global_idx / 4")};
|
|
2242
|
+
let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"};
|
|
2243
|
+
let x_value = ${k===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${P.getByOffset("global_idx")};`};
|
|
2244
|
+
|
|
2245
|
+
// Set scale input
|
|
2246
|
+
${v?`let scale_value= ${I.getByOffset("0")}`:S?`
|
|
2247
|
+
let scale_index = ${q.indicesGet("output_indices","uniforms.axis")};
|
|
2248
|
+
let scale_value= ${I.getByOffset("scale_index")};`:`
|
|
2249
|
+
var scale_indices: ${I.type.indices} = output_indices;
|
|
2250
|
+
let index = ${I.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size;
|
|
2251
|
+
${I.indicesSet("scale_indices","uniforms.axis","index")};
|
|
2252
|
+
let scale_value= ${I.getByIndices("scale_indices")};`};
|
|
2253
|
+
|
|
2254
|
+
// Set zero-point input
|
|
2255
|
+
${B?v?h?`
|
|
2256
|
+
let zero_point_input = ${B.getByOffset("0")};
|
|
2257
|
+
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2258
|
+
let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${B.getByOffset("0")}`:S?h?`
|
|
2259
|
+
let zero_point_index = ${q.indicesGet("output_indices","uniforms.axis")};
|
|
2260
|
+
let zero_point_input = ${B.getByOffset("zero_point_index / 4")};
|
|
2261
|
+
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2262
|
+
let zero_point_value = zero_point_vec[zero_point_index % 4]`:`
|
|
2263
|
+
let zero_point_index = ${q.indicesGet("output_indices","uniforms.axis")};
|
|
2264
|
+
let zero_point_value = ${B.getByOffset("zero_point_index")};`:h?`
|
|
2265
|
+
let zero_point_offset = ${I.indicesToOffset("scale_indices")};
|
|
2266
|
+
let zero_point_input = ${B.getByOffset("zero_point_offset / 4")};
|
|
2267
|
+
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2268
|
+
let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${B.getByIndices("scale_indices")};`:`let zero_point_value = ${h?o?"i32":"u32":P.type.value}(0);`};
|
|
2269
|
+
// Compute and write output
|
|
2270
|
+
${q.setByOffset("global_idx",`${q.type.value}(x_value - zero_point_value) * scale_value`)};
|
|
2271
|
+
}`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:B?["rank","rank","rank"]:["rank","rank"]},getShaderSource:_e,getRunData:()=>({outputs:[{dims:l,dataType:u}],dispatchGroup:{x:Math.ceil(c/k/64),y:1,z:1},programUniforms:ue})}},Hc=(e,t)=>{qc(e.inputs,t),e.compute(Wc(e.inputs,t))},Kc=e=>E({axis:e.axis,blockSize:e.blockSize})}),jc,Qc,Xc,Hm=b(()=>{ct(),Ie(),ye(),jc=(e,t,n)=>{let i=e===t,o=e<t&&n<0,l=e>t&&n>0;if(i||o||l)throw new Error("Range these inputs' contents are invalid.")},Qc=(e,t,n,i)=>{let o=Math.abs(Math.ceil((t-e)/n)),l=[o],u=o,c=[{type:12,data:u},{type:i,data:e},{type:i,data:n},...L(l)],h=p=>{let m=le("output",i,l.length),g=m.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:g},{name:"delta",type:g}];return`
|
|
2272
|
+
${p.registerUniforms(w).declareVariables(m)}
|
|
2273
|
+
${p.mainStart()}
|
|
2274
|
+
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2275
|
+
output[global_idx] = uniforms.start + ${g}(global_idx) * uniforms.delta;
|
|
2276
|
+
}`};return{name:"Range",shaderCache:{hint:`${i}`},getShaderSource:h,getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c})}},Xc=e=>{let t=0,n=0,i=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],i=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],i=e.inputs[2].getFloat32Array()[0]),fe.webgpu.validateInputContent&&jc(t,n,i),e.compute(Qc(t,n,i,e.inputs[0].dataType),{inputs:[]})}}),Yc,Jc,Zc,eh,Km=b(()=>{Ie(),ke(),A(),ye(),Yc=(e,t,n,i)=>{if(e!=="none"&&i!=="i32"&&i!=="u32"&&i!=="f32")throw new Error(`Input ${i} is not supported with reduction ${e}.`);let o=`{
|
|
2277
|
+
var oldValue = 0;
|
|
2278
|
+
loop {
|
|
2279
|
+
let newValueF32 =`,l=`;
|
|
2280
|
+
let newValue = bitcast<i32>(newValueF32);
|
|
2281
|
+
let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue);
|
|
2282
|
+
if res.exchanged {
|
|
2283
|
+
break;
|
|
2284
|
+
}
|
|
2285
|
+
oldValue = res.old_value;
|
|
2286
|
+
}
|
|
2287
|
+
}`;switch(e){case"none":return`${t}=${n};`;case"add":return i==="i32"||i==="u32"?`atomicAdd(&${t}, bitcast<${i}>(${n}));`:`
|
|
2288
|
+
${o}bitcast<${i}>(oldValue) + (${n})${l}`;case"max":return i==="i32"||i==="u32"?`atomicMax(&${t}, bitcast<${i}>(${n}));`:`
|
|
2289
|
+
${o}max(bitcast<f32>(oldValue), (${n}))${l}`;case"min":return i==="i32"||i==="u32"?`atomicMin(&${t}, bitcast<${i}>(${n}));`:`${o}min(bitcast<${i}>(oldValue), (${n}))${l}`;case"mul":return`${o}(bitcast<${i}>(oldValue) * (${n}))${l}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Jc=(e,t)=>{let n=e[0].dims,i=e[1].dims,o=n,l=1,u=Math.ceil(j.sizeToDimension(i,i.length-1)/l),c=i[i.length-1],h=j.sizeFromDimension(n,c),p=[{type:12,data:u},{type:12,data:c},{type:12,data:h},...L(e[1].dims,e[2].dims,o)],m=g=>{let w=F("indices",e[1].dataType,e[1].dims.length),v=F("updates",e[2].dataType,e[2].dims.length,l),S=t.reduction!=="none"&&t.reduction!==""?ut("output",e[0].dataType,o.length):le("output",e[0].dataType,o.length,l);return`
|
|
2290
|
+
${g.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(w,v,S)}
|
|
2291
|
+
${g.mainStart()}
|
|
2292
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2293
|
+
var data_offset = 0u;
|
|
2294
|
+
let indices_start = uniforms.last_index_dimension * global_idx;
|
|
2295
|
+
let indices_end = indices_start + uniforms.last_index_dimension;
|
|
2296
|
+
for (var i = indices_start; i < indices_end; i++) {
|
|
2297
|
+
var index = i32(indices[i].x);
|
|
2298
|
+
${e[0].dims.length===1?`
|
|
2299
|
+
let element_count_dim = uniforms.output_strides;
|
|
2300
|
+
let dim_value = uniforms.output_shape;`:`
|
|
2301
|
+
let element_count_dim = uniforms.output_strides[i - indices_start];
|
|
2302
|
+
let dim_value = uniforms.output_shape[i - indices_start];`}
|
|
2303
|
+
if (index >= 0) {
|
|
2304
|
+
if (index >= i32(dim_value)) {
|
|
2305
|
+
index = i32(dim_value - 1);
|
|
2306
|
+
}
|
|
2307
|
+
} else {
|
|
2308
|
+
if (index < -i32(dim_value)) {
|
|
2309
|
+
index = 0;
|
|
2310
|
+
} else {
|
|
2311
|
+
index += i32(dim_value);
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
data_offset += u32((u32(index) * element_count_dim));
|
|
2315
|
+
}
|
|
2316
|
+
|
|
2317
|
+
for (var i = 0u; i < uniforms.num_updates_elements; i++) {
|
|
2318
|
+
let value = updates[uniforms.num_updates_elements * global_idx + i];
|
|
2319
|
+
${Yc(t.reduction,"output[data_offset + i]","value",S.type.value)}
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
}`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:m}},Zc=e=>E({reduction:e.reduction}),eh=(e,t)=>{e.compute(Jc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),th,rh,sh,Oa,nh,ih,ah,oh,lh,uh,dh,ch,Da,hh,ph,fh,mh,gh,yh,wh,jm=b(()=>{Ie(),ke(),A(),ye(),th=(e,t)=>{if(e.every(n=>n>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and
|
|
2323
|
+
one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},rh=(e,t,n)=>{t.every(o=>o>=0&&o<n||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")}));let i=new Array(n).fill(1);return t.forEach((o,l)=>i[o]=e[l]),i},sh=(e,t,n,i,o,l)=>{let[u,c,h]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(u>0&&e.length>u&&e[u].dims.length>0)e[u].getFloat32Array().forEach(m=>l.push(m));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(c>0&&e.length>c&&e[c].dims.length===1&&e[c].dims[0]>0){if(e[c].getFloat32Array().forEach(m=>i.push(m)),i.length!==0&&i.length!==p&&n>=18&&i.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");th(i,t),t.axes.length>0&&rh(i,t.axes,p).forEach((m,g)=>i[g]=m)}if(h>0&&e.length>h&&e[h].dims.length===1&&e[h].dims[0]>0&&(e[h].getBigInt64Array().forEach(m=>o.push(Number(m))),o.length!==0&&o.length!==p&&n>=18&&o.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(i.length!==0&&i.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof i<"u"&&typeof o<"u"&&i.length>0&&o.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},Oa=(e,t,n,i)=>`
|
|
2324
|
+
// The whole part and the fractional part are calculated separately due to inaccuracy of floating
|
|
2325
|
+
// point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
|
|
2326
|
+
// offset-by-one error later in floor().
|
|
2327
|
+
let big = (${e}) * (${t});
|
|
2328
|
+
let whole = ${i}(big / (${n}));
|
|
2329
|
+
let fract = ${i}(big % (${n})) / ${i}(${n});
|
|
2330
|
+
return whole + fract;
|
|
2331
|
+
`,nh=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,
|
|
2332
|
+
lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`
|
|
2333
|
+
if (xScale < 1.0 || floor(xScale) != xScale) {
|
|
2334
|
+
return ${t}(xResized) / ${t}(xScale);
|
|
2335
|
+
} else {
|
|
2336
|
+
${Oa("xResized","lengthOriginal","lengthResized",t)}
|
|
2337
|
+
}
|
|
2338
|
+
`;case"pytorch_half_pixel":return`if (lengthResized > 1) {
|
|
2339
|
+
return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;
|
|
2340
|
+
} else {
|
|
2341
|
+
return 0.0;
|
|
2342
|
+
}`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {
|
|
2343
|
+
return 0.0;
|
|
2344
|
+
} else {
|
|
2345
|
+
${Oa("xResized","lengthOriginal - 1","lengthResized - 1",t)}
|
|
2346
|
+
}`;case"tf_crop_and_resize":return`if (lengthResized > 1) {
|
|
2347
|
+
return ${t}(roiStart) * ${t}(lengthOriginal - 1) +
|
|
2348
|
+
(${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /
|
|
2349
|
+
${t}(lengthResized - 1);
|
|
2350
|
+
} else {
|
|
2351
|
+
return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);
|
|
2352
|
+
}`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);
|
|
2353
|
+
const adjustment = ${t}(lengthResized) / outputWidth;
|
|
2354
|
+
const center = ${t}(lengthOriginal) / 2;
|
|
2355
|
+
const offset = center * (1 - adjustment);
|
|
2356
|
+
return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",ih=(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`)}})()+"}",ah=(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},oh=(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},lh=(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},uh=(e,t,n,i,o)=>`
|
|
2357
|
+
fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${n.length}> {
|
|
2358
|
+
var original_indices: array<${e.type.value}, ${n.length}>;
|
|
2359
|
+
for (var i:u32 = 0; i < ${n.length}; i++) {
|
|
2360
|
+
var output_index = ${e.indicesGet("output_indices","i")};
|
|
2361
|
+
var scale = ${Q("uniforms.scales","i",i)};
|
|
2362
|
+
var roi_low = ${Q("uniforms.roi","i",o)};
|
|
2363
|
+
var roi_hi = ${Q("uniforms.roi",`i + ${t.length}`,o)};
|
|
2364
|
+
if (scale == 1.0) {
|
|
2365
|
+
original_indices[i] = ${e.type.value}(output_index);
|
|
2366
|
+
} else {
|
|
2367
|
+
var input_shape_i = ${Q("uniforms.input_shape","i",t.length)};
|
|
2368
|
+
var output_shape_i = ${Q("uniforms.output_shape","i",n.length)};
|
|
2369
|
+
original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
|
|
2370
|
+
input_shape_i, roi_low, roi_hi);
|
|
2371
|
+
}
|
|
2372
|
+
}
|
|
2373
|
+
return original_indices;
|
|
2374
|
+
}`,dh=(e,t,n,i,o,l,u)=>`
|
|
2375
|
+
fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
|
|
2376
|
+
var input_indices: ${e.type.indices};
|
|
2377
|
+
for (var i:u32 = 0; i < ${i.length}; i++) {
|
|
2378
|
+
var output_index = ${t.indicesGet("output_indices","i")};
|
|
2379
|
+
var input_index: u32;
|
|
2380
|
+
var scale = ${Q("uniforms.scales","i",o)};
|
|
2381
|
+
if (scale == 1.0) {
|
|
2382
|
+
input_index = output_index;
|
|
2383
|
+
} else {
|
|
2384
|
+
var roi_low = ${Q("uniforms.roi","i",l)};
|
|
2385
|
+
var roi_hi = ${Q("uniforms.roi",`i + ${n.length}`,l)};
|
|
2386
|
+
var input_shape_i = ${Q("uniforms.input_shape","i",n.length)};
|
|
2387
|
+
var output_shape_i = ${Q("uniforms.output_shape","i",i.length)};
|
|
2388
|
+
var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
|
|
2389
|
+
input_shape_i, roi_low, roi_hi);
|
|
2390
|
+
if (!${u} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {
|
|
2391
|
+
if (original_idx < 0) {
|
|
2392
|
+
input_index = 0;
|
|
2393
|
+
} else if (original_idx > ${t.type.value}(input_shape_i - 1)) {
|
|
2394
|
+
input_index = input_shape_i - 1;
|
|
2395
|
+
} else {
|
|
2396
|
+
input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));
|
|
2397
|
+
}
|
|
2398
|
+
} else {
|
|
2399
|
+
input_index = u32(original_idx);
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
${e.indicesSet("input_indices","i","input_index")}
|
|
2403
|
+
}
|
|
2404
|
+
return input_indices;
|
|
2405
|
+
}`,ch=(e,t)=>`
|
|
2406
|
+
fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {
|
|
2407
|
+
for (var i:u32 = 0; i < ${t.length}; i++) {
|
|
2408
|
+
var input_index = ${e.indicesGet("input_indices","i")};
|
|
2409
|
+
if (input_index < 0 || input_index >= ${Q("uniforms.input_shape","i",t.length)}) {
|
|
2410
|
+
return false;
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
return true;
|
|
2414
|
+
}`,Da=(e,t,n,i)=>e.rank>i?`
|
|
2415
|
+
${e.indicesSet("input_indices",t,"channel")};
|
|
2416
|
+
${e.indicesSet("input_indices",n,"batch")};
|
|
2417
|
+
`:"",hh=(e,t,n,i,o)=>{let[l,u,c,h]=n.length===2?[-1,0,1,-1]:[0,2,3,1],p=e.type.value;return`
|
|
2418
|
+
fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${p} {
|
|
2419
|
+
var input_indices: ${e.type.indices};
|
|
2420
|
+
${e.indicesSet("input_indices",u,`max(0, min(row, ${n[u]} - 1))`)};
|
|
2421
|
+
${e.indicesSet("input_indices",c,`max(0, min(col, ${n[c]} - 1))`)};
|
|
2422
|
+
${Da(e,h,l,2)}
|
|
2423
|
+
return ${e.getByIndices("input_indices")};
|
|
2424
|
+
}
|
|
2425
|
+
|
|
2426
|
+
fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} {
|
|
2427
|
+
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
|
|
2428
|
+
var row:${p} = originalIndices[${u}];
|
|
2429
|
+
var col:${p} = originalIndices[${c}];
|
|
2430
|
+
${i?`if (row < 0 || row > (${n[u]} - 1) || col < 0 || col > (${n[c]} - 1)) {
|
|
2431
|
+
return ${o};
|
|
2432
|
+
}`:""};
|
|
2433
|
+
row = max(0, min(row, ${n[u]} - 1));
|
|
2434
|
+
col = max(0, min(col, ${n[c]} - 1));
|
|
2435
|
+
var row1: u32 = u32(row);
|
|
2436
|
+
var col1: u32 = u32(col);
|
|
2437
|
+
var row2: u32 = u32(row + 1);
|
|
2438
|
+
var col2: u32 = u32(col + 1);
|
|
2439
|
+
var channel: u32 = ${n.length>2?`u32(originalIndices[${h}])`:"0"};
|
|
2440
|
+
var batch: u32 = ${n.length>2?`u32(originalIndices[${l}])`:"0"};
|
|
2441
|
+
var x11: ${p} = getInputValue(batch, channel, row1, col1);
|
|
2442
|
+
var x12: ${p} = getInputValue(batch, channel, row1, col2);
|
|
2443
|
+
var x21: ${p} = getInputValue(batch, channel, row2, col1);
|
|
2444
|
+
var x22: ${p} = getInputValue(batch, channel, row2, col2);
|
|
2445
|
+
var dx1: ${p} = abs(row - ${p}(row1));
|
|
2446
|
+
var dx2: ${p} = abs(${p}(row2) - row);
|
|
2447
|
+
var dy1: ${p} = abs(col - ${p}(col1));
|
|
2448
|
+
var dy2: ${p} = abs(${p}(col2) - col);
|
|
2449
|
+
if (row1 == row2) {
|
|
2450
|
+
dx1 = 0.5;
|
|
2451
|
+
dx2 = 0.5;
|
|
2452
|
+
}
|
|
2453
|
+
if (col1 == col2) {
|
|
2454
|
+
dy1 = 0.5;
|
|
2455
|
+
dy2 = 0.5;
|
|
2456
|
+
}
|
|
2457
|
+
return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);
|
|
2458
|
+
}`},ph=(e,t,n,i,o,l,u,c,h,p)=>{let m=n.length===2,[g,w]=m?[0,1]:[2,3],v=e.type.value,S=x=>{let M=x===g?"row":"col";return`
|
|
2459
|
+
fn ${M}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${v} {
|
|
2460
|
+
var output_index = ${t.indicesGet("output_indices",x)};
|
|
2461
|
+
var originalIdx: ${v} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[x]},
|
|
2462
|
+
${i[x]}, ${n[x]}, ${l[x]}, ${l[x]} + ${n.length});
|
|
2463
|
+
var fractOriginalIdx: ${v} = originalIdx - floor(originalIdx);
|
|
2464
|
+
var coefs = getCubicInterpolationCoefs(fractOriginalIdx);
|
|
2465
|
+
|
|
2466
|
+
if (${c} && (originalIdx < 0 || originalIdx > (${n[x]} - 1))) {
|
|
2467
|
+
return ${h};
|
|
2468
|
+
}
|
|
2469
|
+
var data: array<${v}, 4> = array<${v}, 4>(0.0, 0.0, 0.0, 0.0);
|
|
2470
|
+
for (var i: i32 = -1; i < 3; i++) {
|
|
2471
|
+
var ${M}: ${v} = originalIdx + ${v}(i);
|
|
2472
|
+
if (${M} < 0 || ${M} >= ${n[x]}) {
|
|
2473
|
+
${p?`coefs[i + 1] = 0.0;
|
|
2474
|
+
continue;`:c?`return ${h};`:`${M} = max(0, min(${M}, ${n[x]} - 1));`};
|
|
2475
|
+
}
|
|
2476
|
+
var input_indices_copy: ${e.type.indices} = input_indices;
|
|
2477
|
+
${e.indicesSet("input_indices_copy",x,`u32(${M})`)};
|
|
2478
|
+
data[i + 1] = ${x===g?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};
|
|
2479
|
+
}
|
|
2480
|
+
return cubicInterpolation1D(data, coefs);
|
|
2481
|
+
}`};return`
|
|
2482
|
+
${S(g)};
|
|
2483
|
+
${S(w)};
|
|
2484
|
+
fn getCubicInterpolationCoefs(s: ${v}) -> array<${v}, 4> {
|
|
2485
|
+
var absS = abs(s);
|
|
2486
|
+
var coeffs: array<${v}, 4> = array<${v}, 4>(0.0, 0.0, 0.0, 0.0);
|
|
2487
|
+
var oneMinusAbsS: ${v} = 1.0 - absS;
|
|
2488
|
+
var twoMinusAbsS: ${v} = 2.0 - absS;
|
|
2489
|
+
var onePlusAbsS: ${v} = 1.0 + absS;
|
|
2490
|
+
coeffs[0] = ((${u} * onePlusAbsS - 5 * ${u}) * onePlusAbsS + 8 * ${u}) * onePlusAbsS - 4 * ${u};
|
|
2491
|
+
coeffs[1] = ((${u} + 2) * absS - (${u} + 3)) * absS * absS + 1;
|
|
2492
|
+
coeffs[2] = ((${u} + 2) * oneMinusAbsS - (${u} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;
|
|
2493
|
+
coeffs[3] = ((${u} * twoMinusAbsS - 5 * ${u}) * twoMinusAbsS + 8 * ${u}) * twoMinusAbsS - 4 * ${u};
|
|
2494
|
+
return coeffs;
|
|
2495
|
+
}
|
|
2496
|
+
|
|
2497
|
+
fn cubicInterpolation1D(x: array<${v}, 4>, coefs: array<${v}, 4>) -> ${v} {
|
|
2498
|
+
var coefsSum: ${v} = coefs[0] + coefs[1] + coefs[2] + coefs[3];
|
|
2499
|
+
return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2502
|
+
fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${v} {
|
|
2503
|
+
var input_indices: ${e.type.indices} = output_indices;
|
|
2504
|
+
return colCubicInterpolation(input_indices, output_indices);
|
|
2505
|
+
}
|
|
2506
|
+
`},fh=(e,t,n,i,o)=>{let[l,u,c,h,p]=n.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],m=e.type.value;return`
|
|
2507
|
+
fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${m} {
|
|
2508
|
+
var input_indices: ${e.type.indices};
|
|
2509
|
+
${e.indicesSet("input_indices",u,`max(0, min(depth, ${n[u]} - 1))`)};
|
|
2510
|
+
${e.indicesSet("input_indices",c,`max(0, min(height, ${n[c]} - 1))`)};
|
|
2511
|
+
${e.indicesSet("input_indices",h,`max(0, min(width, ${n[h]} - 1))`)};
|
|
2512
|
+
${Da(e,p,l,3)}
|
|
2513
|
+
return ${e.getByIndices("input_indices")};
|
|
2514
|
+
}
|
|
2515
|
+
|
|
2516
|
+
fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} {
|
|
2517
|
+
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
|
|
2518
|
+
var depth:${m} = originalIndices[${u}];
|
|
2519
|
+
var height:${m} = originalIndices[${c}];
|
|
2520
|
+
var width:${m} = originalIndices[${h}];
|
|
2521
|
+
${i?`if (depth < 0 || depth > (${n[u]} - 1) || height < 0 || height > (${n[c]} - 1) || width < 0 || (width > ${n[h]} - 1)) {
|
|
2522
|
+
return ${o};
|
|
2523
|
+
}`:""};
|
|
2524
|
+
|
|
2525
|
+
depth = max(0, min(depth, ${n[u]} - 1));
|
|
2526
|
+
height = max(0, min(height, ${n[c]} - 1));
|
|
2527
|
+
width = max(0, min(width, ${n[h]} - 1));
|
|
2528
|
+
var depth1: u32 = u32(depth);
|
|
2529
|
+
var height1: u32 = u32(height);
|
|
2530
|
+
var width1: u32 = u32(width);
|
|
2531
|
+
var depth2: u32 = u32(depth + 1);
|
|
2532
|
+
var height2: u32 = u32(height + 1);
|
|
2533
|
+
var width2: u32 = u32(width + 1);
|
|
2534
|
+
var channel: u32 = ${n.length>3?`u32(originalIndices[${p}])`:"0"};
|
|
2535
|
+
var batch: u32 = ${n.length>3?`u32(originalIndices[${l}])`:"0"};
|
|
2536
|
+
|
|
2537
|
+
var x111: ${m} = getInputValue(batch, channel, depth1, height1, width1);
|
|
2538
|
+
var x112: ${m} = getInputValue(batch, channel, depth1, height1, width2);
|
|
2539
|
+
var x121: ${m} = getInputValue(batch, channel, depth1, height2, width1);
|
|
2540
|
+
var x122: ${m} = getInputValue(batch, channel, depth1, height2, width2);
|
|
2541
|
+
var x211: ${m} = getInputValue(batch, channel, depth2, height1, width1);
|
|
2542
|
+
var x212: ${m} = getInputValue(batch, channel, depth2, height1, width2);
|
|
2543
|
+
var x221: ${m} = getInputValue(batch, channel, depth2, height2, width1);
|
|
2544
|
+
var x222: ${m} = getInputValue(batch, channel, depth2, height2, width2);
|
|
2545
|
+
var dx1: ${m} = abs(depth - ${m}(depth1));
|
|
2546
|
+
var dx2: ${m} = abs(${m}(depth2) - depth);
|
|
2547
|
+
var dy1: ${m} = abs(height - ${m}(height1));
|
|
2548
|
+
var dy2: ${m} = abs(${m}(height2) - height);
|
|
2549
|
+
var dz1: ${m} = abs(width - ${m}(width1));
|
|
2550
|
+
var dz2: ${m} = abs(${m}(width2) - width);
|
|
2551
|
+
if (depth1 == depth2) {
|
|
2552
|
+
dx1 = 0.5;
|
|
2553
|
+
dx2 = 0.5;
|
|
2554
|
+
}
|
|
2555
|
+
if (height1 == height2) {
|
|
2556
|
+
dy1 = 0.5;
|
|
2557
|
+
dy2 = 0.5;
|
|
2558
|
+
}
|
|
2559
|
+
if (width1 == width2) {
|
|
2560
|
+
dz1 = 0.5;
|
|
2561
|
+
dz2 = 0.5;
|
|
2562
|
+
}
|
|
2563
|
+
return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +
|
|
2564
|
+
x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);
|
|
2565
|
+
}`},mh=(e,t,n,i,o,l)=>{let u=e.dims,c=ah(l,t.axes,u.length),h=oh(u,i,o,t.axes),p=i.slice();i.length===0&&(p=u.map(($,P)=>$===0?1:h[P]/$),t.keepAspectRatioPolicy!=="stretch"&&(h=lh(u,p,t)));let m=le("output",e.dataType,h.length),g=F("input",e.dataType,u.length),w=j.size(h),v=u.length===h.length&&u.every(($,P)=>$===h[P]),S=t.coordinateTransformMode==="tf_crop_and_resize",x=t.extrapolationValue,M=g.type.value,k=$=>`
|
|
2566
|
+
${v?"":`
|
|
2567
|
+
${nh(t.coordinateTransformMode,M)};
|
|
2568
|
+
${(()=>{switch(t.mode){case"nearest":return`
|
|
2569
|
+
${ch(g,u)};
|
|
2570
|
+
${ih(t.nearestMode,n,M)};
|
|
2571
|
+
${dh(g,m,u,h,p.length,c.length,S)};
|
|
2572
|
+
`;case"linear":return`
|
|
2573
|
+
${uh(m,u,h,p.length,c.length)};
|
|
2574
|
+
${(()=>{if(u.length===2||u.length===4)return`${hh(g,m,u,S,x)}`;if(u.length===3||u.length===5)return`${fh(g,m,u,S,x)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};
|
|
2575
|
+
`;case"cubic":return`
|
|
2576
|
+
${(()=>{if(u.length===2||u.length===4)return`${ph(g,m,u,h,p,c,t.cubicCoeffA,S,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};
|
|
2577
|
+
`;default:throw Error("Invalid resize mode")}})()};
|
|
2578
|
+
`}
|
|
2579
|
+
${$.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",c.length).declareVariables(g,m)}
|
|
2580
|
+
${$.mainStart()}
|
|
2581
|
+
${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2582
|
+
${v?"output[global_idx] = input[global_idx];":`
|
|
2583
|
+
let output_indices = ${m.offsetToIndices("global_idx")};
|
|
2584
|
+
var input_indices: ${g.type.indices};
|
|
2585
|
+
${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);
|
|
2586
|
+
if (checkInputIndices(input_indices)) {
|
|
2587
|
+
output[global_idx] = ${g.getByIndices("input_indices")};
|
|
2588
|
+
} else {
|
|
2589
|
+
output[global_idx] = ${t.extrapolationValue};
|
|
2590
|
+
}`;case"linear":return`output[global_idx] = ${u.length===2||u.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};
|
|
2591
|
+
`}
|
|
2592
|
+
}`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${p.length>0?t.mode==="cubic"?p:p.length:""}|${o.length>0?o:""}|${c.length>0?c:""}|${v}|${t.mode==="nearest"?u.length:u}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[{dims:h,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},{type:1,data:p},{type:1,data:c},...L(u,h)]})}},gh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},yh=(e,t)=>{let n=[],i=[],o=[],l=gh(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");sh(e.inputs,t,l,n,i,o),e.compute(mh(e.inputs[0],t,l,n,i,o),{inputs:[0]})},wh=e=>{let t=e.antialias,n=e.axes,i=e.coordinateTransformMode,o=e.cubicCoeffA,l=e.excludeOutside!==0,u=e.extrapolationValue,c=e.keepAspectRatioPolicy,h=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return E({antialias:t,axes:n,coordinateTransformMode:i,cubicCoeffA:o,excludeOutside:l,extrapolationValue:u,keepAspectRatioPolicy:c,mode:h,nearestMode:p})}}),vh,_h,bh,Qm=b(()=>{Ie(),ke(),ye(),vh=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],n=e[1],i=e[2];if(t.dataType!==n.dataType||t.dataType!==i.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(n.dims.length!==3&&n.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],l=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(n.dims[n.dims.length-2]!==l)throw new Error("Skip must have the same sequence length as input");if(i.dims.length!==1)throw new Error("Gamma must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let u=e[3];if(u.dims.length!==1)throw new Error("Beta must be 1D");if(u.dims[u.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let u=e[4];if(u.dims.length!==1)throw new Error("Bias must be 1D");if(u.dims[u.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},_h=(e,t,n,i)=>{let o=t.simplified,l=e[0].dims,u=j.size(l),c=l,h=u,p=l.slice(-1)[0],m=i?l.slice(0,-1).concat(1):[],g=!o&&e.length>3,w=e.length>4,v=i&&n>1,S=i&&n>2,x=n>3,M=64,k=V(p),$=[{type:12,data:h},{type:12,data:k},{type:12,data:p},{type:1,data:t.epsilon}],P=B=>{let q=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],W=[F("x",e[0].dataType,e[0].dims,k),F("skip",e[1].dataType,e[1].dims,k),F("gamma",e[2].dataType,e[2].dims,k)];g&&W.push(F("beta",e[3].dataType,e[3].dims,k)),w&&W.push(F("bias",e[4].dataType,e[4].dims,k)),W.push(le("output",e[0].dataType,c,k)),v&&W.push(le("mean_output",1,m)),S&&W.push(le("inv_std_output",1,m)),x&&W.push(le("input_skip_bias_sum",e[0].dataType,c,k));let ee=G(e[0].dataType),ue=G(1,k);return`
|
|
2593
|
+
|
|
2594
|
+
${B.registerUniforms(q).declareVariables(...W)}
|
|
2595
|
+
var<workgroup> sum_shared : array<${ue}, ${M}>;
|
|
2596
|
+
var<workgroup> sum_squared_shared : array<${ue}, ${M}>;
|
|
2597
|
+
|
|
2598
|
+
${B.mainStart([M,1,1])}
|
|
2599
|
+
let ix = local_id.x;
|
|
2600
|
+
let iy = global_id.x / ${M};
|
|
2601
|
+
|
|
2602
|
+
let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;
|
|
2603
|
+
var stride = hidden_size_vectorized / ${M};
|
|
2604
|
+
let offset = ix * stride + iy * hidden_size_vectorized;
|
|
2605
|
+
let offset1d = stride * ix;
|
|
2606
|
+
if (ix == ${M-1}) {
|
|
2607
|
+
stride = hidden_size_vectorized - stride * ix;
|
|
2608
|
+
}
|
|
2609
|
+
for (var i: u32 = 0; i < stride; i++) {
|
|
2610
|
+
let skip_value = skip[offset + i];
|
|
2611
|
+
let bias_value = ${w?"bias[offset1d + i]":ee+"(0.0)"};
|
|
2612
|
+
let input_value = x[offset + i];
|
|
2613
|
+
let value = input_value + skip_value + bias_value;
|
|
2614
|
+
${x?"input_skip_bias_sum[offset + i] = value;":""}
|
|
2615
|
+
output[offset + i] = value;
|
|
2616
|
+
let f32_value = ${ne(ee,k,"value")};
|
|
2617
|
+
sum_shared[ix] += f32_value;
|
|
2618
|
+
sum_squared_shared[ix] += f32_value * f32_value;
|
|
2619
|
+
}
|
|
2620
|
+
workgroupBarrier();
|
|
2621
|
+
|
|
2622
|
+
var reduce_size : u32 = ${M};
|
|
2623
|
+
for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {
|
|
2624
|
+
reduce_size = curr_size + (reduce_size & 1);
|
|
2625
|
+
if (ix < curr_size) {
|
|
2626
|
+
sum_shared[ix] += sum_shared[ix + reduce_size];
|
|
2627
|
+
sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];
|
|
2628
|
+
}
|
|
2629
|
+
workgroupBarrier();
|
|
2630
|
+
}
|
|
2631
|
+
|
|
2632
|
+
let sum = sum_shared[0];
|
|
2633
|
+
let square_sum = sum_squared_shared[0];
|
|
2634
|
+
let mean = ${Z("sum",k)} / f32(uniforms.hidden_size);
|
|
2635
|
+
let inv_std_dev = inverseSqrt(${Z("square_sum",k)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon);
|
|
2636
|
+
${v?"mean_output[global_idx] = mean;":""}
|
|
2637
|
+
${S?"inv_std_output[global_idx] = inv_std_dev;":""}
|
|
2638
|
+
|
|
2639
|
+
for (var i: u32 = 0; i < stride; i++) {
|
|
2640
|
+
output[offset + i] = (output[offset + i] ${o?"":`- ${ee}(mean)`}) *
|
|
2641
|
+
${ee}(inv_std_dev) * gamma[offset1d + i]
|
|
2642
|
+
${g?"+ beta[offset1d + i]":""};
|
|
2643
|
+
}
|
|
2644
|
+
}`},I=[{dims:c,dataType:e[0].dataType}];return n>1&&I.push({dims:m,dataType:1}),n>2&&I.push({dims:m,dataType:1}),n>3&&I.push({dims:l,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${k};${v};${S};${x}`,inputDependencies:e.map((B,q)=>"type")},getShaderSource:P,getRunData:()=>({outputs:I,dispatchGroup:{x:Math.ceil(h/p)},programUniforms:$})}},bh=(e,t)=>{vh(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(_h(e.inputs,t,e.outputCount,!1),{outputs:n})}}),Sh,Xn,Th,za,Eh,$h,xh,Ch,Xm=b(()=>{Ie(),ke(),A(),ye(),Sh=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((n,i)=>{if(e[i+1].dataType!==6&&e[i+1].dataType!==7)throw new Error(`Input ${i} must be an array of int32 or int64`)})},Xn=(e,t)=>{let n=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(i=>n.push(Number(i)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(i=>n.push(Number(i)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return n},Th=(e,t)=>{if(e.length>1){let n=Xn(e,1),i=Xn(e,2),o=Xn(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),E({starts:n,ends:i,axes:o})}else return t},za=(e,t,n,i,o)=>{let l=e;return e<0&&(l+=n[i[t]]),o[t]<0?Math.max(0,Math.min(l,n[i[t]]-1)):Math.max(0,Math.min(l,n[i[t]]))},Eh=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
|
|
2645
|
+
var input_indices: ${e.type.indices};
|
|
2646
|
+
var carry = 0u;
|
|
2647
|
+
for (var i = ${n.length-1}; i >= 0; i--) {
|
|
2648
|
+
let input_shape_i = ${Q("uniforms.input_shape","i",n.length)};
|
|
2649
|
+
let steps_i = ${Q("uniforms.steps","i",n.length)};
|
|
2650
|
+
let signs_i = ${Q("uniforms.signs","i",n.length)};
|
|
2651
|
+
let starts_i = ${Q("uniforms.starts","i",n.length)};
|
|
2652
|
+
var output_index = ${t.indicesGet("output_indices","i")};
|
|
2653
|
+
var input_index = output_index * steps_i + starts_i + carry;
|
|
2654
|
+
carry = input_index / input_shape_i;
|
|
2655
|
+
input_index = input_index % input_shape_i;
|
|
2656
|
+
if (signs_i < 0) {
|
|
2657
|
+
input_index = input_shape_i - input_index - 1u + starts_i;
|
|
2658
|
+
}
|
|
2659
|
+
${e.indicesSet("input_indices","i","input_index")};
|
|
2660
|
+
}
|
|
2661
|
+
return input_indices;
|
|
2662
|
+
}`,$h=(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,$)=>za(k,$,n,o,l)),c=t.ends.map((k,$)=>za(k,$,n,o,l));if(o.length!==u.length||o.length!==c.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==n.length)for(let k=0;k<n.length;++k)o.includes(k)||(u.splice(k,0,0),c.splice(k,0,n[k]),l.splice(k,0,1));let h=l.map(k=>Math.sign(k));l.forEach((k,$,P)=>{if(k<0){let I=(c[$]-u[$])/k,B=u[$],q=B+I*l[$];u[$]=q,c[$]=B,P[$]=-k}});let p=n.slice(0);o.forEach((k,$)=>{p[k]=Math.ceil((c[k]-u[k])/l[k])});let m={dims:p,dataType:e[0].dataType},g=le("output",e[0].dataType,p.length),w=F("input",e[0].dataType,e[0].dims.length),v=j.size(p),S=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:u.length},{name:"signs",type:"i32",length:h.length},{name:"steps",type:"u32",length:l.length}],x=[{type:12,data:v},{type:12,data:u},{type:6,data:h},{type:12,data:l},...L(e[0].dims,p)],M=k=>`
|
|
2663
|
+
${k.registerUniforms(S).declareVariables(w,g)}
|
|
2664
|
+
${Eh(w,g,n)}
|
|
2665
|
+
${k.mainStart()}
|
|
2666
|
+
${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2667
|
+
let output_indices = ${g.offsetToIndices("global_idx")};
|
|
2668
|
+
let input_indices = calculateInputIndices(output_indices);
|
|
2669
|
+
${g.setByOffset("global_idx",w.getByIndices("input_indices"))}
|
|
2670
|
+
}`;return{name:"Slice",shaderCache:{hint:`${h.length}_${u.length}_${l.length}`,inputDependencies:["rank"]},getShaderSource:M,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:x})}},xh=(e,t)=>{Sh(e.inputs,t);let n=Th(e.inputs,t);e.compute($h(e.inputs,n),{inputs:[0]})},Ch=e=>{let t=e.starts,n=e.ends,i=e.axes;return E({starts:t,ends:n,axes:i})}}),kh,Rh,Ah,Ih,Ym=b(()=>{Ie(),ke(),A(),Ue(),ye(),kh=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Rh=(e,t)=>{let n=e.inputs[0],i=n.dims,o=j.size(i),l=i.length,u=j.normalizeAxis(t.axis,l),c=u<i.length-1,h,p=[];c?(p=Array.from({length:l},(W,ee)=>ee),p[u]=l-1,p[l-1]=u,h=e.compute(ht(n,p),{inputs:[n],outputs:[-1]})[0]):h=n;let m=h.dims,g=m[l-1],w=o/g,v=V(g),S=g/v,x=64;w===1&&(x=256);let M=(W,ee)=>ee===4?`max(max(${W}.x, ${W}.y), max(${W}.z, ${W}.w))`:ee===2?`max(${W}.x, ${W}.y)`:ee===3?`max(max(${W}.x, ${W}.y), ${W}.z)`:W,k=F("x",h.dataType,h.dims,v),$=le("result",h.dataType,h.dims,v),P=k.type.value,I=G(h.dataType)==="f32"?`var threadMax = ${P}(-3.4028234663852886e+38f);`:`var threadMax = ${P}(-65504.0h);`,B=W=>`
|
|
2671
|
+
var<workgroup> rowMaxShared : ${P};
|
|
2672
|
+
var<workgroup> rowSumShared : ${P};
|
|
2673
|
+
var<workgroup> threadShared : array<${P}, ${x}>;
|
|
2674
|
+
|
|
2675
|
+
fn getValue(row: i32, col: i32, row_stride: i32) -> ${P} {
|
|
2676
|
+
let index = row * row_stride + col;
|
|
2677
|
+
return x[index];
|
|
2678
|
+
}
|
|
2679
|
+
|
|
2680
|
+
fn setValue(row: i32, col: i32, row_stride: i32, value: ${P}) {
|
|
2681
|
+
let index = row * row_stride + col;
|
|
2682
|
+
result[index] = value;
|
|
2683
|
+
}
|
|
2684
|
+
${W.registerUniform("packedCols","i32").declareVariables(k,$)}
|
|
2685
|
+
${W.mainStart(x)}
|
|
2686
|
+
let gindex = i32(global_idx);
|
|
2687
|
+
let lindex = i32(local_idx);
|
|
2688
|
+
const wg = ${x};
|
|
2689
|
+
let row = gindex / wg;
|
|
2690
|
+
let cols = uniforms.packedCols;
|
|
2691
|
+
let row_stride : i32 = uniforms.packedCols;
|
|
2692
|
+
|
|
2693
|
+
// find the rows max
|
|
2694
|
+
${I}
|
|
2695
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2696
|
+
let value = getValue(row, col, row_stride);
|
|
2697
|
+
threadMax = max(threadMax, value);
|
|
2698
|
+
}
|
|
2699
|
+
if (lindex < cols) {
|
|
2700
|
+
threadShared[lindex] = threadMax;
|
|
2701
|
+
}
|
|
2702
|
+
workgroupBarrier();
|
|
2703
|
+
|
|
2704
|
+
var reduceSize = min(cols, wg);
|
|
2705
|
+
for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {
|
|
2706
|
+
reduceSize = currSize + (reduceSize & 1);
|
|
2707
|
+
if (lindex < currSize) {
|
|
2708
|
+
threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);
|
|
2709
|
+
}
|
|
2710
|
+
workgroupBarrier();
|
|
2711
|
+
}
|
|
2712
|
+
if (lindex == 0) {
|
|
2713
|
+
rowMaxShared = ${P}(${M("threadShared[0]",v)});
|
|
2714
|
+
}
|
|
2715
|
+
workgroupBarrier();
|
|
2716
|
+
|
|
2717
|
+
// find the rows sum
|
|
2718
|
+
var threadSum = ${P}(0.0);
|
|
2719
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2720
|
+
let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);
|
|
2721
|
+
threadSum += subExp;
|
|
2722
|
+
}
|
|
2723
|
+
threadShared[lindex] = threadSum;
|
|
2724
|
+
workgroupBarrier();
|
|
2725
|
+
|
|
2726
|
+
for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {
|
|
2727
|
+
if (lindex < currSize) {
|
|
2728
|
+
threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];
|
|
2729
|
+
}
|
|
2730
|
+
workgroupBarrier();
|
|
2731
|
+
}
|
|
2732
|
+
if (lindex == 0) {
|
|
2733
|
+
rowSumShared = ${P}(${Z("threadShared[0]",v)});
|
|
2734
|
+
}
|
|
2735
|
+
workgroupBarrier();
|
|
2736
|
+
|
|
2737
|
+
// calculate final value for each element in the row
|
|
2738
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2739
|
+
var value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;
|
|
2740
|
+
// max operation protects against NaN since all values should be >=0
|
|
2741
|
+
value = max(value, ${P}(0.0));
|
|
2742
|
+
setValue(row, col, row_stride, value);
|
|
2743
|
+
}
|
|
2744
|
+
}`,q=e.compute({name:"Softmax",shaderCache:{hint:`${v};${x}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:m,dataType:h.dataType}],dispatchGroup:{x:w},programUniforms:[{type:6,data:S}]}),getShaderSource:B},{inputs:[h],outputs:[c?-1:0]})[0];c&&e.compute(ht(q,p),{inputs:[q]})},Ah=(e,t)=>{kh(e.inputs),Rh(e,t)},Ih=e=>E({axis:e.axis})}),La,Mh,Ph,Oh,Dh,Jm=b(()=>{Ie(),ke(),ye(),La=e=>Array.from(e.getBigInt64Array(),Number),Mh=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(La(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Ph=(e,t)=>{let n=[];for(let i=0;i<e.length;++i)n.push(e[i]*t[i]);return n},Oh=(e,t)=>{let n=e[0].dims,i=t??La(e[1]),o=Ph(n,i),l=j.size(o),u=e[0].dataType,c=F("input",u,n.length),h=le("output",u,o.length),p=m=>`
|
|
2745
|
+
const inputShape = ${c.indices(...n)};
|
|
2746
|
+
${m.registerUniform("output_size","u32").declareVariables(c,h)}
|
|
2747
|
+
${m.mainStart()}
|
|
2748
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2749
|
+
let output_indices = ${h.offsetToIndices("global_idx")};
|
|
2750
|
+
var input_indices: ${c.type.indices};
|
|
2751
|
+
for (var i = 0; i < ${n.length}; i++) {
|
|
2752
|
+
let input_dim_i = ${c.indicesGet("uniforms.input_shape","i")};
|
|
2753
|
+
let input_dim_value = ${h.indicesGet("output_indices","i")} % input_dim_i;
|
|
2754
|
+
|
|
2755
|
+
${c.indicesSet("input_indices","i","input_dim_value")}
|
|
2756
|
+
}
|
|
2757
|
+
${h.setByOffset("global_idx",c.getByIndices("input_indices"))}
|
|
2758
|
+
}`;return{name:"Tile",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},...L(e[0].dims,o)]}),getShaderSource:p}},Dh=e=>{Mh(e.inputs),e.compute(Oh(e.inputs),{inputs:[0]})}}),zh,Lh,Bh,Zm=b(()=>{Ie(),ke(),ye(),zh=(e,t,n,i,o)=>{let l=le("output_data",o,n.length,4),u=F("a_data",t[1].dataType,t[1].dims.length,4),c=F("b_data",t[2].dataType,t[2].dims.length,4),h=F("c_data",t[0].dataType,t[0].dims.length,4),p,m=(g,w,v)=>`select(${w}, ${g}, ${v})`;if(!i)p=l.setByOffset("global_idx",m(u.getByOffset("global_idx"),c.getByOffset("global_idx"),h.getByOffset("global_idx")));else{let g=(w,v,S="")=>{let x=`a_data[index_a${v}][component_a${v}]`,M=`b_data[index_b${v}][component_b${v}]`,k=`bool(c_data[index_c${v}] & (0xffu << (component_c${v} * 8)))`;return`
|
|
2759
|
+
let output_indices${v} = ${l.offsetToIndices(`global_idx * 4u + ${v}u`)};
|
|
2760
|
+
let offset_a${v} = ${u.broadcastedIndicesToOffset(`output_indices${v}`,l)};
|
|
2761
|
+
let offset_b${v} = ${c.broadcastedIndicesToOffset(`output_indices${v}`,l)};
|
|
2762
|
+
let offset_c${v} = ${h.broadcastedIndicesToOffset(`output_indices${v}`,l)};
|
|
2763
|
+
let index_a${v} = offset_a${v} / 4u;
|
|
2764
|
+
let index_b${v} = offset_b${v} / 4u;
|
|
2765
|
+
let index_c${v} = offset_c${v} / 4u;
|
|
2766
|
+
let component_a${v} = offset_a${v} % 4u;
|
|
2767
|
+
let component_b${v} = offset_b${v} % 4u;
|
|
2768
|
+
let component_c${v} = offset_c${v} % 4u;
|
|
2769
|
+
${w}[${v}] = ${S}(${m(x,M,k)});
|
|
2770
|
+
`};o===9?p=`
|
|
2771
|
+
var data = vec4<u32>(0);
|
|
2772
|
+
${g("data",0,"u32")}
|
|
2773
|
+
${g("data",1,"u32")}
|
|
2774
|
+
${g("data",2,"u32")}
|
|
2775
|
+
${g("data",3,"u32")}
|
|
2776
|
+
output_data[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:p=`
|
|
2777
|
+
${g("output_data[global_idx]",0)}
|
|
2778
|
+
${g("output_data[global_idx]",1)}
|
|
2779
|
+
${g("output_data[global_idx]",2)}
|
|
2780
|
+
${g("output_data[global_idx]",3)}
|
|
2781
|
+
`}return`
|
|
2782
|
+
${e.registerUniform("vec_size","u32").declareVariables(h,u,c,l)}
|
|
2783
|
+
${e.mainStart()}
|
|
2784
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
2785
|
+
${p}
|
|
2786
|
+
}`},Lh=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 p=Cr.calcShape(Cr.calcShape(t,n,!1),i,!1);if(!p)throw new Error("Can't perform where op on the given tensors");u=p,c=j.size(u)}let h=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>zh(p,e,u,l,o),getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:h},...L(i,t,n,u)]})}},Bh=e=>{e.compute(Lh(e.inputs))}}),Nh,eg=b(()=>{fm(),Zi(),mm(),gm(),ym(),wm(),vm(),Em(),xm(),Cm(),km(),Rm(),Am(),Im(),Mm(),Pm(),Om(),Dm(),zm(),Lm(),Bm(),Nm(),Um(),Fm(),Vm(),Yd(),Gm(),qm(),Wm(),Hm(),Km(),Xi(),jm(),oc(),Qm(),Xm(),Ym(),nc(),Jm(),Ue(),sa(),Zm(),Nh=new Map([["Abs",[vl]],["Acos",[_l]],["Acosh",[bl]],["Add",[lu]],["ArgMax",[nl,Ji]],["ArgMin",[sl,Ji]],["Asin",[Sl]],["Asinh",[Tl]],["Atan",[El]],["Atanh",[$l]],["Attention",[dl]],["AveragePool",[Lc,zc]],["BatchNormalization",[fl]],["BiasAdd",[yl]],["BiasSplitGelu",[iu]],["Cast",[Cl,xl]],["Ceil",[Al]],["Clip",[Rl]],["Concat",[Su,Tu]],["Conv",[ga,fa]],["ConvTranspose",[Xu,Ku]],["Cos",[Il]],["Cosh",[Ml]],["CumSum",[Ju,Zu]],["DepthToSpace",[sd,nd]],["DequantizeLinear",[Hc,Kc]],["Div",[uu]],["Einsum",[dd,cd]],["Elu",[Pl,qn]],["Equal",[du]],["Erf",[Ol]],["Exp",[Dl]],["Expand",[md]],["FastGelu",[yd]],["Floor",[zl]],["FusedConv",[ga,fa]],["Gather",[bd,_d]],["GatherElements",[Md,Id]],["GatherBlockQuantized",[Cd,kd]],["GatherND",[Td,Ed]],["Gelu",[Ll]],["Gemm",[zd,Dd]],["GlobalAveragePool",[Nc,Bc]],["GlobalMaxPool",[Gc,Vc]],["Greater",[fu]],["GreaterOrEqual",[gu]],["GridSample",[Wd,Hd]],["GroupQueryAttention",[cc]],["HardSigmoid",[Wl,ql]],["InstanceNormalization",[fc]],["LayerNormalization",[yc]],["LeakyRelu",[Bl,qn]],["Less",[mu]],["LessOrEqual",[yu]],["Log",[Zl]],["MatMul",[vc]],["MatMulNBits",[Tc,Ec]],["MaxPool",[Uc,Fc]],["Mul",[cu]],["MultiHeadAttention",[Xd,jd]],["Neg",[Ul]],["Not",[Nl]],["Pad",[Pc]],["Pow",[hu]],["QuickGelu",[ru,qn]],["Range",[Xc]],["Reciprocal",[Fl]],["ReduceMin",[Jo]],["ReduceMean",[Ko]],["ReduceMax",[Yo]],["ReduceSum",[el]],["ReduceProd",[Zo]],["ReduceL1",[jo]],["ReduceL2",[Qo]],["ReduceLogSum",[rl]],["ReduceLogSumExp",[Xo]],["ReduceSumSquare",[tl]],["Relu",[Vl]],["Resize",[yh,wh]],["RotaryEmbedding",[ac]],["ScatterND",[eh,Zc]],["Sigmoid",[Gl]],["Sin",[Hl]],["Sinh",[Kl]],["Slice",[xh,Ch]],["SkipLayerNormalization",[bh]],["Split",[rc,sc]],["Sqrt",[jl]],["Softmax",[Ah,Ih]],["Sub",[pu]],["Tan",[Ql]],["Tanh",[Xl]],["ThresholdedRelu",[Jl,qn]],["Tile",[Dh]],["Transpose",[ir,Fn]],["Where",[Bh]]])}),Uh,tg=b(()=>{ct(),tr(),ye(),Uh=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,i,o){gt(e.programInfo.name);let l=this.backend.device,u=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let c=[];for(let p of t)c.push({binding:c.length,resource:{buffer:p.buffer}});for(let p of n)c.push({binding:c.length,resource:{buffer:p.buffer}});o&&c.push({binding:c.length,resource:o});let h=l.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:c,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let p={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:h,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p)}u.setPipeline(e.computePipeline),u.setBindGroup(0,h),u.dispatchWorkgroups(...i),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),yt(e.programInfo.name)}dispose(){}build(e,t){gt(e.name);let n=this.backend.device,i=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(p=>{n.features.has(p.feature)&&i.push(`enable ${p.extension};`)});let o=Ne(t,this.backend.device.limits),l=e.getShaderSource(o),u=`${i.join(`
|
|
2787
|
+
`)}
|
|
2788
|
+
${o.additionalImplementations}
|
|
2789
|
+
${l}`,c=n.createShaderModule({code:u,label:e.name});We("verbose",()=>`[WebGPU] ${e.name} shader code: ${u}`);let h=n.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:e.name});return yt(e.name),{programInfo:e,computePipeline:h,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,n=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&n<=o&&i<=o)return[t,n,i];let l=t*n*i,u=Math.ceil(Math.sqrt(l));if(u>o){if(u=Math.ceil(Math.cbrt(l)),u>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[u,u,u]}else return[u,u,1]}}}),Fh={};U(Fh,{WebGpuBackend:()=>Wh});var Vh,Gh,qh,Wh,rg=b(()=>{ct(),Ie(),tr(),Zr(),ji(),eg(),tg(),Vh=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let i=0;i<e.length;++i){let o=e[i].dataType;switch(t[i]){case"none":{n.push("");break}case"type":{n.push(`${o}`);break}case"rank":{let l=e[i].dims.length;n.push(`${o};${l}`);break}case"dims":{let l=e[i].dims.join(",");n.push(`${o};${l}`);break}default:throw new Error(`unsupported input dependency: ${t[i]}`)}}return n.join("|")},Gh=(e,t,n)=>{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+n+`:${Vh(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},qh=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Wh=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},o=l=>t.features.has(l)&&n.push(l)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await t.requestDevice(i),this.adapterInfo=new qh(t.info||await t.requestAdapterInfo()),this.gpuDataManager=fi(this),this.programManager=new Uh(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ws(e.logLevel,!!e.debug),this.device.onuncapturederror=l=>{l.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${l.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&this.env?.webgpu&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;gt(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let i=0;i<t.length/2;i++){let o=n[i],l=o.kernelId,u=this.kernels.get(l),c=u.kernelType,h=u.kernelName,p=o.programName,m=o.inputTensorViews,g=o.outputTensorViews,w=t[i*2],v=t[i*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=w);let S=Number(w-this.queryTimeBase),x=Number(v-this.queryTimeBase);if(!Number.isSafeInteger(S)||!Number.isSafeInteger(x))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:m.map(M=>({dims:M.dims,dataType:jt(M.dataType)})),outputsMetadata:g.map(M=>({dims:M.dims,dataType:jt(M.dataType)})),kernelId:l,kernelType:c,kernelName:h,programName:p,startTime:S,endTime:x});else{let M="";m.forEach(($,P)=>{M+=`input[${P}]: [${$.dims}] | ${jt($.dataType)}, `});let k="";g.forEach(($,P)=>{k+=`output[${P}]: [${$.dims}] | ${jt($.dataType)}, `}),console.log(`[profiling] kernel "${l}|${c}|${h}|${p}" ${M}${k}start time: ${S} ns, execution time: ${x-S} ns`)}er("GPU",`${p}::${w}::${v}`)}e.unmap(),this.pendingQueries.delete(e)}),yt()}run(e,t,n,i,o,l){gt(e.name);let u=[];for(let $=0;$<t.length;++$){let P=t[$].data;if(P===0)continue;let I=this.gpuDataManager.get(P);if(!I)throw new Error(`no GPU data for input: ${P}`);u.push(I)}let{outputs:c,dispatchGroup:h,programUniforms:p}=e.getRunData(t),m=n.length===0?c.map(($,P)=>P):n;if(m.length!==c.length)throw new Error(`Output size ${m.length} must be equal to ${c.length}.`);let g=[],w=[];for(let $=0;$<c.length;++$){if(!Number.isInteger(m[$])||m[$]<-3||m[$]>=l)throw new Error(`Invalid output index: ${m[$]}`);if(m[$]===-3)continue;let P=m[$]===-1,I=m[$]===-2,B=P||I?o(c[$].dataType,c[$].dims):i(m[$],c[$].dataType,c[$].dims);if(g.push(B),B.data===0)continue;let q=this.gpuDataManager.get(B.data);if(!q)throw new Error(`no GPU data for output: ${B.data}`);if(P&&this.temporaryData.push(q),I){let W=this.kernelPersistentData.get(this.currentKernelId);W||(W=[],this.kernelPersistentData.set(this.currentKernelId,W)),W.push(q)}w.push(q)}if(u.length!==t.length||w.length!==g.length){if(w.length===0)return yt(e.name),g;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let v;if(p){let $=0,P=[];p.forEach(W=>{let ee=typeof W.data=="number"?[W.data]:W.data;if(ee.length===0)return;let ue=W.type===10?2:4,_e,Fe;W.type===10?(Fe=ee.length>4?16:ee.length>2?8:ee.length*ue,_e=ee.length>4?16:ue*ee.length):(Fe=ee.length<=2?ee.length*ue:16,_e=16),$=Math.ceil($/Fe)*Fe,P.push($);let Re=W.type===10?8:4;$+=ee.length>4?Math.ceil(ee.length/Re)*_e:ee.length*ue});let I=16;$=Math.ceil($/I)*I;let B=new ArrayBuffer($);p.forEach((W,ee)=>{let ue=P[ee],_e=typeof W.data=="number"?[W.data]:W.data;if(W.type===6)new Int32Array(B,ue,_e.length).set(_e);else if(W.type===12)new Uint32Array(B,ue,_e.length).set(_e);else if(W.type===10)new Uint16Array(B,ue,_e.length).set(_e);else if(W.type===1)new Float32Array(B,ue,_e.length).set(_e);else throw new Error(`Unsupported uniform type: ${jt(W.type)}`)});let q=this.gpuDataManager.create($,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(q.buffer,0,B,0,$),this.gpuDataManager.release(q.id),v={offset:0,size:$,buffer:q.buffer}}let S=this.programManager.normalizeDispatchGroupSize(h),x=S[1]===1&&S[2]===1,M=Gh(e,t,x),k=this.programManager.getArtifact(M);if(k||(k=this.programManager.build(e,S),this.programManager.setArtifact(M,k),We("info",()=>`[artifact] key: ${M}, programName: ${e.name}`)),p&&k.uniformVariablesInfo){if(p.length!==k.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${k.uniformVariablesInfo.length}, got ${p.length} in program "${k.programInfo.name}".`);for(let $=0;$<p.length;$++){let P=p[$],I=P.type,B=typeof P.data=="number"?1:P.data.length,[q,W]=k.uniformVariablesInfo[$];if(I!==q||B!==W)throw new Error(`Uniform variable ${$} mismatch: expect type ${q} with size ${W}, got type ${I} with size ${B} in program "${k.programInfo.name}".`)}}if(We("info",()=>`[ProgramManager] run "${e.name}" (key=${M}) with ${S[0]}x${S[1]}x${S[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let $={kernelId:this.currentKernelId,programName:k.programInfo.name,inputTensorViews:t,outputTensorViews:g};this.pendingKernels.push($),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push($)}return this.programManager.run(k,u,w,S,v),yt(e.name),g}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,i){let o=Nh.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let l={kernelType:e,kernelName:i,kernelEntry:o[0],attributes:[o[1],n]};this.kernels.set(t,l)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let n of t)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let o=i.kernelType,l=i.kernelName,u=i.kernelEntry,c=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${l}" is not allowed to be called recursively`);this.currentKernelId=e,c[0]&&(c[1]=c[0](c[1]),c[0]=void 0),We("info",()=>`[WebGPU] Start to run kernel "[${o}] ${l}"...`);let h=this.env.debug;this.temporaryData=[];try{return h&&this.device.pushErrorScope("validation"),u(t,c[1]),0}catch(p){return n.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${l}" failed. ${p}`)),1}finally{h&&n.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${o}] ${l}": ${p.message}`:null));for(let p of this.temporaryData)this.gpuDataManager.release(p.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,i){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let l=o.get(t),u=this.gpuDataManager.registerExternalBuffer(n,i,l);return o.set(t,[u,n]),u}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let i=await Bn(this,e,t);return kr(i.buffer,n)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){We("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(){We("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){We("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let i=0;i<n;i++){let o=this.getComputePassEncoder(),l=e[i];this.writeTimestamp(this.pendingDispatchNumber*2),o.setPipeline(l.computePipeline),o.setBindGroup(0,l.bindGroup),o.dispatchWorkgroups(...l.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(t[i]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Hh={};U(Hh,{init:()=>jh});var Ci,Kh,jh,sg=b(()=>{Ie(),tr(),ke(),Ln(),Ci=class cf{constructor(t,n,i,o){this.module=t,this.dataType=n,this.data=i,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=j.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=j.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=j.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=j.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(j.size(t)!==j.size(this.dims))throw new Error("Invalid new shape");return new cf(this.module,this.dataType,this.data,t)}},Kh=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,o=n/e.PTR_SIZE,l=i===4?"i32":"i64";this.opKernelContext=Number(e.getValue(i*o++,l));let u=Number(e.getValue(i*o++,l));this.outputCount=Number(e.getValue(i*o++,l)),this.customDataOffset=Number(e.getValue(i*o++,"*")),this.customDataSize=Number(e.getValue(i*o++,l));let c=[];for(let h=0;h<u;h++){let p=Number(e.getValue(i*o++,l)),m=Number(e.getValue(i*o++,"*")),g=Number(e.getValue(i*o++,l)),w=[];for(let v=0;v<g;v++)w.push(Number(e.getValue(i*o++,l)));c.push(new Ci(e,p,m,w))}this.inputs=c}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let n=t?.inputs?.map(u=>typeof u=="number"?this.inputs[u]:u)??this.inputs,i=t?.outputs??[],o=(u,c,h)=>new Ci(this.module,c,this.output(u,h),h),l=(u,c)=>{let h=Qt(u,c);if(!h)throw new Error(`Unsupported data type: ${u}`);let p=h>0?this.backend.gpuDataManager.create(h).id:0;return new Ci(this.module,u,p,c)};return this.backend.run(e,n,i,o,l,this.outputCount)}output(e,t){let n=this.module.stackSave();try{let i=this.module.PTR_SIZE,o=i===4?"i32":"i64",l=this.module.stackAlloc((1+t.length)*i);this.module.setValue(l,t.length,o);for(let u=0;u<t.length;u++)this.module.setValue(l+i*(u+1),t[u],o);return this.module._JsepOutput(this.opKernelContext,e,l)}catch(i){throw new Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${i}`)}finally{this.module.stackRestore(n)}}},jh=async(e,t,n,i)=>{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let l=(rg(),re(Fh)).WebGpuBackend,u=new l;await u.initialize(n,i),o("webgpu",[u,c=>u.alloc(Number(c)),c=>u.free(c),(c,h,p,m=!1)=>{if(m)We("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(c)}, dst=${Number(h)}, size=${Number(p)}`),u.memcpy(Number(c),Number(h));else{We("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(c)}, gpuDataId=${Number(h)}, size=${Number(p)}`);let g=t.HEAPU8.subarray(Number(c>>>0),Number(c>>>0)+Number(p));u.upload(Number(h),g)}},async(c,h,p)=>{We("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${c}, dataOffset=${h}, size=${p}`),await u.download(Number(c),()=>t.HEAPU8.subarray(Number(h)>>>0,Number(h+p)>>>0))},(c,h,p)=>u.createKernel(c,Number(h),p,t.UTF8ToString(t._JsepGetNodeName(Number(h)))),c=>u.releaseKernel(c),(c,h,p,m)=>{We("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${c}, contextDataOffset=${h}`);let g=new Kh(t,u,Number(h));return u.computeKernel(Number(c),g,m)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else{let l=new zn(n);o("webnn",[l,()=>l.reserveTensorId(),u=>l.releaseTensorId(u),async(u,c,h,p,m)=>l.ensureTensor(u,c,h,p,m),(u,c)=>{l.uploadTensor(u,c)},async(u,c)=>l.downloadTensor(u,c),(u,c)=>l.registerMLContext(u,c),!!n.trace])}}}),Qh,Ba,Na,ns,Xh,Ua,ki,Fa,Va,Ga,qa,Wa,Ha,Yh=b(()=>{ct(),Hi(),Ki(),Ie(),Ht(),ws(),An(),Qh=(e,t)=>{Pe()._OrtInit(e,t)!==0&&Ce("Can't initialize onnxruntime.")},Ba=async e=>{Qh(e.wasm.numThreads,_s(e.logLevel))},Na=async(e,t)=>{Pe().asyncInit?.();let n=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:o}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let i=(sg(),re(Hh)).init;t==="webgpu"&&await i("webgpu",Pe(),e,n),t==="webnn"&&await i("webnn",Pe(),e)}},ns=new Map,Xh=e=>{let t=Pe(),n=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,o,o+i)!==0&&Ce("Can't get session input/output count.");let l=i===4?"i32":"i64";return[Number(t.getValue(o,l)),Number(t.getValue(o+i,l))]}finally{t.stackRestore(n)}},Ua=(e,t)=>{let n=Pe(),i=n.stackSave(),o=0;try{let l=n.PTR_SIZE,u=n.stackAlloc(2*l);n._OrtGetInputOutputMetadata(e,t,u,u+l)!==0&&Ce("Can't get session input/output metadata.");let c=Number(n.getValue(u,"*"));o=Number(n.getValue(u+l,"*"));let h=n.HEAP32[o/4];if(h===0)return[c,0];let p=n.HEAPU32[o/4+1],m=[];for(let g=0;g<p;g++){let w=Number(n.getValue(o+8+g*l,"*"));m.push(w!==0?n.UTF8ToString(w):Number(n.getValue(o+8+(g+p)*l,"*")))}return[c,h,m]}finally{n.stackRestore(i),o!==0&&n._OrtFree(o)}},ki=e=>{let t=Pe(),n=t._malloc(e.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Fa=async(e,t)=>{let n,i,o=Pe();Array.isArray(e)?[n,i]=e:e.buffer===o.HEAPU8.buffer?[n,i]=[e.byteOffset,e.byteLength]:[n,i]=ki(e);let l=0,u=0,c=0,h=[],p=[],m=[];try{if([u,h]=await Rn(t),t?.externalData&&o.mountExternalData){let I=[];for(let B of t.externalData){let q=typeof B=="string"?B:B.path;I.push(Ts(typeof B=="string"?B:B.data).then(W=>{o.mountExternalData(q,W)}))}await Promise.all(I)}for(let I of t?.executionProviders??[])if((typeof I=="string"?I:I.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof I!="string"){let B=I,q=B?.context,W=B?.gpuDevice,ee=B?.deviceType,ue=B?.powerPreference;q?o.currentContext=q:W?o.currentContext=await o.webnnCreateMLContext(W):o.currentContext=await o.webnnCreateMLContext({deviceType:ee,powerPreference:ue})}else o.currentContext=await o.webnnCreateMLContext();break}l=await o._OrtCreateSession(n,i,u),o.webgpuOnCreateSession?.(l),l===0&&Ce("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.webnnRegisterMLContext(l,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[g,w]=Xh(l),v=!!t?.enableGraphCapture,S=[],x=[],M=[],k=[],$=[];for(let I=0;I<g;I++){let[B,q,W]=Ua(l,I);B===0&&Ce("Can't get an input name."),p.push(B);let ee=o.UTF8ToString(B);S.push(ee),M.push(q===0?{name:ee,isTensor:!1}:{name:ee,isTensor:!0,type:jt(q),shape:W})}for(let I=0;I<w;I++){let[B,q,W]=Ua(l,I+g);B===0&&Ce("Can't get an output name."),m.push(B);let ee=o.UTF8ToString(B);x.push(ee),k.push(q===0?{name:ee,isTensor:!1}:{name:ee,isTensor:!0,type:jt(q),shape:W});{if(v&&t?.preferredOutputLocation===void 0){$.push("gpu-buffer");continue}let ue=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[ee]??"cpu",_e=o.webnnIsGraphOutput;if(ue==="cpu"&&_e&&_e(l,ee)){$.push("ml-tensor-cpu-output");continue}if(ue!=="cpu"&&ue!=="cpu-pinned"&&ue!=="gpu-buffer"&&ue!=="ml-tensor")throw new Error(`Not supported preferred output location: ${ue}.`);if(v&&ue!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${ue}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);$.push(ue)}}let P=null;return $.some(I=>I==="gpu-buffer"||I==="ml-tensor"||I==="ml-tensor-cpu-output")&&(c=o._OrtCreateBinding(l),c===0&&Ce("Can't create IO binding."),P={handle:c,outputPreferredLocations:$,outputPreferredLocationsEncoded:$.map(I=>I==="ml-tensor-cpu-output"?"ml-tensor":I).map(I=>Vs(I))}),ns.set(l,[l,p,m,P,v,!1]),[l,S,x,M,k]}catch(g){throw p.forEach(w=>o._OrtFree(w)),m.forEach(w=>o._OrtFree(w)),c!==0&&o._OrtReleaseBinding(c)!==0&&Ce("Can't release IO binding."),l!==0&&o._OrtReleaseSession(l)!==0&&Ce("Can't release session."),g}finally{o._free(n),u!==0&&o._OrtReleaseSessionOptions(u)!==0&&Ce("Can't release session options."),h.forEach(g=>o._free(g)),o.unmountExternalData?.()}},Va=e=>{let t=Pe(),n=ns.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,o,l,u,c]=n;u&&(c&&t._OrtClearBoundOutputs(u.handle)!==0&&Ce("Can't clear bound outputs."),t._OrtReleaseBinding(u.handle)!==0&&Ce("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),o.forEach(h=>t._OrtFree(h)),l.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(i)!==0&&Ce("Can't release session."),ns.delete(e)},Ga=async(e,t,n,i,o,l,u=!1)=>{if(!e){t.push(0);return}let c=Pe(),h=c.PTR_SIZE,p=e[0],m=e[1],g=e[3],w=g,v,S;if(p==="string"&&(g==="gpu-buffer"||g==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(u&&g!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${l} when enableGraphCapture is true.`);if(g==="gpu-buffer"){let k=e[2].gpuBuffer;S=Qt(Kt(p),m);{let $=c.jsepRegisterBuffer;if(!$)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');v=$(i,l,k,S)}}else if(g==="ml-tensor"){let k=e[2].mlTensor;S=Qt(Kt(p),m);let $=c.webnnRegisterMLTensor;if(!$)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');v=$(i,k,Kt(p),m)}else{let k=e[2];if(Array.isArray(k)){S=h*k.length,v=c._malloc(S),n.push(v);for(let $=0;$<k.length;$++){if(typeof k[$]!="string")throw new TypeError(`tensor data at index ${$} is not a string`);c.setValue(v+$*h,mt(k[$],n),"*")}}else{let $=c.webnnIsGraphInput,P=c.webnnIsGraphOutput;if(p!=="string"&&$&&P){let I=c.UTF8ToString(o);if($(i,I)||P(i,I)){let B=Kt(p);S=Qt(B,m),w="ml-tensor";let q=c.webnnCreateTemporaryTensor,W=c.webnnUploadTensor;if(!q||!W)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let ee=await q(i,B,m);W(ee,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),v=ee}else S=k.byteLength,v=c._malloc(S),n.push(v),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),v)}else S=k.byteLength,v=c._malloc(S),n.push(v),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),v)}}let x=c.stackSave(),M=c.stackAlloc(4*m.length);try{m.forEach(($,P)=>c.setValue(M+P*h,$,h===4?"i32":"i64"));let k=c._OrtCreateTensor(Kt(p),v,S,M,m.length,Vs(w));k===0&&Ce(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(k)}finally{c.stackRestore(x)}},qa=async(e,t,n,i,o,l)=>{let u=Pe(),c=u.PTR_SIZE,h=ns.get(e);if(!h)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=h[0],m=h[1],g=h[2],w=h[3],v=h[4],S=h[5],x=t.length,M=i.length,k=0,$=[],P=[],I=[],B=[],q=[],W=u.stackSave(),ee=u.stackAlloc(x*c),ue=u.stackAlloc(x*c),_e=u.stackAlloc(M*c),Fe=u.stackAlloc(M*c);try{[k,$]=En(l),Ct("wasm prepareInputOutputTensor");for(let ge=0;ge<x;ge++)await Ga(n[ge],P,B,e,m[t[ge]],t[ge],v);for(let ge=0;ge<M;ge++)await Ga(o[ge],I,B,e,g[i[ge]],x+i[ge],v);kt("wasm prepareInputOutputTensor");for(let ge=0;ge<x;ge++)u.setValue(ee+ge*c,P[ge],"*"),u.setValue(ue+ge*c,m[t[ge]],"*");for(let ge=0;ge<M;ge++)u.setValue(_e+ge*c,I[ge],"*"),u.setValue(Fe+ge*c,g[i[ge]],"*");if(w&&!S){let{handle:ge,outputPreferredLocations:$e,outputPreferredLocationsEncoded:Le}=w;if(m.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${m.length}).`);Ct("wasm bindInputsOutputs");for(let Ve=0;Ve<x;Ve++){let De=t[Ve];await u._OrtBindInput(ge,m[De],P[Ve])!==0&&Ce(`Can't bind input[${Ve}] for session=${e}.`)}for(let Ve=0;Ve<M;Ve++){let De=i[Ve];o[Ve]?.[3]?(q.push(I[Ve]),u._OrtBindOutput(ge,g[De],I[Ve],0)!==0&&Ce(`Can't bind pre-allocated output[${Ve}] for session=${e}.`)):u._OrtBindOutput(ge,g[De],0,Le[De])!==0&&Ce(`Can't bind output[${Ve}] to ${$e[Ve]} for session=${e}.`)}kt("wasm bindInputsOutputs"),ns.set(e,[p,m,g,w,v,!0])}u.jsepOnRunStart?.(p),u.webnnOnRunStart?.(p);let Re;w?Re=await u._OrtRunWithBinding(p,w.handle,M,_e,k):Re=await u._OrtRun(p,ue,ee,x,Fe,M,_e,k),Re!==0&&Ce("failed to call OrtRun().");let Me=[],Xe=[];Ct("wasm ProcessOutputTensor");for(let ge=0;ge<M;ge++){let $e=Number(u.getValue(_e+ge*c,"*"));if($e===I[ge]||q.includes(I[ge])){Me.push(o[ge]),$e!==I[ge]&&u._OrtReleaseTensor($e)!==0&&Ce("Can't release tensor.");continue}let Le=u.stackSave(),Ve=u.stackAlloc(4*c),De=!1,He,ae=0;try{u._OrtGetTensorData($e,Ve,Ve+c,Ve+2*c,Ve+3*c)!==0&&Ce(`Can't access output tensor data on index ${ge}.`);let Oe=c===4?"i32":"i64",Ae=Number(u.getValue(Ve,Oe));ae=u.getValue(Ve+c,"*");let Ee=u.getValue(Ve+c*2,"*"),Dt=Number(u.getValue(Ve+c*3,Oe)),Xt=[];for(let nt=0;nt<Dt;nt++)Xt.push(Number(u.getValue(Ee+nt*c,Oe)));u._OrtFree(Ee)!==0&&Ce("Can't free memory for tensor dims.");let _t=Xt.reduce((nt,bt)=>nt*bt,1);He=jt(Ae);let Yt=w?.outputPreferredLocations[i[ge]];if(He==="string"){if(Yt==="gpu-buffer"||Yt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let nt=[];for(let bt=0;bt<_t;bt++){let Ur=u.getValue(ae+bt*c,"*"),lg=u.getValue(ae+(bt+1)*c,"*"),ug=bt===_t-1?void 0:lg-Ur;nt.push(u.UTF8ToString(Ur,ug))}Me.push([He,Xt,nt,"cpu"])}else if(Yt==="gpu-buffer"&&_t>0){let nt=u.jsepGetBuffer;if(!nt)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let bt=nt(ae),Ur=Qt(Ae,_t);if(Ur===void 0||!bs(He))throw new Error(`Unsupported data type: ${He}`);De=!0,Me.push([He,Xt,{gpuBuffer:bt,download:u.jsepCreateDownloader(bt,Ur,He),dispose:()=>{u._OrtReleaseTensor($e)!==0&&Ce("Can't release tensor.")}},"gpu-buffer"])}else if(Yt==="ml-tensor"&&_t>0){let nt=u.webnnEnsureTensor,bt=u.webnnIsGraphInputOutputTypeSupported;if(!nt||!bt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Qt(Ae,_t)===void 0||!Ss(He))throw new Error(`Unsupported data type: ${He}`);if(!bt(e,He,!1))throw new Error(`preferredLocation "ml-tensor" for ${He} output is not supported by current WebNN Context.`);let Ur=await nt(e,ae,Ae,Xt,!1);De=!0,Me.push([He,Xt,{mlTensor:Ur,download:u.webnnCreateMLTensorDownloader(ae,He),dispose:()=>{u.webnnReleaseTensorId(ae),u._OrtReleaseTensor($e)}},"ml-tensor"])}else if(Yt==="ml-tensor-cpu-output"&&_t>0){let nt=u.webnnCreateMLTensorDownloader(ae,He)(),bt=Me.length;De=!0,Xe.push((async()=>{let Ur=[bt,await nt];return u.webnnReleaseTensorId(ae),u._OrtReleaseTensor($e),Ur})()),Me.push([He,Xt,[],"cpu"])}else{let nt=vs(He),bt=new nt(_t);new Uint8Array(bt.buffer,bt.byteOffset,bt.byteLength).set(u.HEAPU8.subarray(ae,ae+bt.byteLength)),Me.push([He,Xt,bt,"cpu"])}}finally{u.stackRestore(Le),He==="string"&&ae&&u._free(ae),De||u._OrtReleaseTensor($e)}}w&&!v&&(u._OrtClearBoundOutputs(w.handle)!==0&&Ce("Can't clear bound outputs."),ns.set(e,[p,m,g,w,v,!1]));for(let[ge,$e]of await Promise.all(Xe))Me[ge][2]=$e;return kt("wasm ProcessOutputTensor"),Me}finally{u.webnnOnRunEnd?.(p),u.stackRestore(W),P.forEach(Re=>u._OrtReleaseTensor(Re)),I.forEach(Re=>u._OrtReleaseTensor(Re)),B.forEach(Re=>u._free(Re)),k!==0&&u._OrtReleaseRunOptions(k),$.forEach(Re=>u._free(Re))}},Wa=e=>{let t=Pe(),n=ns.get(e);if(!n)throw new Error("invalid session id");let i=n[0],o=t._OrtEndProfiling(i);o===0&&Ce("Can't get an profile file name."),t._OrtFree(o)},Ha=e=>{let t=[];for(let n of e){let i=n[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),is,or,on,Yn,Jn,Ri,Ka,Ai,Ds,zs,Jh,Zh,ep,tp,rp,sp,np,ip,ap=b(()=>{ct(),Yh(),Ht(),fs(),is=()=>!!fe.wasm.proxy&&typeof document<"u",on=!1,Yn=!1,Jn=!1,Ai=new Map,Ds=(e,t)=>{let n=Ai.get(e);n?n.push(t):Ai.set(e,[t])},zs=()=>{if(on||!Yn||Jn||!or)throw new Error("worker not ready")},Jh=e=>{switch(e.data.type){case"init-wasm":on=!1,e.data.err?(Jn=!0,Ka[1](e.data.err)):(Yn=!0,Ka[0]()),Ri&&(URL.revokeObjectURL(Ri),Ri=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Ai.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Zh=async()=>{if(!Yn){if(on)throw new Error("multiple calls to 'initWasm()' detected.");if(Jn)throw new Error("previous call to 'initWasm()' failed.");if(on=!0,is())return new Promise((e,t)=>{or?.terminate(),vn().then(([n,i])=>{try{or=i,or.onerror=l=>t(l),or.onmessage=Jh,Ka=[e,t];let o={type:"init-wasm",in:fe};if(!o.in.wasm.wasmPaths&&n){let l=ds();l&&(o.in.wasm.wasmPaths=l)}or.postMessage(o),Ri=n}catch(o){t(o)}},t)});try{await ys(fe.wasm),await Ba(fe),Yn=!0}catch(e){throw Jn=!0,e}finally{on=!1}}},ep=async e=>{if(is())return zs(),new Promise((t,n)=>{Ds("init-ep",[t,n]);let i={type:"init-ep",in:{epName:e,env:fe}};or.postMessage(i)});await Na(fe,e)},tp=async e=>is()?(zs(),new Promise((t,n)=>{Ds("copy-from",[t,n]);let i={type:"copy-from",in:{buffer:e}};or.postMessage(i,[e.buffer])})):ki(e),rp=async(e,t)=>{if(is()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return zs(),new Promise((n,i)=>{Ds("create",[n,i]);let o={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),or.postMessage(o,l)})}else return Fa(e,t)},sp=async e=>{if(is())return zs(),new Promise((t,n)=>{Ds("release",[t,n]);let i={type:"release",in:e};or.postMessage(i)});Va(e)},np=async(e,t,n,i,o,l)=>{if(is()){if(n.some(u=>u[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(u=>u))throw new Error("pre-allocated output tensor is not supported for proxy.");return zs(),new Promise((u,c)=>{Ds("run",[u,c]);let h=n,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:h,outputIndices:i,options:l}};or.postMessage(p,Ha(h))})}else return qa(e,t,n,i,o,l)},ip=async e=>{if(is())return zs(),new Promise((t,n)=>{Ds("end-profiling",[t,n]);let i={type:"end-profiling",in:e};or.postMessage(i)});Wa(e)}}),ja,op,lp,ng=b(()=>{ct(),ap(),Ie(),Ut(),An(),ja=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},op=e=>{switch(e[3]){case"cpu":return new lt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!bs(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:o}=e[2];return lt.fromGpuBuffer(n,{dataType:t,dims:e[1],download:i,dispose:o})}case"ml-tensor":{let t=e[0];if(!Ss(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:o}=e[2];return lt.fromMLTensor(n,{dataType:t,dims:e[1],download:i,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},lp=class{async fetchModelAndCopyToWasmMemory(e){return tp(await Ts(e))}async loadModel(e,t){gt();let n;typeof e=="string"?n=await this.fetchModelAndCopyToWasmMemory(e):n=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await rp(n,t),yt()}async dispose(){return sp(this.sessionId)}async run(e,t,n){gt();let i=[],o=[];Object.entries(e).forEach(g=>{let w=g[0],v=g[1],S=this.inputNames.indexOf(w);if(S===-1)throw new Error(`invalid input '${w}'`);i.push(v),o.push(S)});let l=[],u=[];Object.entries(t).forEach(g=>{let w=g[0],v=g[1],S=this.outputNames.indexOf(w);if(S===-1)throw new Error(`invalid output '${w}'`);l.push(v),u.push(S)});let c=i.map((g,w)=>ja(g,()=>`input "${this.inputNames[o[w]]}"`)),h=l.map((g,w)=>g?ja(g,()=>`output "${this.outputNames[u[w]]}"`):null),p=await np(this.sessionId,o,c,u,h,n),m={};for(let g=0;g<p.length;g++)m[this.outputNames[u[g]]]=l[g]??op(p[g]);return yt(),m}startProfiling(){}endProfiling(){ip(this.sessionId)}}}),up={};U(up,{OnnxruntimeWebAssemblyBackend:()=>Xa,initializeFlags:()=>Qa,wasmBackend:()=>dp});var Qa,Xa,dp,ig=b(()=>{ct(),ap(),ng(),Qa=()=>{(typeof fe.wasm.initTimeout!="number"||fe.wasm.initTimeout<0)&&(fe.wasm.initTimeout=0);let e=fe.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),fe.wasm.simd=!1),typeof fe.wasm.proxy!="boolean"&&(fe.wasm.proxy=!1),typeof fe.wasm.trace!="boolean"&&(fe.wasm.trace=!1),typeof fe.wasm.numThreads!="number"||!Number.isInteger(fe.wasm.numThreads)||fe.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)fe.wasm.numThreads=1;else{let t=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;fe.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Xa=class{async init(e){Qa(),await Zh(),await ep(e)}async createInferenceSessionHandler(e,t){let n=new lp;return await n.loadModel(e,t),n}},dp=new Xa}),cp={};U(cp,{InferenceSession:()=>Qe,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>Ct,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>yt,Tensor:()=>lt,default:()=>og,env:()=>fe,registerBackend:()=>J}),ct(),ct(),ct();var ag="1.26.0",og=ls;{let e=(ig(),re(up)).wasmBackend;J("webgpu",e,5),J("webnn",e,5),J("cpu",e,10),J("wasm",e,10)}return Object.defineProperty(fe.versions,"web",{value:ag,enumerable:!0}),re(cp)})();/**
|
|
2790
|
+
* @license
|
|
2791
|
+
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
2792
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2793
|
+
* you may not use this file except in compliance with the License.
|
|
2794
|
+
* You may obtain a copy of the License at
|
|
2795
|
+
*
|
|
2796
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2797
|
+
*
|
|
2798
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2799
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2800
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2801
|
+
* See the License for the specific language governing permissions and
|
|
2802
|
+
* limitations under the License.
|
|
2803
|
+
* =============================================================================
|
|
2804
|
+
*//**
|
|
2805
|
+
* @license
|
|
2806
|
+
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
2807
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2808
|
+
* you may not use this file except in compliance with the License.
|
|
2809
|
+
* You may obtain a copy of the License at
|
|
2810
|
+
*
|
|
2811
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2812
|
+
*
|
|
2813
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2814
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2815
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2816
|
+
* See the License for the specific language governing permissions and
|
|
2817
|
+
* limitations under the License.
|
|
2818
|
+
* =============================================================================
|
|
2819
|
+
*//**
|
|
2820
|
+
* @license
|
|
2821
|
+
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
2822
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2823
|
+
* you may not use this file except in compliance with the License.
|
|
2824
|
+
* You may obtain a copy of the License at
|
|
2825
|
+
*
|
|
2826
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2827
|
+
*
|
|
2828
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2829
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2830
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2831
|
+
* See the License for the specific language governing permissions and
|
|
2832
|
+
* limitations under the License.
|
|
2833
|
+
* =============================================================================
|
|
2834
|
+
*/d.exports=s})(so)),so.exports}var Ls={},no={},Ep;function yy(){return Ep||(Ep=1,Object.defineProperty(no,"__esModule",{value:!0})),no}var ni={},$p;function wy(){if($p)return ni;$p=1;var d;Object.defineProperty(ni,"__esModule",{value:!0}),ni.SileroLegacy=void 0;const r=ci();class s{constructor(f,_,C,R,b){this.ortInstance=f,this._session=_,this._h=C,this._c=R,this._sr=b,this.reset_state=()=>{const U=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",U,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",U,[2,1,64])},this.process=async U=>{const re={input:new this.ortInstance.Tensor("float32",U,[1,U.length]),h:this._h,c:this._c,sr:this._sr},K=await this._session.run(re);this._h=K.hn,this._c=K.cn;const[ie]=K.output?.data;return{notSpeech:1-ie,isSpeech:ie}},this.release=async()=>{await this._session.release(),this._h.dispose(),this._c.dispose(),this._sr.dispose()}}}return ni.SileroLegacy=s,d=s,s.new=async(a,f)=>{r.log.debug("initializing vad");const _=await f(),C=await a.InferenceSession.create(_),R=new a.Tensor("int64",[16000n]),b=Array(128).fill(0),U=new a.Tensor("float32",b,[2,1,64]),z=new a.Tensor("float32",b,[2,1,64]);return r.log.debug("vad is initialized"),new d(a,C,U,z,R)},ni}var ii={},xp;function vy(){if(xp)return ii;xp=1;var d;Object.defineProperty(ii,"__esModule",{value:!0}),ii.SileroV5=void 0;const r=ci();function s(f){const _=Array(256).fill(0);return new f.Tensor("float32",_,[2,1,128])}class a{constructor(_,C,R,b){this._session=_,this._state=C,this._sr=R,this.ortInstance=b,this.reset_state=()=>{this._state=s(this.ortInstance)},this.process=async U=>{const re={input:new this.ortInstance.Tensor("float32",U,[1,U.length]),state:this._state,sr:this._sr},K=await this._session.run(re);if(!K.stateN)throw new Error("No state from model");if(this._state=K.stateN,!K.output?.data)throw new Error("No output from model");const ie=K.output.data[0];if(typeof ie!="number")throw new Error("Weird output data");return{notSpeech:1-ie,isSpeech:ie}},this.release=async()=>{await this._session.release(),this._state.dispose(),this._sr.dispose()}}}return ii.SileroV5=a,d=a,a.new=async(f,_)=>{r.log.debug("Loading VAD...");const C=await _(),R=await f.InferenceSession.create(C),b=new f.Tensor("int64",[16000n]),U=s(f);return r.log.debug("...finished loading VAD"),new d(R,U,b,f)},ii}var Cp;function hf(){return Cp||(Cp=1,(function(d){var r=Ls&&Ls.__createBinding||(Object.create?(function(_,C,R,b){b===void 0&&(b=R);var U=Object.getOwnPropertyDescriptor(C,R);(!U||("get"in U?!C.__esModule:U.writable||U.configurable))&&(U={enumerable:!0,get:function(){return C[R]}}),Object.defineProperty(_,b,U)}):(function(_,C,R,b){b===void 0&&(b=R),_[b]=C[R]})),s=Ls&&Ls.__exportStar||function(_,C){for(var R in _)R!=="default"&&!Object.prototype.hasOwnProperty.call(C,R)&&r(C,_,R)};Object.defineProperty(d,"__esModule",{value:!0}),d.SileroV5=d.SileroLegacy=void 0,s(yy(),d);var a=wy();Object.defineProperty(d,"SileroLegacy",{enumerable:!0,get:function(){return a.SileroLegacy}});var f=vy();Object.defineProperty(d,"SileroV5",{enumerable:!0,get:function(){return f.SileroV5}})})(Ls)),Ls}var ai={},kp;function pf(){if(kp)return ai;kp=1,Object.defineProperty(ai,"__esModule",{value:!0}),ai.Resampler=void 0;const d=ci();class r{constructor(a){this.options=a,this.process=f=>{const _=[];for(const C of f)for(this.inputBuffer.push(C);this.hasEnoughDataForFrame();){const R=this.generateOutputFrame();_.push(R)}return _},a.nativeSampleRate<16e3&&d.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(a){for(const f of a)for(this.inputBuffer.push(f);this.hasEnoughDataForFrame();)yield this.generateOutputFrame()}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){const a=new Float32Array(this.options.targetFrameSize);let f=0,_=0;for(;f<this.options.targetFrameSize;){let C=0,R=0;for(;_<Math.min(this.inputBuffer.length,(f+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const b=this.inputBuffer[_];b!==void 0&&(C+=b,R++),_++}a[f]=C/R,f++}return this.inputBuffer=this.inputBuffer.slice(_),a}}return ai.Resampler=r,ai}var Rp;function _y(){return Rp||(Rp=1,(function(d){var r=Vr&&Vr.__createBinding||(Object.create?(function(K,ie,J,Y){Y===void 0&&(Y=J);var H=Object.getOwnPropertyDescriptor(ie,J);(!H||("get"in H?!ie.__esModule:H.writable||H.configurable))&&(H={enumerable:!0,get:function(){return ie[J]}}),Object.defineProperty(K,Y,H)}):(function(K,ie,J,Y){Y===void 0&&(Y=J),K[Y]=ie[J]})),s=Vr&&Vr.__setModuleDefault||(Object.create?(function(K,ie){Object.defineProperty(K,"default",{enumerable:!0,value:ie})}):function(K,ie){K.default=ie}),a=Vr&&Vr.__importStar||function(K){if(K&&K.__esModule)return K;var ie={};if(K!=null)for(var J in K)J!=="default"&&Object.prototype.hasOwnProperty.call(K,J)&&r(ie,K,J);return s(ie,K),ie};Object.defineProperty(d,"__esModule",{value:!0}),d.NonRealTimeVAD=d.defaultNonRealTimeVADOptions=void 0;const f=a(gy()),_=uf(),C=Io(),R=Mo(),b=qi(),U=hf(),z=pf();d.defaultNonRealTimeVADOptions={...R.defaultFrameProcessorOptions,modelURL:_.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:C.defaultModelFetcher};class re{static async new(ie={}){const J={...d.defaultNonRealTimeVADOptions,...ie};(0,R.validateOptions)(J),J.ortConfig!==void 0&&J.ortConfig(f);const Y=()=>J.modelFetcher(J.modelURL),H=await U.SileroLegacy.new(f,Y),se=new R.FrameProcessor(H.process,H.reset_state,{positiveSpeechThreshold:J.positiveSpeechThreshold,negativeSpeechThreshold:J.negativeSpeechThreshold,redemptionMs:J.redemptionMs,preSpeechPadMs:J.preSpeechPadMs,minSpeechMs:J.minSpeechMs,submitUserSpeechOnPause:J.submitUserSpeechOnPause},1536/16);return se.resume(),new this(Y,f,J,se)}constructor(ie,J,Y,H){this.modelFetcher=ie,this.ort=J,this.options=Y,this.frameProcessor=H,this.frameSamples=1536}async*run(ie,J){const Y={nativeSampleRate:J,targetSampleRate:16e3,targetFrameSize:this.frameSamples},H=new z.Resampler(Y);let se=0,ve=0,de=0;for await(const pe of H.stream(ie)){const ce=[];await this.frameProcessor.process(pe,Ke=>{ce.push(Ke)});for(const Ke of ce)switch(Ke.msg){case b.Message.SpeechStart:se=de*this.frameSamples/16;break;case b.Message.SpeechEnd:ve=(de+1)*this.frameSamples/16,yield{audio:Ke.audio,start:se,end:ve};break}de++}const he=[];this.frameProcessor.endSegment(pe=>{he.push(pe)});for(const pe of he)switch(pe.msg){case b.Message.SpeechEnd:yield{audio:pe.audio,start:se,end:de*this.frameSamples/16}}}}d.NonRealTimeVAD=re})(Vr)),Vr}var vr={},Ap;function by(){if(Ap)return vr;Ap=1,Object.defineProperty(vr,"__esModule",{value:!0}),vr.audioFileToArray=vr.encodeWAV=vr.arrayBufferToBase64=vr.minFramesForTargetMS=void 0;function d(R,b,U=16e3){return Math.ceil(R*U/1e3/b)}vr.minFramesForTargetMS=d;function r(R){const b=new Uint8Array(R),U=b.byteLength,z=new Array(U);for(let re=0;re<U;re++){const K=b[re];if(K===void 0)break;z[re]=String.fromCharCode(K)}return btoa(z.join(""))}vr.arrayBufferToBase64=r;function s(R,b=3,U=16e3,z=1,re=32){const K=re/8,ie=z*K,J=new ArrayBuffer(44+R.length*K),Y=new DataView(J);return _(Y,0,"RIFF"),Y.setUint32(4,36+R.length*K,!0),_(Y,8,"WAVE"),_(Y,12,"fmt "),Y.setUint32(16,16,!0),Y.setUint16(20,b,!0),Y.setUint16(22,z,!0),Y.setUint32(24,U,!0),Y.setUint32(28,U*ie,!0),Y.setUint16(32,ie,!0),Y.setUint16(34,re,!0),_(Y,36,"data"),Y.setUint32(40,R.length*K,!0),b===1?f(Y,44,R):a(Y,44,R),J}vr.encodeWAV=s;function a(R,b,U){for(let z=0;z<U.length;z++,b+=4)R.setFloat32(b,U[z],!0)}function f(R,b,U){for(let z=0;z<U.length;z++,b+=2){const re=Math.max(-1,Math.min(1,U[z]));R.setInt16(b,re<0?re*32768:re*32767,!0)}}function _(R,b,U){for(let z=0;z<U.length;z++)R.setUint8(b+z,U.charCodeAt(z))}async function C(R){const b=new OfflineAudioContext(1,1,44100),U=new FileReader;let z=null;if(await new Promise(ie=>{U.addEventListener("loadend",()=>{const J=U.result;b.decodeAudioData(J,Y=>{z=Y,b.startRendering().then(()=>{console.log("Rendering completed successfully"),ie()}).catch(H=>{console.error("Rendering failed: ",H)})},Y=>{console.log("Error with decoding audio data: ",Y)})}),U.readAsArrayBuffer(R)}),z===null)throw Error("some shit");const re=z,K=new Float32Array(re.length);for(let ie=0;ie<re.length;ie++)for(let J=0;J<re.numberOfChannels;J++){const Y=re.getChannelData(J)[ie],H=K[ie];if(Y===void 0||H===void 0)throw new Error("sample or out[i] is undefined");K[ie]=H+Y}return{audio:K,sampleRate:re.sampleRate}}return vr.audioFileToArray=C,vr}var Gr={},io={exports:{}};/*!
|
|
2835
|
+
* ONNX Runtime Web v1.26.0
|
|
2836
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2837
|
+
* Licensed under the MIT License.
|
|
2838
|
+
*/var Ip;function Sy(){return Ip||(Ip=1,(function(d,r){var s=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,_=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(y=>typeof ur<"u"?ur:typeof Proxy<"u"?new Proxy(y,{get:(E,A)=>(typeof ur<"u"?ur:E)[A]}):y)(function(y){if(typeof ur<"u")return ur.apply(this,arguments);throw Error('Dynamic require of "'+y+'" is not supported')}),b=(y,E)=>()=>(y&&(E=y(y=0)),E),U=(y,E)=>{for(var A in E)a(y,A,{get:E[A],enumerable:!0})},z=(y,E,A,D)=>{if(E&&typeof E=="object"||typeof E=="function")for(let O of _(E))!C.call(y,O)&&O!==A&&a(y,O,{get:()=>E[O],enumerable:!(D=f(E,O))||D.enumerable});return y},re=y=>z(a({},"__esModule",{value:!0}),y),K,ie,J,Y,H,se=b(()=>{K=new Map,ie=[],J=(y,E,A)=>{if(E&&typeof E.init=="function"&&typeof E.createInferenceSessionHandler=="function"){let D=K.get(y);if(D===void 0)K.set(y,{backend:E,priority:A});else{if(D.priority>A)return;if(D.priority===A&&D.backend!==E)throw new Error(`cannot register backend "${y}" using priority ${A}`)}if(A>=0){let O=ie.indexOf(y);O!==-1&&ie.splice(O,1);for(let G=0;G<ie.length;G++)if(K.get(ie[G]).priority<=A){ie.splice(G,0,y);return}ie.push(y)}return}throw new TypeError("not a valid backend")},Y=async y=>{let E=K.get(y);if(!E)return"backend not found.";if(E.initialized)return E.backend;if(E.aborted)return E.error;{let A=!!E.initPromise;try{return A||(E.initPromise=E.backend.init(y)),await E.initPromise,E.initialized=!0,E.backend}catch(D){return A||(E.error=`${D}`,E.aborted=!0),E.error}finally{delete E.initPromise}}},H=async y=>{let E=y.executionProviders||[],A=E.map(V=>typeof V=="string"?V:V.name),D=A.length===0?ie:A,O,G=[],N=new Set;for(let V of D){let te=await Y(V);typeof te=="string"?G.push({name:V,err:te}):(O||(O=te),O===te&&N.add(V))}if(!O)throw new Error(`no available backend found. ERR: ${G.map(V=>`[${V.name}] ${V.err}`).join(", ")}`);for(let{name:V,err:te}of G)A.includes(V)&&console.warn(`removing requested execution provider "${V}" from session options because it is not available: ${te}`);let L=E.filter(V=>N.has(typeof V=="string"?V:V.name));return[O,new Proxy(y,{get:(V,te)=>te==="executionProviders"?L:Reflect.get(V,te)})]}}),ve=b(()=>{se()}),de,he=b(()=>{de="1.26.0"}),pe,ce,Ke=b(()=>{he(),pe="warning",ce={wasm:{},webgl:{},webgpu:{},versions:{common:de},set logLevel(y){if(y!==void 0){if(typeof y!="string"||["verbose","info","warning","error","fatal"].indexOf(y)===-1)throw new Error(`Unsupported logging level: ${y}`);pe=y}},get logLevel(){return pe}},Object.defineProperty(ce,"logLevel",{enumerable:!0})}),fe,Je=b(()=>{Ke(),fe=ce}),Ge,ot,Ze=b(()=>{Ge=(y,E)=>{let A=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);A.width=y.dims[3],A.height=y.dims[2];let D=A.getContext("2d");if(D!=null){let O,G;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(O=y.dims[2],G=y.dims[3]):(O=y.dims[3],G=y.dims[2]);let N=E?.format!==void 0?E.format:"RGB",L=E?.norm,V,te;L===void 0||L.mean===void 0?V=[255,255,255,255]:typeof L.mean=="number"?V=[L.mean,L.mean,L.mean,L.mean]:(V=[L.mean[0],L.mean[1],L.mean[2],0],L.mean[3]!==void 0&&(V[3]=L.mean[3])),L===void 0||L.bias===void 0?te=[0,0,0,0]:typeof L.bias=="number"?te=[L.bias,L.bias,L.bias,L.bias]:(te=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(te[3]=L.bias[3]));let ne=G*O,Z=0,Q=ne,Se=ne*2,F=-1;N==="RGBA"?(Z=0,Q=ne,Se=ne*2,F=ne*3):N==="RGB"?(Z=0,Q=ne,Se=ne*2):N==="RBG"&&(Z=0,Se=ne,Q=ne*2);for(let le=0;le<G;le++)for(let ut=0;ut<O;ut++){let Be=(y.data[Z++]-te[0])*V[0],Te=(y.data[Q++]-te[1])*V[1],Ne=(y.data[Se++]-te[2])*V[2],ye=F===-1?255:(y.data[F++]-te[3])*V[3];D.fillStyle="rgba("+Be+","+Te+","+Ne+","+ye+")",D.fillRect(ut,le,1,1)}if("toDataURL"in A)return A.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},ot=(y,E)=>{let A=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),D;if(A!=null){let O,G,N;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(O=y.dims[2],G=y.dims[1],N=y.dims[3]):(O=y.dims[3],G=y.dims[2],N=y.dims[1]);let L=E!==void 0&&E.format!==void 0?E.format:"RGB",V=E?.norm,te,ne;V===void 0||V.mean===void 0?te=[255,255,255,255]:typeof V.mean=="number"?te=[V.mean,V.mean,V.mean,V.mean]:(te=[V.mean[0],V.mean[1],V.mean[2],255],V.mean[3]!==void 0&&(te[3]=V.mean[3])),V===void 0||V.bias===void 0?ne=[0,0,0,0]:typeof V.bias=="number"?ne=[V.bias,V.bias,V.bias,V.bias]:(ne=[V.bias[0],V.bias[1],V.bias[2],0],V.bias[3]!==void 0&&(ne[3]=V.bias[3]));let Z=G*O;if(E!==void 0&&(E.format!==void 0&&N===4&&E.format!=="RGBA"||N===3&&E.format!=="RGB"&&E.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Q=4,Se=0,F=1,le=2,ut=3,Be=0,Te=Z,Ne=Z*2,ye=-1;L==="RGBA"?(Be=0,Te=Z,Ne=Z*2,ye=Z*3):L==="RGB"?(Be=0,Te=Z,Ne=Z*2):L==="RBG"&&(Be=0,Ne=Z,Te=Z*2),D=A.createImageData(O,G);for(let Rt=0;Rt<G*O;Se+=Q,F+=Q,le+=Q,ut+=Q,Rt++)D.data[Se]=(y.data[Be++]-ne[0])*te[0],D.data[F]=(y.data[Te++]-ne[1])*te[1],D.data[le]=(y.data[Ne++]-ne[2])*te[2],D.data[ut]=ye===-1?255:(y.data[ye++]-ne[3])*te[3]}else throw new Error("Can not access image data");return D}}),it,tt,Wt,xt,je,qe,st=b(()=>{Tr(),it=(y,E)=>{if(y===void 0)throw new Error("Image buffer must be defined");if(E.height===void 0||E.width===void 0)throw new Error("Image height and width must be defined");if(E.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:A,width:D}=E,O=E.norm??{mean:255,bias:0},G,N;typeof O.mean=="number"?G=[O.mean,O.mean,O.mean,O.mean]:G=[O.mean[0],O.mean[1],O.mean[2],O.mean[3]??255],typeof O.bias=="number"?N=[O.bias,O.bias,O.bias,O.bias]:N=[O.bias[0],O.bias[1],O.bias[2],O.bias[3]??0];let L=E.format!==void 0?E.format:"RGBA",V=E.tensorFormat!==void 0&&E.tensorFormat!==void 0?E.tensorFormat:"RGB",te=A*D,ne=V==="RGBA"?new Float32Array(te*4):new Float32Array(te*3),Z=4,Q=0,Se=1,F=2,le=3,ut=0,Be=te,Te=te*2,Ne=-1;L==="RGB"&&(Z=3,Q=0,Se=1,F=2,le=-1),V==="RGBA"?Ne=te*3:V==="RBG"?(ut=0,Te=te,Be=te*2):V==="BGR"&&(Te=0,Be=te,ut=te*2);for(let ye=0;ye<te;ye++,Q+=Z,F+=Z,Se+=Z,le+=Z)ne[ut++]=(y[Q]+N[0])/G[0],ne[Be++]=(y[Se]+N[1])/G[1],ne[Te++]=(y[F]+N[2])/G[2],Ne!==-1&&le!==-1&&(ne[Ne++]=(y[le]+N[3])/G[3]);return V==="RGBA"?new rt("float32",ne,[1,4,A,D]):new rt("float32",ne,[1,3,A,D])},tt=async(y,E)=>{let A=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,D=typeof ImageData<"u"&&y instanceof ImageData,O=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,G=typeof y=="string",N,L=E??{},V=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},te=ne=>typeof HTMLCanvasElement<"u"&&ne instanceof HTMLCanvasElement||ne instanceof OffscreenCanvas?ne.getContext("2d"):null;if(A){let ne=V();ne.width=y.width,ne.height=y.height;let Z=te(ne);if(Z!=null){let Q=y.height,Se=y.width;if(E!==void 0&&E.resizedHeight!==void 0&&E.resizedWidth!==void 0&&(Q=E.resizedHeight,Se=E.resizedWidth),E!==void 0){if(L=E,E.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");L.tensorFormat="RGBA",L.height=Q,L.width=Se}else L.tensorFormat="RGBA",L.height=Q,L.width=Se;Z.drawImage(y,0,0),N=Z.getImageData(0,0,Se,Q).data}else throw new Error("Can not access image data")}else if(D){let ne,Z;if(E!==void 0&&E.resizedWidth!==void 0&&E.resizedHeight!==void 0?(ne=E.resizedHeight,Z=E.resizedWidth):(ne=y.height,Z=y.width),E!==void 0&&(L=E),L.format="RGBA",L.height=ne,L.width=Z,E!==void 0){let Q=V();Q.width=Z,Q.height=ne;let Se=te(Q);if(Se!=null)Se.putImageData(y,0,0),N=Se.getImageData(0,0,Z,ne).data;else throw new Error("Can not access image data")}else N=y.data}else if(O){if(E===void 0)throw new Error("Please provide image config with format for Imagebitmap");let ne=V();ne.width=y.width,ne.height=y.height;let Z=te(ne);if(Z!=null){let Q=y.height,Se=y.width;return Z.drawImage(y,0,0,Se,Q),N=Z.getImageData(0,0,Se,Q).data,L.height=Q,L.width=Se,it(N,L)}else throw new Error("Can not access image data")}else{if(G)return new Promise((ne,Z)=>{let Q=V(),Se=te(Q);if(!y||!Se)return Z();let F=new Image;F.crossOrigin="Anonymous",F.src=y,F.onload=()=>{Q.width=F.width,Q.height=F.height,Se.drawImage(F,0,0,Q.width,Q.height);let le=Se.getImageData(0,0,Q.width,Q.height);L.height=Q.height,L.width=Q.width,ne(it(le.data,L))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(N!==void 0)return it(N,L);throw new Error("Input data provided is not supported - aborted tensor creation")},Wt=(y,E)=>{let{width:A,height:D,download:O,dispose:G}=E,N=[1,D,A,4];return new rt({location:"texture",type:"float32",texture:y,dims:N,download:O,dispose:G})},xt=(y,E)=>{let{dataType:A,dims:D,download:O,dispose:G}=E;return new rt({location:"gpu-buffer",type:A??"float32",gpuBuffer:y,dims:D,download:O,dispose:G})},je=(y,E)=>{let{dataType:A,dims:D,download:O,dispose:G}=E;return new rt({location:"ml-tensor",type:A??"float32",mlTensor:y,dims:D,download:O,dispose:G})},qe=(y,E,A)=>new rt({location:"cpu-pinned",type:y,data:E,dims:A??[E.length]})}),ze,At,sr,Hr,Us=b(()=>{ze=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),At=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),sr=!1,Hr=()=>{if(!sr){sr=!0;let y=typeof BigInt64Array<"u"&&BigInt64Array.from,E=typeof BigUint64Array<"u"&&BigUint64Array.from,A=globalThis.Float16Array,D=typeof A<"u"&&A.from;y&&(ze.set("int64",BigInt64Array),At.set(BigInt64Array,"int64")),E&&(ze.set("uint64",BigUint64Array),At.set(BigUint64Array,"uint64")),D?(ze.set("float16",A),At.set(A,"float16")):ze.set("float16",Uint16Array)}}}),Kr,jr,Fs=b(()=>{Tr(),Kr=y=>{let E=1;for(let A=0;A<y.length;A++){let D=y[A];if(typeof D!="number"||!Number.isSafeInteger(D))throw new TypeError(`dims[${A}] must be an integer, got: ${D}`);if(D<0)throw new RangeError(`dims[${A}] must be a non-negative integer, got: ${D}`);E*=D}return E},jr=(y,E)=>{switch(y.location){case"cpu":return new rt(y.type,y.data,E);case"cpu-pinned":return new rt({location:"cpu-pinned",data:y.data,type:y.type,dims:E});case"texture":return new rt({location:"texture",texture:y.texture,type:y.type,dims:E});case"gpu-buffer":return new rt({location:"gpu-buffer",gpuBuffer:y.gpuBuffer,type:y.type,dims:E});case"ml-tensor":return new rt({location:"ml-tensor",mlTensor:y.mlTensor,type:y.type,dims:E});default:throw new Error(`tensorReshape: tensor location ${y.location} is not supported`)}}}),rt,Tr=b(()=>{Ze(),st(),Us(),Fs(),rt=class{constructor(y,E,A){Hr();let D,O;if(typeof y=="object"&&"location"in y)switch(this.dataLocation=y.location,D=y.type,O=y.dims,y.location){case"cpu-pinned":{let N=ze.get(D);if(!N)throw new TypeError(`unsupported type "${D}" to create tensor from pinned buffer`);if(!(y.data instanceof N))throw new TypeError(`buffer should be of type ${N.name}`);this.cpuData=y.data;break}case"texture":{if(D!=="float32")throw new TypeError(`unsupported type "${D}" to create tensor from texture`);this.gpuTextureData=y.texture,this.downloader=y.download,this.disposer=y.dispose;break}case"gpu-buffer":{if(D!=="float32"&&D!=="float16"&&D!=="int32"&&D!=="int64"&&D!=="uint32"&&D!=="uint8"&&D!=="bool"&&D!=="uint4"&&D!=="int4")throw new TypeError(`unsupported type "${D}" to create tensor from gpu buffer`);this.gpuBufferData=y.gpuBuffer,this.downloader=y.download,this.disposer=y.dispose;break}case"ml-tensor":{if(D!=="float32"&&D!=="float16"&&D!=="int32"&&D!=="int64"&&D!=="uint32"&&D!=="uint64"&&D!=="int8"&&D!=="uint8"&&D!=="bool"&&D!=="uint4"&&D!=="int4")throw new TypeError(`unsupported type "${D}" to create tensor from MLTensor`);this.mlTensorData=y.mlTensor,this.downloader=y.download,this.disposer=y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let N,L;if(typeof y=="string")if(D=y,L=A,y==="string"){if(!Array.isArray(E))throw new TypeError("A string tensor's data must be a string array.");N=E}else{let V=ze.get(y);if(V===void 0)throw new TypeError(`Unsupported tensor type: ${y}.`);if(Array.isArray(E)){if(y==="float16"&&V===Uint16Array||y==="uint4"||y==="int4")throw new TypeError(`Creating a ${y} tensor from number array is not supported. Please use ${V.name} as data.`);y==="uint64"||y==="int64"?N=V.from(E,BigInt):N=V.from(E)}else if(E instanceof V)N=E;else if(E instanceof Uint8ClampedArray)if(y==="uint8")N=Uint8Array.from(E);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(y==="float16"&&E instanceof Uint16Array&&V!==Uint16Array)N=new globalThis.Float16Array(E.buffer,E.byteOffset,E.length);else throw new TypeError(`A ${D} tensor's data must be type of ${V}`)}else if(L=E,Array.isArray(y)){if(y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let V=typeof y[0];if(V==="string")D="string",N=y;else if(V==="boolean")D="bool",N=Uint8Array.from(y);else throw new TypeError(`Invalid element type of data array: ${V}.`)}else if(y instanceof Uint8ClampedArray)D="uint8",N=Uint8Array.from(y);else{let V=At.get(y.constructor);if(V===void 0)throw new TypeError(`Unsupported type for tensor data: ${y.constructor}.`);D=V,N=y}if(L===void 0)L=[N.length];else if(!Array.isArray(L))throw new TypeError("A tensor's dims must be a number array");O=L,this.cpuData=N,this.dataLocation="cpu"}let G=Kr(O);if(this.cpuData&&G!==this.cpuData.length&&!((D==="uint4"||D==="int4")&&Math.ceil(G/2)===this.cpuData.length))throw new Error(`Tensor's size(${G}) does not match data length(${this.cpuData.length}).`);this.type=D,this.dims=O,this.size=G}static async fromImage(y,E){return tt(y,E)}static fromTexture(y,E){return Wt(y,E)}static fromGpuBuffer(y,E){return xt(y,E)}static fromMLTensor(y,E){return je(y,E)}static fromPinnedBuffer(y,E,A){return qe(y,E,A)}toDataURL(y){return Ge(this,y)}toImageData(y){return ot(this,y)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(y){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let E=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=E,y&&this.disposer&&(this.disposer(),this.disposer=void 0),E}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(y){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return jr(this,y)}}}),lt,Qr=b(()=>{Tr(),lt=rt}),er,Er,gt,yt,Ct,kt,Xr=b(()=>{Ke(),er=(y,E)=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.timeStamp(`${y}::ORT::${E}`)},Er=(y,E)=>{let A=new Error().stack?.split(/\r\n|\r|\n/g)||[],D=!1;for(let O=0;O<A.length;O++){if(D&&!A[O].includes("TRACE_FUNC")){let G=`FUNC_${y}::${A[O].trim().split(" ")[1]}`;E&&(G+=`::${E}`),er("CPU",G);return}A[O].includes("TRACE_FUNC")&&(D=!0)}},gt=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||Er("BEGIN",y)},yt=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||Er("END",y)},Ct=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.time(`ORT::${y}`)},kt=y=>{(typeof ce.trace>"u"?!ce.wasm.trace:!ce.trace)||console.timeEnd(`ORT::${y}`)}}),os,xe=b(()=>{se(),Qr(),Xr(),os=class ff{constructor(E){this.handler=E}async run(E,A,D){gt(),Ct("InferenceSession.run");let O={},G={};if(typeof E!="object"||E===null||E instanceof lt||Array.isArray(E))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let N=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof lt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");N=!1;for(let te of A){if(typeof te!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(te)===-1)throw new RangeError(`'fetches' contains invalid output name: ${te}.`);O[te]=null}if(typeof D=="object"&&D!==null)G=D;else if(typeof D<"u")throw new TypeError("'options' must be an object.")}else{let te=!1,ne=Object.getOwnPropertyNames(A);for(let Z of this.outputNames)if(ne.indexOf(Z)!==-1){let Q=A[Z];(Q===null||Q instanceof lt)&&(te=!0,N=!1,O[Z]=Q)}if(te){if(typeof D=="object"&&D!==null)G=D;else if(typeof D<"u")throw new TypeError("'options' must be an object.")}else G=A}}else if(typeof A<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let te of this.inputNames)if(typeof E[te]>"u")throw new Error(`input '${te}' is missing in 'feeds'.`);if(N)for(let te of this.outputNames)O[te]=null;let L=await this.handler.run(E,O,G),V={};for(let te in L)if(Object.hasOwnProperty.call(L,te)){let ne=L[te];ne instanceof lt?V[te]=ne:V[te]=new lt(ne.type,ne.data,ne.dims)}return kt("InferenceSession.run"),yt(),V}async release(){return this.handler.dispose()}static async create(E,A,D,O){gt(),Ct("InferenceSession.create");let G,N={};if(typeof E=="string"){if(G=E,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(E instanceof Uint8Array){if(G=E,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(E instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&E instanceof SharedArrayBuffer){let ne=E,Z=0,Q=E.byteLength;if(typeof A=="object"&&A!==null)N=A;else if(typeof A=="number"){if(Z=A,!Number.isSafeInteger(Z))throw new RangeError("'byteOffset' must be an integer.");if(Z<0||Z>=ne.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${ne.byteLength}).`);if(Q=E.byteLength-Z,typeof D=="number"){if(Q=D,!Number.isSafeInteger(Q))throw new RangeError("'byteLength' must be an integer.");if(Q<=0||Z+Q>ne.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${ne.byteLength-Z}].`);if(typeof O=="object"&&O!==null)N=O;else if(typeof O<"u")throw new TypeError("'options' must be an object.")}else if(typeof D<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof A<"u")throw new TypeError("'options' must be an object.");G=new Uint8Array(ne,Z,Q)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[L,V]=await H(N),te=await L.createInferenceSessionHandler(G,V);return kt("InferenceSession.create"),yt(),new ff(te)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Qe,Nt=b(()=>{xe(),Qe=os}),nr=b(()=>{}),It=b(()=>{}),Yr=b(()=>{}),hn=b(()=>{}),ls={};U(ls,{InferenceSession:()=>Qe,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>Ct,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>yt,Tensor:()=>lt,env:()=>fe,registerBackend:()=>J});var ct=b(()=>{ve(),Je(),Nt(),Qr(),nr(),It(),Xr(),Yr(),hn()}),Ut=b(()=>{}),$r={};U($r,{default:()=>pn});var Lt,us,pn,Wi=b(()=>{Mn(),Ht(),fs(),Lt="ort-wasm-proxy-worker",us=globalThis.self?.name===Lt,us&&(self.onmessage=y=>{let{type:E,in:A}=y.data;try{switch(E){case"init-wasm":ys(A.wasm).then(()=>{Gs(A).then(()=>{postMessage({type:E})},D=>{postMessage({type:E,err:D})})},D=>{postMessage({type:E,err:D})});break;case"init-ep":{let{epName:D,env:O}=A;qs(O,D).then(()=>{postMessage({type:E})},G=>{postMessage({type:E,err:G})});break}case"copy-from":{let{buffer:D}=A,O=We(D);postMessage({type:E,out:O});break}case"create":{let{model:D,options:O}=A;tr(D,O).then(G=>{postMessage({type:E,out:G})},G=>{postMessage({type:E,err:G})});break}case"release":Ks(A),postMessage({type:E});break;case"run":{let{sessionId:D,inputIndices:O,inputs:G,outputIndices:N,options:L}=A;j(D,O,G,N,new Array(N.length).fill(null),L).then(V=>{V.some(te=>te[3]!=="cpu")?postMessage({type:E,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:E,out:V},js([...G,...V]))},V=>{postMessage({type:E,err:V})});break}case"end-profiling":Jr(A),postMessage({type:E});break;default:}}catch(D){postMessage({type:E,err:D})}}),pn=us?null:y=>new Worker(y??at,{type:"classic",name:Lt})}),fn,mn,at,ds,Dr,gn,yn,cs,wn,hs,vn,ps,_n,fs=b(()=>{Ut(),fn=typeof location>"u"?void 0:location.origin,mn=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,at=mn(),ds=()=>{if(at&&!at.startsWith("blob:"))return at.substring(0,at.lastIndexOf("/")+1)},Dr=(y,E)=>{try{let A=E??at;return(A?new URL(y,A):new URL(y)).origin===fn}catch{return!1}},gn=(y,E)=>{let A=E??at;try{return(A?new URL(y,A):new URL(y)).href}catch{return}},yn=(y,E)=>`${E??"./"}${y}`,cs=async y=>{let E=await(await fetch(y,{credentials:"same-origin"})).blob();return URL.createObjectURL(E)},wn=async y=>(await import(y)).default,hs=(Wi(),re($r)).default,vn=async()=>{if(!at)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Dr(at))return[void 0,hs()];let y=await cs(at);return[y,hs(y)]},ps=void 0,_n=async(y,E,A,D)=>{let O=ps&&!(y||E);if(O)if(at)O=Dr(at)||D&&!A;else if(D&&!A)O=!0;else throw new Error("cannot determine the script source URL.");if(O)return[void 0,ps];{let G="ort-wasm-simd-threaded.mjs",N=y??gn(G,E),L=A&&N&&!Dr(N,E),V=L?await cs(N):N??yn(G,E);return[L?V:void 0,await wn(V)]}}}),ms,zr,dr,gs,bn,Sn,Tn,ys,Pe,Ht=b(()=>{fs(),zr=!1,dr=!1,gs=!1,bn=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Sn=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Tn=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},ys=async y=>{if(zr)return Promise.resolve();if(dr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(gs)throw new Error("previous call to 'initializeWebAssembly()' failed.");dr=!0;let E=y.initTimeout,A=y.numThreads;if(y.simd!==!1){if(y.simd==="relaxed"){if(!Tn())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Sn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let D=bn();A>1&&!D&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+A+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),y.numThreads=A=1);let O=y.wasmPaths,G=typeof O=="string"?O:void 0,N=O?.mjs,L=N?.href??N,V=O?.wasm,te=V?.href??V,ne=y.wasmBinary,[Z,Q]=await _n(L,G,A>1,!!ne||!!te),Se=!1,F=[];if(E>0&&F.push(new Promise(le=>{setTimeout(()=>{Se=!0,le()},E)})),F.push(new Promise((le,ut)=>{let Be={numThreads:A};if(ne)Be.wasmBinary=ne,Be.locateFile=Te=>Te;else if(te||G)Be.locateFile=Te=>te??G+Te;else if(L&&L.indexOf("blob:")!==0)Be.locateFile=Te=>new URL(Te,L).href;else if(Z){let Te=ds();Te&&(Be.locateFile=Ne=>Te+Ne)}Q(Be).then(Te=>{dr=!1,zr=!0,ms=Te,le(),Z&&URL.revokeObjectURL(Z)},Te=>{dr=!1,gs=!0,ut(Te)})})),await Promise.race(F),Se)throw new Error(`WebAssembly backend initializing failed due to timeout: ${E}ms`)},Pe=()=>{if(zr&&ms)return ms;throw new Error("WebAssembly is not initialized yet.")}}),mt,Lr,Ce,ws=b(()=>{Ht(),mt=(y,E)=>{let A=Pe(),D=A.lengthBytesUTF8(y)+1,O=A._malloc(D);return A.stringToUTF8(y,O,D),E.push(O),O},Lr=(y,E,A,D)=>{if(typeof y=="object"&&y!==null){if(A.has(y))throw new Error("Circular reference in options");A.add(y)}Object.entries(y).forEach(([O,G])=>{let N=E?E+O:O;if(typeof G=="object")Lr(G,N+".",A,D);else if(typeof G=="string"||typeof G=="number")D(N,G.toString());else if(typeof G=="boolean")D(N,G?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof G}`)})},Ce=y=>{let E=Pe(),A=E.stackSave();try{let D=E.PTR_SIZE,O=E.stackAlloc(2*D);E._OrtGetLastError(O,O+D);let G=Number(E.getValue(O,D===4?"i32":"i64")),N=E.getValue(O+D,"*"),L=N?E.UTF8ToString(N):"";throw new Error(`${y} ERROR_CODE: ${G}, ERROR_MESSAGE: ${L}`)}finally{E.stackRestore(A)}}}),En,Hi=b(()=>{Ht(),ws(),En=y=>{let E=Pe(),A=0,D=[],O=y||{};try{if(y?.logSeverityLevel===void 0)O.logSeverityLevel=2;else if(typeof y.logSeverityLevel!="number"||!Number.isInteger(y.logSeverityLevel)||y.logSeverityLevel<0||y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${y.logSeverityLevel}`);if(y?.logVerbosityLevel===void 0)O.logVerbosityLevel=0;else if(typeof y.logVerbosityLevel!="number"||!Number.isInteger(y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${y.logVerbosityLevel}`);y?.terminate===void 0&&(O.terminate=!1);let G=0;return y?.tag!==void 0&&(G=mt(y.tag,D)),A=E._OrtCreateRunOptions(O.logSeverityLevel,O.logVerbosityLevel,!!O.terminate,G),A===0&&Ce("Can't create run options."),y?.extra!==void 0&&Lr(y.extra,"",new WeakSet,(N,L)=>{let V=mt(N,D),te=mt(L,D);E._OrtAddRunConfigEntry(A,V,te)!==0&&Ce(`Can't set a run config entry: ${N} - ${L}.`)}),[A,D]}catch(G){throw A!==0&&E._OrtReleaseRunOptions(A),D.forEach(N=>E._free(N)),G}}}),$n,xn,Cn,Ft,kn,Rn,Ki=b(()=>{Ht(),ws(),$n=y=>{switch(y){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${y}`)}},xn=y=>{switch(y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${y}`)}},Cn=y=>{y.extra||(y.extra={}),y.extra.session||(y.extra.session={});let E=y.extra.session;E.use_ort_model_bytes_directly||(E.use_ort_model_bytes_directly="1"),y.executionProviders&&y.executionProviders.some(A=>(typeof A=="string"?A:A.name)==="webgpu")&&(y.enableMemPattern=!1)},Ft=(y,E,A,D)=>{let O=mt(E,D),G=mt(A,D);Pe()._OrtAddSessionConfigEntry(y,O,G)!==0&&Ce(`Can't set a session config entry: ${E} - ${A}.`)},kn=async(y,E,A)=>{let D=E.executionProviders;for(let O of D){let G=typeof O=="string"?O:O.name,N=[];switch(G){case"webnn":if(G="WEBNN",Ft(y,"session.disable_quant_qdq","1",A),Ft(y,"session.disable_qdq_constant_folding","1",A),typeof O!="string"){let Z=O?.deviceType;Z&&Ft(y,"deviceType",Z,A)}break;case"webgpu":if(G="JS",typeof O!="string"){let Z=O;if(Z?.preferredLayout){if(Z.preferredLayout!=="NCHW"&&Z.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${Z.preferredLayout}`);Ft(y,"preferredLayout",Z.preferredLayout,A)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${G}`)}let L=mt(G,A),V=N.length,te=0,ne=0;if(V>0){te=Pe()._malloc(V*Pe().PTR_SIZE),A.push(te),ne=Pe()._malloc(V*Pe().PTR_SIZE),A.push(ne);for(let Z=0;Z<V;Z++)Pe().setValue(te+Z*Pe().PTR_SIZE,N[Z][0],"*"),Pe().setValue(ne+Z*Pe().PTR_SIZE,N[Z][1],"*")}await Pe()._OrtAppendExecutionProvider(y,L,te,ne,V)!==0&&Ce(`Can't append execution provider: ${G}.`)}},Rn=async y=>{let E=Pe(),A=0,D=[],O=y||{};Cn(O);try{let G=$n(O.graphOptimizationLevel??"all"),N=xn(O.executionMode??"sequential"),L=typeof O.logId=="string"?mt(O.logId,D):0,V=O.logSeverityLevel??2;if(!Number.isInteger(V)||V<0||V>4)throw new Error(`log severity level is not valid: ${V}`);let te=O.logVerbosityLevel??0;if(!Number.isInteger(te)||te<0||te>4)throw new Error(`log verbosity level is not valid: ${te}`);let ne=typeof O.optimizedModelFilePath=="string"?mt(O.optimizedModelFilePath,D):0;if(A=E._OrtCreateSessionOptions(G,!!O.enableCpuMemArena,!!O.enableMemPattern,N,!!O.enableProfiling,0,L,V,te,ne),A===0&&Ce("Can't create session options."),O.executionProviders&&await kn(A,O,D),O.enableGraphCapture!==void 0){if(typeof O.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${O.enableGraphCapture}`);Ft(A,"enableGraphCapture",O.enableGraphCapture.toString(),D)}if(O.freeDimensionOverrides)for(let[Z,Q]of Object.entries(O.freeDimensionOverrides)){if(typeof Z!="string")throw new Error(`free dimension override name must be a string: ${Z}`);if(typeof Q!="number"||!Number.isInteger(Q)||Q<0)throw new Error(`free dimension override value must be a non-negative integer: ${Q}`);let Se=mt(Z,D);E._OrtAddFreeDimensionOverride(A,Se,Q)!==0&&Ce(`Can't set a free dimension override: ${Z} - ${Q}.`)}return O.extra!==void 0&&Lr(O.extra,"",new WeakSet,(Z,Q)=>{Ft(A,Z,Q,D)}),[A,D]}catch(G){throw A!==0&&E._OrtReleaseSessionOptions(A)!==0&&Ce("Can't release session options."),D.forEach(N=>E._free(N)),G}}}),Kt,jt,Qt,vs,_s,bs,Ss,Vs,Ie=b(()=>{Kt=y=>{switch(y){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${y}`)}},jt=y=>{switch(y){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${y}`)}},Qt=(y,E)=>{let A=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][y],D=typeof E=="number"?E:E.reduce((O,G)=>O*G,1);return A>0?Math.ceil(D*A):void 0},vs=y=>{switch(y){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${y}`)}},_s=y=>{switch(y){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${y}`)}},bs=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Ss=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint64"||y==="int8"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Vs=y=>{switch(y){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${y}`)}}}),Ts,An=b(()=>{Ut(),Ts=async y=>{if(typeof y=="string"){let E=await fetch(y);if(!E.ok)throw new Error(`failed to load external data file: ${y}`);let A=E.headers.get("Content-Length"),D=A?parseInt(A,10):0;if(D<1073741824)return new Uint8Array(await E.arrayBuffer());{if(!E.body)throw new Error(`failed to load external data file: ${y}, no response body.`);let O=E.body.getReader(),G;try{G=new ArrayBuffer(D)}catch(L){if(L instanceof RangeError){let V=Math.ceil(D/65536);G=new WebAssembly.Memory({initial:V,maximum:V}).buffer}else throw L}let N=0;for(;;){let{done:L,value:V}=await O.read();if(L)break;let te=V.byteLength;new Uint8Array(G,N,te).set(V),N+=te}return new Uint8Array(G,0,D)}}else return y instanceof Blob?new Uint8Array(await y.arrayBuffer()):y instanceof Uint8Array?y:new Uint8Array(y)}}),In,Gs,qs,xr,Ws,Hs,We,tr,Ks,Cr,j,Jr,js,Mn=b(()=>{ct(),Hi(),Ki(),Ie(),Ht(),ws(),An(),In=(y,E)=>{Pe()._OrtInit(y,E)!==0&&Ce("Can't initialize onnxruntime.")},Gs=async y=>{In(y.wasm.numThreads,_s(y.logLevel))},qs=async(y,E)=>{Pe().asyncInit?.();let A=y.webgpu.adapter;if(E==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(A){if(typeof A.limits!="object"||typeof A.features!="object"||typeof A.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let D=y.webgpu.powerPreference;if(D!==void 0&&D!=="low-power"&&D!=="high-performance")throw new Error(`Invalid powerPreference setting: "${D}"`);let O=y.webgpu.forceFallbackAdapter;if(O!==void 0&&typeof O!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${O}"`);if(A=await navigator.gpu.requestAdapter({powerPreference:D,forceFallbackAdapter:O}),!A)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(E==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},xr=new Map,Ws=y=>{let E=Pe(),A=E.stackSave();try{let D=E.PTR_SIZE,O=E.stackAlloc(2*D);E._OrtGetInputOutputCount(y,O,O+D)!==0&&Ce("Can't get session input/output count.");let G=D===4?"i32":"i64";return[Number(E.getValue(O,G)),Number(E.getValue(O+D,G))]}finally{E.stackRestore(A)}},Hs=(y,E)=>{let A=Pe(),D=A.stackSave(),O=0;try{let G=A.PTR_SIZE,N=A.stackAlloc(2*G);A._OrtGetInputOutputMetadata(y,E,N,N+G)!==0&&Ce("Can't get session input/output metadata.");let L=Number(A.getValue(N,"*"));O=Number(A.getValue(N+G,"*"));let V=A.HEAP32[O/4];if(V===0)return[L,0];let te=A.HEAPU32[O/4+1],ne=[];for(let Z=0;Z<te;Z++){let Q=Number(A.getValue(O+8+Z*G,"*"));ne.push(Q!==0?A.UTF8ToString(Q):Number(A.getValue(O+8+(Z+te)*G,"*")))}return[L,V,ne]}finally{A.stackRestore(D),O!==0&&A._OrtFree(O)}},We=y=>{let E=Pe(),A=E._malloc(y.byteLength);if(A===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${y.byteLength}.`);return E.HEAPU8.set(y,A),[A,y.byteLength]},tr=async(y,E)=>{let A,D,O=Pe();Array.isArray(y)?[A,D]=y:y.buffer===O.HEAPU8.buffer?[A,D]=[y.byteOffset,y.byteLength]:[A,D]=We(y);let G=0,N=0,L=[],V=[],te=[];try{if([N,L]=await Rn(E),E?.externalData&&O.mountExternalData){let Te=[];for(let Ne of E.externalData){let ye=typeof Ne=="string"?Ne:Ne.path;Te.push(Ts(typeof Ne=="string"?Ne:Ne.data).then(Rt=>{O.mountExternalData(ye,Rt)}))}await Promise.all(Te)}for(let Te of E?.executionProviders??[])if((typeof Te=="string"?Te:Te.name)==="webnn"){if(O.shouldTransferToMLTensor=!1,typeof Te!="string"){let Ne=Te,ye=Ne?.context,Rt=Ne?.gpuDevice,Mt=Ne?.deviceType,Ar=Ne?.powerPreference;ye?O.currentContext=ye:Rt?O.currentContext=await O.webnnCreateMLContext(Rt):O.currentContext=await O.webnnCreateMLContext({deviceType:Mt,powerPreference:Ar})}else O.currentContext=await O.webnnCreateMLContext();break}G=await O._OrtCreateSession(A,D,N),O.webgpuOnCreateSession?.(G),G===0&&Ce("Can't create a session."),O.jsepOnCreateSession?.(),O.currentContext&&(O.webnnRegisterMLContext(G,O.currentContext),O.currentContext=void 0,O.shouldTransferToMLTensor=!0);let[ne,Z]=Ws(G),Q=!!E?.enableGraphCapture,Se=[],F=[],le=[],ut=[],Be=[];for(let Te=0;Te<ne;Te++){let[Ne,ye,Rt]=Hs(G,Te);Ne===0&&Ce("Can't get an input name."),V.push(Ne);let Mt=O.UTF8ToString(Ne);Se.push(Mt),le.push(ye===0?{name:Mt,isTensor:!1}:{name:Mt,isTensor:!0,type:jt(ye),shape:Rt})}for(let Te=0;Te<Z;Te++){let[Ne,ye,Rt]=Hs(G,Te+ne);Ne===0&&Ce("Can't get an output name."),te.push(Ne);let Mt=O.UTF8ToString(Ne);F.push(Mt),ut.push(ye===0?{name:Mt,isTensor:!1}:{name:Mt,isTensor:!0,type:jt(ye),shape:Rt})}return xr.set(G,[G,V,te,null,Q,!1]),[G,Se,F,le,ut]}catch(ne){throw V.forEach(Z=>O._OrtFree(Z)),te.forEach(Z=>O._OrtFree(Z)),G!==0&&O._OrtReleaseSession(G)!==0&&Ce("Can't release session."),ne}finally{O._free(A),N!==0&&O._OrtReleaseSessionOptions(N)!==0&&Ce("Can't release session options."),L.forEach(ne=>O._free(ne)),O.unmountExternalData?.()}},Ks=y=>{let E=Pe(),A=xr.get(y);if(!A)throw new Error(`cannot release session. invalid session id: ${y}`);let[D,O,G,N,L]=A;N&&(L&&E._OrtClearBoundOutputs(N.handle)!==0&&Ce("Can't clear bound outputs."),E._OrtReleaseBinding(N.handle)!==0&&Ce("Can't release IO binding.")),E.jsepOnReleaseSession?.(y),E.webnnOnReleaseSession?.(y),E.webgpuOnReleaseSession?.(y),O.forEach(V=>E._OrtFree(V)),G.forEach(V=>E._OrtFree(V)),E._OrtReleaseSession(D)!==0&&Ce("Can't release session."),xr.delete(y)},Cr=async(y,E,A,D,O,G,N=!1)=>{if(!y){E.push(0);return}let L=Pe(),V=L.PTR_SIZE,te=y[0],ne=y[1],Z=y[3],Q=Z,Se,F;if(te==="string"&&(Z==="gpu-buffer"||Z==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(N&&Z!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${G} when enableGraphCapture is true.`);if(Z==="gpu-buffer"){let Be=y[2].gpuBuffer;F=Qt(Kt(te),ne);{let Te=L.jsepRegisterBuffer;if(!Te)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Se=Te(D,G,Be,F)}}else if(Z==="ml-tensor"){let Be=y[2].mlTensor;F=Qt(Kt(te),ne);let Te=L.webnnRegisterMLTensor;if(!Te)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Se=Te(D,Be,Kt(te),ne)}else{let Be=y[2];if(Array.isArray(Be)){F=V*Be.length,Se=L._malloc(F),A.push(Se);for(let Te=0;Te<Be.length;Te++){if(typeof Be[Te]!="string")throw new TypeError(`tensor data at index ${Te} is not a string`);L.setValue(Se+Te*V,mt(Be[Te],A),"*")}}else{let Te=L.webnnIsGraphInput,Ne=L.webnnIsGraphOutput;if(te!=="string"&&Te&&Ne){let ye=L.UTF8ToString(O);if(Te(D,ye)||Ne(D,ye)){let Rt=Kt(te);F=Qt(Rt,ne),Q="ml-tensor";let Mt=L.webnnCreateTemporaryTensor,Ar=L.webnnUploadTensor;if(!Mt||!Ar)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let rs=await Mt(D,Rt,ne);Ar(rs,new Uint8Array(Be.buffer,Be.byteOffset,Be.byteLength)),Se=rs}else F=Be.byteLength,Se=L._malloc(F),A.push(Se),L.HEAPU8.set(new Uint8Array(Be.buffer,Be.byteOffset,F),Se)}else F=Be.byteLength,Se=L._malloc(F),A.push(Se),L.HEAPU8.set(new Uint8Array(Be.buffer,Be.byteOffset,F),Se)}}let le=L.stackSave(),ut=L.stackAlloc(4*ne.length);try{ne.forEach((Te,Ne)=>L.setValue(ut+Ne*V,Te,V===4?"i32":"i64"));let Be=L._OrtCreateTensor(Kt(te),Se,F,ut,ne.length,Vs(Q));Be===0&&Ce(`Can't create tensor for input/output. session=${D}, index=${G}.`),E.push(Be)}finally{L.stackRestore(le)}},j=async(y,E,A,D,O,G)=>{let N=Pe(),L=N.PTR_SIZE,V=xr.get(y);if(!V)throw new Error(`cannot run inference. invalid session id: ${y}`);let te=V[0],ne=V[1],Z=V[2],Q=V[3],Se=V[4];V[5];let F=E.length,le=D.length,ut=0,Be=[],Te=[],Ne=[],ye=[],Rt=[],Mt=N.stackSave(),Ar=N.stackAlloc(F*L),rs=N.stackAlloc(F*L),nn=N.stackAlloc(le*L),Un=N.stackAlloc(le*L);try{[ut,Be]=En(G),Ct("wasm prepareInputOutputTensor");for(let Ue=0;Ue<F;Ue++)await Cr(A[Ue],Te,ye,y,ne[E[Ue]],E[Ue],Se);for(let Ue=0;Ue<le;Ue++)await Cr(O[Ue],Ne,ye,y,Z[D[Ue]],F+D[Ue],Se);kt("wasm prepareInputOutputTensor");for(let Ue=0;Ue<F;Ue++)N.setValue(Ar+Ue*L,Te[Ue],"*"),N.setValue(rs+Ue*L,ne[E[Ue]],"*");for(let Ue=0;Ue<le;Ue++)N.setValue(nn+Ue*L,Ne[Ue],"*"),N.setValue(Un+Ue*L,Z[D[Ue]],"*");N.jsepOnRunStart?.(te),N.webnnOnRunStart?.(te);let ht;ht=await N._OrtRun(te,rs,Ar,F,Un,le,nn,ut),ht!==0&&Ce("failed to call OrtRun().");let ir=[],Fn=[];Ct("wasm ProcessOutputTensor");for(let Ue=0;Ue<le;Ue++){let rr=Number(N.getValue(nn+Ue*L,"*"));if(rr===Ne[Ue]||Rt.includes(Ne[Ue])){ir.push(O[Ue]),rr!==Ne[Ue]&&N._OrtReleaseTensor(rr)!==0&&Ce("Can't release tensor.");continue}let mi=N.stackSave(),pr=N.stackAlloc(4*L),Cs=!1,wt,Bt=0;try{N._OrtGetTensorData(rr,pr,pr+L,pr+2*L,pr+3*L)!==0&&Ce(`Can't access output tensor data on index ${Ue}.`);let an=L===4?"i32":"i64",ks=Number(N.getValue(pr,an));Bt=N.getValue(pr+L,"*");let Vn=N.getValue(pr+L*2,"*"),gi=Number(N.getValue(pr+L*3,an)),Et=[];for(let vt=0;vt<gi;vt++)Et.push(Number(N.getValue(Vn+vt*L,an)));N._OrtFree(Vn)!==0&&Ce("Can't free memory for tensor dims.");let fr=Et.reduce((vt,pt)=>vt*pt,1);wt=jt(ks);let ss=Q?.outputPreferredLocations[D[Ue]];if(wt==="string"){if(ss==="gpu-buffer"||ss==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let vt=[];for(let pt=0;pt<fr;pt++){let ar=N.getValue(Bt+pt*L,"*"),yi=N.getValue(Bt+(pt+1)*L,"*"),wi=pt===fr-1?void 0:yi-ar;vt.push(N.UTF8ToString(ar,wi))}ir.push([wt,Et,vt,"cpu"])}else if(ss==="gpu-buffer"&&fr>0){let vt=N.jsepGetBuffer;if(!vt)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let pt=vt(Bt),ar=Qt(ks,fr);if(ar===void 0||!bs(wt))throw new Error(`Unsupported data type: ${wt}`);Cs=!0,ir.push([wt,Et,{gpuBuffer:pt,download:N.jsepCreateDownloader(pt,ar,wt),dispose:()=>{N._OrtReleaseTensor(rr)!==0&&Ce("Can't release tensor.")}},"gpu-buffer"])}else if(ss==="ml-tensor"&&fr>0){let vt=N.webnnEnsureTensor,pt=N.webnnIsGraphInputOutputTypeSupported;if(!vt||!pt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Qt(ks,fr)===void 0||!Ss(wt))throw new Error(`Unsupported data type: ${wt}`);if(!pt(y,wt,!1))throw new Error(`preferredLocation "ml-tensor" for ${wt} output is not supported by current WebNN Context.`);let ar=await vt(y,Bt,ks,Et,!1);Cs=!0,ir.push([wt,Et,{mlTensor:ar,download:N.webnnCreateMLTensorDownloader(Bt,wt),dispose:()=>{N.webnnReleaseTensorId(Bt),N._OrtReleaseTensor(rr)}},"ml-tensor"])}else if(ss==="ml-tensor-cpu-output"&&fr>0){let vt=N.webnnCreateMLTensorDownloader(Bt,wt)(),pt=ir.length;Cs=!0,Fn.push((async()=>{let ar=[pt,await vt];return N.webnnReleaseTensorId(Bt),N._OrtReleaseTensor(rr),ar})()),ir.push([wt,Et,[],"cpu"])}else{let vt=vs(wt),pt=new vt(fr);new Uint8Array(pt.buffer,pt.byteOffset,pt.byteLength).set(N.HEAPU8.subarray(Bt,Bt+pt.byteLength)),ir.push([wt,Et,pt,"cpu"])}}finally{N.stackRestore(mi),wt==="string"&&Bt&&N._free(Bt),Cs||N._OrtReleaseTensor(rr)}}Q&&!Se&&(N._OrtClearBoundOutputs(Q.handle)!==0&&Ce("Can't clear bound outputs."),xr.set(y,[te,ne,Z,Q,Se,!1]));for(let[Ue,rr]of await Promise.all(Fn))ir[Ue][2]=rr;return kt("wasm ProcessOutputTensor"),ir}finally{N.webnnOnRunEnd?.(te),N.stackRestore(Mt),Te.forEach(ht=>N._OrtReleaseTensor(ht)),Ne.forEach(ht=>N._OrtReleaseTensor(ht)),ye.forEach(ht=>N._free(ht)),ut!==0&&N._OrtReleaseRunOptions(ut),Be.forEach(ht=>N._free(ht))}},Jr=y=>{let E=Pe(),A=xr.get(y);if(!A)throw new Error("invalid session id");let D=A[0],O=E._OrtEndProfiling(D);O===0&&Ce("Can't get an profile file name."),E._OrtFree(O)},js=y=>{let E=[];for(let A of y){let D=A[2];!Array.isArray(D)&&"buffer"in D&&E.push(D.buffer)}return E}}),cr,ke,kr,Zr,Br,es,Es,$s,hr,Rr,Qs,Xs,Ys,Pn,On,pi,ts,Dn,zn=b(()=>{ct(),Mn(),Ht(),fs(),cr=()=>!!fe.wasm.proxy&&typeof document<"u",kr=!1,Zr=!1,Br=!1,$s=new Map,hr=(y,E)=>{let A=$s.get(y);A?A.push(E):$s.set(y,[E])},Rr=()=>{if(kr||!Zr||Br||!ke)throw new Error("worker not ready")},Qs=y=>{switch(y.data.type){case"init-wasm":kr=!1,y.data.err?(Br=!0,Es[1](y.data.err)):(Zr=!0,Es[0]()),es&&(URL.revokeObjectURL(es),es=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let E=$s.get(y.data.type);y.data.err?E.shift()[1](y.data.err):E.shift()[0](y.data.out);break}}},Xs=async()=>{if(!Zr){if(kr)throw new Error("multiple calls to 'initWasm()' detected.");if(Br)throw new Error("previous call to 'initWasm()' failed.");if(kr=!0,cr())return new Promise((y,E)=>{ke?.terminate(),vn().then(([A,D])=>{try{ke=D,ke.onerror=G=>E(G),ke.onmessage=Qs,Es=[y,E];let O={type:"init-wasm",in:fe};if(!O.in.wasm.wasmPaths&&A){let G=ds();G&&(O.in.wasm.wasmPaths=G)}ke.postMessage(O),es=A}catch(O){E(O)}},E)});try{await ys(fe.wasm),await Gs(fe),Zr=!0}catch(y){throw Br=!0,y}finally{kr=!1}}},Ys=async y=>{if(cr())return Rr(),new Promise((E,A)=>{hr("init-ep",[E,A]);let D={type:"init-ep",in:{epName:y,env:fe}};ke.postMessage(D)});await qs(fe,y)},Pn=async y=>cr()?(Rr(),new Promise((E,A)=>{hr("copy-from",[E,A]);let D={type:"copy-from",in:{buffer:y}};ke.postMessage(D,[y.buffer])})):We(y),On=async(y,E)=>{if(cr()){if(E?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Rr(),new Promise((A,D)=>{hr("create",[A,D]);let O={type:"create",in:{model:y,options:{...E}}},G=[];y instanceof Uint8Array&&G.push(y.buffer),ke.postMessage(O,G)})}else return tr(y,E)},pi=async y=>{if(cr())return Rr(),new Promise((E,A)=>{hr("release",[E,A]);let D={type:"release",in:y};ke.postMessage(D)});Ks(y)},ts=async(y,E,A,D,O,G)=>{if(cr()){if(A.some(N=>N[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(O.some(N=>N))throw new Error("pre-allocated output tensor is not supported for proxy.");return Rr(),new Promise((N,L)=>{hr("run",[N,L]);let V=A,te={type:"run",in:{sessionId:y,inputIndices:E,inputs:V,outputIndices:D,options:G}};ke.postMessage(te,js(V))})}else return j(y,E,A,D,O,G)},Dn=async y=>{if(cr())return Rr(),new Promise((E,A)=>{hr("end-profiling",[E,A]);let D={type:"end-profiling",in:y};ke.postMessage(D)});Jr(y)}}),Ln,Js,Zs,en=b(()=>{ct(),zn(),Ie(),Ut(),An(),Ln=(y,E)=>{switch(y.location){case"cpu":return[y.type,y.dims,y.data,"cpu"];case"gpu-buffer":return[y.type,y.dims,{gpuBuffer:y.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[y.type,y.dims,{mlTensor:y.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${y.location} for ${E()}`)}},Js=y=>{switch(y[3]){case"cpu":return new lt(y[0],y[2],y[1]);case"gpu-buffer":{let E=y[0];if(!bs(E))throw new Error(`not supported data type: ${E} for deserializing GPU tensor`);let{gpuBuffer:A,download:D,dispose:O}=y[2];return lt.fromGpuBuffer(A,{dataType:E,dims:y[1],download:D,dispose:O})}case"ml-tensor":{let E=y[0];if(!Ss(E))throw new Error(`not supported data type: ${E} for deserializing MLTensor tensor`);let{mlTensor:A,download:D,dispose:O}=y[2];return lt.fromMLTensor(A,{dataType:E,dims:y[1],download:D,dispose:O})}default:throw new Error(`invalid data location: ${y[3]}`)}},Zs=class{async fetchModelAndCopyToWasmMemory(y){return Pn(await Ts(y))}async loadModel(y,E){gt();let A;typeof y=="string"?A=await this.fetchModelAndCopyToWasmMemory(y):A=y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await On(A,E),yt()}async dispose(){return pi(this.sessionId)}async run(y,E,A){gt();let D=[],O=[];Object.entries(y).forEach(Z=>{let Q=Z[0],Se=Z[1],F=this.inputNames.indexOf(Q);if(F===-1)throw new Error(`invalid input '${Q}'`);D.push(Se),O.push(F)});let G=[],N=[];Object.entries(E).forEach(Z=>{let Q=Z[0],Se=Z[1],F=this.outputNames.indexOf(Q);if(F===-1)throw new Error(`invalid output '${Q}'`);G.push(Se),N.push(F)});let L=D.map((Z,Q)=>Ln(Z,()=>`input "${this.inputNames[O[Q]]}"`)),V=G.map((Z,Q)=>Z?Ln(Z,()=>`output "${this.outputNames[N[Q]]}"`):null),te=await ts(this.sessionId,O,L,N,V,A),ne={};for(let Z=0;Z<te.length;Z++)ne[this.outputNames[N[Z]]]=G[Z]??Js(te[Z]);return yt(),ne}startProfiling(){}endProfiling(){Dn(this.sessionId)}}}),xs={};U(xs,{OnnxruntimeWebAssemblyBackend:()=>rn,initializeFlags:()=>tn,wasmBackend:()=>sn});var tn,rn,sn,Bn=b(()=>{ct(),zn(),en(),tn=()=>{(typeof fe.wasm.initTimeout!="number"||fe.wasm.initTimeout<0)&&(fe.wasm.initTimeout=0);let y=fe.wasm.simd;if(typeof y!="boolean"&&y!==void 0&&y!=="fixed"&&y!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${y}". Reset it to \`false\` and ignore SIMD feature checking.`),fe.wasm.simd=!1),typeof fe.wasm.proxy!="boolean"&&(fe.wasm.proxy=!1),typeof fe.wasm.trace!="boolean"&&(fe.wasm.trace=!1),typeof fe.wasm.numThreads!="number"||!Number.isInteger(fe.wasm.numThreads)||fe.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)fe.wasm.numThreads=1;else{let E=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;fe.wasm.numThreads=Math.min(4,Math.ceil((E||1)/2))}},rn=class{async init(y){tn(),await Xs(),await Ys(y)}async createInferenceSessionHandler(y,E){let A=new Zs;return await A.loadModel(y,E),A}},sn=new rn}),Nn={};U(Nn,{InferenceSession:()=>Qe,TRACE:()=>er,TRACE_EVENT_BEGIN:()=>Ct,TRACE_EVENT_END:()=>kt,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>yt,Tensor:()=>lt,default:()=>ji,env:()=>fe,registerBackend:()=>J}),ct(),ct(),ct();var fi="1.26.0",ji=ls;{let y=(Bn(),re(xs)).wasmBackend;J("cpu",y,10),J("wasm",y,10)}return Object.defineProperty(fe.versions,"web",{value:fi,enumerable:!0}),re(Nn)})();d.exports=s})(io)),io.exports}var Mp;function Ty(){return Mp||(Mp=1,(function(d){var r=Gr&&Gr.__createBinding||(Object.create?(function(de,he,pe,ce){ce===void 0&&(ce=pe);var Ke=Object.getOwnPropertyDescriptor(he,pe);(!Ke||("get"in Ke?!he.__esModule:Ke.writable||Ke.configurable))&&(Ke={enumerable:!0,get:function(){return he[pe]}}),Object.defineProperty(de,ce,Ke)}):(function(de,he,pe,ce){ce===void 0&&(ce=pe),de[ce]=he[pe]})),s=Gr&&Gr.__setModuleDefault||(Object.create?(function(de,he){Object.defineProperty(de,"default",{enumerable:!0,value:he})}):function(de,he){de.default=he}),a=Gr&&Gr.__importStar||function(de){if(de&&de.__esModule)return de;var he={};if(de!=null)for(var pe in de)pe!=="default"&&Object.prototype.hasOwnProperty.call(de,pe)&&r(he,de,pe);return s(he,de),he};Object.defineProperty(d,"__esModule",{value:!0}),d.MicVAD=d.getDefaultRealTimeVADOptions=d.ort=d.DEFAULT_MODEL=void 0;const f=a(Sy()),_=Io(),C=Mo(),R=ci(),b=qi(),U=hf(),z=pf();d.DEFAULT_MODEL="legacy",d.ort=f;const re="vad.worklet.bundle.min.js",K="silero_vad_v5.onnx",ie="silero_vad_legacy.onnx",J=de=>({...C.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{R.log.debug("VAD misfire")},onSpeechStart:()=>{R.log.debug("Detected speech start")},onSpeechEnd:()=>{R.log.debug("Detected speech end")},onSpeechRealStart:()=>{R.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:de,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async he=>{he.getTracks().forEach(pe=>{pe.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:he=>{he.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});d.getDefaultRealTimeVADOptions=J;const Y=de=>"audioWorklet"in de&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function H(de,he,pe,ce,Ke){await pe.audioWorklet.addModule(de),he.processorOptions={...he.processorOptions??{},frameSamples:ce};const fe=new AudioWorkletNode(pe,"vad-helper-worklet",he);return fe.port.onmessage=async Je=>{const Ge=Je.data;if(!(typeof Ge=="object"&&Ge&&"message"in Ge)){console.error("Invalid message event",Ge);return}switch(Ge.message){case b.Message.AudioFrame:{if(!("data"in Ge&&Ge.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const ot=new Float32Array(Ge.data);await Ke(ot);break}}},fe}async function se(de,he,pe){const ce=new z.Resampler({nativeSampleRate:de.sampleRate,targetSampleRate:16e3,targetFrameSize:he});R.log.debug("using script processor");const fe=de.createScriptProcessor(4096,1,1);let Je=!1;return fe.onaudioprocess=async Ge=>{if(!Je){Je=!0;try{const ot=Ge.inputBuffer.getChannelData(0);Ge.outputBuffer.getChannelData(0).fill(0);const it=ce.process(ot);for(const tt of it)await pe(tt)}catch(ot){console.error("Error processing audio:",ot)}finally{Je=!1}}},fe.connect(de.destination),fe}class ve{constructor(he,pe,ce,Ke,fe=!1,Je=null,Ge=null,ot=null,Ze=null,it=null,tt=null,Wt="uninitialized",xt=!1){this.options=he,this.frameProcessor=pe,this.model=ce,this.frameSamples=Ke,this.listening=fe,this.errored=Je,this._stream=Ge,this._audioContext=ot,this._vadNode=Ze,this._mediaStreamAudioSourceNode=it,this._audioProcessorAdapterType=tt,this.initializationState=Wt,this.ownsAudioContext=xt,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=je=>{this.initializationState="errored",this.errored=je},this.start=async()=>{switch(this.initializationState){case"uninitialized":{R.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(je){throw je instanceof Error?this.setErrored(je.message):this.setErrored(String(je)),je}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?Y(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await H(this.options.baseAssetPath+re,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await se(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),R.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{R.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:je,audioContext:qe,vadNode:st}=this.getAudioInstances();this._stream=await this.options.resumeStream(je);const ze=new MediaStreamAudioSourceNode(qe,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=ze,ze.connect(st);break}case"destroyed":{R.log.warn("start called after destroyed");break}case"errored":{R.log.error("start called after errored");break}default:{R.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:je,mediaStreamAudioSourceNode:qe}=this.getAudioInstances();await this.options.pauseStream(je),qe.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{R.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:je}=this.getAudioInstances();je instanceof AudioWorkletNode&&je.port.postMessage(b.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await this._audioContext?.close()},this.setOptions=je=>{this.frameProcessor.setOptions(je)},this.processFrame=async je=>{await this.frameProcessor.process(je,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=je=>{switch(je.msg){case b.Message.FrameProcessed:this.options.onFrameProcessed(je.probs,je.frame);break;case b.Message.SpeechStart:this.options.onSpeechStart();break;case b.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case b.Message.VADMisfire:this.options.onVADMisfire();break;case b.Message.SpeechEnd:this.options.onSpeechEnd(je.audio);break}}}static async new(he={}){const pe={...(0,d.getDefaultRealTimeVADOptions)(he.model??d.DEFAULT_MODEL),...he};(0,C.validateOptions)(pe),d.ort.env.wasm.wasmPaths=pe.onnxWASMBasePath,pe.ortConfig!==void 0&&pe.ortConfig(d.ort);const ce=pe.model==="v5"?K:ie,Ke=pe.baseAssetPath+ce,fe=pe.model==="v5"?U.SileroV5.new:U.SileroLegacy.new;let Je;try{Je=await fe(d.ort,()=>(0,_.defaultModelFetcher)(Ke))}catch(tt){throw console.error(`Encountered an error while loading model file ${Ke}`),tt}const Ge=pe.model==="v5"?512:1536,ot=Ge/16,Ze=new C.FrameProcessor(Je.process,Je.reset_state,{positiveSpeechThreshold:pe.positiveSpeechThreshold,negativeSpeechThreshold:pe.negativeSpeechThreshold,redemptionMs:pe.redemptionMs,preSpeechPadMs:pe.preSpeechPadMs,minSpeechMs:pe.minSpeechMs,submitUserSpeechOnPause:pe.submitUserSpeechOnPause},ot),it=new ve(pe,Ze,Je,Ge);if(pe.startOnLoad)try{await it.start()}catch(tt){throw console.error("Error starting micVad",tt),tt}return it}}d.MicVAD=ve})(Gr)),Gr}var Pp;function Op(){return Pp||(Pp=1,(function(d){Object.defineProperty(d,"__esModule",{value:!0}),d.getDefaultRealTimeVADOptions=d.MicVAD=d.DEFAULT_MODEL=d.utils=d.NonRealTimeVAD=d.Message=d.FrameProcessor=d.defaultModelFetcher=d.baseAssetPath=void 0;var r=uf();Object.defineProperty(d,"baseAssetPath",{enumerable:!0,get:function(){return r.baseAssetPath}});var s=Io();Object.defineProperty(d,"defaultModelFetcher",{enumerable:!0,get:function(){return s.defaultModelFetcher}});var a=Mo();Object.defineProperty(d,"FrameProcessor",{enumerable:!0,get:function(){return a.FrameProcessor}});var f=qi();Object.defineProperty(d,"Message",{enumerable:!0,get:function(){return f.Message}});var _=_y();Object.defineProperty(d,"NonRealTimeVAD",{enumerable:!0,get:function(){return _.NonRealTimeVAD}});const C=by();d.utils={audioFileToArray:C.audioFileToArray,minFramesForTargetMS:C.minFramesForTargetMS,arrayBufferToBase64:C.arrayBufferToBase64,encodeWAV:C.encodeWAV};var R=Ty();Object.defineProperty(d,"DEFAULT_MODEL",{enumerable:!0,get:function(){return R.DEFAULT_MODEL}}),Object.defineProperty(d,"MicVAD",{enumerable:!0,get:function(){return R.MicVAD}}),Object.defineProperty(d,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return R.getDefaultRealTimeVADOptions}})})(ro)),ro}var Dp;function Ey(){return Dp||(Dp=1,(function(d){Object.defineProperty(d,"__esModule",{value:!0}),d.useMicVAD=d.getDefaultReactRealTimeVADOptions=d.utils=void 0;const r=Op(),s=oe;var a=Op();Object.defineProperty(d,"utils",{enumerable:!0,get:function(){return a.utils}});const f={userSpeakingThreshold:.6},_=b=>({...(0,r.getDefaultRealTimeVADOptions)(b),...f});d.getDefaultReactRealTimeVADOptions=_;function C(b){const U=b.model??r.DEFAULT_MODEL,z={...(0,d.getDefaultReactRealTimeVADOptions)(U),...b},re={userSpeakingThreshold:z.userSpeakingThreshold},K={positiveSpeechThreshold:z.positiveSpeechThreshold,negativeSpeechThreshold:z.negativeSpeechThreshold,redemptionMs:z.redemptionMs,preSpeechPadMs:z.preSpeechPadMs,minSpeechMs:z.minSpeechMs,submitUserSpeechOnPause:z.submitUserSpeechOnPause,onFrameProcessed:z.onFrameProcessed,onVADMisfire:z.onVADMisfire,onSpeechStart:z.onSpeechStart,onSpeechEnd:z.onSpeechEnd,onSpeechRealStart:z.onSpeechRealStart,baseAssetPath:z.baseAssetPath,onnxWASMBasePath:z.onnxWASMBasePath,model:z.model,workletOptions:z.workletOptions,getStream:z.getStream,pauseStream:z.pauseStream,resumeStream:z.resumeStream,startOnLoad:z.startOnLoad,processorType:z.processorType};return z.ortConfig&&(K.ortConfig=z.ortConfig),z.audioContext&&(K.audioContext=z.audioContext),[re,K]}function R(b){const[U,z]=C(b),re=b.model??r.DEFAULT_MODEL,[K,ie]=(0,s.useState)(!1),[J,Y]=(0,s.useState)(!0),[H,se]=(0,s.useState)(!1),[ve,de]=(0,s.useState)(!1),[he,pe]=(0,s.useState)(null),ce=(0,s.useRef)(z.onFrameProcessed),Ke=(0,s.useRef)(z.onSpeechEnd),fe=(0,s.useRef)(z.onSpeechStart),Je=(0,s.useRef)(z.onSpeechRealStart),Ge=(0,s.useRef)(z.onVADMisfire),ot=(0,s.useRef)(z.getStream);(0,s.useEffect)(()=>{ce.current=z.onFrameProcessed,Ke.current=z.onSpeechEnd,fe.current=z.onSpeechStart,Je.current=z.onSpeechRealStart,Ge.current=z.onVADMisfire},[z.onFrameProcessed,z.onSpeechEnd,z.onSpeechStart,z.onSpeechRealStart,z.onVADMisfire]),(0,s.useEffect)(()=>{ot.current=z.getStream},[z.getStream]);const Ze=z.getStream.toString();(0,s.useEffect)(()=>{let xt=null,je=!1;return(async()=>{try{Y(!0),se(!1);const st={...z,onFrameProcessed:(ze,At)=>{const sr=ze.isSpeech>U.userSpeakingThreshold;ie(sr),ce.current(ze,At)},onSpeechEnd:ze=>{Ke.current(ze)},onSpeechStart:()=>{fe.current()},onSpeechRealStart:()=>{Je.current()},onVADMisfire:()=>{Ge.current()},getStream:()=>ot.current()};if(xt=await r.MicVAD.new(st),je){await xt.destroy();return}pe(xt),z.startOnLoad&&(await xt.start(),de(!0)),Y(!1)}catch(st){Y(!1),st instanceof Error?se(st.message):se(String(st))}})().catch(()=>{}),function(){je=!0,xt&&xt.destroy(),!J&&!H&&de(!1)}},[Ze,re]);const it=(0,s.useCallback)(async()=>{!J&&!H&&(await he?.pause(),de(!1))},[J,H,he]),tt=(0,s.useCallback)(async()=>{!J&&!H&&(await he?.start(),de(!0))},[J,H,he]),Wt=(0,s.useCallback)(async()=>{ve?await it():await tt()},[ve,it,tt]);return{listening:ve,errored:H,loading:J,userSpeaking:K,pause:it,start:tt,toggle:Wt}}d.useMicVAD=R})(to)),to}var $y=Ey();const zp={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},xy=16e3,mf=512,gf=1e3,Cy=300,ky=mf/xy*1e3,Ry=Math.ceil(gf/ky);function ao(d){const r=new ArrayBuffer(d.length*2),s=new DataView(r);for(let a=0;a<d.length;a++){const f=Math.max(-1,Math.min(1,d[a]));s.setInt16(a*2,f<0?f*32768:f*32767,!0)}return new Uint8Array(r)}function oo(d){if(!d.length)return new Float32Array(0);if(d.length===1)return d[0];const r=d.reduce((f,_)=>f+_.length,0),s=new Float32Array(r);let a=0;for(const f of d)s.set(f,a),a+=f.length;return s}function Ay(d={}){const{onAudioChunk:r,onAudioEnd:s,onSpeechStart:a,onSpeechEnd:f,onVADMisfire:_,onError:C,enabled:R=!0,preloadStream:b=!0}=d,{sendAudioChunk:U,endAudioStream:z}=dn(),[re,K]=oe.useState(!1),[ie,J]=oe.useState(null),Y=oe.useRef(null),H=oe.useRef(!1),se=oe.useRef(null),ve=oe.useRef([]),de=oe.useRef(!1),he=oe.useRef([]),pe=r??U;oe.useEffect(()=>{!R||!b||typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||navigator.mediaDevices.getUserMedia({audio:zp}).then(qe=>{Y.current=qe,J(null)}).catch(qe=>{J("permission_denied"),C?.(qe)})},[R,C,b]);const ce=oe.useCallback(async()=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone APIs are unavailable in this browser");if(Y.current&&Y.current.getTracks()[0]?.readyState==="live")return Y.current;const qe=await navigator.mediaDevices.getUserMedia({audio:zp});return Y.current=qe,J(null),qe},[]),Ke=oe.useCallback(async qe=>{qe.getTracks().forEach(st=>{st.enabled=!1})},[]),fe=oe.useCallback(async()=>Y.current&&Y.current.getTracks()[0]?.readyState==="live"?(Y.current.getTracks().forEach(qe=>{qe.enabled=!0}),Y.current):ce(),[ce]);oe.useCallback(()=>{const qe=ve.current;return ve.current=[],oo(qe)},[]);const Je=oe.useCallback(()=>{he.current=[];const qe=ve.current;ve.current=[];for(const st of qe)pe(ao(st));de.current=!0},[pe]),Ge=oe.useCallback(()=>{de.current=!1;const qe=he.current;if(he.current=[],qe.length>0){const st=oo(qe);pe(ao(st))}},[pe]),ot=oe.useCallback(()=>{Y.current&&(Y.current.getTracks().forEach(qe=>qe.stop()),Y.current=null)},[]);if(!R)return{isListening:!1,isLoading:!1,isErrored:!1,isSpeaking:!1,micError:null,toggle:async()=>!1,prepare:async()=>null,start:async()=>!1,stop:async()=>!1,pause:async()=>{},userSpeaking:!1};const Ze=$y.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:gf,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:mf}},baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.30/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.1/dist/",ortConfig:qe=>{qe.env.wasm.numThreads=1,qe.env.logLevel="error"},getStream:ce,pauseStream:Ke,resumeStream:fe,onFrameProcessed:(qe,st)=>{if(st&&(ve.current.push(new Float32Array(st)),ve.current.length>Ry&&ve.current.shift(),de.current)){const ze=he.current;if(ze.push(new Float32Array(st)),ze.length>=3){const At=oo(ze);ze.length=0,pe(ao(At))}}},onSpeechStart:()=>{H.current||(se.current&&(clearTimeout(se.current),se.current=null),K(!0),a?.(),Je())},onSpeechEnd:()=>{se.current=setTimeout(()=>{K(!1),Ge(),s?s():z(),H.current=!0,setTimeout(()=>{H.current=!1},300),f?.()},Cy)},onVADMisfire:()=>{se.current&&(clearTimeout(se.current),se.current=null),K(!1),Ge(),_?.()}}),it=oe.useCallback(async()=>!R||Ze.loading||Ze.errored?!1:(Ze.listening&&(se.current&&(clearTimeout(se.current),se.current=null),K(!1),Ge(),await Ze.pause()),!0),[R,Ge,Ze]),tt=oe.useCallback(async()=>{try{await Ze.start()}catch(qe){const st=qe instanceof Error?qe.message:String(qe);if(st.includes("null stream")||st.includes("audio context")||st.includes("processor adapter"))await new Promise(ze=>setTimeout(ze,100)),await Ze.start();else throw qe}},[Ze]),Wt=oe.useCallback(async()=>!R||Ze.loading||Ze.errored?!1:(Ze.listening?(se.current&&(clearTimeout(se.current),se.current=null),K(!1),Ge(),await Ze.pause()):await tt(),!0),[R,Ge,tt]),xt=oe.useCallback(async()=>R?ce():null,[R,ce]),je=oe.useCallback(async()=>!R||Ze.loading||Ze.errored?!1:(Ze.listening||await tt(),!0),[R,tt]);return oe.useEffect(()=>()=>{se.current&&clearTimeout(se.current),Ge(),ot()},[ot,Ge]),{isListening:Ze.listening,isLoading:Ze.loading,isErrored:!!Ze.errored,isSpeaking:re,micError:ie,toggle:Wt,prepare:xt,start:je,stop:it,pause:Ze.pause,userSpeaking:Ze.userSpeaking}}function Iy({connect:d=!0,session:r,onError:s,onInitialized:a,clientTools:f,children:_}){const{initializeSession:C,joinDesktopSession:R,disconnect:b,registerClientTools:U}=of(),z=oe.useRef(!1),re=oe.useRef(!1),K=oe.useRef(C),ie=oe.useRef(R),J=oe.useRef(b),Y=oe.useRef(s),H=oe.useRef(a),se=oe.useRef(U),ve=oe.useRef(f);return oe.useEffect(()=>{K.current=C}),oe.useEffect(()=>{ie.current=R}),oe.useEffect(()=>{J.current=b}),oe.useEffect(()=>{Y.current=s}),oe.useEffect(()=>{H.current=a}),oe.useEffect(()=>{se.current=U}),oe.useEffect(()=>{ve.current=f}),oe.useEffect(()=>{if(!d||z.current)return;z.current=!0,re.current=!1;let de=!1;return(async()=>{try{const pe=ve.current;if(r?.mode==="join_desktop"){const Ke=await ie.current({uniqueId:r.uniqueId});de||(pe&&se.current(pe),H.current?.(Ke));return}const ce=await K.current({apiKey:r?.apiKey,publicChatId:r?.publicChatId,agentId:r?.agentId,language:r?.language||"en",config:r?.config});de||(pe&&se.current(pe),H.current?.(ce))}catch(pe){de||(re.current=!0,Y.current?.(pe))}})(),()=>{de=!0,!re.current&&(J.current(),z.current=!1)}},[d,r]),Jt.jsx(Jt.Fragment,{children:_})}function My({children:d,wsUrl:r,restUrl:s,session:a,connect:f=!0,enableAudio:_=!0,pcmOptions:C,debug:R=!1,withCredentials:b=!1,onError:U,onInitialized:z,clientTools:re}){return Jt.jsx(af,{wsUrl:r,restUrl:s,enableAudio:_,pcmOptions:C,debug:R,withCredentials:b,children:Jt.jsx(Iy,{connect:f,session:a,onError:U,onInitialized:z,clientTools:re,children:d})})}var lo={exports:{}},Lp;function Py(){return Lp||(Lp=1,(function(d){const r={};r.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},r.localCName=r.generateIdentifier(),r.splitLines=function(s){return s.trim().split(`
|
|
2839
|
+
`).map(a=>a.trim())},r.splitSections=function(s){return s.split(`
|
|
2840
|
+
m=`).map((f,_)=>(_>0?"m="+f:f).trim()+`\r
|
|
2841
|
+
`)},r.getDescription=function(s){const a=r.splitSections(s);return a&&a[0]},r.getMediaSections=function(s){const a=r.splitSections(s);return a.shift(),a},r.matchPrefix=function(s,a){return r.splitLines(s).filter(f=>f.indexOf(a)===0)},r.parseCandidate=function(s){let a;s.indexOf("a=candidate:")===0?a=s.substring(12).split(" "):a=s.substring(10).split(" ");const f={foundation:a[0],component:{1:"rtp",2:"rtcp"}[a[1]]||a[1],protocol:a[2].toLowerCase(),priority:parseInt(a[3],10),ip:a[4],address:a[4],port:parseInt(a[5],10),type:a[7]};for(let _=8;_<a.length;_+=2)switch(a[_]){case"raddr":f.relatedAddress=a[_+1];break;case"rport":f.relatedPort=parseInt(a[_+1],10);break;case"tcptype":f.tcpType=a[_+1];break;case"ufrag":f.ufrag=a[_+1],f.usernameFragment=a[_+1];break;default:f[a[_]]===void 0&&(f[a[_]]=a[_+1]);break}return f},r.writeCandidate=function(s){const a=[];a.push(s.foundation);const f=s.component;f==="rtp"?a.push(1):f==="rtcp"?a.push(2):a.push(f),a.push(s.protocol.toUpperCase()),a.push(s.priority),a.push(s.address||s.ip),a.push(s.port);const _=s.type;return a.push("typ"),a.push(_),_!=="host"&&s.relatedAddress&&s.relatedPort!==void 0&&(a.push("raddr"),a.push(s.relatedAddress),a.push("rport"),a.push(s.relatedPort)),s.tcpType&&s.protocol.toLowerCase()==="tcp"&&(a.push("tcptype"),a.push(s.tcpType)),(s.usernameFragment||s.ufrag)&&(a.push("ufrag"),a.push(s.usernameFragment||s.ufrag)),"candidate:"+a.join(" ")},r.parseIceOptions=function(s){return s.substring(14).split(" ")},r.parseRtpMap=function(s){let a=s.substring(9).split(" ");const f={payloadType:parseInt(a.shift(),10)};return a=a[0].split("/"),f.name=a[0],f.clockRate=parseInt(a[1],10),f.channels=a.length===3?parseInt(a[2],10):1,f.numChannels=f.channels,f},r.writeRtpMap=function(s){let a=s.payloadType;s.preferredPayloadType!==void 0&&(a=s.preferredPayloadType);const f=s.channels||s.numChannels||1;return"a=rtpmap:"+a+" "+s.name+"/"+s.clockRate+(f!==1?"/"+f:"")+`\r
|
|
2842
|
+
`},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
|
|
2843
|
+
`},r.parseFmtp=function(s){const a={};let f;const _=s.substring(s.indexOf(" ")+1).split(";");for(let C=0;C<_.length;C++)f=_[C].trim().split("="),a[f[0].trim()]=f[1];return a},r.writeFmtp=function(s){let a="",f=s.payloadType;if(s.preferredPayloadType!==void 0&&(f=s.preferredPayloadType),s.parameters&&Object.keys(s.parameters).length){const _=[];Object.keys(s.parameters).forEach(C=>{s.parameters[C]!==void 0?_.push(C+"="+s.parameters[C]):_.push(C)}),a+="a=fmtp:"+f+" "+_.join(";")+`\r
|
|
2844
|
+
`}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="",f=s.payloadType;return s.preferredPayloadType!==void 0&&(f=s.preferredPayloadType),s.rtcpFeedback&&s.rtcpFeedback.length&&s.rtcpFeedback.forEach(_=>{a+="a=rtcp-fb:"+f+" "+_.type+(_.parameter&&_.parameter.length?" "+_.parameter:"")+`\r
|
|
2845
|
+
`}),a},r.parseSsrcMedia=function(s){const a=s.indexOf(" "),f={ssrc:parseInt(s.substring(7,a),10)},_=s.indexOf(":",a);return _>-1?(f.attribute=s.substring(a+1,_),f.value=s.substring(_+1)):f.attribute=s.substring(a+1),f},r.parseSsrcGroup=function(s){const a=s.substring(13).split(" ");return{semantics:a.shift(),ssrcs:a.map(f=>parseInt(f,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 f="a=setup:"+a+`\r
|
|
2846
|
+
`;return s.fingerprints.forEach(_=>{f+="a=fingerprint:"+_.algorithm+" "+_.value+`\r
|
|
2847
|
+
`}),f},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
|
|
2848
|
+
`},r.parseCryptoKeyParams=function(s){if(s.indexOf("inline:")!==0)return null;const a=s.substring(7).split("|");return{keyMethod:"inline",keySalt:a[0],lifeTime:a[1],mkiValue:a[2]?a[2].split(":")[0]:void 0,mkiLength:a[2]?a[2].split(":")[1]:void 0}},r.writeCryptoKeyParams=function(s){return s.keyMethod+":"+s.keySalt+(s.lifeTime?"|"+s.lifeTime:"")+(s.mkiValue&&s.mkiLength?"|"+s.mkiValue+":"+s.mkiLength:"")},r.getCryptoParameters=function(s,a){return r.matchPrefix(s+a,"a=crypto:").map(r.parseCryptoLine)},r.getIceParameters=function(s,a){const f=r.matchPrefix(s+a,"a=ice-ufrag:")[0],_=r.matchPrefix(s+a,"a=ice-pwd:")[0];return f&&_?{usernameFragment:f.substring(12),password:_.substring(10)}:null},r.writeIceParameters=function(s){let a="a=ice-ufrag:"+s.usernameFragment+`\r
|
|
2849
|
+
a=ice-pwd:`+s.password+`\r
|
|
2850
|
+
`;return s.iceLite&&(a+=`a=ice-lite\r
|
|
2851
|
+
`),a},r.parseRtpParameters=function(s){const a={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},_=r.splitLines(s)[0].split(" ");a.profile=_[2];for(let R=3;R<_.length;R++){const b=_[R],U=r.matchPrefix(s,"a=rtpmap:"+b+" ")[0];if(U){const z=r.parseRtpMap(U),re=r.matchPrefix(s,"a=fmtp:"+b+" ");switch(z.parameters=re.length?r.parseFmtp(re[0]):{},z.rtcpFeedback=r.matchPrefix(s,"a=rtcp-fb:"+b+" ").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(b=>{R.rtcpFeedback.find(z=>z.type===b.type&&z.parameter===b.parameter)||R.rtcpFeedback.push(b)})}),a},r.writeRtpDescription=function(s,a){let f="";f+="m="+s+" ",f+=a.codecs.length>0?"9":"0",f+=" "+(a.profile||"UDP/TLS/RTP/SAVPF")+" ",f+=a.codecs.map(C=>C.preferredPayloadType!==void 0?C.preferredPayloadType:C.payloadType).join(" ")+`\r
|
|
2852
|
+
`,f+=`c=IN IP4 0.0.0.0\r
|
|
2853
|
+
`,f+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
2854
|
+
`,a.codecs.forEach(C=>{f+=r.writeRtpMap(C),f+=r.writeFmtp(C),f+=r.writeRtcpFb(C)});let _=0;return a.codecs.forEach(C=>{C.maxptime>_&&(_=C.maxptime)}),_>0&&(f+="a=maxptime:"+_+`\r
|
|
2855
|
+
`),a.headerExtensions&&a.headerExtensions.forEach(C=>{f+=r.writeExtmap(C)}),f},r.parseRtpEncodingParameters=function(s){const a=[],f=r.parseRtpParameters(s),_=f.fecMechanisms.indexOf("RED")!==-1,C=f.fecMechanisms.indexOf("ULPFEC")!==-1,R=r.matchPrefix(s,"a=ssrc:").map(K=>r.parseSsrcMedia(K)).filter(K=>K.attribute==="cname"),b=R.length>0&&R[0].ssrc;let U;const z=r.matchPrefix(s,"a=ssrc-group:FID").map(K=>K.substring(17).split(" ").map(J=>parseInt(J,10)));z.length>0&&z[0].length>1&&z[0][0]===b&&(U=z[0][1]),f.codecs.forEach(K=>{if(K.name.toUpperCase()==="RTX"&&K.parameters.apt){let ie={ssrc:b,codecPayloadType:parseInt(K.parameters.apt,10)};b&&U&&(ie.rtx={ssrc:U}),a.push(ie),_&&(ie=JSON.parse(JSON.stringify(ie)),ie.fec={ssrc:b,mechanism:C?"red+ulpfec":"red"},a.push(ie))}}),a.length===0&&b&&a.push({ssrc:b});let re=r.matchPrefix(s,"b=");return re.length&&(re[0].indexOf("b=TIAS:")===0?re=parseInt(re[0].substring(7),10):re[0].indexOf("b=AS:")===0?re=parseInt(re[0].substring(5),10)*1e3*.95-2e3*8:re=void 0,a.forEach(K=>{K.maxBitrate=re})),a},r.parseRtcpParameters=function(s){const a={},f=r.matchPrefix(s,"a=ssrc:").map(R=>r.parseSsrcMedia(R)).filter(R=>R.attribute==="cname")[0];f&&(a.cname=f.value,a.ssrc=f.ssrc);const _=r.matchPrefix(s,"a=rtcp-rsize");a.reducedSize=_.length>0,a.compound=_.length===0;const C=r.matchPrefix(s,"a=rtcp-mux");return a.mux=C.length>0,a},r.writeRtcpParameters=function(s){let a="";return s.reducedSize&&(a+=`a=rtcp-rsize\r
|
|
2856
|
+
`),s.mux&&(a+=`a=rtcp-mux\r
|
|
2857
|
+
`),s.ssrc!==void 0&&s.cname&&(a+="a=ssrc:"+s.ssrc+" cname:"+s.cname+`\r
|
|
2858
|
+
`),a},r.parseMsid=function(s){let a;const f=r.matchPrefix(s,"a=msid:");if(f.length===1)return a=f[0].substring(7).split(" "),{stream:a[0],track:a[1]};const _=r.matchPrefix(s,"a=ssrc:").map(C=>r.parseSsrcMedia(C)).filter(C=>C.attribute==="msid");if(_.length>0)return a=_[0].value.split(" "),{stream:a[0],track:a[1]}},r.parseSctpDescription=function(s){const a=r.parseMLine(s),f=r.matchPrefix(s,"a=max-message-size:");let _;f.length>0&&(_=parseInt(f[0].substring(19),10)),isNaN(_)&&(_=65536);const C=r.matchPrefix(s,"a=sctp-port:");if(C.length>0)return{port:parseInt(C[0].substring(12),10),protocol:a.fmt,maxMessageSize:_};const R=r.matchPrefix(s,"a=sctpmap:");if(R.length>0){const b=R[0].substring(10).split(" ");return{port:parseInt(b[0],10),protocol:b[1],maxMessageSize:_}}},r.writeSctpDescription=function(s,a){let f=[];return s.protocol!=="DTLS/SCTP"?f=["m="+s.kind+" 9 "+s.protocol+" "+a.protocol+`\r
|
|
2859
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
2860
|
+
`,"a=sctp-port:"+a.port+`\r
|
|
2861
|
+
`]:f=["m="+s.kind+" 9 "+s.protocol+" "+a.port+`\r
|
|
2862
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
2863
|
+
`,"a=sctpmap:"+a.port+" "+a.protocol+` 65535\r
|
|
2864
|
+
`],a.maxMessageSize!==void 0&&f.push("a=max-message-size:"+a.maxMessageSize+`\r
|
|
2865
|
+
`),f.join("")},r.generateSessionId=function(){return Math.random().toString().substr(2,22)},r.writeSessionBoilerplate=function(s,a,f){let _;const C=a!==void 0?a:2;return s?_=s:_=r.generateSessionId(),`v=0\r
|
|
2866
|
+
o=`+(f||"thisisadapterortc")+" "+_+" "+C+` IN IP4 127.0.0.1\r
|
|
2867
|
+
s=-\r
|
|
2868
|
+
t=0 0\r
|
|
2869
|
+
`},r.getDirection=function(s,a){const f=r.splitLines(s);for(let _=0;_<f.length;_++)switch(f[_]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return f[_].substring(2)}return a?r.getDirection(a):"sendrecv"},r.getKind=function(s){return r.splitLines(s)[0].split(" ")[0].substring(2)},r.isRejected=function(s){return s.split(" ",2)[1]==="0"},r.parseMLine=function(s){const f=r.splitLines(s)[0].substring(2).split(" ");return{kind:f[0],port:parseInt(f[1],10),protocol:f[2],fmt:f.slice(3).join(" ")}},r.parseOLine=function(s){const f=r.matchPrefix(s,"o=")[0].substring(2).split(" ");return{username:f[0],sessionId:f[1],sessionVersion:parseInt(f[2],10),netType:f[3],addressType:f[4],address:f[5]}},r.isValidSDP=function(s){if(typeof s!="string"||s.length===0)return!1;const a=r.splitLines(s);for(let f=0;f<a.length;f++)if(a[f].length<2||a[f].charAt(1)!=="=")return!1;return!0},d.exports=r})(lo)),lo.exports}var Bp=Py(),Sr,Tt,Ui={d:(d,r)=>{for(var s in r)Ui.o(r,s)&&!Ui.o(d,s)&&Object.defineProperty(d,s,{enumerable:!0,get:r[s]})},o:(d,r)=>Object.prototype.hasOwnProperty.call(d,r)},we={};Ui.d(we,{Dz:()=>Zf,g$:()=>Sf,Lt:()=>_f,Q9:()=>bf,qf:()=>So,hV:()=>nm,z$:()=>xw,J0:()=>Eo,De:()=>Zy,$C:()=>Ns,al:()=>If,_W:()=>Mf,Gv:()=>Hf,m:()=>Kf,tz:()=>Af,Nu:()=>rm,zg:()=>om,vp:()=>Jf,vU:()=>X,wF:()=>Ff,rv:()=>em,Nh:()=>tm,ss:()=>am,qW:()=>jf,QL:()=>Wf,cf:()=>um,eM:()=>Uf,Yd:()=>T,Tk:()=>be,iM:()=>yf,qy:()=>Wr,ce:()=>Gy,sK:()=>me,Ok:()=>dt,q5:()=>sm,g:()=>$w,xl:()=>Bf,I:()=>Nf,bx:()=>To,dD:()=>Xf,Ib:()=>hi,Az:()=>St,Iw:()=>Mr,qY:()=>bo,db:()=>vf,mR:()=>ui,Tn:()=>_o,rV:()=>Vf,gh:()=>Of,Mi:()=>Df,j:()=>zf,YB:()=>Lf,Yt:()=>qf,i5:()=>Gf,x_:()=>qr,Am:()=>$o,eR:()=>Tf,r8:()=>Pf,u3:()=>lm,vd:()=>$f,iV:()=>Cf,jZ:()=>xf,SW:()=>Rf,ZH:()=>kf,Ni:()=>dm,lh:()=>Ef,ZP:()=>Yf,bq:()=>wf,$f:()=>cm,eu:()=>Qf,Ax:()=>jy,Mc:()=>Ky});class T{static GetStackTrace(){const r=new Error;let s="No Stack Available for this browser";return r.stack&&(s=r.stack.toString().replace(/Error/g,"")),s}static SetLoggerVerbosity(r){this.verboseLogLevel!=null&&(this.verboseLogLevel=r)}static Log(r,s,a){if(a>this.verboseLogLevel)return;const f=`Level: Log
|
|
2870
|
+
Msg: ${s}
|
|
2871
|
+
Caller: ${r}`;console.log(f)}static Info(r,s,a){if(a>this.verboseLogLevel)return;const f=`Level: Info
|
|
2872
|
+
Msg: ${s}`;console.info(f)}static Error(r,s){const a=`Level: Error
|
|
2873
|
+
Msg: ${s}
|
|
2874
|
+
Caller: ${r}`;console.error(a)}static Warning(r,s){const a=`Level: Warning
|
|
2875
|
+
Caller: ${r}
|
|
2876
|
+
Msg: ${s}`;console.warn(a)}}T.verboseLogLevel=5,(function(d){d.LIST_STREAMERS="listStreamers",d.SUBSCRIBE="subscribe",d.UNSUBSCRIBE="unsubscribe",d.ICE_CANDIDATE="iceCandidate",d.OFFER="offer",d.ANSWER="answer",d.DATACHANNELREQUEST="dataChannelRequest",d.SFURECVDATACHANNELREADY="peerDataChannelsReady",d.PONG="pong"})(Sr||(Sr={}));class Wr{sendFilter(r,s){return s}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2877
|
+
`+JSON.stringify(this,this.sendFilter,4),6),JSON.stringify(this,this.sendFilter)}}class Oy extends Wr{constructor(){super(),this.type=Sr.LIST_STREAMERS}}class Dy extends Wr{constructor(r){super(),this.type=Sr.SUBSCRIBE,this.streamerId=r}}class zy extends Wr{constructor(){super(),this.type=Sr.UNSUBSCRIBE}}class Ly extends Wr{constructor(r){super(),this.type=Sr.PONG,this.time=r}}class By extends Wr{constructor(r,s){super(),this.type=Sr.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 Ny extends Wr{constructor(r,s){super(),this.type=Sr.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 Uy extends Wr{constructor(){super(),this.type=Sr.DATACHANNELREQUEST}}class Fy extends Wr{constructor(){super(),this.type=Sr.SFURECVDATACHANNELREADY}}class Vy{constructor(r){this.type=Sr.ICE_CANDIDATE,this.candidate=r}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2878
|
+
`+JSON.stringify(this,void 0,4),6),JSON.stringify(this)}}(function(d){d.CONFIG="config",d.STREAMER_LIST="streamerList",d.STREAMER_ID_CHANGED="streamerIDChanged",d.PLAYER_COUNT="playerCount",d.OFFER="offer",d.ANSWER="answer",d.ICE_CANDIDATE="iceCandidate",d.PEER_DATA_CHANNELS="peerDataChannels",d.PING="ping",d.WARNING="warning"})(Tt||(Tt={}));class yf{}class Gy extends yf{}class _o{constructor(){this.FromUEMessageHandlers=new Map}addMessageHandler(r,s){this.FromUEMessageHandlers.set(r,s)}handleMessage(r,s){this.FromUEMessageHandlers.has(r)?this.FromUEMessageHandlers.get(r)(s):T.Error(T.GetStackTrace(),`Message type of ${r} does not have a message handler registered on the frontend - ignoring message.`)}static setupDefaultHandlers(r){r.signallingProtocol.addMessageHandler(Tt.PING,(s=>{const a=new Ly(new Date().getTime()).payload();T.Log(T.GetStackTrace(),Tt.PING+": "+s,6),r.webSocket.send(a)})),r.signallingProtocol.addMessageHandler(Tt.CONFIG,(s=>{T.Log(T.GetStackTrace(),Tt.CONFIG,6);const a=JSON.parse(s);r.onConfig(a)})),r.signallingProtocol.addMessageHandler(Tt.STREAMER_LIST,(s=>{T.Log(T.GetStackTrace(),Tt.STREAMER_LIST,6);const a=JSON.parse(s);r.onStreamerList(a)})),r.signallingProtocol.addMessageHandler(Tt.STREAMER_ID_CHANGED,(s=>{T.Log(T.GetStackTrace(),Tt.STREAMER_ID_CHANGED,6);const a=JSON.parse(s);r.onStreamerIDChanged(a)})),r.signallingProtocol.addMessageHandler(Tt.PLAYER_COUNT,(s=>{T.Log(T.GetStackTrace(),Tt.PLAYER_COUNT,6);const a=JSON.parse(s);T.Log(T.GetStackTrace(),"Player Count: "+a.count,6),r.onPlayerCount(a)})),r.signallingProtocol.addMessageHandler(Tt.ANSWER,(s=>{T.Log(T.GetStackTrace(),Tt.ANSWER,6);const a=JSON.parse(s);r.onWebRtcAnswer(a)})),r.signallingProtocol.addMessageHandler(Tt.OFFER,(s=>{T.Log(T.GetStackTrace(),Tt.OFFER,6);const a=JSON.parse(s);r.onWebRtcOffer(a)})),r.signallingProtocol.addMessageHandler(Tt.ICE_CANDIDATE,(s=>{T.Log(T.GetStackTrace(),Tt.ICE_CANDIDATE,6);const a=JSON.parse(s);r.onIceCandidate(a.candidate)})),r.signallingProtocol.addMessageHandler(Tt.WARNING,(s=>{T.Warning(T.GetStackTrace(),`Warning received: ${s}`)})),r.signallingProtocol.addMessageHandler(Tt.PEER_DATA_CHANNELS,(s=>{T.Log(T.GetStackTrace(),Tt.PEER_DATA_CHANNELS,6);const a=JSON.parse(s);r.onWebRtcPeerDataChannels(a)}))}}class wf{constructor(){this.WS_OPEN_STATE=1,this.onOpen=new EventTarget,this.onClose=new EventTarget,this.signallingProtocol=new _o,_o.setupDefaultHandlers(this)}connect(r){T.Log(T.GetStackTrace(),r,6);try{return this.webSocket=new WebSocket(r),this.webSocket.onopen=s=>this.handleOnOpen(s),this.webSocket.onerror=()=>this.handleOnError(),this.webSocket.onclose=s=>this.handleOnClose(s),this.webSocket.onmessage=s=>this.handleOnMessage(s),this.webSocket.onmessagebinary=s=>this.handleOnMessageBinary(s),!0}catch(s){return T.Error(s,s),!1}}handleOnMessageBinary(r){r&&r.data&&r.data.text().then((s=>{const a=new MessageEvent("messageFromBinary",{data:s});this.handleOnMessage(a)})).catch((s=>{T.Error(T.GetStackTrace(),`Failed to parse binary blob from websocket, reason: ${s}`)}))}handleOnMessage(r){if(r.data&&r.data instanceof Blob)return void this.handleOnMessageBinary(r);const s=JSON.parse(r.data);T.Log(T.GetStackTrace(),`received =>
|
|
2879
|
+
`+JSON.stringify(JSON.parse(r.data),void 0,4),6),this.signallingProtocol.handleMessage(s.type,r.data)}handleOnOpen(r){T.Log(T.GetStackTrace(),"Connected to the signalling server via WebSocket",6),this.onOpen.dispatchEvent(new Event("open"))}handleOnError(){T.Error(T.GetStackTrace(),"WebSocket error")}handleOnClose(r){T.Log(T.GetStackTrace(),"Disconnected to the signalling server via WebSocket: "+JSON.stringify(r.code)+" - "+r.reason),this.onClose.dispatchEvent(new CustomEvent("close",{detail:r}))}requestStreamerList(){const r=new Oy;this.webSocket.send(r.payload())}sendSubscribe(r){const s=new Dy(r);this.webSocket.send(s.payload())}sendUnsubscribe(){const r=new zy;this.webSocket.send(r.payload())}sendWebRtcOffer(r,s){const a=new By(r,s);this.webSocket.send(a.payload())}sendWebRtcAnswer(r,s){const a=new Ny(r,s);this.webSocket.send(a.payload())}sendWebRtcDatachannelRequest(){const r=new Uy;this.webSocket.send(r.payload())}sendSFURecvDataChannelReady(){const r=new Fy;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 Vy(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 qy{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 Wy{constructor(r){this.freezeFrameHeight=0,this.freezeFrameWidth=0,this.rootDiv=r,this.rootElement=document.createElement("div"),this.rootElement.id="freezeFrame",this.rootElement.style.display="none",this.rootElement.style.pointerEvents="none",this.rootElement.style.position="absolute",this.rootElement.style.zIndex="20",this.imageElement=document.createElement("img"),this.imageElement.style.position="absolute",this.rootElement.appendChild(this.imageElement),this.rootDiv.appendChild(this.rootElement)}setElementForShow(){this.rootElement.style.display="block"}setElementForHide(){this.rootElement.style.display="none"}updateImageElementSource(r){const s=btoa(r.reduce(((a,f)=>a+String.fromCharCode(f)),""));this.imageElement.src="data:image/jpeg;base64,"+s}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(this.freezeFrameWidth!==0&&this.freezeFrameHeight!==0){let r=0,s=0,a=0,f=0;const _=this.rootDiv.clientWidth/this.rootDiv.clientHeight,C=this.freezeFrameWidth/this.freezeFrameHeight;_<C?(r=this.rootDiv.clientWidth,s=Math.floor(this.rootDiv.clientWidth/C),a=Math.floor(.5*(this.rootDiv.clientHeight-s)),f=0):(r=Math.floor(this.rootDiv.clientHeight*C),s=this.rootDiv.clientHeight,a=0,f=Math.floor(.5*(this.rootDiv.clientWidth-r))),this.rootElement.style.width=this.rootDiv.offsetWidth+"px",this.rootElement.style.height=this.rootDiv.offsetHeight+"px",this.rootElement.style.left="0px",this.rootElement.style.top="0px",this.imageElement.style.width=r+"px",this.imageElement.style.height=s+"px",this.imageElement.style.left=f+"px",this.imageElement.style.top=a+"px"}}}class Hy{constructor(r){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Wy(r)}showFreezeFrame(){this.valid&&this.freezeFrame.setElementForShow()}hideFreezeFrame(){this.valid=!1,this.freezeFrame.setElementForHide()}updateFreezeFrameAndShow(r,s){this.freezeFrame.updateImageElementSource(r),this.freezeFrame.imageElement.onload=()=>{this.freezeFrame.setDimensionsFromElementAndResize(),s()}}processFreezeFrameMessage(r,s){this.receiving||(this.receiving=!0,this.valid=!1,this.size=0,this.jpeg=void 0),this.size=new DataView(r.slice(1,5).buffer).getInt32(0,!0);const a=r.slice(5);if(this.jpeg){const f=new Uint8Array(this.jpeg.length+a.length);f.set(this.jpeg,0),f.set(a,this.jpeg.length),this.jpeg=f}else this.jpeg=a,this.receiving=!0,T.Log(T.GetStackTrace(),`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`,6);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,T.Log(T.GetStackTrace(),`received complete freeze frame ${this.size}`,6),this.updateFreezeFrameAndShow(this.jpeg,s)):this.jpeg.length>this.size&&(T.Error(T.GetStackTrace(),`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class hi{constructor(r,s,a,f,_=(()=>{})){this.onChange=_,this.onChangeEmit=()=>{},this.id=r,this.description=a,this.label=s,this.value=f}set label(r){this._label=r,this.onChangeEmit(this._value)}get label(){return this._label}get value(){return this._value}set value(r){this._value=r,this.onChange(this._value,this),this.onChangeEmit(this._value)}}class St extends hi{constructor(r,s,a,f,_,C=(()=>{})){super(r,s,a,f,C);const R=new URLSearchParams(window.location.search);if(_&&R.has(this.id)){const b=this.getUrlParamFlag();this.flag=b}else this.flag=f;this.useUrlParams=_}getUrlParamFlag(){const r=new URLSearchParams(window.location.search);return!!r.has(this.id)&&r.get(this.id)!=="false"&&r.get(this.id)!=="False"}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);this.flag===!0?r.set(this.id,"true"):r.set(this.id,"false"),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}enable(){this.flag=!0}get flag(){return!!this.value}set flag(r){this.value=r}}class Mr extends hi{constructor(r,s,a,f,_,C,R,b=(()=>{})){super(r,s,a,C,b),this._min=f,this._max=_;const U=new URLSearchParams(window.location.search);if(R&&U.has(this.id)){const z=Number.parseFloat(U.get(this.id));this.number=Number.isNaN(z)?C:z}else this.number=C;this.useUrlParams=R}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.number.toString()),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}set number(r){this.value=this.clamp(r)}get number(){return this.value}clamp(r){return this._min==null&&this._max==null?r:this._min==null?Math.min(this._max,r):this._max==null?Math.max(this._min,r):Math.max(Math.min(this._max,r),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(r){this.onChange=r}}class vf extends hi{constructor(r,s,a,f,_,C=(()=>{})){super(r,s,a,f,C);const R=new URLSearchParams(window.location.search);if(_&&R.has(this.id)){const b=this.getUrlParamText();this.text=b}else this.text=f;this.useUrlParams=_}getUrlParamText(){var r;const s=new URLSearchParams(window.location.search);return s.has(this.id)&&(r=s.get(this.id))!==null&&r!==void 0?r:""}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.text),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}get text(){return this.value}set text(r){this.value=r}}class bo extends hi{constructor(r,s,a,f,_,C,R=(()=>{})){super(r,s,a,f,R),this.options=_;const b=new URLSearchParams(window.location.search),U=C&&b.has(this.id)?this.getUrlParamText():f;this.selected=U,this.useUrlParams=C}getUrlParamText(){var r;const s=new URLSearchParams(window.location.search);return s.has(this.id)&&(r=s.get(this.id))!==null&&r!==void 0?r:""}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.selected),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}addOnChangedListener(r){this.onChange=r}get options(){return this._options}set options(r){this._options=r,this.onChangeEmit(this.selected)}get selected(){return this.value}set selected(r){let s=this.options.filter((a=>a.indexOf(r)!==-1));s.length?this.value=s[0]:(s=this.options.filter((a=>a.indexOf(r.split(" ")[0])!==-1)),s.length&&(this.value=s[0]))}}class _f extends Event{constructor(r){super("afkWarningActivate"),this.data=r}}class So extends Event{constructor(r){super("afkWarningUpdate"),this.data=r}}class bf extends Event{constructor(){super("afkWarningDeactivate")}}class Sf extends Event{constructor(){super("afkTimedOut")}}class Tf extends Event{constructor(r){super("videoEncoderAvgQP"),this.data=r}}class Ef extends Event{constructor(){super("webRtcSdp")}}class $f extends Event{constructor(){super("webRtcAutoConnect")}}class xf extends Event{constructor(){super("webRtcConnecting")}}class Cf extends Event{constructor(){super("webRtcConnected")}}class kf extends Event{constructor(){super("webRtcFailed")}}class Rf extends Event{constructor(r){super("webRtcDisconnected"),this.data=r}}class Af extends Event{constructor(r){super("dataChannelOpen"),this.data=r}}class If extends Event{constructor(r){super("dataChannelClose"),this.data=r}}class Mf extends Event{constructor(r){super("dataChannelError"),this.data=r}}class Pf extends Event{constructor(){super("videoInitialized")}}class Of extends Event{constructor(){super("streamLoading")}}class Df extends Event{constructor(){super("streamConnect")}}class zf extends Event{constructor(){super("streamDisconnect")}}class Lf extends Event{constructor(){super("streamReconnect")}}class Bf extends Event{constructor(r){super("playStreamError"),this.data=r}}class Nf extends Event{constructor(){super("playStream")}}class To extends Event{constructor(r){super("playStreamRejected"),this.data=r}}class Uf extends Event{constructor(r){super("loadFreezeFrame"),this.data=r}}class Ff extends Event{constructor(){super("hideFreezeFrame")}}class Vf extends Event{constructor(r){super("statsReceived"),this.data=r}}class Gf extends Event{constructor(r){super("streamerListMessage"),this.data=r}}class qf extends Event{constructor(r){super("StreamerIDChangedMessage"),this.data=r}}class Wf extends Event{constructor(r){super("latencyTestResult"),this.data=r}}class Hf extends Event{constructor(r){super("dataChannelLatencyTestResponse"),this.data=r}}class Kf extends Event{constructor(r){super("dataChannelLatencyTestResult"),this.data=r}}class jf extends Event{constructor(r){super("initialSettings"),this.data=r}}class ui extends Event{constructor(r){super("settingsChanged"),this.data=r}}class Ky extends Event{constructor(){super("xrSessionStarted")}}class jy extends Event{constructor(){super("xrSessionEnded")}}class Qf extends Event{constructor(r){super("xrFrame"),this.data=r}}class Xf extends Event{constructor(r){super("playerCount"),this.data=r}}class Yf extends Event{constructor(){super("webRtcTCPRelayDetected")}}class Jf extends EventTarget{dispatchEvent(r){return super.dispatchEvent(r)}addEventListener(r,s){super.addEventListener(r,s)}removeEventListener(r,s){super.removeEventListener(r,s)}}class X{}X.AutoConnect="AutoConnect",X.AutoPlayVideo="AutoPlayVideo",X.AFKDetection="TimeoutIfIdle",X.BrowserSendOffer="OfferToReceive",X.HoveringMouseMode="HoveringMouse",X.ForceMonoAudio="ForceMonoAudio",X.ForceTURN="ForceTURN",X.FakeMouseWithTouches="FakeMouseWithTouches",X.IsQualityController="ControlsQuality",X.MatchViewportResolution="MatchViewportRes",X.StartVideoMuted="StartVideoMuted",X.SuppressBrowserKeys="SuppressBrowserKeys",X.UseMic="UseMic",X.KeyboardInput="KeyboardInput",X.MouseInput="MouseInput",X.TouchInput="TouchInput",X.GamepadInput="GamepadInput",X.XRControllerInput="XRControllerInput",X.WaitForStreamer="WaitForStreamer",X.HideUI="HideUI";const Qy=d=>Object.getOwnPropertyNames(X).some((r=>X[r]===d));class me{}me.AFKTimeoutSecs="AFKTimeout",me.AFKCountdownSecs="AFKCountdown",me.MinQP="MinQP",me.MaxQP="MaxQP",me.WebRTCFPS="WebRTCFPS",me.WebRTCMinBitrate="WebRTCMinBitrate",me.WebRTCMaxBitrate="WebRTCMaxBitrate",me.MaxReconnectAttempts="MaxReconnectAttempts",me.StreamerAutoJoinInterval="StreamerAutoJoinInterval";const Xy=d=>Object.getOwnPropertyNames(me).some((r=>me[r]===d));class qr{}qr.SignallingServerUrl="ss";const Yy=d=>Object.getOwnPropertyNames(qr).some((r=>qr[r]===d));class dt{}dt.PreferredCodec="PreferredCodec",dt.StreamerId="StreamerId";const Jy=d=>Object.getOwnPropertyNames(dt).some((r=>dt[r]===d));class Zy{constructor(r={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:s,useUrlParams:a}=r;this._useUrlParams=!!a,this.populateDefaultSettings(this._useUrlParams,s)}get useUrlParams(){return this._useUrlParams}populateDefaultSettings(r,s){this.textParameters.set(qr.SignallingServerUrl,new vf(qr.SignallingServerUrl,"Signalling url","Url of the signalling server",s&&s.hasOwnProperty(qr.SignallingServerUrl)?s[qr.SignallingServerUrl]:(location.protocol==="https:"?"wss://":"ws://")+window.location.hostname+(window.location.port==="80"||window.location.port===""?"":`:${window.location.port}`),r)),this.optionParameters.set(dt.StreamerId,new bo(dt.StreamerId,"Streamer ID","The ID of the streamer to stream.",s&&s.hasOwnProperty(dt.StreamerId)?s[dt.StreamerId]:"",[],r)),this.optionParameters.set(dt.PreferredCodec,new bo(dt.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation","H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",s&&s.hasOwnProperty(dt.PreferredCodec)?[s[dt.PreferredCodec]]:(function(){const a=[];if(!RTCRtpReceiver.getCapabilities)return a.push("Only available on Chrome"),a;const f=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((_=>{const C=_.mimeType.split("/")[1]+" "+(_.sdpFmtpLine||"");f.exec(C)!==null&&a.push(C)})),a})(),r)),this.flags.set(X.AutoConnect,new St(X.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",!(!s||!s.hasOwnProperty(X.AutoConnect))&&s[X.AutoConnect],r)),this.flags.set(X.AutoPlayVideo,new St(X.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!s||!s.hasOwnProperty(X.AutoPlayVideo)||s[X.AutoPlayVideo],r)),this.flags.set(X.BrowserSendOffer,new St(X.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!s||!s.hasOwnProperty(X.BrowserSendOffer))&&s[X.BrowserSendOffer],r)),this.flags.set(X.UseMic,new St(X.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!s||!s.hasOwnProperty(X.UseMic))&&s[X.UseMic],r)),this.flags.set(X.StartVideoMuted,new St(X.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!s||!s.hasOwnProperty(X.StartVideoMuted))&&s[X.StartVideoMuted],r)),this.flags.set(X.SuppressBrowserKeys,new St(X.SuppressBrowserKeys,"Suppress browser keys","Suppress certain browser keys that we use in UE, for example F5 to show shader complexity instead of refresh the page.",!s||!s.hasOwnProperty(X.SuppressBrowserKeys)||s[X.SuppressBrowserKeys],r)),this.flags.set(X.IsQualityController,new St(X.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!s||!s.hasOwnProperty(X.IsQualityController)||s[X.IsQualityController],r)),this.flags.set(X.ForceMonoAudio,new St(X.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!s||!s.hasOwnProperty(X.ForceMonoAudio))&&s[X.ForceMonoAudio],r)),this.flags.set(X.ForceTURN,new St(X.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!s||!s.hasOwnProperty(X.ForceTURN))&&s[X.ForceTURN],r)),this.flags.set(X.AFKDetection,new St(X.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!s||!s.hasOwnProperty(X.AFKDetection))&&s[X.AFKDetection],r)),this.flags.set(X.MatchViewportResolution,new St(X.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",!(!s||!s.hasOwnProperty(X.MatchViewportResolution))&&s[X.MatchViewportResolution],r)),this.flags.set(X.HoveringMouseMode,new St(X.HoveringMouseMode,"Control Scheme: Locked Mouse","Either locked mouse, where the pointer is consumed by the video and locked to it, or hovering mouse, where the mouse is not consumed.",!(!s||!s.hasOwnProperty(X.HoveringMouseMode))&&s[X.HoveringMouseMode],r,((a,f)=>{f.label=`Control Scheme: ${a?"Hovering":"Locked"} Mouse`}))),this.flags.set(X.FakeMouseWithTouches,new St(X.FakeMouseWithTouches,"Fake mouse with touches","A single finger touch is converted into a mouse event. This allows a non-touch application to be controlled partially via a touch device.",!(!s||!s.hasOwnProperty(X.FakeMouseWithTouches))&&s[X.FakeMouseWithTouches],r)),this.flags.set(X.KeyboardInput,new St(X.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!s||!s.hasOwnProperty(X.KeyboardInput)||s[X.KeyboardInput],r)),this.flags.set(X.MouseInput,new St(X.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!s||!s.hasOwnProperty(X.MouseInput)||s[X.MouseInput],r)),this.flags.set(X.TouchInput,new St(X.TouchInput,"Touch input","If enabled, send touch events to streamer",!s||!s.hasOwnProperty(X.TouchInput)||s[X.TouchInput],r)),this.flags.set(X.GamepadInput,new St(X.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!s||!s.hasOwnProperty(X.GamepadInput)||s[X.GamepadInput],r)),this.flags.set(X.XRControllerInput,new St(X.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!s||!s.hasOwnProperty(X.XRControllerInput)||s[X.XRControllerInput],r)),this.flags.set(X.WaitForStreamer,new St(X.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!s||!s.hasOwnProperty(X.WaitForStreamer)||s[X.WaitForStreamer],r)),this.flags.set(X.HideUI,new St(X.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!s||!s.hasOwnProperty(X.HideUI))&&s[X.HideUI],r)),this.numericParameters.set(me.AFKTimeoutSecs,new Mr(me.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,s&&s.hasOwnProperty(me.AFKTimeoutSecs)?s[me.AFKTimeoutSecs]:120,r)),this.numericParameters.set(me.AFKCountdownSecs,new Mr(me.AFKCountdownSecs,"AFK countdown","The time (in seconds) for a user to respond before the stream is ended after an AFK timeout.",10,null,10,r)),this.numericParameters.set(me.MaxReconnectAttempts,new Mr(me.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,s&&s.hasOwnProperty(me.MaxReconnectAttempts)?s[me.MaxReconnectAttempts]:3,r)),this.numericParameters.set(me.MinQP,new Mr(me.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,s&&s.hasOwnProperty(me.MinQP)?s[me.MinQP]:0,r)),this.numericParameters.set(me.MaxQP,new Mr(me.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,s&&s.hasOwnProperty(me.MaxQP)?s[me.MaxQP]:51,r)),this.numericParameters.set(me.WebRTCFPS,new Mr(me.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,s&&s.hasOwnProperty(me.WebRTCFPS)?s[me.WebRTCFPS]:60,r)),this.numericParameters.set(me.WebRTCMinBitrate,new Mr(me.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,s&&s.hasOwnProperty(me.WebRTCMinBitrate)?s[me.WebRTCMinBitrate]:0,r)),this.numericParameters.set(me.WebRTCMaxBitrate,new Mr(me.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,s&&s.hasOwnProperty(me.WebRTCMaxBitrate)?s[me.WebRTCMaxBitrate]:0,r)),this.numericParameters.set(me.StreamerAutoJoinInterval,new Mr(me.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,s&&s.hasOwnProperty(me.StreamerAutoJoinInterval)?s[me.StreamerAutoJoinInterval]:3e3,r))}_addOnNumericSettingChangedListener(r,s){this.numericParameters.has(r)&&this.numericParameters.get(r).addOnChangedListener(s)}_addOnOptionSettingChangedListener(r,s){this.optionParameters.has(r)&&this.optionParameters.get(r).addOnChangedListener(s)}getNumericSettingValue(r){if(this.numericParameters.has(r))return this.numericParameters.get(r).number;throw new Error(`There is no numeric setting with the id of ${r}`)}getTextSettingValue(r){if(this.textParameters.has(r))return this.textParameters.get(r).value;throw new Error(`There is no numeric setting with the id of ${r}`)}setNumericSetting(r,s){if(!this.numericParameters.has(r))throw new Error(`There is no numeric setting with the id of ${r}`);this.numericParameters.get(r).number=s}_addOnSettingChangedListener(r,s){this.flags.has(r)&&(this.flags.get(r).onChange=s)}_addOnTextSettingChangedListener(r,s){this.textParameters.has(r)&&(this.textParameters.get(r).onChange=s)}getSettingOption(r){return this.optionParameters.get(r)}isFlagEnabled(r){return this.flags.get(r).flag}setFlagEnabled(r,s){this.flags.has(r)?this.flags.get(r).flag=s:T.Warning(T.GetStackTrace(),`Cannot toggle flag called ${r} - it does not exist in the Config.flags map.`)}setTextSetting(r,s){this.textParameters.has(r)?this.textParameters.get(r).text=s:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.textParameters map.`)}setOptionSettingOptions(r,s){this.optionParameters.has(r)?this.optionParameters.get(r).options=s:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(r,s){if(this.optionParameters.has(r)){const a=this.optionParameters.get(r),f=a.options;f.includes(s)||(f.push(s),a.options=f),a.selected=s}else T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.enumParameters map.`)}setFlagLabel(r,s){this.flags.has(r)?this.flags.get(r).label=s:T.Warning(T.GetStackTrace(),`Cannot set label for flag called ${r} - it does not exist in the Config.flags map.`)}setSettings(r){for(const s of Object.keys(r))Qy(s)?this.setFlagEnabled(s,r[s]):Xy(s)?this.setNumericSetting(s,r[s]):Yy(s)?this.setTextSetting(s,r[s]):Jy(s)&&this.setOptionSettingValue(s,r[s])}getSettings(){const r={};for(const[s,a]of this.flags.entries())r[s]=a.flag;for(const[s,a]of this.numericParameters.entries())r[s]=a.number;for(const[s,a]of this.textParameters.entries())r[s]=a.text;for(const[s,a]of this.optionParameters.entries())r[s]=a.selected;return r}getFlags(){return Array.from(this.flags.values())}getTextSettings(){return Array.from(this.textParameters.values())}getNumericSettings(){return Array.from(this.numericParameters.values())}getOptionSettings(){return Array.from(this.optionParameters.values())}_registerOnChangeEvents(r){for(const s of this.flags.keys()){const a=this.flags.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"flag",value:f,target:a})))}for(const s of this.numericParameters.keys()){const a=this.numericParameters.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"number",value:f,target:a})))}for(const s of this.textParameters.keys()){const a=this.textParameters.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"text",value:f,target:a})))}for(const s of this.optionParameters.keys()){const a=this.optionParameters.get(s);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"option",value:f,target:a})))}}}var Ns;(function(d){d[d.LockedMouse=0]="LockedMouse",d[d.HoveringMouse=1]="HoveringMouse"})(Ns||(Ns={}));class Zf{constructor(r,s,a){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=r,this.pixelStreaming=s,this.onDismissAfk=a,this.onAFKTimedOutCallback=()=>{console.log("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new bf))}startAfkWarningTimer(){this.config.getNumericSettingValue(me.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(X.AFKDetection)?this.active=!0:this.active=!1,this.resetAfkWarningTimer()}stopAfkWarningTimer(){this.active=!1,this.countdownActive=!1,clearTimeout(this.warnTimer),clearInterval(this.countDownTimer)}pauseAfkWarningTimer(){this.active=!1}resetAfkWarningTimer(){this.active&&this.config.isFlagEnabled(X.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(me.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new _f({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(me.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new So({countDown:this.countDown})),this.config.isFlagEnabled(X.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new Sf),this.onAFKTimedOutCallback(),T.Log(T.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new So({countDown:this.countDown}))}),1e3)}}class Np{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(r,s,a){this.peerConnection=r,this.label=s,this.datachannelOptions=a,a==null&&(this.datachannelOptions={},this.datachannelOptions.ordered=!0),this.dataChannel=this.peerConnection.createDataChannel(this.label,this.datachannelOptions),this.setupDataChannel()}setupDataChannel(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=r=>this.handleOnOpen(r),this.dataChannel.onclose=r=>this.handleOnClose(r),this.dataChannel.onmessage=r=>this.handleOnMessage(r),this.dataChannel.onerror=r=>this.handleOnError(r)}handleOnOpen(r){var s;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) opened.`,7),this.onOpen((s=this.dataChannel)===null||s===void 0?void 0:s.label,r)}handleOnClose(r){var s;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) closed.`,7),this.onClose((s=this.dataChannel)===null||s===void 0?void 0:s.label,r)}handleOnMessage(r){T.Log(T.GetStackTrace(),`Data Channel (${this.label}) message: ${r}`,8)}handleOnError(r){var s;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) error: ${r}`,7),this.onError((s=this.dataChannel)===null||s===void 0?void 0:s.label,r)}onOpen(r,s){}onClose(r,s){}onError(r,s){}}class em{}class tm{}class rm{}class Eo{}class sm{}class ew{}class tw{}class nm{constructor(){this.inboundVideoStats=new tm,this.inboundAudioStats=new em,this.DataChannelStats=new rm,this.outBoundVideoStats=new sm,this.sessionStats=new ew,this.streamStats=new tw,this.codecs=new Map}processStats(r){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,r.forEach((s=>{switch(s.type){case"candidate-pair":this.handleCandidatePair(s);break;case"certificate":case"media-source":case"media-playout":case"outbound-rtp":case"peer-connection":case"remote-inbound-rtp":break;case"codec":this.handleCodec(s);break;case"data-channel":this.handleDataChannel(s);break;case"inbound-rtp":this.handleInBoundRTP(s);break;case"local-candidate":this.handleLocalCandidate(s);break;case"remote-candidate":this.handleRemoteCandidate(s);break;case"remote-outbound-rtp":this.handleRemoteOutBound(s);break;case"track":this.handleTrack(s);break;case"transport":this.handleTransport(s);break;case"stream":this.handleStream(s);break;default:T.Error(T.GetStackTrace(),"unhandled Stat Type"),T.Log(T.GetStackTrace(),s)}}))}handleStream(r){this.streamStats=r}handleCandidatePair(r){this.candidatePairs.push(r)}handleDataChannel(r){this.DataChannelStats.bytesReceived=r.bytesReceived,this.DataChannelStats.bytesSent=r.bytesSent,this.DataChannelStats.dataChannelIdentifier=r.dataChannelIdentifier,this.DataChannelStats.id=r.id,this.DataChannelStats.label=r.label,this.DataChannelStats.messagesReceived=r.messagesReceived,this.DataChannelStats.messagesSent=r.messagesSent,this.DataChannelStats.protocol=r.protocol,this.DataChannelStats.state=r.state,this.DataChannelStats.timestamp=r.timestamp}handleLocalCandidate(r){const s=new Eo;s.label="local-candidate",s.address=r.address,s.port=r.port,s.protocol=r.protocol,s.candidateType=r.candidateType,s.id=r.id,s.relayProtocol=r.relayProtocol,s.transportId=r.transportId,this.localCandidates.push(s)}handleRemoteCandidate(r){const s=new Eo;s.label="remote-candidate",s.address=r.address,s.port=r.port,s.protocol=r.protocol,s.id=r.id,s.candidateType=r.candidateType,s.relayProtocol=r.relayProtocol,s.transportId=r.transportId,this.remoteCandidates.push(s)}handleInBoundRTP(r){switch(r.kind){case"video":this.inboundVideoStats=r,this.lastVideoStats!=null&&(this.inboundVideoStats.bitrate=8*(this.inboundVideoStats.bytesReceived-this.lastVideoStats.bytesReceived)/(this.inboundVideoStats.timestamp-this.lastVideoStats.timestamp),this.inboundVideoStats.bitrate=Math.floor(this.inboundVideoStats.bitrate)),this.lastVideoStats=Object.assign({},this.inboundVideoStats);break;case"audio":this.inboundAudioStats=r,this.lastAudioStats!=null&&(this.inboundAudioStats.bitrate=8*(this.inboundAudioStats.bytesReceived-this.lastAudioStats.bytesReceived)/(this.inboundAudioStats.timestamp-this.lastAudioStats.timestamp),this.inboundAudioStats.bitrate=Math.floor(this.inboundAudioStats.bitrate)),this.lastAudioStats=Object.assign({},this.inboundAudioStats);break;default:T.Log(T.GetStackTrace(),"Kind is not handled")}}handleRemoteOutBound(r){r.kind==="video"&&(this.outBoundVideoStats.bytesSent=r.bytesSent,this.outBoundVideoStats.id=r.id,this.outBoundVideoStats.localId=r.localId,this.outBoundVideoStats.packetsSent=r.packetsSent,this.outBoundVideoStats.remoteTimestamp=r.remoteTimestamp,this.outBoundVideoStats.timestamp=r.timestamp)}handleTrack(r){r.type!=="track"||r.trackIdentifier!=="video_label"&&r.kind!=="video"||(this.inboundVideoStats.framesDropped=r.framesDropped,this.inboundVideoStats.framesReceived=r.framesReceived,this.inboundVideoStats.frameHeight=r.frameHeight,this.inboundVideoStats.frameWidth=r.frameWidth)}handleTransport(r){this.transportStats=r}handleCodec(r){const s=r.id,a=`${r.mimeType.replace("video/","").replace("audio/","")}${r.sdpFmtpLine?` ${r.sdpFmtpLine}`:""}`;this.codecs.set(s,a)}handleSessionStatistics(r,s,a){const f=Date.now()-r;this.sessionStats.runTime=new Date(f).toISOString().substr(11,8).toString();const _=s===null?"Not sent yet":s?"true":"false";this.sessionStats.controlsStreamInput=_,this.sessionStats.videoEncoderAvgQP=a}isNumber(r){return typeof r=="number"&&isFinite(r)}getActiveCandidatePair(){return this.transportStats?this.candidatePairs.find((r=>r.id===this.transportStats.selectedCandidatePairId),null):this.candidatePairs.find((r=>r.selected),null)}}const Up=(Fp={parseRtpParameters:()=>Bp.parseRtpParameters,splitSections:()=>Bp.splitSections},uo={},Ui.d(uo,Fp),uo);var Fp,uo;class im{static isVideoTransciever(r){return this.canTransceiverReceiveVideo(r)||this.canTransceiverSendVideo(r)}static canTransceiverReceiveVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="video"}static canTransceiverSendVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="video"}static isAudioTransciever(r){return this.canTransceiverReceiveAudio(r)||this.canTransceiverSendAudio(r)}static canTransceiverReceiveAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="audio"}static canTransceiverSendAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="audio"}}var ln,be,co=function(d,r,s,a){return new(s||(s=Promise))((function(f,_){function C(U){try{b(a.next(U))}catch(z){_(z)}}function R(U){try{b(a.throw(U))}catch(z){_(z)}}function b(U){var z;U.done?f(U.value):(z=U.value,z instanceof s?z:new s((function(re){re(z)}))).then(C,R)}b((a=a.apply(d,[])).next())}))};class rw{constructor(r,s,a){this.config=s,this.createPeerConnection(r,a)}createPeerConnection(r,s){this.config.isFlagEnabled(X.ForceTURN)&&(r.iceTransportPolicy="relay",T.Log(T.GetStackTrace(),"Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(r),this.peerConnection.onsignalingstatechange=a=>this.handleSignalStateChange(a),this.peerConnection.oniceconnectionstatechange=a=>this.handleIceConnectionStateChange(a),this.peerConnection.onicegatheringstatechange=a=>this.handleIceGatheringStateChange(a),this.peerConnection.ontrack=a=>this.handleOnTrack(a),this.peerConnection.onicecandidate=a=>this.handleIceCandidate(a),this.peerConnection.ondatachannel=a=>this.handleDataChannel(a),this.aggregatedStats=new nm,this.preferredCodec=s,this.updateCodecSelection=!0}createOffer(r,s){return co(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Create Offer",6);const a=location.hostname==="localhost"||location.hostname==="127.0.0.1",f=location.protocol==="https:";let _=s.isFlagEnabled(X.UseMic);!_||a||f||(_=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(_).finally((()=>{var C;(C=this.peerConnection)===null||C===void 0||C.createOffer(r).then((R=>{var b;this.showTextOverlayConnecting(),R.sdp=this.mungeSDP(R.sdp,_),(b=this.peerConnection)===null||b===void 0||b.setLocalDescription(R),this.onSendWebRTCOffer(R)})).catch((()=>{this.showTextOverlaySetupFailure()}))}))}))}receiveOffer(r,s){var a;return co(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Receive Offer",6),(a=this.peerConnection)===null||a===void 0||a.setRemoteDescription(r).then((()=>{const f=location.hostname==="localhost"||location.hostname==="127.0.0.1",_=location.protocol==="https:";let C=s.isFlagEnabled(X.UseMic);!C||f||_||(C=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(dt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r)),this.setupTransceiversAsync(C).finally((()=>{var R;(R=this.peerConnection)===null||R===void 0||R.createAnswer().then((b=>{var U;return b.sdp=this.mungeSDP(b.sdp,C),(U=this.peerConnection)===null||U===void 0?void 0:U.setLocalDescription(b)})).then((()=>{var b;this.onSendWebRTCAnswer((b=this.peerConnection)===null||b===void 0?void 0:b.currentLocalDescription)})).catch((()=>{T.Error(T.GetStackTrace(),"createAnswer() failed")}))}))}))}))}receiveAnswer(r){var s;(s=this.peerConnection)===null||s===void 0||s.setRemoteDescription(r),this.config.setOptionSettingOptions(dt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r))}generateStats(){var r;(r=this.peerConnection)===null||r===void 0||r.getStats(null).then((s=>{this.aggregatedStats.processStats(s),this.onVideoStats(this.aggregatedStats),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId&&this.config.setOptionSettingValue(dt.PreferredCodec,this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId))}))}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(r,s){let a=r.replace(/(a=fmtp:\d+ .*level-asymmetry-allowed=.*)\r\n/gm,`$1;x-google-start-bitrate=10000;x-google-max-bitrate=100000\r
|
|
2880
|
+
`),f="maxaveragebitrate=510000;";return s&&(f+="sprop-maxcapturerate=48000;"),f+=this.config.isFlagEnabled(X.ForceMonoAudio)?"stereo=0;":"stereo=1;",f+="useinbandfec=1",a=a.replace("useinbandfec=1",f),a}handleOnIce(r){var s;T.Log(T.GetStackTrace(),"peerconnection handleOnIce",6),this.config.isFlagEnabled(X.ForceTURN)&&r.candidate.indexOf("relay")<0?T.Info(T.GetStackTrace(),`Dropping candidate because it was not TURN relay. | Type= ${r.type} | Protocol= ${r.protocol} | Address=${r.address} | Port=${r.port} |`,6):(s=this.peerConnection)===null||s===void 0||s.addIceCandidate(r)}handleSignalStateChange(r){T.Log(T.GetStackTrace(),"signaling state change: "+r,6)}handleIceConnectionStateChange(r){T.Log(T.GetStackTrace(),"ice connection state change: "+r,6),this.onIceConnectionStateChange(r)}handleIceGatheringStateChange(r){T.Log(T.GetStackTrace(),"ice gathering state change: "+JSON.stringify(r),6)}handleOnTrack(r){this.onTrack(r)}handleIceCandidate(r){this.onPeerIceCandidate(r)}handleDataChannel(r){this.onDataChannel(r)}onTrack(r){}onIceConnectionStateChange(r){}onPeerIceCandidate(r){}onDataChannel(r){}fuzzyIntersectUEAndBrowserCodecs(r){const s=new Array,a=this.parseAvailableCodecs(r),f=this.config.getSettingOption(dt.PreferredCodec).options;for(const _ of a)if(f.includes(_))s.push(_);else{const C=_.split(" ")[0];for(const R of f)if(R.includes(C)){s.push(R);break}}return s}setupTransceiversAsync(r){var s,a,f,_,C,R,b,U,z,re,K,ie;return co(this,void 0,void 0,(function*(){let J=!1;for(const H of(a=(s=this.peerConnection)===null||s===void 0?void 0:s.getTransceivers())!==null&&a!==void 0?a:[])if(H&&H.receiver&&H.receiver.track&&H.receiver.track.kind==="video"){J=!0;break}if(J||(f=this.peerConnection)===null||f===void 0||f.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&this.preferredCodec!=""){for(const H of(C=(_=this.peerConnection)===null||_===void 0?void 0:_.getTransceivers())!==null&&C!==void 0?C:[])if(H&&H.receiver&&H.receiver.track&&H.receiver.track.kind==="video"&&H.setCodecPreferences){const se=this.preferredCodec.split(" "),ve={mimeType:"video/"+se[0],clockRate:9e4,sdpFmtpLine:se[1]?se[1]:""},de=[ve];RTCRtpReceiver.getCapabilities("video").codecs.forEach((he=>{(he.mimeType!=ve.mimeType||he?.sdpFmtpLine!=ve?.sdpFmtpLine)&&de.push(he)}));for(const he of de)he?.sdpFmtpLine!==void 0&&he.sdpFmtpLine!==""||delete he.sdpFmtpLine;H.setCodecPreferences(de)}}let Y=!1;for(const H of(b=(R=this.peerConnection)===null||R===void 0?void 0:R.getTransceivers())!==null&&b!==void 0?b:[])if(H&&H.receiver&&H.receiver.track&&H.receiver.track.kind==="audio"){Y=!0;break}if(r){const H={video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}},se=yield navigator.mediaDevices.getUserMedia(H);if(se)if(Y){for(const ve of(re=(z=this.peerConnection)===null||z===void 0?void 0:z.getTransceivers())!==null&&re!==void 0?re:[])if(im.canTransceiverReceiveAudio(ve))for(const de of se.getTracks())de.kind&&de.kind=="audio"&&(ve.sender.replaceTrack(de),ve.direction="sendrecv")}else for(const ve of se.getTracks())ve.kind&&ve.kind=="audio"&&((K=this.peerConnection)===null||K===void 0||K.addTransceiver(ve,{direction:"sendrecv"}));else Y||(ie=this.peerConnection)===null||ie===void 0||ie.addTransceiver("audio",{direction:"recvonly"})}else Y||(U=this.peerConnection)===null||U===void 0||U.addTransceiver("audio",{direction:"recvonly"})}))}onVideoStats(r){}onSendWebRTCOffer(r){}onSendWebRTCAnswer(r){}showTextOverlayConnecting(){}showTextOverlaySetupFailure(){}parseAvailableCodecs(r){if(!RTCRtpReceiver.getCapabilities)return["Only available on Chrome"];const s=[],a=(0,Up.splitSections)(r.sdp);return a.shift(),a.forEach((f=>{const{codecs:_}=(0,Up.parseRtpParameters)(f),C=/(VP\d|H26\d|AV1).*/;_.forEach((R=>{const b=R.name+" "+Object.keys(R.parameters||{}).map((U=>U+"="+R.parameters[U])).join(";");if(C.exec(b)!==null){R.name=="VP9"&&(R.parameters={"profile-id":"0"});const U=R.name+" "+Object.keys(R.parameters||{}).map((z=>z+"="+R.parameters[z])).join(";");s.push(U)}}))})),s}}class am{constructor(){this.PixelStreamingSettings=new sw,this.EncoderSettings=new om,this.WebRTCSettings=new lm}ueCompatible(){this.WebRTCSettings.MaxFPS!=null&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class sw{}class om{}class lm{}class um{constructor(){this.ReceiptTimeMs=null,this.TransmissionTimeMs=null,this.PreCaptureTimeMs=null,this.PostCaptureTimeMs=null,this.PreEncodeTimeMs=null,this.PostEncodeTimeMs=null,this.EncodeMs=null,this.CaptureToSendMs=null,this.testStartTimeMs=0,this.browserReceiptTimeMs=0,this.latencyExcludingDecode=0,this.testDuration=0,this.networkLatency=0,this.browserSendLatency=0,this.frameDisplayDeltaTimeMs=0,this.endToEndLatency=0,this.encodeLatency=0}setFrameDisplayDeltaTime(r){this.frameDisplayDeltaTimeMs==0&&(this.frameDisplayDeltaTimeMs=Math.round(r))}processFields(){this.EncodeMs!=null||this.PreEncodeTimeMs==null&&this.PostEncodeTimeMs==null||(T.Log(T.GetStackTrace(),`Setting Encode Ms
|
|
2881
|
+
${this.PostEncodeTimeMs}
|
|
2882
|
+
${this.PreEncodeTimeMs}`,6),this.EncodeMs=this.PostEncodeTimeMs-this.PreEncodeTimeMs),this.CaptureToSendMs!=null||this.PreCaptureTimeMs==null&&this.PostCaptureTimeMs==null||(T.Log(T.GetStackTrace(),`Setting CaptureToSendMs Ms
|
|
2883
|
+
${this.PostCaptureTimeMs}
|
|
2884
|
+
${this.PreCaptureTimeMs}`,6),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class ho{static setExtensionFromBytes(r,s){s.receiving||(s.mimetype="",s.extension="",s.receiving=!0,s.valid=!1,s.chunks=0,s.data=[],s.timestampStart=new Date().getTime(),T.Log(T.GetStackTrace(),"Received first chunk of file",6));const a=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),a,6),s.extension=a}static setMimeTypeFromBytes(r,s){s.receiving||(s.mimetype="",s.extension="",s.receiving=!0,s.valid=!1,s.chunks=0,s.data=[],s.timestampStart=new Date().getTime(),T.Log(T.GetStackTrace(),"Received first chunk of file",6));const a=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),a,6),s.mimetype=a}static setContentsFromBytes(r,s){if(!s.receiving)return;s.chunks=Math.ceil(new DataView(r.slice(1,5).buffer).getInt32(0,!0)/16379);const a=r.slice(5);if(s.data.push(a),T.Log(T.GetStackTrace(),`Received file chunk: ${s.data.length}/${s.chunks}`,6),s.data.length===s.chunks){s.receiving=!1,s.valid=!0,T.Log(T.GetStackTrace(),"Received complete file",6);const f=new Date().getTime()-s.timestampStart,_=Math.round(16384*s.chunks/f);T.Log(T.GetStackTrace(),`Average transfer bitrate: ${_}kb/s over ${f/1e3} seconds`,6);const C=new Blob(s.data,{type:s.mimetype}),R=document.createElement("a");R.setAttribute("href",URL.createObjectURL(C)),R.setAttribute("download",`transfer.${s.extension}`),document.body.append(R),R.remove()}else s.data.length>s.chunks&&(s.receiving=!1,T.Error(T.GetStackTrace(),`Received bigger file than advertised: ${s.data.length}/${s.chunks}`))}}class nw{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}}class zt{}zt.mainButton=0,zt.auxiliaryButton=1,zt.secondaryButton=2,zt.fourthButton=3,zt.fifthButton=4;class Gt{}Gt.primaryButton=1,Gt.secondaryButton=2,Gt.auxiliaryButton=4,Gt.fourthButton=8,Gt.fifthButton=16;class cn{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(r){this.unregisterCallbacks.push(r)}unregisterAll(){for(const r of this.unregisterCallbacks)r();this.unregisterCallbacks=[]}}class iw{constructor(r,s,a){this.touchEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a;const f=R=>this.onTouchStart(R),_=R=>this.onTouchEnd(R),C=R=>this.onTouchMove(R);document.addEventListener("touchstart",f,{passive:!1}),document.addEventListener("touchend",_,{passive:!1}),document.addEventListener("touchmove",C,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchend",_))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",C)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}setVideoElementParentClientRect(r){this.videoElementParentClientRect=r}onTouchStart(r){if(this.videoElementProvider.isVideoReady()&&r.target===this.videoElementProvider.getVideoElement()){if(this.fakeTouchFinger==null){const s=r.changedTouches[0];this.fakeTouchFinger=new aw(s.identifier,s.clientX-this.videoElementParentClientRect.left,s.clientY-this.videoElementParentClientRect.top);const a=this.videoElementProvider.getVideoParentElement(),f=new MouseEvent("mouseenter",s);a.dispatchEvent(f);const _=this.coordinateConverter.normalizeAndQuantizeUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([zt.mainButton,_.x,_.y])}r.preventDefault()}}onTouchEnd(r){if(!this.videoElementProvider.isVideoReady()||this.fakeTouchFinger==null)return;const s=this.videoElementProvider.getVideoParentElement(),a=this.toStreamerMessagesProvider.toStreamerHandlers;for(let f=0;f<r.changedTouches.length;f++){const _=r.changedTouches[f];if(_.identifier===this.fakeTouchFinger.id){const C=_.clientX-this.videoElementParentClientRect.left,R=_.clientY-this.videoElementParentClientRect.top,b=this.coordinateConverter.normalizeAndQuantizeUnsigned(C,R);a.get("MouseUp")([zt.mainButton,b.x,b.y]);const U=new MouseEvent("mouseleave",_);s.dispatchEvent(U),this.fakeTouchFinger=null;break}}r.preventDefault()}onTouchMove(r){if(!this.videoElementProvider.isVideoReady()||this.fakeTouchFinger==null)return;const s=this.toStreamerMessagesProvider.toStreamerHandlers;for(let a=0;a<r.touches.length;a++){const f=r.touches[a];if(f.identifier===this.fakeTouchFinger.id){const _=f.clientX-this.videoElementParentClientRect.left,C=f.clientY-this.videoElementParentClientRect.top,R=this.coordinateConverter.normalizeAndQuantizeUnsigned(_,C),b=this.coordinateConverter.normalizeAndQuantizeSigned(_-this.fakeTouchFinger.x,C-this.fakeTouchFinger.y);s.get("MouseMove")([R.x,R.y,b.x,b.y]),this.fakeTouchFinger.x=_,this.fakeTouchFinger.y=C;break}}r.preventDefault()}}class aw{constructor(r,s,a){this.id=r,this.x=s,this.y=a}}class qt{}qt.backSpace=8,qt.shift=16,qt.control=17,qt.alt=18,qt.rightShift=253,qt.rightControl=254,qt.rightAlt=255;class ow{constructor(r,s,a){this.keyboardEventListenerTracker=new cn,this.CodeToKeyCode={Escape:27,Digit0:48,Digit1:49,Digit2:50,Digit3:51,Digit4:52,Digit5:53,Digit6:54,Digit7:55,Digit8:56,Digit9:57,Minus:173,Equal:187,Backspace:8,Tab:9,KeyQ:81,KeyW:87,KeyE:69,KeyR:82,KeyT:84,KeyY:89,KeyU:85,KeyI:73,KeyO:79,KeyP:80,BracketLeft:219,BracketRight:221,Enter:13,ControlLeft:17,KeyA:65,KeyS:83,KeyD:68,KeyF:70,KeyG:71,KeyH:72,KeyJ:74,KeyK:75,KeyL:76,Semicolon:186,Quote:222,Backquote:192,ShiftLeft:16,Backslash:220,KeyZ:90,KeyX:88,KeyC:67,KeyV:86,KeyB:66,KeyN:78,KeyM:77,Comma:188,Period:190,Slash:191,ShiftRight:253,AltLeft:18,Space:32,CapsLock:20,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,Pause:19,ScrollLock:145,NumpadDivide:111,NumpadMultiply:106,NumpadSubtract:109,NumpadAdd:107,NumpadDecimal:110,Numpad9:105,Numpad8:104,Numpad7:103,Numpad6:102,Numpad5:101,Numpad4:100,Numpad3:99,Numpad2:98,Numpad1:97,Numpad0:96,NumLock:144,ControlRight:254,AltRight:255,Home:36,End:35,ArrowUp:38,ArrowLeft:37,ArrowRight:39,ArrowDown:40,PageUp:33,PageDown:34,Insert:45,Delete:46,ContextMenu:93},this.toStreamerMessagesProvider=r,this.config=s,this.activeKeysProvider=a}registerKeyBoardEvents(){const r=_=>this.handleOnCompositionEnd(_),s=_=>this.handleOnKeyDown(_),a=_=>this.handleOnKeyUp(_),f=_=>this.handleOnKeyPress(_);document.addEventListener("compositionend",r),document.addEventListener("keydown",s),document.addEventListener("keyup",a),document.addEventListener("keypress",f),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("compositionend",r))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keydown",s))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keyup",a))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keypress",f)))}unregisterKeyBoardEvents(){this.keyboardEventListenerTracker.unregisterAll()}handleOnKeyDown(r){const s=this.getKeycode(r);s&&s!==229&&(T.Log(T.GetStackTrace(),`key down ${s}, repeat = ${r.repeat}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyDown")([this.getKeycode(r),r.repeat?1:0]),this.activeKeysProvider.getActiveKeys().push(s),s===qt.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:qt.backSpace})),this.config.isFlagEnabled(X.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(s)&&r.preventDefault())}handleOnKeyUp(r){const s=this.getKeycode(r);s&&(T.Log(T.GetStackTrace(),`key up ${s}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyUp")([s]),this.config.isFlagEnabled(X.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(s)&&r.preventDefault())}handleOnKeyPress(r){if(!("charCode"in r))return void T.Warning(T.GetStackTrace(),"KeyboardEvent.charCode is deprecated in this browser, cannot send key press.");const s=r.charCode;T.Log(T.GetStackTrace(),`key press ${s}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyPress")([s])}handleOnCompositionEnd(r){r.data&&r.data.length&&r.data.split("").forEach((s=>{this.handleOnKeyDown(new KeyboardEvent("keydown",{keyCode:s.toUpperCase().charCodeAt(0),charCode:s.charCodeAt(0)})),this.handleOnKeyPress(new KeyboardEvent("keypress",{keyCode:s.toUpperCase().charCodeAt(0),charCode:s.charCodeAt(0)})),this.handleOnKeyUp(new KeyboardEvent("keyup",{keyCode:s.toUpperCase().charCodeAt(0),charCode:s.charCodeAt(0)}))}))}getKeycode(r){if(!("keyCode"in r)){const s=r;return s.code in this.CodeToKeyCode?this.CodeToKeyCode[s.code]:(T.Warning(T.GetStackTrace(),`Keyboard code of ${s.code} is not supported in our mapping, ignoring this key.`),null)}return r.keyCode===qt.shift&&r.code==="ShiftRight"?qt.rightShift:r.keyCode===qt.control&&r.code==="ControlRight"?qt.rightControl:r.keyCode===qt.alt&&r.code==="AltRight"?qt.rightAlt:r.keyCode}isKeyCodeBrowserKey(r){return r>=112&&r<=123||r===9}}class lw{constructor(r,s,a){this.x=0,this.y=0,this.updateMouseMovePositionEvent=_=>{this.updateMouseMovePosition(_)},this.mouseEventListenerTracker=new cn,this.videoElementProvider=r,this.mouseController=s,this.activeKeysProvider=a;const f=this.videoElementProvider.getVideoParentElement();this.x=f.getBoundingClientRect().width/2,this.y=f.getBoundingClientRect().height/2,this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y)}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}lockStateChange(){const r=this.videoElementProvider.getVideoParentElement(),s=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers;if(document.pointerLockElement===r||document.mozPointerLockElement===r)T.Log(T.GetStackTrace(),"Pointer locked",6),document.addEventListener("mousemove",this.updateMouseMovePositionEvent,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1)));else{T.Log(T.GetStackTrace(),"The pointer lock status is now unlocked",6),document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1);let a=this.activeKeysProvider.getActiveKeys();const f=new Set(a),_=[];f.forEach((C=>{})),_.forEach((C=>{s.get("KeyUp")([C])})),a=[]}}updateMouseMovePosition(r){if(!this.videoElementProvider.isVideoReady())return;const s=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers,a=this.videoElementProvider.getVideoParentElement().clientWidth,f=this.videoElementProvider.getVideoParentElement().clientHeight;this.x+=r.movementX,this.y+=r.movementY,this.x>a&&(this.x-=a),this.y>f&&(this.y-=f),this.x<0&&(this.x=a+this.x),this.y<0&&(this.y=f-this.y),this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y);const _=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(r.movementX,r.movementY);s.get("MouseMove")([this.coord.x,this.coord.y,_.x,_.y])}handleMouseDown(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([r.button,this.coord.x,this.coord.y])}handleMouseUp(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r.button,this.coord.x,this.coord.y])}handleMouseWheel(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([r.wheelDelta,this.coord.x,this.coord.y])}handleMouseDouble(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([r.button,this.coord.x,this.coord.y])}handlePressMouseButtons(r){this.videoElementProvider.isVideoReady()&&this.mouseController.pressMouseButtons(r.buttons,this.x,this.y)}handleReleaseMouseButtons(r){this.videoElementProvider.isVideoReady()&&this.mouseController.releaseMouseButtons(r.buttons,this.x,this.y)}}class uw{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 dw{constructor(r,s,a,f){this.mouseEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.coordinateConverter=a,this.videoElementProvider=s,this.activeKeysProvider=f,this.registerMouseEnterAndLeaveEvents()}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}registerLockedMouseEvents(r){const s=this.videoElementProvider.getVideoParentElement(),a=new lw(this.videoElementProvider,r,this.activeKeysProvider);if(s.requestPointerLock=s.requestPointerLock||s.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,s.requestPointerLock){const U=()=>{s.requestPointerLock()};s.addEventListener("click",U),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("click",U)))}const f=()=>a.lockStateChange();document.addEventListener("pointerlockchange",f,!1),document.addEventListener("mozpointerlockchange",f,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("pointerlockchange",f,!1))),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mozpointerlockchange",f,!1)));const _=U=>a.handleMouseDown(U),C=U=>a.handleMouseUp(U),R=U=>a.handleMouseWheel(U),b=U=>a.handleMouseDouble(U);s.addEventListener("mousedown",_),s.addEventListener("mouseup",C),s.addEventListener("wheel",R),s.addEventListener("dblclick",b),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousedown",_))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mouseup",C))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("wheel",R))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("dblclick",b))),this.mouseEventListenerTracker.addUnregisterCallback((()=>a.unregisterMouseEvents())),this.mouseEventListenerTracker.addUnregisterCallback((()=>{!document.exitPointerLock||document.pointerLockElement!==s&&document.mozPointerLockElement!==s||document.exitPointerLock()}))}registerHoveringMouseEvents(r){const s=this.videoElementProvider.getVideoParentElement(),a=new uw(r),f=z=>a.updateMouseMovePosition(z),_=z=>a.handleMouseDown(z),C=z=>a.handleMouseUp(z),R=z=>a.handleContextMenu(z),b=z=>a.handleMouseWheel(z),U=z=>a.handleMouseDouble(z);s.addEventListener("mousemove",f),s.addEventListener("mousedown",_),s.addEventListener("mouseup",C),s.addEventListener("contextmenu",R),s.addEventListener("wheel",b),s.addEventListener("dblclick",U),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousemove",f))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mousedown",_))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("mouseup",C))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("contextmenu",R))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("wheel",b))),this.mouseEventListenerTracker.addUnregisterCallback((()=>s.removeEventListener("dblclick",U))),this.mouseEventListenerTracker.addUnregisterCallback((()=>a.unregisterMouseEvents()))}registerMouseEnterAndLeaveEvents(){const r=this.videoElementProvider.getVideoParentElement(),s=f=>{this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"Mouse Entered",6),this.sendMouseEnter(),this.pressMouseButtons(f.buttons,f.x,f.y))},a=f=>{this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"Mouse Left",6),this.sendMouseLeave(),this.releaseMouseButtons(f.buttons,f.x,f.y))};r.addEventListener("mouseenter",s),r.addEventListener("mouseleave",a),this.mouseEventListenerTracker.addUnregisterCallback((()=>r.removeEventListener("mouseenter",s))),this.mouseEventListenerTracker.addUnregisterCallback((()=>r.removeEventListener("mouseleave",a)))}releaseMouseButtons(r,s,a){const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);r&Gt.primaryButton&&this.sendMouseUp(zt.mainButton,f.x,f.y),r&Gt.secondaryButton&&this.sendMouseUp(zt.secondaryButton,f.x,f.y),r&Gt.auxiliaryButton&&this.sendMouseUp(zt.auxiliaryButton,f.x,f.y),r&Gt.fourthButton&&this.sendMouseUp(zt.fourthButton,f.x,f.y),r&Gt.fifthButton&&this.sendMouseUp(zt.fifthButton,f.x,f.y)}pressMouseButtons(r,s,a){if(!this.videoElementProvider.isVideoReady())return;const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);r&Gt.primaryButton&&this.sendMouseDown(zt.mainButton,f.x,f.y),r&Gt.secondaryButton&&this.sendMouseDown(zt.secondaryButton,f.x,f.y),r&Gt.auxiliaryButton&&this.sendMouseDown(zt.auxiliaryButton,f.x,f.y),r&Gt.fourthButton&&this.sendMouseDown(zt.fourthButton,f.x,f.y),r&Gt.fifthButton&&this.sendMouseDown(zt.fifthButton,f.x,f.y)}sendMouseEnter(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseEnter")()}sendMouseLeave(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseLeave")()}sendMouseDown(r,s,a){this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),`mouse button ${r} down at (${s}, ${a})`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([r,s,a]))}sendMouseUp(r,s,a){if(!this.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),`mouse button ${r} up at (${s}, ${a})`,6);const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(s,a);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r,f.x,f.y])}}class cw{constructor(r,s,a){this.fingers=[9,8,7,6,5,4,3,2,1,0],this.fingerIds=new Map,this.maxByteValue=255,this.touchEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a,this.videoElementParent=s.getVideoElement();const f=b=>this.onTouchStart(b),_=b=>this.onTouchEnd(b),C=b=>this.onTouchMove(b);this.videoElementParent.addEventListener("touchstart",f),this.videoElementParent.addEventListener("touchend",_),this.videoElementParent.addEventListener("touchmove",C),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchend",_))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchmove",C))),T.Log(T.GetStackTrace(),"Touch Events Registered",6);const R=b=>{b.preventDefault()};document.addEventListener("touchmove",R),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",R)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}rememberTouch(r){const s=this.fingers.pop();s===void 0&&T.Log(T.GetStackTrace(),"exhausted touch identifiers",6),this.fingerIds.set(r.identifier,s)}forgetTouch(r){this.fingers.push(this.fingerIds.get(r.identifier)),this.fingers.sort((function(s,a){return a-s})),this.fingerIds.delete(r.identifier)}onTouchStart(r){if(this.videoElementProvider.isVideoReady()){for(let s=0;s<r.changedTouches.length;s++)this.rememberTouch(r.changedTouches[s]);T.Log(T.GetStackTrace(),"touch start",6),this.emitTouchData("TouchStart",r.changedTouches),r.preventDefault()}}onTouchEnd(r){if(this.videoElementProvider.isVideoReady()){T.Log(T.GetStackTrace(),"touch end",6),this.emitTouchData("TouchEnd",r.changedTouches);for(let s=0;s<r.changedTouches.length;s++)this.forgetTouch(r.changedTouches[s]);r.preventDefault()}}onTouchMove(r){this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"touch move",6),this.emitTouchData("TouchMove",r.touches),r.preventDefault())}emitTouchData(r,s){if(!this.videoElementProvider.isVideoReady())return;const a=this.videoElementProvider.getVideoParentElement().getBoundingClientRect(),f=this.toStreamerMessagesProvider.toStreamerHandlers;for(let _=0;_<s.length;_++){const R=s[_],b=R.clientX-a.left,U=R.clientY-a.top;T.Log(T.GetStackTrace(),`F${this.fingerIds.get(R.identifier)}=(${b}, ${U})`,6);const z=this.coordinateConverter.normalizeAndQuantizeUnsigned(b,U);switch(r){case"TouchStart":f.get("TouchStart")([1,z.x,z.y,this.fingerIds.get(R.identifier),this.maxByteValue*(R.force>0?R.force:1),z.inRange?1:0]);break;case"TouchEnd":f.get("TouchEnd")([1,z.x,z.y,this.fingerIds.get(R.identifier),this.maxByteValue*R.force,z.inRange?1:0]);break;case"TouchMove":f.get("TouchMove")([1,z.x,z.y,this.fingerIds.get(R.identifier),this.maxByteValue*(R.force>0?R.force:1),z.inRange?1:0])}}}}class hw{constructor(r){this.gamePadEventListenerTracker=new cn,this.toStreamerMessagesProvider=r,this.requestAnimationFrame=(window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.requestAnimationFrame).bind(window);const s=window;if(window.addEventListener("beforeunload",(a=>this.onBeforeUnload(a))),"GamepadEvent"in s){const a=_=>this.gamePadConnectHandler(_),f=_=>this.gamePadDisconnectHandler(_);window.addEventListener("gamepadconnected",a),window.addEventListener("gamepaddisconnected",f),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepadconnected",a))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepaddisconnected",f)))}else if("WebKitGamepadEvent"in s){const a=_=>this.gamePadConnectHandler(_),f=_=>this.gamePadDisconnectHandler(_);window.addEventListener("webkitgamepadconnected",a),window.addEventListener("webkitgamepaddisconnected",f),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepadconnected",a))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepaddisconnected",f)))}if(this.controllers=[],navigator.getGamepads)for(const a of navigator.getGamepads())a&&this.gamePadConnectHandler(new GamepadEvent("gamepadconnected",{gamepad:a}))}unregisterGamePadEvents(){this.gamePadEventListenerTracker.unregisterAll();for(const r of this.controllers)r.id!==void 0&&this.onGamepadDisconnected(r.id);this.controllers=[],this.onGamepadConnected=()=>{},this.onGamepadDisconnected=()=>{}}gamePadConnectHandler(r){T.Log(T.GetStackTrace(),"Gamepad connect handler",6);const s=r.gamepad,a={currentState:s,prevState:s,id:void 0};this.controllers.push(a),this.controllers[s.index].currentState=s,this.controllers[s.index].prevState=s,T.Log(T.GetStackTrace(),"gamepad: "+s.id+" connected",6),window.requestAnimationFrame((()=>this.updateStatus())),this.onGamepadConnected()}gamePadDisconnectHandler(r){T.Log(T.GetStackTrace(),"Gamepad disconnect handler",6),T.Log(T.GetStackTrace(),"gamepad: "+r.gamepad.id+" disconnected",6);const s=this.controllers[r.gamepad.index];delete this.controllers[r.gamepad.index],this.controllers=this.controllers.filter((a=>a!==void 0)),this.onGamepadDisconnected(s.id)}scanGamePads(){const r=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[];for(let s=0;s<r.length;s++)r[s]&&r[s].index in this.controllers&&(this.controllers[r[s].index].currentState=r[s])}updateStatus(){this.scanGamePads();const r=this.toStreamerMessagesProvider.toStreamerHandlers;for(const s of this.controllers){const a=s.id===void 0?this.controllers.indexOf(s):s.id,f=s.currentState;for(let _=0;_<s.currentState.buttons.length;_++){const C=s.currentState.buttons[_],R=s.prevState.buttons[_];C.pressed?_==ln.LeftTrigger?r.get("GamepadAnalog")([a,5,C.value]):_==ln.RightTrigger?r.get("GamepadAnalog")([a,6,C.value]):r.get("GamepadButtonPressed")([a,_,R.pressed?1:0]):!C.pressed&&R.pressed&&(_==ln.LeftTrigger?r.get("GamepadAnalog")([a,5,0]):_==ln.RightTrigger?r.get("GamepadAnalog")([a,6,0]):r.get("GamepadButtonReleased")([a,_,0]))}for(let _=0;_<f.axes.length;_+=2){const C=parseFloat(f.axes[_].toFixed(4)),R=-parseFloat(f.axes[_+1].toFixed(4));r.get("GamepadAnalog")([a,_+1,C]),r.get("GamepadAnalog")([a,_+2,R])}this.controllers[a].prevState=f}this.controllers.length>0&&this.requestAnimationFrame((()=>this.updateStatus()))}onGamepadResponseReceived(r){for(const s of this.controllers)if(s.id===void 0){s.id=r;break}}onGamepadConnected(){}onGamepadDisconnected(r){}onBeforeUnload(r){for(const s of this.controllers)this.onGamepadDisconnected(s.id)}}(function(d){d[d.RightClusterBottomButton=0]="RightClusterBottomButton",d[d.RightClusterRightButton=1]="RightClusterRightButton",d[d.RightClusterLeftButton=2]="RightClusterLeftButton",d[d.RightClusterTopButton=3]="RightClusterTopButton",d[d.LeftShoulder=4]="LeftShoulder",d[d.RightShoulder=5]="RightShoulder",d[d.LeftTrigger=6]="LeftTrigger",d[d.RightTrigger=7]="RightTrigger",d[d.SelectOrBack=8]="SelectOrBack",d[d.StartOrForward=9]="StartOrForward",d[d.LeftAnalogPress=10]="LeftAnalogPress",d[d.RightAnalogPress=11]="RightAnalogPress",d[d.LeftClusterTopButton=12]="LeftClusterTopButton",d[d.LeftClusterBottomButton=13]="LeftClusterBottomButton",d[d.LeftClusterLeftButton=14]="LeftClusterLeftButton",d[d.LeftClusterRightButton=15]="LeftClusterRightButton",d[d.CentreButton=16]="CentreButton",d[d.LeftStickHorizontal=0]="LeftStickHorizontal",d[d.LeftStickVertical=1]="LeftStickVertical",d[d.RightStickHorizontal=2]="RightStickHorizontal",d[d.RightStickVertical=3]="RightStickVertical"})(ln||(ln={}));class pw{constructor(r,s,a){this.activeKeys=new fw,this.toStreamerMessagesProvider=r,this.videoElementProvider=s,this.coordinateConverter=a}registerKeyBoard(r){T.Log(T.GetStackTrace(),"Register Keyboard Events",7);const s=new ow(this.toStreamerMessagesProvider,r,this.activeKeys);return s.registerKeyBoardEvents(),s}registerMouse(r){T.Log(T.GetStackTrace(),"Register Mouse Events",7);const s=new dw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys);switch(r){case Ns.LockedMouse:s.registerLockedMouseEvents(s);break;case Ns.HoveringMouse:s.registerHoveringMouseEvents(s);break;default:T.Info(T.GetStackTrace(),"unknown Control Scheme Type Defaulting to Locked Mouse Events"),s.registerLockedMouseEvents(s)}return s}registerTouch(r,s){if(T.Log(T.GetStackTrace(),"Registering Touch",6),r){const a=new iw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return a.setVideoElementParentClientRect(s),a}return new cw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return T.Log(T.GetStackTrace(),"Register Game Pad",7),new hw(this.toStreamerMessagesProvider)}}class fw{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class mw{constructor(r,s){this.lastTimeResized=new Date().getTime(),this.videoElement=document.createElement("video"),this.config=s,this.videoElement.id="streamingVideo",this.videoElement.disablePictureInPicture=!0,this.videoElement.playsInline=!0,this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.pointerEvents="all",r.appendChild(this.videoElement),this.onResizePlayerCallback=()=>{console.log("Resolution changed, restyling player, did you forget to override this function?")},this.onMatchViewportResolutionCallback=()=>{console.log("Resolution changed and match viewport resolution is turned on, did you forget to override this function?")},this.videoElement.onclick=()=>{this.audioElement!=null&&this.audioElement.paused&&this.audioElement.play(),this.videoElement.paused&&this.videoElement.play()},this.videoElement.onloadedmetadata=()=>{this.onVideoInitialized()},window.addEventListener("resize",(()=>this.resizePlayerStyle()),!0),window.addEventListener("orientationchange",(()=>this.onOrientationChange()))}setAudioElement(r){this.audioElement=r}play(){return this.videoElement.muted=this.config.isFlagEnabled(X.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(X.AutoPlayVideo),this.videoElement.play()}isPaused(){return this.videoElement.paused}isVideoReady(){return this.videoElement.readyState!==void 0&&this.videoElement.readyState>0}hasVideoSource(){return this.videoElement.srcObject!==void 0&&this.videoElement.srcObject!==null}getVideoElement(){return this.videoElement}getVideoParentElement(){return this.videoElement.parentElement}setVideoEnabled(r){this.videoElement.srcObject.getTracks().forEach((s=>s.enabled=r))}onVideoInitialized(){}onOrientationChange(){clearTimeout(this.orientationChangeTimeout),this.orientationChangeTimeout=window.setTimeout((()=>{this.resizePlayerStyle()}),500)}resizePlayerStyle(){const r=this.getVideoParentElement();r&&(this.updateVideoStreamSize(),r.classList.contains("fixed-size")||this.resizePlayerStyleToFillParentElement(),this.onResizePlayerCallback())}resizePlayerStyleToFillParentElement(){this.getVideoParentElement().setAttribute("style","top: 0px; left: 0px; width: 100%; height: 100%; cursor: default;")}updateVideoStreamSize(){if(this.config.isFlagEnabled(X.MatchViewportResolution))if(new Date().getTime()-this.lastTimeResized>300){const r=this.getVideoParentElement();if(!r)return;this.onMatchViewportResolutionCallback(r.clientWidth,r.clientHeight),this.lastTimeResized=new Date().getTime()}else T.Log(T.GetStackTrace(),"Resizing too often - skipping",6),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout((()=>this.updateVideoStreamSize()),100)}}class gw{constructor(){this.toStreamerHandlers=new Map,this.fromStreamerHandlers=new Map,this.toStreamerMessages=new Map,this.fromStreamerMessages=new Map}populateDefaultProtocol(){this.toStreamerMessages.set("IFrameRequest",{id:0,structure:[]}),this.toStreamerMessages.set("RequestQualityControl",{id:1,structure:[]}),this.toStreamerMessages.set("FpsRequest",{id:2,structure:[]}),this.toStreamerMessages.set("AverageBitrateRequest",{id:3,structure:[]}),this.toStreamerMessages.set("StartStreaming",{id:4,structure:[]}),this.toStreamerMessages.set("StopStreaming",{id:5,structure:[]}),this.toStreamerMessages.set("LatencyTest",{id:6,structure:["string"]}),this.toStreamerMessages.set("RequestInitialSettings",{id:7,structure:[]}),this.toStreamerMessages.set("TestEcho",{id:8,structure:[]}),this.toStreamerMessages.set("DataChannelLatencyTest",{id:9,structure:[]}),this.toStreamerMessages.set("UIInteraction",{id:50,structure:["string"]}),this.toStreamerMessages.set("Command",{id:51,structure:["string"]}),this.toStreamerMessages.set("KeyDown",{id:60,structure:["uint8","uint8"]}),this.toStreamerMessages.set("KeyUp",{id:61,structure:["uint8"]}),this.toStreamerMessages.set("KeyPress",{id:62,structure:["uint16"]}),this.toStreamerMessages.set("MouseEnter",{id:70,structure:[]}),this.toStreamerMessages.set("MouseLeave",{id:71,structure:[]}),this.toStreamerMessages.set("MouseDown",{id:72,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseUp",{id:73,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseMove",{id:74,structure:["uint16","uint16","int16","int16"]}),this.toStreamerMessages.set("MouseWheel",{id:75,structure:["int16","uint16","uint16"]}),this.toStreamerMessages.set("MouseDouble",{id:76,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("TouchStart",{id:80,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchEnd",{id:81,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchMove",{id:82,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadConnected",{id:93,structure:[]}),this.toStreamerMessages.set("GamepadButtonPressed",{id:90,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadButtonReleased",{id:91,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadAnalog",{id:92,structure:["uint8","uint8","double"]}),this.toStreamerMessages.set("GamepadDisconnected",{id:94,structure:["uint8"]}),this.fromStreamerMessages.set(0,"QualityControlOwnership"),this.fromStreamerMessages.set(1,"Response"),this.fromStreamerMessages.set(2,"Command"),this.fromStreamerMessages.set(3,"FreezeFrame"),this.fromStreamerMessages.set(4,"UnfreezeFrame"),this.fromStreamerMessages.set(5,"VideoEncoderAvgQP"),this.fromStreamerMessages.set(6,"LatencyTest"),this.fromStreamerMessages.set(7,"InitialSettings"),this.fromStreamerMessages.set(8,"FileExtension"),this.fromStreamerMessages.set(9,"FileMimeType"),this.fromStreamerMessages.set(10,"FileContents"),this.fromStreamerMessages.set(11,"TestEcho"),this.fromStreamerMessages.set(12,"InputControlOwnership"),this.fromStreamerMessages.set(13,"GamepadResponse"),this.fromStreamerMessages.set(14,"DataChannelLatencyTest"),this.fromStreamerMessages.set(255,"Protocol")}registerMessageHandler(r,s,a){switch(r){case be.ToStreamer:this.toStreamerHandlers.set(s,a);break;case be.FromStreamer:this.fromStreamerHandlers.set(s,a);break;default:T.Log(T.GetStackTrace(),`Unknown message direction ${r}`)}}}(function(d){d[d.ToStreamer=0]="ToStreamer",d[d.FromStreamer=1]="FromStreamer"})(be||(be={}));class yw{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 ww{constructor(r,s){this.dataChannelSender=r,this.toStreamerMessagesMapProvider=s}sendMessageToStreamer(r,s){s===void 0&&(s=[]);const a=this.toStreamerMessagesMapProvider.toStreamerMessages.get(r);if(a===void 0)return void T.Error(T.GetStackTrace(),`Attempted to send a message to the streamer with message type: ${r}, but the frontend hasn't been configured to send such a message. Check you've added the message type in your cpp`);if(a.structure&&s&&a.structure.length!==s.length)return void T.Error(T.GetStackTrace(),`Provided message data doesn't match expected layout. Expected [ ${a.structure.map((b=>{switch(b){case"uint8":case"uint16":case"int16":case"float":case"double":return"number";case"string":return"string"}})).toString()} ] but received [ ${s.map((b=>typeof b)).toString()} ]`);let f=0;const _=new TextEncoder;s.forEach(((b,U)=>{switch(a.structure[U]){case"uint8":f+=1;break;case"uint16":case"int16":f+=2;break;case"float":f+=4;break;case"double":f+=8;break;case"string":f+=2,f+=2*_.encode(b).length}}));const C=new DataView(new ArrayBuffer(f+1));C.setUint8(0,a.id);let R=1;s.forEach(((b,U)=>{switch(a.structure[U]){case"uint8":C.setUint8(R,b),R+=1;break;case"uint16":C.setUint16(R,b,!0),R+=2;break;case"int16":C.setInt16(R,b,!0),R+=2;break;case"float":C.setFloat32(R,b,!0),R+=4;break;case"double":C.setFloat64(R,b,!0),R+=8;break;case"string":C.setUint16(R,b.length,!0),R+=2;for(let z=0;z<b.length;z++)C.setUint16(R,b.charCodeAt(z),!0),R+=2}})),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(C.buffer):T.Info(T.GetStackTrace(),`Data channel cannot send yet, skipping sending message: ${r} - ${new Uint8Array(C.buffer)}`)}}class vw{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 _w{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 bw{constructor(r){this.videoElementProvider=r,this.normalizeAndQuantizeUnsignedFunc=()=>{throw new Error("Normalize and quantize unsigned, method not implemented.")},this.normalizeAndQuantizeSignedFunc=()=>{throw new Error("Normalize and unquantize signed, method not implemented.")},this.denormalizeAndUnquantizeUnsignedFunc=()=>{throw new Error("Denormalize and unquantize unsigned, method not implemented.")}}normalizeAndQuantizeUnsigned(r,s){return this.normalizeAndQuantizeUnsignedFunc(r,s)}unquantizeAndDenormalizeUnsigned(r,s){return this.denormalizeAndUnquantizeUnsignedFunc(r,s)}normalizeAndQuantizeSigned(r,s){return this.normalizeAndQuantizeSignedFunc(r,s)}setupNormalizeAndQuantize(){if(this.videoElementParent=this.videoElementProvider.getVideoParentElement(),this.videoElement=this.videoElementProvider.getVideoElement(),this.videoElementParent&&this.videoElement){const r=this.videoElementParent.clientWidth||1,s=this.videoElementParent.clientHeight||1,a=this.videoElement.videoWidth||1,f=s/r,_=(this.videoElement.videoHeight||1)/a;f>_?(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio > videoAspectRatio",6),this.ratio=f/_,this.normalizeAndQuantizeUnsignedFunc=(C,R)=>this.normalizeAndQuantizeUnsignedPlayerBigger(C,R),this.normalizeAndQuantizeSignedFunc=(C,R)=>this.normalizeAndQuantizeSignedPlayerBigger(C,R),this.denormalizeAndUnquantizeUnsignedFunc=(C,R)=>this.denormalizeAndUnquantizeUnsignedPlayerBigger(C,R)):(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio <= videoAspectRatio",6),this.ratio=_/f,this.normalizeAndQuantizeUnsignedFunc=(C,R)=>this.normalizeAndQuantizeUnsignedPlayerSmaller(C,R),this.normalizeAndQuantizeSignedFunc=(C,R)=>this.normalizeAndQuantizeSignedPlayerSmaller(C,R),this.denormalizeAndUnquantizeUnsignedFunc=(C,R)=>this.denormalizeAndUnquantizeUnsignedPlayerSmaller(C,R))}}normalizeAndQuantizeUnsignedPlayerBigger(r,s){const a=r/this.videoElementParent.clientWidth,f=this.ratio*(s/this.videoElementParent.clientHeight-.5)+.5;return a<0||a>1||f<0||f>1?new Oi(!1,65535,65535):new Oi(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerBigger(r,s){const a=r/65536,f=(s/65536-.5)/this.ratio+.5;return new $o(a*this.videoElementParent.clientWidth,f*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerBigger(r,s){const a=r/(.5*this.videoElementParent.clientWidth),f=this.ratio*s/(.5*this.videoElementParent.clientHeight);return new Vp(32767*a,32767*f)}normalizeAndQuantizeUnsignedPlayerSmaller(r,s){const a=this.ratio*(r/this.videoElementParent.clientWidth-.5)+.5,f=s/this.videoElementParent.clientHeight;return a<0||a>1||f<0||f>1?new Oi(!1,65535,65535):new Oi(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerSmaller(r,s){const a=(r/65536-.5)/this.ratio+.5,f=s/65536;return new $o(a*this.videoElementParent.clientWidth,f*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerSmaller(r,s){const a=this.ratio*r/(.5*this.videoElementParent.clientWidth),f=s/(.5*this.videoElementParent.clientHeight);return new Vp(32767*a,32767*f)}}class Oi{constructor(r,s,a){this.inRange=r,this.x=s,this.y=a}}class $o{constructor(r,s){this.x=r,this.y=s}}class Vp{constructor(r,s){this.x=r,this.y=s}}class dm{constructor(r,s){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=r,this.pixelStreaming=s,this.responseController=new yw,this.file=new nw,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new Zf(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new Hy(this.pixelStreaming.videoElementParent),this.videoPlayer=new mw(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(a,f)=>{const _={"Resolution.Width":a,"Resolution.Height":f};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(_)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new qy(this.videoPlayer),this.coordinateConverter=new bw(this.videoPlayer),this.sendrecvDataChannelController=new Np,this.recvDataChannelController=new Np,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new _w(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new gw,this.webSocketController=new wf,this.webSocketController.onConfig=a=>this.handleOnConfigMessage(a),this.webSocketController.onStreamerList=a=>this.handleStreamerListMessage(a),this.webSocketController.onStreamerIDChanged=a=>this.handleStreamerIDChangedMessage(a),this.webSocketController.onPlayerCount=a=>{this.pixelStreaming._onPlayerCount(a.count)},this.webSocketController.onOpen.addEventListener("open",(()=>{this.config.isFlagEnabled(X.BrowserSendOffer)||this.webSocketController.requestStreamerList()})),this.webSocketController.onClose.addEventListener("close",(a=>{const f=this.shouldReconnect&&a.detail.code!=1001&&this.config.getNumericSettingValue(me.MaxReconnectAttempts)>0,_=this.disconnectMessage?this.disconnectMessage:a.detail.reason;this.pixelStreaming._onDisconnect(_,!f&&!this.isReconnecting),this.afkController.stopAfkWarningTimer(),this.statsTimerHandle&&this.statsTimerHandle!==void 0&&window.clearInterval(this.statsTimerHandle),this.setVideoEncoderAvgQP(0),this.setTouchInputEnabled(!1),this.setMouseInputEnabled(!1),this.setKeyboardInputEnabled(!1),this.setGamePadInputEnabled(!1),f&&setTimeout((()=>{this.isReconnecting=!0,this.reconnectAttempt++,this.tryReconnect(a.detail.reason)}),2e3)})),this.sendMessageController=new ww(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new vw(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new pw(this.streamMessageController,this.videoPlayer,this.coordinateConverter),this.isUsingSFU=!1,this.isQualityController=!1,this.preferredCodec="",this.shouldReconnect=!0,this.isReconnecting=!1,this.reconnectAttempt=0,this.config._addOnOptionSettingChangedListener(dt.StreamerId,(a=>{a!==""&&(this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=a,this.webSocketController.sendSubscribe(a))})),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>{let a=this.config.getTextSettingValue(qr.SignallingServerUrl);return this.config.isFlagEnabled(X.BrowserSendOffer)&&(a+="?"+X.BrowserSendOffer+"=true"),a}}requestUnquantizedAndDenormalizeUnsigned(r,s){return this.coordinateConverter.unquantizeAndDenormalizeUnsigned(r,s)}handleOnMessage(r){const s=new Uint8Array(r.data);T.Log(T.GetStackTrace(),"Message incoming:"+s,6);const a=this.streamMessageController.fromStreamerMessages.get(s[0]);this.streamMessageController.fromStreamerHandlers.get(a)(r.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(be.FromStreamer,"QualityControlOwnership",(r=>this.onQualityControlOwnership(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"Response",(r=>this.responseController.onResponse(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"Command",(r=>{this.onCommand(r)})),this.streamMessageController.registerMessageHandler(be.FromStreamer,"FreezeFrame",(r=>this.onFreezeFrameMessage(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"UnfreezeFrame",(()=>this.invalidateFreezeFrameAndEnableVideo())),this.streamMessageController.registerMessageHandler(be.FromStreamer,"VideoEncoderAvgQP",(r=>this.handleVideoEncoderAvgQP(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"LatencyTest",(r=>this.handleLatencyTestResult(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"DataChannelLatencyTest",(r=>this.handleDataChannelLatencyTestResponse(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"InitialSettings",(r=>this.handleInitialSettings(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"FileExtension",(r=>this.onFileExtension(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"FileMimeType",(r=>this.onFileMimeType(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"FileContents",(r=>this.onFileContents(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(be.FromStreamer,"InputControlOwnership",(r=>this.onInputControlOwnership(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"GamepadResponse",(r=>this.onGamepadResponse(r))),this.streamMessageController.registerMessageHandler(be.FromStreamer,"Protocol",(r=>this.onProtocolMessage(r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"IFrameRequest",(()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"RequestQualityControl",(()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"FpsRequest",(()=>this.sendMessageController.sendMessageToStreamer("FpsRequest"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"AverageBitrateRequest",(()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"StartStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StartStreaming"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"StopStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StopStreaming"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"LatencyTest",(r=>this.sendMessageController.sendMessageToStreamer("LatencyTest",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"RequestInitialSettings",(()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(be.ToStreamer,"UIInteraction",(r=>this.sendMessageController.sendMessageToStreamer("UIInteraction",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"Command",(r=>this.sendMessageController.sendMessageToStreamer("Command",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"TextboxEntry",(r=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"KeyDown",(r=>this.sendMessageController.sendMessageToStreamer("KeyDown",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"KeyUp",(r=>this.sendMessageController.sendMessageToStreamer("KeyUp",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"KeyPress",(r=>this.sendMessageController.sendMessageToStreamer("KeyPress",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseEnter",(r=>this.sendMessageController.sendMessageToStreamer("MouseEnter",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseLeave",(r=>this.sendMessageController.sendMessageToStreamer("MouseLeave",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseDown",(r=>this.sendMessageController.sendMessageToStreamer("MouseDown",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseUp",(r=>this.sendMessageController.sendMessageToStreamer("MouseUp",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseMove",(r=>this.sendMessageController.sendMessageToStreamer("MouseMove",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseWheel",(r=>this.sendMessageController.sendMessageToStreamer("MouseWheel",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"MouseDouble",(r=>this.sendMessageController.sendMessageToStreamer("MouseDouble",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"TouchStart",(r=>this.sendMessageController.sendMessageToStreamer("TouchStart",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"TouchEnd",(r=>this.sendMessageController.sendMessageToStreamer("TouchEnd",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"TouchMove",(r=>this.sendMessageController.sendMessageToStreamer("TouchMove",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"GamepadConnected",(()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected"))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"GamepadButtonPressed",(r=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"GamepadButtonReleased",(r=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"GamepadAnalog",(r=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"GamepadDisconnected",(r=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XREyeViews",(r=>this.sendMessageController.sendMessageToStreamer("XREyeViews",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRHMDTransform",(r=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRControllerTransform",(r=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRSystem",(r=>this.sendMessageController.sendMessageToStreamer("XRSystem",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRButtonTouched",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRButtonTouchReleased",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRButtonPressed",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRButtonReleased",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",r))),this.streamMessageController.registerMessageHandler(be.ToStreamer,"XRAnalog",(r=>this.sendMessageController.sendMessageToStreamer("XRAnalog",r)))}onCommand(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.Command",6);const s=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),"Data Channel Command: "+s,6);const a=JSON.parse(s);a.command==="onScreenKeyboard"&&this.pixelStreaming._activateOnScreenKeyboard(a)}onProtocolMessage(r){try{const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s);Object.prototype.hasOwnProperty.call(a,"Direction")||T.Error(T.GetStackTrace(),"Malformed protocol received. Ensure the protocol message contains a direction");const f=a.Direction;delete a.Direction,T.Log(T.GetStackTrace(),`Received new ${f==be.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(a).forEach((_=>{const C=a[_];switch(f){case be.ToStreamer:if(!Object.prototype.hasOwnProperty.call(C,"id"))return void T.Error(T.GetStackTrace(),`ToStreamer->${_} protocol definition was malformed as it didn't contain at least an id
|
|
2885
|
+
|
|
2886
|
+
Definition was: ${JSON.stringify(C,null,2)}`);if(_==="UIInteraction"||_==="Command"||_==="LatencyTest")return;this.streamMessageController.toStreamerHandlers.get(_)?this.streamMessageController.toStreamerMessages.set(_,C):T.Error(T.GetStackTrace(),`There was no registered handler for "${_}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${_}", myHandler)`);break;case be.FromStreamer:if(!Object.prototype.hasOwnProperty.call(C,"id"))return void T.Error(T.GetStackTrace(),`FromStreamer->${_} protocol definition was malformed as it didn't contain at least an id
|
|
2887
|
+
|
|
2888
|
+
Definition was: ${JSON.stringify(C,null,2)}`);this.streamMessageController.fromStreamerHandlers.get(_)?this.streamMessageController.fromStreamerMessages.set(C.id,_):T.Error(T.GetStackTrace(),`There was no registered handler for "${C}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${_}", myHandler)`);break;default:T.Error(T.GetStackTrace(),`Unknown direction: ${f}`)}})),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(s){T.Log(T.GetStackTrace(),s)}}onInputControlOwnership(r){const s=new Uint8Array(r);T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.InputControlOwnership",6);const a=new Boolean(s[1]).valueOf();T.Log(T.GetStackTrace(),`Received input controller message - will your input control the stream: ${a}`),this.pixelStreaming._onInputControlOwnership(a)}onGamepadResponse(r){const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s);this.gamePadController.onGamepadResponseReceived(a.controllerId)}onAfkTriggered(){this.afkController.onAfkClick(),this.videoPlayer.isPaused()&&this.videoPlayer.hasVideoSource()&&this.playStream()}setAfkEnabled(r){r?this.onAfkTriggered():this.afkController.stopAfkWarningTimer()}tryReconnect(r){this.webSocketController?(this.isReconnecting=!0,this.webSocketController.webSocket&&this.webSocketController.webSocket.readyState!=WebSocket.CLOSED?(this.closeSignalingServer(`${r} Restarting stream...`),setTimeout((()=>{this.tryReconnect(r)}),3e3)):(this.pixelStreaming._onWebRtcAutoConnect(),this.connectToSignallingServer())):T.Log(T.GetStackTrace(),"The Web Socket Controller does not exist so this will not work right now.")}loadFreezeFrameOrShowPlayOverlay(){this.pixelStreaming.dispatchEvent(new Uf({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),this.shouldShowPlayOverlay===!0?(T.Log(T.GetStackTrace(),"showing play overlay"),this.resizePlayerStyle()):(T.Log(T.GetStackTrace(),"showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout((()=>{this.videoPlayer.setVideoEnabled(!1)}),this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6);const s=new Uint8Array(r);this.freezeFrameController.processFreezeFrameMessage(s,(()=>this.loadFreezeFrameOrShowPlayOverlay()))}invalidateFreezeFrameAndEnableVideo(){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6),setTimeout((()=>{this.pixelStreaming.dispatchEvent(new Ff),this.freezeFrameController.hideFreezeFrame()}),this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(r){const s=new Uint8Array(r);ho.setExtensionFromBytes(s,this.file)}onFileMimeType(r){const s=new Uint8Array(r);ho.setMimeTypeFromBytes(s,this.file)}onFileContents(r){const s=new Uint8Array(r);ho.setContentsFromBytes(s,this.file)}playStream(){if(!this.videoPlayer.getVideoElement()){const r="Could not play video stream because the video player was not initialized correctly.";return this.pixelStreaming.dispatchEvent(new Bf({message:r})),T.Error(T.GetStackTrace(),r),void this.closeSignalingServer("Stream not initialized correctly")}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(X.TouchInput)),this.pixelStreaming.dispatchEvent(new Nf),this.streamController.audioElement.srcObject){const r=this.config.isFlagEnabled(X.StartVideoMuted);this.streamController.audioElement.muted=r,r?this.playVideo():this.streamController.audioElement.play().then((()=>{this.playVideo()})).catch((s=>{T.Log(T.GetStackTrace(),s),T.Log(T.GetStackTrace(),"Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new To({reason:s}))}))}else this.playVideo();this.shouldShowPlayOverlay=!1,this.freezeFrameController.showFreezeFrame()}else T.Warning(T.GetStackTrace(),"Cannot play stream, the video element has no srcObject to play.")}playVideo(){this.videoPlayer.play().catch((r=>{this.streamController.audioElement.srcObject&&this.streamController.audioElement.pause(),T.Log(T.GetStackTrace(),r),T.Log(T.GetStackTrace(),"Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new To({reason:r}))}))}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(X.AutoPlayVideo)&&this.playStream(),this.resizePlayerStyle()}connectToSignallingServer(){this.locallyClosed=!1,this.shouldReconnect=!0,this.disconnectMessage=null;const r=this.signallingUrlBuilder();this.webSocketController.connect(r)}startSession(r){if(this.peerConfig=r,this.config.isFlagEnabled(X.ForceTURN)&&!this.checkTurnServerAvailability(r))return T.Info(T.GetStackTrace(),"No turn server was found in the Peer Connection Options. TURN cannot be forced, closing connection. Please use STUN instead"),void this.closeSignalingServer("TURN cannot be forced, closing connection. Please use STUN instead.");this.peerConnectionController=new rw(this.peerConfig,this.config,this.preferredCodec),this.peerConnectionController.onVideoStats=a=>this.handleVideoStats(a),this.peerConnectionController.onSendWebRTCOffer=a=>this.handleSendWebRTCOffer(a),this.peerConnectionController.onSendWebRTCAnswer=a=>this.handleSendWebRTCAnswer(a),this.peerConnectionController.onPeerIceCandidate=a=>this.handleSendIceCandidate(a),this.peerConnectionController.onDataChannel=a=>this.handleDataChannel(a),this.peerConnectionController.showTextOverlayConnecting=()=>this.pixelStreaming._onWebRtcConnecting(),this.peerConnectionController.showTextOverlaySetupFailure=()=>this.pixelStreaming._onWebRtcFailed();let s=!1;this.peerConnectionController.onIceConnectionStateChange=()=>{!s&&["connected","completed"].includes(this.peerConnectionController.peerConnection.iceConnectionState)&&(this.pixelStreaming._onWebRtcConnected(),s=!0)},this.peerConnectionController.onTrack=a=>this.streamController.handleOnTrack(a),this.config.isFlagEnabled(X.BrowserSendOffer)&&(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"cirrus",this.datachannelOptions),this.sendrecvDataChannelController.handleOnMessage=a=>this.handleOnMessage(a),this.peerConnectionController.createOffer(this.sdpConstraints,this.config))}checkTurnServerAvailability(r){if(!r.iceServers)return T.Info(T.GetStackTrace(),"A turn sever was not found"),!1;for(const s of r.iceServers)for(const a of s.urls)if(a.includes("turn"))return T.Log(T.GetStackTrace(),`A turn sever was found at ${a}`),!0;return T.Info(T.GetStackTrace(),"A turn sever was not found"),!1}handleOnConfigMessage(r){this.resizePlayerStyle(),this.startSession(r.peerConnectionOptions),this.webSocketController.onWebRtcAnswer=s=>this.handleWebRtcAnswer(s),this.webSocketController.onWebRtcOffer=s=>this.handleWebRtcOffer(s),this.webSocketController.onWebRtcPeerDataChannels=s=>this.handleWebRtcSFUPeerDatachannels(s),this.webSocketController.onIceCandidate=s=>this.handleIceCandidate(s)}handleStreamerListMessage(r){T.Log(T.GetStackTrace(),`Got streamer list ${r.ids}`,6);let s=null;var a=this.config.getSettingOption(dt.StreamerId);a.selected.toString().trim()&&(s=a.selected);const f=[...r.ids];f.unshift(""),this.config.setOptionSettingOptions(dt.StreamerId,f);let _=null;const C=this.config.isFlagEnabled(X.WaitForStreamer),R=this.config.getNumericSettingValue(me.MaxReconnectAttempts),b=this.config.getNumericSettingValue(me.StreamerAutoJoinInterval),U=this.config.useUrlParams,z=new URLSearchParams(window.location.search);U&&z.has(dt.StreamerId)?s=z.get(dt.StreamerId):this.subscribedStream&&(s=this.subscribedStream),s&&r.ids.includes(s)?_=s:s&&C||r.ids.length!=1||(_=r.ids[0]),_?(this.isReconnecting=!1,this.reconnectAttempt=0,this.config.setOptionSettingValue(dt.StreamerId,_)):C&&(this.reconnectAttempt<R?(this.isReconnecting=!0,this.reconnectAttempt++,setTimeout((()=>{this.webSocketController.requestStreamerList()}),b)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.shouldReconnect=!1)),this.pixelStreaming.dispatchEvent(new Gf({messageStreamerList:r,autoSelectedStreamerId:_,wantedStreamerId:s}))}handleStreamerIDChangedMessage(r){const s=r.newID;var a=this.config.getSettingOption(dt.StreamerId),f=a.onChange;a.onChange=()=>{};for(var _=a.options,C=0;C<_.length;++C)if(_[C]==this.subscribedStream){_[C]=s;break}a.options=_,a.selected=s,a.onChange=f,this.subscribedStream=r.newID,this.pixelStreaming.dispatchEvent(new qf({newID:s}))}handleWebRtcAnswer(r){T.Log(T.GetStackTrace(),`Got answer sdp ${r.sdp}`,6);const s={sdp:r.sdp,type:"answer"};this.peerConnectionController.receiveAnswer(s),this.handlePostWebrtcNegotiation()}handleWebRtcOffer(r){T.Log(T.GetStackTrace(),`Got offer sdp ${r.sdp}`,6),this.isUsingSFU=!!r.sfu&&r.sfu,this.isUsingSFU&&(this.peerConnectionController.preferredCodec="");const s={sdp:r.sdp,type:"offer"};this.peerConnectionController.receiveOffer(s,this.config),this.handlePostWebrtcNegotiation()}handleWebRtcSFUPeerDatachannels(r){const s={ordered:!0,negotiated:!0,id:r.sendStreamId},a=r.sendStreamId!=r.recvStreamId;if(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,a?"send-datachannel":"datachannel",s),a){const f={ordered:!0,negotiated:!0,id:r.recvStreamId};this.recvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"recv-datachannel",f),this.recvDataChannelController.handleOnOpen=()=>this.webSocketController.sendSFURecvDataChannelReady(),this.recvDataChannelController.handleOnMessage=_=>this.handleOnMessage(_)}else this.sendrecvDataChannelController.handleOnMessage=f=>this.handleOnMessage(f)}handlePostWebrtcNegotiation(){this.afkController.startAfkWarningTimer(),this.pixelStreaming._onWebRtcSdp(),this.statsTimerHandle&&this.statsTimerHandle!==void 0&&window.clearInterval(this.statsTimerHandle),this.statsTimerHandle=window.setInterval((()=>this.getStats()),1e3),this.setMouseInputEnabled(this.config.isFlagEnabled(X.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(X.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(X.GamepadInput))}handleIceCandidate(r){T.Log(T.GetStackTrace(),"Web RTC Controller: onWebRtcIce",6);const s=new RTCIceCandidate(r);this.peerConnectionController.handleOnIce(s)}handleSendIceCandidate(r){T.Log(T.GetStackTrace(),"OnIceCandidate",6),r.candidate&&r.candidate.candidate&&this.webSocketController.sendIceCandidate(r.candidate)}handleDataChannel(r){T.Log(T.GetStackTrace(),"Data channel created for us by browser as we are a receiving peer.",6),this.sendrecvDataChannelController.dataChannel=r.channel,this.sendrecvDataChannelController.setupDataChannel(),this.sendrecvDataChannelController.handleOnMessage=s=>this.handleOnMessage(s)}handleSendWebRTCOffer(r){T.Log(T.GetStackTrace(),"Sending the offer to the Server",6);const s={minBitrateBps:1e3*this.config.getNumericSettingValue(me.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(me.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcOffer(r,s)}handleSendWebRTCAnswer(r){T.Log(T.GetStackTrace(),"Sending the answer to the Server",6);const s={minBitrateBps:1e3*this.config.getNumericSettingValue(me.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(me.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcAnswer(r,s),this.isUsingSFU&&this.webSocketController.sendWebRtcDatachannelRequest()}setUpMouseAndFreezeFrame(){this.videoElementParentClientRect=this.videoPlayer.getVideoParentElement().getBoundingClientRect(),this.coordinateConverter.setupNormalizeAndQuantize(),this.freezeFrameController.freezeFrame.resize()}closeSignalingServer(r){var s;this.locallyClosed=!0,this.shouldReconnect=!1,this.disconnectMessage=r,(s=this.webSocketController)===null||s===void 0||s.close()}closePeerConnection(){var r;(r=this.peerConnectionController)===null||r===void 0||r.close()}close(){this.closeSignalingServer(""),this.closePeerConnection()}getStats(){this.peerConnectionController.generateStats()}sendLatencyTest(){this.latencyStartTime=Date.now(),this.streamMessageController.toStreamerHandlers.get("LatencyTest")([JSON.stringify({StartTime:this.latencyStartTime})])}sendDataChannelLatencyTest(r){this.streamMessageController.toStreamerHandlers.get("DataChannelLatencyTest")([JSON.stringify(r)])}sendEncoderMinQP(r){T.Log(T.GetStackTrace(),`MinQP=${r}
|
|
2889
|
+
`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQP":r})])}sendEncoderMaxQP(r){T.Log(T.GetStackTrace(),`MaxQP=${r}
|
|
2890
|
+
`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQP":r})])}sendWebRTCMinBitrate(r){T.Log(T.GetStackTrace(),`WebRTC Min Bitrate=${r}`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MinBitrate":r})])}sendWebRTCMaxBitrate(r){T.Log(T.GetStackTrace(),`WebRTC Max Bitrate=${r}`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxBitrate":r})])}sendWebRTCFps(r){T.Log(T.GetStackTrace(),`WebRTC FPS=${r}`,6),r!=null&&(this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.Fps":r})]),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxFps":r})]))}sendShowFps(){T.Log(T.GetStackTrace(),"---- Sending show stat to UE ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"stat.fps":""})])}sendIframeRequest(){T.Log(T.GetStackTrace(),"---- Sending Request for an IFrame ----",6),this.streamMessageController.toStreamerHandlers.get("IFrameRequest")()}emitUIInteraction(r){T.Log(T.GetStackTrace(),"---- Sending custom UIInteraction message ----",6),this.streamMessageController.toStreamerHandlers.get("UIInteraction")([JSON.stringify(r)])}emitCommand(r){T.Log(T.GetStackTrace(),"---- Sending custom Command message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(r)])}emitConsoleCommand(r){T.Log(T.GetStackTrace(),"---- Sending custom Command:ConsoleCommand message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({ConsoleCommand:r})])}sendRequestQualityControlOwnership(){T.Log(T.GetStackTrace(),"---- Sending Request to Control Quality ----",6),this.toStreamerMessagesController.SendRequestQualityControl()}handleLatencyTestResult(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.latencyTest",6);const s=new TextDecoder("utf-16").decode(r.slice(1)),a=new um;Object.assign(a,JSON.parse(s)),a.processFields(),a.testStartTimeMs=this.latencyStartTime,a.browserReceiptTimeMs=Date.now(),a.latencyExcludingDecode=~~(a.browserReceiptTimeMs-a.testStartTimeMs),a.testDuration=~~(a.TransmissionTimeMs-a.ReceiptTimeMs),a.networkLatency=~~(a.latencyExcludingDecode-a.testDuration),a.frameDisplayDeltaTimeMs&&a.browserReceiptTimeMs&&(a.endToEndLatency=(a.frameDisplayDeltaTimeMs,a.networkLatency,~~+a.CaptureToSendMs)),this.pixelStreaming._onLatencyTestResult(a)}handleDataChannelLatencyTestResponse(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.dataChannelLatencyResponse",6);const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s);this.pixelStreaming._onDataChannelLatencyTestResponse(a)}handleInitialSettings(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.InitialSettings",6);const s=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(s),f=new am;a.Encoder&&(f.EncoderSettings=a.Encoder),a.WebRTC&&(f.WebRTCSettings=a.WebRTC),a.PixelStreaming&&(f.PixelStreamingSettings=a.PixelStreaming),a.ConfigOptions&&a.ConfigOptions.DefaultToHover!==void 0&&this.config.setFlagEnabled(X.HoveringMouseMode,!!a.ConfigOptions.DefaultToHover),f.ueCompatible(),T.Log(T.GetStackTrace(),s,6),this.pixelStreaming._onInitialSettings(f)}handleVideoEncoderAvgQP(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.VideoEncoderAvgQP",6);const s=Number(new TextDecoder("utf-16").decode(r.slice(1)));this.setVideoEncoderAvgQP(s)}handleVideoInitialized(){this.pixelStreaming._onVideoInitialized(),this.autoPlayVideoOrSetUpPlayOverlay(),this.resizePlayerStyle(),this.videoPlayer.updateVideoStreamSize()}onQualityControlOwnership(r){const s=new Uint8Array(r);T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.QualityControlOwnership",6),this.isQualityController=new Boolean(s[1]).valueOf(),T.Log(T.GetStackTrace(),`Received quality controller message, will control quality: ${this.isQualityController}`),this.pixelStreaming._onQualityControlOwnership(this.isQualityController)}handleVideoStats(r){this.pixelStreaming._onVideoStats(r)}resizePlayerStyle(){this.videoPlayer.resizePlayerStyle()}setPreferredCodec(r){this.preferredCodec=r,this.peerConnectionController&&(this.peerConnectionController.preferredCodec=r,this.peerConnectionController.updateCodecSelection=!1)}setVideoEncoderAvgQP(r){this.videoAvgQp=r,this.pixelStreaming._onVideoEncoderAvgQP(this.videoAvgQp)}setKeyboardInputEnabled(r){var s;(s=this.keyboardController)===null||s===void 0||s.unregisterKeyBoardEvents(),r&&(this.keyboardController=this.inputClassesFactory.registerKeyBoard(this.config))}setMouseInputEnabled(r){var s;if((s=this.mouseController)===null||s===void 0||s.unregisterMouseEvents(),r){const a=this.config.isFlagEnabled(X.HoveringMouseMode)?Ns.HoveringMouse:Ns.LockedMouse;this.mouseController=this.inputClassesFactory.registerMouse(a)}}setTouchInputEnabled(r){var s;(s=this.touchController)===null||s===void 0||s.unregisterTouchEvents(),r&&(this.touchController=this.inputClassesFactory.registerTouch(this.config.isFlagEnabled(X.FakeMouseWithTouches),this.videoElementParentClientRect))}setGamePadInputEnabled(r){var s;(s=this.gamePadController)===null||s===void 0||s.unregisterGamePadEvents(),r&&(this.gamePadController=this.inputClassesFactory.registerGamePad(),this.gamePadController.onGamepadConnected=()=>{this.streamMessageController.toStreamerHandlers.get("GamepadConnected")()},this.gamePadController.onGamepadDisconnected=a=>{this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([a])})}registerDataChannelEventEmitters(r){r.onOpen=(s,a)=>this.pixelStreaming.dispatchEvent(new Af({label:s,event:a})),r.onClose=(s,a)=>this.pixelStreaming.dispatchEvent(new If({label:s,event:a})),r.onError=(s,a)=>this.pixelStreaming.dispatchEvent(new Mf({label:s,event:a}))}registerMessageHandler(r,s,a){s===be.FromStreamer&&a===void 0&&T.Warning(T.GetStackTrace(),`Unable to register handler for ${r} as no handler was passed`),this.streamMessageController.registerMessageHandler(s,r,(f=>a===void 0&&s===be.ToStreamer?this.sendMessageController.sendMessageToStreamer(r,f):a(f)))}}class Fi{constructor(r){this.toStreamerMessagesProvider=r,this.controllers=[]}static deepCopyGamepad(r){return JSON.parse(JSON.stringify({buttons:r.buttons.map((s=>JSON.parse(JSON.stringify({pressed:s.pressed,touched:s.touched,value:s.value})))),axes:r.axes}))}updateStatus(r,s,a){if(r.gamepad){const f=s.getPose(r.gripSpace,a);if(!f)return;let _=0;r.profiles.includes("htc-vive")?_=1:r.profiles.includes("oculus-touch")&&(_=2),this.toStreamerMessagesProvider.toStreamerHandlers.get("XRSystem")([_]);let C=2;switch(r.handedness){case"left":C=0;break;case"right":C=1}const R=f.transform.matrix,b=[];for(let K=0;K<16;K++)b[K]=new Float32Array([R[K]])[0];this.toStreamerMessagesProvider.toStreamerHandlers.get("XRControllerTransform")([b[0],b[4],b[8],b[12],b[1],b[5],b[9],b[13],b[2],b[6],b[10],b[14],b[3],b[7],b[11],b[15],C]),this.controllers[C]===void 0&&(this.controllers[C]={prevState:void 0,currentState:void 0,id:void 0},this.controllers[C].prevState=Fi.deepCopyGamepad(r.gamepad)),this.controllers[C].currentState=Fi.deepCopyGamepad(r.gamepad);const U=this.controllers[C],z=U.currentState,re=U.prevState;for(let K=0;K<z.buttons.length;K++){const ie=z.buttons[K],J=re.buttons[K];if(ie.pressed){let Y=J.pressed?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonPressed")([C,K,Y])}else J.pressed&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonReleased")([C,K,0]);if(ie.touched){let Y=J.touched?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouched")([C,K,Y])}else J.touched&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouchReleased")([C,K,0])}for(let K=0;K<z.axes.length;K++){let ie=z.axes[K];ie!=re.axes[K]&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRAnalog")([C,K,ie])}this.controllers[C].prevState=z}}}class cm{constructor(r){this.xrViewerPose=null,this.videoTexture=null,this.prevVideoWidth=0,this.prevVideoHeight=0,this.leftView=null,this.rightView=null,this.xrSession=null,this.webRtcController=r,this.xrGamepadController=new Fi(this.webRtcController.streamMessageController),this.onSessionEnded=new EventTarget,this.onSessionStarted=new EventTarget,this.onFrame=new EventTarget}xrClicked(){if(this.xrSession)this.xrSession.end();else{if(!navigator.xr)return void T.Error(T.GetStackTrace(),"This browser does not support XR.");navigator.xr.requestSession("immersive-vr",{optionalFeatures:[]}).then((r=>{this.onXrSessionStarted(r)}))}}onXrSessionEnded(){T.Log(T.GetStackTrace(),"XR Session ended"),this.xrSession=null,this.onSessionEnded.dispatchEvent(new Event("xrSessionEnded"))}initGL(){if(this.gl)return;const r=document.createElement("canvas");this.gl=r.getContext("webgl2",{xrCompatible:!0}),this.gl.clearColor(0,0,0,1)}initShaders(){const r=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(r,`
|
|
2891
|
+
attribute vec2 a_position;
|
|
2892
|
+
attribute vec2 a_texCoord;
|
|
2893
|
+
|
|
2894
|
+
// varyings
|
|
2895
|
+
varying vec2 v_texCoord;
|
|
2896
|
+
|
|
2897
|
+
void main() {
|
|
2898
|
+
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
2899
|
+
// pass the texCoord to the fragment shader
|
|
2900
|
+
// The GPU will interpolate this value between points.
|
|
2901
|
+
v_texCoord = a_texCoord;
|
|
2902
|
+
}
|
|
2903
|
+
`),this.gl.compileShader(r);const s=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(s,`
|
|
2904
|
+
precision mediump float;
|
|
2905
|
+
|
|
2906
|
+
// our texture
|
|
2907
|
+
uniform sampler2D u_image;
|
|
2908
|
+
|
|
2909
|
+
// the texCoords passed in from the vertex shader.
|
|
2910
|
+
varying vec2 v_texCoord;
|
|
2911
|
+
|
|
2912
|
+
void main() {
|
|
2913
|
+
gl_FragColor = texture2D(u_image, v_texCoord);
|
|
2914
|
+
}
|
|
2915
|
+
`),this.gl.compileShader(s);const a=this.gl.createProgram();this.gl.attachShader(a,r),this.gl.attachShader(a,s),this.gl.linkProgram(a),this.gl.useProgram(a),this.positionLocation=this.gl.getAttribLocation(a,"a_position"),this.texcoordLocation=this.gl.getAttribLocation(a,"a_texCoord")}updateVideoTexture(){this.videoTexture||(this.videoTexture=this.gl.createTexture(),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR));let r=this.webRtcController.videoPlayer.getVideoElement().videoHeight,s=this.webRtcController.videoPlayer.getVideoElement().videoWidth;this.prevVideoHeight!=r||this.prevVideoWidth!=s?this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,s,r,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()):this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,0,0,s,r,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()),this.prevVideoHeight=r,this.prevVideoWidth=s}initBuffers(){this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.positionLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-1,1,1,1,-1,-1,-1,-1,1,1,1,-1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.positionLocation,2,this.gl.FLOAT,!1,0,0),this.texcoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texcoordBuffer),this.gl.enableVertexAttribArray(this.texcoordLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.texcoordLocation,2,this.gl.FLOAT,!1,0,0)}onXrSessionStarted(r){T.Log(T.GetStackTrace(),"XR Session started"),this.xrSession=r,this.xrSession.addEventListener("end",(()=>{this.onXrSessionEnded()})),this.initGL(),this.initShaders(),this.initBuffers(),r.requestReferenceSpace("local").then((s=>{if(this.xrRefSpace=s,this.xrSession.updateRenderState({baseLayer:new XRWebGLLayer(this.xrSession,this.gl)}),this.xrSession.supportedFrameRates)for(let a of this.xrSession.supportedFrameRates)a==90&&r.updateTargetFrameRate(90);this.xrSession.requestAnimationFrame(this.onXrFrame.bind(this))})),this.onSessionStarted.dispatchEvent(new Event("xrSessionStarted"))}sendXRDataToUE(){if(this.leftView==null||this.rightView==null)return;const r=this.leftView.transform.matrix,s=this.leftView.projectionMatrix,a=this.rightView.transform.matrix,f=this.rightView.projectionMatrix;this.webRtcController.streamMessageController.toStreamerHandlers.get("XREyeViews")([r[0],r[4],r[8],r[12],r[1],r[5],r[9],r[13],r[2],r[6],r[10],r[14],r[3],r[7],r[11],r[15],s[0],s[4],s[8],s[12],s[1],s[5],s[9],s[13],s[2],s[6],s[10],s[14],s[3],s[7],s[11],s[15],a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15],f[0],f[4],f[8],f[12],f[1],f[5],f[9],f[13],f[2],f[6],f[10],f[14],f[3],f[7],f[11],f[15]])}onXrFrame(r,s){if(this.xrViewerPose=s.getViewerPose(this.xrRefSpace),this.xrViewerPose){if(this.updateViews(),this.leftView==null||this.rightView==null)return;this.sendXRDataToUE(),this.updateVideoTexture(),this.render()}this.webRtcController.config.isFlagEnabled(X.XRControllerInput)&&this.xrSession.inputSources.forEach(((a,f,_)=>{this.xrGamepadController.updateStatus(a,s,this.xrRefSpace)}),this),this.xrSession.requestAnimationFrame(((a,f)=>this.onXrFrame(a,f))),this.onFrame.dispatchEvent(new Qf({time:r,frame:s}))}updateViews(){if(this.xrViewerPose)for(const r of this.xrViewerPose.views)r.eye==="left"?this.leftView=r:r.eye==="right"&&(this.rightView=r)}render(){if(!this.gl)return;const r=this.xrSession.renderState.baseLayer;this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,r.framebuffer),this.gl.viewport(0,0,r.framebufferWidth,r.framebufferHeight),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}static isSessionSupported(r){return location.protocol!=="https:"&&T.Info(null,"WebXR requires https, if you want WebXR use https."),navigator.xr?navigator.xr.isSessionSupported(r):new Promise((()=>!1))}}class Sw{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 Tw{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 Ew{constructor(r,s){this.sink=r,this.callback=s,this.records=new Map,this.seq=0}start(r){return!this.isRunning()&&(this.startTime=Date.now(),this.records.clear(),this.interval=setInterval((()=>{Date.now()-this.startTime>=r.duration?this.stop():this.sendRequest(r.requestSize,r.responseSize)}).bind(this),Math.floor(1e3/r.rps)),!0)}stop(){this.interval&&(clearInterval(this.interval),this.interval=void 0,this.callback(this.produceResult()))}produceResult(){const r=new Map(this.records);return{records:r,dataChannelRtt:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.playerReceivedTimestamp-a.playerSentTimestamp)),0)/this.records.size),playerToStreamerTime:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.streamerReceivedTimestamp-a.playerSentTimestamp)),0)/this.records.size),streamerToPlayerTime:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.playerReceivedTimestamp-a.streamerSentTimestamp)),0)/this.records.size),exportLatencyAsCSV:()=>{let s=`Timestamp;RTT;PlayerToStreamer;StreamerToPlayer;
|
|
2916
|
+
`;return r.forEach((a=>{s+=a.playerSentTimestamp+";",s+=a.playerReceivedTimestamp-a.playerSentTimestamp+";",s+=a.streamerReceivedTimestamp-a.playerSentTimestamp+";",s+=a.playerReceivedTimestamp-a.streamerSentTimestamp+";",s+=`
|
|
2917
|
+
`})),s}}}isRunning(){return!!this.interval}receive(r){if(!this.isRunning())return;if(!r)return void T.Error(T.GetStackTrace(),"Undefined response from server");let s=this.records.get(r.Seq);s&&s.update(r)}sendRequest(r,s){let a=this.createRequest(r,s),f=new Tw(a);this.records.set(f.seq,f),this.sink(a)}createRequest(r,s){return{Seq:this.seq++,FillResponseSize:s,Filler:r?"A".repeat(r):""}}}class $w{constructor(r,s){this.allowConsoleCommands=!1,this.config=r,s?.videoElementParent&&(this._videoElementParent=s.videoElementParent),this._eventEmitter=new Jf,this.configureSettings(),this.setWebRtcPlayerController(new dm(this.config,this)),this.onScreenKeyboardHelper=new Sw(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(a,f)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(a,f),this._activateOnScreenKeyboard=a=>this.onScreenKeyboardHelper.showOnScreenKeyboard(a),this._webXrController=new cm(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",(a=>{this._eventEmitter.addEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}))}get videoElementParent(){return this._videoElementParent||(this._videoElementParent=document.createElement("div"),this._videoElementParent.id="videoElementParent"),this._videoElementParent}configureSettings(){this.config._addOnSettingChangedListener(X.IsQualityController,(r=>{r!==!0||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(X.AFKDetection,(r=>{this._webRtcController.setAfkEnabled(r)})),this.config._addOnSettingChangedListener(X.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(X.HoveringMouseMode,(r=>{this.config.setFlagLabel(X.HoveringMouseMode,`Control Scheme: ${r?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(X.MouseInput))})),this.config._addOnSettingChangedListener(X.KeyboardInput,(r=>{this._webRtcController.setKeyboardInputEnabled(r)})),this.config._addOnSettingChangedListener(X.MouseInput,(r=>{this._webRtcController.setMouseInputEnabled(r)})),this.config._addOnSettingChangedListener(X.FakeMouseWithTouches,(r=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(X.TouchInput))})),this.config._addOnSettingChangedListener(X.TouchInput,(r=>{this._webRtcController.setTouchInputEnabled(r)})),this.config._addOnSettingChangedListener(X.GamepadInput,(r=>{this._webRtcController.setGamePadInputEnabled(r)})),this.config._addOnNumericSettingChangedListener(me.MinQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending MinQP --------",7),this._webRtcController.sendEncoderMinQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.MaxQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending encoder settings --------",7),this._webRtcController.sendEncoderMaxQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.WebRTCMinBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMinBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.WebRTCMaxBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMaxBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.WebRTCFPS,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCFps(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnOptionSettingChangedListener(dt.PreferredCodec,(r=>{this._webRtcController&&this._webRtcController.setPreferredCodec(r)})),this.config._registerOnChangeEvents(this._eventEmitter)}_activateOnScreenKeyboard(r){throw new Error("Method not implemented.")}_onInputControlOwnership(r){this._inputController=r}setWebRtcPlayerController(r){this._webRtcController=r,this._webRtcController.setPreferredCodec(this.config.getSettingOption(dt.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Df),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Lf),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new zf),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(X.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(r=!1){if(!this.config.isFlagEnabled("UseMic"))return r?(this.config.setFlagEnabled("UseMic",!0),void this.reconnect()):void T.Warning(T.GetStackTrace(),"Trying to unmute mic, but PixelStreaming was initialized with no microphone track. Call with forceEnable == true to re-connect with a mic track.");this.setMicrophoneMuted(!1)}muteMicrophone(){this.config.isFlagEnabled("UseMic")?this.setMicrophoneMuted(!0):T.Info(T.GetStackTrace(),"Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(r){var s,a,f,_;for(const C of(_=(f=(a=(s=this._webRtcController)===null||s===void 0?void 0:s.peerConnectionController)===null||a===void 0?void 0:a.peerConnection)===null||f===void 0?void 0:f.getTransceivers())!==null&&_!==void 0?_:[])im.canTransceiverSendAudio(C)&&(C.sender.track.enabled=!r)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new $f)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new Ef)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new Of)}_onDisconnect(r,s){this._eventEmitter.dispatchEvent(new Rf({eventString:r,allowClickToReconnect:s}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new xf)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Cf)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new kf)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new Pf),this._videoStartTime=Date.now()}_onLatencyTestResult(r){this._eventEmitter.dispatchEvent(new Wf({latencyTimings:r}))}_onDataChannelLatencyTestResponse(r){this._eventEmitter.dispatchEvent(new Hf({response:r}))}_onVideoStats(r){this._videoStartTime&&this._videoStartTime!==void 0||(this._videoStartTime=Date.now()),r.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new Vf({aggregatedStats:r}))}_onVideoEncoderAvgQP(r){this._eventEmitter.dispatchEvent(new Tf({avgQP:r}))}_onInitialSettings(r){var s;this._eventEmitter.dispatchEvent(new jf({settings:r})),r.PixelStreamingSettings&&(this.allowConsoleCommands=(s=r.PixelStreamingSettings.AllowPixelStreamingCommands)!==null&&s!==void 0&&s,this.allowConsoleCommands===!1&&T.Info(T.GetStackTrace(),"-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const a=this.config.useUrlParams,f=new URLSearchParams(window.location.search);T.Info(T.GetStackTrace(),`using URL parameters ${a}`),r.EncoderSettings&&(this.config.setNumericSetting(me.MinQP,a&&f.has(me.MinQP)?Number.parseFloat(f.get(me.MinQP)):r.EncoderSettings.MinQP),this.config.setNumericSetting(me.MaxQP,a&&f.has(me.MaxQP)?Number.parseFloat(f.get(me.MaxQP)):r.EncoderSettings.MaxQP)),r.WebRTCSettings&&(this.config.setNumericSetting(me.WebRTCMinBitrate,a&&f.has(me.WebRTCMinBitrate)?Number.parseFloat(f.get(me.WebRTCMinBitrate)):r.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(me.WebRTCMaxBitrate,a&&f.has(me.WebRTCMaxBitrate)?Number.parseFloat(f.get(me.WebRTCMaxBitrate)):r.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(me.WebRTCFPS,a&&f.has(me.WebRTCFPS)?Number.parseFloat(f.get(me.WebRTCFPS)):r.WebRTCSettings.FPS))}_onQualityControlOwnership(r){this.config.setFlagEnabled(X.IsQualityController,r)}_onPlayerCount(r){this._eventEmitter.dispatchEvent(new Xf({count:r}))}_setupWebRtcTCPRelayDetection(r){let s=r.data.aggregatedStats.getActiveCandidatePair();if(s!=null){let a=r.data.aggregatedStats.localCandidates.find((f=>f.id==s.localCandidateId),null);a!=null&&a.candidateType=="relay"&&a.relayProtocol=="tcp"&&this._eventEmitter.dispatchEvent(new Yf),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new Ew(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(s=>{this._eventEmitter.dispatchEvent(new Kf({result:s}))})),this.addEventListener("dataChannelLatencyTestResponse",(({data:{response:s}})=>{this._dataChannelLatencyTestController.receive(s)}))),this._dataChannelLatencyTestController.start(r))}requestShowFps(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendShowFps(),!0)}requestIframe(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendIframeRequest(),!0)}emitUIInteraction(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.emitUIInteraction(r),!0)}emitCommand(r){return!(!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in r||(this._webRtcController.emitCommand(r),0))}emitConsoleCommand(r){return!(!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()||(this._webRtcController.emitConsoleCommand(r),0))}addResponseEventListener(r,s){this._webRtcController.responseController.addResponseEventListener(r,s)}removeResponseEventListener(r){this._webRtcController.responseController.removeResponseEventListener(r)}dispatchEvent(r){return this._eventEmitter.dispatchEvent(r)}addEventListener(r,s){this._eventEmitter.addEventListener(r,s)}removeEventListener(r,s){this._eventEmitter.removeEventListener(r,s)}toggleXR(){this.webXrController.xrClicked()}setSignallingUrlBuilder(r){this._webRtcController.signallingUrlBuilder=r}get webSocketController(){return this._webRtcController.webSocketController}get webXrController(){return this._webXrController}registerMessageHandler(r,s,a){s!==be.FromStreamer||a!==void 0?s===be.ToStreamer&&a===void 0?this._webRtcController.streamMessageController.registerMessageHandler(s,r,(f=>this._webRtcController.sendMessageController.sendMessageToStreamer(r,f))):this._webRtcController.streamMessageController.registerMessageHandler(s,r,(f=>a(f))):T.Warning(T.GetStackTrace(),`Unable to register an undefined handler for ${r}`)}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}}class xw{}we.Dz;we.g$;we.Lt;we.Q9;we.qf;we.hV;we.z$;we.J0;var Cw=we.De;we.$C;we.al;we._W;we.Gv;we.m;we.tz;we.Nu;we.zg;we.vp;we.vU;we.wF;we.rv;we.Nh;we.ss;we.qW;we.QL;we.cf;we.eM;we.Yd;we.Tk;we.iM;we.qy;we.ce;we.sK;we.Ok;we.q5;var kw=we.g;we.xl;we.I;we.bx;we.dD;we.Ib;we.Az;we.Iw;we.qY;we.db;we.mR;we.Tn;we.rV;we.gh;we.Mi;we.j;we.YB;we.Yt;we.i5;we.x_;we.Am;we.eR;we.r8;we.u3;we.vd;we.iV;we.jZ;we.SW;we.ZH;we.Ni;we.lh;we.ZP;we.bq;we.$f;we.eu;we.Ax;we.Mc;const hm=({signallingUrl:d,autoConnect:r=!0,width:s,height:a,onConnecting:f,onLoading:_,onConnected:C,onDisconnected:R,onError:b,muted:U=!1})=>{const z=oe.useRef(null),re=oe.useRef(null),K=oe.useRef(!1),[ie,J]=oe.useState(!1),[Y,H]=oe.useState(!1),[se,ve]=oe.useState(null);return oe.useEffect(()=>{if(!(!z.current||!d)){f&&f(),process.env.NODE_ENV==="development"&&console.log("Initializing Epic Pixel Streaming with URL:",d),"mediaDevices"in navigator||Object.defineProperty(navigator,"mediaDevices",{value:{}}),navigator.mediaDevices.getUserMedia||(navigator.mediaDevices.getUserMedia=function(){return Promise.reject(new Error("getUserMedia is not supported"))});try{const de=new Cw({useUrlParams:!1,initialSettings:{ss:d,AutoConnect:r,AutoPlayVideo:!0,StartVideoMuted:U,UseMic:!1,HoveringMouse:!1,FakeMouseWithTouches:!0,TouchInput:!1,MouseInput:!1,KeyboardInput:!1,WaitForStreamer:!0}}),he=new kw(de,{videoElementParent:z.current});he.addEventListener("webRtcConnected",()=>{K.current=!0,J(!0),H(!1),ve(null),C?.()}),he.addEventListener("webRtcDisconnected",()=>{K.current=!1,J(!1),R?.()}),he.addEventListener("streamLoading",()=>{H(!0),_?.()}),he.addEventListener("playStreamError",()=>{ve("Failed to play stream"),H(!1),b?.("Failed to play stream")}),he.addEventListener("playStream",()=>{H(!1),K.current||(K.current=!0,J(!0),C?.())}),he.addEventListener("videoInitialized",()=>{H(!1)}),re.current=he}catch(de){process.env.NODE_ENV==="development"&&console.error("Failed to initialize Pixel Streaming:",de),ve("Failed to initialize streaming: "+de.message),H(!1),b?.(de.message)}return()=>{if(re.current){try{const de=re.current;de._webSocketController&&de._webSocketController.close(),re.current.disconnect()}catch(de){process.env.NODE_ENV==="development"&&console.error("Error during cleanup:",de)}re.current=null}}}},[d,r,f,_,C,R,b]),oe.useEffect(()=>{if(re.current)try{const he=re.current._webRtcController?.videoPlayer;if(!he)return;let pe=!1;if(he.audioElement){const Ke=he.audioElement.srcObject;if(Ke){const fe=Ke.getAudioTracks();fe.length>0&&(fe.forEach(Je=>{Je.enabled=!U}),pe=!0)}}const ce=he.getVideoElement();if(ce&&ce.srcObject&&ce.srcObject instanceof MediaStream){const fe=ce.srcObject.getAudioTracks();fe.length>0&&(fe.forEach(Je=>{Je.enabled=!U}),pe=!0)}!pe&&ce&&(ce.muted=U)}catch(de){process.env.NODE_ENV==="development"&&console.error("Error controlling audio:",de)}},[U]),Jt.jsxs("div",{className:"pixel-streaming-container",style:{width:s||"100%",height:a||"100%",position:"relative",display:"flex",flexDirection:"column",touchAction:"none",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},children:[Jt.jsx("div",{ref:z,className:"player-container",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"hidden",touchAction:"none"}}),Y&&Jt.jsxs("div",{className:"loading-overlay",children:[Jt.jsx("div",{className:"loading-spinner"}),Jt.jsx("div",{className:"loading-text",children:"Connecting to stream..."})]}),!ie&&!Y&&se&&Jt.jsx("div",{className:"connection-overlay",children:Jt.jsx("div",{className:"error-message",children:se})})]})};function Rw({className:d,style:r,autoConnect:s=!0,muted:a=!1,onConnected:f,onDisconnected:_,onError:C}){const{streamingUrl:R,setCloudStreamState:b}=lf();if(!R)return null;const U=()=>{b(Zt.CONNECTING)},z=()=>{b(Zt.LOADING)},re=()=>{b(Zt.CONNECTED),f?.()},K=()=>{b(Zt.DISCONNECTED),_?.()},ie=J=>{b(Zt.ERROR,J),C?.(J)};return Jt.jsx("div",{className:d,style:r,children:Jt.jsx(hm,{signallingUrl:R,autoConnect:s,muted:a,onConnecting:U,onLoading:z,onConnected:re,onDisconnected:K,onError:ie})})}exports.AGENT_TYPES=di;exports.CLOUD_STREAM_STATE=Zt;exports.CONNECTION_STATE=ft;exports.DEFAULT_PCM_OPTIONS=Gp;exports.EpicPixelStreamingPlayer=hm;exports.EventEmitter=sf;exports.RqmiiAgentProvider=af;exports.RqmiiAgentRoom=My;exports.RqmiiCloudAvatarPlayer=Rw;exports.SESSION_STATE=Bs;exports.SOCKET_EVENTS=_r;exports.useRqmiiAgentContext=dn;exports.useRqmiiAvatar=lf;exports.useRqmiiConnection=of;exports.useRqmiiMessages=fy;exports.useRqmiiVAD=Ay;exports.useRqmiiVoice=my;
|
|
2918
|
+
//# sourceMappingURL=RqmiiCloudAvatarPlayer-BI7Uz7DP.cjs.map
|