@rqmii_immersive/agent-react-sdk 1.0.11 → 2.0.0
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/{rqmii-react-agent-sdk.js → RqmiiCloudAvatarPlayer-BnsY8xIR.js} +5758 -5740
- package/dist/RqmiiCloudAvatarPlayer-BnsY8xIR.js.map +1 -0
- package/dist/RqmiiCloudAvatarPlayer-lqCz2xlU.cjs +2938 -0
- package/dist/RqmiiCloudAvatarPlayer-lqCz2xlU.cjs.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +44 -0
- package/dist/index.js +23 -0
- package/dist/index.js.map +1 -0
- package/dist/ui.cjs +2 -0
- package/dist/ui.cjs.map +1 -0
- package/dist/ui.d.ts +10 -0
- package/dist/ui.js +7 -0
- package/dist/ui.js.map +1 -0
- package/package.json +18 -10
- package/dist/rqmii-react-agent-sdk.cjs +0 -2938
- package/dist/rqmii-react-agent-sdk.cjs.map +0 -1
- package/dist/rqmii-react-agent-sdk.js.map +0 -1
- /package/dist/{rqmii-react-agent-sdk.css → agent-react-sdk.css} +0 -0
|
@@ -0,0 +1,2938 @@
|
|
|
1
|
+
"use strict";const me=require("react");var Ii={exports:{}},Ys={};/**
|
|
2
|
+
* @license React
|
|
3
|
+
* react-jsx-runtime.production.js
|
|
4
|
+
*
|
|
5
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
6
|
+
*
|
|
7
|
+
* This source code is licensed under the MIT license found in the
|
|
8
|
+
* LICENSE file in the root directory of this source tree.
|
|
9
|
+
*/var wp;function _g(){if(wp)return Ys;wp=1;var d=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function n(a,f,v){var $=null;if(v!==void 0&&($=""+v),f.key!==void 0&&($=""+f.key),"key"in f){v={};for(var R in f)R!=="key"&&(v[R]=f[R])}else v=f;return f=v.ref,{$$typeof:d,type:a,key:$,ref:f!==void 0?f:null,props:v}}return Ys.Fragment=r,Ys.jsx=n,Ys.jsxs=n,Ys}var Js={};/**
|
|
10
|
+
* @license React
|
|
11
|
+
* react-jsx-runtime.development.js
|
|
12
|
+
*
|
|
13
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
14
|
+
*
|
|
15
|
+
* This source code is licensed under the MIT license found in the
|
|
16
|
+
* LICENSE file in the root directory of this source tree.
|
|
17
|
+
*/var vp;function bg(){return vp||(vp=1,process.env.NODE_ENV!=="production"&&(function(){function d(Z){if(Z==null)return null;if(typeof Z=="function")return Z.$$typeof===at?null:Z.displayName||Z.name||null;if(typeof Z=="string")return Z;switch(Z){case ae:return"Fragment";case Ee:return"Profiler";case Te:return"StrictMode";case pe:return"Suspense";case Pe:return"SuspenseList";case tt:return"Activity"}if(typeof Z=="object")switch(typeof Z.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),Z.$$typeof){case H:return"Portal";case le:return Z.displayName||"Context";case ce:return(Z._context.displayName||"Context")+".Consumer";case he:var Oe=Z.render;return Z=Z.displayName,Z||(Z=Oe.displayName||Oe.name||"",Z=Z!==""?"ForwardRef("+Z+")":"ForwardRef"),Z;case fe:return Oe=Z.displayName||null,Oe!==null?Oe:d(Z.type)||"Memo";case st:Oe=Z._payload,Z=Z._init;try{return d(Z(Oe))}catch{}}return null}function r(Z){return""+Z}function n(Z){try{r(Z);var Oe=!1}catch{Oe=!0}if(Oe){Oe=console;var et=Oe.error,pt=typeof Symbol=="function"&&Symbol.toStringTag&&Z[Symbol.toStringTag]||Z.constructor.name||"Object";return et.call(Oe,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",pt),r(Z)}}function a(Z){if(Z===ae)return"<>";if(typeof Z=="object"&&Z!==null&&Z.$$typeof===st)return"<...>";try{var Oe=d(Z);return Oe?"<"+Oe+">":"<...>"}catch{return"<...>"}}function f(){var Z=Tt.A;return Z===null?null:Z.getOwner()}function v(){return Error("react-stack-top-frame")}function $(Z){if(Re.call(Z,"key")){var Oe=Object.getOwnPropertyDescriptor(Z,"key").get;if(Oe&&Oe.isReactWarning)return!1}return Z.key!==void 0}function R(Z,Oe){function et(){ot||(ot=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",Oe))}et.isReactWarning=!0,Object.defineProperty(Z,"key",{get:et,configurable:!0})}function b(){var Z=d(this.type);return je[Z]||(je[Z]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),Z=this.props.ref,Z!==void 0?Z:null}function N(Z,Oe,et,pt,Ft,$t){var dt=et.ref;return Z={$$typeof:te,type:Z,key:Oe,props:et,_owner:pt},(dt!==void 0?dt:null)!==null?Object.defineProperty(Z,"ref",{enumerable:!1,get:b}):Object.defineProperty(Z,"ref",{enumerable:!1,value:null}),Z._store={},Object.defineProperty(Z._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(Z,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(Z,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:Ft}),Object.defineProperty(Z,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:$t}),Object.freeze&&(Object.freeze(Z.props),Object.freeze(Z)),Z}function B(Z,Oe,et,pt,Ft,$t){var dt=Oe.children;if(dt!==void 0)if(pt)if(Ye(dt)){for(pt=0;pt<dt.length;pt++)re(dt[pt]);Object.freeze&&Object.freeze(dt)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else re(dt);if(Re.call(Oe,"key")){dt=d(Z);var nt=Object.keys(Oe).filter(function(gt){return gt!=="key"});pt=0<nt.length?"{key: someKey, "+nt.join(": ..., ")+": ...}":"{key: someKey}",Ze[dt+pt]||(nt=0<nt.length?"{"+nt.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
|
|
18
|
+
let props = %s;
|
|
19
|
+
<%s {...props} />
|
|
20
|
+
React keys must be passed directly to JSX without using spread:
|
|
21
|
+
let props = %s;
|
|
22
|
+
<%s key={someKey} {...props} />`,pt,dt,nt,dt),Ze[dt+pt]=!0)}if(dt=null,et!==void 0&&(n(et),dt=""+et),$(Oe)&&(n(Oe.key),dt=""+Oe.key),"key"in Oe){et={};for(var Xt in Oe)Xt!=="key"&&(et[Xt]=Oe[Xt])}else et=Oe;return dt&&R(et,typeof Z=="function"?Z.displayName||Z.name||"Unknown":Z),N(Z,dt,et,f(),Ft,$t)}function re(Z){X(Z)?Z._store&&(Z._store.validated=1):typeof Z=="object"&&Z!==null&&Z.$$typeof===st&&(Z._payload.status==="fulfilled"?X(Z._payload.value)&&Z._payload.value._store&&(Z._payload.value._store.validated=1):Z._store&&(Z._store.validated=1))}function X(Z){return typeof Z=="object"&&Z!==null&&Z.$$typeof===te}var Y=me,te=Symbol.for("react.transitional.element"),H=Symbol.for("react.portal"),ae=Symbol.for("react.fragment"),Te=Symbol.for("react.strict_mode"),Ee=Symbol.for("react.profiler"),ce=Symbol.for("react.consumer"),le=Symbol.for("react.context"),he=Symbol.for("react.forward_ref"),pe=Symbol.for("react.suspense"),Pe=Symbol.for("react.suspense_list"),fe=Symbol.for("react.memo"),st=Symbol.for("react.lazy"),tt=Symbol.for("react.activity"),at=Symbol.for("react.client.reference"),Tt=Y.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Re=Object.prototype.hasOwnProperty,Ye=Array.isArray,_t=console.createTask?console.createTask:function(){return null};Y={react_stack_bottom_frame:function(Z){return Z()}};var ot,je={},Le=Y.react_stack_bottom_frame.bind(Y,v)(),Ke=_t(a(v)),Ze={};Js.Fragment=ae,Js.jsx=function(Z,Oe,et){var pt=1e4>Tt.recentlyCreatedOwnerStacks++;return B(Z,Oe,et,!1,pt?Error("react-stack-top-frame"):Le,pt?_t(a(Z)):Ke)},Js.jsxs=function(Z,Oe,et){var pt=1e4>Tt.recentlyCreatedOwnerStacks++;return B(Z,Oe,et,!0,pt?Error("react-stack-top-frame"):Le,pt?_t(a(Z)):Ke)}})()),Js}var _p;function Sg(){return _p||(_p=1,process.env.NODE_ENV==="production"?Ii.exports=_g():Ii.exports=bg()),Ii.exports}var or=Sg();const Hr={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},Wt={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",HEARTBEAT:"heartbeat",HEARTBEAT_ACK:"heartbeat_ack",CLEAR_SESSION_HISTORY:"clear_session_history",TRANSCRIPT:"transcript",PARTIAL_TRANSCRIPT:"partial_transcript",AGENT_RESPONSE_CHUNK:"agent_response_chunk",AGENT_RESPONSE:"agent_response",AGENT_AUDIO_CHUNK:"agent_audio_chunk",AGENT_AUDIO_COMPLETE:"agent_audio_complete",AVATAR_SPEAKING:"avatar_speaking",AVATAR_SPEAKING_DONE:"avatar_speaking_done",INTERRUPTED:"interrupted",ERROR:"error",AUTH_ERROR:"auth_error",RECONNECT_CREDENTIAL:"reconnect_credential",RECONNECT_SUCCESS:"reconnect_success",RECONNECT_FAILED:"reconnect_failed",SESSION_EXPIRED:"session_expired",CREDITS_EXHAUSTED:"credits_exhausted",SESSION_STATE_CHANGED:"session:state_changed",AUDIO_PLAYBACK_COMPLETE:"audio:playback_complete"},It={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",FAILED:"failed",ENDED:"ended"},tr={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},Bn={IDLE:"idle",USER_SPEAKING:"user_speaking",AGENT_THINKING:"agent_thinking",AGENT_SPEAKING:"agent_speaking",TOOL_EXECUTING:"tool_executing",TERMINATING:"terminating",TERMINATED:"terminated"},Tg={enabled:!0,maxAttempts:8,initialDelayMs:500,maxDelayMs:5e3,timeoutMs:8e3},Eg={encoding:"16bitInt",channels:1,sampleRate:16e3},$g=d=>new Promise(r=>setTimeout(r,d)),xg=d=>{if(!d)return null;if(d instanceof Uint8Array)return d;if(d instanceof ArrayBuffer)return new Uint8Array(d);if(d?.buffer instanceof ArrayBuffer){const r=Number.isInteger(d.byteOffset)?d.byteOffset:0,n=Number.isInteger(d.byteLength)?d.byteLength:d.buffer.byteLength-r;return new Uint8Array(d.buffer,r,n)}if(typeof d=="object"&&d.type==="Buffer"&&Array.isArray(d.data))return new Uint8Array(d.data);try{return new Uint8Array(d)}catch{return null}},no=d=>String(d||"").toLowerCase().replaceAll("-","_"),Cg=()=>{const d=new Map;return{addChunk:(f,v)=>{const $=f||`request-${Date.now()}`,b=`${d.get($)||""}${v||""}`;return d.set($,b),{id:$,text:b}},consume:(f,v="")=>{const $=f||`request-${Date.now()}`,R=d.get($)||v||"";return d.delete($),{id:$,text:R}},clear:()=>{d.clear()}}},Pr=Object.create(null);Pr.open="0";Pr.close="1";Pr.ping="2";Pr.pong="3";Pr.message="4";Pr.upgrade="5";Pr.noop="6";const zi=Object.create(null);Object.keys(Pr).forEach(d=>{zi[Pr[d]]=d});const vo={type:"error",data:"parser error"},ef=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",tf=typeof ArrayBuffer=="function",rf=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d&&d.buffer instanceof ArrayBuffer,Mo=({type:d,data:r},n,a)=>ef&&r instanceof Blob?n?a(r):bp(r,a):tf&&(r instanceof ArrayBuffer||rf(r))?n?a(r):bp(new Blob([r]),a):a(Pr[d]+(r||"")),bp=(d,r)=>{const n=new FileReader;return n.onload=function(){const a=n.result.split(",")[1];r("b"+(a||""))},n.readAsDataURL(d)};function Sp(d){return d instanceof Uint8Array?d:d instanceof ArrayBuffer?new Uint8Array(d):new Uint8Array(d.buffer,d.byteOffset,d.byteLength)}let so;function kg(d,r){if(ef&&d.data instanceof Blob)return d.data.arrayBuffer().then(Sp).then(r);if(tf&&(d.data instanceof ArrayBuffer||rf(d.data)))return r(Sp(d.data));Mo(d,!1,n=>{so||(so=new TextEncoder),r(so.encode(n))})}const Tp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oi=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let d=0;d<Tp.length;d++)oi[Tp.charCodeAt(d)]=d;const Rg=d=>{let r=d.length*.75,n=d.length,a,f=0,v,$,R,b;d[d.length-1]==="="&&(r--,d[d.length-2]==="="&&r--);const N=new ArrayBuffer(r),B=new Uint8Array(N);for(a=0;a<n;a+=4)v=oi[d.charCodeAt(a)],$=oi[d.charCodeAt(a+1)],R=oi[d.charCodeAt(a+2)],b=oi[d.charCodeAt(a+3)],B[f++]=v<<2|$>>4,B[f++]=($&15)<<4|R>>2,B[f++]=(R&3)<<6|b&63;return N},Ag=typeof ArrayBuffer=="function",Po=(d,r)=>{if(typeof d!="string")return{type:"message",data:nf(d,r)};const n=d.charAt(0);return n==="b"?{type:"message",data:Ig(d.substring(1),r)}:zi[n]?d.length>1?{type:zi[n],data:d.substring(1)}:{type:zi[n]}:vo},Ig=(d,r)=>{if(Ag){const n=Rg(d);return nf(n,r)}else return{base64:!0,data:d}},nf=(d,r)=>{switch(r){case"blob":return d instanceof Blob?d:new Blob([d]);case"arraybuffer":default:return d instanceof ArrayBuffer?d:d.buffer}},sf="",Mg=(d,r)=>{const n=d.length,a=new Array(n);let f=0;d.forEach((v,$)=>{Mo(v,!1,R=>{a[$]=R,++f===n&&r(a.join(sf))})})},Pg=(d,r)=>{const n=d.split(sf),a=[];for(let f=0;f<n.length;f++){const v=Po(n[f],r);if(a.push(v),v.type==="error")break}return a};function Og(){return new TransformStream({transform(d,r){kg(d,n=>{const a=n.length;let f;if(a<126)f=new Uint8Array(1),new DataView(f.buffer).setUint8(0,a);else if(a<65536){f=new Uint8Array(3);const v=new DataView(f.buffer);v.setUint8(0,126),v.setUint16(1,a)}else{f=new Uint8Array(9);const v=new DataView(f.buffer);v.setUint8(0,127),v.setBigUint64(1,BigInt(a))}d.data&&typeof d.data!="string"&&(f[0]|=128),r.enqueue(f),r.enqueue(n)})}})}let io;function Mi(d){return d.reduce((r,n)=>r+n.length,0)}function Pi(d,r){if(d[0].length===r)return d.shift();const n=new Uint8Array(r);let a=0;for(let f=0;f<r;f++)n[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)),n}function Dg(d,r){io||(io=new TextDecoder);const n=[];let a=0,f=-1,v=!1;return new TransformStream({transform($,R){for(n.push($);;){if(a===0){if(Mi(n)<1)break;const b=Pi(n,1);v=(b[0]&128)===128,f=b[0]&127,f<126?a=3:f===126?a=1:a=2}else if(a===1){if(Mi(n)<2)break;const b=Pi(n,2);f=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(Mi(n)<8)break;const b=Pi(n,8),N=new DataView(b.buffer,b.byteOffset,b.length),B=N.getUint32(0);if(B>Math.pow(2,21)-1){R.enqueue(vo);break}f=B*Math.pow(2,32)+N.getUint32(4),a=3}else{if(Mi(n)<f)break;const b=Pi(n,f);R.enqueue(Po(v?b:io.decode(b),r)),a=0}if(f===0||f>d){R.enqueue(vo);break}}}})}const af=4;function Ot(d){if(d)return zg(d)}function zg(d){for(var r in Ot.prototype)d[r]=Ot.prototype[r];return d}Ot.prototype.on=Ot.prototype.addEventListener=function(d,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+d]=this._callbacks["$"+d]||[]).push(r),this};Ot.prototype.once=function(d,r){function n(){this.off(d,n),r.apply(this,arguments)}return n.fn=r,this.on(d,n),this};Ot.prototype.off=Ot.prototype.removeListener=Ot.prototype.removeAllListeners=Ot.prototype.removeEventListener=function(d,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+d];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+d],this;for(var a,f=0;f<n.length;f++)if(a=n[f],a===r||a.fn===r){n.splice(f,1);break}return n.length===0&&delete this._callbacks["$"+d],this};Ot.prototype.emit=function(d){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),n=this._callbacks["$"+d],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if(n){n=n.slice(0);for(var a=0,f=n.length;a<f;++a)n[a].apply(this,r)}return this};Ot.prototype.emitReserved=Ot.prototype.emit;Ot.prototype.listeners=function(d){return this._callbacks=this._callbacks||{},this._callbacks["$"+d]||[]};Ot.prototype.hasListeners=function(d){return!!this.listeners(d).length};const Gi=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,n)=>n(r,0),lr=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Lg="arraybuffer";function of(d,...r){return r.reduce((n,a)=>(d.hasOwnProperty(a)&&(n[a]=d[a]),n),{})}const Bg=lr.setTimeout,Ng=lr.clearTimeout;function qi(d,r){r.useNativeTimers?(d.setTimeoutFn=Bg.bind(lr),d.clearTimeoutFn=Ng.bind(lr)):(d.setTimeoutFn=lr.setTimeout.bind(lr),d.clearTimeoutFn=lr.clearTimeout.bind(lr))}const Ug=1.33;function Fg(d){return typeof d=="string"?Vg(d):Math.ceil((d.byteLength||d.size)*Ug)}function Vg(d){let r=0,n=0;for(let a=0,f=d.length;a<f;a++)r=d.charCodeAt(a),r<128?n+=1:r<2048?n+=2:r<55296||r>=57344?n+=3:(a++,n+=4);return n}function lf(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Gg(d){let r="";for(let n in d)d.hasOwnProperty(n)&&(r.length&&(r+="&"),r+=encodeURIComponent(n)+"="+encodeURIComponent(d[n]));return r}function qg(d){let r={},n=d.split("&");for(let a=0,f=n.length;a<f;a++){let v=n[a].split("=");r[decodeURIComponent(v[0])]=decodeURIComponent(v[1])}return r}class Wg extends Error{constructor(r,n,a){super(r),this.description=n,this.context=a,this.type="TransportError"}}class Oo extends Ot{constructor(r){super(),this.writable=!1,qi(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,n,a){return super.emitReserved("error",new Wg(r,n,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 n=Po(r,this.socket.binaryType);this.onPacket(n)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,n={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_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 n=Gg(r);return n.length?"?"+n:""}}class Hg extends Oo{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const n=()=>{this.readyState="paused",r()};if(this._polling||!this.writable){let a=0;this._polling&&(a++,this.once("pollComplete",function(){--a||n()})),this.writable||(a++,this.once("drain",function(){--a||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){const n=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)};Pg(r,this.socket.binaryType).forEach(n),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,Mg(r,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=lf()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(r,n)}}let uf=!1;try{uf=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const jg=uf;function Kg(){}class Qg extends Hg{constructor(r){if(super(r),typeof location<"u"){const n=location.protocol==="https:";let a=location.port;a||(a=n?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||a!==r.port}}doWrite(r,n){const a=this.request({method:"POST",data:r});a.on("success",n),a.on("error",(f,v)=>{this.onError("xhr post error",f,v)})}doPoll(){const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(n,a)=>{this.onError("xhr poll error",n,a)}),this.pollXhr=r}}class Mr extends Ot{constructor(r,n,a){super(),this.createRequest=r,qi(this,a),this._opts=a,this._method=a.method||"GET",this._uri=n,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var r;const n=of(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const a=this._xhr=this.createRequest(n);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=Mr.requestsCount++,Mr.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=Kg,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Mr.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()}}Mr.requestsCount=0;Mr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ep);else if(typeof addEventListener=="function"){const d="onpagehide"in lr?"pagehide":"unload";addEventListener(d,Ep,!1)}}function Ep(){for(let d in Mr.requests)Mr.requests.hasOwnProperty(d)&&Mr.requests[d].abort()}const Xg=(function(){const d=df({xdomain:!1});return d&&d.responseType!==null})();class Yg extends Qg{constructor(r){super(r);const n=r&&r.forceBase64;this.supportsBinary=Xg&&!n}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Mr(df,this.uri(),r)}}function df(d){const r=d.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||jg))return new XMLHttpRequest}catch{}if(!r)try{return new lr[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const cf=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Jg extends Oo{get name(){return"websocket"}doOpen(){const r=this.uri(),n=this.opts.protocols,a=cf?{}:of(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,n,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 n=0;n<r.length;n++){const a=r[n],f=n===r.length-1;Mo(a,this.supportsBinary,v=>{try{this.doWrite(a,v)}catch{}f&&Gi(()=>{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",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=lf()),this.supportsBinary||(n.b64=1),this.createUri(r,n)}}const ao=lr.WebSocket||lr.MozWebSocket;class Zg extends Jg{createSocket(r,n,a){return cf?new ao(r,n,a):n?new ao(r,n):new ao(r)}doWrite(r,n){this.ws.send(n)}}class ey extends Oo{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 n=Dg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(n).getReader(),f=Og();f.readable.pipeTo(r.writable),this._writer=f.writable.getWriter();const v=()=>{a.read().then(({done:R,value:b})=>{R||(this.onPacket(b),v())}).catch(R=>{})};v();const $={type:"open"};this.query.sid&&($.data=`{"sid":"${this.query.sid}"}`),this._writer.write($).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let n=0;n<r.length;n++){const a=r[n],f=n===r.length-1;this._writer.write(a).then(()=>{f&&Gi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const ty={websocket:Zg,webtransport:ey,polling:Yg},ry=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ny=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function _o(d){if(d.length>8e3)throw"URI too long";const r=d,n=d.indexOf("["),a=d.indexOf("]");n!=-1&&a!=-1&&(d=d.substring(0,n)+d.substring(n,a).replace(/:/g,";")+d.substring(a,d.length));let f=ry.exec(d||""),v={},$=14;for(;$--;)v[ny[$]]=f[$]||"";return n!=-1&&a!=-1&&(v.source=r,v.host=v.host.substring(1,v.host.length-1).replace(/;/g,":"),v.authority=v.authority.replace("[","").replace("]","").replace(/;/g,":"),v.ipv6uri=!0),v.pathNames=sy(v,v.path),v.queryKey=iy(v,v.query),v}function sy(d,r){const n=/\/{2,9}/g,a=r.replace(n,"/").split("/");return(r.slice(0,1)=="/"||r.length===0)&&a.splice(0,1),r.slice(-1)=="/"&&a.splice(a.length-1,1),a}function iy(d,r){const n={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,v){f&&(n[f]=v)}),n}const bo=typeof addEventListener=="function"&&typeof removeEventListener=="function",Li=[];bo&&addEventListener("offline",()=>{Li.forEach(d=>d())},!1);class sn extends Ot{constructor(r,n){if(super(),this.binaryType=Lg,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(n=r,r=null),r){const a=_o(r);n.hostname=a.host,n.secure=a.protocol==="https"||a.protocol==="wss",n.port=a.port,a.query&&(n.query=a.query)}else n.host&&(n.hostname=_o(n.host).host);qi(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.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},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=qg(this.opts.query)),bo&&(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"})},Li.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const n=Object.assign({},this.opts.query);n.EIO=af,n.transport=r,this.id&&(n.sid=this.id);const a=Object.assign({},this.opts,{query:n,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&&sn.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(r);n.open(),this.setTransport(n)}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",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",sn.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 n=new Error("server error");n.code=r.data,this._onError(n);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 n=1;for(let a=0;a<this.writeBuffer.length;a++){const f=this.writeBuffer[a].data;if(f&&(n+=Fg(f)),a>0&&n>this._maxPayload)return this.writeBuffer.slice(0,a);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(this._pingTimeoutTime=0,Gi(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,n,a){return this._sendPacket("message",r,n,a),this}send(r,n,a){return this._sendPacket("message",r,n,a),this}_sendPacket(r,n,a,f){if(typeof n=="function"&&(f=n,n=void 0),typeof a=="function"&&(f=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;const v={type:r,data:n,options:a};this.emitReserved("packetCreate",v),this.writeBuffer.push(v),f&&this.once("flush",f),this.flush()}close(){const r=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),r()},a=()=>{this.once("upgrade",n),this.once("upgradeError",n)};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(sn.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,n){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(),bo&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=Li.indexOf(this._offlineEventListener);a!==-1&&Li.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,n),this.writeBuffer=[],this._prevBufferLen=0}}}sn.protocol=af;class ay extends sn{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 n=this.createTransport(r),a=!1;sn.priorWebsocketSuccess=!1;const f=()=>{a||(n.send([{type:"ping",data:"probe"}]),n.once("packet",re=>{if(!a)if(re.type==="pong"&&re.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sn.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{a||this.readyState!=="closed"&&(B(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const X=new Error("probe error");X.transport=n.name,this.emitReserved("upgradeError",X)}}))};function v(){a||(a=!0,B(),n.close(),n=null)}const $=re=>{const X=new Error("probe error: "+re);X.transport=n.name,v(),this.emitReserved("upgradeError",X)};function R(){$("transport closed")}function b(){$("socket closed")}function N(re){n&&re.name!==n.name&&v()}const B=()=>{n.removeListener("open",f),n.removeListener("error",$),n.removeListener("close",R),this.off("close",b),this.off("upgrading",N)};n.once("open",f),n.once("error",$),n.once("close",R),this.once("close",b),this.once("upgrading",N),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{a||n.open()},200):n.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const n=[];for(let a=0;a<r.length;a++)~this.transports.indexOf(r[a])&&n.push(r[a]);return n}}let oy=class extends ay{constructor(r,n={}){const a=typeof r=="object"?r:n;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(f=>ty[f]).filter(f=>!!f)),super(r,a)}};function ly(d,r="",n){let a=d;n=n||typeof location<"u"&&location,d==null&&(d=n.protocol+"//"+n.host),typeof d=="string"&&(d.charAt(0)==="/"&&(d.charAt(1)==="/"?d=n.protocol+d:d=n.host+d),/^(https?|wss?):\/\//.test(d)||(typeof n<"u"?d=n.protocol+"//"+d:d="https://"+d),a=_o(d)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";const v=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+v+":"+a.port+r,a.href=a.protocol+"://"+v+(n&&n.port===a.port?"":":"+a.port),a}const uy=typeof ArrayBuffer=="function",dy=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d.buffer instanceof ArrayBuffer,hf=Object.prototype.toString,cy=typeof Blob=="function"||typeof Blob<"u"&&hf.call(Blob)==="[object BlobConstructor]",hy=typeof File=="function"||typeof File<"u"&&hf.call(File)==="[object FileConstructor]";function Do(d){return uy&&(d instanceof ArrayBuffer||dy(d))||cy&&d instanceof Blob||hy&&d instanceof File}function Bi(d,r){if(!d||typeof d!="object")return!1;if(Array.isArray(d)){for(let n=0,a=d.length;n<a;n++)if(Bi(d[n]))return!0;return!1}if(Do(d))return!0;if(d.toJSON&&typeof d.toJSON=="function"&&arguments.length===1)return Bi(d.toJSON(),!0);for(const n in d)if(Object.prototype.hasOwnProperty.call(d,n)&&Bi(d[n]))return!0;return!1}function py(d){const r=[],n=d.data,a=d;return a.data=So(n,r),a.attachments=r.length,{packet:a,buffers:r}}function So(d,r){if(!d)return d;if(Do(d)){const n={_placeholder:!0,num:r.length};return r.push(d),n}else if(Array.isArray(d)){const n=new Array(d.length);for(let a=0;a<d.length;a++)n[a]=So(d[a],r);return n}else if(typeof d=="object"&&!(d instanceof Date)){const n={};for(const a in d)Object.prototype.hasOwnProperty.call(d,a)&&(n[a]=So(d[a],r));return n}return d}function fy(d,r){return d.data=To(d.data,r),delete d.attachments,d}function To(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 n=0;n<d.length;n++)d[n]=To(d[n],r);else if(typeof d=="object")for(const n in d)Object.prototype.hasOwnProperty.call(d,n)&&(d[n]=To(d[n],r));return d}const my=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var it;(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"})(it||(it={}));class gy{constructor(r){this.replacer=r}encode(r){return(r.type===it.EVENT||r.type===it.ACK)&&Bi(r)?this.encodeAsBinary({type:r.type===it.EVENT?it.BINARY_EVENT:it.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let n=""+r.type;return(r.type===it.BINARY_EVENT||r.type===it.BINARY_ACK)&&(n+=r.attachments+"-"),r.nsp&&r.nsp!=="/"&&(n+=r.nsp+","),r.id!=null&&(n+=r.id),r.data!=null&&(n+=JSON.stringify(r.data,this.replacer)),n}encodeAsBinary(r){const n=py(r),a=this.encodeAsString(n.packet),f=n.buffers;return f.unshift(a),f}}class zo extends Ot{constructor(r){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof r=="function"?{reviver:r}:r)}add(r){let n;if(typeof r=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(r);const a=n.type===it.BINARY_EVENT;a||n.type===it.BINARY_ACK?(n.type=a?it.EVENT:it.ACK,this.reconstructor=new yy(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(Do(r)||r.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(r),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+r)}decodeString(r){let n=0;const a={type:Number(r.charAt(0))};if(it[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===it.BINARY_EVENT||a.type===it.BINARY_ACK){const v=n+1;for(;r.charAt(++n)!=="-"&&n!=r.length;);const $=r.substring(v,n);if($!=Number($)||r.charAt(n)!=="-")throw new Error("Illegal attachments");const R=Number($);if(!wy(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(n+1)==="/"){const v=n+1;for(;++n&&!(r.charAt(n)===","||n===r.length););a.nsp=r.substring(v,n)}else a.nsp="/";const f=r.charAt(n+1);if(f!==""&&Number(f)==f){const v=n+1;for(;++n;){const $=r.charAt(n);if($==null||Number($)!=$){--n;break}if(n===r.length)break}a.id=Number(r.substring(v,n+1))}if(r.charAt(++n)){const v=this.tryParse(r.substr(n));if(zo.isPayloadValid(a.type,v))a.data=v;else throw new Error("invalid payload")}return a}tryParse(r){try{return JSON.parse(r,this.opts.reviver)}catch{return!1}}static isPayloadValid(r,n){switch(r){case it.CONNECT:return $p(n);case it.DISCONNECT:return n===void 0;case it.CONNECT_ERROR:return typeof n=="string"||$p(n);case it.EVENT:case it.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&my.indexOf(n[0])===-1);case it.ACK:case it.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class yy{constructor(r){this.packet=r,this.buffers=[],this.reconPack=r}takeBinaryData(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){const n=fy(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const wy=Number.isInteger||function(d){return typeof d=="number"&&isFinite(d)&&Math.floor(d)===d};function $p(d){return Object.prototype.toString.call(d)==="[object Object]"}const vy=Object.freeze(Object.defineProperty({__proto__:null,Decoder:zo,Encoder:gy,get PacketType(){return it}},Symbol.toStringTag,{value:"Module"}));function Sr(d,r,n){return d.on(r,n),function(){d.off(r,n)}}const _y=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class pf extends Ot{constructor(r,n,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=n,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const r=this.io;this.subs=[Sr(r,"open",this.onopen.bind(this)),Sr(r,"packet",this.onpacket.bind(this)),Sr(r,"error",this.onerror.bind(this)),Sr(r,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...n){var a,f,v;if(_y.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(n.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const $={type:it.EVENT,data:n};if($.options={},$.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const B=this.ids++,re=n.pop();this._registerAckCallback(B,re),$.id=B}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&&!(!((v=this.io.engine)===null||v===void 0)&&v._hasPingExpired());return this.flags.volatile&&!R||(b?(this.notifyOutgoingListeners($),this.packet($)):this.sendBuffer.push($)),this.flags={},this}_registerAckCallback(r,n){var a;const f=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(f===void 0){this.acks[r]=n;return}const v=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let R=0;R<this.sendBuffer.length;R++)this.sendBuffer[R].id===r&&this.sendBuffer.splice(R,1);n.call(this,new Error("operation has timed out"))},f),$=(...R)=>{this.io.clearTimeoutFn(v),n.apply(this,R)};$.withError=!0,this.acks[r]=$}emitWithAck(r,...n){return new Promise((a,f)=>{const v=($,R)=>$?f($):a(R);v.withError=!0,n.push(v),this.emit(r,...n)})}_addToQueue(r){let n;typeof r[r.length-1]=="function"&&(n=r.pop());const a={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((f,...v)=>(this._queue[0],f!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(f)):(this._queue.shift(),n&&n(null,...v)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(r=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!r||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.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:it.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,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",r,n),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 it.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 it.EVENT:case it.BINARY_EVENT:this.onevent(r);break;case it.ACK:case it.BINARY_ACK:this.onack(r);break;case it.DISCONNECT:this.ondisconnect();break;case it.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 n=r.data||[];r.id!=null&&n.push(this.ack(r.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const a of n)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 n=this;let a=!1;return function(...f){a||(a=!0,n.packet({type:it.ACK,id:r,data:f}))}}onack(r){const n=this.acks[r.id];typeof n=="function"&&(delete this.acks[r.id],n.withError&&r.data.unshift(null),n.apply(this,r.data))}onconnect(r,n){this.id=r,this.recovered=n&&this._pid===n,this._pid=n,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:it.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 n=this._anyListeners;for(let a=0;a<n.length;a++)if(r===n[a])return n.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 n=this._anyOutgoingListeners;for(let a=0;a<n.length;a++)if(r===n[a])return n.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const a of n)a.apply(this,r.data)}}}function as(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}as.prototype.duration=function(){var d=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),n=Math.floor(r*this.jitter*d);d=(Math.floor(r*10)&1)==0?d-n:d+n}return Math.min(d,this.max)|0};as.prototype.reset=function(){this.attempts=0};as.prototype.setMin=function(d){this.ms=d};as.prototype.setMax=function(d){this.max=d};as.prototype.setJitter=function(d){this.jitter=d};class Eo extends Ot{constructor(r,n){var a;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(n=r,r=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,qi(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((a=n.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new as({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=r;const f=n.parser||vy;this.encoder=new f.Encoder,this.decoder=new f.Decoder,this._autoConnect=n.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 n;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(n=this.backoff)===null||n===void 0||n.setMin(r),this)}randomizationFactor(r){var n;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(n=this.backoff)===null||n===void 0||n.setJitter(r),this)}reconnectionDelayMax(r){var n;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(n=this.backoff)===null||n===void 0||n.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 oy(this.uri,this.opts);const n=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const f=Sr(n,"open",function(){a.onopen(),r&&r()}),v=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},$=Sr(n,"error",v);if(this._timeout!==!1){const R=this._timeout,b=this.setTimeoutFn(()=>{f(),v(new Error("timeout")),n.close()},R);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(f),this.subs.push($),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(Sr(r,"ping",this.onping.bind(this)),Sr(r,"data",this.ondata.bind(this)),Sr(r,"error",this.onerror.bind(this)),Sr(r,"close",this.onclose.bind(this)),Sr(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(n){this.onclose("parse error",n)}}ondecoded(r){Gi(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){this.emitReserved("error",r)}socket(r,n){let a=this.nsps[r];return a?this._autoConnect&&!a.active&&a.connect():(a=new pf(this,r,n),this.nsps[r]=a),a}_destroy(r){const n=Object.keys(this.nsps);for(const a of n)if(this.nsps[a].active)return;this._close()}_packet(r){const n=this.encoder.encode(r);for(let a=0;a<n.length;a++)this.engine.write(n[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,n){var a;this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,n),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 n=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()}))},n);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 Zs={};function di(d,r){typeof d=="object"&&(r=d,d=void 0),r=r||{};const n=ly(d,r.path||"/socket.io"),a=n.source,f=n.id,v=n.path,$=Zs[f]&&v in Zs[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||$;let b;return R?b=new Eo(a,r):(Zs[f]||(Zs[f]=new Eo(a,r)),b=Zs[f]),n.query&&!r.query&&(r.query=n.queryKey),b.socket(n.path,r)}Object.assign(di,{Manager:Eo,Socket:pf,io:di,connect:di});function by({wsUrl:d,log:r}){let n=null;function a({authPayload:R,queryToken:b,expectReconnectSuccess:N,timeoutMs:B}){return v(),new Promise((re,X)=>{const Y=di(d,{transports:["websocket","polling"],timeout:2e4,reconnection:!1,auth:R,query:b?{token:b}:void 0});n=Y,Y.once("connect",()=>{r("SocketManager: socket connected"),re(Y)}),Y.once("connect_error",te=>{r("SocketManager: socket connect_error",te),X(te)})})}function f({authPayload:R,queryToken:b}){const N=di(d,{transports:["websocket","polling"],timeout:2e4,reconnection:!1,auth:R,query:b?{token:b}:void 0});return n=N,N}function v(){if(n){try{n.removeAllListeners(),n.disconnect()}catch{}n=null}}function $(){return n}return{connectSocket:a,connectSocketRaw:f,cleanupSocket:v,getSocket:$}}const Sy=d=>{if(window.audioCtx=d,d.state!=="suspended")return;const r=document.body,n=["touchstart","touchend","mousedown","keydown"];n.forEach(v=>r.addEventListener(v,a,!1));function a(){d.resume().then(f)}function f(){n.forEach(v=>r.removeEventListener(v,a))}};function Ut(d){this.init(d)}Ut.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()};Ut.prototype.getMaxValue=function(){var d={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ut.prototype.getTypedArray=function(){var d={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ut.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),Sy(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Ut.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};Ut.prototype.isTypedArray=function(d){return d.byteLength&&d.buffer&&d.buffer.constructor==ArrayBuffer};Ut.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()}};Ut.prototype.getFormatedValue=function(r){var r=new this.typedArray(r.buffer),n=new Float32Array(r.length),a;for(a=0;a<r.length;a++)n[a]=r[a]/this.maxValue;return n};Ut.prototype.volume=function(d){this.gainNode.gain.value=d};Ut.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Ut.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};Ut.prototype.setRequestStop=function(){this.flag_request_stop=!0};Ut.prototype.setOnEnd=function(d){this.onEnd=d};Ut.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};Ut.prototype.ensuredSetTimeout=(function(){let d;return function(r,n){d=performance.now();const a=f=>{f-d>=n?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Ut.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Ut.prototype.flush=function(){if(this.samples.length){var d=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,n=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,f,v,$,R;for(f=0;f<this.option.channels;f++)for(a=n.getChannelData(f),v=f,R=50,$=0;$<r;$++)a[$]=this.samples[v],$<50&&(a[$]=a[$]*$/50),$>=r-51&&(a[$]=a[$]*R--/50),v+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,d.buffer=n,d.connect(this.gainNode),d.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=d,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=n.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 Ty(d,r){const n=new Ut(d),a=n.destroy.bind(n);let f=!1;return n.destroy=()=>{if(!f){f=!0;try{a()}catch{}}},n.setOnEnd(()=>{f||r?.()}),n._isDestroyed=()=>f,n}function Ey({enableAudio:d,pcmOptions:r,log:n,onPlaybackComplete:a}){const v=typeof n=="function"?n:()=>{};let $=null,R=null;function b(){if(!d||$)return $;const Te={...Eg,...r||{}};return $=Ty(Te,()=>{a?.()}),$}function N(){if($){try{$.interrupt?.(),$.destroy?.()}catch{}$=null}}function B(Te){const Ee=b();if(Ee)try{Ee.feed(Te)}catch(ce){v("feedAudio: player.feed() failed",ce),a?.()}}function re(){if($)try{$.setRequestStop()}catch(Te){v("requestStop: setRequestStop() failed",Te),a?.()}}function X(){N()}async function Y(){const Te=b();if(Te)try{Te.audioCtx?.state==="suspended"&&await Te.audioCtx.resume()}catch(Ee){v("resumeAudioPlayback: audioCtx.resume() failed",Ee)}}function te(Te){R=Te||null}function H(){return R}function ae(){return $?$._isDestroyed?.()??!0:!0}return{ensurePcmPlayer:b,destroyPcmPlayer:N,feedAudio:B,requestStop:re,interruptPlayback:X,resumeAudioPlayback:Y,attachAudioElement:te,getAudioElement:H,isDestroyed:ae}}function $y({log:d,reconnectOptions:r}){let n=null,a=!1,f=!1;const v={...Tg,...r||{}};return{storeCredential:Y=>{!Y?.sessionId||!Y?.reconnectToken||!Y?.role||(n={sessionId:Y.sessionId,reconnectToken:Y.reconnectToken,role:Y.role})},getCredential:()=>n,clearCredential:()=>{n=null},tryReconnect:async({connectSocket:Y,onAttempt:te,onSuccess:H,onFailure:ae,isAborted:Te})=>{if(!a){if(!n){ae("Reconnect token unavailable. Please initialize a new session.");return}a=!0,f=!1;for(let Ee=1;Ee<=v.maxAttempts;Ee+=1){if(Te?.()||f){a=!1;return}te?.(Ee);try{await Y({authPayload:{reconnectToken:n.reconnectToken,sessionId:n.sessionId,role:n.role},expectReconnectSuccess:!0}),a=!1,H?.();return}catch(ce){d?.(`reconnect attempt ${Ee} failed`,ce);const le=Math.min(v.maxDelayMs,v.initialDelayMs*2**(Ee-1));await $g(le)}}a=!1,ae("Reconnect window expired. Please initialize a new session.")}},abort:()=>{f=!0},isReconnecting:()=>a,updateOptions:Y=>{Object.assign(v,Y)}}}const xy=()=>{try{const d=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof d=="string"&&d.trim()?d.trim():void 0}catch{return}},xp=async d=>{if(!d?.ok){let r=`HTTP ${d.status}`;try{const a=await d.json();r=a?.detail||a?.message||r}catch{}const n=new Error(r);throw n.status=d.status,n}return d.json()};function Cy({restUrl:d,log:r=()=>{}}){const n=()=>{if(!d)throw new Error("Missing restUrl in RqmiiAgentProvider")};return{initializeSession:async({apiKey:v,publicChatId:$,agentId:R,language:b="en"}={})=>{n();const N={...v?{api_key:v}:{},...$?{public_chat_id:$}:{},...R?{agent_id:R}:{},language:b};r("initializeSession — POST /sessions/init",N);const B=await fetch(`${d}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)}),re=await xp(B);if(!re?.session_id||!re?.session_token)throw new Error("Invalid initialize session response");return re},joinDesktopSession:async({uniqueId:v})=>{n(),r("joinDesktopSession — POST /sessions/join",{uniqueId:v});const $=await fetch(`${d}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:v})}),R=await xp($);if(!R?.session_id||!R?.session_token)throw new Error("Invalid join session response");return R}}}const $o={connectionState:It.IDLE,isConnected:!1,isSessionReady:!1,error:null,reconnectAttempt:0,isAudioPlaying:!1,isAvatarSpeaking:!1,lastHeartbeatAck:null,sessionState:Bn.IDLE,cloudStream:{state:tr.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[],creditExhausted:!1,creditError:null};function Vt(d,r){d(n=>({...n,connectionState:r,isConnected:r===It.CONNECTED}))}function Vr(d,r){d(n=>({...n,error:r?String(r):null}))}function oo(d,r,n=null){d(a=>({...a,cloudStream:{state:r,error:n?String(n):null}}))}function ky(d,r){d(n=>({...n,sessionState:r}))}function Ry(d,r){d(n=>({...n,session:{...n.session,...r}}))}function Ay(d,r){d(n=>({...n,messages:[...n.messages,r]}))}function Oi(d,r){d(n=>({...n,isAudioPlaying:r}))}function Cp(d,r){d(n=>({...n,isAvatarSpeaking:r}))}function lo(d,r,n=null){d(a=>({...a,creditExhausted:r,creditError:n?String(n):null}))}function Iy(d){d($o)}function My(d){return{isSessionTerminated:d===Bn.TERMINATED,isSessionTerminating:d===Bn.TERMINATING,isAgentThinking:d===Bn.AGENT_THINKING,isAgentSpeaking:d===Bn.AGENT_SPEAKING,isToolExecuting:d===Bn.TOOL_EXECUTING}}function Py({intervalMs:d,log:r}){let n=null;function a($){n!==null&&(clearInterval(n),n=null),r?.("[HeartbeatManager] starting heartbeat, intervalMs:",d),n=setInterval(()=>{$&&$.emit(Wt.HEARTBEAT,{})},d)}function f(){n!==null&&(r?.("[HeartbeatManager] stopping heartbeat"),clearInterval(n),n=null)}function v(){return n!==null}return{start:a,stop:f,isRunning:v}}const ff=me.createContext(null);function mf({children:d,wsUrl:r,restUrl:n,reconnectOptions:a,enableAudio:f=!0,pcmOptions:v,debug:$=!1,heartbeatIntervalSeconds:R=15,onSessionExpired:b,onSessionTerminated:N,onError:B,onDisconnect:re,onReconnectSuccess:X,onReconnectFailed:Y}){const[te,H]=me.useState($o),ae=me.useRef(!1),Te=me.useRef(Cg()),Ee=me.useRef(null),ce=me.useRef($o.session.agentType),le=me.useRef(!1),he=me.useRef({onSessionExpired:b,onSessionTerminated:N,onError:B,onDisconnect:re,onReconnectSuccess:X,onReconnectFailed:Y});me.useEffect(()=>{he.current={onSessionExpired:b,onSessionTerminated:N,onError:B,onDisconnect:re,onReconnectSuccess:X,onReconnectFailed:Y}},[b,N,B,re,X,Y]),me.useEffect(()=>{ce.current=te.session.agentType},[te.session.agentType]),me.useEffect(()=>{Ee.current=te.session.sessionId},[te.session.sessionId]);const pe=me.useCallback((...Se)=>{$&&console.log("[RqmiiSDK]",...Se)},[$]),Pe=me.useRef(null),fe=me.useRef(null),st=me.useRef(null),tt=me.useRef(null),at=me.useRef(null);Pe.current||(Pe.current=by({wsUrl:r,log:pe})),fe.current||(fe.current=Ey({enableAudio:f,pcmOptions:v,log:pe,onPlaybackComplete:()=>{Oi(H,!1);const Se=Pe.current.getSocket();Se?.connected&&Se.emit(Wt.AUDIO_PLAYBACK_COMPLETE,{session_id:Ee.current})}})),st.current||(st.current=$y({log:pe,reconnectOptions:a})),tt.current||(tt.current=Cy({restUrl:n,log:pe})),at.current||(at.current=Py({intervalMs:R*1e3,log:pe}));const Tt=me.useCallback(Se=>{const Fe=Wt,ft=at.current,mt=fe.current;Se.on(Fe.DISCONNECT,ue=>{pe("socket disconnected",ue),H(De=>({...De,isConnected:!1,isSessionReady:!1})),ft.stop(),he.current.onDisconnect?.(ue),!ae.current&&(a?.enabled!==!1?Vt(H,It.RECONNECTING):(Vt(H,It.FAILED),Vr(H,"Connection lost")))}),Se.on(Fe.SESSION_READY,ue=>{H(De=>({...De,isSessionReady:!0,error:null,session:{...De.session,agentType:no(ue?.agentType||De.session.agentType)}})),ft.start(Se)}),Se.on(Fe.SESSION_JOINED,()=>{H(ue=>({...ue,isSessionReady:!0,error:null})),ft.start(Se)}),Se.on(Fe.SESSION_TERMINATED,()=>{Vt(H,It.ENDED),H(ue=>({...ue,isSessionReady:!1})),ft.stop(),he.current.onSessionTerminated?.()}),Se.on(Fe.TRANSCRIPT,ue=>{H(De=>{const Dt={...De,transcript:ue||null};return ue?.is_final&&ue?.text?.trim()&&(Dt.messages=[...De.messages,{id:`transcript-${Date.now()}`,role:"user",text:ue.text.trim(),timestamp:new Date().toISOString()}]),Dt})}),Se.on(Fe.PARTIAL_TRANSCRIPT,ue=>H(De=>({...De,partialTranscript:ue||null}))),Se.on(Fe.AGENT_RESPONSE_CHUNK,ue=>{const{id:De,text:Dt}=Te.current.addChunk(ue?.requestId,ue?.text);H(Ht=>({...Ht,messages:[...Ht.messages.filter(Dr=>Dr.id!==De),{id:De,role:"assistant",text:Dt,streaming:!0,timestamp:new Date().toISOString()}]}))}),Se.on(Fe.AGENT_RESPONSE,ue=>{const{id:De,text:Dt}=Te.current.consume(ue?.requestId,ue?.text);H(Ht=>({...Ht,messages:[...Ht.messages.filter(Dr=>Dr.id!==De),{id:De,role:"assistant",text:Dt,streaming:!1,timestamp:new Date().toISOString()}]}))}),Se.on(Fe.AVATAR_SPEAKING,()=>Cp(H,!0)),Se.on(Fe.AVATAR_SPEAKING_DONE,()=>Cp(H,!1)),Se.on(Fe.AGENT_AUDIO_CHUNK,ue=>{if(!f||le.current)return;const De=no(ce.current);if(De===Hr.CLOUD_AVATAR||De===Hr.DESKTOP_AVATAR)return;const Dt=xg(ue?.audio);Dt&&(mt.feedAudio(Dt),Oi(H,!0))}),Se.on(Fe.AGENT_AUDIO_COMPLETE,()=>{if(!f)return;const ue=no(ce.current);ue===Hr.CLOUD_AVATAR||ue===Hr.DESKTOP_AVATAR||mt.requestStop()}),Se.on(Fe.INTERRUPTED,()=>{const ue=!mt.isDestroyed();le.current=!1,mt.interruptPlayback(),Oi(H,!1),ue&&Se.connected&&Se.emit(Fe.AUDIO_PLAYBACK_COMPLETE,{session_id:Ee.current})}),Se.on(Fe.HEARTBEAT_ACK,ue=>{pe("heartbeat ack",ue?.timestamp),H(De=>({...De,lastHeartbeatAck:ue?.timestamp??null}))});const rt=ue=>{st.current.storeCredential(ue),ue?.sessionId&&ue?.role&&Ry(H,{sessionId:ue.sessionId,role:ue.role})};Se.on(Fe.RECONNECT_CREDENTIAL,ue=>{pe("received reconnect credential"),rt(ue)}),Se.on(Fe.RECONNECT_SUCCESS,ue=>{rt(ue),H(De=>({...De,reconnectAttempt:0,isSessionReady:!0})),Vt(H,It.CONNECTED),he.current.onReconnectSuccess?.(ue)}),Se.on(Fe.RECONNECT_FAILED,ue=>{pe("reconnect failed",ue),Vt(H,It.FAILED),Vr(H,ue?.reason||"Reconnect failed"),he.current.onReconnectFailed?.(ue)}),Se.on(Fe.AUTH_ERROR,ue=>{Vt(H,It.FAILED),Vr(H,ue?.message||"Authentication error")}),Se.on(Fe.ERROR,ue=>{const De=ue?.code;if(De==="TTS_ERROR"){pe("non-fatal TTS error",ue);return}if(De==="INSUFFICIENT_CREDITS"){lo(H,!0,ue?.message||"Insufficient credits to process this request."),he.current.onError?.(ue);return}Vr(H,ue?.message||ue?.detail||"Server error"),he.current.onError?.(ue)}),Se.on(Fe.SESSION_EXPIRED,ue=>{pe("session expired",ue),Vt(H,It.ENDED),H(De=>({...De,isSessionReady:!1})),ft.stop(),he.current.onSessionExpired?.(ue)}),Se.on(Fe.CREDITS_EXHAUSTED,()=>{pe("credits exhausted — disconnecting"),H(ue=>({...ue,creditExhausted:!0,creditError:"This project has run out of credits.",isSessionReady:!1})),Vt(H,It.ENDED),ft.stop(),ae.current=!0;try{Se.disconnect()}catch{}}),Se.on(Fe.SESSION_STATE_CHANGED,ue=>{ue?.state&&(pe("session state changed",ue?.previous_state,"→",ue.state),ky(H,ue.state))})},[f,pe]),Re=me.useCallback(({authPayload:Se,queryToken:Fe,expectReconnectSuccess:ft=!1})=>new Promise((mt,rt)=>{Pe.current.cleanupSocket();const ue=Pe.current.connectSocketRaw({authPayload:Se,queryToken:Fe});if(Tt(ue),!ft)ue.once("connect",()=>{Vt(H,It.CONNECTED),Vr(H,null),mt(ue)}),ue.once("connect_error",De=>{Vt(H,It.FAILED),Vr(H,De?.message||"Connection error"),rt(De)});else{const De=a?.timeoutMs??8e3,Dt=()=>{ue.off(Wt.RECONNECT_FAILED,Ht),mt()},Ht=Dr=>{ue.off(Wt.RECONNECT_SUCCESS,Dt),rt(new Error(Dr?.reason||"Reconnect failed"))};ue.once(Wt.RECONNECT_SUCCESS,Dt),ue.once(Wt.RECONNECT_FAILED,Ht),setTimeout(()=>{ue.off(Wt.RECONNECT_SUCCESS,Dt),ue.off(Wt.RECONNECT_FAILED,Ht),rt(new Error("Reconnect timed out"))},De)}}),[Tt,a]);me.useEffect(()=>{te.connectionState===It.RECONNECTING&&a?.enabled!==!1&&st.current.tryReconnect({connectSocket:Re,onAttempt:Se=>H(Fe=>({...Fe,reconnectAttempt:Se})),onSuccess:()=>{},onFailure:Se=>{Vt(H,It.FAILED),Vr(H,Se),he.current.onReconnectFailed?.({reason:Se})},isAborted:()=>ae.current})},[te.connectionState,Re]);const Ye=me.useCallback(({keepManualDisconnect:Se=!1}={})=>{ae.current=!0,st.current.clearCredential(),le.current=!1,Te.current.clear(),at.current.stop(),fe.current.destroyPcmPlayer(),Pe.current.cleanupSocket(),Se||(ae.current=!1),Iy(H)},[]),_t=me.useCallback(async({apiKey:Se,publicChatId:Fe,agentId:ft,language:mt="en"}={})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!Se&&!Fe&&!ft)throw new Error("Provide one of apiKey, publicChatId, or agentId");Ye(),Vt(H,It.INITIALIZING),Vr(H,null);let rt;try{rt=await tt.current.initializeSession({apiKey:Se,publicChatId:Fe,agentId:ft,language:mt})}catch(De){throw De.status===402&&(lo(H,!0,De.message||"Insufficient credits"),Vt(H,It.FAILED)),De}H(De=>({...De,session:{...De.session,sessionId:rt.session_id,agentType:rt.streaming_url?Hr.CLOUD_AVATAR:De.session.agentType,streamingUrl:rt.streaming_url||null,uniqueId:rt.unique_id||null,role:null}})),Vt(H,It.CONNECTING),oo(H,rt.streaming_url?tr.CONNECTING:tr.IDLE);const ue=xy();return await Re({authPayload:ue?{token:rt.session_token,timezone:ue}:{token:rt.session_token},queryToken:rt.session_token}),rt},[Re,Ye,r]),ot=me.useCallback(async({uniqueId:Se})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!Se)throw new Error("uniqueId is required");Ye(),Vt(H,It.INITIALIZING),Vr(H,null);let Fe;try{Fe=await tt.current.joinDesktopSession({uniqueId:Se})}catch(ft){throw ft.status===402&&(lo(H,!0,ft.message||"Insufficient credits"),Vt(H,It.FAILED)),ft}return H(ft=>({...ft,session:{...ft.session,sessionId:Fe.session_id,uniqueId:Se,role:"user",agentType:Hr.DESKTOP_AVATAR}})),Vt(H,It.CONNECTING),oo(H,tr.IDLE),await Re({authPayload:{token:Fe.session_token},queryToken:Fe.session_token}),Fe},[Re,Ye,r]),je=me.useCallback(()=>Ye({keepManualDisconnect:!0}),[Ye]),Le=me.useCallback(async()=>(je(),{success:!0}),[je]),Ke=me.useCallback((Se,Fe={})=>{const ft=Pe.current.getSocket();return!ft||!te.isConnected?!1:(ft.emit(Se,Fe),!0)},[te.isConnected]),Ze=me.useCallback(Se=>!Se||!String(Se).trim()?!1:(Ay(H,{id:`user-${Date.now()}`,role:"user",text:String(Se),timestamp:new Date().toISOString()}),Ke(Wt.USER_MESSAGE,{message:String(Se)})),[Ke]),Z=me.useCallback(Se=>Ke(Wt.AUDIO_CHUNK,{audio:Se}),[Ke]),Oe=me.useCallback(()=>Ke(Wt.AUDIO_END,{}),[Ke]),et=me.useCallback(()=>(le.current=!0,fe.current.interruptPlayback(),Oi(H,!1),Ke(Wt.INTERRUPT,{})),[Ke]),pt=me.useCallback(()=>Ke(Wt.CLEAR_SESSION_HISTORY,{}),[Ke]),Ft=me.useCallback(Se=>Se?Ke(Wt.CHANGE_SESSION_LANGUAGE,{language:Se}):!1,[Ke]),$t=me.useCallback(()=>{Te.current.clear(),H(Se=>({...Se,messages:[]}))},[]),dt=me.useCallback(()=>fe.current.resumeAudioPlayback(),[]),nt=me.useCallback(Se=>fe.current.attachAudioElement(Se),[]),Xt=me.useCallback((Se,Fe=null)=>oo(H,Se,Fe),[]);me.useEffect(()=>()=>{ae.current=!0,at.current.stop(),Pe.current.cleanupSocket(),fe.current.destroyPcmPlayer()},[]);const gt=me.useMemo(()=>({...te,...My(te.sessionState),initializeSession:_t,joinDesktopSession:ot,disconnect:je,terminateSession:Le,emit:Ke,sendTextMessage:Ze,sendAudioChunk:Z,endAudioStream:Oe,interrupt:et,clearSessionHistory:pt,changeSessionLanguage:Ft,clearMessages:$t,resumeAudioPlayback:dt,attachAudioElement:nt,setCloudStreamState:Xt,audioElement:fe.current?.getAudioElement()??null,socket:Pe.current?.getSocket()??null}),[te,_t,ot,je,Le,Ke,Ze,Z,Oe,et,pt,Ft,$t,dt,nt,Xt]);return or.jsx(ff.Provider,{value:gt,children:d})}const Or=()=>{const d=me.useContext(ff);if(!d)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return d},Oy=["Cannot read properties of null (reading 'state')","MicVAD has null stream"],kp=d=>d?Oy.some(r=>String(d).includes(r)):!1;function gf(){typeof window>"u"||window.__rqmiiAudioErrorSuppressorsInstalled||(window.__rqmiiAudioErrorSuppressorsInstalled=!0,window.addEventListener("error",d=>{if(kp(d?.message))return d.preventDefault(),!0}),window.addEventListener("unhandledrejection",d=>{const r=d?.reason?.message||String(d?.reason||"");kp(r)&&d.preventDefault()}))}gf();const Dy={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,sampleRate:16e3},zy=["audio/webm;codecs=opus","audio/webm","audio/mp4"],Ly=()=>typeof window>"u"||!window.MediaRecorder?.isTypeSupported?"":zy.find(d=>window.MediaRecorder.isTypeSupported(d))||"";function By(d={}){const{onAudioChunk:r,onAudioEnd:n,onError:a,holdDelayMs:f=220,timesliceMs:v=100,interruptOnHoldStart:$=!0,audioConstraints:R=Dy}=d,{sendAudioChunk:b,endAudioStream:N,interrupt:B}=Or(),re=me.useRef(null),X=me.useRef(null),Y=me.useRef(null),te=me.useRef(!0),H=me.useRef(!1),[ae,Te]=me.useState(!1),[Ee,ce]=me.useState(!1),[le,he]=me.useState(null),pe=me.useCallback(async Re=>{if(!Re||Re.size<=0)return;const Ye=await Re.arrayBuffer();if(r){r(Ye);return}b(Ye)},[r,b]),Pe=me.useCallback(()=>{X.current&&(X.current.getTracks().forEach(Re=>Re.stop()),X.current=null)},[]),fe=me.useCallback(({discard:Re=!1}={})=>{const Ye=re.current;if(!Ye)return H.current=!0,!1;if(te.current=!Re,re.current=null,Ye.state==="inactive")return Re||(n?n():N()),Pe(),ce(!1),!0;try{Ye.requestData()}catch{}Ye.onstop=()=>{te.current&&(n?n():N()),Pe(),ce(!1)};try{Ye.stop()}catch(_t){Pe(),ce(!1),a?.(_t)}return!0},[Pe,N,n,a]),st=me.useCallback(async()=>{if(re.current)return!0;if(H.current=!1,typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||typeof window>"u"||typeof window.MediaRecorder>"u"){const Re=new Error("MediaRecorder or microphone APIs are unavailable in this browser");return he(Re.message),a?.(Re),!1}try{const Re=await navigator.mediaDevices.getUserMedia({audio:R});X.current=Re;const Ye=Ly(),_t=Ye?{mimeType:Ye}:void 0,ot=new window.MediaRecorder(Re,_t);return ot.ondataavailable=je=>{pe(je.data)},ot.onerror=je=>{const Le=je?.error||new Error("Microphone recording failed");he(Le?.message||"recording_failed"),a?.(Le)},re.current=ot,ce(!0),he(null),ot.start(v),H.current&&(H.current=!1,fe()),!0}catch(Re){return Pe(),ce(!1),he("permission_denied"),a?.(Re),!1}},[R,Pe,pe,a,v]),tt=me.useCallback(()=>{Y.current&&(clearTimeout(Y.current),Y.current=null),Te(!0),Y.current=setTimeout(()=>{$&&B(),st()},f)},[f,B,$,st]),at=me.useCallback(()=>{Te(!1),Y.current&&(clearTimeout(Y.current),Y.current=null),fe()},[fe]);me.useEffect(()=>()=>{Y.current&&(clearTimeout(Y.current),Y.current=null);const Re=re.current;if(Re&&(re.current=null,Re.state!=="inactive"))try{Re.stop()}catch{}X.current&&(X.current.getTracks().forEach(Ye=>Ye.stop()),X.current=null)},[]);const Tt=me.useMemo(()=>({onPointerDown:Re=>{Re.preventDefault(),tt()},onPointerUp:Re=>{Re.preventDefault(),at()},onPointerCancel:Re=>{Re.preventDefault(),at()},onPointerLeave:Re=>{Re.preventDefault(),at()}}),[tt,at]);return{isPressing:ae,isRecording:Ee,micError:le,startRecording:st,stopRecording:fe,startPress:tt,stopPress:at,eventHandlers:Tt}}var uo={},co={},ei={},Rp;function yf(){if(Rp)return ei;Rp=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 n="/";return r&&(n=r.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),ei.baseAssetPath=n,ei}var ti={},Ap;function Lo(){if(Ap)return ti;Ap=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.defaultModelFetcher=void 0;const d=r=>fetch(r).then(n=>n.arrayBuffer());return ti.defaultModelFetcher=d,ti}var Gr={},ri={},Ip;function ci(){if(Ip)return ri;Ip=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.log=void 0;const d=r=>n=>{console.log(`VAD | ${r} >`,n)};return ri.log={error:d("error"),debug:d("debug"),warn:d("warn")},ri}var ni={},Mp;function Wi(){if(Mp)return ni;Mp=1,Object.defineProperty(ni,"__esModule",{value:!0}),ni.Message=void 0;var d;return(function(r){r.AudioFrame="AUDIO_FRAME",r.SpeechStart="SPEECH_START",r.VADMisfire="VAD_MISFIRE",r.SpeechEnd="SPEECH_END",r.SpeechStop="SPEECH_STOP",r.SpeechRealStart="SPEECH_REAL_START",r.FrameProcessed="FRAME_PROCESSED"})(d||(ni.Message=d={})),ni}var Pp;function Bo(){if(Pp)return Gr;Pp=1,Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.FrameProcessor=Gr.validateOptions=Gr.defaultFrameProcessorOptions=void 0;const d=ci(),r=Wi();Gr.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function n($){($.positiveSpeechThreshold<0||$.positiveSpeechThreshold>1)&&d.log.error("positiveSpeechThreshold should be a number between 0 and 1"),($.negativeSpeechThreshold<0||$.negativeSpeechThreshold>$.positiveSpeechThreshold)&&d.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),$.preSpeechPadMs<0&&d.log.error("preSpeechPadMs should be positive"),$.redemptionMs<0&&d.log.error("redemptionMs should be positive"),$.minSpeechMs<0&&d.log.error("minSpeechMs should be positive")}Gr.validateOptions=n;const a=$=>{const R=$.reduce((N,B)=>(N.push(N.at(-1)+B.length),N),[0]),b=new Float32Array(R.at(-1));return $.forEach((N,B)=>{const re=R[B];b.set(N,re)}),b};function f($,R){const b=Math.floor($.redemptionMs/R),N=Math.floor($.preSpeechPadMs/R),B=Math.floor($.minSpeechMs/R);return{redemptionFrames:b,preSpeechPadFrames:N,minSpeechFrames:B}}class v{constructor(R,b,N,B){this.modelProcessFunc=R,this.modelResetFunc=b,this.options=N,this.msPerFrame=B,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=te=>{this.options={...this.options,...te};const{redemptionFrames:H,preSpeechPadFrames:ae,minSpeechFrames:Te}=f(this.options,this.msPerFrame);this.redemptionFrames=H,this.preSpeechPadFrames=ae,this.minSpeechFrames=Te},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=te=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(te):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=te=>{const H=this.audioBuffer;this.audioBuffer=[];const ae=this.speaking;if(this.reset(),ae)if(H.reduce((Ee,ce)=>ce.isSpeech?Ee+1:Ee,0)>=this.minSpeechFrames){const Ee=a(H.map(ce=>ce.frame));te({msg:r.Message.SpeechEnd,audio:Ee})}else te({msg:r.Message.VADMisfire});return{}},this.process=async(te,H)=>{if(!this.active)return;const ae=await this.modelProcessFunc(te),Te=ae.isSpeech>=this.options.positiveSpeechThreshold;if(H({probs:ae,msg:r.Message.FrameProcessed,frame:te}),this.audioBuffer.push({frame:te,isSpeech:Te}),Te&&(this.speechFrameCount++,this.redemptionCounter=0),Te&&!this.speaking&&(this.speaking=!0,H({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,H({msg:r.Message.SpeechRealStart})),ae.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const Ee=this.audioBuffer;if(this.audioBuffer=[],Ee.reduce((le,he)=>he.isSpeech?le+1:le,0)>=this.minSpeechFrames){const le=a(Ee.map(he=>he.frame));H({msg:r.Message.SpeechEnd,audio:le})}else H({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:X,minSpeechFrames:Y}=f(this.options,this.msPerFrame);this.redemptionFrames=re,this.preSpeechPadFrames=X,this.minSpeechFrames=Y,this.reset()}}return Gr.FrameProcessor=v,Gr}var qr={};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 ho={exports:{}};/*!
|
|
23
|
+
* ONNX Runtime Web v1.24.3
|
|
24
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
25
|
+
* Licensed under the MIT License.
|
|
26
|
+
*/var Op;function Ny(){return Op||(Op=1,(function(d,r){var n=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,$=Object.prototype.hasOwnProperty,R=(e=>typeof ur<"u"?ur:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof ur<"u"?ur:t)[s]}):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),N=(e,t)=>{for(var s in t)a(e,s,{get:t[s],enumerable:!0})},B=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of v(t))!$.call(e,o)&&o!==s&&a(e,o,{get:()=>t[o],enumerable:!(i=f(t,o))||i.enumerable});return e},re=e=>B(a({},"__esModule",{value:!0}),e),X,Y,te,H,ae,Te=b(()=>{X=new Map,Y=[],te=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=X.get(e);if(i===void 0)X.set(e,{backend:t,priority:s});else{if(i.priority>s)return;if(i.priority===s&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){let o=Y.indexOf(e);o!==-1&&Y.splice(o,1);for(let l=0;l<Y.length;l++)if(X.get(Y[l]).priority<=s){Y.splice(l,0,e);return}Y.push(e)}return}throw new TypeError("not a valid backend")},H=async e=>{let t=X.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return s||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ae=async e=>{let t=e.executionProviders||[],s=t.map(h=>typeof h=="string"?h:h.name),i=s.length===0?Y:s,o,l=[],u=new Set;for(let h of i){let p=await H(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)s.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)})]}}),Ee=b(()=>{Te()}),ce,le=b(()=>{ce="1.24.3"}),he,pe,Pe=b(()=>{le(),he="warning",pe={wasm:{},webgl:{},webgpu:{},versions:{common:ce},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);he=e}},get logLevel(){return he}},Object.defineProperty(pe,"logLevel",{enumerable:!0})}),fe,st=b(()=>{Pe(),fe=pe}),tt,at,Tt=b(()=>{tt=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let i=s.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 g=l*o,m=0,w=g,_=g*2,S=-1;u==="RGBA"?(m=0,w=g,_=g*2,S=g*3):u==="RGB"?(m=0,w=g,_=g*2):u==="RBG"&&(m=0,_=g,w=g*2);for(let C=0;C<l;C++)for(let M=0;M<o;M++){let k=(e.data[m++]-p[0])*h[0],x=(e.data[w++]-p[1])*h[1],O=(e.data[_++]-p[2])*h[2],I=S===-1?255:(e.data[S++]-p[3])*h[3];i.fillStyle="rgba("+k+","+x+","+O+","+I+")",i.fillRect(M,C,1,1)}if("toDataURL"in s)return s.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},at=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(s!=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,g;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?g=[0,0,0,0]:typeof h.bias=="number"?g=[h.bias,h.bias,h.bias,h.bias]:(g=[h.bias[0],h.bias[1],h.bias[2],0],h.bias[3]!==void 0&&(g[3]=h.bias[3]));let m=l*o;if(t!==void 0&&(t.format!==void 0&&u===4&&t.format!=="RGBA"||u===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let w=4,_=0,S=1,C=2,M=3,k=0,x=m,O=m*2,I=-1;c==="RGBA"?(k=0,x=m,O=m*2,I=m*3):c==="RGB"?(k=0,x=m,O=m*2):c==="RBG"&&(k=0,O=m,x=m*2),i=s.createImageData(o,l);for(let z=0;z<l*o;_+=w,S+=w,C+=w,M+=w,z++)i.data[_]=(e.data[k++]-g[0])*p[0],i.data[S]=(e.data[x++]-g[1])*p[1],i.data[C]=(e.data[O++]-g[2])*p[2],i.data[M]=I===-1?255:(e.data[I++]-g[3])*p[3]}else throw new Error("Can not access image data");return i}}),Re,Ye,_t,ot,je,Le,Ke=b(()=>{Xt(),Re=(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:s,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=s*i,g=h==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),m=4,w=0,_=1,S=2,C=3,M=0,k=p,x=p*2,O=-1;c==="RGB"&&(m=3,w=0,_=1,S=2,C=-1),h==="RGBA"?O=p*3:h==="RBG"?(M=0,x=p,k=p*2):h==="BGR"&&(x=0,k=p,M=p*2);for(let I=0;I<p;I++,w+=m,S+=m,_+=m,C+=m)g[M++]=(e[w]+u[0])/l[0],g[k++]=(e[_]+u[1])/l[1],g[x++]=(e[S]+u[2])/l[2],O!==-1&&C!==-1&&(g[O++]=(e[C]+u[3])/l[3]);return h==="RGBA"?new nt("float32",g,[1,4,s,i]):new nt("float32",g,[1,3,s,i])},Ye=async(e,t)=>{let s=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=g=>typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||g instanceof OffscreenCanvas?g.getContext("2d"):null;if(s){let g=h();g.width=e.width,g.height=e.height;let m=p(g);if(m!=null){let w=e.height,_=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(w=t.resizedHeight,_=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=w,c.width=_}else c.tensorFormat="RGBA",c.height=w,c.width=_;m.drawImage(e,0,0),u=m.getImageData(0,0,_,w).data}else throw new Error("Can not access image data")}else if(i){let g,m;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(g=t.resizedHeight,m=t.resizedWidth):(g=e.height,m=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=g,c.width=m,t!==void 0){let w=h();w.width=m,w.height=g;let _=p(w);if(_!=null)_.putImageData(e,0,0),u=_.getImageData(0,0,m,g).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 g=h();g.width=e.width,g.height=e.height;let m=p(g);if(m!=null){let w=e.height,_=e.width;return m.drawImage(e,0,0,_,w),u=m.getImageData(0,0,_,w).data,c.height=w,c.width=_,Re(u,c)}else throw new Error("Can not access image data")}else{if(l)return new Promise((g,m)=>{let w=h(),_=p(w);if(!e||!_)return m();let S=new Image;S.crossOrigin="Anonymous",S.src=e,S.onload=()=>{w.width=S.width,w.height=S.height,_.drawImage(S,0,0,w.width,w.height);let C=_.getImageData(0,0,w.width,w.height);c.height=w.height,c.width=w.width,g(Re(C.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return Re(u,c);throw new Error("Input data provided is not supported - aborted tensor creation")},_t=(e,t)=>{let{width:s,height:i,download:o,dispose:l}=t,u=[1,i,s,4];return new nt({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:l})},ot=(e,t)=>{let{dataType:s,dims:i,download:o,dispose:l}=t;return new nt({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:i,download:o,dispose:l})},je=(e,t)=>{let{dataType:s,dims:i,download:o,dispose:l}=t;return new nt({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:i,download:o,dispose:l})},Le=(e,t,s)=>new nt({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),Ze,Z,Oe,et,pt=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]]),Z=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Oe=!1,et=()=>{if(!Oe){Oe=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=globalThis.Float16Array,i=typeof s<"u"&&s.from;e&&(Ze.set("int64",BigInt64Array),Z.set(BigInt64Array,"int64")),t&&(Ze.set("uint64",BigUint64Array),Z.set(BigUint64Array,"uint64")),i?(Ze.set("float16",s),Z.set(s,"float16")):Ze.set("float16",Uint16Array)}}}),Ft,$t,dt=b(()=>{Xt(),Ft=e=>{let t=1;for(let s=0;s<e.length;s++){let i=e[s];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${s}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${i}`);t*=i}return t},$t=(e,t)=>{switch(e.location){case"cpu":return new nt(e.type,e.data,t);case"cpu-pinned":return new nt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new nt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new nt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new nt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),nt,Xt=b(()=>{Tt(),Ke(),pt(),dt(),nt=class{constructor(e,t,s){et();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=s,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=Z.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=Ft(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 Ye(e,t)}static fromTexture(e,t){return _t(e,t)}static fromGpuBuffer(e,t){return ot(e,t)}static fromMLTensor(e,t){return je(e,t)}static fromPinnedBuffer(e,t,s){return Le(e,t,s)}toDataURL(e){return tt(this,e)}toImageData(e){return at(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 $t(this,e)}}}),gt,Se=b(()=>{Xt(),gt=nt}),Fe,ft,mt,rt,ue,De,Dt=b(()=>{Pe(),Fe=(e,t)=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeStamp(`${e}::ORT::${t}`)},ft=(e,t)=>{let s=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let o=0;o<s.length;o++){if(i&&!s[o].includes("TRACE_FUNC")){let l=`FUNC_${e}::${s[o].trim().split(" ")[1]}`;t&&(l+=`::${t}`),Fe("CPU",l);return}s[o].includes("TRACE_FUNC")&&(i=!0)}},mt=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||ft("BEGIN",e)},rt=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||ft("END",e)},ue=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.time(`ORT::${e}`)},De=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeEnd(`ORT::${e}`)}}),Ht,Dr=b(()=>{Te(),Se(),Dt(),Ht=class wf{constructor(t){this.handler=t}async run(t,s,i){mt(),ue("InferenceSession.run");let o={},l={};if(typeof t!="object"||t===null||t instanceof gt||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 s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof gt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");u=!1;for(let p of s){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,g=Object.getOwnPropertyNames(s);for(let m of this.outputNames)if(g.indexOf(m)!==-1){let w=s[m];(w===null||w instanceof gt)&&(p=!0,u=!1,o[m]=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=s}}else if(typeof s<"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 g=c[p];g instanceof gt?h[p]=g:h[p]=new gt(g.type,g.data,g.dims)}return De("InferenceSession.run"),rt(),h}async release(){return this.handler.dispose()}static async create(t,s,i,o){mt(),ue("InferenceSession.create");let l,u={};if(typeof t=="string"){if(l=t,typeof s=="object"&&s!==null)u=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(l=t,typeof s=="object"&&s!==null)u=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let g=t,m=0,w=t.byteLength;if(typeof s=="object"&&s!==null)u=s;else if(typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteOffset' must be an integer.");if(m<0||m>=g.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${g.byteLength}).`);if(w=t.byteLength-m,typeof i=="number"){if(w=i,!Number.isSafeInteger(w))throw new RangeError("'byteLength' must be an integer.");if(w<=0||m+w>g.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${g.byteLength-m}].`);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 s<"u")throw new TypeError("'options' must be an object.");l=new Uint8Array(g,m,w)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,h]=await ae(u),p=await c.createInferenceSessionHandler(l,h);return De("InferenceSession.create"),rt(),new wf(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}}}),an,Hi=b(()=>{Dr(),an=Ht}),ji=b(()=>{}),Ki=b(()=>{}),Qi=b(()=>{}),Xi=b(()=>{}),ls={};N(ls,{InferenceSession:()=>an,TRACE:()=>Fe,TRACE_EVENT_BEGIN:()=>ue,TRACE_EVENT_END:()=>De,TRACE_FUNC_BEGIN:()=>mt,TRACE_FUNC_END:()=>rt,Tensor:()=>gt,env:()=>fe,registerBackend:()=>te});var Mt=b(()=>{Ee(),st(),Hi(),Se(),ji(),Ki(),Dt(),Qi(),Xi()}),on=b(()=>{}),us={};N(us,{default:()=>ds});var ln,un,ds,Yi=b(()=>{np(),Yt(),fn(),ln="ort-wasm-proxy-worker",un=globalThis.self?.name===ln,un&&(self.onmessage=e=>{let{type:t,in:s}=e.data;try{switch(t){case"init-wasm":yn(s.wasm).then(()=>{qa(s).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}=s;Wa(o,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=s,o=ki(i);postMessage({type:t,out:o});break}case"create":{let{model:i,options:o}=s;ja(i,o).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":Ka(s),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:o,inputs:l,outputIndices:u,options:c}=s;Xa(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},Ja([...l,...h]))},h=>{postMessage({type:t,err:h})});break}case"end-profiling":Ya(s),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),ds=un?null:e=>new Worker(e??yt,{type:"classic",name:ln})}),cs,hs,yt,dn,zr,ps,fs,cn,ms,hn,gs,pn,ys,fn=b(()=>{on(),cs=typeof location>"u"?void 0:location.origin,hs=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,yt=hs(),dn=()=>{if(yt&&!yt.startsWith("blob:"))return yt.substring(0,yt.lastIndexOf("/")+1)},zr=(e,t)=>{try{let s=t??yt;return(s?new URL(e,s):new URL(e)).origin===cs}catch{return!1}},ps=(e,t)=>{let s=t??yt;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},fs=(e,t)=>`${t??"./"}${e}`,cn=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},ms=async e=>(await import(e)).default,hn=(Yi(),re(us)).default,gs=async()=>{if(!yt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(zr(yt))return[void 0,hn()];let e=await cn(yt);return[e,hn(e)]},pn=void 0,ys=async(e,t,s,i)=>{let o=pn&&!(e||t);if(o)if(yt)o=zr(yt)||i&&!s;else if(i&&!s)o=!0;else throw new Error("cannot determine the script source URL.");if(o)return[void 0,pn];{let l="ort-wasm-simd-threaded.jsep.mjs",u=e??ps(l,t),c=s&&u&&!zr(u,t),h=c?await cn(u):u??fs(l,t);return[c?h:void 0,await ms(h)]}}}),mn,Lr,dr,gn,ws,vs,_s,yn,Ne,Yt=b(()=>{fn(),Lr=!1,dr=!1,gn=!1,ws=()=>{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}},vs=()=>{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}},_s=()=>{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}},yn=async e=>{if(Lr)return Promise.resolve();if(dr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(gn)throw new Error("previous call to 'initializeWebAssembly()' failed.");dr=!0;let t=e.initTimeout,s=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!_s())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!vs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=ws();s>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", 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=s=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,g=e.wasmBinary,[m,w]=await ys(c,l,s>1,!!g||!!p),_=!1,S=[];if(t>0&&S.push(new Promise(C=>{setTimeout(()=>{_=!0,C()},t)})),S.push(new Promise((C,M)=>{let k={numThreads:s};if(g)k.wasmBinary=g,k.locateFile=x=>x;else if(p||l)k.locateFile=x=>p??l+x;else if(c&&c.indexOf("blob:")!==0)k.locateFile=x=>new URL(x,c).href;else if(m){let x=dn();x&&(k.locateFile=O=>x+O)}w(k).then(x=>{dr=!1,Lr=!0,mn=x,C(),m&&URL.revokeObjectURL(m)},x=>{dr=!1,gn=!0,M(x)})})),await Promise.race(S),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ne=()=>{if(Lr&&mn)return mn;throw new Error("WebAssembly is not initialized yet.")}}),Et,Br,Ie,wn=b(()=>{Yt(),Et=(e,t)=>{let s=Ne(),i=s.lengthBytesUTF8(e)+1,o=s._malloc(i);return s.stringToUTF8(e,o,i),t.push(o),o},Br=(e,t,s,i)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([o,l])=>{let u=t?t+o:o;if(typeof l=="object")Br(l,u+".",s,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}`)})},Ie=e=>{let t=Ne(),s=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(s)}}}),bs,Ji=b(()=>{Yt(),wn(),bs=e=>{let t=Ne(),s=0,i=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let l=0;return e?.tag!==void 0&&(l=Et(e.tag,i)),s=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,l),s===0&&Ie("Can't create run options."),e?.extra!==void 0&&Br(e.extra,"",new WeakSet,(u,c)=>{let h=Et(u,i),p=Et(c,i);t._OrtAddRunConfigEntry(s,h,p)!==0&&Ie(`Can't set a run config entry: ${u} - ${c}.`)}),[s,i]}catch(l){throw s!==0&&t._OrtReleaseRunOptions(s),i.forEach(u=>t._free(u)),l}}}),Ss,Ts,Es,cr,$s,xs,Zi=b(()=>{Yt(),wn(),Ss=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}`)}},Ts=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Es=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(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},cr=(e,t,s,i)=>{let o=Et(t,i),l=Et(s,i);Ne()._OrtAddSessionConfigEntry(e,o,l)!==0&&Ie(`Can't set a session config entry: ${t} - ${s}.`)},$s=async(e,t,s)=>{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",typeof o!="string"){let m=o?.deviceType;m&&cr(e,"deviceType",m,s)}break;case"webgpu":if(l="JS",typeof o!="string"){let m=o;if(m?.preferredLayout){if(m.preferredLayout!=="NCHW"&&m.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${m.preferredLayout}`);cr(e,"preferredLayout",m.preferredLayout,s)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let c=Et(l,s),h=u.length,p=0,g=0;if(h>0){p=Ne()._malloc(h*Ne().PTR_SIZE),s.push(p),g=Ne()._malloc(h*Ne().PTR_SIZE),s.push(g);for(let m=0;m<h;m++)Ne().setValue(p+m*Ne().PTR_SIZE,u[m][0],"*"),Ne().setValue(g+m*Ne().PTR_SIZE,u[m][1],"*")}await Ne()._OrtAppendExecutionProvider(e,c,p,g,h)!==0&&Ie(`Can't append execution provider: ${l}.`)}},xs=async e=>{let t=Ne(),s=0,i=[],o=e||{};Es(o);try{let l=Ss(o.graphOptimizationLevel??"all"),u=Ts(o.executionMode??"sequential"),c=typeof o.logId=="string"?Et(o.logId,i):0,h=o.logSeverityLevel??2;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log severity level is not valid: ${h}`);let p=o.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let g=typeof o.optimizedModelFilePath=="string"?Et(o.optimizedModelFilePath,i):0;if(s=t._OrtCreateSessionOptions(l,!!o.enableCpuMemArena,!!o.enableMemPattern,u,!!o.enableProfiling,0,c,h,p,g),s===0&&Ie("Can't create session options."),o.executionProviders&&await $s(s,o,i),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);cr(s,"enableGraphCapture",o.enableGraphCapture.toString(),i)}if(o.freeDimensionOverrides)for(let[m,w]of Object.entries(o.freeDimensionOverrides)){if(typeof m!="string")throw new Error(`free dimension override name must be a string: ${m}`);if(typeof w!="number"||!Number.isInteger(w)||w<0)throw new Error(`free dimension override value must be a non-negative integer: ${w}`);let _=Et(m,i);t._OrtAddFreeDimensionOverride(s,_,w)!==0&&Ie(`Can't set a free dimension override: ${m} - ${w}.`)}return o.extra!==void 0&&Br(o.extra,"",new WeakSet,(m,w)=>{cr(s,m,w,i)}),[s,i]}catch(l){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&Ie("Can't release session options."),i.forEach(u=>t._free(u)),l}}}),Jt,Zt,er,vn,_n,bn,Sn,Un,ze=b(()=>{Jt=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Zt=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}`)}},er=(e,t)=>{let s=[-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 s>0?Math.ceil(i*s):void 0},vn=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}`)}},_n=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}`)}},bn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Sn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Un=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}`)}}}),Tn,Cs=b(()=>{on(),Tn=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 s=t.headers.get("Content-Length"),i=s?parseInt(s,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)}}),ks,Fn,Vn,Er,Gn,qn,Je,rr=b(()=>{ze(),ks=["V","I","W","E","F"],Fn=(e,t)=>{console.log(`[${ks[e]},${new Date().toISOString()}]${t}`)},Gn=(e,t)=>{Vn=e,Er=t},qn=(e,t)=>{let s=_n(e),i=_n(Vn);s>=i&&Fn(s,typeof t=="function"?t():t)},Je=(...e)=>{Er&&qn(...e)}}),Wn,$r,j,Qr,Hn,Rs,hr,Me=b(()=>{Wn=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},$r=class{static calcShape(e,t,s=!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(s){if(i<2||o<2)return;let c=Wn.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=s?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 g=Math.max(h,p);if(h&&p)u[l-c]=Math.max(h,p);else{if(g>1)return;u[l-c]=0}}return u}static isValidBroadcast(e,t){let s=e.length,i=t.length;if(s>i)return!1;for(let o=1;o<=s;o++)if(e[s-o]!==1&&e[s-o]!==t[i-o])return!1;return!0}},j=class Ni{static size(t){return Ni.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,s=4){let i=t.length;if(i===0)return[];let o=new Array(i),l=i-1;for(;l>=0;){if(t[l]%s===0){o[l]=t[l]/s;break}if(s%t[l]!==0)throw new Error("cannot convert shape");o[l]=1,s/=t[l],l--}for(l--;l>=0;l--)o[l]=t[l];return o}static sizeFromDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Ni.getSizeFromDimensionRange(t,s,t.length)}static sizeToDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Ni.getSizeFromDimensionRange(t,0,s)}static getSizeFromDimensionRange(t,s,i){let o=1;for(let l=s;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 s=t.length;if(s===0)return[];if(s===1)return[1];let i=new Array(s);i[s-1]=1,i[s-2]=t[s-1];for(let o=s-3;o>=0;--o)i[o]=i[o+1]*t[o+1];return i}static normalizeAxis(t,s){if(t<-s&&t>=s)throw new Error("unsupported axis for this operation.");return t<0?t+s:t}static normalizeAxes(t,s){return t.map(i=>this.normalizeAxis(i,s??t.length))}static sortBasedOnPerm(t,s){return s?s.map(i=>t[i]):t.slice().reverse()}static padShape(t,s){let i=t.length;return t.map((o,l)=>o+s[l]+s[l+i])}static areEqual(t,s){return t.length!==s.length?!1:t.every((i,o)=>i===s[o])}},Qr=class li{static adjustPoolAttributes(t,s,i,o,l,u){if(!t&&i.length!==s.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<s.length-2;c++)c>=i.length?i.push(s[c+2]):i[c]=s[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,s,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(s.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)],s[h],i[h],o[h],l,h,h+t.length-2,c)}}static computePoolOutputShape(t,s,i,o,l,u,c){if(s.length<=0)throw new Error("input shape must be of size greater than 0");let h=[s[0],s[1]];return li.computeShapeHelper(t,s,h,i,o,l,u,c),h}static computeConvOutputShape(t,s,i,o,l,u,c){if(t.length<=0||s.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let h=[t[0],s[0]];return li.computeShapeHelper(!1,t,h,i,o,l,u,c),h}static computeShapeHelper(t,s,i,o,l,u,c,h){if(t)for(let p=0;p<s.length-2;p++)i.push(1);else for(let p=0;p<s.length-2;p++)i.push(li.adjustPadAndReturnShape(s[p+2],o[p],l[p],u[p],c,p,p+s.length-2,h))}static adjustPadAndReturnShape(t,s,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)/s+1);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let g=((t+s-1)/s-1)*s+o-t;return l[u]=Math.floor(h==="SAME_LOWER"?(g+1)/2:g/2),l[c]=g-l[u],Math.floor((t+g-o)/s+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((t+l[u]+l[c]-p)/s+1)}},Hn=class{static getShapeOfGemmResult(e,t,s,i,o){if(e.length!==2||s.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=s[0],h=1):(c=s[1],h=0),s[h]!==u)throw new Error("dimension mismatch");if(l<=0||c<=0||u<=0)throw new Error("invalid shape specified");if(o&&!$r.isValidBroadcast(o,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,u]}},Rs=-34028234663852886e22,hr=34028234663852886e22}),xr,Xr=b(()=>{ze(),xr=(e,t)=>new(vn(t))(e)}),Nr,Yr,En,$n,pr,Cr,jn,Kn,Qn,As,Is,pi=b(()=>{ze(),rr(),Nr=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Yr=(e,t)=>{if(t==="int32")return e;let s=Nr.get(t);if(!s)throw new Error(`WebNN backend does not support data type: ${t}`);let i=s/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(vn(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'`)}},En=(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 s=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,s);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}`)}},$n=1,pr=()=>$n++,Cr=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),jn=(e,t)=>{let s=Nr.get(e);if(!s)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,o)=>i*o)*s/8):0},Kn=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:s,tensor:i,dataType:o,shape:l,fallbackDataType:u}=e;this.sessionId=t,this.mlContext=s,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 jn(this.dataType,this.tensorShape)}destroy(){Je("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),s=En(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(s);return}else return s.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,s){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===s.length&&this.tensorShape.every((i,o)=>i===s[o])}setIsDataConverted(e){this.isDataConverted=e}},Qn=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,s,i){let o=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),u;if(!l?.input.dataTypes.includes(t)){if(u=Cr.get(t),!u||l?.input.dataTypes.includes(u))throw new Error(`WebNN backend does not support data type: ${t}`);Je("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${u}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(o,t,s))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==jn(t,s))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,s,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=Yr(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 Je("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?En(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()}},As=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=pr();return this.tensorTrackersById.set(e,new Qn(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,s,i,o){Je("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${s}, shape: ${i}, copyOld: ${o}}`);let l=this.tensorTrackersById.get(t);if(!l)throw new Error("Tensor not found.");return l.ensureTensor(e,s,i,o)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){Je("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");return s.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,s,i){let o=this.getMLContext(e),l=pr(),u=new Kn({sessionId:e,context:o,tensor:t,dataType:s,shape:i});return this.tensorTrackersById.set(l,new Qn(this,u)),this.externalTensors.add(u),l}async getCachedTensor(e,t,s,i,o,l,u){let c=this.getMLContext(e);for(let[p,g]of this.freeTensors.entries())if(g.canReuseTensor(c,t,s)){Je("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${s}`);let m=this.freeTensors.splice(p,1)[0];return m.sessionId=e,m}Je("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${s}}`);let h=await c.createTensor({dataType:u??t,shape:s,dimensions:s,usage:i,writable:o,readable:l});return new Kn({sessionId:e,context:c,tensor:h,dataType:t,shape:s,fallbackDataType:u})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Is=(...e)=>new As(...e)}),Jr,Ms,Ps,Os=b(()=>{ze(),Yt(),Xr(),pi(),rr(),Jr=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Ms=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),i=Object.keys(t).sort();return s.length===i.length&&s.every((o,l)=>o===i[l]&&e[o]===t[o])},Ps=class{constructor(e){this.tensorManager=Is(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,Gn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Je("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Je("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let s of t)Je("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${s}}`),this.tensorManager.releaseTensorId(s);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(i=>i.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let i=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:i}),i}}else if(e===void 0){let s=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let t=this.mlContextCache.findIndex(s=>Ms(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.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 s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.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){Je("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,i,o){let l=Jr.get(s);if(!l)throw new Error(`Unsupported ONNX data type: ${s}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,l,i,o)}async createTemporaryTensor(e,t,s){Je("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${s}}`);let i=Jr.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,i,s,!1);let l=this.temporarySessionTensorIds.get(e);return l?l.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,t){if(!Ne().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Je("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 s=await this.tensorManager.download(e);return xr(s,t)}}registerMLTensor(e,t,s,i){let o=Jr.get(s);if(!o)throw new Error(`Unsupported ONNX data type: ${s}`);let l=this.tensorManager.registerTensor(e,t,o,i);return Je("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${i}} -> {tensorId: ${l}}`),l}registerMLConstant(e,t,s,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+s>h.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=h.slice(t,t+s).buffer,g;switch(o.dataType){case"float32":g=new Float32Array(p);break;case"float16":g=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(p):new Uint16Array(p);break;case"int32":g=new Int32Array(p);break;case"uint32":g=new Uint32Array(p);break;case"int64":if(u){let m=Yr(new Uint8Array(p),"int64");g=new Int32Array(m.buffer),o.dataType="int32"}else g=new BigInt64Array(p);break;case"uint64":g=new BigUint64Array(p);break;case"int8":g=new Int8Array(p);break;case"int4":case"uint4":case"uint8":g=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return Je("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,g)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let s=this.sessionGraphInputs.get(e);return s?s.includes(t):!1}isGraphOutput(e,t){let s=this.sessionGraphOutputs.get(e);return s?s.includes(t):!1}isGraphInputOutputTypeSupported(e,t,s=!0){let i=Jr.get(Jt(t)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:s?!!o?.input.dataTypes.includes(i):!!o?.output.dataTypes.includes(i)}flush(){}}}),Xn=b(()=>{}),Yn,Jn,xn,Zn,es,ts,Ds,zs,fi,ea=b(()=>{rr(),Xn(),Yn=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]]),Jn=[],xn=e=>Math.ceil(Number(e)/16)*16,Zn=e=>{for(let t=0;t<Jn.length;t++){let s=Jn[t];if(e<=s)return s}return Math.ceil(e/16)*16},es=1,ts=()=>es++,Ds=async(e,t,s,i)=>{let o=xn(s),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,s)),h}else return new Uint8Array(c.slice(0,s))}finally{l.destroy()}},zs=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 Yn)Jn.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,i=t.byteOffset,o=t.byteLength,l=xn(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(s,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(),Je("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let s=this.storageCache.get(e);if(!s)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(s.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=xn(s.originalSize),l=this.backend.getCommandEncoder();this.backend.endComputePass(),l.copyBufferToBuffer(s.gpuData.buffer,0,i.gpuData.buffer,0,o)}registerExternalBuffer(e,t,s){let i;if(s){if(i=s[0],e===s[1])return Je("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.
|
|
27
|
+
Please use the previous external buffer!`)}else i=ts();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:t}),Je("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Je("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=Zn(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(s);c?c.length>0?i=c.pop():i=this.backend.device.createBuffer({size:s,usage:t}):i=this.backend.device.createBuffer({size:s,usage:t})}else i=this.backend.device.createBuffer({size:s,usage:t});let u={id:ts(),type:0,buffer:i};return this.storageCache.set(u.id,{gpuData:u,originalSize:Number(e)}),Je("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,s=this.storageCache.get(t);if(!s){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Je("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${s.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(s.gpuData.buffer),s.originalSize}async download(e,t){let s=this.storageCache.get(Number(e));if(!s)throw new Error("data does not exist");await Ds(this.backend,s.gpuData.buffer,s.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=Yn.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.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(s=>{s.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Je("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},fi=(...e)=>new zs(...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,P,G,U,L,V,ne,ie,ee,K,xe,F,de,wt,qe,Ce,We,_e=b(()=>{ze(),Me(),D=64,P=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}<f16>`:"f16";case 1:return t>1?`vec${t}<f32>`:"f32";case 6:return t>1?`vec${t}<i32>`:"i32";case 12:return t>1?`vec${t}<u32>`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4<bool>"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},G=(e,t=1)=>{let s=P(e,t);return typeof s=="string"?s:s[0]},U=(e,t=1)=>{let s=P(e,t);return typeof s=="string"?s:s[1]},L=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:j.computeStrides(s)})}),t},V=e=>e%4===0?4:e%2===0?2:1,ne=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,ie=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}<f32>(${s})`,ee=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,K=(e,t,s,i)=>e.startsWith("uniforms.")&&s>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}]`:s>1?`${e}[${t}]`:e,xe=(e,t,s,i,o)=>{let l=typeof s=="number",u=l?s:s.length,c=[...new Array(u).keys()],h=u<2?"u32":u<=4?`vec${u}<u32>`:`array<u32, ${u}>`,p=P(t,o),g=typeof p=="string"?p:p[1],m=typeof p=="string"?p:p[0],w={indices:h,value:g,storage:m,tensor:t},_=se=>typeof se=="string"?se:`${se}u`,S={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},C=l?"uniforms.":"",M=`${C}${e}_shape`,k=`${C}${e}_strides`,x="";for(let se=0;se<u-1;se++)x+=`
|
|
28
|
+
let dim${se} = current / ${K(k,se,u)};
|
|
29
|
+
let rest${se} = current % ${K(k,se,u)};
|
|
30
|
+
indices[${se}] = dim${se};
|
|
31
|
+
current = rest${se};
|
|
32
|
+
`;x+=`indices[${u-1}] = current;`;let O=u<2?"":`
|
|
33
|
+
fn o2i_${e}(offset: u32) -> ${w.indices} {
|
|
34
|
+
var indices: ${w.indices};
|
|
35
|
+
var current = offset;
|
|
36
|
+
${x}
|
|
37
|
+
return indices;
|
|
38
|
+
}`,I=se=>(S.offsetToIndices=!0,u<2?se:`o2i_${e}(${se})`),z=[];if(u>=2)for(let se=u-1;se>=0;se--)z.push(`${K(k,se,u)} * (indices[${se}])`);let W=u<2?"":`
|
|
39
|
+
fn i2o_${e}(indices: ${w.indices}) -> u32 {
|
|
40
|
+
return ${z.join("+")};
|
|
41
|
+
}`,q=se=>(S.indicesToOffset=!0,u<2?se:`i2o_${e}(${se})`),J=(...se)=>u===0?"0u":`${w.indices}(${se.map(_).join(",")})`,oe=(se,ve)=>u<2?`${se}`:`${K(se,ve,u)}`,ge=(se,ve,Ge)=>u<2?`${se}=${Ge};`:`${K(se,ve,u)}=${Ge};`,Qe={},Ae=(se,ve)=>{S.broadcastedIndicesToOffset=!0;let Ge=`${ve.name}broadcastedIndicesTo${e}Offset`;if(Ge in Qe)return`${Ge}(${se})`;let ht=[];for(let _r=u-1;_r>=0;_r--){let Ar=ve.indicesGet("outputIndices",_r+ve.rank-u);ht.push(`${oe(k,_r)} * (${Ar} % ${oe(M,_r)})`)}return Qe[Ge]=`fn ${Ge}(outputIndices: ${ve.type.indices}) -> u32 {
|
|
42
|
+
return ${ht.length>0?ht.join("+"):"0u"};
|
|
43
|
+
}`,`${Ge}(${se})`},Be=(se,ve)=>(()=>{if(w.storage===w.value)return`${e}[${se}]=${ve};`;if(w.storage==="vec2<u32>"&&w.value==="i32")return`${e}[${se}]=vec2<u32>(u32(${ve}), select(0u, 0xFFFFFFFFu, ${ve} < 0));`;if(w.storage==="vec2<u32>"&&w.value==="u32")return`${e}[${se}]=vec2<u32>(u32(${ve}), 0u);`;if(w.storage==="u32"&&w.value==="vec4<bool>")return`${e}[${se}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${ve}));`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),ut=se=>(()=>{if(w.storage===w.value)return`${e}[${se}]`;if(w.storage==="vec2<u32>"&&w.value==="i32")return`i32(${e}[${se}].x)`;if(w.storage==="vec2<u32>"&&w.value==="u32")return`u32(${e}[${se}].x)`;if(w.storage==="u32"&&w.value==="vec4<bool>")return`vec4<bool>(bool(${e}[${se}] & 0xFFu), bool(${e}[${se}] & 0xFF00u), bool(${e}[${se}] & 0xFF0000u), bool(${e}[${se}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),we=u<2?"":`
|
|
44
|
+
fn get_${e}ByIndices(indices: ${w.indices}) -> ${g} {
|
|
45
|
+
return ${ut(`i2o_${e}(indices)`)};
|
|
46
|
+
}`,ke=u<2?"":(()=>{let se=c.map(Ge=>`d${Ge}: u32`).join(", "),ve=c.map(Ge=>`d${Ge}`).join(", ");return`
|
|
47
|
+
fn get_${e}(${se}) -> ${g} {
|
|
48
|
+
return get_${e}ByIndices(${J(ve)});
|
|
49
|
+
}`})(),Xe=(...se)=>{if(se.length!==u)throw new Error(`indices length must be ${u}`);let ve=se.map(_).join(",");return u===0?ut("0u"):u===1?ut(ve[0]):(S.get=!0,S.getByIndices=!0,S.indicesToOffset=!0,`get_${e}(${ve})`)},Ve=se=>u<2?ut(se):(S.getByIndices=!0,S.indicesToOffset=!0,`get_${e}ByIndices(${se})`),Ue=u<2?"":`
|
|
50
|
+
fn set_${e}ByIndices(indices: ${w.indices}, value: ${g}) {
|
|
51
|
+
${Be(`i2o_${e}(indices)`,"value")}
|
|
52
|
+
}`,ct=u<2?"":(()=>{let se=c.map(Ge=>`d${Ge}: u32`).join(", "),ve=c.map(Ge=>`d${Ge}`).join(", ");return`
|
|
53
|
+
fn set_${e}(${se}, value: ${g}) {
|
|
54
|
+
set_${e}ByIndices(${J(ve)}, value);
|
|
55
|
+
}`})();return{impl:()=>{let se=[],ve=!1;return S.offsetToIndices&&(se.push(O),ve=!0),S.indicesToOffset&&(se.push(W),ve=!0),S.broadcastedIndicesToOffset&&(Object.values(Qe).forEach(Ge=>se.push(Ge)),ve=!0),S.set&&(se.push(ct),ve=!0),S.setByIndices&&(se.push(Ue),ve=!0),S.get&&(se.push(ke),ve=!0),S.getByIndices&&(se.push(we),ve=!0),!l&&ve&&se.unshift(`const ${M} = ${w.indices}(${s.join(",")});`,`const ${k} = ${w.indices}(${j.computeStrides(s).join(",")});`),se.join(`
|
|
56
|
+
`)},type:w,offsetToIndices:I,indicesToOffset:q,broadcastedIndicesToOffset:Ae,indices:J,indicesGet:oe,indicesSet:ge,set:(...se)=>{if(se.length!==u+1)throw new Error(`indices length must be ${u}`);let ve=se[u];if(typeof ve!="string")throw new Error("value must be string");let Ge=se.slice(0,u).map(_).join(",");return u===0?Be("0u",ve):u===1?Be(Ge[0],ve):(S.set=!0,S.setByIndices=!0,S.indicesToOffset=!0,`set_${e}(${Ge}, ${ve})`)},setByOffset:Be,setByIndices:(se,ve)=>u<2?Be(se,ve):(S.setByIndices=!0,S.indicesToOffset=!0,`set_${e}ByIndices(${se}, ${ve});`),get:Xe,getByOffset:ut,getByIndices:Ve,usage:i,name:e,strides:k,shape:M,rank:u}},F=(e,t,s,i=1)=>xe(e,t,s,"input",i),de=(e,t,s,i=1)=>xe(e,t,s,"output",i),wt=(e,t,s)=>xe(e,t,s,"atomicOutput",1),qe=(e,t,s,i=1)=>xe(e,t,s,"internal",i),Ce=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],s=typeof e=="number"?1:e[1],i=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${s}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*s*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${s}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,l=o?`@builtin(global_invocation_id) global_id : vec3<u32>,
|
|
57
|
+
@builtin(workgroup_id) workgroup_id : vec3<u32>,
|
|
58
|
+
@builtin(local_invocation_index) local_idx : u32,
|
|
59
|
+
@builtin(local_invocation_id) local_id : vec3<u32>`:`@builtin(global_invocation_id) global_id : vec3<u32>,
|
|
60
|
+
@builtin(local_invocation_id) local_id : vec3<u32>,
|
|
61
|
+
@builtin(local_invocation_index) local_idx : u32,
|
|
62
|
+
@builtin(workgroup_id) workgroup_id : vec3<u32>,
|
|
63
|
+
@builtin(num_workgroups) num_workgroups : vec3<u32>`,u=o?`let global_idx = global_id.x;
|
|
64
|
+
let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +
|
|
65
|
+
workgroup_id.y * num_workgroups[0] + workgroup_id.x;
|
|
66
|
+
let global_idx = workgroup_index * ${t*s*i}u + local_idx;`;return`@compute @workgroup_size(${t}, ${s}, ${i})
|
|
67
|
+
fn main(${l}) {
|
|
68
|
+
${u}
|
|
69
|
+
`}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let s=e.usage==="input"?"read":"read_write",i=e.usage==="atomicOutput"?"atomic<i32>":e.type.storage;return`@group(0) @binding(${t}) var<storage, ${s}> ${e.name}: array<${i}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(`
|
|
70
|
+
`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,s=1){return this.uniforms.push({name:e,type:t,length:s}),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:s,length:i}of this.uniforms)if(i&&i>4)s==="f16"?e.push(`@align(16) ${t}:array<mat2x4<${s}>, ${Math.ceil(i/8)}>`):e.push(`${t}:array<vec4<${s}>, ${Math.ceil(i/4)}>`);else{let o=i==null||i===1?s:`vec${i}<${s}>`;e.push(`${t}:${o}`)}return`
|
|
71
|
+
struct Uniforms { ${e.join(", ")} };
|
|
72
|
+
@group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(`
|
|
73
|
+
`)+this.internalVariables.map(e=>e.impl()).join(`
|
|
74
|
+
`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},We=(e,t)=>new Ce(e,t)}),zt,Lt,kr,Zr,rs,Ls,bt,sr,Bs,He=b(()=>{ze(),Me(),A(),_e(),zt=(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}`)},Lt=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),kr=(e,t)=>j.sortBasedOnPerm(e,Lt(e.length,t)),Zr=(e,t,s,i)=>{let o=`fn perm(i: ${i.type.indices}) -> ${s.type.indices} {
|
|
75
|
+
var a: ${s.type.indices};`;for(let l=0;l<t;++l)o+=`a[${e[l]}]=i[${l}];`;return o+="return a;}"},rs=(e,t)=>{let s=[],i=[];for(let o=0;o<e.length;++o)e[o]!==1&&s.push(e[o]),e[t[o]]!==1&&i.push(t[o]);return{newShape:s,newPerm:i}},Ls=(e,t)=>{let s=0;for(let i=0;i<e.length;++i)if(t[e[i]]!==1){if(e[i]<s)return!1;s=e[i]}return!0},bt=(e,t)=>{let s=e.dataType,i=e.dims.length,o=Lt(i,t),l=kr(e.dims,o),u=e.dims,c=l,h=i<2||Ls(o,e.dims),p;if(h)return p=S=>{let C=F("input",s,u,4),M=de("output",s,c,4);return`
|
|
76
|
+
${S.registerUniform("output_size","u32").declareVariables(C,M)}
|
|
77
|
+
${S.mainStart()}
|
|
78
|
+
${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
79
|
+
output[global_idx] = input[global_idx];
|
|
80
|
+
}`},{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:g,newPerm:m}=rs(e.dims,o),w=j.areEqual(m,[2,3,1]),_=j.areEqual(m,[3,1,2]);if(g.length===2||w||_){u=w?[g[0],g[1]*g[2]]:_?[g[0]*g[1],g[2]]:g,c=[u[1],u[0]];let S=16;return p=C=>{let M=F("a",s,u.length),k=de("output",s,c.length);return`
|
|
81
|
+
${C.registerUniform("output_size","u32").declareVariables(M,k)}
|
|
82
|
+
var<workgroup> tile : array<array<${k.type.value}, ${S+1}>, ${S}>;
|
|
83
|
+
${C.mainStart([S,S,1])}
|
|
84
|
+
let stride = (uniforms.output_shape[1] - 1) / ${S} + 1;
|
|
85
|
+
let workgroup_id_x = workgroup_index % stride;
|
|
86
|
+
let workgroup_id_y = workgroup_index / stride;
|
|
87
|
+
let input_col = workgroup_id_y * ${S}u + local_id.x;
|
|
88
|
+
let input_row = workgroup_id_x * ${S}u + local_id.y;
|
|
89
|
+
if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {
|
|
90
|
+
tile[local_id.y][local_id.x] = ${M.getByIndices(`${M.type.indices}(input_row, input_col)`)};
|
|
91
|
+
}
|
|
92
|
+
workgroupBarrier();
|
|
93
|
+
|
|
94
|
+
let output_col = workgroup_id_x * ${S}u + local_id.x;
|
|
95
|
+
let output_row = workgroup_id_y * ${S}u + local_id.y;
|
|
96
|
+
if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {
|
|
97
|
+
${k.setByIndices(`${k.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")}
|
|
98
|
+
}
|
|
99
|
+
}`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let C=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:C},...L(u,c)]}},getShaderSource:p}}return p=S=>{let C=F("a",s,u.length),M=de("output",s,c.length);return`
|
|
100
|
+
${S.registerUniform("output_size","u32").declareVariables(C,M)}
|
|
101
|
+
|
|
102
|
+
${Zr(o,i,C,M)}
|
|
103
|
+
|
|
104
|
+
${S.mainStart()}
|
|
105
|
+
${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
106
|
+
|
|
107
|
+
let indices = ${M.offsetToIndices("global_idx")};
|
|
108
|
+
let aIndices = perm(indices);
|
|
109
|
+
|
|
110
|
+
${M.setByOffset("global_idx",C.getByIndices("aIndices"))}
|
|
111
|
+
}`},{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}},sr=(e,t)=>{zt(e.inputs,t.perm),e.compute(bt(e.inputs[0],t.perm))},Bs=e=>E({perm:e.perm})}),nr,mi,fr,Cn,xt,qt,ns,kn,Ns,gi,Pt,mr,en,Ct,St,ir,yi,wi,No,Uo,Fo,Tm=b(()=>{ze(),Me(),_e(),ra(),He(),nr={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"},fr={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Cn={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},xt=(e,t)=>{let s=[];for(let i=t-e;i<t;++i)s.push(i);return s},qt=(e,t)=>{let s=[],i=e.length;for(let l=0;l<i;l++)t.indexOf(l)===-1&&s.push(e[l]);let o=t.map(l=>e[l]);return[s,o]},ns=(e,t)=>{let s=e.length+t.length,i=[],o=0;for(let l=0;l<s;l++)t.indexOf(l)===-1?i.push(e[o++]):i.push(1);return i},kn=(e,t)=>{for(let s=0;s<e.length;++s)if(e[e.length-s-1]!==t-1-s)return!1;return!0},Ns=(e,t)=>{let s=[];if(!kn(e,t)){for(let i=0;i<t;++i)e.indexOf(i)===-1&&s.push(i);e.forEach(i=>s.push(i))}return s},gi=(e,t,s,i,o,l,u)=>{let c=s[0].dims,h=j.size(l),p=j.size(u),g=F("_A",s[0].dataType,c),m=de("output",o,l),w=64;h===1&&(w=256);let _=`
|
|
112
|
+
var<workgroup> aBestValues : array<f32, ${w}>;
|
|
113
|
+
`,S=C=>`
|
|
114
|
+
${C.registerUniform("reduceSize","u32").declareVariables(g,m)}
|
|
115
|
+
${_}
|
|
116
|
+
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
117
|
+
return ((a - 1u) / b + 1u);
|
|
118
|
+
}
|
|
119
|
+
${C.mainStart(w)}
|
|
120
|
+
|
|
121
|
+
let outputIndex = global_idx / ${w};
|
|
122
|
+
let offset = outputIndex * uniforms.reduceSize;
|
|
123
|
+
|
|
124
|
+
var bestValue = f32(${fr[i]});
|
|
125
|
+
let Length = uniforms.reduceSize;
|
|
126
|
+
for (var k = local_idx; k < Length; k = k + ${w}) {
|
|
127
|
+
let candidate = f32(${g.getByOffset("offset + k")});
|
|
128
|
+
bestValue = ${nr[i]};
|
|
129
|
+
}
|
|
130
|
+
aBestValues[local_idx] = bestValue;
|
|
131
|
+
workgroupBarrier();
|
|
132
|
+
|
|
133
|
+
var reduceSize = min(Length, ${w}u);
|
|
134
|
+
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
|
|
135
|
+
currentSize = reduceSize / 2u) {
|
|
136
|
+
let interval = DIV_CEIL(reduceSize, 2u);
|
|
137
|
+
if (local_idx < currentSize) {
|
|
138
|
+
let candidate = aBestValues[local_idx + interval];
|
|
139
|
+
bestValue = ${mi[i]};
|
|
140
|
+
aBestValues[local_idx] = bestValue;
|
|
141
|
+
}
|
|
142
|
+
reduceSize = interval;
|
|
143
|
+
workgroupBarrier();
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (local_idx == 0u) {
|
|
147
|
+
${m.setByOffset("outputIndex",`${i==="mean"?`${m.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${m.type.storage}(${Cn[i]})`}`)};
|
|
148
|
+
}
|
|
149
|
+
}`;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}]})}},Pt=(e,t,s,i)=>{let o=e.inputs.length===1?s:ta(e.inputs,s),l=o.axes;l.length===0&&!o.noopWithEmptyAxes&&(l=e.inputs[0].dims.map((_,S)=>S));let u=j.normalizeAxes(l,e.inputs[0].dims.length),c=u,h=e.inputs[0],p=Ns(c,e.inputs[0].dims.length);p.length>0&&(h=e.compute(bt(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],c=xt(c.length,h.dims.length));let[g,m]=qt(h.dims,c),w=g;o.keepDims&&(w=ns(g,u)),e.compute(gi(t,o.cacheKey,[h],i,e.inputs[0].dataType,w,m),{inputs:[h]})},mr=(e,t)=>{Pt(e,"ReduceMeanShared",t,"mean")},en=(e,t)=>{Pt(e,"ReduceL1Shared",t,"l1")},Ct=(e,t)=>{Pt(e,"ReduceL2Shared",t,"l2")},St=(e,t)=>{Pt(e,"ReduceLogSumExpShared",t,"logSumExp")},ir=(e,t)=>{Pt(e,"ReduceMaxShared",t,"max")},yi=(e,t)=>{Pt(e,"ReduceMinShared",t,"min")},wi=(e,t)=>{Pt(e,"ReduceProdShared",t,"prod")},No=(e,t)=>{Pt(e,"ReduceSumShared",t,"sum")},Uo=(e,t)=>{Pt(e,"ReduceSumSquareShared",t,"sumSquare")},Fo=(e,t)=>{Pt(e,"ReduceLogSumShared",t,"logSum")}}),gr,Vo,vi,ta,yr,Go,qo,Wo,Ho,jo,Ko,Qo,Xo,Yo,Jo,wr,Zo,el,tl,rl,nl,sl,il,al,ol,ll,ra=b(()=>{ze(),Me(),A(),_e(),Tm(),gr=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Vo=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],vi=(e,t,s,i,o,l,u=!1,c=!1)=>{let h=[],p=s[0].dims,g=p.length,m=j.normalizeAxes(o,g),w=!c&&m.length===0;p.forEach((C,M)=>{w||m.indexOf(M)>=0?u&&h.push(1):h.push(C)});let _=h.length,S=j.size(h);return{name:e,shaderCache:t,getShaderSource:C=>{let M=[],k=F("_A",s[0].dataType,g),x=de("output",l,_),O=i(k,x,m),I=O[2];for(let z=0,W=0;z<g;z++)w||m.indexOf(z)>=0?(u&&W++,I=`for(var j${z}: u32 = 0; j${z} < ${p[z]}; j${z}++) {
|
|
150
|
+
${O[2].includes("last_index")?`let last_index = j${z};`:""}
|
|
151
|
+
${k.indicesSet("input_indices",z,`j${z}`)}
|
|
152
|
+
${I}
|
|
153
|
+
}`):(M.push(`${k.indicesSet("input_indices",z,x.indicesGet("output_indices",W))};`),W++);return`
|
|
154
|
+
|
|
155
|
+
${C.registerUniform("output_size","u32").declareVariables(k,x)}
|
|
156
|
+
|
|
157
|
+
${C.mainStart()}
|
|
158
|
+
${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
159
|
+
var input_indices: ${k.type.indices};
|
|
160
|
+
let output_indices = ${x.offsetToIndices("global_idx")};
|
|
161
|
+
|
|
162
|
+
${M.join(`
|
|
163
|
+
`)}
|
|
164
|
+
${O[0]} // init ops for reduce max/min
|
|
165
|
+
${O[1]}
|
|
166
|
+
${I}
|
|
167
|
+
${O[3]}
|
|
168
|
+
${O.length===4?x.setByOffset("global_idx","value"):O.slice(4).join(`
|
|
169
|
+
`)}
|
|
170
|
+
}`},getRunData:()=>({outputs:[{dims:h,dataType:l}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...L(p,h)]})}},ta=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(i=>s.push(Number(i))),E({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},yr=(e,t,s,i)=>{let o=e.inputs,l=o.length===1?s:ta(o,s);e.compute(vi(t,{hint:l.cacheKey,inputDependencies:["rank"]},[o[0]],l.noopWithEmptyAxes&&l.axes.length===0?Vo:i,l.axes,o[0].dataType,l.keepDims,l.noopWithEmptyAxes),{inputs:[0]})},Go=(e,t)=>{gr(e.inputs),yr(e,"ReduceLogSum",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},qo=(e,t)=>{gr(e.inputs),yr(e,"ReduceL1",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},Wo=(e,t)=>{gr(e.inputs),yr(e,"ReduceL2",t,(s,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Ho=(e,t)=>{gr(e.inputs),yr(e,"ReduceLogSumExp",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},jo=(e,t)=>{gr(e.inputs),yr(e,"ReduceMax",t,(s,i,o)=>{let l=[];for(let u=0;u<s.rank;u++)(o.indexOf(u)>=0||o.length===0)&&l.push(s.indicesSet("input_indices",u,0));return[`${l.join(`
|
|
171
|
+
`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},Ko=(e,t)=>{gr(e.inputs),yr(e,"ReduceMean",t,(s,i,o)=>{let l=1;for(let u=0;u<s.rank;u++)(o.indexOf(u)>=0||o.length===0)&&(l*=e.inputs[0].dims[u]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${l});`]})},Qo=(e,t)=>{gr(e.inputs),yr(e,"ReduceMin",t,(s,i,o)=>{let l=[];for(let u=0;u<s.rank;u++)(o.indexOf(u)>=0||o.length===0)&&l.push(`input_indices[${u}] = 0;`);return[`${l.join(`
|
|
172
|
+
`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},Xo=(e,t)=>{gr(e.inputs),yr(e,"ReduceProd",t,(s,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},Yo=(e,t)=>{gr(e.inputs),yr(e,"ReduceSum",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Jo=(e,t)=>{gr(e.inputs),yr(e,"ReduceSumSquare",t,(s,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},wr=(e,t,s)=>{if(t.length===0)return s;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},Zo=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ko(e,t):mr(e,t)},el=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qo(e,t):en(e,t)},tl=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Wo(e,t):Ct(e,t)},rl=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ho(e,t):St(e,t)},nl=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?jo(e,t):ir(e,t)},sl=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Qo(e,t):yi(e,t)},il=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xo(e,t):wi(e,t)},al=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Yo(e,t):No(e,t)},ol=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Jo(e,t):Uo(e,t)},ll=(e,t)=>{wr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Go(e,t):Fo(e,t)}}),na,ul,dl,sa,Em=b(()=>{ze(),A(),ra(),na=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.")},ul=(e,t)=>{na(e.inputs);let s=(i,o,l)=>{let u=[];for(let c=0;c<i.rank;c++)(l.indexOf(c)>=0||l.length===0)&&u.push(`input_indices[${c}] = 0;`);return[`${u.join(`
|
|
173
|
+
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
174
|
+
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {
|
|
175
|
+
value = ${i.getByIndices("input_indices")};
|
|
176
|
+
best_index = i32(last_index);
|
|
177
|
+
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(vi("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},dl=(e,t)=>{na(e.inputs);let s=(i,o,l)=>{let u=[];for(let c=0;c<i.rank;c++)(l.indexOf(c)>=0||l.length===0)&&u.push(`input_indices[${c}] = 0;`);return[`${u.join(`
|
|
178
|
+
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
179
|
+
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {
|
|
180
|
+
value = ${i.getByIndices("input_indices")};
|
|
181
|
+
best_index = i32(last_index);
|
|
182
|
+
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(vi("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},sa=e=>E(e)}),cl,_i,hl,pl,fl,Us,ml,gl,ia=b(()=>{ze(),Me(),Xn(),_e(),cl=(e,t)=>{let s=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(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let h=s.dims[0],p=s.dims[1],g=s.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]!==g)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 m=o.dims[0]/3,w=m,_=w;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let O of t.qkvHiddenSizes)if(O%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");m=t.qkvHiddenSizes[0],w=t.qkvHiddenSizes[1],_=t.qkvHiddenSizes[2]}let S=p;if(m!==w)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==m+w+_)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let C=0;if(u){if(w!==_)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(u.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(u.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(u.dims[1]!==h)throw new Error('Input "past" second dimension must be batch_size');if(u.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(u.dims[4]!==w/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(C=u.dims[3])}let M=S+C,k=-1,x=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:C,kvSequenceLength:S,totalSequenceLength:M,maxSequenceLength:k,inputHiddenSize:g,hiddenSize:m,vHiddenSize:_,headSize:Math.floor(m/t.numHeads),vHeadSize:Math.floor(_/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:x,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},_i=(e,t,s)=>t&&e?`
|
|
183
|
+
let total_sequence_length_input = u32(${t.getByOffset("0")});
|
|
184
|
+
let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);
|
|
185
|
+
let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;
|
|
186
|
+
let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;
|
|
187
|
+
total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1;
|
|
188
|
+
var past_sequence_length: u32 = 0;
|
|
189
|
+
if (is_first_prompt == false) {
|
|
190
|
+
past_sequence_length = total_sequence_length - sequence_length;
|
|
191
|
+
}
|
|
192
|
+
`:`
|
|
193
|
+
${s?"let past_sequence_length = uniforms.past_sequence_length":""};
|
|
194
|
+
let present_sequence_length = total_sequence_length;
|
|
195
|
+
`,hl=(e,t,s,i,o,l,u,c)=>{let h=V(u?1:l),p=64,g=l/h;g<p&&(p=32);let m=Math.ceil(l/h/p),w=[{type:12,data:t},{type:12,data:s},{type:12,data:i},{type:12,data:o},{type:12,data:g},{type:12,data:m}],_=G(e.dataType,h),S=U(1,h),C=["type"];u&&C.push("type"),c&&C.push("type");let M=k=>{let x=de("x",e.dataType,e.dims,h),O=[x],I=u?F("seq_lens",u.dataType,u.dims):void 0;I&&O.push(I);let z=c?F("total_sequence_length_input",c.dataType,c.dims):void 0;z&&O.push(z);let W=U(e.dataType),q=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return`
|
|
196
|
+
var<workgroup> thread_max: array<f32, ${p}>;
|
|
197
|
+
var<workgroup> thread_sum: array<f32, ${p}>;
|
|
198
|
+
${k.registerUniforms(q).declareVariables(...O)}
|
|
199
|
+
${k.mainStart([p,1,1])}
|
|
200
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
201
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
202
|
+
let sequence_length = uniforms.sequence_length;
|
|
203
|
+
var total_sequence_length = uniforms.total_sequence_length;
|
|
204
|
+
${_i(I,z,!1)}
|
|
205
|
+
let local_offset = local_idx * uniforms.elements_per_thread;
|
|
206
|
+
let offset = (global_idx / ${p}) * uniforms.total_sequence_length + local_offset;
|
|
207
|
+
let seq_causal_length = ${u?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"};
|
|
208
|
+
var thread_max_vector = ${S}(-3.4028234663852886e+38f);
|
|
209
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
210
|
+
thread_max_vector = max(${S}(x[offset + i]), thread_max_vector);
|
|
211
|
+
}
|
|
212
|
+
thread_max[local_idx] = ${(()=>{switch(h){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${h}`)}})()};
|
|
213
|
+
workgroupBarrier();
|
|
214
|
+
|
|
215
|
+
var max_value = f32(-3.4028234663852886e+38f);
|
|
216
|
+
for (var i = 0u; i < ${p}; i++) {
|
|
217
|
+
max_value = max(thread_max[i], max_value);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
var sum_vector = ${S}(0);
|
|
221
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
222
|
+
sum_vector += exp(${S}(x[offset + i]) - max_value);
|
|
223
|
+
}
|
|
224
|
+
thread_sum[local_idx] = ${(()=>{switch(h){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${h}`)}})()};
|
|
225
|
+
workgroupBarrier();
|
|
226
|
+
|
|
227
|
+
var sum: f32 = 0;
|
|
228
|
+
for (var i = 0u; i < ${p}; i++) {
|
|
229
|
+
sum += thread_sum[i];
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (sum == 0) {
|
|
233
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
234
|
+
x[offset + i] = ${x.type.value}(${W}(1.0) / ${W}(seq_causal_length));
|
|
235
|
+
}
|
|
236
|
+
} else {
|
|
237
|
+
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
|
|
238
|
+
var f32input = ${S}(x[offset + i]);
|
|
239
|
+
x[offset + i] = ${x.type.value}(exp(f32input - max_value) / sum);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
${u?`
|
|
243
|
+
for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {
|
|
244
|
+
x[offset + total_seq_id] = ${x.type.value}(${W}(0));
|
|
245
|
+
}`:""};
|
|
246
|
+
}`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${p};${_};${h}`,inputDependencies:C},getShaderSource:M,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:t*s},programUniforms:w})}},pl=(e,t,s,i,o,l,u,c,h)=>{let p=u+l.kvSequenceLength,g=[l.batchSize,l.numHeads,l.sequenceLength,p],m=e>1&&i,w=l.kvNumHeads?l.kvNumHeads:l.numHeads,_=m?[l.batchSize,w,p,l.headSize]:void 0,S=l.nReps?l.nReps:1,C=l.scale===0?1/Math.sqrt(l.headSize):l.scale,M=V(l.headSize),k=l.headSize/M,x=12,O={x:Math.ceil(p/x),y:Math.ceil(l.sequenceLength/x),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:C},{type:12,data:u},{type:12,data:l.kvSequenceLength},{type:12,data:S}],z=m&&i&&j.size(i.dims)>0,W=["type","type"];z&&W.push("type"),o&&W.push("type"),c&&W.push("type"),h&&W.push("type");let q=[{dims:g,dataType:t.dataType,gpuDataType:0}];m&&q.push({dims:_,dataType:t.dataType,gpuDataType:0});let J=oe=>{let ge=F("q",t.dataType,t.dims,M),Qe=F("key",s.dataType,s.dims,M),Ae=[ge,Qe];if(z){let Ue=F("past_key",i.dataType,i.dims,M);Ae.push(Ue)}o&&Ae.push(F("attention_bias",o.dataType,o.dims));let Be=c?F("seq_lens",c.dataType,c.dims):void 0;Be&&Ae.push(Be);let ut=h?F("total_sequence_length_input",h.dataType,h.dims):void 0;ut&&Ae.push(ut);let we=de("output",t.dataType,g),ke=[we];m&&ke.push(de("present_key",t.dataType,_,M));let Xe=U(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`
|
|
247
|
+
const TILE_SIZE = ${x}u;
|
|
248
|
+
|
|
249
|
+
var<workgroup> tileQ: array<${ge.type.storage}, ${x*x}>;
|
|
250
|
+
var<workgroup> tileK: array<${ge.type.storage}, ${x*x}>;
|
|
251
|
+
${oe.registerUniforms(Ve).declareVariables(...Ae,...ke)}
|
|
252
|
+
${oe.mainStart([x,x,1])}
|
|
253
|
+
// x holds the N and y holds the M
|
|
254
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
255
|
+
let kvHeadIdx = ${S===1?"headIdx":"headIdx / uniforms.n_reps"};
|
|
256
|
+
let kv_num_heads = ${S===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
|
|
257
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
258
|
+
let m = workgroup_id.y * TILE_SIZE;
|
|
259
|
+
let n = workgroup_id.x * TILE_SIZE;
|
|
260
|
+
let sequence_length = uniforms.M;
|
|
261
|
+
var total_sequence_length = uniforms.N;
|
|
262
|
+
${_i(Be,ut,!0)}
|
|
263
|
+
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;
|
|
264
|
+
let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
265
|
+
${z&&m?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};
|
|
266
|
+
let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;
|
|
267
|
+
${m?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""}
|
|
268
|
+
var value = ${Xe}(0);
|
|
269
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
270
|
+
if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {
|
|
271
|
+
tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];
|
|
272
|
+
}
|
|
273
|
+
if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {
|
|
274
|
+
var idx = TILE_SIZE * local_id.y + local_id.x;
|
|
275
|
+
${z&&m?`
|
|
276
|
+
if (n + local_id.y < past_sequence_length) {
|
|
277
|
+
tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
|
|
278
|
+
} else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
|
|
279
|
+
tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];
|
|
280
|
+
}`:`
|
|
281
|
+
if (n + local_id.y < uniforms.kv_sequence_length) {
|
|
282
|
+
tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
|
|
283
|
+
}`}
|
|
284
|
+
${m?`if (n + local_id.y < present_sequence_length) {
|
|
285
|
+
present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];
|
|
286
|
+
}`:""}
|
|
287
|
+
}
|
|
288
|
+
workgroupBarrier();
|
|
289
|
+
|
|
290
|
+
for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {
|
|
291
|
+
value += ${Xe}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
workgroupBarrier();
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {
|
|
298
|
+
let headOffset = workgroup_id.z * uniforms.M * uniforms.N;
|
|
299
|
+
let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;
|
|
300
|
+
var sum: f32 = ${(()=>{switch(M){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${M}`)}})()};
|
|
301
|
+
output[outputIdx] = ${we.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"};
|
|
302
|
+
}
|
|
303
|
+
}`};return{name:"AttentionProbs",shaderCache:{hint:`${M};${o!==void 0};${i!==void 0};${e}`,inputDependencies:W},getRunData:()=>({outputs:q,dispatchGroup:O,programUniforms:I}),getShaderSource:J}},fl=(e,t,s,i,o,l,u=void 0,c=void 0)=>{let h=l+o.kvSequenceLength,p=o.nReps?o.nReps:1,g=o.vHiddenSize*p,m=e>1&&i,w=o.kvNumHeads?o.kvNumHeads:o.numHeads,_=m?[o.batchSize,w,h,o.headSize]:void 0,S=[o.batchSize,o.sequenceLength,g],C=12,M={x:Math.ceil(o.vHeadSize/C),y:Math.ceil(o.sequenceLength/C),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:g},{type:12,data:l},{type:12,data:o.kvSequenceLength},{type:12,data:p}],x=m&&i&&j.size(i.dims)>0,O=["type","type"];x&&O.push("type"),u&&O.push("type"),c&&O.push("type");let I=[{dims:S,dataType:t.dataType,gpuDataType:0}];m&&I.push({dims:_,dataType:t.dataType,gpuDataType:0});let z=W=>{let q=F("probs",t.dataType,t.dims),J=F("v",s.dataType,s.dims),oe=[q,J];x&&oe.push(F("past_value",i.dataType,i.dims));let ge=u?F("seq_lens",u.dataType,u.dims):void 0;u&&oe.push(ge);let Qe=c?F("total_sequence_length_input",c.dataType,c.dims):void 0;c&&oe.push(Qe);let Ae=[de("output",t.dataType,S)];m&&Ae.push(de("present_value",t.dataType,_));let Be=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return`
|
|
304
|
+
const TILE_SIZE = ${C}u;
|
|
305
|
+
var<workgroup> tileQ: array<${q.type.value}, ${C*C}>;
|
|
306
|
+
var<workgroup> tileV: array<${q.type.value}, ${C*C}>;
|
|
307
|
+
${W.registerUniforms(Be).declareVariables(...oe,...Ae)}
|
|
308
|
+
${W.mainStart([C,C,1])}
|
|
309
|
+
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
310
|
+
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
311
|
+
let kvHeadIdx = ${p===1?"headIdx":"headIdx / uniforms.n_reps"};
|
|
312
|
+
let kv_num_heads = ${p===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
|
|
313
|
+
let m = global_id.y;
|
|
314
|
+
let n = global_id.x;
|
|
315
|
+
let sequence_length = uniforms.M;
|
|
316
|
+
var total_sequence_length = uniforms.K;
|
|
317
|
+
${_i(ge,Qe,!0)}
|
|
318
|
+
let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
319
|
+
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch
|
|
320
|
+
${x&&m?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};
|
|
321
|
+
let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;
|
|
322
|
+
${m?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""}
|
|
323
|
+
var value = ${q.type.storage}(0);
|
|
324
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
325
|
+
if (m < uniforms.M && w + local_id.x < uniforms.K) {
|
|
326
|
+
tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];
|
|
327
|
+
}
|
|
328
|
+
if (n < uniforms.N && w + local_id.y < uniforms.K) {
|
|
329
|
+
var idx = TILE_SIZE * local_id.y + local_id.x;
|
|
330
|
+
${x&&m?`
|
|
331
|
+
if (w + local_id.y < past_sequence_length) {
|
|
332
|
+
tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];
|
|
333
|
+
} else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
|
|
334
|
+
tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];
|
|
335
|
+
}
|
|
336
|
+
`:`
|
|
337
|
+
if (w + local_id.y < uniforms.kv_sequence_length) {
|
|
338
|
+
tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];
|
|
339
|
+
}`}
|
|
340
|
+
${m?`
|
|
341
|
+
if (w + local_id.y < present_sequence_length) {
|
|
342
|
+
present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];
|
|
343
|
+
}`:""}
|
|
344
|
+
}
|
|
345
|
+
workgroupBarrier();
|
|
346
|
+
for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {
|
|
347
|
+
value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];
|
|
348
|
+
}
|
|
349
|
+
workgroupBarrier();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// we need to transpose output from BNSH_v to BSND_v
|
|
353
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
354
|
+
let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size
|
|
355
|
+
+ headIdx * uniforms.N + n;
|
|
356
|
+
output[outputIdx] = value;
|
|
357
|
+
}
|
|
358
|
+
}`};return{name:"AttentionScore",shaderCache:{hint:`${i!==void 0};${e}`,inputDependencies:O},getRunData:()=>({outputs:I,dispatchGroup:M,programUniforms:k}),getShaderSource:z}},Us=(e,t,s,i,o,l,u,c,h,p,g=void 0,m=void 0)=>{let w=Math.min(e.outputCount,1+(u?1:0)+(c?1:0)),_=w>1?p.pastSequenceLength:0,S=_+p.kvSequenceLength,C=h&&j.size(h.dims)>0?h:void 0,M=[t,s];w>1&&u&&j.size(u.dims)>0&&M.push(u),C&&M.push(C),g&&M.push(g),m&&M.push(m);let k=e.compute(pl(w,t,s,u,C,p,_,g,m),{inputs:M,outputs:w>1?[-1,1]:[-1]})[0];e.compute(hl(k,p.batchSize,p.numHeads,_,p.sequenceLength,S,g,m),{inputs:g&&m?[k,g,m]:[k],outputs:[]});let x=[k,i];w>1&&c&&j.size(c.dims)>0&&x.push(c),g&&x.push(g),m&&x.push(m),e.compute(fl(w,k,i,c,p,_,g,m),{inputs:x,outputs:w>1?[0,2]:[0]})},ml=(e,t)=>{let s=[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}],g=m=>{let w=de("output_q",h[0].dataType,s),_=de("output_k",h[0].dataType,s),S=de("output_v",h[0].dataType,s),C=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=C.type.storage,O=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return`
|
|
359
|
+
const TILE_SIZE = ${u}u;
|
|
360
|
+
var<workgroup> tileInput: array<${x}, ${u*u}>;
|
|
361
|
+
var<workgroup> tileWeightQ: array<${x}, ${u*u}>;
|
|
362
|
+
var<workgroup> tileWeightK: array<${x}, ${u*u}>;
|
|
363
|
+
var<workgroup> tileWeightV: array<${x}, ${u*u}>;
|
|
364
|
+
${m.registerUniforms(O).declareVariables(C,M,k,w,_,S)}
|
|
365
|
+
${m.mainStart([u,u,1])}
|
|
366
|
+
let batchIndex = workgroup_id.z / uniforms.num_heads;
|
|
367
|
+
let headNumber = workgroup_id.z % uniforms.num_heads;
|
|
368
|
+
let m = global_id.y;
|
|
369
|
+
let n = global_id.x;
|
|
370
|
+
|
|
371
|
+
let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;
|
|
372
|
+
let biasOffsetQ = headNumber * uniforms.head_size;
|
|
373
|
+
let biasOffsetK = uniforms.hidden_size + biasOffsetQ;
|
|
374
|
+
let biasOffsetV = uniforms.hidden_size + biasOffsetK;
|
|
375
|
+
|
|
376
|
+
var valueQ = ${x}(0);
|
|
377
|
+
var valueK = ${x}(0);
|
|
378
|
+
var valueV = ${x}(0);
|
|
379
|
+
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
380
|
+
if (m < uniforms.M && w + local_id.x < uniforms.K) {
|
|
381
|
+
tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];
|
|
382
|
+
}
|
|
383
|
+
if (n < uniforms.N && w + local_id.y < uniforms.K) {
|
|
384
|
+
let offset = n + (w + local_id.y) * uniforms.ldb;
|
|
385
|
+
tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];
|
|
386
|
+
tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];
|
|
387
|
+
tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];
|
|
388
|
+
}
|
|
389
|
+
workgroupBarrier();
|
|
390
|
+
for (var k: u32 = 0u; k<TILE_SIZE && w+k < uniforms.K; k++) {
|
|
391
|
+
let inputTileOffset = TILE_SIZE * local_id.y + k;
|
|
392
|
+
let weightTileOffset = TILE_SIZE * k + local_id.x;
|
|
393
|
+
valueQ += tileInput[inputTileOffset] * tileWeightQ[weightTileOffset];
|
|
394
|
+
valueK += tileInput[inputTileOffset] * tileWeightK[weightTileOffset];
|
|
395
|
+
valueV += tileInput[inputTileOffset] * tileWeightV[weightTileOffset];
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
workgroupBarrier();
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
let headOffset = (m * uniforms.N + n) % uniforms.head_size;
|
|
402
|
+
valueQ += bias[headOffset + biasOffsetQ];
|
|
403
|
+
valueK += bias[headOffset + biasOffsetK];
|
|
404
|
+
valueV += bias[headOffset + biasOffsetV];
|
|
405
|
+
|
|
406
|
+
let offset = workgroup_id.z * uniforms.M * uniforms.N;
|
|
407
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
408
|
+
let outputIdx = offset + m * uniforms.N + n;
|
|
409
|
+
output_q[outputIdx] = valueQ;
|
|
410
|
+
output_k[outputIdx] = valueK;
|
|
411
|
+
output_v[outputIdx] = valueV;
|
|
412
|
+
}
|
|
413
|
+
}`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:p}),getShaderSource:g},{inputs:h,outputs:[-1,-1,-1]})},gl=(e,t)=>{let s=cl(e.inputs,t),[i,o,l]=ml(e,s);return Us(e,i,o,l,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),yl,wl,vl,_l,$m=b(()=>{Mt(),ze(),Me(),A(),_e(),yl=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(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);s(e[1].dims,i,"Invalid input scale"),s(e[2].dims,i,"Invalid input B"),s(e[3].dims,i,"Invalid input mean"),s(e[4].dims,i,"Invalid input var")}else s(e[1].dims,[1],"Invalid input scale"),s(e[2].dims,[1],"Invalid input B"),s(e[3].dims,[1],"Invalid input mean"),s(e[4].dims,[1],"Invalid input var")},wl=(e,t)=>{let{epsilon:s,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,g=p?l.length:l,m=F("x",e[0].dataType,e[0].dims,u),w=F("scale",e[1].dataType,e[1].dims,c),_=F("bias",e[2].dataType,e[2].dims,c),S=F("inputMean",e[3].dataType,e[3].dims,c),C=F("inputVar",e[4].dataType,e[4].dims,c),M=de("y",e[0].dataType,g,u),k=()=>{let O="";if(i)O=`let cOffset = ${l.length===1?"0u":o==="NHWC"?`outputIndices[${l.length-1}] / ${u}`:"outputIndices[1]"};`;else if(o==="NCHW")O=`
|
|
414
|
+
${M.indicesSet("outputIndices","0","0")}
|
|
415
|
+
let cOffset = ${M.indicesToOffset("outputIndices")};`;else{O=`var cIndices = ${w.type.indices}(0);
|
|
416
|
+
cIndices[0] = outputIndices[${l.length-1}];`;for(let I=1;I<w.rank;I++)O+=`cIndices[${I}] = outputIndices[${I}];`;O+=`let cOffset = ${w.indicesToOffset("cIndices")};`}return O},x=O=>`
|
|
417
|
+
const epsilon = ${s};
|
|
418
|
+
${O.registerUniform("outputSize","u32").declareVariables(m,w,_,S,C,M)}
|
|
419
|
+
${O.mainStart()}
|
|
420
|
+
${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
421
|
+
var outputIndices = ${M.offsetToIndices(`global_idx * ${u}`)};
|
|
422
|
+
${k()}
|
|
423
|
+
let scale = ${w.getByOffset("cOffset")};
|
|
424
|
+
let bias = ${_.getByOffset("cOffset")};
|
|
425
|
+
let inputMean = ${S.getByOffset("cOffset")};
|
|
426
|
+
let inputVar = ${C.getByOffset("cOffset")};
|
|
427
|
+
let x = ${m.getByOffset("global_idx")};
|
|
428
|
+
let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;
|
|
429
|
+
${M.setByOffset("global_idx","value")}
|
|
430
|
+
}`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${i}_${u}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:x,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}]})}},vl=e=>E(e),_l=(e,t)=>{let{inputs:s,outputCount:i}=e,o=vl({...t,outputCount:i});if(fe.webgpu.validateInputContent&&yl(s,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(wl(s,o))}}),bl,Sl,Tl,xm=b(()=>{Me(),_e(),bl=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")},Sl=e=>{let t=e[0].dims,s=e[0].dims[2],i=j.size(t)/4,o=e[0].dataType,l=F("input",o,t,4),u=F("bias",o,[s],4),c=F("residual",o,t,4),h=de("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:p=>`
|
|
431
|
+
const channels = ${s}u / 4;
|
|
432
|
+
${p.declareVariables(l,u,c,h)}
|
|
433
|
+
|
|
434
|
+
${p.mainStart()}
|
|
435
|
+
${p.guardAgainstOutOfBoundsWorkgroupSizes(i)}
|
|
436
|
+
let value = ${l.getByOffset("global_idx")}
|
|
437
|
+
+ ${u.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")};
|
|
438
|
+
${h.setByOffset("global_idx","value")}
|
|
439
|
+
}`}},Tl=e=>{bl(e.inputs),e.compute(Sl(e.inputs))}}),El,lt,$l,xl,Cl,kl,Rl,Al,Il,Ml,Pl,Ol,Dl,zl,Ll,Bl,Fs,Nl,bi,Ul,Fl,Vl,Gl,ql,Wl,Hl,jl,Kl,Ql,Xl,Yl,Jl,Zl,eu,tu,aa,ru,oa,la,nu,su,iu,au,ou,lu,ua=b(()=>{ze(),Me(),A(),_e(),El=(e,t,s,i,o,l,u)=>{let c=Math.ceil(t/4),h="";typeof o=="string"?h=`${o}(a)`:h=o("a");let p=F("inputData",s,[c],4),g=de("outputData",i,[c],4),m=[{name:"vec_size",type:"u32"}];return u&&m.push(...u),`
|
|
440
|
+
${e.registerUniforms(m).declareVariables(p,g)}
|
|
441
|
+
|
|
442
|
+
${l??""}
|
|
443
|
+
|
|
444
|
+
${e.mainStart()}
|
|
445
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
446
|
+
|
|
447
|
+
let a = ${p.getByOffset("global_idx")};
|
|
448
|
+
${g.setByOffset("global_idx",h)}
|
|
449
|
+
}`},lt=(e,t,s,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=>El(p,j.size(e.dims),e.dataType,l,s,i,c),getRunData:p=>({outputs:[{dims:e.dims,dataType:l}],dispatchGroup:{x:Math.ceil(j.size(p[0].dims)/64/4)},programUniforms:h})}},$l=e=>{e.compute(lt(e.inputs[0],"Abs","abs"))},xl=e=>{e.compute(lt(e.inputs[0],"Acos","acos"))},Cl=e=>{e.compute(lt(e.inputs[0],"Acosh","acosh"))},kl=e=>{e.compute(lt(e.inputs[0],"Asin","asin"))},Rl=e=>{e.compute(lt(e.inputs[0],"Asinh","asinh"))},Al=e=>{e.compute(lt(e.inputs[0],"Atan","atan"))},Il=e=>{e.compute(lt(e.inputs[0],"Atanh","atanh"))},Ml=e=>E(e),Pl=(e,t)=>{let s;switch(t.to){case 10:s="vec4<f16>";break;case 1:s="vec4<f32>";break;case 12:s="vec4<u32>";break;case 6:s="vec4<i32>";break;case 9:s="vec4<bool>";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(lt(e.inputs[0],"Cast",s,void 0,t.cacheKey,t.to))},Ol=e=>{let t,s,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,s=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=i?e[1].getUint16Array()[0]:64511,s=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return E({min:t,max:s})},Dl=(e,t)=>{let s=t||Ol(e.inputs),i=U(e.inputs[0].dataType);e.compute(lt(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${i}>(uniforms.min), vec4<${i}>(uniforms.max))`,void 0,s.cacheKey,void 0,[{type:e.inputs[0].dataType,data:s.min},{type:e.inputs[0].dataType,data:s.max}],[{name:"min",type:i},{name:"max",type:i}]),{inputs:[0]})},zl=e=>{e.compute(lt(e.inputs[0],"Ceil","ceil"))},Ll=e=>{e.compute(lt(e.inputs[0],"Cos","cos"))},Bl=e=>{e.compute(lt(e.inputs[0],"Cosh","cosh"))},Fs=e=>E(e),Nl=(e,t)=>{let s=U(e.inputs[0].dataType);e.compute(lt(e.inputs[0],"Elu",i=>`elu_vf32(${i})`,`
|
|
450
|
+
const elu_alpha_ = ${s}(${t.alpha});
|
|
451
|
+
|
|
452
|
+
fn elu_f32(a: ${s}) -> ${s} {
|
|
453
|
+
return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
fn elu_vf32(v: vec4<${s}>) -> vec4<${s}> {
|
|
457
|
+
return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));
|
|
458
|
+
}`,t.cacheKey))},bi=(e="f32")=>`
|
|
459
|
+
const r0: ${e} = 0.3275911;
|
|
460
|
+
const r1: ${e} = 0.254829592;
|
|
461
|
+
const r2: ${e} = -0.284496736;
|
|
462
|
+
const r3: ${e} = 1.421413741;
|
|
463
|
+
const r4: ${e} = -1.453152027;
|
|
464
|
+
const r5: ${e} = 1.061405429;
|
|
465
|
+
|
|
466
|
+
fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {
|
|
467
|
+
let absv = abs(v);
|
|
468
|
+
let x = 1.0 / (1.0 + r0 * absv);
|
|
469
|
+
return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));
|
|
470
|
+
}`,Ul=e=>{let t=U(e.inputs[0].dataType);e.compute(lt(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,bi(t)))},Fl=e=>{e.compute(lt(e.inputs[0],"Exp","exp"))},Vl=e=>{e.compute(lt(e.inputs[0],"Floor","floor"))},Gl=e=>{let t=U(e.inputs[0].dataType);e.compute(lt(e.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,bi(t)))},ql=(e,t)=>{let s=U(e.inputs[0].dataType);e.compute(lt(e.inputs[0],"LeakyRelu",i=>`select(leaky_relu_alpha_ * ${i}, ${i}, ${i} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${t.alpha});`,t.cacheKey))},Wl=e=>{e.compute(lt(e.inputs[0],"Not",t=>`!${t}`))},Hl=e=>{e.compute(lt(e.inputs[0],"Neg",t=>`-${t}`))},jl=e=>{e.compute(lt(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Kl=e=>{let t=U(e.inputs[0].dataType);e.compute(lt(e.inputs[0],"Relu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`))},Ql=e=>{e.compute(lt(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Xl=e=>E(e),Yl=(e,t)=>{let s=U(e.inputs[0].dataType);e.compute(lt(e.inputs[0],"HardSigmoid",i=>`max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${t.alpha} * ${i} + vec4<${s}>(${t.beta})))`,void 0,t.cacheKey))},Jl=e=>{e.compute(lt(e.inputs[0],"Sin","sin"))},Zl=e=>{e.compute(lt(e.inputs[0],"Sinh","sinh"))},eu=e=>{e.compute(lt(e.inputs[0],"Sqrt","sqrt"))},tu=e=>{e.compute(lt(e.inputs[0],"Tan","tan"))},aa=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,ru=e=>{e.compute(lt(e.inputs[0],"Tanh",aa))},oa=(e="f32")=>`
|
|
471
|
+
const fast_gelu_a: ${e} = 0.5;
|
|
472
|
+
const fast_gelu_b: ${e} = 0.7978845608028654;
|
|
473
|
+
const fast_gelu_c: ${e} = 0.035677408136300125;
|
|
474
|
+
|
|
475
|
+
fn tanh_v(v: vec4<${e}>) -> vec4<${e}> {
|
|
476
|
+
return ${aa("v")};
|
|
477
|
+
}
|
|
478
|
+
`,la=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,nu=e=>{let t=U(e.inputs[0].dataType);e.compute(lt(e.inputs[0],"FastGelu",la,oa(t),void 0,e.inputs[0].dataType))},su=(e,t)=>{let s=U(e.inputs[0].dataType);return e.compute(lt(e.inputs[0],"ThresholdedRelu",i=>`select(vec4<${s}>(0.0), ${i}, ${i} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${s}>(${t.alpha});`,t.cacheKey)),0},iu=e=>{e.compute(lt(e.inputs[0],"Log","log"))},au=(e,t)=>`
|
|
479
|
+
const alpha = vec4<${e}>(${t});
|
|
480
|
+
const one = ${e}(1.0);
|
|
481
|
+
const zero = ${e}(0.0);
|
|
482
|
+
|
|
483
|
+
fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
484
|
+
let v = x *alpha;
|
|
485
|
+
var x1 : vec4<${e}>;
|
|
486
|
+
for (var i = 0; i < 4; i = i + 1) {
|
|
487
|
+
if (v[i] >= zero) {
|
|
488
|
+
x1[i] = one / (one + exp(-v[i]));
|
|
489
|
+
} else {
|
|
490
|
+
x1[i] = one - one / (one + exp(v[i]));
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
return x * x1;
|
|
494
|
+
}
|
|
495
|
+
`,ou=e=>`quick_gelu_impl(${e})`,lu=(e,t)=>{let s=U(e.inputs[0].dataType);e.compute(lt(e.inputs[0],"QuickGelu",ou,au(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),uu,du,cu,Cm=b(()=>{Me(),_e(),ua(),uu=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")},du=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let s=F("input",e[0].dataType,e[0].dims,4),i=F("bias",e[0].dataType,[e[0].dims[2]],4),o=de("output",e[0].dataType,t,4),l=j.size(t)/4,u=G(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)}}),getShaderSource:c=>`
|
|
496
|
+
const M_SQRT2 = sqrt(2.0);
|
|
497
|
+
const halfChannels = ${e[0].dims[2]/4/2}u;
|
|
498
|
+
|
|
499
|
+
${c.declareVariables(s,i,o)}
|
|
500
|
+
|
|
501
|
+
${bi(u)}
|
|
502
|
+
|
|
503
|
+
${c.mainStart()}
|
|
504
|
+
${c.guardAgainstOutOfBoundsWorkgroupSizes(l)}
|
|
505
|
+
let biasIdx = global_idx % halfChannels;
|
|
506
|
+
let batchIndex = global_idx / halfChannels;
|
|
507
|
+
let inputOffset = biasIdx + batchIndex * halfChannels * 2;
|
|
508
|
+
let valueLeft = input[inputOffset] + bias[biasIdx];
|
|
509
|
+
let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];
|
|
510
|
+
let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);
|
|
511
|
+
|
|
512
|
+
${o.setByOffset("global_idx","valueLeft * geluRight")}
|
|
513
|
+
}`}},cu=e=>{uu(e.inputs),e.compute(du(e.inputs))}}),hu,pu,vr,fu,mu,gu,yu,wu,vu,_u,bu,Su,Tu,km=b(()=>{ze(),Me(),_e(),hu=(e,t,s,i,o,l,u,c,h,p,g,m)=>{let w,_;typeof c=="string"?w=_=(x,O)=>`${c}((${x}),(${O}))`:typeof c=="function"?w=_=c:(w=c.scalar,_=c.vector);let S=de("outputData",g,i.length,4),C=F("aData",h,t.length,4),M=F("bData",p,s.length,4),k;if(o)if(l){let x=j.size(t)===1,O=j.size(s)===1,I=t.length>0&&t[t.length-1]%4===0,z=s.length>0&&s[s.length-1]%4===0;x||O?k=S.setByOffset("global_idx",_(x?`${C.type.value}(${C.getByOffset("0")}.x)`:C.getByOffset("global_idx"),O?`${M.type.value}(${M.getByOffset("0")}.x)`:M.getByOffset("global_idx"))):k=`
|
|
514
|
+
let outputIndices = ${S.offsetToIndices("global_idx * 4u")};
|
|
515
|
+
let offsetA = ${C.broadcastedIndicesToOffset("outputIndices",S)};
|
|
516
|
+
let offsetB = ${M.broadcastedIndicesToOffset("outputIndices",S)};
|
|
517
|
+
${S.setByOffset("global_idx",_(u||I?C.getByOffset("offsetA / 4u"):`${C.type.value}(${C.getByOffset("offsetA / 4u")}[offsetA % 4u])`,u||z?M.getByOffset("offsetB / 4u"):`${M.type.value}(${M.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}
|
|
518
|
+
`}else k=S.setByOffset("global_idx",_(C.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 x=(O,I,z="")=>{let W=`aData[indexA${I}][componentA${I}]`,q=`bData[indexB${I}][componentB${I}]`;return`
|
|
519
|
+
let outputIndices${I} = ${S.offsetToIndices(`global_idx * 4u + ${I}u`)};
|
|
520
|
+
let offsetA${I} = ${C.broadcastedIndicesToOffset(`outputIndices${I}`,S)};
|
|
521
|
+
let offsetB${I} = ${M.broadcastedIndicesToOffset(`outputIndices${I}`,S)};
|
|
522
|
+
let indexA${I} = offsetA${I} / 4u;
|
|
523
|
+
let indexB${I} = offsetB${I} / 4u;
|
|
524
|
+
let componentA${I} = offsetA${I} % 4u;
|
|
525
|
+
let componentB${I} = offsetB${I} % 4u;
|
|
526
|
+
${O}[${I}] = ${z}(${w(W,q)});
|
|
527
|
+
`};g===9?k=`
|
|
528
|
+
var data = vec4<u32>(0);
|
|
529
|
+
${x("data",0,"u32")}
|
|
530
|
+
${x("data",1,"u32")}
|
|
531
|
+
${x("data",2,"u32")}
|
|
532
|
+
${x("data",3,"u32")}
|
|
533
|
+
outputData[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:k=`
|
|
534
|
+
${x("outputData[global_idx]",0)}
|
|
535
|
+
${x("outputData[global_idx]",1)}
|
|
536
|
+
${x("outputData[global_idx]",2)}
|
|
537
|
+
${x("outputData[global_idx]",3)}
|
|
538
|
+
`}return`
|
|
539
|
+
${e.registerUniform("vec_size","u32").declareVariables(C,M,S)}
|
|
540
|
+
|
|
541
|
+
${m??""}
|
|
542
|
+
|
|
543
|
+
${e.mainStart()}
|
|
544
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
545
|
+
${k}
|
|
546
|
+
}`},pu=(e,t,s,i,o,l,u=s.dataType)=>{let c=s.dims.map(Number),h=i.dims.map(Number),p=!j.areEqual(c,h),g=c,m=j.size(c),w=!1,_=!1,S=[p];if(p){let C=$r.calcShape(c,h,!1);if(!C)throw new Error("Can't perform binary op on the given tensors");g=C.slice(),m=j.size(g);let M=j.size(c)===1,k=j.size(h)===1,x=c.length>0&&c[c.length-1]%4===0,O=h.length>0&&h[h.length-1]%4===0;S.push(M),S.push(k),S.push(x),S.push(O);let I=1;for(let z=1;z<g.length;z++){let W=c[c.length-z],q=h[h.length-z];if(W===q)I*=W;else break}I%4===0?(_=!0,w=!0):(M||k||x||O)&&(w=!0)}else w=!0;return S.push(w),{name:e,shaderCache:{hint:t+S.map(C=>C.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:C=>hu(C,c,h,g,w,p,_,o,s.dataType,i.dataType,u,l),getRunData:()=>({outputs:[{dims:g,dataType:u}],dispatchGroup:{x:Math.ceil(m/64/4)},programUniforms:[{type:12,data:Math.ceil(j.size(g)/4)},...L(c,h,g)]})}},vr=(e,t,s,i,o,l)=>{e.compute(pu(t,o??"",e.inputs[0],e.inputs[1],s,i,l))},fu=e=>{vr(e,"Add",(t,s)=>`${t}+${s}`)},mu=e=>{vr(e,"Div",(t,s)=>`${t}/${s}`)},gu=e=>{vr(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4<u32>(${t}==${s})`},void 0,void 0,9)},yu=e=>{vr(e,"Mul",(t,s)=>`${t}*${s}`)},wu=e=>{let t=F("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;vr(e,"Pow",{scalar:(s,i)=>`pow_custom(${s},${i})`,vector:(s,i)=>`pow_vector_custom(${s},${i})`},`
|
|
547
|
+
fn pow_custom(a : ${t}, b : ${t}) -> ${t} {
|
|
548
|
+
if (b == ${t}(0.0)) {
|
|
549
|
+
return ${t}(1.0);
|
|
550
|
+
} else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {
|
|
551
|
+
return ${t}(pow(f32(a), f32(b))); // NaN
|
|
552
|
+
}
|
|
553
|
+
return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));
|
|
554
|
+
}
|
|
555
|
+
fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {
|
|
556
|
+
// TODO: implement vectorized pow
|
|
557
|
+
return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));
|
|
558
|
+
}
|
|
559
|
+
`)},vu=e=>{vr(e,"Sub",(t,s)=>`${t}-${s}`)},_u=e=>{vr(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4<u32>(${t}>${s})`},void 0,void 0,9)},bu=e=>{vr(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4<u32>(${t}<${s})`},void 0,void 0,9)},Su=e=>{vr(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4<u32>(${t}>=${s})`},void 0,void 0,9)},Tu=e=>{vr(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4<u32>(${t}<=${s})`},void 0,void 0,9)}}),Eu,$u,xu,Cu,ku,Ru,Rm=b(()=>{ze(),Me(),A(),_e(),Eu=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let s=0,i=e[s],o=i.dataType,l=i.dims.length;e.forEach((u,c)=>{if(c!==s){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")})}})},$u=(e,t)=>`
|
|
560
|
+
fn calculateInputIndex(index: u32) -> u32 {
|
|
561
|
+
let sizeInConcatAxis = array<u32, ${e}u>(${t});
|
|
562
|
+
for (var i: u32 = 0u; i < ${e}; i += 1u ) {
|
|
563
|
+
if (index < sizeInConcatAxis[i]) {
|
|
564
|
+
return i;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return ${e}u;
|
|
568
|
+
}`,xu=(e,t)=>{let s=e.length,i=[];for(let o=0;o<s;++o){let l=t.setByOffset("global_idx",e[o].getByIndices("indices"));s===1?i.push(l):o===0?i.push(`if (inputIndex == ${o}u) { ${l} }`):o===s-1?i.push(`else { ${l} }`):i.push(`else if (inputIndex == ${o}) { ${l} }`)}return i.join(`
|
|
569
|
+
`)},Cu=(e,t,s,i)=>{let o=j.size(s),l=new Array(e.length),u=new Array(e.length),c=0,h=[],p=[],g=[{type:12,data:o}];for(let C=0;C<e.length;++C)c+=e[C].dims[t],l[C]=c,p.push(e[C].dims.length),u[C]=F(`input${C}`,i,p[C]),h.push("rank"),g.push({type:12,data:l[C]});for(let C=0;C<e.length;++C)g.push(...L(e[C].dims));g.push(...L(s));let m=de("output",i,s.length),w=m.indicesGet("indices",t),_=Array.from(Array(l.length).keys()).map(C=>`uniforms.sizeInConcatAxis${C}`).join(","),S=C=>`
|
|
570
|
+
|
|
571
|
+
${(()=>{C.registerUniform("outputSize","u32");for(let M=0;M<e.length;M++)C.registerUniform(`sizeInConcatAxis${M}`,"u32");return C.declareVariables(...u,m)})()}
|
|
572
|
+
|
|
573
|
+
${$u(l.length,_)}
|
|
574
|
+
|
|
575
|
+
${C.mainStart()}
|
|
576
|
+
${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
577
|
+
|
|
578
|
+
var indices = ${m.offsetToIndices("global_idx")};
|
|
579
|
+
|
|
580
|
+
let inputIndex = calculateInputIndex(${w});
|
|
581
|
+
if (inputIndex != 0u) {
|
|
582
|
+
let sizeInConcatAxis = array<u32, ${l.length}u>(${_});
|
|
583
|
+
${w} -= sizeInConcatAxis[inputIndex - 1u];
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
${xu(u,m)}
|
|
587
|
+
}`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:g}),getShaderSource:S}},ku=(e,t)=>{let s=e.inputs,i=s[0].dims,o=j.normalizeAxis(t.axis,i.length);Eu(s,o);let l=i.slice();l[o]=s.reduce((c,h)=>c+(h.dims.length>o?h.dims[o]:0),0);let u=s.filter(c=>j.size(c.dims)>0);e.compute(Cu(u,o,l,s[0].dataType),{inputs:u})},Ru=e=>E({axis:e.axis})}),Rn,An,In,da,Mn=b(()=>{ze(),Me(),Rn=(e,t,s="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}(${s}(uniforms.clip_min)), ${t}(${s}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${s}(uniforms.alpha) * value + ${s}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${s}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value));
|
|
588
|
+
value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
|
|
589
|
+
`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},An=(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})},In=(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"})},da=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[s,i]=e?.activation_params||[.2,.5];return{activation:t,alpha:s,beta:i}}else if(t==="Clip"){let[s,i]=e?.activation_params||[Rs,hr];return{activation:t,clipMax:i,clipMin:s}}else if(t==="LeakyRelu"){let[s]=e?.activation_params||[.01];return{activation:t,alpha:s}}return{activation:t}}}),Bt,Au,ca=b(()=>{Bt=(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.`)}},Au=e=>`
|
|
590
|
+
${e?"value = value + getBiasByOutputCoords(coords);":""}
|
|
591
|
+
`}),Iu,Am=b(()=>{Iu=e=>`
|
|
592
|
+
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
|
|
593
|
+
return dot(coords, vec4<i32>(
|
|
594
|
+
shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
|
|
595
|
+
}
|
|
596
|
+
fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
|
|
597
|
+
return dot(coords, vec4<i32>(
|
|
598
|
+
i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));
|
|
599
|
+
}
|
|
600
|
+
`}),Vs,ha,pa=b(()=>{ze(),Me(),_e(),Mn(),Vs=(e,t,s,i,o)=>{let l=i-s;return`
|
|
601
|
+
${Array.from({length:s}).map((u,c)=>`
|
|
602
|
+
if (${K(t.shape,c,t.rank)} != 1) {
|
|
603
|
+
${t.indicesSet(e,c,K(o,c+l,i))}
|
|
604
|
+
} else {
|
|
605
|
+
${t.indicesSet(e,c,0)}
|
|
606
|
+
}`).join("")}
|
|
607
|
+
`},ha=(e,t,s,i,o=!1,l)=>{let u=e[0].dims,c=e[1].dims,h=u[u.length-2],p=c[c.length-1],g=u[u.length-1],m=V(p),w=V(g),_=V(h),S=j.size(s)/m/_,C=e.length>2,M=i?i.slice(0,-2):s.slice(0,-2),k=[j.size(M),h,p],x=[{type:12,data:S},{type:12,data:h},{type:12,data:p},{type:12,data:g}];An(t,x),x.push(...L(M,u,c)),C&&x.push(...L(e[2].dims)),x.push(...L(k));let O=I=>{let z=qe("batch_dims",e[0].dataType,M.length),W=F("a",e[0].dataType,u.length,w),q=F("b",e[1].dataType,c.length,m),J=de("output",e[0].dataType,k.length,m),oe=G(J.type.tensor),ge=Rn(t,J.type.value,oe),Qe=[W,q],Ae="";if(C){let we=o?m:1;Qe.push(F("bias",e[2].dataType,e[2].dims.length,we)),Ae=`${o?`value += bias[col / ${we}];`:`value += ${J.type.value}(bias[row + i]);`}`}let Be=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];In(t,Be);let ut=()=>{let we=`var a_data: ${W.type.value};`;for(let ke=0;ke<w;ke++)we+=`
|
|
608
|
+
let b_data${ke} = b[(b_offset + (k + ${ke}) * uniforms.N + col) / ${m}];`;for(let ke=0;ke<_;ke++){we+=`a_data = a[(a_offset + (row + ${ke}) * uniforms.K + k) / ${w}];`;for(let Xe=0;Xe<w;Xe++)we+=`
|
|
609
|
+
values[${ke}] = fma(${q.type.value}(a_data${w===1?"":`[${Xe}]`}), b_data${Xe}, values[${ke}]);
|
|
610
|
+
`}return we};return`
|
|
611
|
+
${I.registerUniforms(Be).registerInternalVariables(z).declareVariables(...Qe,J)}
|
|
612
|
+
${I.mainStart()}
|
|
613
|
+
${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
614
|
+
let col = (global_idx % (uniforms.N / ${m})) * ${m};
|
|
615
|
+
var index1 = global_idx / (uniforms.N / ${m});
|
|
616
|
+
let stride1 = uniforms.M / ${_};
|
|
617
|
+
let row = (index1 % stride1) * ${_};
|
|
618
|
+
let batch = index1 / stride1;
|
|
619
|
+
|
|
620
|
+
${s.length===2?"":`let batch_indices = ${z.offsetToIndices("batch")};`}
|
|
621
|
+
|
|
622
|
+
var a_indices: ${W.type.indices};
|
|
623
|
+
${Vs("a_indices",W,W.rank-2,z.rank,"batch_indices")}
|
|
624
|
+
${W.indicesSet("a_indices",W.rank-2,0)}
|
|
625
|
+
${W.indicesSet("a_indices",W.rank-1,0)}
|
|
626
|
+
let a_offset = ${W.indicesToOffset("a_indices")};
|
|
627
|
+
|
|
628
|
+
var b_indices: ${q.type.indices};
|
|
629
|
+
${Vs("b_indices",q,q.rank-2,z.rank,"batch_indices")}
|
|
630
|
+
${q.indicesSet("b_indices",q.rank-2,0)}
|
|
631
|
+
${q.indicesSet("b_indices",q.rank-1,0)}
|
|
632
|
+
let b_offset = ${q.indicesToOffset("b_indices")};
|
|
633
|
+
var values: array<${J.type.value}, ${_}>;
|
|
634
|
+
for (var k: u32 = 0u; k < uniforms.K; k = k + ${w}) {
|
|
635
|
+
${ut()}
|
|
636
|
+
}
|
|
637
|
+
for (var i = 0u; i < ${_}u; i++) {
|
|
638
|
+
var value = values[i];
|
|
639
|
+
${Ae}
|
|
640
|
+
${ge}
|
|
641
|
+
let cur_indices = ${J.type.indices}(batch, row + i, col);
|
|
642
|
+
let offset = ${J.indicesToOffset("cur_indices")};
|
|
643
|
+
${J.setByOffset(`offset / ${m}`,"value")};
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
`};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${m};${w};${_};${o}`,inputDependencies:C?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:l?l(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:x}),getShaderSource:O}}}),Mu,Pu,fa,ma,Ou,ga,Du,Si,ya=b(()=>{ze(),Me(),_e(),Mn(),pa(),ca(),Mu=(e,t)=>e?`
|
|
647
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
648
|
+
kStart + inputRow,
|
|
649
|
+
globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});
|
|
650
|
+
`:`
|
|
651
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
652
|
+
globalRow + innerRow,
|
|
653
|
+
kStart / innerElementSize + inputCol${t?", batchIndices":""});
|
|
654
|
+
`,Pu=(e,t)=>e?`
|
|
655
|
+
let ACached0 = mm_Asub[k * innerElementSize][localRow];
|
|
656
|
+
let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];
|
|
657
|
+
let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];
|
|
658
|
+
${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}
|
|
659
|
+
for (var i = 0; i < rowPerThread; i = i + 1) {
|
|
660
|
+
acc[i] = BCached0 * ACached0[i] + acc[i];
|
|
661
|
+
acc[i] = BCached1 * ACached1[i] + acc[i];
|
|
662
|
+
acc[i] = BCached2 * ACached2[i] + acc[i];
|
|
663
|
+
${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}
|
|
664
|
+
}`:`
|
|
665
|
+
for (var i = 0; i < rowPerThread; i = i + 1) {
|
|
666
|
+
let ACached = mm_Asub[tileRow + i][k];
|
|
667
|
+
acc[i] = BCached0 * ACached.x + acc[i];
|
|
668
|
+
acc[i] = BCached1 * ACached.y + acc[i];
|
|
669
|
+
acc[i] = BCached2 * ACached.z + acc[i];
|
|
670
|
+
${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}
|
|
671
|
+
}`,fa=(e,t,s="f32",i,o=!1,l=32,u=!1,c=32)=>{let h=t[1]*e[1],p=t[0]*e[0],g=o?h:l,m=o?l:h,w=g/t[0],_=l/t[1];if(!((o&&w===4&&e[1]===4||!o&&(w===3||w===4))&&g%t[0]===0&&l%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${w} and workPerThread[1] ${e[1]} must be 4.
|
|
672
|
+
Otherwise, innerElementSize ${w} must be 3 or 4.
|
|
673
|
+
tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}. tileInner ${l} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`
|
|
674
|
+
var<workgroup> mm_Asub: array<array<vec${w}<${s}>, ${g/w}>, ${m}>;
|
|
675
|
+
var<workgroup> mm_Bsub: array<array<vec4<${s}>, ${p/e[0]}>, ${l}>;
|
|
676
|
+
|
|
677
|
+
const rowPerThread = ${e[1]};
|
|
678
|
+
const colPerThread = ${e[0]};
|
|
679
|
+
const innerElementSize = ${w};
|
|
680
|
+
const tileInner = ${l};
|
|
681
|
+
|
|
682
|
+
@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})
|
|
683
|
+
fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
684
|
+
@builtin(global_invocation_id) globalId : vec3<u32>,
|
|
685
|
+
@builtin(workgroup_id) workgroupId : vec3<u32>) {
|
|
686
|
+
let localRow = i32(localId.y);
|
|
687
|
+
let tileRow = localRow * rowPerThread;
|
|
688
|
+
let tileCol = i32(localId.x);
|
|
689
|
+
|
|
690
|
+
let globalRow =i32(globalId.y) * rowPerThread;
|
|
691
|
+
let globalCol = i32(globalId.x);
|
|
692
|
+
let batch = ${u?"0":"i32(globalId.z)"};
|
|
693
|
+
${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""}
|
|
694
|
+
let globalRowStart = i32(workgroupId.y) * ${h};
|
|
695
|
+
|
|
696
|
+
let num_tiles = ${u?`${Math.ceil(c/l)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
|
|
697
|
+
var kStart = ${u?`i32(globalId.z) * ${c}`:"0"};
|
|
698
|
+
|
|
699
|
+
var acc: array<vec4<${s}>, rowPerThread>;
|
|
700
|
+
|
|
701
|
+
// Loop over shared dimension.
|
|
702
|
+
let tileRowB = localRow * ${_};
|
|
703
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
704
|
+
// Load one tile of A into local memory.
|
|
705
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
706
|
+
let inputRow = tileRow + innerRow;
|
|
707
|
+
let inputCol = tileCol;
|
|
708
|
+
${Mu(o,i)}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// Load one tile of B into local memory.
|
|
712
|
+
for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {
|
|
713
|
+
let inputRow = tileRowB + innerRow;
|
|
714
|
+
let inputCol = tileCol;
|
|
715
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${i?", batchIndices":""});
|
|
716
|
+
}
|
|
717
|
+
kStart = kStart + tileInner;
|
|
718
|
+
workgroupBarrier();
|
|
719
|
+
|
|
720
|
+
// Compute acc values for a single thread.
|
|
721
|
+
for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {
|
|
722
|
+
let BCached0 = mm_Bsub[k * innerElementSize][tileCol];
|
|
723
|
+
let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];
|
|
724
|
+
let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];
|
|
725
|
+
${w===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}
|
|
726
|
+
|
|
727
|
+
${Pu(o,w)}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
workgroupBarrier();
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
734
|
+
mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
|
|
735
|
+
}
|
|
736
|
+
}`},ma=(e,t)=>e?`
|
|
737
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
738
|
+
kStart + inputRow,
|
|
739
|
+
globalRowStart + inputCol${t?", batchIndices":""});
|
|
740
|
+
`:`
|
|
741
|
+
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
742
|
+
globalRowStart + inputRow,
|
|
743
|
+
kStart + inputCol${t?", batchIndices":""});
|
|
744
|
+
`,Ou=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ga=(e,t,s="f32",i,o=!1,l=32,u=!1,c=32,h=!1)=>{let p=e[1]*t[1],g=e[0]*t[0],m=o?p:l,w=o?l:p;if(!(w%t[1]===0&&m%t[0]===0&&l%t[1]===0))throw new Error(`tileAHight ${w} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}, tileInner ${l} must be divisible by workgroupSize[1]${t[1]}`);let _=w/t[1],S=m/t[0],C=l/t[1],M=h?`
|
|
745
|
+
let localRow = i32(localId.y);
|
|
746
|
+
let localCol = i32(localId.x);
|
|
747
|
+
let globalRowStart = i32(workgroupId.y) * ${p};
|
|
748
|
+
let globalColStart = i32(workgroupId.x) * ${g};
|
|
749
|
+
|
|
750
|
+
// Loop over shared dimension.
|
|
751
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
752
|
+
// Load one tile of A into local memory.
|
|
753
|
+
for (var inputRow = localRow; inputRow < ${w}; inputRow = inputRow + ${t[1]}) {
|
|
754
|
+
for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) {
|
|
755
|
+
${ma(o,i)}
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
// Load one tile of B into local memory.
|
|
759
|
+
for (var inputRow = localRow; inputRow < ${l}; inputRow = inputRow + ${t[1]}) {
|
|
760
|
+
for (var inputCol = localCol; inputCol < ${g}; inputCol = inputCol + ${t[0]}) {
|
|
761
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch,
|
|
762
|
+
kStart + inputRow,
|
|
763
|
+
globalColStart + inputCol${i?", batchIndices":""});
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
kStart = kStart + tileInner;
|
|
767
|
+
workgroupBarrier();
|
|
768
|
+
|
|
769
|
+
// Compute acc values for a single thread.
|
|
770
|
+
var BCached : array<${s}, colPerThread>;
|
|
771
|
+
for (var k = 0; k < tileInner; k = k + 1) {
|
|
772
|
+
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
|
|
773
|
+
BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];
|
|
774
|
+
}
|
|
775
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
776
|
+
let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}
|
|
777
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
778
|
+
acc[innerRow][innerCol] = acc[innerRow][innerCol] +
|
|
779
|
+
ACached * BCached[innerCol];
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
workgroupBarrier();
|
|
784
|
+
}
|
|
785
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
786
|
+
let gRow = globalRowStart + localRow + innerRow * ${t[1]};
|
|
787
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
788
|
+
let gCol = globalColStart + localCol + innerCol * ${t[0]};
|
|
789
|
+
mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
`:`
|
|
793
|
+
let tileRow = i32(localId.y) * rowPerThread;
|
|
794
|
+
let tileCol = i32(localId.x) * colPerThread;
|
|
795
|
+
|
|
796
|
+
let globalRow = i32(globalId.y) * rowPerThread;
|
|
797
|
+
let globalCol = i32(globalId.x) * colPerThread;
|
|
798
|
+
let globalRowStart = i32(workgroupId.y) * ${p};
|
|
799
|
+
|
|
800
|
+
let tileRowA = i32(localId.y) * ${_};
|
|
801
|
+
let tileColA = i32(localId.x) * ${S};
|
|
802
|
+
let tileRowB = i32(localId.y) * ${C};
|
|
803
|
+
// Loop over shared dimension.
|
|
804
|
+
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
805
|
+
// Load one tile of A into local memory.
|
|
806
|
+
for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {
|
|
807
|
+
for (var innerCol = 0; innerCol < ${S}; innerCol = innerCol + 1) {
|
|
808
|
+
let inputRow = tileRowA + innerRow;
|
|
809
|
+
let inputCol = tileColA + innerCol;
|
|
810
|
+
${ma(o,i)}
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
// Load one tile of B into local memory.
|
|
815
|
+
for (var innerRow = 0; innerRow < ${C}; innerRow = innerRow + 1) {
|
|
816
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
817
|
+
let inputRow = tileRowB + innerRow;
|
|
818
|
+
let inputCol = tileCol + innerCol;
|
|
819
|
+
mm_Bsub[inputRow][inputCol] = mm_readB(batch,
|
|
820
|
+
kStart + inputRow,
|
|
821
|
+
globalCol + innerCol${i?", batchIndices":""});
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
kStart = kStart + tileInner;
|
|
825
|
+
workgroupBarrier();
|
|
826
|
+
|
|
827
|
+
// Compute acc values for a single thread.
|
|
828
|
+
var BCached : array<${s}, colPerThread>;
|
|
829
|
+
for (var k = 0; k < tileInner; k = k + 1) {
|
|
830
|
+
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
|
|
831
|
+
BCached[inner] = mm_Bsub[k][tileCol + inner];
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
835
|
+
${Ou(o)}
|
|
836
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
837
|
+
acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
workgroupBarrier();
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
846
|
+
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
|
|
847
|
+
mm_write(batch, globalRow + innerRow, globalCol + innerCol,
|
|
848
|
+
acc[innerRow][innerCol]);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
`;return`
|
|
852
|
+
var<workgroup> mm_Asub : array<array<${s}, ${m}>, ${w}>;
|
|
853
|
+
var<workgroup> mm_Bsub : array<array<${s}, ${g}>, ${l}>;
|
|
854
|
+
const rowPerThread = ${e[1]};
|
|
855
|
+
const colPerThread = ${e[0]};
|
|
856
|
+
const tileInner = ${l};
|
|
857
|
+
|
|
858
|
+
@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})
|
|
859
|
+
fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
860
|
+
@builtin(global_invocation_id) globalId : vec3<u32>,
|
|
861
|
+
@builtin(workgroup_id) workgroupId : vec3<u32>) {
|
|
862
|
+
let batch = ${u?"0":"i32(globalId.z)"};
|
|
863
|
+
${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""}
|
|
864
|
+
let num_tiles = ${u?`${Math.ceil(c/l)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
|
|
865
|
+
var kStart = ${u?`i32(globalId.z) * ${c}`:"0"};
|
|
866
|
+
|
|
867
|
+
var acc : array<array<${s}, colPerThread>, rowPerThread>;
|
|
868
|
+
${M}
|
|
869
|
+
}
|
|
870
|
+
`},Du=(e,t,s,i,o=!1)=>{let[l,u,c,h]=i,p=G(i[0].type.tensor);return`
|
|
871
|
+
fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${l.type.indices}) -> ${Bt(e,p)} {
|
|
872
|
+
var value = ${Bt(e,p)}(0.0);
|
|
873
|
+
let col = colIn * ${e};
|
|
874
|
+
if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)
|
|
875
|
+
{
|
|
876
|
+
var aIndices: ${u.type.indices};
|
|
877
|
+
${Vs("aIndices",u,u.rank-2,l.rank,"batchIndices")}
|
|
878
|
+
${u.indicesSet("aIndices",u.rank-2,"u32(row)")}
|
|
879
|
+
${u.indicesSet("aIndices",u.rank-1,"u32(colIn)")}
|
|
880
|
+
value = ${u.getByIndices("aIndices")};
|
|
881
|
+
}
|
|
882
|
+
return value;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${l.type.indices}) -> ${Bt(e,p)} {
|
|
886
|
+
var value = ${Bt(e,p)}(0.0);
|
|
887
|
+
let col = colIn * ${e};
|
|
888
|
+
if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)
|
|
889
|
+
{
|
|
890
|
+
var bIndices: ${c.type.indices};
|
|
891
|
+
${Vs("bIndices",c,c.rank-2,l.rank,"batchIndices")}
|
|
892
|
+
${c.indicesSet("bIndices",c.rank-2,"u32(row)")}
|
|
893
|
+
${c.indicesSet("bIndices",c.rank-1,"u32(colIn)")}
|
|
894
|
+
value = ${c.getByIndices("bIndices")};
|
|
895
|
+
}
|
|
896
|
+
return value;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Bt(e,p)}) {
|
|
900
|
+
let col = colIn * ${e};
|
|
901
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {
|
|
902
|
+
var value = valueIn;
|
|
903
|
+
let coords = vec3<i32>(batch, row, colIn);
|
|
904
|
+
${t?`value = value + ${o?"bias[colIn]":`${Bt(e,p)}(bias[row])`};`:""}
|
|
905
|
+
${s}
|
|
906
|
+
${h.setByIndices("vec3<u32>(coords)","value")}
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
`},Si=(e,t,s,i,o=!1,l)=>{let u=e[0].dims,c=e[1].dims,h=u.slice(0,-2),p=c.slice(0,-2),g=i?i.slice(0,-2):s.slice(0,-2),m=j.size(g),w=u[u.length-2],_=u[u.length-1],S=c[c.length-1],C=_%4===0&&S%4===0,M=w<=8?[4,1,1]:[4,4,1],k=[8,8,1],x=[Math.ceil(S/k[0]/M[0]),Math.ceil(w/k[1]/M[1]),Math.ceil(m/k[2]/M[2])],O=C?4:1,I=[...h,w,_/O],z=I.length,W=[...p,_,S/O],q=W.length,J=[m,w,S/O],oe=[{type:6,data:w},{type:6,data:S},{type:6,data:_}];An(t,oe),oe.push(...L(g,I,W));let ge=["rank","rank"],Qe=e.length>2;Qe&&(oe.push(...L(e[2].dims)),ge.push("rank")),oe.push(...L(J));let Ae=Be=>{let ut=g.length,we=qe("batchDims",e[0].dataType,ut,1),ke=G(e[0].dataType),Xe=F("a",e[0].dataType,z,O),Ve=F("b",e[1].dataType,q,O),Ue=de("result",e[0].dataType,J.length,O),ct=[Xe,Ve];if(Qe){let _r=o?O:1;ct.push(F("bias",e[2].dataType,e[2].dims.length,_r))}let se=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];In(t,se);let ve=G(Ue.type.tensor),Ge=Rn(t,Ue.type.value,ve),ht=Du(O,Qe,Ge,[we,Xe,Ve,Ue],o);return`
|
|
910
|
+
${Be.registerUniforms(se).registerInternalVariables(we).declareVariables(...ct,Ue)}
|
|
911
|
+
${ht}
|
|
912
|
+
${C?fa(M,k,ke,we):ga(M,k,ke,we)}
|
|
913
|
+
`};return{name:"MatMul",shaderCache:{hint:`${M};${t.activation};${C};${o}`,inputDependencies:ge},getRunData:()=>({outputs:[{dims:l?l(s):s,dataType:e[0].dataType}],dispatchGroup:{x:x[0],y:x[1],z:x[2]},programUniforms:oe}),getShaderSource:Ae}}}),zu,Lu,Im=b(()=>{ze(),rr(),_e(),Mn(),ca(),Am(),ya(),zu=(e,t,s,i,o=!1,l,u=4,c=4,h=4,p="f32")=>{let g=oe=>{switch(oe){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 ${oe} is not supported.`)}},m=oe=>{switch(oe){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 ${oe} is not supported.`)}},w=e?`
|
|
914
|
+
let coord = vec4<i32>(batch, xRow, xCol, xCh);
|
|
915
|
+
`:`
|
|
916
|
+
let coord = vec4<i32>(batch, xCh, xRow, xCol);
|
|
917
|
+
`,_=e?`
|
|
918
|
+
let coords = vec4<i32>(
|
|
919
|
+
batch,
|
|
920
|
+
row / outWidth,
|
|
921
|
+
row % outWidth,
|
|
922
|
+
col);
|
|
923
|
+
`:`
|
|
924
|
+
let coords = vec4<i32>(
|
|
925
|
+
batch,
|
|
926
|
+
row,
|
|
927
|
+
col / outWidth,
|
|
928
|
+
col % outWidth);
|
|
929
|
+
`,S=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",C=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",M=e?"row":"col",k=e?"col":"row",x=`
|
|
930
|
+
let inChannels = i32(uniforms.w_shape[2]);
|
|
931
|
+
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
|
|
932
|
+
let outRow = ${M} / outWidth;
|
|
933
|
+
let outCol = ${M} % outWidth;
|
|
934
|
+
|
|
935
|
+
let WRow = ${k} / (i32(uniforms.w_shape[1]) * inChannels);
|
|
936
|
+
let WCol = ${k} / inChannels % i32(uniforms.w_shape[1]);
|
|
937
|
+
let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];
|
|
938
|
+
let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];
|
|
939
|
+
let xCh = ${k} % inChannels;
|
|
940
|
+
var resData = ${Bt(u,p)}(0.0);
|
|
941
|
+
// The bounds checking is always needed since we use it to pad zero for
|
|
942
|
+
// the 'same' padding type.
|
|
943
|
+
if (xRow >= 0 && xRow < ${S} && xCol >= 0 && xCol < ${C}) {
|
|
944
|
+
${w}
|
|
945
|
+
let xIndex = getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape));
|
|
946
|
+
${g(u)}
|
|
947
|
+
}
|
|
948
|
+
return resData;`,O=e?t&&i?`
|
|
949
|
+
let col = colIn * ${u};
|
|
950
|
+
${x}`:`
|
|
951
|
+
let col = colIn * ${u};
|
|
952
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {
|
|
953
|
+
${x}
|
|
954
|
+
}
|
|
955
|
+
return ${Bt(u,p)}(0.0);`:i&&s?`
|
|
956
|
+
let col = colIn * ${u};
|
|
957
|
+
${x}`:`
|
|
958
|
+
let col = colIn * ${u};
|
|
959
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
|
|
960
|
+
${x}
|
|
961
|
+
}
|
|
962
|
+
return ${Bt(u,p)}(0.0);`,I=e?i&&s?m(c):`
|
|
963
|
+
let col = colIn * ${c};
|
|
964
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
|
|
965
|
+
${m(c)}
|
|
966
|
+
}
|
|
967
|
+
return ${Bt(c,p)}(0.0);`:`
|
|
968
|
+
let col = colIn * ${c};
|
|
969
|
+
if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {
|
|
970
|
+
${m(c)}
|
|
971
|
+
}
|
|
972
|
+
return ${Bt(c,p)}(0.0);`,z=Bt(h,p),W=Bt(e?u:c,p),q=Bt(e?c:u,p),J=Rn(l,z,p);return`
|
|
973
|
+
fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${W} {
|
|
974
|
+
${e?O:I}
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${q} {
|
|
978
|
+
${e?I:O}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${z}) {
|
|
982
|
+
let col = colIn * ${h};
|
|
983
|
+
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)
|
|
984
|
+
{
|
|
985
|
+
var value = valueIn;
|
|
986
|
+
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
|
|
987
|
+
${_}
|
|
988
|
+
${Au(o)}
|
|
989
|
+
${J}
|
|
990
|
+
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
|
|
991
|
+
}
|
|
992
|
+
}`},Lu=(e,t,s,i,o,l,u,c,h)=>{let p=t.format==="NHWC",g=p?e[0].dims[3]:e[0].dims[1],m=s[0],w=p?s[2]:s[3],_=p?s[1]:s[2],S=p?s[3]:s[1],C=p&&(g%4===0||g%3===0)&&S%4===0,M=p?S:w*_,k=p?w*_:S,x=[8,8,1],O=i<=8?[4,1,1]:[4,4,1],I=[Math.ceil(M/x[0]/O[0]),Math.ceil(k/x[1]/O[1]),Math.ceil(m/x[2]/O[2])];Je("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${I}`);let z=C?p&&g%4!==0?3:4:1,W=x[1]*O[1],q=x[0]*O[0],J=Math.max(x[0]*z,x[1]),oe=i%W===0,ge=o%q===0,Qe=l%J===0,Ae=C?[z,4,4]:[1,1,1],Be=[{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}];An(t,Be),Be.push(...L(e[0].dims,e[1].dims));let ut=["rank","rank"];u&&(Be.push(...L(e[2].dims)),ut.push("rank")),Be.push(...L(s));let we=ke=>{let Xe=[{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}];In(t,Xe);let Ve=C?4:1,Ue=G(e[0].dataType),ct=`
|
|
993
|
+
fn setOutputAtIndex(flatIndex : i32, value : ${C?`vec4<${Ue}>`:Ue}) {
|
|
994
|
+
result[flatIndex] = ${C?`vec4<${Ue}>`:Ue}(value);
|
|
995
|
+
}
|
|
996
|
+
fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${C?`vec4<${Ue}>`:Ue}) {
|
|
997
|
+
let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));
|
|
998
|
+
setOutputAtIndex(flatIndex ${C?"/ 4":""}, value);
|
|
999
|
+
}`,se=F("x",e[0].dataType,e[0].dims.length,z===3?1:z),ve=F("w",e[1].dataType,e[1].dims.length,Ve),Ge=[se,ve],ht=de("result",e[0].dataType,s.length,Ve);if(u){let _r=F("bias",e[2].dataType,e[2].dims.length,Ve);Ge.push(_r),ct+=`
|
|
1000
|
+
fn getBiasByOutputCoords(coords : vec4<i32>) -> ${C?`vec4<${Ue}>`:Ue} {
|
|
1001
|
+
return bias[coords.${p?"w":"y"}${C?"/ 4":""}];
|
|
1002
|
+
}`}return`
|
|
1003
|
+
${Iu("uniforms.result_strides")}
|
|
1004
|
+
//struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>,
|
|
1005
|
+
// outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>,
|
|
1006
|
+
// dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };
|
|
1007
|
+
${ke.registerUniforms(Xe).declareVariables(...Ge,ht)}
|
|
1008
|
+
${ct}
|
|
1009
|
+
${zu(p,oe,ge,Qe,u,t,Ae[0],Ae[1],Ae[2],Ue)}
|
|
1010
|
+
${C?fa(O,x,Ue,void 0,!p,J):ga(O,x,Ue,void 0,!p,J,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${z};${C};${oe};${ge};${Qe};${W};${q};${J}`,inputDependencies:ut},getRunData:()=>({outputs:[{dims:h?h(s):s,dataType:e[0].dataType}],dispatchGroup:{x:I[0],y:I[1],z:I[2]},programUniforms:Be}),getShaderSource:we}}}),Bu,wa,Gs,Nu,va,Uu,Fu,Vu,Mm=b(()=>{ze(),rr(),Me(),_e(),Mn(),ca(),Bu=e=>{let t=1;for(let s=0;s<e.length;s++)t*=e[s];return t},wa=e=>typeof e=="number"?[e,e,e]:e,Gs=(e,t)=>t<=1?e:e+(e-1)*(t-1),Nu=(e,t,s,i=1)=>{let o=Gs(t,i);return Math.floor((e[0]*(s-1)-s+o)/2)},va=(e,t,s,i,o)=>{o==null&&(o=Nu(e,t[0],i[0]));let l=[0,0,0,s];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},Uu=(e,t,s,i,o,l,u,c,h,p)=>{let g,m,w,_;if(e==="VALID"&&(e=0),typeof e=="number"){g={top:e,bottom:e,left:e,right:e,front:e,back:e};let S=va([t,s,i,1],[c,h,p],1,[o,l,u],e);m=S[0],w=S[1],_=S[2]}else if(Array.isArray(e)){if(!e.every((C,M,k)=>C===k[0]))throw Error(`Unsupported padding parameter: ${e}`);g={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let S=va([t,s,i,1],[c,h,p],1,[o,l,u],e[0]);m=S[0],w=S[1],_=S[2]}else if(e==="SAME_UPPER"){m=Math.ceil(t/o),w=Math.ceil(s/l),_=Math.ceil(i/u);let S=(m-1)*o+c-t,C=(w-1)*l+h-s,M=(_-1)*u+p-i,k=Math.floor(S/2),x=S-k,O=Math.floor(C/2),I=C-O,z=Math.floor(M/2),W=M-z;g={top:O,bottom:I,left:z,right:W,front:k,back:x}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:g,outDepth:m,outHeight:w,outWidth:_}},Fu=(e,t,s,i,o,l=!1,u="channelsLast")=>{let c,h,p,g,m;if(u==="channelsLast")[c,h,p,g,m]=e;else if(u==="channelsFirst")[c,m,h,p,g]=e;else throw new Error(`Unknown dataFormat ${u}`);let[w,,_,S,C]=t,[M,k,x]=wa(s),[O,I,z]=wa(i),W=Gs(_,O),q=Gs(S,I),J=Gs(C,z),{padInfo:oe,outDepth:ge,outHeight:Qe,outWidth:Ae}=Uu(o,h,p,g,M,k,x,W,q,J),Be=l?w*m:w,ut=[0,0,0,0,0];return u==="channelsFirst"?ut=[c,Be,ge,Qe,Ae]:u==="channelsLast"&&(ut=[c,ge,Qe,Ae,Be]),{batchSize:c,dataFormat:u,inDepth:h,inHeight:p,inWidth:g,inChannels:m,outDepth:ge,outHeight:Qe,outWidth:Ae,outChannels:Be,padInfo:oe,strideDepth:M,strideHeight:k,strideWidth:x,filterDepth:_,filterHeight:S,filterWidth:C,effectiveFilterDepth:W,effectiveFilterHeight:q,effectiveFilterWidth:J,dilationDepth:O,dilationHeight:I,dilationWidth:z,inShape:e,outShape:ut,filterShape:t}},Vu=(e,t,s,i,o,l)=>{let u=l==="channelsLast";u?e[0].dims[3]:e[0].dims[1];let c=[64,1,1],h={x:s.map((M,k)=>k)},p=[Math.ceil(Bu(h.x.map(M=>s[M]))/c[0]),1,1];Je("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${p}`);let g=1,m=j.size(s),w=[{type:12,data:m},{type:12,data:i},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];An(t,w),w.push(...L(e[0].dims,e[1].dims));let _=["rank","rank"],S=e.length===3;S&&(w.push(...L(e[2].dims)),_.push("rank")),w.push(...L(s));let C=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}];In(t,k);let x=1,O=G(e[0].dataType),I=F("x",e[0].dataType,e[0].dims.length,g),z=F("W",e[1].dataType,e[1].dims.length,x),W=[I,z],q=de("result",e[0].dataType,s.length,x),J="";if(S){let Qe=F("bias",e[2].dataType,e[2].dims.length,x);W.push(Qe),J+=`
|
|
1011
|
+
fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${O} {
|
|
1012
|
+
return bias[${u?K("coords",4,5):K("coords",1,5)}];
|
|
1013
|
+
}`}let oe=Bt(g,O),ge=Rn(t,oe,O);return`
|
|
1014
|
+
${J}
|
|
1015
|
+
fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
|
|
1016
|
+
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
|
|
1017
|
+
return ${I.getByIndices("aIndices")};
|
|
1018
|
+
}
|
|
1019
|
+
fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
|
|
1020
|
+
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
|
|
1021
|
+
return ${z.getByIndices("aIndices")};
|
|
1022
|
+
}
|
|
1023
|
+
${M.registerUniforms(k).declareVariables(...W,q)}
|
|
1024
|
+
${M.mainStart()}
|
|
1025
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1026
|
+
let coords = ${q.offsetToIndices("global_idx")};
|
|
1027
|
+
let batch = ${K("coords",0,I.rank)};
|
|
1028
|
+
let d2 = ${u?K("coords",I.rank-1,I.rank):K("coords",1,I.rank)};
|
|
1029
|
+
let xFRCCorner = vec3<u32>(${u?K("coords",1,I.rank):K("coords",2,I.rank)},
|
|
1030
|
+
${u?K("coords",2,I.rank):K("coords",3,I.rank)},
|
|
1031
|
+
${u?K("coords",3,I.rank):K("coords",4,I.rank)}) * uniforms.strides - uniforms.pads;
|
|
1032
|
+
let xFCorner = xFRCCorner.x;
|
|
1033
|
+
let xRCorner = xFRCCorner.y;
|
|
1034
|
+
let xCCorner = xFRCCorner.z;
|
|
1035
|
+
let xShapeY = ${u?K("uniforms.x_shape",1,I.rank):K("uniforms.x_shape",2,I.rank)};
|
|
1036
|
+
let xShapeZ = ${u?K("uniforms.x_shape",2,I.rank):K("uniforms.x_shape",3,I.rank)};
|
|
1037
|
+
let xShapeW = ${u?K("uniforms.x_shape",3,I.rank):K("uniforms.x_shape",4,I.rank)};
|
|
1038
|
+
let xShapeU = ${u?K("uniforms.x_shape",4,I.rank):K("uniforms.x_shape",1,I.rank)};
|
|
1039
|
+
let inputDepthNearestVec4 = (xShapeU / 4) * 4;
|
|
1040
|
+
let inputDepthVec4Remainder = xShapeU % 4;
|
|
1041
|
+
|
|
1042
|
+
var value = 0.0;
|
|
1043
|
+
for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {
|
|
1044
|
+
let xF = xFCorner + wF * uniforms.dilations[0];
|
|
1045
|
+
if (xF < 0 || xF >= xShapeY) {
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {
|
|
1050
|
+
let xR = xRCorner + wR * uniforms.dilations[1];
|
|
1051
|
+
if (xR < 0 || xR >= xShapeZ) {
|
|
1052
|
+
continue;
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {
|
|
1056
|
+
let xC = xCCorner + wC * uniforms.dilations[2];
|
|
1057
|
+
if (xC < 0 || xC >= xShapeW) {
|
|
1058
|
+
continue;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {
|
|
1062
|
+
${u?`let xValues = vec4<f32>(
|
|
1063
|
+
getX(batch, xF, xR, xC, d1),
|
|
1064
|
+
getX(batch, xF, xR, xC, d1 + 1),
|
|
1065
|
+
getX(batch, xF, xR, xC, d1 + 2),
|
|
1066
|
+
getX(batch, xF, xR, xC, d1 + 3));
|
|
1067
|
+
`:`let xValues = vec4<f32>(
|
|
1068
|
+
getX(batch, d1, xF, xR, xC),
|
|
1069
|
+
getX(batch, d1 + 1, xF, xR, xC),
|
|
1070
|
+
getX(batch, d1 + 2, xF, xR, xC),
|
|
1071
|
+
getX(batch, d1 + 3, xF, xR, xC));
|
|
1072
|
+
`}
|
|
1073
|
+
let wValues = vec4<f32>(
|
|
1074
|
+
getW(d2, d1, wF, wR, wC),
|
|
1075
|
+
getW(d2, d1 + 1, wF, wR, wC),
|
|
1076
|
+
getW(d2, d1 + 2, wF, wR, wC),
|
|
1077
|
+
getW(d2, d1 + 3, wF, wR, wC));
|
|
1078
|
+
value += dot(xValues, wValues);
|
|
1079
|
+
}
|
|
1080
|
+
if (inputDepthVec4Remainder == 1) {
|
|
1081
|
+
${u?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4)
|
|
1082
|
+
* getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC)
|
|
1083
|
+
* getW(d2, inputDepthNearestVec4, wF, wR, wC);`}
|
|
1084
|
+
} else if (inputDepthVec4Remainder == 2) {
|
|
1085
|
+
${u?`let xValues = vec2<f32>(
|
|
1086
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4),
|
|
1087
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));
|
|
1088
|
+
`:`let xValues = vec2<f32>(
|
|
1089
|
+
getX(batch, inputDepthNearestVec4, xF, xR, xC),
|
|
1090
|
+
getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));
|
|
1091
|
+
`}
|
|
1092
|
+
let wValues = vec2<f32>(
|
|
1093
|
+
getW(d2, inputDepthNearestVec4, wF, wR, wC),
|
|
1094
|
+
getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));
|
|
1095
|
+
value += dot(xValues, wValues);
|
|
1096
|
+
} else if (inputDepthVec4Remainder == 3) {
|
|
1097
|
+
${u?`let xValues = vec3<f32>(
|
|
1098
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4),
|
|
1099
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),
|
|
1100
|
+
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));
|
|
1101
|
+
`:`let xValues = vec3<f32>(
|
|
1102
|
+
getX(batch, inputDepthNearestVec4, xF, xR, xC),
|
|
1103
|
+
getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),
|
|
1104
|
+
getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));
|
|
1105
|
+
`}
|
|
1106
|
+
let wValues = vec3<f32>(
|
|
1107
|
+
getW(d2, inputDepthNearestVec4, wF, wR, wC),
|
|
1108
|
+
getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),
|
|
1109
|
+
getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));
|
|
1110
|
+
value += dot(xValues, wValues);
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
${S?"value = value + getBiasByOutputCoords(coords)":""};
|
|
1116
|
+
${ge}
|
|
1117
|
+
result[global_idx] = f32(value);
|
|
1118
|
+
}`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${u};${g};${S}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:p[0],y:p[1],z:p[2]},programUniforms:w}),getShaderSource:C}}}),Gu,qu,Pm=b(()=>{ze(),Me(),_e(),Mn(),Gu=(e,t,s,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?s[3]:s[1],g=p/t.group,m=h&&g>=4?V(p):1,w=j.size(s)/m,_=[{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:g}];An(t,_),_.push(...L(u,[c[0],c[1],c[2],c[3]/m]));let S=o?["rank","rank","rank"]:["rank","rank"];_.push(...L([s[0],s[1],s[2],s[3]/m]));let C=M=>{let k=de("output",e[0].dataType,s.length,m),x=G(k.type.tensor),O=Rn(t,k.type.value,x),I=F("x",e[0].dataType,u.length),z=F("w",e[1].dataType,c.length,m),W=[I,z];o&&W.push(F("b",e[2].dataType,e[2].dims,m));let q=[{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"}];In(t,q);let J=h?`
|
|
1119
|
+
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {
|
|
1120
|
+
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
|
|
1121
|
+
|
|
1122
|
+
if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {
|
|
1123
|
+
continue;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {
|
|
1127
|
+
let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
|
|
1128
|
+
if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {
|
|
1129
|
+
continue;
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {
|
|
1133
|
+
let input_channel = in_channel_offset + wInChannel;
|
|
1134
|
+
let xVal = ${I.get("batch","xHeight","xWidth","input_channel")};
|
|
1135
|
+
let wVal = ${z.get("wHeight","wWidth","wInChannel","output_channel")};
|
|
1136
|
+
value += xVal * wVal;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
`:`
|
|
1141
|
+
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {
|
|
1142
|
+
let input_channel = in_channel_offset + wInChannel;
|
|
1143
|
+
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {
|
|
1144
|
+
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
|
|
1145
|
+
|
|
1146
|
+
if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {
|
|
1147
|
+
continue;
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {
|
|
1151
|
+
let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
|
|
1152
|
+
if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {
|
|
1153
|
+
continue;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
let xVal = ${I.get("batch","input_channel","xHeight","xWidth")};
|
|
1157
|
+
let wVal = ${z.get("output_channel","wInChannel","wHeight","wWidth")};
|
|
1158
|
+
value += xVal * wVal;
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
`;return`
|
|
1163
|
+
${M.registerUniforms(q).declareVariables(...W,k)}
|
|
1164
|
+
|
|
1165
|
+
${M.mainStart()}
|
|
1166
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1167
|
+
|
|
1168
|
+
let outputIndices = ${k.offsetToIndices("global_idx")};
|
|
1169
|
+
let batch: u32 = outputIndices[0];
|
|
1170
|
+
let output_channel: u32 = outputIndices[${h?3:1}];
|
|
1171
|
+
let xRCCorner: vec2<u32> = vec2<u32>(outputIndices[${h?1:2}], outputIndices[${h?2:3}]) * uniforms.strides - uniforms.pads;
|
|
1172
|
+
let group_id: u32 = output_channel * ${m} / uniforms.output_channels_per_group;
|
|
1173
|
+
var in_channel_offset = group_id * uniforms.w_shape[${h?2:1}];
|
|
1174
|
+
|
|
1175
|
+
var value: ${k.type.value} = ${k.type.value}(0);
|
|
1176
|
+
${J}
|
|
1177
|
+
${l}
|
|
1178
|
+
${O}
|
|
1179
|
+
${k.setByOffset("global_idx","value")}
|
|
1180
|
+
}`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${m}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:i?i(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:_}),getShaderSource:C}},qu=(e,t,s,i)=>{let o=e.length>2,l=V(s[3]),u=V(s[2]),c=j.size(s)/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],g=[s[0],s[1],s[2],s[3]/l],m=[{type:12,data:c},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];An(t,m),m.push(...L(h,p,g));let w=(u-1)*t.strides[1]+p[1],_=S=>{let C=de("output",e[0].dataType,g.length,l),M=G(C.type.tensor),k=Rn(t,C.type.value,M),x=F("x",e[0].dataType,h.length,l),O=F("w",e[1].dataType,p.length,l),I=[x,O];o&&I.push(F("b",e[2].dataType,e[2].dims,l));let z=o?"value += b[output_channel];":"",W=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return In(t,W),`
|
|
1181
|
+
${S.registerUniforms(W).declareVariables(...I,C)}
|
|
1182
|
+
${S.mainStart()}
|
|
1183
|
+
${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1184
|
+
let width0 = uniforms.output_shape[3];
|
|
1185
|
+
let output_channel = global_idx % width0;
|
|
1186
|
+
var index1 = global_idx / width0;
|
|
1187
|
+
let width1 = uniforms.output_shape[2] / ${u}u;
|
|
1188
|
+
let col = (index1 % width1) * ${u}u;
|
|
1189
|
+
index1 = index1 / width1;
|
|
1190
|
+
let row = index1 % uniforms.output_shape[1];
|
|
1191
|
+
let batch = index1 / uniforms.output_shape[1];
|
|
1192
|
+
|
|
1193
|
+
let x_corner = vec2<i32>(i32(row), i32(col)) * uniforms.strides - uniforms.pads;
|
|
1194
|
+
|
|
1195
|
+
var x_vals: array<${x.type.value}, ${w}>;
|
|
1196
|
+
var values: array<${C.type.value}, ${u}>;
|
|
1197
|
+
let input_channel = output_channel;
|
|
1198
|
+
// Use constant instead of uniform can give better performance for w's height/width.
|
|
1199
|
+
for (var w_height: u32 = 0u; w_height < ${p[0]}; w_height++) {
|
|
1200
|
+
let x_height = x_corner.x + i32(w_height);
|
|
1201
|
+
if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {
|
|
1202
|
+
for (var i = 0; i < ${w}; i++) {
|
|
1203
|
+
let x_width = x_corner.y + i;
|
|
1204
|
+
if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {
|
|
1205
|
+
x_vals[i] = ${x.get("batch","u32(x_height)","u32(x_width)","input_channel")};
|
|
1206
|
+
} else {
|
|
1207
|
+
x_vals[i] = ${x.type.value}(0);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) {
|
|
1211
|
+
let w_val = ${O.get("w_height","w_width","0","output_channel")};
|
|
1212
|
+
for (var i = 0u; i < ${u}u; i++) {
|
|
1213
|
+
values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
for (var i = 0u; i < ${u}u; i++) {
|
|
1220
|
+
var value = values[i];
|
|
1221
|
+
${z}
|
|
1222
|
+
${k}
|
|
1223
|
+
${C.set("batch","row","col + i","output_channel","value")};
|
|
1224
|
+
}
|
|
1225
|
+
}`};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(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:m}),getShaderSource:_}}}),Wu,Ti,Hu,Ei,_a,ba,ju,Ku,Sa,Om=b(()=>{Me(),Im(),Mm(),ya(),Pm(),Mn(),pa(),He(),Wu=(e,t,s,i,o,l)=>{let u=e[0],c=e.slice(l?1:2,l?3:4),h=c.length,p=t[0],g=t.slice(2).map((w,_)=>w+(w-1)*(s[_]-1)),m=c.map((w,_)=>w+i[_]+i[_+h]).map((w,_)=>Math.floor((w-g[_]+o[_])/o[_]));return m.splice(0,0,u),m.splice(l?3:1,0,p),m},Ti=[2,3,1,0],Hu=(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 s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[1]*t.group;if(s!==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 s=e.kernelShape.slice();s.length<t[1].dims.length-2&&s.push(...Array(t[1].dims.length-2-s.length).fill(0));for(let l=2;l<t[1].dims.length;++l)s[l-2]===0&&(s[l-2]=t[1].dims[l]);let i=e.pads.slice();Qr.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,s,i,e.format==="NHWC",e.autoPad);let o=Object.assign({},e);return Object.assign(o,{kernelShape:s,pads:i}),o},_a=e=>{let t=da(e),s=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:s,dilations:o,group:l,kernelShape:u,pads:c,strides:h,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},ba=(e,t,s,i)=>{let o=s.format==="NHWC",l=Wu(t[0].dims,t[1].dims,s.dilations,s.pads,s.strides,o);if(s.group!==1){let W=[t[0]];if(o){let q=e.kernelCustomData.wT??e.compute(bt(t[1],Ti),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=q),W.push(q)}else W.push(t[1]);t.length===3&&W.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===s.group&&t[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1?e.compute(qu(W,s,l,i),{inputs:W}):e.compute(Gu(W,s,l,i),{inputs:W});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],g=t[1].dims[2],m=t[1].dims[3],w=l[o?1:2],_=l[o?2:3],S=l[o?3:1],C=o&&g===c&&m===h&&s.pads[0]===0&&s.pads[1]===0;if(C||g===1&&m===1&&s.dilations[0]===1&&s.dilations[1]===1&&s.strides[0]===1&&s.strides[1]===1&&s.pads[0]===0&&s.pads[1]===0){let W=l[0],q,J,oe,ge=[];if(o){let Be=e.kernelCustomData.wT??e.compute(bt(t[1],Ti),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Be),C){let ut=c*h*p;q=t[0].reshape([1,W,ut]),J=Be.reshape([1,ut,S]),oe=[1,W,S]}else q=t[0].reshape([W,c*h,p]),J=Be.reshape([1,p,S]),oe=[W,w*_,S];ge.push(q),ge.push(J)}else q=t[0].reshape([W,p,c*h]),J=t[1].reshape([1,S,p]),oe=[W,S,w*_],ge.push(J),ge.push(q);u&&ge.push(t[2]);let Qe=oe[2],Ae=ge[0].dims[ge[0].dims.length-1];Qe<8&&Ae<8?e.compute(ha(ge,s,l,oe,o,i),{inputs:ge}):e.compute(Si(ge,s,l,oe,o,i),{inputs:ge});return}let M=!0,k=e.kernelCustomData.wT??e.compute(bt(t[1],Ti),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=k);let x=[t[0],k];u&&x.push(t[2]);let O=o?w*_:S,I=o?S:w*_,z=g*m*p;e.compute(Lu(x,s,l,O,I,z,u,M,i),{inputs:x})},ju=(e,t)=>{let s=t.format==="NHWC",i=[e.inputs[0].reshape(s?[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);ba(e,i,h,p=>s?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Ku=(e,t,s)=>{let i=s.format==="NHWC"?"channelsLast":"channelsFirst",o=Ei(s,t),l=s.autoPad==="NOTSET"?s.pads:s.autoPad,u=Fu(t[0].dims,t[1].dims,s.strides,s.dilations,l,!1,i);e.compute(Vu(t,o,u.outShape,[u.filterDepth,u.filterHeight,u.filterWidth],[u.padInfo.front,u.padInfo.top,u.padInfo.left],i))},Sa=(e,t)=>{if(Hu(e.inputs,t),e.inputs[0].dims.length===3)ju(e,t);else if(e.inputs[0].dims.length===5)Ku(e,e.inputs,t);else{let s=Ei(t,e.inputs);ba(e,e.inputs,s)}}}),Qu,Dm=b(()=>{ze(),rr(),Me(),_e(),Qu=(e,t,s)=>{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],g=l?V(h):1,m=l&&p===1&&h>=4,w=m?Math.floor(h/4)*4:Math.floor(h/g)*g,_=h-w,S=l?V(p):1,C=l?p===1?g:S:1,M=j.size(o)/S,k=[Math.ceil(M/64),1,1];Je("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${k}`);let x=["rank","rank"],O=[t.strides[0],t.strides[1]],I=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],z=[t.dilations[0],t.dilations[1]],W=[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))],q=[W[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),W[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],J=[{type:12,data:M},{type:12,data:O},{type:12,data:I},{type:12,data:z},{type:12,data:W},{type:6,data:q},{type:12,data:w},{type:12,data:h},{type:12,data:p},...L(e[0].dims,e[1].dims)];i&&(J.push(...L(e[2].dims)),x.push("rank")),J.push(...L(o));let oe=ge=>{let Qe=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:O.length},{name:"filter_dims",type:"u32",length:I.length},{name:"dilations",type:"u32",length:I.length},{name:"effective_filter_dims",type:"u32",length:W.length},{name:"pads",type:"i32",length:q.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Ae=G(e[0].dataType),Be=l?1:2,ut=l?2:3,we=l?3:1,ke=F("W",e[1].dataType,e[1].dims.length,C),Xe=F("Dy",e[0].dataType,e[0].dims.length,g),Ve=[Xe,ke];i&&Ve.push(F("bias",e[2].dataType,[o[we]].length,S));let Ue=de("result",e[0].dataType,o.length,S),ct=()=>{let Ge="";if(m)g===4?Ge+=`
|
|
1226
|
+
let xValue = ${Xe.getByOffset("x_offset")};
|
|
1227
|
+
let wValue = ${ke.getByOffset("w_offset")};
|
|
1228
|
+
dotProd = dotProd + dot(xValue, wValue);
|
|
1229
|
+
x_offset += 1u;
|
|
1230
|
+
w_offset += 1u;`:g===2?Ge+=`
|
|
1231
|
+
dotProd = dotProd + dot(vec4<${Ae}>(${Xe.getByOffset("x_offset")}, ${Xe.getByOffset("x_offset + 1u")}), vec4<${Ae}>(${ke.getByOffset("w_offset")}, ${ke.getByOffset("w_offset + 1u")}));
|
|
1232
|
+
x_offset += 2u;
|
|
1233
|
+
w_offset += 2u;`:g===1&&(Ge+=`
|
|
1234
|
+
dotProd = dotProd + dot(vec4<${Ae}>(${Xe.getByOffset("x_offset")}, ${Xe.getByOffset("x_offset + 1u")}, ${Xe.getByOffset("x_offset + 2u")}, ${Xe.getByOffset("x_offset + 3u")}), vec4<${Ae}>(${ke.getByOffset("w_offset")}, ${ke.getByOffset("w_offset + 1u")}, ${ke.getByOffset("w_offset + 2u")}, ${ke.getByOffset("w_offset + 3u")}));
|
|
1235
|
+
x_offset += 4u;
|
|
1236
|
+
w_offset += 4u;`);else if(Ge+=`
|
|
1237
|
+
let xValue = ${l?Xe.getByOffset(`${Xe.indicesToOffset(`${Xe.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${g}`):Xe.get("batch","inputChannel","idyR","idyC")};
|
|
1238
|
+
`,g===1)Ge+=`
|
|
1239
|
+
let w_offset = ${ke.indicesToOffset(`${ke.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};
|
|
1240
|
+
let wValue = ${ke.getByOffset(`w_offset / ${C}`)};
|
|
1241
|
+
dotProd = dotProd + xValue * wValue;`;else for(let ht=0;ht<g;ht++)Ge+=`
|
|
1242
|
+
let wValue${ht} = ${ke.getByOffset(`${ke.indicesToOffset(`${ke.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${ht}, wOutChannel)`)} / ${C}`)};
|
|
1243
|
+
dotProd = dotProd + xValue[${ht}] * wValue${ht};`;return Ge},se=()=>{if(_===0)return"";if(!m)throw new Error(`packInputAs4 ${m} is not true.`);let Ge="";if(g===1){Ge+="dotProd = dotProd";for(let ht=0;ht<_;ht++)Ge+=`
|
|
1244
|
+
+ ${Xe.getByOffset(`x_offset + ${ht}`)} * ${ke.getByOffset(`w_offset + ${ht}`)}`;Ge+=";"}else if(g===2){if(_!==2)throw new Error(`Invalid inputChannelsRemainder ${_}.`);Ge+=`
|
|
1245
|
+
let xValue = ${Xe.getByOffset("x_offset")};
|
|
1246
|
+
let wValue = ${ke.getByOffset("w_offset")};
|
|
1247
|
+
dotProd = dotProd + dot(xValue, wValue);`}return Ge},ve=`
|
|
1248
|
+
let outputIndices = ${Ue.offsetToIndices(`global_idx * ${S}`)};
|
|
1249
|
+
let batch = ${Ue.indicesGet("outputIndices",0)};
|
|
1250
|
+
let d1 = ${Ue.indicesGet("outputIndices",we)};
|
|
1251
|
+
let r = ${Ue.indicesGet("outputIndices",Be)};
|
|
1252
|
+
let c = ${Ue.indicesGet("outputIndices",ut)};
|
|
1253
|
+
let dyCorner = vec2<i32>(i32(r), i32(c)) - uniforms.pads;
|
|
1254
|
+
let dyRCorner = dyCorner.x;
|
|
1255
|
+
let dyCCorner = dyCorner.y;
|
|
1256
|
+
let groupId = d1 / uniforms.output_channels_per_group;
|
|
1257
|
+
let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;
|
|
1258
|
+
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
1259
|
+
// ? = to be determined. : = across all values in that axis.
|
|
1260
|
+
var dotProd = ${Ue.type.value}(0.0);
|
|
1261
|
+
var wR: u32 = 0;
|
|
1262
|
+
if (uniforms.dilations.x == 1) {
|
|
1263
|
+
// Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0
|
|
1264
|
+
wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner);
|
|
1265
|
+
}
|
|
1266
|
+
for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {
|
|
1267
|
+
if (wR % uniforms.dilations.x != 0) {
|
|
1268
|
+
continue;
|
|
1269
|
+
}
|
|
1270
|
+
let dyR = (${Ae}(dyRCorner) + ${Ae}(wR)) / ${Ae}(uniforms.strides[0]);
|
|
1271
|
+
let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;
|
|
1272
|
+
if (dyR < 0.0 || dyR >= ${Ae}(uniforms.Dy_shape[${Be}]) || fract(dyR) > 0.0 ||
|
|
1273
|
+
wRPerm < 0) {
|
|
1274
|
+
continue;
|
|
1275
|
+
}
|
|
1276
|
+
let idyR: u32 = u32(dyR);
|
|
1277
|
+
var wC: u32 = 0;
|
|
1278
|
+
if (uniforms.dilations.y == 1) {
|
|
1279
|
+
// Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0
|
|
1280
|
+
wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner);
|
|
1281
|
+
}
|
|
1282
|
+
for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {
|
|
1283
|
+
if (wC % uniforms.dilations.y != 0) {
|
|
1284
|
+
continue;
|
|
1285
|
+
}
|
|
1286
|
+
let dyC = (${Ae}(dyCCorner) + ${Ae}(wC)) / ${Ae}(uniforms.strides.y);
|
|
1287
|
+
let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;
|
|
1288
|
+
if (dyC < 0.0 || dyC >= ${Ae}(uniforms.Dy_shape[${ut}]) ||
|
|
1289
|
+
fract(dyC) > 0.0 || wCPerm < 0) {
|
|
1290
|
+
continue;
|
|
1291
|
+
}
|
|
1292
|
+
let idyC: u32 = u32(dyC);
|
|
1293
|
+
var inputChannel = groupId * uniforms.input_channels_per_group;
|
|
1294
|
+
${m?`
|
|
1295
|
+
var x_offset = ${Xe.indicesToOffset(`${Xe.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${g};
|
|
1296
|
+
var w_offset = ${ke.indicesToOffset(`${ke.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${C};
|
|
1297
|
+
`:""}
|
|
1298
|
+
for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${m?4:g}) {
|
|
1299
|
+
${ct()}
|
|
1300
|
+
inputChannel = inputChannel + ${m?4:g};
|
|
1301
|
+
}
|
|
1302
|
+
${se()}
|
|
1303
|
+
wC = wC + uniforms.strides.y - 1;
|
|
1304
|
+
}
|
|
1305
|
+
wR = wR + uniforms.strides[0] - 1;
|
|
1306
|
+
}
|
|
1307
|
+
let value = dotProd${i?` + bias[d1 / ${S}]`:""};
|
|
1308
|
+
${Ue.setByOffset("global_idx","value")};
|
|
1309
|
+
`;return`
|
|
1310
|
+
${ge.registerUniforms(Qe).declareVariables(...Ve,Ue)}
|
|
1311
|
+
${ge.mainStart()}
|
|
1312
|
+
${ge.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};
|
|
1313
|
+
${ve}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${g}${C}${S}${m}${_}`,inputDependencies:x},getRunData:()=>({dispatchGroup:{x:k[0],y:k[1],z:k[2]},outputs:[{dims:s?s(o):o,dataType:e[0].dataType}],programUniforms:J}),getShaderSource:oe}}}),Xu,Yu,Ju,Ta,Zu,ed,Ea,td,rd,zm=b(()=>{Dm(),Mn(),He(),Xu=(e,t,s,i,o,l)=>(e-1)*t+s+(i-1)*o+1-l,Yu=(e,t,s,i,o)=>{let l=Math.floor(e/2);t==="SAME_UPPER"?(s[i]=l,s[o]=e-l):t==="SAME_LOWER"&&(s[i]=e-l,s[o]=l)},Ju=(e,t,s,i,o,l,u,c,h,p)=>{let g=e.length-2,m=p.length===0;h.length<g&&h.push(...Array(g-h.length).fill(0));let w=e[0],_=t[c?3:1]*o;for(let S=0,C=e.length-g-(c?1:0);S<g;++S,++C){let M=e[C],k=m?M*u[S]:p[S],x=Xu(M,u[S],l[S],t[C],s[S],k);Yu(x,i,l,S,S+g),m&&p.push(u[S]*(M-1)+h[S]+(t[C]-1)*s[S]+1-l[S]-l[S+g])}p.splice(0,0,w),p.splice(c?3:1,0,_)},Ta=(e,t)=>{let s=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((m,w)=>m*w,1)===0){s.length=0;for(let m=2;m<t[1].dims.length;++m)s.push(t[1].dims[m])}let i=e.format==="NHWC";s.splice(0,0,t[1].dims[0]),s.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((m,w)=>m+w,0)===0){let m=t[0].dims.length-2;h=new Array(m).fill(1)}let p=e.strides.slice();if(p.reduce((m,w)=>m+w,0)===0){let m=t[0].dims.length-2;p=new Array(m).fill(1)}Ju(c,s,h,e.autoPad,e.group,o,p,i,u,l);let g=Object.assign({},e);return Object.assign(g,{kernelShape:s,pads:o,outputPadding:u,outputShape:l,dilations:h,strides:p}),g},Zu=e=>{let t=da(e),s=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(),g=e.outputPadding,m=e.outputShape;return{autoPad:i,format:s,dilations:o,group:l,kernelShape:u,outputPadding:g,outputShape:m,pads:c,strides:h,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},ed=(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 s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[0];if(s!==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")},Ea=(e,t,s,i)=>{let o=e.kernelCustomData.wT??e.compute(bt(t[1],[2,3,0,1]),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let l=[t[0],o];t.length===3&&l.push(t[2]),e.compute(Qu(l,s,i),{inputs:l})},td=(e,t)=>{let s=t.format==="NHWC",i=[e.inputs[0].reshape(s?[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=Ta({...t,pads:c,strides:u,dilations:l,kernelShape:o,outputPadding:h},i);Ea(e,i,p,g=>s?[g[0],g[2],g[3]]:[g[0],g[1],g[3]])},rd=(e,t)=>{if(ed(e.inputs,t),e.inputs[0].dims.length===3)td(e,t);else{let s=Ta(t,e.inputs);Ea(e,e.inputs,s)}}}),nd,sd,id,Lm=b(()=>{ze(),Me(),A(),_e(),nd=(e,t,s,i)=>{let o=j.size(t),l=t.length,u=F("input",e,l),c=de("output",e,l),h=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),p=j.normalizeAxis(h,l),g=m=>{let w=` i32(${u.indicesGet("inputIndices","uniforms.axis")}) `,_=K("uniforms.input_shape","uniforms.axis",l),S=i.reverse?w+(i.exclusive?" + 1":""):"0",C=i.reverse?_:w+(i.exclusive?"":" + 1");return`
|
|
1314
|
+
${m.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(u,c)}
|
|
1315
|
+
${m.mainStart()}
|
|
1316
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1317
|
+
var inputIndices = ${c.offsetToIndices("global_idx")};
|
|
1318
|
+
var sum = ${c.type.value}(0);
|
|
1319
|
+
let first : i32 = ${S};
|
|
1320
|
+
let last : i32 = ${C};
|
|
1321
|
+
for (var i : i32 = first; i < last; i++) {
|
|
1322
|
+
${u.indicesSet("inputIndices","uniforms.axis","u32(i)")};
|
|
1323
|
+
sum = sum + ${u.getByIndices("inputIndices")};
|
|
1324
|
+
}
|
|
1325
|
+
${c.setByOffset("global_idx","sum")};
|
|
1326
|
+
}`};return{name:"CumSum",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:p},...L(t,t)]}),getShaderSource:g}},sd=(e,t)=>{let s=e.inputs[0].dims,i=e.inputs[0].dataType,o=e.inputs[1];e.compute(nd(i,s,o,t),{inputs:[0]})},id=e=>{let t=e.exclusive===1,s=e.reverse===1;return E({exclusive:t,reverse:s})}}),ad,od,ld,ud,dd,Bm=b(()=>{ze(),Me(),A(),_e(),ad=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.")},od=(e,t,s,i)=>{let o=[];o.push(`fn perm(i: ${i.type.indices}) -> ${s.type.indices} {
|
|
1327
|
+
var a: ${s.type.indices};`);for(let l=0;l<t;++l)o.push(s.indicesSet("a",e[l],`i[${l}]`));return o.push("return a;}"),o.join(`
|
|
1328
|
+
`)},ld=(e,t)=>{let s,i,o,l,u,c,h=t.format==="NHWC",p=t.blocksize,g=t.mode==="DCR";h?([s,i,o,l]=e.dims,u=g?[s,i,o,p,p,l/p**2]:[s,i,o,l/p**2,p,p],c=g?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,i,o,l]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],u=g?[s,p,p,l/p**2,i,o]:[s,l/p**2,p,p,i,o],c=g?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let m=e.reshape(u),w=m.dims.length,_=e.dataType,S=F("a",_,w),C=de("output",_,w),M=k=>`
|
|
1329
|
+
${k.registerUniform("output_size","u32").declareVariables(S,C)}
|
|
1330
|
+
|
|
1331
|
+
${od(c,w,S,C)}
|
|
1332
|
+
|
|
1333
|
+
${k.mainStart()}
|
|
1334
|
+
${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1335
|
+
|
|
1336
|
+
let indices = ${C.offsetToIndices("global_idx")};
|
|
1337
|
+
let aIndices = perm(indices);
|
|
1338
|
+
|
|
1339
|
+
${C.setByOffset("global_idx",S.getByIndices("aIndices"))}
|
|
1340
|
+
}`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:k=>{let x=h?[s,i*p,o*p,l/p**2]:[s,l/p**2,i*p,o*p],O=j.size(x),I=m.dims,z=j.sortBasedOnPerm(I,c);return{outputs:[{dims:x,dataType:k[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:[{type:12,data:O},...L(I,z)]}},getShaderSource:M}},ud=(e,t)=>{ad(e.inputs),e.compute(ld(e.inputs[0],t))},dd=e=>E({blocksize:e.blocksize,mode:e.mode,format:e.format})}),$i,qs,$a,cd,hd,pd,fd,xa,md,gd,yd,Nm=b(()=>{ze(),Me(),A(),_e(),$i="[a-zA-Z]|\\.\\.\\.",qs="("+$i+")+",$a="^"+qs+"$",cd="("+qs+",)*"+qs,hd="^"+cd+"$",pd=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let s=this.symbolToIndices.get(e);s===void 0?s=[t]:s.push(t),this.symbolToIndices.set(e,s)}},fd=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,i]=t.includes("->")?t.split("->",2):[t,""];if(!s.match(RegExp(hd)))throw new Error("Invalid LHS term");if(s.split(",").forEach((o,l)=>{let u=e[l].dims.slice();if(!o.match(RegExp($a)))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(qs)))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,s){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(s)}else i={count:1,dimValue:t,inputIndices:[s]};this.symbolToInfo.set(e,i)}processTerm(e,t,s,i=-1){let o=s.length,l=!1,u=[],c=0;if(!e.match(RegExp($a))&&!t&&e!=="")throw new Error("Invalid LHS term");let h=e.match(RegExp($i,"g")),p=new pd(i);return h?.forEach((g,m)=>{if(g==="..."){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=s.slice(c,c+w),this.hasEllipsis){if(this.ellipsisDims.length!==u.length||this.ellipsisDims.toString()!==u.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=u;else throw new Error("Ellipsis must be specified in the LHS");for(let _=0;_<u.length;_++){let S=String.fromCharCode(48+_);p.addSymbol(S,m+_),this.addSymbol(S,s[c++],i)}}else p.addSymbol(g,m+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(g,s[c++],i)}),p}},xa=e=>e+"_max",md=(e,t,s,i)=>{let o=e.map(p=>p.length).map((p,g)=>F(`input${g}`,t,p)),l=j.size(i),u=de("output",t,i.length),c=[...s.symbolToInfo.keys()].filter(p=>!s.rhs.symbolToIndices.has(p)),h=p=>{let g=[],m="var prod = 1.0;",w="var sum = 0.0;",_="sum += prod;",S=[],C=[],M=[],k=[],x=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((I,z)=>{if(s.rhs.symbolToIndices.has(z)){let W=s.rhs.symbolToIndices.get(z)?.[0];W!==void 0&&s.lhs.forEach((q,J)=>{if(I.inputIndices.includes(J)){let oe=q.symbolToIndices.get(z);if(oe===void 0)throw new Error("Invalid symbol error");oe.forEach(ge=>{g.push(`${o[J].indicesSet(`input${J}Indices`,ge,u.indicesGet("outputIndices",W))}`)})}})}else s.lhs.forEach((W,q)=>{if(I.inputIndices.includes(q)){let J=W.symbolToIndices.get(z);if(J===void 0)throw new Error("Invalid symbol error");J.forEach(oe=>{S.push(`${o[q].indicesSet(`input${q}Indices`,oe,`${z}`)}`)}),k.push(`prod *= ${o[q].getByIndices(`input${q}Indices`)};`)}}),C.push(`for(var ${z}: u32 = 0; ${z} < uniforms.${xa(z)}; ${z}++) {`),M.push("}")});let O=x?[...g,`let sum = ${o.map((I,z)=>I.getByIndices(`input${z}Indices`)).join(" * ")};`]:[...g,w,...C,...S,m,...k,_,...M];return`
|
|
1341
|
+
${p.registerUniforms(c.map(I=>({name:`${xa(I)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,u)}
|
|
1342
|
+
|
|
1343
|
+
${p.mainStart()}
|
|
1344
|
+
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1345
|
+
var outputIndices = ${u.offsetToIndices("global_idx")};
|
|
1346
|
+
${o.map((I,z)=>`var input${z}Indices: ${o[z].type.indices};`).join(`
|
|
1347
|
+
`)}
|
|
1348
|
+
${O.join(`
|
|
1349
|
+
`)};
|
|
1350
|
+
${u.setByOffset("global_idx","sum")};
|
|
1351
|
+
}`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=c.filter(m=>s.symbolToInfo.has(m)).map(m=>({type:12,data:s.symbolToInfo.get(m)?.dimValue||0}));p.push({type:12,data:l});let g=e.map((m,w)=>[...L(m)]).reduce((m,w)=>m.concat(w),p);return g.push(...L(i)),{outputs:[{dims:i,dataType:t}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:g}},getShaderSource:h}},gd=(e,t)=>{let s=new fd(e.inputs,t.equation),i=s.outputDims,o=e.inputs.map((l,u)=>l.dims);e.compute(md(o,e.inputs[0].dataType,s,i))},yd=e=>{let t=e.equation.replace(/\s+/g,"");return E({equation:t})}}),wd,Ca,vd,_d,bd,Um=b(()=>{ze(),Me(),_e(),wd=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),i=s.length<t.length?0:s.length-t.length,o=t.length<s.length?0:t.length-s.length;for(;i<s.length&&o<t.length;++i,++o)if(s[i]!==t[o]&&s[i]!==1&&t[o]!==1)throw new Error("Expand requires shape to be broadcastable to input")},Ca=(e,t)=>{let s=e.length-t.length,i=[];for(let o=0;o<s;++o)i.push(e[o]);for(let o=0;o<t.length;++o)i.push(t[o]===1?e[o+s]:t[o]);return i},vd=(e,t)=>e.length>t.length?Ca(e,t):Ca(t,e),_d=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),i=vd(t,s),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=m=>{let w=F("input",o,t.length,u),_=de("output",o,i.length,c),S;if(o===9){let C=(M,k,x="")=>`
|
|
1352
|
+
let outputIndices${k} = ${_.offsetToIndices(`outputOffset + ${k}u`)};
|
|
1353
|
+
let offset${k} = ${w.broadcastedIndicesToOffset(`outputIndices${k}`,_)};
|
|
1354
|
+
let index${k} = offset${k} / 4u;
|
|
1355
|
+
let component${k} = offset${k} % 4u;
|
|
1356
|
+
${M}[${k}] = ${x}(${w.getByOffset(`index${k}`)}[component${k}]);
|
|
1357
|
+
`;S=`
|
|
1358
|
+
let outputOffset = global_idx * ${c};
|
|
1359
|
+
var data = vec4<u32>(0);
|
|
1360
|
+
${C("data",0,"u32")}
|
|
1361
|
+
${C("data",1,"u32")}
|
|
1362
|
+
${C("data",2,"u32")}
|
|
1363
|
+
${C("data",3,"u32")}
|
|
1364
|
+
${_.setByOffset("global_idx","data")}
|
|
1365
|
+
}`}else S=`
|
|
1366
|
+
let outputIndices = ${_.offsetToIndices(`global_idx * ${c}`)};
|
|
1367
|
+
let inputOffset = ${w.broadcastedIndicesToOffset("outputIndices",_)};
|
|
1368
|
+
let data = ${_.type.value}(${w.getByOffset(`inputOffset / ${u}`)});
|
|
1369
|
+
${_.setByOffset("global_idx","data")}
|
|
1370
|
+
}`;return`
|
|
1371
|
+
${m.registerUniform("vec_size","u32").declareVariables(w,_)}
|
|
1372
|
+
${m.mainStart()}
|
|
1373
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
1374
|
+
${S}`},g=[{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:g})}},bd=e=>{wd(e.inputs),e.compute(_d(e.inputs),{inputs:[0]})}}),Sd,Td,Fm=b(()=>{ze(),Me(),_e(),ua(),Sd=e=>{let t=e[0].dataType,s=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=de("y",t,[1],4),g=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],m=_=>`
|
|
1375
|
+
let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size;
|
|
1376
|
+
let bias${_} = ${h.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,w=o?`
|
|
1377
|
+
let bias = ${h.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${m(0)}${m(1)}${m(2)}${m(3)}
|
|
1378
|
+
let bias = ${c.type.value}(bias0, bias1, bias2, bias3);`;return`${u.registerUniforms(g).declareVariables(c,h,p)}
|
|
1379
|
+
|
|
1380
|
+
${oa(U(t))}
|
|
1381
|
+
|
|
1382
|
+
${u.mainStart(D)}
|
|
1383
|
+
${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}
|
|
1384
|
+
|
|
1385
|
+
let x = ${c.getByOffset("global_idx")};
|
|
1386
|
+
${w}
|
|
1387
|
+
let x_in = x + bias;
|
|
1388
|
+
${p.setByOffset("global_idx",la("x_in"))}
|
|
1389
|
+
}`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:l,getRunData:u=>({outputs:[{dims:u[0].dims,dataType:u[0].dataType}],programUniforms:[{type:12,data:Math.ceil(s/4)},{type:12,data:i}],dispatchGroup:{x:Math.ceil(s/D/4)}})}},Td=e=>{e.inputs.length<2||j.size(e.inputs[1].dims)===0?nu(e):e.compute(Sd(e.inputs))}}),Ed,$d,xd,Cd,Vm=b(()=>{ze(),Me(),A(),_e(),Ed=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},$d=(e,t)=>{let s=e[0].dims,i=e[1].dims,o=s.length,l=j.normalizeAxis(t.axis,o),u=s.slice(0);u.splice(l,1,...i);let c=s[l],h=e[0].dataType===9?4:1,p=Math.ceil(j.size(u)/h),g=[{type:12,data:p},{type:6,data:c},{type:12,data:l},...L(e[0].dims,e[1].dims,u)],m=w=>{let _=F("data",e[0].dataType,e[0].dims.length,h),S=F("inputIndices",e[1].dataType,e[1].dims.length),C=de("output",e[0].dataType,u.length,h),M=x=>{let O=i.length,I=`var indicesIndices${x} = ${S.type.indices}(0);`;for(let z=0;z<O;z++)I+=`${O>1?`indicesIndices${x}[${z}]`:`indicesIndices${x}`} = ${u.length>1?`outputIndices${x}[uniforms.axis + ${z}]`:`outputIndices${x}`};`;I+=`
|
|
1390
|
+
var idx${x} = ${S.getByIndices(`indicesIndices${x}`)};
|
|
1391
|
+
if (idx${x} < 0) {
|
|
1392
|
+
idx${x} = idx${x} + uniforms.axisDimLimit;
|
|
1393
|
+
}
|
|
1394
|
+
var dataIndices${x} : ${_.type.indices};
|
|
1395
|
+
`;for(let z=0,W=0;z<o;z++)z===l?(I+=`${o>1?`dataIndices${x}[${z}]`:`dataIndices${x}`} = u32(idx${x});`,W+=O):(I+=`${o>1?`dataIndices${x}[${z}]`:`dataIndices${x}`} = ${u.length>1?`outputIndices${x}[${W}]`:`outputIndices${x}`};`,W++);return I},k;if(e[0].dataType===9){let x=(O,I,z="")=>`
|
|
1396
|
+
let outputIndices${I} = ${C.offsetToIndices(`outputOffset + ${I}u`)};
|
|
1397
|
+
${M(I)};
|
|
1398
|
+
let offset${I} = ${_.indicesToOffset(`dataIndices${I}`)};
|
|
1399
|
+
let index${I} = offset${I} / 4u;
|
|
1400
|
+
let component${I} = offset${I} % 4u;
|
|
1401
|
+
${O}[${I}] = ${z}(${_.getByOffset(`index${I}`)}[component${I}]);
|
|
1402
|
+
`;k=`
|
|
1403
|
+
let outputOffset = global_idx * ${h};
|
|
1404
|
+
var value = vec4<u32>(0);
|
|
1405
|
+
${x("value",0,"u32")}
|
|
1406
|
+
${x("value",1,"u32")}
|
|
1407
|
+
${x("value",2,"u32")}
|
|
1408
|
+
${x("value",3,"u32")}
|
|
1409
|
+
${C.setByOffset("global_idx","value")}
|
|
1410
|
+
`}else k=`
|
|
1411
|
+
let outputIndices = ${C.offsetToIndices("global_idx")};
|
|
1412
|
+
${M("")};
|
|
1413
|
+
let value = ${_.getByIndices("dataIndices")};
|
|
1414
|
+
${C.setByOffset("global_idx","value")};
|
|
1415
|
+
`;return`
|
|
1416
|
+
${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,S,C)}
|
|
1417
|
+
${w.mainStart()}
|
|
1418
|
+
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1419
|
+
${k}
|
|
1420
|
+
}`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:g}),getShaderSource:m}},xd=e=>E({axis:e.axis}),Cd=(e,t)=>{let s=e.inputs;Ed(s),e.compute($d(e.inputs,t))}}),kd,Rd,Ad,Gm=b(()=>{ze(),Me(),_e(),kd=(e,t,s,i,o,l,u,c,h)=>{let p=[{type:12,data:l},{type:12,data:i},{type:12,data:o},{type:12,data:s},{type:12,data:u},{type:12,data:c},{type:12,data:h}],g=[l];p.push(...L(t.dims,g));let m=w=>{let _=F("indices_data",t.dataType,t.dims.length),S=de("input_slice_offsets_data",12,1,1),C=[_,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:s.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return`
|
|
1421
|
+
${w.registerUniforms(M).declareVariables(...C)}
|
|
1422
|
+
${w.mainStart()}
|
|
1423
|
+
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1424
|
+
let batch_idx = global_idx / uniforms.num_slices_per_batch;
|
|
1425
|
+
let base_offset = batch_idx * uniforms.input_batch_stride;
|
|
1426
|
+
|
|
1427
|
+
let slice_indices_base_offset = global_idx * uniforms.num_slice_dims;
|
|
1428
|
+
var relative_slice_offset = 0;
|
|
1429
|
+
for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) {
|
|
1430
|
+
var index = i32(indices_data[dim_idx + slice_indices_base_offset].x);
|
|
1431
|
+
let input_dim_idx = uniforms.batch_dims + dim_idx;
|
|
1432
|
+
if (index < 0) {
|
|
1433
|
+
${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"}
|
|
1434
|
+
}
|
|
1435
|
+
${s.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"}
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset);
|
|
1439
|
+
}`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${s.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:g,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p}),getShaderSource:m},{inputs:[t],outputs:[-1]})[0]},Rd=(e,t)=>{let s=e.inputs,i=s[0].dims,o=s[0].dataType,l=s[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),g=j.sizeFromDimension(i,t.batchDims),m=c/p,w=new Array(u),_=h;for(let I=0;I<u;++I)w[u-1-I]=_,_*=i[t.batchDims+u-1-I];let S=kd(e,s[1],w,t.batchDims,i,c,m,g,u),C=t.batchDims+u;if(C>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(C)),k=j.size(M),x=[{type:12,data:k},{type:12,data:h},...L(s[0].dims,S.dims,M)],O=I=>{let z=F("data",s[0].dataType,s[0].dims.length),W=F("slice_offsets",12,S.dims.length),q=de("output",s[0].dataType,M.length);return`
|
|
1440
|
+
${I.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(z,W,q)}
|
|
1441
|
+
${I.mainStart()}
|
|
1442
|
+
${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1443
|
+
let slice_offset = slice_offsets[global_idx / uniforms.slice_size];
|
|
1444
|
+
output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size];
|
|
1445
|
+
}`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:M,dataType:o}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:x}),getShaderSource:O},{inputs:[s[0],S]})},Ad=e=>({batchDims:e.batch_dims,cacheKey:""})}),Id,Md,Pd,Od,qm=b(()=>{ze(),Me(),A(),_e(),Id=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=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===s?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.")}},Md=(e,t)=>{let s=e[0].dims,i=e[1].dims,o=s.length,l=j.normalizeAxis(t.gatherAxis,o),u=j.normalizeAxis(t.quantizeAxis,o),c=s.slice(0);c.splice(l,1,...i);let h=j.size(c),p=e[2].dataType,g=e[0].dataType===22,m=[{type:12,data:h},{type:12,data:u},{type:12,data:l},{type:12,data:t.blockSize},...L(...e.map((_,S)=>_.dims),c)],w=_=>{let S=F("data",e[0].dataType,e[0].dims.length),C=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,x=de("output",p,c.length),O=[S,C,M];k&&O.push(k);let I=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
1446
|
+
${_.registerUniforms(I).declareVariables(...O,x)}
|
|
1447
|
+
${_.mainStart()}
|
|
1448
|
+
let output_indices = ${x.offsetToIndices("global_idx")};
|
|
1449
|
+
var indices_indices = ${C.type.indices}(0);
|
|
1450
|
+
${i.length>1?`
|
|
1451
|
+
for (var i: u32 = 0; i < ${i.length}; i++) {
|
|
1452
|
+
let index = ${x.indicesGet("output_indices","uniforms.gather_axis + i")};
|
|
1453
|
+
${C.indicesSet("indices_indices","i","index")};
|
|
1454
|
+
}`:`indices_indices = ${x.indicesGet("output_indices","uniforms.gather_axis")};`};
|
|
1455
|
+
var data_indices = ${S.type.indices}(0);
|
|
1456
|
+
for (var i: u32 = 0; i < uniforms.gather_axis; i++) {
|
|
1457
|
+
let index = ${x.indicesGet("output_indices","i")};
|
|
1458
|
+
${S.indicesSet("data_indices","i","index")};
|
|
1459
|
+
}
|
|
1460
|
+
var index_from_indices = ${C.getByIndices("indices_indices")};
|
|
1461
|
+
if (index_from_indices < 0) {
|
|
1462
|
+
index_from_indices += ${s[l]};
|
|
1463
|
+
}
|
|
1464
|
+
${S.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")};
|
|
1465
|
+
for (var i = uniforms.gather_axis + 1; i < ${c.length}; i++) {
|
|
1466
|
+
let index = ${x.indicesGet("output_indices",`i + ${i.length} - 1`)};
|
|
1467
|
+
${S.indicesSet("data_indices","i","index")};
|
|
1468
|
+
}
|
|
1469
|
+
let data_offset = ${S.indicesToOffset("data_indices")};
|
|
1470
|
+
let data_index = data_offset % 8;
|
|
1471
|
+
// Convert 4-bit packed data to 8-bit packed data.
|
|
1472
|
+
let packed_4bit_quantized_data = ${S.getByOffset("data_offset / 8")};
|
|
1473
|
+
let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;
|
|
1474
|
+
let quantized_data_vec = ${g?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data));
|
|
1475
|
+
let quantized_data = quantized_data_vec[data_index / 2];
|
|
1476
|
+
var scale_indices = data_indices;
|
|
1477
|
+
let quantize_axis_index = ${M.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size;
|
|
1478
|
+
${M.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")};
|
|
1479
|
+
var scale = ${M.getByIndices("scale_indices")};
|
|
1480
|
+
${k?`
|
|
1481
|
+
let zero_point_indices = scale_indices;
|
|
1482
|
+
let zero_point_offset = ${k.indicesToOffset("zero_point_indices")};
|
|
1483
|
+
let zero_point_index = zero_point_offset % 8;
|
|
1484
|
+
let packed_4bit_zero_points = ${k.getByOffset("zero_point_offset / 8")};
|
|
1485
|
+
let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;
|
|
1486
|
+
let zero_point_vec = ${g?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points));
|
|
1487
|
+
let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};
|
|
1488
|
+
let dequantized_data = ${U(p)}(quantized_data - zero_point) * scale;
|
|
1489
|
+
${x.setByOffset("global_idx","dequantized_data")};
|
|
1490
|
+
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((_,S)=>S!==1).map(_=>_.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(_,S)=>"rank")},getRunData:()=>({outputs:[{dims:c,dataType:p}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:m}),getShaderSource:w}},Pd=(e,t)=>{let s=e.inputs;Id(s,t),e.compute(Md(e.inputs,t))},Od=e=>E({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Dd,zd,Ld,Bd,Wm=b(()=>{ze(),Me(),A(),_e(),Dd=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and
|
|
1491
|
+
indices input tensors be of same rank.`)},zd=(e,t)=>{let s=e[0].dims,i=e[0].dataType,o=s.length,l=e[1].dims,u=e[1].dataType,c=j.normalizeAxis(t.axis,o),h=s[c],p=l.slice(0),g=j.size(p),m=F("input",i,o),w=F("indicesInput",u,l.length),_=de("output",i,p.length),S=[{type:12,data:g},{type:6,data:h},{type:12,data:c}];return S.push(...L(s,l,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:S}),getShaderSource:C=>`
|
|
1492
|
+
${C.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(m,w,_)}
|
|
1493
|
+
${C.mainStart()}
|
|
1494
|
+
${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1495
|
+
|
|
1496
|
+
let outputIndices = ${_.offsetToIndices("global_idx")};
|
|
1497
|
+
|
|
1498
|
+
var idx = ${w.getByOffset("global_idx")};
|
|
1499
|
+
if (idx < 0) {
|
|
1500
|
+
idx = idx + uniforms.axisDimLimit;
|
|
1501
|
+
}
|
|
1502
|
+
var inputIndices = ${m.type.indices}(outputIndices);
|
|
1503
|
+
${m.indicesSet("inputIndices","uniforms.axis","u32(idx)")};
|
|
1504
|
+
let value = ${m.getByIndices("inputIndices")};
|
|
1505
|
+
|
|
1506
|
+
${_.setByOffset("global_idx","value")};
|
|
1507
|
+
}`}},Ld=e=>E({axis:e.axis}),Bd=(e,t)=>{let s=e.inputs;Dd(s),e.compute(zd(e.inputs,t))}}),Nd,Ud,Fd,Vd,Hm=b(()=>{ze(),Me(),_e(),Nd=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")},Ud=(e,t)=>{let s=e[0].dims.slice(),i=e[1].dims.slice(),[o,l,u]=Hn.getShapeOfGemmResult(s,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),g=Math.ceil(o/h),m=!0,w=j.size(c),_=[{type:12,data:m?p:w},{type:12,data:o},{type:12,data:l},{type:12,data:u},{type:1,data:t.alpha},{type:1,data:t.beta}],S=["type","type"];e.length===3&&(_.push(...L(e[2].dims)),S.push("rank")),_.push(...L(c));let C=k=>{let x="";t.transA&&t.transB?x="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?x="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?x="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(x="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let O=t.alpha===1?"":"value *= uniforms.alpha;",I=F("a",e[0].dataType,e[0].dims),z=F("b",e[1].dataType,e[1].dims),W=I.type.value,q=null,J=[I,z];e.length===3&&(q=F("c",e[2].dataType,e[2].dims.length),J.push(q));let oe=de("output",e[0].dataType,c.length);J.push(oe);let ge=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return`
|
|
1508
|
+
${k.registerUniforms(ge).declareVariables(...J)}
|
|
1509
|
+
|
|
1510
|
+
${k.mainStart()}
|
|
1511
|
+
${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1512
|
+
|
|
1513
|
+
let m = global_idx / uniforms.N;
|
|
1514
|
+
let n = global_idx % uniforms.N;
|
|
1515
|
+
|
|
1516
|
+
var value = ${W}(0);
|
|
1517
|
+
for (var k: u32 = 0u; k < uniforms.K; k++) {
|
|
1518
|
+
${x}
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
${O}
|
|
1522
|
+
${q!=null?`let cOffset = ${q.broadcastedIndicesToOffset("vec2(m, n)",oe)}; value += ${W}(uniforms.beta) * ${q.getByOffset("cOffset")};`:""}
|
|
1523
|
+
output[global_idx] = value;
|
|
1524
|
+
}`},M=k=>{let x=F("a",e[0].dataType,e[0].dims),O=F("b",e[1].dataType,e[1].dims),I=null,z=[x,O];e.length===3&&(I=F("c",e[2].dataType,e[2].dims.length),z.push(I));let W=de("output",e[0].dataType,c.length);z.push(W);let q=[{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"}],J="",oe="";t.transA&&t.transB?(oe=`
|
|
1525
|
+
var col = tile_row_start + local_id.x;
|
|
1526
|
+
var row = k_start + local_id.y;
|
|
1527
|
+
if (col < uniforms.M && row < uniforms.K) {
|
|
1528
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
|
|
1529
|
+
} else {
|
|
1530
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
col = k_start + local_id.x;
|
|
1534
|
+
row = tile_col_start + local_id.y;
|
|
1535
|
+
if (col < uniforms.K && row < uniforms.N) {
|
|
1536
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
|
|
1537
|
+
} else {
|
|
1538
|
+
tile_b[local_id.y][local_id.x] = ${O.type.value}(0);
|
|
1539
|
+
}
|
|
1540
|
+
`,J="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(oe=`
|
|
1541
|
+
var col = tile_row_start + local_id.x;
|
|
1542
|
+
var row = k_start + local_id.y;
|
|
1543
|
+
if (col < uniforms.M && row < uniforms.K) {
|
|
1544
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
|
|
1545
|
+
} else {
|
|
1546
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
col = tile_col_start + local_id.x;
|
|
1550
|
+
row = k_start + local_id.y;
|
|
1551
|
+
if (col < uniforms.N && row < uniforms.K) {
|
|
1552
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
|
|
1553
|
+
} else {
|
|
1554
|
+
tile_b[local_id.y][local_id.x] = ${O.type.value}(0);
|
|
1555
|
+
}
|
|
1556
|
+
`,J="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(oe=`
|
|
1557
|
+
var col = k_start + local_id.x;
|
|
1558
|
+
var row = tile_row_start + local_id.y;
|
|
1559
|
+
if (col < uniforms.K && row < uniforms.M) {
|
|
1560
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
|
|
1561
|
+
} else {
|
|
1562
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
col = k_start + local_id.x;
|
|
1566
|
+
row = tile_col_start + local_id.y;
|
|
1567
|
+
if (col < uniforms.K && row < uniforms.N) {
|
|
1568
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
|
|
1569
|
+
} else {
|
|
1570
|
+
tile_b[local_id.y][local_id.x] = ${O.type.value}(0);
|
|
1571
|
+
}
|
|
1572
|
+
`,J="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(oe=`
|
|
1573
|
+
var col = k_start + local_id.x;
|
|
1574
|
+
var row = tile_row_start + local_id.y;
|
|
1575
|
+
if (col < uniforms.K && row < uniforms.M) {
|
|
1576
|
+
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
|
|
1577
|
+
} else {
|
|
1578
|
+
tile_a[local_id.y][local_id.x] = ${x.type.value}(0);
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
col = tile_col_start + local_id.x;
|
|
1582
|
+
row = k_start + local_id.y;
|
|
1583
|
+
if (col < uniforms.N && row < uniforms.K) {
|
|
1584
|
+
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
|
|
1585
|
+
} else {
|
|
1586
|
+
tile_b[local_id.y][local_id.x] = ${O.type.value}(0);
|
|
1587
|
+
}
|
|
1588
|
+
`,J="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let ge=t.alpha===1?"":"value *= uniforms.alpha;";return`
|
|
1589
|
+
${k.registerUniforms(q).declareVariables(...z)}
|
|
1590
|
+
var<workgroup> tile_a: array<array<${x.type.storage}, ${h}>, ${h}>;
|
|
1591
|
+
var<workgroup> tile_b: array<array<${O.type.storage}, ${h}>, ${h}>;
|
|
1592
|
+
${k.mainStart([h,h,1])}
|
|
1593
|
+
let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${h};
|
|
1594
|
+
let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${h};
|
|
1595
|
+
let num_tiles = (uniforms.K - 1) / ${h} + 1;
|
|
1596
|
+
var k_start = 0u;
|
|
1597
|
+
var value = ${W.type.value}(0);
|
|
1598
|
+
for (var t: u32 = 0u; t < num_tiles; t++) {
|
|
1599
|
+
${oe}
|
|
1600
|
+
k_start = k_start + ${h};
|
|
1601
|
+
workgroupBarrier();
|
|
1602
|
+
|
|
1603
|
+
for (var k: u32 = 0u; k < ${h}; k++) {
|
|
1604
|
+
${J}
|
|
1605
|
+
}
|
|
1606
|
+
workgroupBarrier();
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
${ge}
|
|
1610
|
+
let m = tile_row_start + local_id.y;
|
|
1611
|
+
let n = tile_col_start + local_id.x;
|
|
1612
|
+
${I!=null?`let cOffset = ${I.broadcastedIndicesToOffset("vec2(m, n)",W)}; value += ${W.type.value}(uniforms.beta) * ${I.getByOffset("cOffset")};`:""}
|
|
1613
|
+
if (m < uniforms.M && n < uniforms.N) {
|
|
1614
|
+
output[m * uniforms.N + n] = value;
|
|
1615
|
+
}
|
|
1616
|
+
}`};return m?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:p*g},programUniforms:_}),getShaderSource:M}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:_}),getShaderSource:C}},Fd=e=>{let t=e.transA,s=e.transB,i=e.alpha,o=e.beta;return{transA:t,transB:s,alpha:i,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Vd=(e,t)=>{Nd(e.inputs),e.compute(Ud(e.inputs,t))}}),Rr,Ur,Pn,On,Gd,qd,Wd,Hd,jd,Kd,Qd,Xd,Yd,Jd,jm=b(()=>{ze(),Me(),A(),_e(),[Rr,Ur,Pn,On]=[0,1,2,3],Gd=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")},qd=`
|
|
1617
|
+
fn gs_get_cubic_coeffs(x: f32) -> vec4<f32> {
|
|
1618
|
+
let cubic_alpha = -0.75f;
|
|
1619
|
+
let x_abs = abs(x);
|
|
1620
|
+
var coeffs: vec4<f32>;
|
|
1621
|
+
coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);
|
|
1622
|
+
coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);
|
|
1623
|
+
coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);
|
|
1624
|
+
coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);
|
|
1625
|
+
return coeffs;
|
|
1626
|
+
}
|
|
1627
|
+
`,Wd=e=>`
|
|
1628
|
+
fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {
|
|
1629
|
+
var v: vec4<f32>;
|
|
1630
|
+
var coeffs = gs_get_cubic_coeffs(x);
|
|
1631
|
+
for (var i = 0; i < 4; i++) {
|
|
1632
|
+
v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];
|
|
1633
|
+
}
|
|
1634
|
+
coeffs = gs_get_cubic_coeffs(y);
|
|
1635
|
+
let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);
|
|
1636
|
+
return pixel;
|
|
1637
|
+
}
|
|
1638
|
+
`,Hd=e=>`
|
|
1639
|
+
fn gs_denormalize(n: f32, length: i32) -> f32 {
|
|
1640
|
+
${e.alignCorners===0?`
|
|
1641
|
+
// alignCorners: false => [-1, 1] to [-0.5, length - 0.5]
|
|
1642
|
+
return ((n + 1.0) * f32(length) - 1.0) / 2.0;
|
|
1643
|
+
`:`
|
|
1644
|
+
// alignCorners: true => [-1, 1] to [0, length - 1]
|
|
1645
|
+
return (n + 1.0) / 2.0 * (f32(length - 1));
|
|
1646
|
+
`}
|
|
1647
|
+
}
|
|
1648
|
+
`,jd=e=>`
|
|
1649
|
+
${e.paddingMode==="reflection"?`
|
|
1650
|
+
fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {
|
|
1651
|
+
var dx = 0.0;
|
|
1652
|
+
var fx = f32(x);
|
|
1653
|
+
let range = x_max - x_min;
|
|
1654
|
+
if (fx < x_min) {
|
|
1655
|
+
dx = x_min - fx;
|
|
1656
|
+
let n = u32(dx / range);
|
|
1657
|
+
let r = dx - f32(n) * range;
|
|
1658
|
+
if (n % 2 == 0) {
|
|
1659
|
+
fx = x_min + r;
|
|
1660
|
+
} else {
|
|
1661
|
+
fx = x_max - r;
|
|
1662
|
+
}
|
|
1663
|
+
} else if (fx > x_max) {
|
|
1664
|
+
dx = fx - x_max;
|
|
1665
|
+
let n = u32(dx / range);
|
|
1666
|
+
let r = dx - f32(n) * range;
|
|
1667
|
+
if (n % 2 == 0) {
|
|
1668
|
+
fx = x_max - r;
|
|
1669
|
+
} else {
|
|
1670
|
+
fx = x_min + r;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
return u32(fx);
|
|
1674
|
+
}`:""}
|
|
1675
|
+
`,Kd=(e,t,s)=>`
|
|
1676
|
+
fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4<f32>) -> ${t} {
|
|
1677
|
+
var pixel = ${t}(0);
|
|
1678
|
+
var indices = vec4<u32>(0);
|
|
1679
|
+
indices[${Rr}] = batch;
|
|
1680
|
+
indices[${Ur}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return`
|
|
1681
|
+
if (r >= 0 && r < H && c >=0 && c < W) {
|
|
1682
|
+
indices[${Pn}] = u32(r);
|
|
1683
|
+
indices[${On}] = u32(c);
|
|
1684
|
+
} else {
|
|
1685
|
+
return ${t}(0);
|
|
1686
|
+
}
|
|
1687
|
+
`;case"border":return`
|
|
1688
|
+
indices[${Pn}] = u32(clamp(r, 0, H - 1));
|
|
1689
|
+
indices[${On}] = u32(clamp(c, 0, W - 1));
|
|
1690
|
+
`;case"reflection":return`
|
|
1691
|
+
indices[${Pn}] = gs_reflect(r, border[1], border[3]);
|
|
1692
|
+
indices[${On}] = gs_reflect(c, border[0], border[2]);
|
|
1693
|
+
`;default:throw new Error(`padding mode ${s.paddingMode} is not supported`)}})()+`
|
|
1694
|
+
return ${e.getByIndices("indices")};
|
|
1695
|
+
}
|
|
1696
|
+
`,Qd=(e,t,s)=>(()=>{switch(s.mode){case"nearest":return`
|
|
1697
|
+
let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Rr}], indices[${Ur}], border);
|
|
1698
|
+
`;case"bilinear":return`
|
|
1699
|
+
let x1 = i32(floor(x));
|
|
1700
|
+
let y1 = i32(floor(y));
|
|
1701
|
+
let x2 = x1 + 1;
|
|
1702
|
+
let y2 = y1 + 1;
|
|
1703
|
+
|
|
1704
|
+
let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Rr}], indices[${Ur}], border);
|
|
1705
|
+
let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Rr}], indices[${Ur}], border);
|
|
1706
|
+
let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Rr}], indices[${Ur}], border);
|
|
1707
|
+
let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Rr}], indices[${Ur}], border);
|
|
1708
|
+
|
|
1709
|
+
let dx2 = ${t}(f32(x2) - x);
|
|
1710
|
+
let dx1 = ${t}(x - f32(x1));
|
|
1711
|
+
let dy2 = ${t}(f32(y2) - y);
|
|
1712
|
+
let dy1 = ${t}(y - f32(y1));
|
|
1713
|
+
let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);
|
|
1714
|
+
`;case"bicubic":return`
|
|
1715
|
+
let x0 = i32(floor(x)) - 1;
|
|
1716
|
+
let y0 = i32(floor(y)) - 1;
|
|
1717
|
+
var p: mat4x4<${t}>;
|
|
1718
|
+
for (var h = 0; h < 4; h++) {
|
|
1719
|
+
for (var w = 0; w < 4; w++) {
|
|
1720
|
+
p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Rr}], indices[${Ur}], border);
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
let dx = x - f32(x0 + 1);
|
|
1725
|
+
let dy = y - f32(y0 + 1);
|
|
1726
|
+
let result = gs_bicubic_interpolate(p, dx, dy);
|
|
1727
|
+
`;default:throw new Error(`mode ${s.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Xd=(e,t)=>{let s=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]],[Rr,Ur,Pn,On]=[0,3,1,2]);let u=de("output",e[0].dataType,l.length),c=s.type.value,h=j.size(l),p=[{type:12,data:h},...L(e[0].dims,i,l)],g=m=>`
|
|
1728
|
+
${m.registerUniform("output_size","u32").declareVariables(s,o,u)}
|
|
1729
|
+
${qd}
|
|
1730
|
+
${Wd(c)}
|
|
1731
|
+
${Hd(t)}
|
|
1732
|
+
${jd(t)}
|
|
1733
|
+
${Kd(s,c,t)}
|
|
1734
|
+
|
|
1735
|
+
${m.mainStart()}
|
|
1736
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1737
|
+
let H_in = i32(uniforms.x_shape[${Pn}]);
|
|
1738
|
+
let W_in = i32(uniforms.x_shape[${On}]);
|
|
1739
|
+
|
|
1740
|
+
${t.alignCorners===0?`
|
|
1741
|
+
let x_min = -0.5;
|
|
1742
|
+
let x_max = f32(W_in) - 0.5;
|
|
1743
|
+
let y_min = -0.5;
|
|
1744
|
+
let y_max = f32(H_in) - 0.5;
|
|
1745
|
+
`:`
|
|
1746
|
+
let x_min = 0.0;
|
|
1747
|
+
let x_max = f32(W_in) - 1.0;
|
|
1748
|
+
let y_min = 0.0;
|
|
1749
|
+
let y_max = f32(H_in) - 1.0;
|
|
1750
|
+
`};
|
|
1751
|
+
let border = vec4<f32>(x_min, y_min, x_max, y_max);
|
|
1752
|
+
|
|
1753
|
+
let indices = ${u.offsetToIndices("global_idx")};
|
|
1754
|
+
var grid_indices = vec3<u32>(indices[${Rr}], indices[${Pn}], indices[${On}]);
|
|
1755
|
+
let nxy = ${o.getByIndices("grid_indices")};
|
|
1756
|
+
var x = gs_denormalize(f32(nxy[0]), W_in);
|
|
1757
|
+
var y = gs_denormalize(f32(nxy[1]), H_in);
|
|
1758
|
+
|
|
1759
|
+
${Qd(u,c,t)}
|
|
1760
|
+
}`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:m=>{let w=j.size(l);return{outputs:[{dims:l,dataType:m[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:p}},getShaderSource:g}},Yd=(e,t)=>{Gd(e.inputs),e.compute(Xd(e.inputs,t))},Jd=e=>E({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),jt,Zd,ec,ka,tc,Ws,rc,nc=b(()=>{ze(),Me(),A(),Xn(),ia(),_e(),He(),jt=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Zd=(e,t)=>{let s=e[0],i=jt(e,1),o=jt(e,2),l=jt(e,3),u=jt(e,4),c=jt(e,5),h=jt(e,6),p=jt(e,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let g=s.dims[0],m=s.dims[1],w=s.dims.length===3?s.dims[2]:t.numHeads*s.dims[4],_=m,S=0,C=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]!==g||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]!==g||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],C=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(s.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(s.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]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');k=2,_=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==M)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');k=5,_=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==M)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');k=0,_=i.dims[2]}}else{if(s.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(s.dims[2]!==t.numHeads||s.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 x=S+_,O=0;if(u&&j.size(u.dims)>0){O=8;let q=u.dims;throw q.length===1?q[0]===g?O=1:q[0]===3*g+2&&(O=3):q.length===2&&q[0]===g&&q[1]===x&&(O=5),O===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let I=!1,z=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(s.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(_!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');z=o.dims[2]}else{if(_!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');z=o.dims[1]*o.dims[3],I=!0}}let W=!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]!==g||c.dims[1]!==t.numHeads||c.dims[2]!==m||c.dims[3]!==x)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:g,sequenceLength:m,pastSequenceLength:S,kvSequenceLength:_,totalSequenceLength:x,maxSequenceLength:C,inputHiddenSize:0,hiddenSize:w,vHiddenSize:z,headSize:M,vHeadSize:Math.floor(z/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:O,scale:t.scale,broadcastResPosBias:W,passPastInKv:I,qkvFormat:k}},ec=e=>E({...e}),ka=E({perm:[0,2,1,3]}),tc=(e,t,s,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}],g=m=>{let w=de("qkv_with_bias",t.dataType,c),_=F("qkv",t.dataType,c),S=F("bias",s.dataType,c),C=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`
|
|
1761
|
+
${m.registerUniforms(C).declareVariables(_,S,w)}
|
|
1762
|
+
${m.mainStart()}
|
|
1763
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1764
|
+
let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
|
|
1765
|
+
|
|
1766
|
+
qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];
|
|
1767
|
+
}`};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:g},{inputs:[t,s],outputs:[-1]})[0]},Ws=(e,t,s,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=tc(e,l,u,t,i,s*o,c),h=h.reshape([t,i,s,o]),s===1||i===1?h:e.compute(bt(h,ka.perm),{inputs:[h],outputs:[-1]})[0]}else return l.dims.length===3&&(h=l.reshape([t,i,s,o])),s===1||i===1?h:e.compute(bt(h,ka.perm),{inputs:[h],outputs:[-1]})[0]},rc=(e,t)=>{let s=Zd(e.inputs,t),i=e.inputs[0],o=jt(e.inputs,1),l=jt(e.inputs,2),u=jt(e.inputs,3),c=jt(e.inputs,4),h=jt(e.inputs,5),p=jt(e.inputs,6),g=jt(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 m=o&&l&&o.dims.length===4&&l.dims.length===4,w=Ws(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,i,u,0);if(m)return Us(e,w,o,l,c,void 0,p,g,h,s);if(!o||!l)throw new Error("key and value must be provided");let _=Ws(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,o,u,s.hiddenSize),S=Ws(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,l,u,2*s.hiddenSize);Us(e,w,_,S,c,void 0,p,g,h,s)}}),sc,ic,ac,oc,Ra,lc,uc,dc=b(()=>{ze(),Me(),A(),_e(),sc=e=>{if(!e||e.length<1)throw new Error("too few inputs")},ic=(e,t)=>{let s=[],i=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>s.push(Number(o))),i=s.length),E({numOutputs:i,axis:t.axis,splitSizes:s})},ac=e=>`
|
|
1768
|
+
fn calculateOutputIndex(index: u32) -> u32 {
|
|
1769
|
+
for (var i: u32 = 0u; i < ${e}u; i += 1u ) {
|
|
1770
|
+
if (index < ${K("uniforms.size_in_split_axis","i",e)}) {
|
|
1771
|
+
return i;
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
return ${e}u;
|
|
1775
|
+
}`,oc=e=>{let t=e.length,s=[];for(let i=0;i<t;++i){let o=e[i].setByIndices("indices","input[global_idx]");t===1?s.push(o):i===0?s.push(`if (output_number == ${i}u) { ${o} }`):i===t-1?s.push(`else { ${o} }`):s.push(`else if (output_number == ${i}) { ${o} }`)}return`
|
|
1776
|
+
fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) {
|
|
1777
|
+
${s.join(`
|
|
1778
|
+
`)}
|
|
1779
|
+
}`},Ra=(e,t)=>{let s=e[0].dims,i=j.size(s),o=e[0].dataType,l=j.normalizeAxis(t.axis,s.length),u=new Array(t.numOutputs),c=F("input",o,s.length),h=new Array(t.numOutputs),p=[],g=[],m=0,w=[{type:12,data:i}];for(let S=0;S<t.numOutputs;S++){m+=t.splitSizes[S],h[S]=m;let C=s.slice();C[l]=t.splitSizes[S],g.push(C),u[S]=de(`output${S}`,o,C.length),p.push({dims:g[S],dataType:e[0].dataType})}w.push({type:12,data:h},...L(s,...g));let _=S=>`
|
|
1780
|
+
${S.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",h.length).declareVariables(c,...u)}
|
|
1781
|
+
${ac(h.length)}
|
|
1782
|
+
${oc(u)}
|
|
1783
|
+
|
|
1784
|
+
${S.mainStart()}
|
|
1785
|
+
${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}
|
|
1786
|
+
|
|
1787
|
+
var indices = ${c.offsetToIndices("global_idx")};
|
|
1788
|
+
var index = ${c.indicesGet("indices",l)};
|
|
1789
|
+
let output_number = calculateOutputIndex(index);
|
|
1790
|
+
if (output_number != 0) {
|
|
1791
|
+
index -= ${K("uniforms.size_in_split_axis","output_number - 1u",h.length)};
|
|
1792
|
+
${c.indicesSet("indices",l,"index")};
|
|
1793
|
+
}
|
|
1794
|
+
writeBufferData(output_number, indices, global_idx);
|
|
1795
|
+
}`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(i/64)},programUniforms:w})}},lc=(e,t)=>{sc(e.inputs);let s=e.inputs.length===1?t:ic(e.inputs,t);e.compute(Ra(e.inputs,s),{inputs:[0]})},uc=e=>{let t=e.axis,s=e.splitSizes,i=e.numOutputs<0?s.length:e.numOutputs;if(i!==s.length)throw new Error("numOutputs and splitSizes length must be equal");return E({axis:t,numOutputs:i,splitSizes:s})}}),cc,xi,hc,pc=b(()=>{ze(),Me(),A(),_e(),cc=(e,t)=>{let[s,i,o,l]=e,{numHeads:u,rotaryEmbeddingDim:c}=t;if(s.dims.length!==3&&s.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${s.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=s.dims[0],p=s.dims[s.dims.length-2],g=o.dims[0],m=j.sizeFromDimension(s.dims,1)/p,w=c===0?o.dims[1]*2:m/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(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]}`);if(p>g)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},xi=(e,t)=>{let{interleaved:s,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,g=e[2].dims[1],m=o===0?g*2:p/i,w=new Array(u,h,p/m,m-g),_=j.computeStrides(w),S=[{type:1,data:l},{type:12,data:w},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[c,p,m,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[c,m,h*m,1]}):[],...L(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],C=M=>{let k=F("input",e[0].dataType,e[0].dims.length),x=F("position_ids",e[1].dataType,e[1].dims.length),O=F("cos_cache",e[2].dataType,e[2].dims.length),I=F("sin_cache",e[3].dataType,e[3].dims.length),z=de("output",e[0].dataType,e[0].dims.length);return M.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:w.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),`
|
|
1796
|
+
${M.declareVariables(k,x,O,I,z)}
|
|
1797
|
+
|
|
1798
|
+
${M.mainStart(D)}
|
|
1799
|
+
let half_rotary_emb_dim = uniforms.${O.name}_shape[1];
|
|
1800
|
+
let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;
|
|
1801
|
+
let size = uniforms.global_shape[0] * uniforms.global_strides[0];
|
|
1802
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("size")}
|
|
1803
|
+
|
|
1804
|
+
if (bsnh[3] < half_rotary_emb_dim) {
|
|
1805
|
+
let position_ids_idx =
|
|
1806
|
+
${x.broadcastedIndicesToOffset("bsnh.xy",de("",x.type.tensor,2))};
|
|
1807
|
+
let position_id =
|
|
1808
|
+
u32(${x.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);
|
|
1809
|
+
let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${s});
|
|
1810
|
+
let j = i + select(half_rotary_emb_dim, 1, ${s});
|
|
1811
|
+
let re = ${k.getByOffset("i")} * ${O.get("position_id","bsnh[3]")} -
|
|
1812
|
+
${k.getByOffset("j")} * ${I.get("position_id","bsnh[3]")};
|
|
1813
|
+
${z.setByOffset("i","re")}
|
|
1814
|
+
let im = ${k.getByOffset("i")} * ${I.get("position_id","bsnh[3]")} +
|
|
1815
|
+
${k.getByOffset("j")} * ${O.get("position_id","bsnh[3]")};
|
|
1816
|
+
${z.setByOffset("j","im")}
|
|
1817
|
+
} else {
|
|
1818
|
+
let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
|
|
1819
|
+
${z.setByOffset("k",k.getByOffset("k"))}
|
|
1820
|
+
}
|
|
1821
|
+
}`};return{name:"RotaryEmbedding",shaderCache:{hint:E({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:C,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(j.size(w)/D)},programUniforms:S})}},hc=(e,t)=>{cc(e.inputs,t),e.compute(xi(e.inputs,t))}}),fc,mc,Aa,gc,yc,Km=b(()=>{A(),ze(),ia(),nc(),dc(),He(),pc(),_e(),fc=(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 s=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(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=!1,h=s.dims[0],p=s.dims[1],g=s.dims.length===3?c?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],m=p,w=0,_=!i||i.dims.length===0,S=Math.floor(_?g/(t.numHeads+2*t.kvNumHeads):g/t.numHeads);_&&(g=S*t.numHeads);let C=l&&l.dims.length!==0,M=u&&u.dims.length!==0;if(C&&l.dims.length===4&&l.dims[0]===h&&l.dims[1]!==t.kvNumHeads&&l.dims[2]===t.kvNumHeads&&l.dims[3]===S)throw new Error("BSNH pastKey/pastValue is not supported");if(C&&M){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');w=l.dims[2]}else if(C||M)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let k=1;if(i&&i.dims.length>0){if(s.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(s.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(s.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]!==S)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]!==S)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');m=i.dims[2]}}else{if(s.dims.length!==3&&s.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(s.dims.length===5&&(s.dims[2]!==t.numHeads||s.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');k=3}let x=0,O=!1,I=t.kvNumHeads?S*t.kvNumHeads:g;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(s.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)');I=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)');I=o.dims[1]*o.dims[3],O=!0}}let z=e.length>4?e[5]:void 0;if(z&&z.dims.length!==1&&z.dims[0]!==h)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:h,sequenceLength:p,pastSequenceLength:w,kvSequenceLength:m,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:g,vHiddenSize:I,headSize:S,vHeadSize:Math.floor(I/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:x,scale:t.scale,broadcastResPosBias:!1,passPastInKv:O,qkvFormat:k}},mc=E({perm:[0,2,1,3]}),Aa=(e,t,s)=>{let i=t,o=s.kvNumHeads;return t.dims.length===3&&s.kvSequenceLength!==0&&(i=t.reshape([s.batchSize,s.kvSequenceLength,o,s.headSize]),i=e.compute(bt(i,mc.perm),{inputs:[i],outputs:[-1]})[0]),i},gc=(e,t,s,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=g=>{let m=F("seq_lens",s.dataType,s.dims),w=F("total_seq_lens",i.dataType,i.dims),_=de("pos_ids",o,u),S=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return`
|
|
1822
|
+
${g.registerUniforms(S).declareVariables(m,w,_)}
|
|
1823
|
+
${g.mainStart()}
|
|
1824
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1825
|
+
let total_sequence_length = u32(${w.getByOffset("0")});
|
|
1826
|
+
let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length;
|
|
1827
|
+
let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length;
|
|
1828
|
+
let batch_idx = global_idx / uniforms.sequence_length;
|
|
1829
|
+
let sequence_idx = i32(global_idx % uniforms.sequence_length);
|
|
1830
|
+
var pos_id: i32 = 0;
|
|
1831
|
+
let seqlen = ${m.getByOffset("batch_idx")};
|
|
1832
|
+
let total_seqlen = seqlen + 1;
|
|
1833
|
+
if (is_first_prompt) {
|
|
1834
|
+
if (sequence_idx < total_seqlen) {
|
|
1835
|
+
pos_id = sequence_idx;
|
|
1836
|
+
} else {
|
|
1837
|
+
pos_id = 1;
|
|
1838
|
+
}
|
|
1839
|
+
${_.setByOffset("global_idx","pos_id")}
|
|
1840
|
+
} else if (is_subsequent_prompt) {
|
|
1841
|
+
let past_seqlen = total_seqlen - i32(uniforms.sequence_length);
|
|
1842
|
+
if (past_seqlen + sequence_idx < total_seqlen) {
|
|
1843
|
+
pos_id = past_seqlen + sequence_idx;
|
|
1844
|
+
} else {
|
|
1845
|
+
pos_id = 1;
|
|
1846
|
+
}
|
|
1847
|
+
${_.setByOffset("global_idx","pos_id")}
|
|
1848
|
+
} else if (global_idx < uniforms.batch_size) {
|
|
1849
|
+
${_.setByOffset("global_idx","seqlen")}
|
|
1850
|
+
};
|
|
1851
|
+
}
|
|
1852
|
+
`};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}},yc=(e,t)=>{let s=fc(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,g=s.kvNumHeads?s.kvNumHeads:s.numHeads,m=E({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,g*s.headSize,g*s.headSize]}),[w,_,S]=!o&&!l?e.compute(Ra([i],m),{inputs:[i],outputs:[-1,-1,-1]}):[i,o,l],C,M;if(t.doRotary){let I=e.compute(gc(s.batchSize,s.sequenceLength,h,p),{inputs:[h,p],outputs:[-1]})[0],z=e.inputs[7],W=e.inputs[8],q=E({interleaved:t.rotaryInterleaved!==0,numHeads:s.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),J=[w,I,z,W],oe=[-1];C=e.compute(xi(J,q),{inputs:J,outputs:oe})[0],J.splice(0,1,_);let ge=E({interleaved:t.rotaryInterleaved!==0,numHeads:s.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});M=e.compute(xi(J,ge),{inputs:J,outputs:oe})[0]}let k=Ws(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,t.doRotary?C:w,void 0,0),x=Aa(e,t.doRotary?M:_,s),O=Aa(e,S,s);Us(e,k,x,O,void 0,void 0,u,c,void 0,s,h,p)}}),Ia,wc,vc,_c,Qm=b(()=>{ze(),Me(),He(),_e(),Ia=(e,t,s,i,o,l,u,c)=>{let h=V(l),p=h===1?"f32":`vec${h}f`,g=h===1?"vec2f":`mat2x${h}f`,m=o*u,w=64;m===1&&(w=256);let _=[o,u,l/h],S=[o,u,2],C=["rank","type","type"],M=[];M.push(...L(_,S));let k=x=>{let O=F("x",t.dataType,3,h),I=F("scale",s.dataType,s.dims),z=F("bias",i.dataType,i.dims),W=de("output",1,3,2),q=[O,I,z,W];return`
|
|
1853
|
+
var<workgroup> workgroup_shared : array<${g}, ${w}>;
|
|
1854
|
+
const workgroup_size = ${w}u;
|
|
1855
|
+
${x.declareVariables(...q)}
|
|
1856
|
+
${x.mainStart(w)}
|
|
1857
|
+
let batch = workgroup_index / uniforms.x_shape[1];
|
|
1858
|
+
let channel = workgroup_index % uniforms.x_shape[1];
|
|
1859
|
+
let hight = uniforms.x_shape[2];
|
|
1860
|
+
// initialize workgroup memory
|
|
1861
|
+
var sum = ${p}(0);
|
|
1862
|
+
var squared_sum = ${p}(0);
|
|
1863
|
+
for (var h = local_idx; h < hight; h += workgroup_size) {
|
|
1864
|
+
let value = ${p}(${O.get("batch","channel","h")});
|
|
1865
|
+
sum += value;
|
|
1866
|
+
squared_sum += value * value;
|
|
1867
|
+
}
|
|
1868
|
+
workgroup_shared[local_idx] = ${g}(sum, squared_sum);
|
|
1869
|
+
workgroupBarrier();
|
|
1870
|
+
|
|
1871
|
+
for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {
|
|
1872
|
+
if (local_idx < currSize) {
|
|
1873
|
+
workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];
|
|
1874
|
+
}
|
|
1875
|
+
workgroupBarrier();
|
|
1876
|
+
}
|
|
1877
|
+
if (local_idx == 0) {
|
|
1878
|
+
let sum_final = ${ee("workgroup_shared[0][0]",h)} / f32(hight * ${h});
|
|
1879
|
+
let squared_sum_final = ${ee("workgroup_shared[0][1]",h)} / f32(hight * ${h});
|
|
1880
|
+
|
|
1881
|
+
let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${c}));
|
|
1882
|
+
let channel_scale = inv_std_dev * f32(scale[channel]);
|
|
1883
|
+
let channel_shift = f32(bias[channel]) - sum_final * channel_scale;
|
|
1884
|
+
output[workgroup_index] = vec2f(channel_scale, channel_shift);
|
|
1885
|
+
}
|
|
1886
|
+
}`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${h};${c};${w}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:S,dataType:1}],dispatchGroup:{x:m},programUniforms:M}),getShaderSource:k},{inputs:[t,s,i],outputs:[-1]})[0]},wc=(e,t,s)=>{let i=t[0].dims,o=i,l=2,u=i[0],c=i[1],h=j.sizeFromDimension(i,l),p=V(h),g=j.size(o)/p,m=Ia(e,t[0],t[1],t[2],u,h,c,s.epsilon),w=[u,c,h/p],_=[u,c],S=["type","none"],C=M=>{let k=F("x",t[0].dataType,w.length,p),x=F("scale_shift",1,_.length,2),O=de("output",t[0].dataType,w.length,p),I=[k,x,O];return`
|
|
1887
|
+
${M.registerUniform("output_size","u32").declareVariables(...I)}
|
|
1888
|
+
${M.mainStart()}
|
|
1889
|
+
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1890
|
+
let outputIndices = ${O.offsetToIndices("global_idx")};
|
|
1891
|
+
let batch = outputIndices[0];
|
|
1892
|
+
let channel = outputIndices[1];
|
|
1893
|
+
let scale_shift = ${x.getByIndices("vec2<u32>(batch, channel)")};
|
|
1894
|
+
let value = ${k.getByOffset("global_idx")} * ${O.type.value}(scale_shift.x) + ${O.type.value}(scale_shift.y);
|
|
1895
|
+
${O.setByOffset("global_idx","value")};
|
|
1896
|
+
}`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${p}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...L(w,_,w)]}),getShaderSource:C},{inputs:[t[0],m]})},vc=(e,t,s)=>{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,g=[{type:12,data:c},{type:12,data:Math.floor(u/h)}],m=["type","type"],w=!1,_=[0,i.length-1];for(let k=0;k<i.length-2;k++)w=w||i[k+1]!==1,_.push(k+1);w=w&&i[i.length-1]!==1;let S=w?e.compute(bt(e.inputs[0],_),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:i.length},(k,x)=>i[_[x]])),C=Ia(e,S,t[1],t[2],l,c,u,s.epsilon),M=k=>{let x=G(t[0].dataType),O=h===1?"vec2f":`mat${h}x2f`,I=q=>{let J=q===0?"x":"y",oe=h===1?"f32":`vec${h}f`;switch(h){case 1:return`${x}(${oe}(scale.${J}))`;case 2:return`vec2<${x}>(${oe}(scale[0].${J}, scale[1].${J}))`;case 4:return`vec4<${x}>(${oe}(scale[0].${J}, scale[1].${J}, scale[2].${J}, scale[3].${J}))`;default:throw new Error(`Not supported compoents ${h}`)}},z=F("input",t[0].dataType,t[0].dims,h),W=de("output",t[0].dataType,o,h);return`
|
|
1897
|
+
@group(0) @binding(0) var<storage, read> input : array<${z.type.storage}>;
|
|
1898
|
+
@group(0) @binding(1) var<storage, read> scale_input : array<${O}>;
|
|
1899
|
+
@group(0) @binding(2) var<storage, read_write> output : array<${W.type.storage}>;
|
|
1900
|
+
struct Uniforms {H: u32, C : u32};
|
|
1901
|
+
@group(0) @binding(3) var<uniform> uniforms: Uniforms;
|
|
1902
|
+
|
|
1903
|
+
${k.mainStart()}
|
|
1904
|
+
let current_image_number = global_idx / (uniforms.C * uniforms.H);
|
|
1905
|
+
let current_channel_number = global_idx % uniforms.C;
|
|
1906
|
+
|
|
1907
|
+
let scale_offset = current_image_number * uniforms.C + current_channel_number;
|
|
1908
|
+
let scale = scale_input[scale_offset];
|
|
1909
|
+
output[global_idx] = fma(input[global_idx], ${I(0)}, ${I(1)});
|
|
1910
|
+
}`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${h}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:g}),getShaderSource:M},{inputs:[t[0],C]})},_c=(e,t)=>{t.format==="NHWC"?vc(e,e.inputs,t):wc(e,e.inputs,t)}}),bc,Sc,Tc,Xm=b(()=>{ze(),Me(),_e(),bc=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Sc=(e,t,s)=>{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),g=j.sizeFromDimension(o,h),m=j.size(l.dims),w=u?j.size(u.dims):0;if(m!==g||u&&w!==g)throw new Error(`Size of X.shape()[axis:] == ${g}.
|
|
1911
|
+
Size of scale and bias (if provided) must match this.
|
|
1912
|
+
Got scale size of ${m} and bias size of ${w}`);let _=[];for(let z=0;z<o.length;++z)z<h?_.push(o[z]):_.push(1);let S=V(g),C=["type","type"],M=[{type:12,data:p},{type:1,data:g},{type:12,data:Math.floor(g/S)},{type:1,data:t.epsilon}];u&&C.push("type");let k=s>1,x=s>2,O=z=>{let W=G(e[0].dataType),q=[F("x",e[0].dataType,e[0].dims,S),F("scale",l.dataType,l.dims,S)];u&&q.push(F("bias",u.dataType,u.dims,S)),q.push(de("output",e[0].dataType,c,S)),k&&q.push(de("mean_data_output",1,_)),x&&q.push(de("inv_std_output",1,_));let J=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`
|
|
1913
|
+
${z.registerUniforms(J).declareVariables(...q)}
|
|
1914
|
+
${z.mainStart()}
|
|
1915
|
+
${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}
|
|
1916
|
+
let offset = global_idx * uniforms.norm_size_vectorized;
|
|
1917
|
+
var mean_vector = ${ne("f32",S)};
|
|
1918
|
+
var mean_square_vector = ${ne("f32",S)};
|
|
1919
|
+
|
|
1920
|
+
for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {
|
|
1921
|
+
let value = ${ie(W,S,"x[h + offset]")};
|
|
1922
|
+
mean_vector += value;
|
|
1923
|
+
mean_square_vector += value * value;
|
|
1924
|
+
}
|
|
1925
|
+
let mean = ${ee("mean_vector",S)} / uniforms.norm_size;
|
|
1926
|
+
let inv_std_dev = inverseSqrt(${ee("mean_square_vector",S)} / uniforms.norm_size ${i?"":"- mean * mean"} + uniforms.epsilon);
|
|
1927
|
+
|
|
1928
|
+
for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {
|
|
1929
|
+
let f32input = ${ie(W,S,"x[j + offset]")};
|
|
1930
|
+
let f32scale = ${ie(W,S,"scale[j]")};
|
|
1931
|
+
output[j + offset] = ${q[0].type.value}((f32input ${i?"":"- mean"}) * inv_std_dev * f32scale
|
|
1932
|
+
${u?`+ ${ie(W,S,"bias[j]")}`:""}
|
|
1933
|
+
);
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1936
|
+
${k?"mean_data_output[global_idx] = mean":""};
|
|
1937
|
+
${x?"inv_std_output[global_idx] = inv_std_dev":""};
|
|
1938
|
+
}`},I=[{dims:c,dataType:e[0].dataType}];return k&&I.push({dims:_,dataType:1}),x&&I.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${S};${s};${i}`,inputDependencies:C},getRunData:()=>({outputs:I,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:M}),getShaderSource:O}},Tc=(e,t)=>{bc(e.inputs),e.compute(Sc(e.inputs,t,e.outputCount))}}),Ec,$c,Ym=b(()=>{Me(),pa(),ya(),Ec=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},$c=e=>{Ec(e.inputs);let t=$r.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let s=t[t.length-1],i=e.inputs[0].dims[e.inputs[0].dims.length-1];if(s<8&&i<8)e.compute(ha(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,s]),p=[1,l,s],g=[c,h];e.compute(Si(g,{activation:""},t,p),{inputs:g})}else e.compute(Si(e.inputs,{activation:""},t))}}}),xc,Cc,kc,Rc,Ac,Jm=b(()=>{ze(),Me(),A(),_e(),xc=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=e[0],i=s.dims.length;if(s.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.")}},Cc=(e,t)=>{let s=e[0].dims,i=s.length,o=s[i-2],l=t.k,u=t.n,c=s.slice(0,i-2),h=j.size(c),p=e[1].dims[2]/4,g=e[0].dataType,m=V(t.k),w=V(p),_=V(u),S=c.concat([o,u]),C=o>1&&u/_%2===0?2:1,M=j.size(S)/_/C,k=64,x=[],O=[h,o,l/m],I=j.convertShape(e[1].dims).slice();I.splice(-1,1,p/w),x.push(...L(O)),x.push(...L(I)),x.push(...L(e[2].dims)),e.length===4&&x.push(...L(j.convertShape(e[3].dims)));let z=[h,o,u/_];x.push(...L(z));let W=q=>{let J=O.length,oe=F("a",e[0].dataType,J,m),ge=F("b",12,I.length,w),Qe=F("scales",e[2].dataType,e[2].dims.length),Ae=[oe,ge,Qe],Be=e.length===4?F("zero_points",12,e[3].dims.length):void 0;Be&&Ae.push(Be);let ut=z.length,we=de("output",e[0].dataType,ut,_),ke=G(e[0].dataType),Xe=(()=>{switch(m){case 1:return`array<${ke}, 8>`;case 2:return`mat4x2<${ke}>`;case 4:return`mat2x4<${ke}>`;default:throw new Error(`${m}-component is not supported.`)}})(),Ve=()=>{let se=`
|
|
1939
|
+
// reuse a data
|
|
1940
|
+
var input_offset = ${oe.indicesToOffset(`${oe.type.indices}(batch, row, word_offset)`)};
|
|
1941
|
+
var a_data: ${Xe};
|
|
1942
|
+
for (var j: u32 = 0; j < ${8/m}; j++) {
|
|
1943
|
+
a_data[j] = ${oe.getByOffset("input_offset")};
|
|
1944
|
+
input_offset++;
|
|
1945
|
+
}
|
|
1946
|
+
`;for(let ve=0;ve<_*C;ve++)se+=`
|
|
1947
|
+
b_value = ${w===1?`b${ve}_data`:`b${ve}_data[i]`};
|
|
1948
|
+
b_value_lower = unpack4xU8(b_value & b_mask);
|
|
1949
|
+
b_value_upper = unpack4xU8((b_value >> 4) & b_mask);
|
|
1950
|
+
b_quantized_values = ${Xe}(${Array.from({length:4},(Ge,ht)=>`${ke}(b_value_lower[${ht}]), ${ke}(b_value_upper[${ht}])`).join(", ")});
|
|
1951
|
+
b_dequantized_values = ${m===1?`${Xe}(${Array.from({length:8},(Ge,ht)=>`(b_quantized_values[${ht}] - ${Be?`zero_point${ve}`:"zero_point"}) * scale${ve}`).join(", ")});`:`(b_quantized_values - ${Xe}(${Array(8).fill(`${Be?`zero_point${ve}`:"zero_point"}`).join(",")})) * scale${ve};`};
|
|
1952
|
+
workgroup_shared[local_id.x * ${C} + ${Math.floor(ve/_)}]${_>1?`[${ve%_}]`:""} += ${Array.from({length:8/m},(Ge,ht)=>`${m===1?`a_data[${ht}] * b_dequantized_values[${ht}]`:`dot(a_data[${ht}], b_dequantized_values[${ht}])`}`).join(" + ")};
|
|
1953
|
+
`;return se},Ue=()=>{let se=`
|
|
1954
|
+
var col_index = col * ${_};
|
|
1955
|
+
${Be?`
|
|
1956
|
+
let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;
|
|
1957
|
+
var zero_point_byte_count: u32;
|
|
1958
|
+
var zero_point_word_index: u32;
|
|
1959
|
+
var zero_point_byte_offset: u32;
|
|
1960
|
+
let zero_point_nibble_offset: u32 = block & 0x1u;
|
|
1961
|
+
var zero_point_bits_offset: u32;
|
|
1962
|
+
var zero_point_word: u32;`:`
|
|
1963
|
+
// The default zero point is 8 for unsigned 4-bit quantization.
|
|
1964
|
+
let zero_point = ${ke}(8);`}
|
|
1965
|
+
`;for(let ve=0;ve<_*C;ve++)se+=`
|
|
1966
|
+
let scale${ve} = ${Qe.getByOffset("col_index * nBlocksPerCol + block")};
|
|
1967
|
+
${Be?`
|
|
1968
|
+
zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u);
|
|
1969
|
+
zero_point_word_index = zero_point_byte_count >> 0x2u;
|
|
1970
|
+
zero_point_byte_offset = zero_point_byte_count & 0x3u;
|
|
1971
|
+
zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);
|
|
1972
|
+
zero_point_word = ${Be.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
1973
|
+
let zero_point${ve} = ${ke}((zero_point_word) & 0xFu);`:""}
|
|
1974
|
+
col_index += 1;`;return se},ct=()=>{let se=`col_index = col * ${_};`;for(let ve=0;ve<_*C;ve++)se+=`
|
|
1975
|
+
let b${ve}_data = ${ge.getByIndices(`${ge.type.indices}(col_index, block, word)`)};
|
|
1976
|
+
col_index += 1;`;return se+=`
|
|
1977
|
+
var b_value: u32;
|
|
1978
|
+
let b_mask: u32 = 0x0F0F0F0Fu;
|
|
1979
|
+
var b_value_lower: vec4<u32>;
|
|
1980
|
+
var b_value_upper: vec4<u32>;
|
|
1981
|
+
var b_quantized_values: ${Xe};
|
|
1982
|
+
var b_dequantized_values: ${Xe};`,se};return`
|
|
1983
|
+
var<workgroup> workgroup_shared: array<${we.type.value}, ${C*k}>;
|
|
1984
|
+
${q.declareVariables(...Ae,we)}
|
|
1985
|
+
${q.mainStart([k,1,1])}
|
|
1986
|
+
let output_indices = ${we.offsetToIndices(`(global_idx / ${k}) * ${C}`)};
|
|
1987
|
+
let col = output_indices[2];
|
|
1988
|
+
let row = output_indices[1];
|
|
1989
|
+
let batch = output_indices[0];
|
|
1990
|
+
let nBlocksPerCol = uniforms.b_shape[1];
|
|
1991
|
+
|
|
1992
|
+
for (var block = local_id.x; block < nBlocksPerCol; block += ${k}) {
|
|
1993
|
+
//process one block
|
|
1994
|
+
var word_offset: u32 = block * ${t.blockSize/m};
|
|
1995
|
+
${Ue()}
|
|
1996
|
+
for (var word: u32 = 0; word < ${p}; word += ${w}) {
|
|
1997
|
+
${ct()}
|
|
1998
|
+
for (var i: u32 = 0; i < ${w}; i++) {
|
|
1999
|
+
${Ve()}
|
|
2000
|
+
word_offset += ${8/m};
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
workgroupBarrier();
|
|
2005
|
+
|
|
2006
|
+
if (local_id.x < ${C}) {
|
|
2007
|
+
var output_value: ${we.type.value} = ${we.type.value}(0);
|
|
2008
|
+
var workgroup_shared_offset: u32 = local_id.x;
|
|
2009
|
+
for (var b: u32 = 0u; b < ${k}u; b++) {
|
|
2010
|
+
output_value += workgroup_shared[workgroup_shared_offset];
|
|
2011
|
+
workgroup_shared_offset += ${C};
|
|
2012
|
+
}
|
|
2013
|
+
${we.setByIndices(`${we.type.indices}(batch, row, col + local_id.x)`,"output_value")};
|
|
2014
|
+
}
|
|
2015
|
+
}`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${m};${w};${_};${C};${k}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:S,dataType:g}],dispatchGroup:{x:M},programUniforms:x}),getShaderSource:W}},kc=(e,t)=>{let s=e[0].dims,i=s.length,o=s[i-2],l=t.k,u=t.n,c=s.slice(0,i-2),h=j.size(c),p=e[1].dims[2]/4,g=e[0].dataType,m=V(t.k),w=V(p),_=c.concat([o,u]),S=128,C=u%8===0?8:u%4===0?4:1,M=S/C,k=M*w*8,x=k/m,O=k/t.blockSize,I=j.size(_)/C,z=[],W=[h,o,l/m],q=j.convertShape(e[1].dims).slice();q.splice(-1,1,p/w),z.push(...L(W)),z.push(...L(q)),z.push(...L(e[2].dims)),e.length===4&&z.push(...L(j.convertShape(e[3].dims)));let J=[h,o,u];z.push(...L(J));let oe=ge=>{let Qe=W.length,Ae=F("a",e[0].dataType,Qe,m),Be=F("b",12,q.length,w),ut=F("scales",e[2].dataType,e[2].dims.length),we=[Ae,Be,ut],ke=e.length===4?F("zero_points",12,e[3].dims.length):void 0;ke&&we.push(ke);let Xe=J.length,Ve=de("output",e[0].dataType,Xe),Ue=G(e[0].dataType),ct=()=>{switch(m){case 1:return`
|
|
2016
|
+
let a_data0 = vec4<${Ue}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);
|
|
2017
|
+
let a_data1 = vec4<${Ue}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`
|
|
2018
|
+
let a_data0 = vec4<${Ue}>(sub_a[word_offset], sub_a[word_offset + 1]);
|
|
2019
|
+
let a_data1 = vec4<${Ue}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`
|
|
2020
|
+
let a_data0 = sub_a[word_offset];
|
|
2021
|
+
let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${m}-component is not supported.`)}};return`
|
|
2022
|
+
var<workgroup> sub_a: array<${Ae.type.value}, ${x}>;
|
|
2023
|
+
var<workgroup> inter_results: array<array<${Ve.type.value}, ${M}>, ${C}>;
|
|
2024
|
+
${ge.declareVariables(...we,Ve)}
|
|
2025
|
+
${ge.mainStart([M,C,1])}
|
|
2026
|
+
let output_indices = ${Ve.offsetToIndices(`workgroup_index * ${C}`)};
|
|
2027
|
+
let col = output_indices[2];
|
|
2028
|
+
let row = output_indices[1];
|
|
2029
|
+
let batch = output_indices[0];
|
|
2030
|
+
let n_blocks_per_col = uniforms.b_shape[1];
|
|
2031
|
+
let num_tiles = (n_blocks_per_col - 1) / ${O} + 1;
|
|
2032
|
+
|
|
2033
|
+
// Loop over shared dimension.
|
|
2034
|
+
for (var tile: u32 = 0; tile < num_tiles; tile += 1) {
|
|
2035
|
+
let a_col_start = tile * ${x};
|
|
2036
|
+
// load one tile A data into shared memory.
|
|
2037
|
+
for (var a_offset = local_idx; a_offset < ${x}; a_offset += ${S})
|
|
2038
|
+
{
|
|
2039
|
+
let a_col = a_col_start + a_offset;
|
|
2040
|
+
if (a_col < uniforms.a_shape[2])
|
|
2041
|
+
{
|
|
2042
|
+
sub_a[a_offset] = ${Ae.getByIndices(`${Ae.type.indices}(batch, row, a_col)`)};
|
|
2043
|
+
} else {
|
|
2044
|
+
sub_a[a_offset] = ${Ae.type.value}(0);
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
workgroupBarrier();
|
|
2048
|
+
|
|
2049
|
+
// each thread process one block
|
|
2050
|
+
let b_row = col + local_id.y;
|
|
2051
|
+
let block = tile * ${O} + local_id.x;
|
|
2052
|
+
${ke?`
|
|
2053
|
+
let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;
|
|
2054
|
+
let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);
|
|
2055
|
+
let zero_point_word_index = zero_point_byte_count >> 0x2u;
|
|
2056
|
+
let zero_point_byte_offset = zero_point_byte_count & 0x3u;
|
|
2057
|
+
let zero_point_nibble_offset: u32 = block & 0x1u;
|
|
2058
|
+
let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);
|
|
2059
|
+
let zero_point_word = ${ke.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
2060
|
+
let zero_point = ${Ue}((zero_point_word) & 0xFu);`:`
|
|
2061
|
+
// The default zero point is 8 for unsigned 4-bit quantization.
|
|
2062
|
+
let zero_point = ${Ue}(8);`}
|
|
2063
|
+
let scale = ${ut.getByOffset("b_row * n_blocks_per_col + block")};
|
|
2064
|
+
let b_data = ${Be.getByIndices(`${Be.type.indices}(b_row, block, 0)`)};
|
|
2065
|
+
var word_offset = local_id.x * ${t.blockSize/m};
|
|
2066
|
+
for (var i: u32 = 0; i < ${w}; i++) {
|
|
2067
|
+
${ct()}
|
|
2068
|
+
let b_value = ${w===1?"b_data":"b_data[i]"};
|
|
2069
|
+
let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);
|
|
2070
|
+
let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);
|
|
2071
|
+
let b_quantized_values = mat2x4<${Ue}>(${Array.from({length:4},(se,ve)=>`${Ue}(b_value_lower[${ve}]), ${Ue}(b_value_upper[${ve}])`).join(", ")});
|
|
2072
|
+
let b_dequantized_values = (b_quantized_values - mat2x4<${Ue}>(${Array(8).fill("zero_point").join(",")})) * scale;
|
|
2073
|
+
inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(se,ve)=>`${`dot(a_data${ve}, b_dequantized_values[${ve}])`}`).join(" + ")};
|
|
2074
|
+
word_offset += ${8/m};
|
|
2075
|
+
}
|
|
2076
|
+
workgroupBarrier();
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
if (local_idx < ${C}) {
|
|
2080
|
+
var output_value: ${Ve.type.value} = ${Ve.type.value}(0);
|
|
2081
|
+
for (var b = 0u; b < ${M}; b++) {
|
|
2082
|
+
output_value += inter_results[local_idx][b];
|
|
2083
|
+
}
|
|
2084
|
+
if (col + local_idx < uniforms.output_shape[2])
|
|
2085
|
+
{
|
|
2086
|
+
${Ve.setByIndices(`${Ve.type.indices}(batch, row, col + local_idx)`,"output_value")}
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${m};${w};${M};${C}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:g}],dispatchGroup:{x:I},programUniforms:z}),getShaderSource:oe}},Rc=(e,t)=>{xc(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(kc(e.inputs,t)):e.compute(Cc(e.inputs,t))},Ac=e=>E(e)}),Ic,Mc,Pc,Oc,Dc,zc,Lc,Bc,Nc,Zm=b(()=>{ze(),Me(),_e(),Ic=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].")}},Mc=(e,t,s)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2090
|
+
k = i32(${e.indicesGet("indices",o)}) - ${K("uniforms.pads",o,s)};
|
|
2091
|
+
if (k < 0) {
|
|
2092
|
+
break;
|
|
2093
|
+
}
|
|
2094
|
+
if (k >= i32(${K("uniforms.x_shape",o,t)})) {
|
|
2095
|
+
break;
|
|
2096
|
+
}
|
|
2097
|
+
offset += k * i32(${K("uniforms.x_strides",o,t)});
|
|
2098
|
+
`;return`
|
|
2099
|
+
value = ${e.type.value}(uniforms.constant_value);
|
|
2100
|
+
for (var i = 0; i < 1; i++) {
|
|
2101
|
+
var offset = 0;
|
|
2102
|
+
var k = 0;
|
|
2103
|
+
${i}
|
|
2104
|
+
value = x[offset];
|
|
2105
|
+
}
|
|
2106
|
+
`},Pc=(e,t,s)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2107
|
+
k = i32(${e.indicesGet("indices",o)}) - ${K("uniforms.pads",o,s)};
|
|
2108
|
+
if (k < 0) {
|
|
2109
|
+
k = -k;
|
|
2110
|
+
}
|
|
2111
|
+
{
|
|
2112
|
+
let _2n_1 = 2 * (i32(${K("uniforms.x_shape",o,t)}) - 1);
|
|
2113
|
+
k = k % _2n_1;
|
|
2114
|
+
if(k >= i32(${K("uniforms.x_shape",o,t)})) {
|
|
2115
|
+
k = _2n_1 - k;
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
offset += k * i32(${K("uniforms.x_strides",o,t)});
|
|
2119
|
+
`;return`
|
|
2120
|
+
var offset = 0;
|
|
2121
|
+
var k = 0;
|
|
2122
|
+
${i}
|
|
2123
|
+
value = x[offset];
|
|
2124
|
+
`},Oc=(e,t,s)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2125
|
+
k = i32(${e.indicesGet("indices",o)}) - ${K("uniforms.pads",o,s)};
|
|
2126
|
+
if (k < 0) {
|
|
2127
|
+
k = 0;
|
|
2128
|
+
}
|
|
2129
|
+
if (k >= i32(${K("uniforms.x_shape",o,t)})) {
|
|
2130
|
+
k = i32(${K("uniforms.x_shape",o,t)}) - 1;
|
|
2131
|
+
}
|
|
2132
|
+
offset += k * i32(${K("uniforms.x_strides",o,t)});
|
|
2133
|
+
`;return`
|
|
2134
|
+
var offset = 0;
|
|
2135
|
+
var k = 0;
|
|
2136
|
+
${i}
|
|
2137
|
+
value = x[offset];
|
|
2138
|
+
`},Dc=(e,t,s)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2139
|
+
k = i32(${e.indicesGet("indices",o)}) - ${K("uniforms.pads",o,s)};
|
|
2140
|
+
if (k < 0) {
|
|
2141
|
+
k += i32(${K("uniforms.x_shape",o,t)}]);
|
|
2142
|
+
}
|
|
2143
|
+
if (k >= i32(${K("uniforms.x_shape",o,t)})) {
|
|
2144
|
+
k -= i32(${K("uniforms.x_shape",o,t)});
|
|
2145
|
+
}
|
|
2146
|
+
offset += k * i32(${K("uniforms.x_strides",o,t)});
|
|
2147
|
+
`;return`
|
|
2148
|
+
var offset = 0;
|
|
2149
|
+
var k = 0;
|
|
2150
|
+
${i}
|
|
2151
|
+
value = x[offset];
|
|
2152
|
+
`},zc=(e,t,s)=>{switch(s.mode){case 0:return Mc(e,t,s.pads.length);case 1:return Pc(e,t,s.pads.length);case 2:return Oc(e,t,s.pads.length);case 3:return Dc(e,t,s.pads.length);default:throw new Error("Invalid mode")}},Lc=(e,t)=>{let s=j.padShape(e[0].dims.slice(),t.pads),i=e[0].dims,o=j.size(s),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,s));let c=["rank"],h=p=>{let g=de("output",e[0].dataType,s.length),m=F("x",e[0].dataType,i.length),w=m.type.value,_=zc(g,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"}),`
|
|
2153
|
+
${p.registerUniforms(S).declareVariables(m,g)}
|
|
2154
|
+
${p.mainStart()}
|
|
2155
|
+
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2156
|
+
|
|
2157
|
+
let indices = ${g.offsetToIndices("global_idx")};
|
|
2158
|
+
|
|
2159
|
+
var value = ${w}(0);
|
|
2160
|
+
${_}
|
|
2161
|
+
output[global_idx] = value;
|
|
2162
|
+
}`};return{name:"Pad",shaderCache:{hint:`${t.mode}${u}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(j.size(s)/64)},programUniforms:l}),getShaderSource:h}},Bc=(e,t)=>{if(e.length>1){let s=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(s[h]),l[Number(c[h])+o]=Number(s[h+c.length])}else s.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},Nc=(e,t)=>{Ic(e.inputs);let s=Bc(e.inputs,t);e.compute(Lc(e.inputs,s),{inputs:[0]})}}),Hs,Ma,Pa,Oa,Da,Uc,Fc,za,La,Vc,Gc,Ba,qc,Wc,Na,Hc,jc,Kc,Qc,eg=b(()=>{Mt(),ze(),Me(),_e(),Hs=e=>{if(fe.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Ma=(e,t,s)=>{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();Qr.adjustPoolAttributes(s,o,u,c,h,p);let g=Qr.computePoolOutputShape(s,o,c,h,u,p,t.autoPad),m=Object.assign({},t);l?Object.assign(m,{kernelShape:u,strides:c,pads:p,dilations:h,cacheKey:t.cacheKey}):Object.assign(m,{kernelShape:u,strides:c,pads:p,cacheKey:t.cacheKey});let w=g.slice();return w.push(w.splice(1,1)[0]),[m,i?w:g]},Pa=(e,t)=>{let s=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],g=t.pads[t.pads.length-1],m=!!(p+g);l.push({type:12,data:c},{type:12,data:h},{type:12,data:p},{type:12,data:g}),u.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let w=!1;if(t.kernelShape.length===2){let _=t.kernelShape[t.kernelShape.length-2],S=t.strides[t.strides.length-2],C=t.pads[t.pads.length/2-2],M=t.pads[t.pads.length-2];w=!!(C+M),l.push({type:12,data:_},{type:12,data:S},{type:12,data:C},{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,m,w]}else{if(s)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,g)=>p+g);return[l,u,!!h,!1,!1]}},Oa=(e,t,s,i,o,l,u,c,h,p,g,m)=>{let w=o.format==="NHWC",_=t.type.value,S=de("output",t.type.tensor,i);if(o.kernelShape.length<=2){let C="",M="",k="",x=s-(w?2:1);if(g?C=`
|
|
2163
|
+
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2164
|
+
xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;
|
|
2165
|
+
if (xIndices[${x}] < 0 || xIndices[${x}]
|
|
2166
|
+
>= uniforms.x_shape[${x}]) {
|
|
2167
|
+
pad++;
|
|
2168
|
+
continue;
|
|
2169
|
+
}
|
|
2170
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2171
|
+
${l}
|
|
2172
|
+
}`:C=`
|
|
2173
|
+
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2174
|
+
xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;
|
|
2175
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2176
|
+
${l}
|
|
2177
|
+
}`,o.kernelShape.length===2){let O=s-(w?3:2);m?M=`
|
|
2178
|
+
for (var j: u32 = 0u; j < uniforms.kh; j++) {
|
|
2179
|
+
xIndices[${O}] = indices[${O}] * uniforms.sh - uniforms.phStart + j;
|
|
2180
|
+
if (xIndices[${O}] < 0 || xIndices[${O}] >= uniforms.x_shape[${O}]) {
|
|
2181
|
+
pad += i32(uniforms.kw);
|
|
2182
|
+
continue;
|
|
2183
|
+
}
|
|
2184
|
+
`:M=`
|
|
2185
|
+
for (var j: u32 = 0u; j < uniforms.kh; j++) {
|
|
2186
|
+
xIndices[${O}] = indices[${O}] * uniforms.sh - uniforms.phStart + j;
|
|
2187
|
+
`,k=`
|
|
2188
|
+
}
|
|
2189
|
+
`}return`
|
|
2190
|
+
${e.registerUniforms(h).declareVariables(t,S)}
|
|
2191
|
+
|
|
2192
|
+
${e.mainStart()}
|
|
2193
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2194
|
+
|
|
2195
|
+
let indices = ${S.offsetToIndices("global_idx")};
|
|
2196
|
+
var xIndices = ${S.offsetToIndices("global_idx")};
|
|
2197
|
+
|
|
2198
|
+
var value = ${_}(${c});
|
|
2199
|
+
var pad = 0;
|
|
2200
|
+
${M}
|
|
2201
|
+
${C}
|
|
2202
|
+
${k}
|
|
2203
|
+
${u}
|
|
2204
|
+
|
|
2205
|
+
output[global_idx] = value;
|
|
2206
|
+
}`}else{if(w)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let C=o.kernelShape.length,M=o.pads.length,k="";return p?k=`
|
|
2207
|
+
if (xIndices[j] >= uniforms.x_shape[j]) {
|
|
2208
|
+
pad++;
|
|
2209
|
+
isPad = true;
|
|
2210
|
+
break;
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
if (!isPad) {
|
|
2214
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2215
|
+
${l}
|
|
2216
|
+
}`:k=`
|
|
2217
|
+
}
|
|
2218
|
+
let x_val = x[${t.indicesToOffset("xIndices")}];
|
|
2219
|
+
${l}
|
|
2220
|
+
`,`
|
|
2221
|
+
${e.registerUniforms(h).declareVariables(t,S)}
|
|
2222
|
+
|
|
2223
|
+
${e.mainStart()}
|
|
2224
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2225
|
+
let indices = ${S.offsetToIndices("global_idx")};
|
|
2226
|
+
var xIndices = ${S.offsetToIndices("global_idx")};
|
|
2227
|
+
|
|
2228
|
+
var offsets: array<u32, ${C}>;
|
|
2229
|
+
|
|
2230
|
+
var value = ${_}(${c});
|
|
2231
|
+
var pad = 0;
|
|
2232
|
+
var isPad = false;
|
|
2233
|
+
|
|
2234
|
+
for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {
|
|
2235
|
+
var offset = i;
|
|
2236
|
+
for (var j = 0u; j < ${C-1}u; j++) {
|
|
2237
|
+
offsets[j] = offset / ${K("uniforms.kernelStrides","j",C)};
|
|
2238
|
+
offset -= offsets[j] * ${K("uniforms.kernelStrides","j",C)};
|
|
2239
|
+
}
|
|
2240
|
+
offsets[${C-1}] = offset;
|
|
2241
|
+
|
|
2242
|
+
isPad = false;
|
|
2243
|
+
for (var j = ${s-C}u; j < ${s}u; j++) {
|
|
2244
|
+
xIndices[j] = indices[j] * ${K("uniforms.strides",`j - ${s-C}u`,C)}
|
|
2245
|
+
+ offsets[j - ${s-C}u] - ${K("uniforms.pads","j - 2u",M)};
|
|
2246
|
+
${k}
|
|
2247
|
+
}
|
|
2248
|
+
${u}
|
|
2249
|
+
|
|
2250
|
+
output[global_idx] = value;
|
|
2251
|
+
}`}},Da=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Uc=e=>`${Da(e)};${e.countIncludePad}`,Fc=e=>`${Da(e)};${e.storageOrder};${e.dilations}`,za=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}),La=(e,t,s,i)=>{let[o,l]=Ma(t,i,s),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[g,m,w,_,S]=Pa(l,o);g.push(...L(t.dims,l));let C=["rank"];return{name:e,shaderCache:{hint:`${i.cacheKey};${w};${_};${S}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(j.size(l)/64)},programUniforms:g}),getShaderSource:M=>Oa(M,u,t.dims.length,l.length,o,h,p,0,m,w,_,S)}},Vc=e=>{let t=e.count_include_pad!==0,s=za(e);if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let i={countIncludePad:t,...s,cacheKey:""};return{...i,cacheKey:Uc(i)}},Gc=(e,t)=>{Hs(e.inputs),e.compute(La("AveragePool",e.inputs[0],!1,t))},Ba={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},qc=e=>{let t=e.format;return{format:t,...Ba,cacheKey:t}},Wc=(e,t)=>{Hs(e.inputs),e.compute(La("GlobalAveragePool",e.inputs[0],!0,t))},Na=(e,t,s,i)=>{let[o,l]=Ma(t,i,s),u=`
|
|
2252
|
+
value = max(x_val, value);
|
|
2253
|
+
`,c="",h=F("x",t.dataType,t.dims.length),p=["rank"],[g,m,w,_,S]=Pa(l,o);return g.push(...L(t.dims,l)),{name:e,shaderCache:{hint:`${i.cacheKey};${w};${_};${S}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(j.size(l)/64)},programUniforms:g}),getShaderSource:C=>Oa(C,h,t.dims.length,l.length,o,u,c,t.dataType===10?-65504:-1e5,m,w,_,S)}},Hc=(e,t)=>{Hs(e.inputs),e.compute(Na("MaxPool",e.inputs[0],!1,t))},jc=e=>{let t=e.storage_order,s=e.dilations,i=za(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:s,...i,cacheKey:""};return{...o,cacheKey:Fc(o)}},Kc=e=>{let t=e.format;return{format:t,...Ba,cacheKey:t}},Qc=(e,t)=>{Hs(e.inputs),e.compute(Na("GlobalMaxPool",e.inputs[0],!0,t))}}),Xc,Yc,Jc,Zc,tg=b(()=>{ze(),Me(),A(),_e(),Xc=(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[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");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((s,i)=>s===e[2].dims[i]).reduce((s,i)=>s&&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 s=e[0].dims[t.axis],i=e[1].dims[t.axis];if(t.blockSize<Math.ceil(s/i)||t.blockSize>Math.ceil(s/(i-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Yc=(e,t)=>{let s=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,g=e[1].dims,m=e.length>2?e[2]:void 0,w=m?h?[Math.ceil(j.size(m.dims)/4)]:m.dims:void 0,_=g.length===0||g.length===1&&g[0]===1,S=_===!1&&g.length===1,C=V(c),M=_&&(!h||C===4),k=M?C:1,x=M&&!h?C:1,O=F("input",h?12:i,p.length,x),I=F("scale",u,g.length),z=m?F("zero_point",h?12:i,w.length):void 0,W=de("output",u,l.length,k),q=[O,I];z&&q.push(z);let J=[p,g];m&&J.push(w);let oe=[{type:12,data:c/k},{type:12,data:s},{type:12,data:t.blockSize},...L(...J,l)],ge=Qe=>{let Ae=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
2254
|
+
${Qe.registerUniforms(Ae).declareVariables(...q,W)}
|
|
2255
|
+
${Qe.mainStart()}
|
|
2256
|
+
${Qe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2257
|
+
let output_indices = ${W.offsetToIndices("global_idx")};
|
|
2258
|
+
|
|
2259
|
+
// Set input x
|
|
2260
|
+
${h?`
|
|
2261
|
+
let input = ${O.getByOffset("global_idx / 4")};
|
|
2262
|
+
let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"};
|
|
2263
|
+
let x_value = ${k===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${O.getByOffset("global_idx")};`};
|
|
2264
|
+
|
|
2265
|
+
// Set scale input
|
|
2266
|
+
${_?`let scale_value= ${I.getByOffset("0")}`:S?`
|
|
2267
|
+
let scale_index = ${W.indicesGet("output_indices","uniforms.axis")};
|
|
2268
|
+
let scale_value= ${I.getByOffset("scale_index")};`:`
|
|
2269
|
+
var scale_indices: ${I.type.indices} = output_indices;
|
|
2270
|
+
let index = ${I.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size;
|
|
2271
|
+
${I.indicesSet("scale_indices","uniforms.axis","index")};
|
|
2272
|
+
let scale_value= ${I.getByIndices("scale_indices")};`};
|
|
2273
|
+
|
|
2274
|
+
// Set zero-point input
|
|
2275
|
+
${z?_?h?`
|
|
2276
|
+
let zero_point_input = ${z.getByOffset("0")};
|
|
2277
|
+
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2278
|
+
let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${z.getByOffset("0")}`:S?h?`
|
|
2279
|
+
let zero_point_index = ${W.indicesGet("output_indices","uniforms.axis")};
|
|
2280
|
+
let zero_point_input = ${z.getByOffset("zero_point_index / 4")};
|
|
2281
|
+
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2282
|
+
let zero_point_value = zero_point_vec[zero_point_index % 4]`:`
|
|
2283
|
+
let zero_point_index = ${W.indicesGet("output_indices","uniforms.axis")};
|
|
2284
|
+
let zero_point_value = ${z.getByOffset("zero_point_index")};`:h?`
|
|
2285
|
+
let zero_point_offset = ${I.indicesToOffset("scale_indices")};
|
|
2286
|
+
let zero_point_input = ${z.getByOffset("zero_point_offset / 4")};
|
|
2287
|
+
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2288
|
+
let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${z.getByIndices("scale_indices")};`:`let zero_point_value = ${h?o?"i32":"u32":O.type.value}(0);`};
|
|
2289
|
+
// Compute and write output
|
|
2290
|
+
${W.setByOffset("global_idx",`${W.type.value}(x_value - zero_point_value) * scale_value`)};
|
|
2291
|
+
}`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:z?["rank","rank","rank"]:["rank","rank"]},getShaderSource:ge,getRunData:()=>({outputs:[{dims:l,dataType:u}],dispatchGroup:{x:Math.ceil(c/k/64),y:1,z:1},programUniforms:oe})}},Jc=(e,t)=>{Xc(e.inputs,t),e.compute(Yc(e.inputs,t))},Zc=e=>E({axis:e.axis,blockSize:e.blockSize})}),eh,th,rh,rg=b(()=>{Mt(),ze(),_e(),eh=(e,t,s)=>{let i=e===t,o=e<t&&s<0,l=e>t&&s>0;if(i||o||l)throw new Error("Range these inputs' contents are invalid.")},th=(e,t,s,i)=>{let o=Math.abs(Math.ceil((t-e)/s)),l=[o],u=o,c=[{type:12,data:u},{type:i,data:e},{type:i,data:s},...L(l)],h=p=>{let g=de("output",i,l.length),m=g.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:m},{name:"delta",type:m}];return`
|
|
2292
|
+
${p.registerUniforms(w).declareVariables(g)}
|
|
2293
|
+
${p.mainStart()}
|
|
2294
|
+
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2295
|
+
output[global_idx] = uniforms.start + ${m}(global_idx) * uniforms.delta;
|
|
2296
|
+
}`};return{name:"Range",shaderCache:{hint:`${i}`},getShaderSource:h,getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c})}},rh=e=>{let t=0,s=0,i=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],s=e.inputs[1].getInt32Array()[0],i=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],s=e.inputs[1].getFloat32Array()[0],i=e.inputs[2].getFloat32Array()[0]),fe.webgpu.validateInputContent&&eh(t,s,i),e.compute(th(t,s,i,e.inputs[0].dataType),{inputs:[]})}}),nh,sh,ih,ah,ng=b(()=>{ze(),Me(),A(),_e(),nh=(e,t,s,i)=>{if(e!=="none"&&i!=="i32"&&i!=="u32"&&i!=="f32")throw new Error(`Input ${i} is not supported with reduction ${e}.`);let o=`{
|
|
2297
|
+
var oldValue = 0;
|
|
2298
|
+
loop {
|
|
2299
|
+
let newValueF32 =`,l=`;
|
|
2300
|
+
let newValue = bitcast<i32>(newValueF32);
|
|
2301
|
+
let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue);
|
|
2302
|
+
if res.exchanged {
|
|
2303
|
+
break;
|
|
2304
|
+
}
|
|
2305
|
+
oldValue = res.old_value;
|
|
2306
|
+
}
|
|
2307
|
+
}`;switch(e){case"none":return`${t}=${s};`;case"add":return i==="i32"||i==="u32"?`atomicAdd(&${t}, bitcast<${i}>(${s}));`:`
|
|
2308
|
+
${o}bitcast<${i}>(oldValue) + (${s})${l}`;case"max":return i==="i32"||i==="u32"?`atomicMax(&${t}, bitcast<${i}>(${s}));`:`
|
|
2309
|
+
${o}max(bitcast<f32>(oldValue), (${s}))${l}`;case"min":return i==="i32"||i==="u32"?`atomicMin(&${t}, bitcast<${i}>(${s}));`:`${o}min(bitcast<${i}>(oldValue), (${s}))${l}`;case"mul":return`${o}(bitcast<${i}>(oldValue) * (${s}))${l}`;default:throw new Error(`Reduction ${e} is not supported.`)}},sh=(e,t)=>{let s=e[0].dims,i=e[1].dims,o=s,l=1,u=Math.ceil(j.sizeToDimension(i,i.length-1)/l),c=i[i.length-1],h=j.sizeFromDimension(s,c),p=[{type:12,data:u},{type:12,data:c},{type:12,data:h},...L(e[1].dims,e[2].dims,o)],g=m=>{let w=F("indices",e[1].dataType,e[1].dims.length),_=F("updates",e[2].dataType,e[2].dims.length,l),S=t.reduction!=="none"&&t.reduction!==""?wt("output",e[0].dataType,o.length):de("output",e[0].dataType,o.length,l);return`
|
|
2310
|
+
${m.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(w,_,S)}
|
|
2311
|
+
${m.mainStart()}
|
|
2312
|
+
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2313
|
+
var data_offset = 0u;
|
|
2314
|
+
let indices_start = uniforms.last_index_dimension * global_idx;
|
|
2315
|
+
let indices_end = indices_start + uniforms.last_index_dimension;
|
|
2316
|
+
for (var i = indices_start; i < indices_end; i++) {
|
|
2317
|
+
var index = i32(indices[i].x);
|
|
2318
|
+
${e[0].dims.length===1?`
|
|
2319
|
+
let element_count_dim = uniforms.output_strides;
|
|
2320
|
+
let dim_value = uniforms.output_shape;`:`
|
|
2321
|
+
let element_count_dim = uniforms.output_strides[i - indices_start];
|
|
2322
|
+
let dim_value = uniforms.output_shape[i - indices_start];`}
|
|
2323
|
+
if (index >= 0) {
|
|
2324
|
+
if (index >= i32(dim_value)) {
|
|
2325
|
+
index = i32(dim_value - 1);
|
|
2326
|
+
}
|
|
2327
|
+
} else {
|
|
2328
|
+
if (index < -i32(dim_value)) {
|
|
2329
|
+
index = 0;
|
|
2330
|
+
} else {
|
|
2331
|
+
index += i32(dim_value);
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
data_offset += u32((u32(index) * element_count_dim));
|
|
2335
|
+
}
|
|
2336
|
+
|
|
2337
|
+
for (var i = 0u; i < uniforms.num_updates_elements; i++) {
|
|
2338
|
+
let value = updates[uniforms.num_updates_elements * global_idx + i];
|
|
2339
|
+
${nh(t.reduction,"output[data_offset + i]","value",S.type.value)}
|
|
2340
|
+
}
|
|
2341
|
+
|
|
2342
|
+
}`};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:g}},ih=e=>E({reduction:e.reduction}),ah=(e,t)=>{e.compute(sh(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),oh,lh,uh,Ua,dh,ch,hh,ph,fh,mh,gh,yh,Fa,wh,vh,_h,bh,Sh,Th,Eh,sg=b(()=>{ze(),Me(),A(),_e(),oh=(e,t)=>{if(e.every(s=>s>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
|
|
2343
|
+
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")}},lh=(e,t,s)=>{t.every(o=>o>=0&&o<s||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")}));let i=new Array(s).fill(1);return t.forEach((o,l)=>i[o]=e[l]),i},uh=(e,t,s,i,o,l)=>{let[u,c,h]=s>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(g=>l.push(g));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(g=>i.push(g)),i.length!==0&&i.length!==p&&s>=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");oh(i,t),t.axes.length>0&&lh(i,t.axes,p).forEach((g,m)=>i[m]=g)}if(h>0&&e.length>h&&e[h].dims.length===1&&e[h].dims[0]>0&&(e[h].getBigInt64Array().forEach(g=>o.push(Number(g))),o.length!==0&&o.length!==p&&s>=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")},Ua=(e,t,s,i)=>`
|
|
2344
|
+
// The whole part and the fractional part are calculated separately due to inaccuracy of floating
|
|
2345
|
+
// point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
|
|
2346
|
+
// offset-by-one error later in floor().
|
|
2347
|
+
let big = (${e}) * (${t});
|
|
2348
|
+
let whole = ${i}(big / (${s}));
|
|
2349
|
+
let fract = ${i}(big % (${s})) / ${i}(${s});
|
|
2350
|
+
return whole + fract;
|
|
2351
|
+
`,dh=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,
|
|
2352
|
+
lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`
|
|
2353
|
+
if (xScale < 1.0 || floor(xScale) != xScale) {
|
|
2354
|
+
return ${t}(xResized) / ${t}(xScale);
|
|
2355
|
+
} else {
|
|
2356
|
+
${Ua("xResized","lengthOriginal","lengthResized",t)}
|
|
2357
|
+
}
|
|
2358
|
+
`;case"pytorch_half_pixel":return`if (lengthResized > 1) {
|
|
2359
|
+
return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;
|
|
2360
|
+
} else {
|
|
2361
|
+
return 0.0;
|
|
2362
|
+
}`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {
|
|
2363
|
+
return 0.0;
|
|
2364
|
+
} else {
|
|
2365
|
+
${Ua("xResized","lengthOriginal - 1","lengthResized - 1",t)}
|
|
2366
|
+
}`;case"tf_crop_and_resize":return`if (lengthResized > 1) {
|
|
2367
|
+
return ${t}(roiStart) * ${t}(lengthOriginal - 1) +
|
|
2368
|
+
(${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /
|
|
2369
|
+
${t}(lengthResized - 1);
|
|
2370
|
+
} else {
|
|
2371
|
+
return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);
|
|
2372
|
+
}`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);
|
|
2373
|
+
const adjustment = ${t}(lengthResized) / outputWidth;
|
|
2374
|
+
const center = ${t}(lengthOriginal) / 2;
|
|
2375
|
+
const offset = center * (1 - adjustment);
|
|
2376
|
+
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`)}})()+"}",ch=(e,t,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{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`)}})()+"}",hh=(e,t,s)=>{let i=new Array(s).fill(0).concat(new Array(s).fill(1)),o=e.length===0?i:e.slice();return t.length>0?(t.forEach((l,u)=>{i[l]=o[u],i[u+s]=o[t.length+u]}),i):o},ph=(e,t,s,i)=>{let o=[];if(s.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]=s[u])}else s.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},fh=(e,t,s)=>{let i=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(l=>t[l]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(l=>t[l]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return s.axes.length>0?(s.axes.forEach(l=>t[l]=i),s.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},mh=(e,t,s,i,o)=>`
|
|
2377
|
+
fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${s.length}> {
|
|
2378
|
+
var original_indices: array<${e.type.value}, ${s.length}>;
|
|
2379
|
+
for (var i:u32 = 0; i < ${s.length}; i++) {
|
|
2380
|
+
var output_index = ${e.indicesGet("output_indices","i")};
|
|
2381
|
+
var scale = ${K("uniforms.scales","i",i)};
|
|
2382
|
+
var roi_low = ${K("uniforms.roi","i",o)};
|
|
2383
|
+
var roi_hi = ${K("uniforms.roi",`i + ${t.length}`,o)};
|
|
2384
|
+
if (scale == 1.0) {
|
|
2385
|
+
original_indices[i] = ${e.type.value}(output_index);
|
|
2386
|
+
} else {
|
|
2387
|
+
var input_shape_i = ${K("uniforms.input_shape","i",t.length)};
|
|
2388
|
+
var output_shape_i = ${K("uniforms.output_shape","i",s.length)};
|
|
2389
|
+
original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
|
|
2390
|
+
input_shape_i, roi_low, roi_hi);
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
return original_indices;
|
|
2394
|
+
}`,gh=(e,t,s,i,o,l,u)=>`
|
|
2395
|
+
fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
|
|
2396
|
+
var input_indices: ${e.type.indices};
|
|
2397
|
+
for (var i:u32 = 0; i < ${i.length}; i++) {
|
|
2398
|
+
var output_index = ${t.indicesGet("output_indices","i")};
|
|
2399
|
+
var input_index: u32;
|
|
2400
|
+
var scale = ${K("uniforms.scales","i",o)};
|
|
2401
|
+
if (scale == 1.0) {
|
|
2402
|
+
input_index = output_index;
|
|
2403
|
+
} else {
|
|
2404
|
+
var roi_low = ${K("uniforms.roi","i",l)};
|
|
2405
|
+
var roi_hi = ${K("uniforms.roi",`i + ${s.length}`,l)};
|
|
2406
|
+
var input_shape_i = ${K("uniforms.input_shape","i",s.length)};
|
|
2407
|
+
var output_shape_i = ${K("uniforms.output_shape","i",i.length)};
|
|
2408
|
+
var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
|
|
2409
|
+
input_shape_i, roi_low, roi_hi);
|
|
2410
|
+
if (!${u} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {
|
|
2411
|
+
if (original_idx < 0) {
|
|
2412
|
+
input_index = 0;
|
|
2413
|
+
} else if (original_idx > ${t.type.value}(input_shape_i - 1)) {
|
|
2414
|
+
input_index = input_shape_i - 1;
|
|
2415
|
+
} else {
|
|
2416
|
+
input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));
|
|
2417
|
+
}
|
|
2418
|
+
} else {
|
|
2419
|
+
input_index = u32(original_idx);
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
${e.indicesSet("input_indices","i","input_index")}
|
|
2423
|
+
}
|
|
2424
|
+
return input_indices;
|
|
2425
|
+
}`,yh=(e,t)=>`
|
|
2426
|
+
fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {
|
|
2427
|
+
for (var i:u32 = 0; i < ${t.length}; i++) {
|
|
2428
|
+
var input_index = ${e.indicesGet("input_indices","i")};
|
|
2429
|
+
if (input_index < 0 || input_index >= ${K("uniforms.input_shape","i",t.length)}) {
|
|
2430
|
+
return false;
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
return true;
|
|
2434
|
+
}`,Fa=(e,t,s,i)=>e.rank>i?`
|
|
2435
|
+
${e.indicesSet("input_indices",t,"channel")};
|
|
2436
|
+
${e.indicesSet("input_indices",s,"batch")};
|
|
2437
|
+
`:"",wh=(e,t,s,i,o)=>{let[l,u,c,h]=s.length===2?[-1,0,1,-1]:[0,2,3,1],p=e.type.value;return`
|
|
2438
|
+
fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${p} {
|
|
2439
|
+
var input_indices: ${e.type.indices};
|
|
2440
|
+
${e.indicesSet("input_indices",u,`max(0, min(row, ${s[u]} - 1))`)};
|
|
2441
|
+
${e.indicesSet("input_indices",c,`max(0, min(col, ${s[c]} - 1))`)};
|
|
2442
|
+
${Fa(e,h,l,2)}
|
|
2443
|
+
return ${e.getByIndices("input_indices")};
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} {
|
|
2447
|
+
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
|
|
2448
|
+
var row:${p} = originalIndices[${u}];
|
|
2449
|
+
var col:${p} = originalIndices[${c}];
|
|
2450
|
+
${i?`if (row < 0 || row > (${s[u]} - 1) || col < 0 || col > (${s[c]} - 1)) {
|
|
2451
|
+
return ${o};
|
|
2452
|
+
}`:""};
|
|
2453
|
+
row = max(0, min(row, ${s[u]} - 1));
|
|
2454
|
+
col = max(0, min(col, ${s[c]} - 1));
|
|
2455
|
+
var row1: u32 = u32(row);
|
|
2456
|
+
var col1: u32 = u32(col);
|
|
2457
|
+
var row2: u32 = u32(row + 1);
|
|
2458
|
+
var col2: u32 = u32(col + 1);
|
|
2459
|
+
var channel: u32 = ${s.length>2?`u32(originalIndices[${h}])`:"0"};
|
|
2460
|
+
var batch: u32 = ${s.length>2?`u32(originalIndices[${l}])`:"0"};
|
|
2461
|
+
var x11: ${p} = getInputValue(batch, channel, row1, col1);
|
|
2462
|
+
var x12: ${p} = getInputValue(batch, channel, row1, col2);
|
|
2463
|
+
var x21: ${p} = getInputValue(batch, channel, row2, col1);
|
|
2464
|
+
var x22: ${p} = getInputValue(batch, channel, row2, col2);
|
|
2465
|
+
var dx1: ${p} = abs(row - ${p}(row1));
|
|
2466
|
+
var dx2: ${p} = abs(${p}(row2) - row);
|
|
2467
|
+
var dy1: ${p} = abs(col - ${p}(col1));
|
|
2468
|
+
var dy2: ${p} = abs(${p}(col2) - col);
|
|
2469
|
+
if (row1 == row2) {
|
|
2470
|
+
dx1 = 0.5;
|
|
2471
|
+
dx2 = 0.5;
|
|
2472
|
+
}
|
|
2473
|
+
if (col1 == col2) {
|
|
2474
|
+
dy1 = 0.5;
|
|
2475
|
+
dy2 = 0.5;
|
|
2476
|
+
}
|
|
2477
|
+
return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);
|
|
2478
|
+
}`},vh=(e,t,s,i,o,l,u,c,h,p)=>{let g=s.length===2,[m,w]=g?[0,1]:[2,3],_=e.type.value,S=C=>{let M=C===m?"row":"col";return`
|
|
2479
|
+
fn ${M}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${_} {
|
|
2480
|
+
var output_index = ${t.indicesGet("output_indices",C)};
|
|
2481
|
+
var originalIdx: ${_} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[C]},
|
|
2482
|
+
${i[C]}, ${s[C]}, ${l[C]}, ${l[C]} + ${s.length});
|
|
2483
|
+
var fractOriginalIdx: ${_} = originalIdx - floor(originalIdx);
|
|
2484
|
+
var coefs = getCubicInterpolationCoefs(fractOriginalIdx);
|
|
2485
|
+
|
|
2486
|
+
if (${c} && (originalIdx < 0 || originalIdx > (${s[C]} - 1))) {
|
|
2487
|
+
return ${h};
|
|
2488
|
+
}
|
|
2489
|
+
var data: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0);
|
|
2490
|
+
for (var i: i32 = -1; i < 3; i++) {
|
|
2491
|
+
var ${M}: ${_} = originalIdx + ${_}(i);
|
|
2492
|
+
if (${M} < 0 || ${M} >= ${s[C]}) {
|
|
2493
|
+
${p?`coefs[i + 1] = 0.0;
|
|
2494
|
+
continue;`:c?`return ${h};`:`${M} = max(0, min(${M}, ${s[C]} - 1));`};
|
|
2495
|
+
}
|
|
2496
|
+
var input_indices_copy: ${e.type.indices} = input_indices;
|
|
2497
|
+
${e.indicesSet("input_indices_copy",C,`u32(${M})`)};
|
|
2498
|
+
data[i + 1] = ${C===m?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};
|
|
2499
|
+
}
|
|
2500
|
+
return cubicInterpolation1D(data, coefs);
|
|
2501
|
+
}`};return`
|
|
2502
|
+
${S(m)};
|
|
2503
|
+
${S(w)};
|
|
2504
|
+
fn getCubicInterpolationCoefs(s: ${_}) -> array<${_}, 4> {
|
|
2505
|
+
var absS = abs(s);
|
|
2506
|
+
var coeffs: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0);
|
|
2507
|
+
var oneMinusAbsS: ${_} = 1.0 - absS;
|
|
2508
|
+
var twoMinusAbsS: ${_} = 2.0 - absS;
|
|
2509
|
+
var onePlusAbsS: ${_} = 1.0 + absS;
|
|
2510
|
+
coeffs[0] = ((${u} * onePlusAbsS - 5 * ${u}) * onePlusAbsS + 8 * ${u}) * onePlusAbsS - 4 * ${u};
|
|
2511
|
+
coeffs[1] = ((${u} + 2) * absS - (${u} + 3)) * absS * absS + 1;
|
|
2512
|
+
coeffs[2] = ((${u} + 2) * oneMinusAbsS - (${u} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;
|
|
2513
|
+
coeffs[3] = ((${u} * twoMinusAbsS - 5 * ${u}) * twoMinusAbsS + 8 * ${u}) * twoMinusAbsS - 4 * ${u};
|
|
2514
|
+
return coeffs;
|
|
2515
|
+
}
|
|
2516
|
+
|
|
2517
|
+
fn cubicInterpolation1D(x: array<${_}, 4>, coefs: array<${_}, 4>) -> ${_} {
|
|
2518
|
+
var coefsSum: ${_} = coefs[0] + coefs[1] + coefs[2] + coefs[3];
|
|
2519
|
+
return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;
|
|
2520
|
+
}
|
|
2521
|
+
|
|
2522
|
+
fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${_} {
|
|
2523
|
+
var input_indices: ${e.type.indices} = output_indices;
|
|
2524
|
+
return colCubicInterpolation(input_indices, output_indices);
|
|
2525
|
+
}
|
|
2526
|
+
`},_h=(e,t,s,i,o)=>{let[l,u,c,h,p]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],g=e.type.value;return`
|
|
2527
|
+
fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${g} {
|
|
2528
|
+
var input_indices: ${e.type.indices};
|
|
2529
|
+
${e.indicesSet("input_indices",u,`max(0, min(depth, ${s[u]} - 1))`)};
|
|
2530
|
+
${e.indicesSet("input_indices",c,`max(0, min(height, ${s[c]} - 1))`)};
|
|
2531
|
+
${e.indicesSet("input_indices",h,`max(0, min(width, ${s[h]} - 1))`)};
|
|
2532
|
+
${Fa(e,p,l,3)}
|
|
2533
|
+
return ${e.getByIndices("input_indices")};
|
|
2534
|
+
}
|
|
2535
|
+
|
|
2536
|
+
fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${g} {
|
|
2537
|
+
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
|
|
2538
|
+
var depth:${g} = originalIndices[${u}];
|
|
2539
|
+
var height:${g} = originalIndices[${c}];
|
|
2540
|
+
var width:${g} = originalIndices[${h}];
|
|
2541
|
+
${i?`if (depth < 0 || depth > (${s[u]} - 1) || height < 0 || height > (${s[c]} - 1) || width < 0 || (width > ${s[h]} - 1)) {
|
|
2542
|
+
return ${o};
|
|
2543
|
+
}`:""};
|
|
2544
|
+
|
|
2545
|
+
depth = max(0, min(depth, ${s[u]} - 1));
|
|
2546
|
+
height = max(0, min(height, ${s[c]} - 1));
|
|
2547
|
+
width = max(0, min(width, ${s[h]} - 1));
|
|
2548
|
+
var depth1: u32 = u32(depth);
|
|
2549
|
+
var height1: u32 = u32(height);
|
|
2550
|
+
var width1: u32 = u32(width);
|
|
2551
|
+
var depth2: u32 = u32(depth + 1);
|
|
2552
|
+
var height2: u32 = u32(height + 1);
|
|
2553
|
+
var width2: u32 = u32(width + 1);
|
|
2554
|
+
var channel: u32 = ${s.length>3?`u32(originalIndices[${p}])`:"0"};
|
|
2555
|
+
var batch: u32 = ${s.length>3?`u32(originalIndices[${l}])`:"0"};
|
|
2556
|
+
|
|
2557
|
+
var x111: ${g} = getInputValue(batch, channel, depth1, height1, width1);
|
|
2558
|
+
var x112: ${g} = getInputValue(batch, channel, depth1, height1, width2);
|
|
2559
|
+
var x121: ${g} = getInputValue(batch, channel, depth1, height2, width1);
|
|
2560
|
+
var x122: ${g} = getInputValue(batch, channel, depth1, height2, width2);
|
|
2561
|
+
var x211: ${g} = getInputValue(batch, channel, depth2, height1, width1);
|
|
2562
|
+
var x212: ${g} = getInputValue(batch, channel, depth2, height1, width2);
|
|
2563
|
+
var x221: ${g} = getInputValue(batch, channel, depth2, height2, width1);
|
|
2564
|
+
var x222: ${g} = getInputValue(batch, channel, depth2, height2, width2);
|
|
2565
|
+
var dx1: ${g} = abs(depth - ${g}(depth1));
|
|
2566
|
+
var dx2: ${g} = abs(${g}(depth2) - depth);
|
|
2567
|
+
var dy1: ${g} = abs(height - ${g}(height1));
|
|
2568
|
+
var dy2: ${g} = abs(${g}(height2) - height);
|
|
2569
|
+
var dz1: ${g} = abs(width - ${g}(width1));
|
|
2570
|
+
var dz2: ${g} = abs(${g}(width2) - width);
|
|
2571
|
+
if (depth1 == depth2) {
|
|
2572
|
+
dx1 = 0.5;
|
|
2573
|
+
dx2 = 0.5;
|
|
2574
|
+
}
|
|
2575
|
+
if (height1 == height2) {
|
|
2576
|
+
dy1 = 0.5;
|
|
2577
|
+
dy2 = 0.5;
|
|
2578
|
+
}
|
|
2579
|
+
if (width1 == width2) {
|
|
2580
|
+
dz1 = 0.5;
|
|
2581
|
+
dz2 = 0.5;
|
|
2582
|
+
}
|
|
2583
|
+
return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +
|
|
2584
|
+
x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);
|
|
2585
|
+
}`},bh=(e,t,s,i,o,l)=>{let u=e.dims,c=hh(l,t.axes,u.length),h=ph(u,i,o,t.axes),p=i.slice();i.length===0&&(p=u.map((x,O)=>x===0?1:h[O]/x),t.keepAspectRatioPolicy!=="stretch"&&(h=fh(u,p,t)));let g=de("output",e.dataType,h.length),m=F("input",e.dataType,u.length),w=j.size(h),_=u.length===h.length&&u.every((x,O)=>x===h[O]),S=t.coordinateTransformMode==="tf_crop_and_resize",C=t.extrapolationValue,M=m.type.value,k=x=>`
|
|
2586
|
+
${_?"":`
|
|
2587
|
+
${dh(t.coordinateTransformMode,M)};
|
|
2588
|
+
${(()=>{switch(t.mode){case"nearest":return`
|
|
2589
|
+
${yh(m,u)};
|
|
2590
|
+
${ch(t.nearestMode,s,M)};
|
|
2591
|
+
${gh(m,g,u,h,p.length,c.length,S)};
|
|
2592
|
+
`;case"linear":return`
|
|
2593
|
+
${mh(g,u,h,p.length,c.length)};
|
|
2594
|
+
${(()=>{if(u.length===2||u.length===4)return`${wh(m,g,u,S,C)}`;if(u.length===3||u.length===5)return`${_h(m,g,u,S,C)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};
|
|
2595
|
+
`;case"cubic":return`
|
|
2596
|
+
${(()=>{if(u.length===2||u.length===4)return`${vh(m,g,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.")})()};
|
|
2597
|
+
`;default:throw Error("Invalid resize mode")}})()};
|
|
2598
|
+
`}
|
|
2599
|
+
${x.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",c.length).declareVariables(m,g)}
|
|
2600
|
+
${x.mainStart()}
|
|
2601
|
+
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2602
|
+
${_?"output[global_idx] = input[global_idx];":`
|
|
2603
|
+
let output_indices = ${g.offsetToIndices("global_idx")};
|
|
2604
|
+
var input_indices: ${m.type.indices};
|
|
2605
|
+
${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);
|
|
2606
|
+
if (checkInputIndices(input_indices)) {
|
|
2607
|
+
output[global_idx] = ${m.getByIndices("input_indices")};
|
|
2608
|
+
} else {
|
|
2609
|
+
output[global_idx] = ${t.extrapolationValue};
|
|
2610
|
+
}`;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}`)}})()};
|
|
2611
|
+
`}
|
|
2612
|
+
}`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${s}|${p.length>0?t.mode==="cubic"?p:p.length:""}|${o.length>0?o:""}|${c.length>0?c:""}|${_}|${t.mode==="nearest"?u.length:u}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[{dims:h,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},{type:1,data:p},{type:1,data:c},...L(u,h)]})}},Sh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Th=(e,t)=>{let s=[],i=[],o=[],l=Sh(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");uh(e.inputs,t,l,s,i,o),e.compute(bh(e.inputs[0],t,l,s,i,o),{inputs:[0]})},Eh=e=>{let t=e.antialias,s=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:s,coordinateTransformMode:i,cubicCoeffA:o,excludeOutside:l,extrapolationValue:u,keepAspectRatioPolicy:c,mode:h,nearestMode:p})}}),$h,xh,Ch,ig=b(()=>{ze(),Me(),_e(),$h=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],s=e[1],i=e[2];if(t.dataType!==s.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(s.dims.length!==3&&s.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(s.dims[s.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.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")}},xh=(e,t,s,i)=>{let o=t.simplified,l=e[0].dims,u=j.size(l),c=l,h=u,p=l.slice(-1)[0],g=i?l.slice(0,-1).concat(1):[],m=!o&&e.length>3,w=e.length>4,_=i&&s>1,S=i&&s>2,C=s>3,M=64,k=V(p),x=[{type:12,data:h},{type:12,data:k},{type:12,data:p},{type:1,data:t.epsilon}],O=z=>{let W=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],q=[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)];m&&q.push(F("beta",e[3].dataType,e[3].dims,k)),w&&q.push(F("bias",e[4].dataType,e[4].dims,k)),q.push(de("output",e[0].dataType,c,k)),_&&q.push(de("mean_output",1,g)),S&&q.push(de("inv_std_output",1,g)),C&&q.push(de("input_skip_bias_sum",e[0].dataType,c,k));let J=G(e[0].dataType),oe=G(1,k);return`
|
|
2613
|
+
|
|
2614
|
+
${z.registerUniforms(W).declareVariables(...q)}
|
|
2615
|
+
var<workgroup> sum_shared : array<${oe}, ${M}>;
|
|
2616
|
+
var<workgroup> sum_squared_shared : array<${oe}, ${M}>;
|
|
2617
|
+
|
|
2618
|
+
${z.mainStart([M,1,1])}
|
|
2619
|
+
let ix = local_id.x;
|
|
2620
|
+
let iy = global_id.x / ${M};
|
|
2621
|
+
|
|
2622
|
+
let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;
|
|
2623
|
+
var stride = hidden_size_vectorized / ${M};
|
|
2624
|
+
let offset = ix * stride + iy * hidden_size_vectorized;
|
|
2625
|
+
let offset1d = stride * ix;
|
|
2626
|
+
if (ix == ${M-1}) {
|
|
2627
|
+
stride = hidden_size_vectorized - stride * ix;
|
|
2628
|
+
}
|
|
2629
|
+
for (var i: u32 = 0; i < stride; i++) {
|
|
2630
|
+
let skip_value = skip[offset + i];
|
|
2631
|
+
let bias_value = ${w?"bias[offset1d + i]":J+"(0.0)"};
|
|
2632
|
+
let input_value = x[offset + i];
|
|
2633
|
+
let value = input_value + skip_value + bias_value;
|
|
2634
|
+
${C?"input_skip_bias_sum[offset + i] = value;":""}
|
|
2635
|
+
output[offset + i] = value;
|
|
2636
|
+
let f32_value = ${ie(J,k,"value")};
|
|
2637
|
+
sum_shared[ix] += f32_value;
|
|
2638
|
+
sum_squared_shared[ix] += f32_value * f32_value;
|
|
2639
|
+
}
|
|
2640
|
+
workgroupBarrier();
|
|
2641
|
+
|
|
2642
|
+
var reduce_size : u32 = ${M};
|
|
2643
|
+
for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {
|
|
2644
|
+
reduce_size = curr_size + (reduce_size & 1);
|
|
2645
|
+
if (ix < curr_size) {
|
|
2646
|
+
sum_shared[ix] += sum_shared[ix + reduce_size];
|
|
2647
|
+
sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];
|
|
2648
|
+
}
|
|
2649
|
+
workgroupBarrier();
|
|
2650
|
+
}
|
|
2651
|
+
|
|
2652
|
+
let sum = sum_shared[0];
|
|
2653
|
+
let square_sum = sum_squared_shared[0];
|
|
2654
|
+
let mean = ${ee("sum",k)} / f32(uniforms.hidden_size);
|
|
2655
|
+
let inv_std_dev = inverseSqrt(${ee("square_sum",k)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon);
|
|
2656
|
+
${_?"mean_output[global_idx] = mean;":""}
|
|
2657
|
+
${S?"inv_std_output[global_idx] = inv_std_dev;":""}
|
|
2658
|
+
|
|
2659
|
+
for (var i: u32 = 0; i < stride; i++) {
|
|
2660
|
+
output[offset + i] = (output[offset + i] ${o?"":`- ${J}(mean)`}) *
|
|
2661
|
+
${J}(inv_std_dev) * gamma[offset1d + i]
|
|
2662
|
+
${m?"+ beta[offset1d + i]":""};
|
|
2663
|
+
}
|
|
2664
|
+
}`},I=[{dims:c,dataType:e[0].dataType}];return s>1&&I.push({dims:g,dataType:1}),s>2&&I.push({dims:g,dataType:1}),s>3&&I.push({dims:l,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${k};${_};${S};${C}`,inputDependencies:e.map((z,W)=>"type")},getShaderSource:O,getRunData:()=>({outputs:I,dispatchGroup:{x:Math.ceil(h/p)},programUniforms:x})}},Ch=(e,t)=>{$h(e.inputs);let s=[0];e.outputCount>1&&s.push(-3),e.outputCount>2&&s.push(-3),e.outputCount>3&&s.push(3),e.compute(xh(e.inputs,t,e.outputCount,!1),{outputs:s})}}),kh,js,Rh,Va,Ah,Ih,Mh,Ph,ag=b(()=>{ze(),Me(),A(),_e(),kh=(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((s,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`)})},js=(e,t)=>{let s=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(i=>s.push(Number(i)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(i=>s.push(Number(i)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return s},Rh=(e,t)=>{if(e.length>1){let s=js(e,1),i=js(e,2),o=js(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),E({starts:s,ends:i,axes:o})}else return t},Va=(e,t,s,i,o)=>{let l=e;return e<0&&(l+=s[i[t]]),o[t]<0?Math.max(0,Math.min(l,s[i[t]]-1)):Math.max(0,Math.min(l,s[i[t]]))},Ah=(e,t,s)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
|
|
2665
|
+
var input_indices: ${e.type.indices};
|
|
2666
|
+
var carry = 0u;
|
|
2667
|
+
for (var i = ${s.length-1}; i >= 0; i--) {
|
|
2668
|
+
let input_shape_i = ${K("uniforms.input_shape","i",s.length)};
|
|
2669
|
+
let steps_i = ${K("uniforms.steps","i",s.length)};
|
|
2670
|
+
let signs_i = ${K("uniforms.signs","i",s.length)};
|
|
2671
|
+
let starts_i = ${K("uniforms.starts","i",s.length)};
|
|
2672
|
+
var output_index = ${t.indicesGet("output_indices","i")};
|
|
2673
|
+
var input_index = output_index * steps_i + starts_i + carry;
|
|
2674
|
+
carry = input_index / input_shape_i;
|
|
2675
|
+
input_index = input_index % input_shape_i;
|
|
2676
|
+
if (signs_i < 0) {
|
|
2677
|
+
input_index = input_shape_i - input_index - 1u + starts_i;
|
|
2678
|
+
}
|
|
2679
|
+
${e.indicesSet("input_indices","i","input_index")};
|
|
2680
|
+
}
|
|
2681
|
+
return input_indices;
|
|
2682
|
+
}`,Ih=(e,t)=>{let s=e[0].dims,i=j.size(s),o=t.axes.length>0?j.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],l=js(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,x)=>Va(k,x,s,o,l)),c=t.ends.map((k,x)=>Va(k,x,s,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!==s.length)for(let k=0;k<s.length;++k)o.includes(k)||(u.splice(k,0,0),c.splice(k,0,s[k]),l.splice(k,0,1));let h=l.map(k=>Math.sign(k));l.forEach((k,x,O)=>{if(k<0){let I=(c[x]-u[x])/k,z=u[x],W=z+I*l[x];u[x]=W,c[x]=z,O[x]=-k}});let p=s.slice(0);o.forEach((k,x)=>{p[k]=Math.ceil((c[k]-u[k])/l[k])});let g={dims:p,dataType:e[0].dataType},m=de("output",e[0].dataType,p.length),w=F("input",e[0].dataType,e[0].dims.length),_=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}],C=[{type:12,data:_},{type:12,data:u},{type:6,data:h},{type:12,data:l},...L(e[0].dims,p)],M=k=>`
|
|
2683
|
+
${k.registerUniforms(S).declareVariables(w,m)}
|
|
2684
|
+
${Ah(w,m,s)}
|
|
2685
|
+
${k.mainStart()}
|
|
2686
|
+
${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2687
|
+
let output_indices = ${m.offsetToIndices("global_idx")};
|
|
2688
|
+
let input_indices = calculateInputIndices(output_indices);
|
|
2689
|
+
${m.setByOffset("global_idx",w.getByIndices("input_indices"))}
|
|
2690
|
+
}`;return{name:"Slice",shaderCache:{hint:`${h.length}_${u.length}_${l.length}`,inputDependencies:["rank"]},getShaderSource:M,getRunData:()=>({outputs:[g],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:C})}},Mh=(e,t)=>{kh(e.inputs,t);let s=Rh(e.inputs,t);e.compute(Ih(e.inputs,s),{inputs:[0]})},Ph=e=>{let t=e.starts,s=e.ends,i=e.axes;return E({starts:t,ends:s,axes:i})}}),Oh,Dh,zh,Lh,og=b(()=>{ze(),Me(),A(),He(),_e(),Oh=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Dh=(e,t)=>{let s=e.inputs[0],i=s.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},(q,J)=>J),p[u]=l-1,p[l-1]=u,h=e.compute(bt(s,p),{inputs:[s],outputs:[-1]})[0]):h=s;let g=h.dims,m=g[l-1],w=o/m,_=V(m),S=m/_,C=64;w===1&&(C=256);let M=(q,J)=>J===4?`max(max(${q}.x, ${q}.y), max(${q}.z, ${q}.w))`:J===2?`max(${q}.x, ${q}.y)`:J===3?`max(max(${q}.x, ${q}.y), ${q}.z)`:q,k=F("x",h.dataType,h.dims,_),x=de("result",h.dataType,h.dims,_),O=k.type.value,I=G(h.dataType)==="f32"?`var threadMax = ${O}(-3.4028234663852886e+38f);`:`var threadMax = ${O}(-65504.0h);`,z=q=>`
|
|
2691
|
+
var<workgroup> rowMaxShared : ${O};
|
|
2692
|
+
var<workgroup> rowSumShared : ${O};
|
|
2693
|
+
var<workgroup> threadShared : array<${O}, ${C}>;
|
|
2694
|
+
|
|
2695
|
+
fn getValue(row: i32, col: i32, row_stride: i32) -> ${O} {
|
|
2696
|
+
let index = row * row_stride + col;
|
|
2697
|
+
return x[index];
|
|
2698
|
+
}
|
|
2699
|
+
|
|
2700
|
+
fn setValue(row: i32, col: i32, row_stride: i32, value: ${O}) {
|
|
2701
|
+
let index = row * row_stride + col;
|
|
2702
|
+
result[index] = value;
|
|
2703
|
+
}
|
|
2704
|
+
${q.registerUniform("packedCols","i32").declareVariables(k,x)}
|
|
2705
|
+
${q.mainStart(C)}
|
|
2706
|
+
let gindex = i32(global_idx);
|
|
2707
|
+
let lindex = i32(local_idx);
|
|
2708
|
+
const wg = ${C};
|
|
2709
|
+
let row = gindex / wg;
|
|
2710
|
+
let cols = uniforms.packedCols;
|
|
2711
|
+
let row_stride : i32 = uniforms.packedCols;
|
|
2712
|
+
|
|
2713
|
+
// find the rows max
|
|
2714
|
+
${I}
|
|
2715
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2716
|
+
let value = getValue(row, col, row_stride);
|
|
2717
|
+
threadMax = max(threadMax, value);
|
|
2718
|
+
}
|
|
2719
|
+
if (lindex < cols) {
|
|
2720
|
+
threadShared[lindex] = threadMax;
|
|
2721
|
+
}
|
|
2722
|
+
workgroupBarrier();
|
|
2723
|
+
|
|
2724
|
+
var reduceSize = min(cols, wg);
|
|
2725
|
+
for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {
|
|
2726
|
+
reduceSize = currSize + (reduceSize & 1);
|
|
2727
|
+
if (lindex < currSize) {
|
|
2728
|
+
threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);
|
|
2729
|
+
}
|
|
2730
|
+
workgroupBarrier();
|
|
2731
|
+
}
|
|
2732
|
+
if (lindex == 0) {
|
|
2733
|
+
rowMaxShared = ${O}(${M("threadShared[0]",_)});
|
|
2734
|
+
}
|
|
2735
|
+
workgroupBarrier();
|
|
2736
|
+
|
|
2737
|
+
// find the rows sum
|
|
2738
|
+
var threadSum = ${O}(0.0);
|
|
2739
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2740
|
+
let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);
|
|
2741
|
+
threadSum += subExp;
|
|
2742
|
+
}
|
|
2743
|
+
threadShared[lindex] = threadSum;
|
|
2744
|
+
workgroupBarrier();
|
|
2745
|
+
|
|
2746
|
+
for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {
|
|
2747
|
+
if (lindex < currSize) {
|
|
2748
|
+
threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];
|
|
2749
|
+
}
|
|
2750
|
+
workgroupBarrier();
|
|
2751
|
+
}
|
|
2752
|
+
if (lindex == 0) {
|
|
2753
|
+
rowSumShared = ${O}(${ee("threadShared[0]",_)});
|
|
2754
|
+
}
|
|
2755
|
+
workgroupBarrier();
|
|
2756
|
+
|
|
2757
|
+
// calculate final value for each element in the row
|
|
2758
|
+
for (var col = lindex; col < cols; col += wg) {
|
|
2759
|
+
var value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;
|
|
2760
|
+
// max operation protects against NaN since all values should be >=0
|
|
2761
|
+
value = max(value, ${O}(0.0));
|
|
2762
|
+
setValue(row, col, row_stride, value);
|
|
2763
|
+
}
|
|
2764
|
+
}`,W=e.compute({name:"Softmax",shaderCache:{hint:`${_};${C}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:g,dataType:h.dataType}],dispatchGroup:{x:w},programUniforms:[{type:6,data:S}]}),getShaderSource:z},{inputs:[h],outputs:[c?-1:0]})[0];c&&e.compute(bt(W,p),{inputs:[W]})},zh=(e,t)=>{Oh(e.inputs),Dh(e,t)},Lh=e=>E({axis:e.axis})}),Ga,Bh,Nh,Uh,Fh,lg=b(()=>{ze(),Me(),_e(),Ga=e=>Array.from(e.getBigInt64Array(),Number),Bh=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(Ga(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")},Nh=(e,t)=>{let s=[];for(let i=0;i<e.length;++i)s.push(e[i]*t[i]);return s},Uh=(e,t)=>{let s=e[0].dims,i=t??Ga(e[1]),o=Nh(s,i),l=j.size(o),u=e[0].dataType,c=F("input",u,s.length),h=de("output",u,o.length),p=g=>`
|
|
2765
|
+
const inputShape = ${c.indices(...s)};
|
|
2766
|
+
${g.registerUniform("output_size","u32").declareVariables(c,h)}
|
|
2767
|
+
${g.mainStart()}
|
|
2768
|
+
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2769
|
+
let output_indices = ${h.offsetToIndices("global_idx")};
|
|
2770
|
+
var input_indices: ${c.type.indices};
|
|
2771
|
+
for (var i = 0; i < ${s.length}; i++) {
|
|
2772
|
+
let input_dim_i = ${c.indicesGet("uniforms.input_shape","i")};
|
|
2773
|
+
let input_dim_value = ${h.indicesGet("output_indices","i")} % input_dim_i;
|
|
2774
|
+
|
|
2775
|
+
${c.indicesSet("input_indices","i","input_dim_value")}
|
|
2776
|
+
}
|
|
2777
|
+
${h.setByOffset("global_idx",c.getByIndices("input_indices"))}
|
|
2778
|
+
}`;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}},Fh=e=>{Bh(e.inputs),e.compute(Uh(e.inputs),{inputs:[0]})}}),Vh,Gh,qh,ug=b(()=>{ze(),Me(),_e(),Vh=(e,t,s,i,o)=>{let l=de("output_data",o,s.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,g=(m,w,_)=>`select(${w}, ${m}, ${_})`;if(!i)p=l.setByOffset("global_idx",g(u.getByOffset("global_idx"),c.getByOffset("global_idx"),h.getByOffset("global_idx")));else{let m=(w,_,S="")=>{let C=`a_data[index_a${_}][component_a${_}]`,M=`b_data[index_b${_}][component_b${_}]`,k=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return`
|
|
2779
|
+
let output_indices${_} = ${l.offsetToIndices(`global_idx * 4u + ${_}u`)};
|
|
2780
|
+
let offset_a${_} = ${u.broadcastedIndicesToOffset(`output_indices${_}`,l)};
|
|
2781
|
+
let offset_b${_} = ${c.broadcastedIndicesToOffset(`output_indices${_}`,l)};
|
|
2782
|
+
let offset_c${_} = ${h.broadcastedIndicesToOffset(`output_indices${_}`,l)};
|
|
2783
|
+
let index_a${_} = offset_a${_} / 4u;
|
|
2784
|
+
let index_b${_} = offset_b${_} / 4u;
|
|
2785
|
+
let index_c${_} = offset_c${_} / 4u;
|
|
2786
|
+
let component_a${_} = offset_a${_} % 4u;
|
|
2787
|
+
let component_b${_} = offset_b${_} % 4u;
|
|
2788
|
+
let component_c${_} = offset_c${_} % 4u;
|
|
2789
|
+
${w}[${_}] = ${S}(${g(C,M,k)});
|
|
2790
|
+
`};o===9?p=`
|
|
2791
|
+
var data = vec4<u32>(0);
|
|
2792
|
+
${m("data",0,"u32")}
|
|
2793
|
+
${m("data",1,"u32")}
|
|
2794
|
+
${m("data",2,"u32")}
|
|
2795
|
+
${m("data",3,"u32")}
|
|
2796
|
+
output_data[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:p=`
|
|
2797
|
+
${m("output_data[global_idx]",0)}
|
|
2798
|
+
${m("output_data[global_idx]",1)}
|
|
2799
|
+
${m("output_data[global_idx]",2)}
|
|
2800
|
+
${m("output_data[global_idx]",3)}
|
|
2801
|
+
`}return`
|
|
2802
|
+
${e.registerUniform("vec_size","u32").declareVariables(h,u,c,l)}
|
|
2803
|
+
${e.mainStart()}
|
|
2804
|
+
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
2805
|
+
${p}
|
|
2806
|
+
}`},Gh=e=>{let t=e[1].dims,s=e[2].dims,i=e[0].dims,o=e[1].dataType,l=!(j.areEqual(t,s)&&j.areEqual(s,i)),u=t,c=j.size(t);if(l){let p=$r.calcShape($r.calcShape(t,s,!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=>Vh(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,s,u)]})}},qh=e=>{e.compute(Gh(e.inputs))}}),Wh,dg=b(()=>{Em(),ia(),$m(),xm(),Cm(),km(),Rm(),Om(),zm(),Lm(),Bm(),Nm(),Um(),Fm(),Vm(),Gm(),qm(),Wm(),Hm(),jm(),Km(),Qm(),Xm(),Ym(),Jm(),nc(),Zm(),eg(),tg(),rg(),ng(),ra(),sg(),pc(),ig(),ag(),og(),dc(),lg(),He(),ua(),ug(),Wh=new Map([["Abs",[$l]],["Acos",[xl]],["Acosh",[Cl]],["Add",[fu]],["ArgMax",[dl,sa]],["ArgMin",[ul,sa]],["Asin",[kl]],["Asinh",[Rl]],["Atan",[Al]],["Atanh",[Il]],["Attention",[gl]],["AveragePool",[Gc,Vc]],["BatchNormalization",[_l]],["BiasAdd",[Tl]],["BiasSplitGelu",[cu]],["Cast",[Pl,Ml]],["Ceil",[zl]],["Clip",[Dl]],["Concat",[ku,Ru]],["Conv",[Sa,_a]],["ConvTranspose",[rd,Zu]],["Cos",[Ll]],["Cosh",[Bl]],["CumSum",[sd,id]],["DepthToSpace",[ud,dd]],["DequantizeLinear",[Jc,Zc]],["Div",[mu]],["Einsum",[gd,yd]],["Elu",[Nl,Fs]],["Equal",[gu]],["Erf",[Ul]],["Exp",[Fl]],["Expand",[bd]],["FastGelu",[Td]],["Floor",[Vl]],["FusedConv",[Sa,_a]],["Gather",[Cd,xd]],["GatherElements",[Bd,Ld]],["GatherBlockQuantized",[Pd,Od]],["GatherND",[Rd,Ad]],["Gelu",[Gl]],["Gemm",[Vd,Fd]],["GlobalAveragePool",[Wc,qc]],["GlobalMaxPool",[Qc,Kc]],["Greater",[_u]],["GreaterOrEqual",[Su]],["GridSample",[Yd,Jd]],["GroupQueryAttention",[yc]],["HardSigmoid",[Yl,Xl]],["InstanceNormalization",[_c]],["LayerNormalization",[Tc]],["LeakyRelu",[ql,Fs]],["Less",[bu]],["LessOrEqual",[Tu]],["Log",[iu]],["MatMul",[$c]],["MatMulNBits",[Rc,Ac]],["MaxPool",[Hc,jc]],["Mul",[yu]],["MultiHeadAttention",[rc,ec]],["Neg",[Hl]],["Not",[Wl]],["Pad",[Nc]],["Pow",[wu]],["QuickGelu",[lu,Fs]],["Range",[rh]],["Reciprocal",[jl]],["ReduceMin",[sl]],["ReduceMean",[Zo]],["ReduceMax",[nl]],["ReduceSum",[al]],["ReduceProd",[il]],["ReduceL1",[el]],["ReduceL2",[tl]],["ReduceLogSum",[ll]],["ReduceLogSumExp",[rl]],["ReduceSumSquare",[ol]],["Relu",[Kl]],["Resize",[Th,Eh]],["RotaryEmbedding",[hc]],["ScatterND",[ah,ih]],["Sigmoid",[Ql]],["Sin",[Jl]],["Sinh",[Zl]],["Slice",[Mh,Ph]],["SkipLayerNormalization",[Ch]],["Split",[lc,uc]],["Sqrt",[eu]],["Softmax",[zh,Lh]],["Sub",[vu]],["Tan",[tu]],["Tanh",[ru]],["ThresholdedRelu",[su,Fs]],["Tile",[Fh]],["Transpose",[sr,Bs]],["Where",[qh]]])}),Hh,cg=b(()=>{Mt(),rr(),_e(),Hh=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,s,i,o){mt(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 s)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(),rt(e.programInfo.name)}dispose(){}build(e,t){mt(e.name);let s=this.backend.device,i=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(p=>{s.features.has(p.feature)&&i.push(`enable ${p.extension};`)});let o=We(t,this.backend.device.limits),l=e.getShaderSource(o),u=`${i.join(`
|
|
2807
|
+
`)}
|
|
2808
|
+
${o.additionalImplementations}
|
|
2809
|
+
${l}`,c=s.createShaderModule({code:u,label:e.name});Je("verbose",()=>`[WebGPU] ${e.name} shader code: ${u}`);let h=s.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:e.name});return rt(e.name),{programInfo:e,computePipeline:h,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&s<=o&&i<=o)return[t,s,i];let l=t*s*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]}}}),jh={};N(jh,{WebGpuBackend:()=>Yh});var Kh,Qh,Xh,Yh,hg=b(()=>{Mt(),ze(),rr(),Xr(),ea(),dg(),cg(),Kh=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let s=[];for(let i=0;i<e.length;++i){let o=e[i].dataType;switch(t[i]){case"none":{s.push("");break}case"type":{s.push(`${o}`);break}case"rank":{let l=e[i].dims.length;s.push(`${o};${l}`);break}case"dims":{let l=e[i].dims.join(",");s.push(`${o};${l}`);break}default:throw new Error(`unsupported input dependency: ${t[i]}`)}}return s.join("|")},Qh=(e,t,s)=>{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+s+`:${Kh(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},Xh=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Yh=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 s=[],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:s},o=l=>t.features.has(l)&&s.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 Xh(t.info||await t.requestAdapterInfo()),this.gpuDataManager=fi(this),this.programManager=new Hh(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Gn(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:!1}),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()}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;mt(),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()),s=this.pendingQueries.get(e);for(let i=0;i<t.length/2;i++){let o=s[i],l=o.kernelId,u=this.kernels.get(l),c=u.kernelType,h=u.kernelName,p=o.programName,g=o.inputTensorViews,m=o.outputTensorViews,w=t[i*2],_=t[i*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=w);let S=Number(w-this.queryTimeBase),C=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(S)||!Number.isSafeInteger(C))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:g.map(M=>({dims:M.dims,dataType:Zt(M.dataType)})),outputsMetadata:m.map(M=>({dims:M.dims,dataType:Zt(M.dataType)})),kernelId:l,kernelType:c,kernelName:h,programName:p,startTime:S,endTime:C});else{let M="";g.forEach((x,O)=>{M+=`input[${O}]: [${x.dims}] | ${Zt(x.dataType)}, `});let k="";m.forEach((x,O)=>{k+=`output[${O}]: [${x.dims}] | ${Zt(x.dataType)}, `}),console.log(`[profiling] kernel "${l}|${c}|${h}|${p}" ${M}${k}start time: ${S} ns, execution time: ${C-S} ns`)}Fe("GPU",`${p}::${w}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),rt()}run(e,t,s,i,o,l){mt(e.name);let u=[];for(let x=0;x<t.length;++x){let O=t[x].data;if(O===0)continue;let I=this.gpuDataManager.get(O);if(!I)throw new Error(`no GPU data for input: ${O}`);u.push(I)}let{outputs:c,dispatchGroup:h,programUniforms:p}=e.getRunData(t),g=s.length===0?c.map((x,O)=>O):s;if(g.length!==c.length)throw new Error(`Output size ${g.length} must be equal to ${c.length}.`);let m=[],w=[];for(let x=0;x<c.length;++x){if(!Number.isInteger(g[x])||g[x]<-3||g[x]>=l)throw new Error(`Invalid output index: ${g[x]}`);if(g[x]===-3)continue;let O=g[x]===-1,I=g[x]===-2,z=O||I?o(c[x].dataType,c[x].dims):i(g[x],c[x].dataType,c[x].dims);if(m.push(z),z.data===0)continue;let W=this.gpuDataManager.get(z.data);if(!W)throw new Error(`no GPU data for output: ${z.data}`);if(O&&this.temporaryData.push(W),I){let q=this.kernelPersistentData.get(this.currentKernelId);q||(q=[],this.kernelPersistentData.set(this.currentKernelId,q)),q.push(W)}w.push(W)}if(u.length!==t.length||w.length!==m.length){if(w.length===0)return rt(e.name),m;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let _;if(p){let x=0,O=[];p.forEach(q=>{let J=typeof q.data=="number"?[q.data]:q.data;if(J.length===0)return;let oe=q.type===10?2:4,ge,Qe;q.type===10?(Qe=J.length>4?16:J.length>2?8:J.length*oe,ge=J.length>4?16:oe*J.length):(Qe=J.length<=2?J.length*oe:16,ge=16),x=Math.ceil(x/Qe)*Qe,O.push(x);let Ae=q.type===10?8:4;x+=J.length>4?Math.ceil(J.length/Ae)*ge:J.length*oe});let I=16;x=Math.ceil(x/I)*I;let z=new ArrayBuffer(x);p.forEach((q,J)=>{let oe=O[J],ge=typeof q.data=="number"?[q.data]:q.data;if(q.type===6)new Int32Array(z,oe,ge.length).set(ge);else if(q.type===12)new Uint32Array(z,oe,ge.length).set(ge);else if(q.type===10)new Uint16Array(z,oe,ge.length).set(ge);else if(q.type===1)new Float32Array(z,oe,ge.length).set(ge);else throw new Error(`Unsupported uniform type: ${Zt(q.type)}`)});let W=this.gpuDataManager.create(x,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(W.buffer,0,z,0,x),this.gpuDataManager.release(W.id),_={offset:0,size:x,buffer:W.buffer}}let S=this.programManager.normalizeDispatchGroupSize(h),C=S[1]===1&&S[2]===1,M=Qh(e,t,C),k=this.programManager.getArtifact(M);if(k||(k=this.programManager.build(e,S),this.programManager.setArtifact(M,k),Je("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 x=0;x<p.length;x++){let O=p[x],I=O.type,z=typeof O.data=="number"?1:O.data.length,[W,q]=k.uniformVariablesInfo[x];if(I!==W||z!==q)throw new Error(`Uniform variable ${x} mismatch: expect type ${W} with size ${q}, got type ${I} with size ${z} in program "${k.programInfo.name}".`)}}if(Je("info",()=>`[ProgramManager] run "${e.name}" (key=${M}) with ${S[0]}x${S[1]}x${S[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let x={kernelId:this.currentKernelId,programName:k.programInfo.name,inputTensorViews:t,outputTensorViews:m};this.pendingKernels.push(x),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(x)}return this.programManager.run(k,u,w,S,_),rt(e.name),m}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,s,i){let o=Wh.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let l={kernelType:e,kernelName:i,kernelEntry:o[0],attributes:[o[1],s]};this.kernels.set(t,l)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){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),Je("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 s.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${l}" failed. ${p}`)),1}finally{h&&s.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,s,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(s,i,l);return o.set(t,[u,s]),u}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[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,s){return async()=>{let i=await Ds(this,e,t);return xr(i.buffer,s)}}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(){Je("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(){Je("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Je("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),s=e.length;this.pendingKernels=[];for(let i=0;i<s;i++){let o=this.getComputePassEncoder(),l=e[i];this.writeTimestamp(this.pendingDispatchNumber*2),o.setPipeline(l.computePipeline),o.setBindGroup(0,l.bindGroup),o.dispatchWorkgroups(...l.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(t[i]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Jh={};N(Jh,{init:()=>ep});var Ci,Zh,ep,pg=b(()=>{ze(),rr(),Me(),Os(),Ci=class vf{constructor(t,s,i,o){this.module=t,this.dataType=s,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 vf(this.module,this.dataType,this.data,t)}},Zh=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,o=s/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)),g=Number(e.getValue(i*o++,"*")),m=Number(e.getValue(i*o++,l)),w=[];for(let _=0;_<m;_++)w.push(Number(e.getValue(i*o++,l)));c.push(new Ci(e,p,g,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 s=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=er(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,s,i,o,l,this.outputCount)}output(e,t){let s=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(s)}}},ep=async(e,t,s,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=(hg(),re(jh)).WebGpuBackend,u=new l;await u.initialize(s,i),o("webgpu",[u,c=>u.alloc(Number(c)),c=>u.free(c),(c,h,p,g=!1)=>{if(g)Je("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(c)}, dst=${Number(h)}, size=${Number(p)}`),u.memcpy(Number(c),Number(h));else{Je("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(c)}, gpuDataId=${Number(h)}, size=${Number(p)}`);let m=t.HEAPU8.subarray(Number(c>>>0),Number(c>>>0)+Number(p));u.upload(Number(h),m)}},async(c,h,p)=>{Je("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,g)=>{Je("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${c}, contextDataOffset=${h}`);let m=new Zh(t,u,Number(h));return u.computeKernel(Number(c),m,g)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else{let l=new Ps(s);o("webnn",[l,()=>l.reserveTensorId(),u=>l.releaseTensorId(u),async(u,c,h,p,g)=>l.ensureTensor(u,c,h,p,g),(u,c)=>{l.uploadTensor(u,c)},async(u,c)=>l.downloadTensor(u,c),(u,c)=>l.registerMLContext(u,c),!!s.trace])}}}),tp,qa,Wa,tn,rp,Ha,ki,ja,Ka,Qa,Xa,Ya,Ja,np=b(()=>{Mt(),Ji(),Zi(),ze(),Yt(),wn(),Cs(),tp=(e,t)=>{Ne()._OrtInit(e,t)!==0&&Ie("Can't initialize onnxruntime.")},qa=async e=>{tp(e.wasm.numThreads,_n(e.logLevel))},Wa=async(e,t)=>{Ne().asyncInit?.();let s=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.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(s=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:o}),!s)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=(pg(),re(Jh)).init;t==="webgpu"&&await i("webgpu",Ne(),e,s),t==="webnn"&&await i("webnn",Ne(),e)}},tn=new Map,rp=e=>{let t=Ne(),s=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,o,o+i)!==0&&Ie("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(s)}},Ha=(e,t)=>{let s=Ne(),i=s.stackSave(),o=0;try{let l=s.PTR_SIZE,u=s.stackAlloc(2*l);s._OrtGetInputOutputMetadata(e,t,u,u+l)!==0&&Ie("Can't get session input/output metadata.");let c=Number(s.getValue(u,"*"));o=Number(s.getValue(u+l,"*"));let h=s.HEAP32[o/4];if(h===0)return[c,0];let p=s.HEAPU32[o/4+1],g=[];for(let m=0;m<p;m++){let w=Number(s.getValue(o+8+m*l,"*"));g.push(w!==0?s.UTF8ToString(w):Number(s.getValue(o+8+(m+p)*l,"*")))}return[c,h,g]}finally{s.stackRestore(i),o!==0&&s._OrtFree(o)}},ki=e=>{let t=Ne(),s=t._malloc(e.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,s),[s,e.byteLength]},ja=async(e,t)=>{let s,i,o=Ne();Array.isArray(e)?[s,i]=e:e.buffer===o.HEAPU8.buffer?[s,i]=[e.byteOffset,e.byteLength]:[s,i]=ki(e);let l=0,u=0,c=0,h=[],p=[],g=[];try{if([u,h]=await xs(t),t?.externalData&&o.mountExternalData){let I=[];for(let z of t.externalData){let W=typeof z=="string"?z:z.path;I.push(Tn(typeof z=="string"?z:z.data).then(q=>{o.mountExternalData(W,q)}))}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 z=I,W=z?.context,q=z?.gpuDevice,J=z?.deviceType,oe=z?.powerPreference;W?o.currentContext=W:q?o.currentContext=await o.webnnCreateMLContext(q):o.currentContext=await o.webnnCreateMLContext({deviceType:J,powerPreference:oe})}else o.currentContext=await o.webnnCreateMLContext();break}l=await o._OrtCreateSession(s,i,u),o.webgpuOnCreateSession?.(l),l===0&&Ie("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.webnnRegisterMLContext(l,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[m,w]=rp(l),_=!!t?.enableGraphCapture,S=[],C=[],M=[],k=[],x=[];for(let I=0;I<m;I++){let[z,W,q]=Ha(l,I);z===0&&Ie("Can't get an input name."),p.push(z);let J=o.UTF8ToString(z);S.push(J),M.push(W===0?{name:J,isTensor:!1}:{name:J,isTensor:!0,type:Zt(W),shape:q})}for(let I=0;I<w;I++){let[z,W,q]=Ha(l,I+m);z===0&&Ie("Can't get an output name."),g.push(z);let J=o.UTF8ToString(z);C.push(J),k.push(W===0?{name:J,isTensor:!1}:{name:J,isTensor:!0,type:Zt(W),shape:q});{if(_&&t?.preferredOutputLocation===void 0){x.push("gpu-buffer");continue}let oe=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[J]??"cpu",ge=o.webnnIsGraphOutput;if(oe==="cpu"&&ge&&ge(l,J)){x.push("ml-tensor-cpu-output");continue}if(oe!=="cpu"&&oe!=="cpu-pinned"&&oe!=="gpu-buffer"&&oe!=="ml-tensor")throw new Error(`Not supported preferred output location: ${oe}.`);if(_&&oe!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${oe}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);x.push(oe)}}let O=null;return x.some(I=>I==="gpu-buffer"||I==="ml-tensor"||I==="ml-tensor-cpu-output")&&(c=o._OrtCreateBinding(l),c===0&&Ie("Can't create IO binding."),O={handle:c,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(I=>I==="ml-tensor-cpu-output"?"ml-tensor":I).map(I=>Un(I))}),tn.set(l,[l,p,g,O,_,!1]),[l,S,C,M,k]}catch(m){throw p.forEach(w=>o._OrtFree(w)),g.forEach(w=>o._OrtFree(w)),c!==0&&o._OrtReleaseBinding(c)!==0&&Ie("Can't release IO binding."),l!==0&&o._OrtReleaseSession(l)!==0&&Ie("Can't release session."),m}finally{o._free(s),u!==0&&o._OrtReleaseSessionOptions(u)!==0&&Ie("Can't release session options."),h.forEach(m=>o._free(m)),o.unmountExternalData?.()}},Ka=e=>{let t=Ne(),s=tn.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,o,l,u,c]=s;u&&(c&&t._OrtClearBoundOutputs(u.handle)!==0&&Ie("Can't clear bound outputs."),t._OrtReleaseBinding(u.handle)!==0&&Ie("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&&Ie("Can't release session."),tn.delete(e)},Qa=async(e,t,s,i,o,l,u=!1)=>{if(!e){t.push(0);return}let c=Ne(),h=c.PTR_SIZE,p=e[0],g=e[1],m=e[3],w=m,_,S;if(p==="string"&&(m==="gpu-buffer"||m==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(u&&m!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${l} when enableGraphCapture is true.`);if(m==="gpu-buffer"){let k=e[2].gpuBuffer;S=er(Jt(p),g);{let x=c.jsepRegisterBuffer;if(!x)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=x(i,l,k,S)}}else if(m==="ml-tensor"){let k=e[2].mlTensor;S=er(Jt(p),g);let x=c.webnnRegisterMLTensor;if(!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=x(i,k,Jt(p),g)}else{let k=e[2];if(Array.isArray(k)){S=h*k.length,_=c._malloc(S),s.push(_);for(let x=0;x<k.length;x++){if(typeof k[x]!="string")throw new TypeError(`tensor data at index ${x} is not a string`);c.setValue(_+x*h,Et(k[x],s),"*")}}else{let x=c.webnnIsGraphInput,O=c.webnnIsGraphOutput;if(p!=="string"&&x&&O){let I=c.UTF8ToString(o);if(x(i,I)||O(i,I)){let z=Jt(p);S=er(z,g),w="ml-tensor";let W=c.webnnCreateTemporaryTensor,q=c.webnnUploadTensor;if(!W||!q)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let J=await W(i,z,g);q(J,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),_=J}else S=k.byteLength,_=c._malloc(S),s.push(_),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),_)}else S=k.byteLength,_=c._malloc(S),s.push(_),c.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),_)}}let C=c.stackSave(),M=c.stackAlloc(4*g.length);try{g.forEach((x,O)=>c.setValue(M+O*h,x,h===4?"i32":"i64"));let k=c._OrtCreateTensor(Jt(p),_,S,M,g.length,Un(w));k===0&&Ie(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(k)}finally{c.stackRestore(C)}},Xa=async(e,t,s,i,o,l)=>{let u=Ne(),c=u.PTR_SIZE,h=tn.get(e);if(!h)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=h[0],g=h[1],m=h[2],w=h[3],_=h[4],S=h[5],C=t.length,M=i.length,k=0,x=[],O=[],I=[],z=[],W=[],q=u.stackSave(),J=u.stackAlloc(C*c),oe=u.stackAlloc(C*c),ge=u.stackAlloc(M*c),Qe=u.stackAlloc(M*c);try{[k,x]=bs(l),ue("wasm prepareInputOutputTensor");for(let we=0;we<C;we++)await Qa(s[we],O,z,e,g[t[we]],t[we],_);for(let we=0;we<M;we++)await Qa(o[we],I,z,e,m[i[we]],C+i[we],_);De("wasm prepareInputOutputTensor");for(let we=0;we<C;we++)u.setValue(J+we*c,O[we],"*"),u.setValue(oe+we*c,g[t[we]],"*");for(let we=0;we<M;we++)u.setValue(ge+we*c,I[we],"*"),u.setValue(Qe+we*c,m[i[we]],"*");if(w&&!S){let{handle:we,outputPreferredLocations:ke,outputPreferredLocationsEncoded:Xe}=w;if(g.length!==C)throw new Error(`input count from feeds (${C}) is expected to be always equal to model's input count (${g.length}).`);ue("wasm bindInputsOutputs");for(let Ve=0;Ve<C;Ve++){let Ue=t[Ve];await u._OrtBindInput(we,g[Ue],O[Ve])!==0&&Ie(`Can't bind input[${Ve}] for session=${e}.`)}for(let Ve=0;Ve<M;Ve++){let Ue=i[Ve];o[Ve]?.[3]?(W.push(I[Ve]),u._OrtBindOutput(we,m[Ue],I[Ve],0)!==0&&Ie(`Can't bind pre-allocated output[${Ve}] for session=${e}.`)):u._OrtBindOutput(we,m[Ue],0,Xe[Ue])!==0&&Ie(`Can't bind output[${Ve}] to ${ke[Ve]} for session=${e}.`)}De("wasm bindInputsOutputs"),tn.set(e,[p,g,m,w,_,!0])}u.jsepOnRunStart?.(p),u.webnnOnRunStart?.(p);let Ae;w?Ae=await u._OrtRunWithBinding(p,w.handle,M,ge,k):Ae=await u._OrtRun(p,oe,J,C,Qe,M,ge,k),Ae!==0&&Ie("failed to call OrtRun().");let Be=[],ut=[];ue("wasm ProcessOutputTensor");for(let we=0;we<M;we++){let ke=Number(u.getValue(ge+we*c,"*"));if(ke===I[we]||W.includes(I[we])){Be.push(o[we]),ke!==I[we]&&u._OrtReleaseTensor(ke)!==0&&Ie("Can't release tensor.");continue}let Xe=u.stackSave(),Ve=u.stackAlloc(4*c),Ue=!1,ct,se=0;try{u._OrtGetTensorData(ke,Ve,Ve+c,Ve+2*c,Ve+3*c)!==0&&Ie(`Can't access output tensor data on index ${we}.`);let ve=c===4?"i32":"i64",Ge=Number(u.getValue(Ve,ve));se=u.getValue(Ve+c,"*");let ht=u.getValue(Ve+c*2,"*"),_r=Number(u.getValue(Ve+c*3,ve)),Ar=[];for(let Nt=0;Nt<_r;Nt++)Ar.push(Number(u.getValue(ht+Nt*c,ve)));u._OrtFree(ht)!==0&&Ie("Can't free memory for tensor dims.");let nn=Ar.reduce((Nt,kt)=>Nt*kt,1);ct=Zt(Ge);let Xs=w?.outputPreferredLocations[i[we]];if(ct==="string"){if(Xs==="gpu-buffer"||Xs==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Nt=[];for(let kt=0;kt<nn;kt++){let Fr=u.getValue(se+kt*c,"*"),wg=u.getValue(se+(kt+1)*c,"*"),vg=kt===nn-1?void 0:wg-Fr;Nt.push(u.UTF8ToString(Fr,vg))}Be.push([ct,Ar,Nt,"cpu"])}else if(Xs==="gpu-buffer"&&nn>0){let Nt=u.jsepGetBuffer;if(!Nt)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let kt=Nt(se),Fr=er(Ge,nn);if(Fr===void 0||!bn(ct))throw new Error(`Unsupported data type: ${ct}`);Ue=!0,Be.push([ct,Ar,{gpuBuffer:kt,download:u.jsepCreateDownloader(kt,Fr,ct),dispose:()=>{u._OrtReleaseTensor(ke)!==0&&Ie("Can't release tensor.")}},"gpu-buffer"])}else if(Xs==="ml-tensor"&&nn>0){let Nt=u.webnnEnsureTensor,kt=u.webnnIsGraphInputOutputTypeSupported;if(!Nt||!kt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(er(Ge,nn)===void 0||!Sn(ct))throw new Error(`Unsupported data type: ${ct}`);if(!kt(e,ct,!1))throw new Error(`preferredLocation "ml-tensor" for ${ct} output is not supported by current WebNN Context.`);let Fr=await Nt(e,se,Ge,Ar,!1);Ue=!0,Be.push([ct,Ar,{mlTensor:Fr,download:u.webnnCreateMLTensorDownloader(se,ct),dispose:()=>{u.webnnReleaseTensorId(se),u._OrtReleaseTensor(ke)}},"ml-tensor"])}else if(Xs==="ml-tensor-cpu-output"&&nn>0){let Nt=u.webnnCreateMLTensorDownloader(se,ct)(),kt=Be.length;Ue=!0,ut.push((async()=>{let Fr=[kt,await Nt];return u.webnnReleaseTensorId(se),u._OrtReleaseTensor(ke),Fr})()),Be.push([ct,Ar,[],"cpu"])}else{let Nt=vn(ct),kt=new Nt(nn);new Uint8Array(kt.buffer,kt.byteOffset,kt.byteLength).set(u.HEAPU8.subarray(se,se+kt.byteLength)),Be.push([ct,Ar,kt,"cpu"])}}finally{u.stackRestore(Xe),ct==="string"&&se&&u._free(se),Ue||u._OrtReleaseTensor(ke)}}w&&!_&&(u._OrtClearBoundOutputs(w.handle)!==0&&Ie("Can't clear bound outputs."),tn.set(e,[p,g,m,w,_,!1]));for(let[we,ke]of await Promise.all(ut))Be[we][2]=ke;return De("wasm ProcessOutputTensor"),Be}finally{u.webnnOnRunEnd?.(p),u.stackRestore(q),O.forEach(Ae=>u._OrtReleaseTensor(Ae)),I.forEach(Ae=>u._OrtReleaseTensor(Ae)),z.forEach(Ae=>u._free(Ae)),k!==0&&u._OrtReleaseRunOptions(k),x.forEach(Ae=>u._free(Ae))}},Ya=e=>{let t=Ne(),s=tn.get(e);if(!s)throw new Error("invalid session id");let i=s[0],o=t._OrtEndProfiling(i);o===0&&Ie("Can't get an profile file name."),t._OrtFree(o)},Ja=e=>{let t=[];for(let s of e){let i=s[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),rn,ar,ss,Ks,Qs,Ri,Za,Ai,Dn,zn,sp,ip,ap,op,lp,up,dp,cp,hp=b(()=>{Mt(),np(),Yt(),fn(),rn=()=>!!fe.wasm.proxy&&typeof document<"u",ss=!1,Ks=!1,Qs=!1,Ai=new Map,Dn=(e,t)=>{let s=Ai.get(e);s?s.push(t):Ai.set(e,[t])},zn=()=>{if(ss||!Ks||Qs||!ar)throw new Error("worker not ready")},sp=e=>{switch(e.data.type){case"init-wasm":ss=!1,e.data.err?(Qs=!0,Za[1](e.data.err)):(Ks=!0,Za[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}}},ip=async()=>{if(!Ks){if(ss)throw new Error("multiple calls to 'initWasm()' detected.");if(Qs)throw new Error("previous call to 'initWasm()' failed.");if(ss=!0,rn())return new Promise((e,t)=>{ar?.terminate(),gs().then(([s,i])=>{try{ar=i,ar.onerror=l=>t(l),ar.onmessage=sp,Za=[e,t];let o={type:"init-wasm",in:fe};if(!o.in.wasm.wasmPaths&&s){let l=dn();l&&(o.in.wasm.wasmPaths=l)}ar.postMessage(o),Ri=s}catch(o){t(o)}},t)});try{await yn(fe.wasm),await qa(fe),Ks=!0}catch(e){throw Qs=!0,e}finally{ss=!1}}},ap=async e=>{if(rn())return zn(),new Promise((t,s)=>{Dn("init-ep",[t,s]);let i={type:"init-ep",in:{epName:e,env:fe}};ar.postMessage(i)});await Wa(fe,e)},op=async e=>rn()?(zn(),new Promise((t,s)=>{Dn("copy-from",[t,s]);let i={type:"copy-from",in:{buffer:e}};ar.postMessage(i,[e.buffer])})):ki(e),lp=async(e,t)=>{if(rn()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return zn(),new Promise((s,i)=>{Dn("create",[s,i]);let o={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),ar.postMessage(o,l)})}else return ja(e,t)},up=async e=>{if(rn())return zn(),new Promise((t,s)=>{Dn("release",[t,s]);let i={type:"release",in:e};ar.postMessage(i)});Ka(e)},dp=async(e,t,s,i,o,l)=>{if(rn()){if(s.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 zn(),new Promise((u,c)=>{Dn("run",[u,c]);let h=s,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:h,outputIndices:i,options:l}};ar.postMessage(p,Ja(h))})}else return Xa(e,t,s,i,o,l)},cp=async e=>{if(rn())return zn(),new Promise((t,s)=>{Dn("end-profiling",[t,s]);let i={type:"end-profiling",in:e};ar.postMessage(i)});Ya(e)}}),eo,pp,fp,fg=b(()=>{Mt(),hp(),ze(),on(),Cs(),eo=(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()}`)}},pp=e=>{switch(e[3]){case"cpu":return new gt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!bn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:i,dispose:o}=e[2];return gt.fromGpuBuffer(s,{dataType:t,dims:e[1],download:i,dispose:o})}case"ml-tensor":{let t=e[0];if(!Sn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:i,dispose:o}=e[2];return gt.fromMLTensor(s,{dataType:t,dims:e[1],download:i,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},fp=class{async fetchModelAndCopyToWasmMemory(e){return op(await Tn(e))}async loadModel(e,t){mt();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await lp(s,t),rt()}async dispose(){return up(this.sessionId)}async run(e,t,s){mt();let i=[],o=[];Object.entries(e).forEach(m=>{let w=m[0],_=m[1],S=this.inputNames.indexOf(w);if(S===-1)throw new Error(`invalid input '${w}'`);i.push(_),o.push(S)});let l=[],u=[];Object.entries(t).forEach(m=>{let w=m[0],_=m[1],S=this.outputNames.indexOf(w);if(S===-1)throw new Error(`invalid output '${w}'`);l.push(_),u.push(S)});let c=i.map((m,w)=>eo(m,()=>`input "${this.inputNames[o[w]]}"`)),h=l.map((m,w)=>m?eo(m,()=>`output "${this.outputNames[u[w]]}"`):null),p=await dp(this.sessionId,o,c,u,h,s),g={};for(let m=0;m<p.length;m++)g[this.outputNames[u[m]]]=l[m]??pp(p[m]);return rt(),g}startProfiling(){}endProfiling(){cp(this.sessionId)}}}),mp={};N(mp,{OnnxruntimeWebAssemblyBackend:()=>ro,initializeFlags:()=>to,wasmBackend:()=>gp});var to,ro,gp,mg=b(()=>{Mt(),hp(),fg(),to=()=>{(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))}},ro=class{async init(e){to(),await ip(),await ap(e)}async createInferenceSessionHandler(e,t){let s=new fp;return await s.loadModel(e,t),s}},gp=new ro}),yp={};N(yp,{InferenceSession:()=>an,TRACE:()=>Fe,TRACE_EVENT_BEGIN:()=>ue,TRACE_EVENT_END:()=>De,TRACE_FUNC_BEGIN:()=>mt,TRACE_FUNC_END:()=>rt,Tensor:()=>gt,default:()=>yg,env:()=>fe,registerBackend:()=>te}),Mt(),Mt(),Mt();var gg="1.24.3",yg=ls;{let e=(mg(),re(mp)).wasmBackend;te("webgpu",e,5),te("webnn",e,5),te("cpu",e,10),te("wasm",e,10)}return Object.defineProperty(fe.versions,"web",{value:gg,enumerable:!0}),re(yp)})();/**
|
|
2810
|
+
* @license
|
|
2811
|
+
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
2812
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2813
|
+
* you may not use this file except in compliance with the License.
|
|
2814
|
+
* You may obtain a copy of the License at
|
|
2815
|
+
*
|
|
2816
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2817
|
+
*
|
|
2818
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2819
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2820
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2821
|
+
* See the License for the specific language governing permissions and
|
|
2822
|
+
* limitations under the License.
|
|
2823
|
+
* =============================================================================
|
|
2824
|
+
*//**
|
|
2825
|
+
* @license
|
|
2826
|
+
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
2827
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2828
|
+
* you may not use this file except in compliance with the License.
|
|
2829
|
+
* You may obtain a copy of the License at
|
|
2830
|
+
*
|
|
2831
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2832
|
+
*
|
|
2833
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2834
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2835
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2836
|
+
* See the License for the specific language governing permissions and
|
|
2837
|
+
* limitations under the License.
|
|
2838
|
+
* =============================================================================
|
|
2839
|
+
*//**
|
|
2840
|
+
* @license
|
|
2841
|
+
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
2842
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2843
|
+
* you may not use this file except in compliance with the License.
|
|
2844
|
+
* You may obtain a copy of the License at
|
|
2845
|
+
*
|
|
2846
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2847
|
+
*
|
|
2848
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2849
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2850
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2851
|
+
* See the License for the specific language governing permissions and
|
|
2852
|
+
* limitations under the License.
|
|
2853
|
+
* =============================================================================
|
|
2854
|
+
*/d.exports=n})(ho)),ho.exports}var Ln={},po={},Dp;function Uy(){return Dp||(Dp=1,Object.defineProperty(po,"__esModule",{value:!0})),po}var si={},zp;function Fy(){if(zp)return si;zp=1;var d;Object.defineProperty(si,"__esModule",{value:!0}),si.SileroLegacy=void 0;const r=ci();class n{constructor(f,v,$,R,b){this.ortInstance=f,this._session=v,this._h=$,this._c=R,this._sr=b,this.reset_state=()=>{const N=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",N,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",N,[2,1,64])},this.process=async N=>{const re={input:new this.ortInstance.Tensor("float32",N,[1,N.length]),h:this._h,c:this._c,sr:this._sr},X=await this._session.run(re);this._h=X.hn,this._c=X.cn;const[Y]=X.output?.data;return{notSpeech:1-Y,isSpeech:Y}},this.release=async()=>{await this._session.release(),this._h.dispose(),this._c.dispose(),this._sr.dispose()}}}return si.SileroLegacy=n,d=n,n.new=async(a,f)=>{r.log.debug("initializing vad");const v=await f(),$=await a.InferenceSession.create(v),R=new a.Tensor("int64",[16000n]),b=Array(128).fill(0),N=new a.Tensor("float32",b,[2,1,64]),B=new a.Tensor("float32",b,[2,1,64]);return r.log.debug("vad is initialized"),new d(a,$,N,B,R)},si}var ii={},Lp;function Vy(){if(Lp)return ii;Lp=1;var d;Object.defineProperty(ii,"__esModule",{value:!0}),ii.SileroV5=void 0;const r=ci();function n(f){const v=Array(256).fill(0);return new f.Tensor("float32",v,[2,1,128])}class a{constructor(v,$,R,b){this._session=v,this._state=$,this._sr=R,this.ortInstance=b,this.reset_state=()=>{this._state=n(this.ortInstance)},this.process=async N=>{const re={input:new this.ortInstance.Tensor("float32",N,[1,N.length]),state:this._state,sr:this._sr},X=await this._session.run(re);if(!X.stateN)throw new Error("No state from model");if(this._state=X.stateN,!X.output?.data)throw new Error("No output from model");const Y=X.output.data[0];if(typeof Y!="number")throw new Error("Weird output data");return{notSpeech:1-Y,isSpeech:Y}},this.release=async()=>{await this._session.release(),this._state.dispose(),this._sr.dispose()}}}return ii.SileroV5=a,d=a,a.new=async(f,v)=>{r.log.debug("Loading VAD...");const $=await v(),R=await f.InferenceSession.create($),b=new f.Tensor("int64",[16000n]),N=n(f);return r.log.debug("...finished loading VAD"),new d(R,N,b,f)},ii}var Bp;function _f(){return Bp||(Bp=1,(function(d){var r=Ln&&Ln.__createBinding||(Object.create?(function(v,$,R,b){b===void 0&&(b=R);var N=Object.getOwnPropertyDescriptor($,R);(!N||("get"in N?!$.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return $[R]}}),Object.defineProperty(v,b,N)}):(function(v,$,R,b){b===void 0&&(b=R),v[b]=$[R]})),n=Ln&&Ln.__exportStar||function(v,$){for(var R in v)R!=="default"&&!Object.prototype.hasOwnProperty.call($,R)&&r($,v,R)};Object.defineProperty(d,"__esModule",{value:!0}),d.SileroV5=d.SileroLegacy=void 0,n(Uy(),d);var a=Fy();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}})})(Ln)),Ln}var ai={},Np;function bf(){if(Np)return ai;Np=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 v=[];for(const $ of f)for(this.inputBuffer.push($);this.hasEnoughDataForFrame();){const R=this.generateOutputFrame();v.push(R)}return v},a.nativeSampleRate<16e3&&d.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(a){for(const f of a)for(this.inputBuffer.push(f);this.hasEnoughDataForFrame();)yield this.generateOutputFrame()}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){const a=new Float32Array(this.options.targetFrameSize);let f=0,v=0;for(;f<this.options.targetFrameSize;){let $=0,R=0;for(;v<Math.min(this.inputBuffer.length,(f+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const b=this.inputBuffer[v];b!==void 0&&($+=b,R++),v++}a[f]=$/R,f++}return this.inputBuffer=this.inputBuffer.slice(v),a}}return ai.Resampler=r,ai}var Up;function Gy(){return Up||(Up=1,(function(d){var r=qr&&qr.__createBinding||(Object.create?(function(X,Y,te,H){H===void 0&&(H=te);var ae=Object.getOwnPropertyDescriptor(Y,te);(!ae||("get"in ae?!Y.__esModule:ae.writable||ae.configurable))&&(ae={enumerable:!0,get:function(){return Y[te]}}),Object.defineProperty(X,H,ae)}):(function(X,Y,te,H){H===void 0&&(H=te),X[H]=Y[te]})),n=qr&&qr.__setModuleDefault||(Object.create?(function(X,Y){Object.defineProperty(X,"default",{enumerable:!0,value:Y})}):function(X,Y){X.default=Y}),a=qr&&qr.__importStar||function(X){if(X&&X.__esModule)return X;var Y={};if(X!=null)for(var te in X)te!=="default"&&Object.prototype.hasOwnProperty.call(X,te)&&r(Y,X,te);return n(Y,X),Y};Object.defineProperty(d,"__esModule",{value:!0}),d.NonRealTimeVAD=d.defaultNonRealTimeVADOptions=void 0;const f=a(Ny()),v=yf(),$=Lo(),R=Bo(),b=Wi(),N=_f(),B=bf();d.defaultNonRealTimeVADOptions={...R.defaultFrameProcessorOptions,modelURL:v.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:$.defaultModelFetcher};class re{static async new(Y={}){const te={...d.defaultNonRealTimeVADOptions,...Y};(0,R.validateOptions)(te),te.ortConfig!==void 0&&te.ortConfig(f);const H=()=>te.modelFetcher(te.modelURL),ae=await N.SileroLegacy.new(f,H),Te=new R.FrameProcessor(ae.process,ae.reset_state,{positiveSpeechThreshold:te.positiveSpeechThreshold,negativeSpeechThreshold:te.negativeSpeechThreshold,redemptionMs:te.redemptionMs,preSpeechPadMs:te.preSpeechPadMs,minSpeechMs:te.minSpeechMs,submitUserSpeechOnPause:te.submitUserSpeechOnPause},1536/16);return Te.resume(),new this(H,f,te,Te)}constructor(Y,te,H,ae){this.modelFetcher=Y,this.ort=te,this.options=H,this.frameProcessor=ae,this.frameSamples=1536}async*run(Y,te){const H={nativeSampleRate:te,targetSampleRate:16e3,targetFrameSize:this.frameSamples},ae=new B.Resampler(H);let Te=0,Ee=0,ce=0;for await(const he of ae.stream(Y)){const pe=[];await this.frameProcessor.process(he,Pe=>{pe.push(Pe)});for(const Pe of pe)switch(Pe.msg){case b.Message.SpeechStart:Te=ce*this.frameSamples/16;break;case b.Message.SpeechEnd:Ee=(ce+1)*this.frameSamples/16,yield{audio:Pe.audio,start:Te,end:Ee};break}ce++}const le=[];this.frameProcessor.endSegment(he=>{le.push(he)});for(const he of le)switch(he.msg){case b.Message.SpeechEnd:yield{audio:he.audio,start:Te,end:ce*this.frameSamples/16}}}}d.NonRealTimeVAD=re})(qr)),qr}var br={},Fp;function qy(){if(Fp)return br;Fp=1,Object.defineProperty(br,"__esModule",{value:!0}),br.audioFileToArray=br.encodeWAV=br.arrayBufferToBase64=br.minFramesForTargetMS=void 0;function d(R,b,N=16e3){return Math.ceil(R*N/1e3/b)}br.minFramesForTargetMS=d;function r(R){const b=new Uint8Array(R),N=b.byteLength,B=new Array(N);for(let re=0;re<N;re++){const X=b[re];if(X===void 0)break;B[re]=String.fromCharCode(X)}return btoa(B.join(""))}br.arrayBufferToBase64=r;function n(R,b=3,N=16e3,B=1,re=32){const X=re/8,Y=B*X,te=new ArrayBuffer(44+R.length*X),H=new DataView(te);return v(H,0,"RIFF"),H.setUint32(4,36+R.length*X,!0),v(H,8,"WAVE"),v(H,12,"fmt "),H.setUint32(16,16,!0),H.setUint16(20,b,!0),H.setUint16(22,B,!0),H.setUint32(24,N,!0),H.setUint32(28,N*Y,!0),H.setUint16(32,Y,!0),H.setUint16(34,re,!0),v(H,36,"data"),H.setUint32(40,R.length*X,!0),b===1?f(H,44,R):a(H,44,R),te}br.encodeWAV=n;function a(R,b,N){for(let B=0;B<N.length;B++,b+=4)R.setFloat32(b,N[B],!0)}function f(R,b,N){for(let B=0;B<N.length;B++,b+=2){const re=Math.max(-1,Math.min(1,N[B]));R.setInt16(b,re<0?re*32768:re*32767,!0)}}function v(R,b,N){for(let B=0;B<N.length;B++)R.setUint8(b+B,N.charCodeAt(B))}async function $(R){const b=new OfflineAudioContext(1,1,44100),N=new FileReader;let B=null;if(await new Promise(Y=>{N.addEventListener("loadend",()=>{const te=N.result;b.decodeAudioData(te,H=>{B=H,b.startRendering().then(()=>{console.log("Rendering completed successfully"),Y()}).catch(ae=>{console.error("Rendering failed: ",ae)})},H=>{console.log("Error with decoding audio data: ",H)})}),N.readAsArrayBuffer(R)}),B===null)throw Error("some shit");const re=B,X=new Float32Array(re.length);for(let Y=0;Y<re.length;Y++)for(let te=0;te<re.numberOfChannels;te++){const H=re.getChannelData(te)[Y],ae=X[Y];if(H===void 0||ae===void 0)throw new Error("sample or out[i] is undefined");X[Y]=ae+H}return{audio:X,sampleRate:re.sampleRate}}return br.audioFileToArray=$,br}var Wr={},fo={exports:{}};/*!
|
|
2855
|
+
* ONNX Runtime Web v1.24.3
|
|
2856
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2857
|
+
* Licensed under the MIT License.
|
|
2858
|
+
*/var Vp;function Wy(){return Vp||(Vp=1,(function(d,r){var n=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,$=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),N=(y,E)=>{for(var A in E)a(y,A,{get:E[A],enumerable:!0})},B=(y,E,A,D)=>{if(E&&typeof E=="object"||typeof E=="function")for(let P of v(E))!$.call(y,P)&&P!==A&&a(y,P,{get:()=>E[P],enumerable:!(D=f(E,P))||D.enumerable});return y},re=y=>B(a({},"__esModule",{value:!0}),y),X,Y,te,H,ae,Te=b(()=>{X=new Map,Y=[],te=(y,E,A)=>{if(E&&typeof E.init=="function"&&typeof E.createInferenceSessionHandler=="function"){let D=X.get(y);if(D===void 0)X.set(y,{backend:E,priority:A});else{if(D.priority>A)return;if(D.priority===A&&D.backend!==E)throw new Error(`cannot register backend "${y}" using priority ${A}`)}if(A>=0){let P=Y.indexOf(y);P!==-1&&Y.splice(P,1);for(let G=0;G<Y.length;G++)if(X.get(Y[G]).priority<=A){Y.splice(G,0,y);return}Y.push(y)}return}throw new TypeError("not a valid backend")},H=async y=>{let E=X.get(y);if(!E)return"backend not found.";if(E.initialized)return E.backend;if(E.aborted)return E.error;{let A=!!E.initPromise;try{return A||(E.initPromise=E.backend.init(y)),await E.initPromise,E.initialized=!0,E.backend}catch(D){return A||(E.error=`${D}`,E.aborted=!0),E.error}finally{delete E.initPromise}}},ae=async y=>{let E=y.executionProviders||[],A=E.map(V=>typeof V=="string"?V:V.name),D=A.length===0?Y:A,P,G=[],U=new Set;for(let V of D){let ne=await H(V);typeof ne=="string"?G.push({name:V,err:ne}):(P||(P=ne),P===ne&&U.add(V))}if(!P)throw new Error(`no available backend found. ERR: ${G.map(V=>`[${V.name}] ${V.err}`).join(", ")}`);for(let{name:V,err:ne}of G)A.includes(V)&&console.warn(`removing requested execution provider "${V}" from session options because it is not available: ${ne}`);let L=E.filter(V=>U.has(typeof V=="string"?V:V.name));return[P,new Proxy(y,{get:(V,ne)=>ne==="executionProviders"?L:Reflect.get(V,ne)})]}}),Ee=b(()=>{Te()}),ce,le=b(()=>{ce="1.24.3"}),he,pe,Pe=b(()=>{le(),he="warning",pe={wasm:{},webgl:{},webgpu:{},versions:{common:ce},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}`);he=y}},get logLevel(){return he}},Object.defineProperty(pe,"logLevel",{enumerable:!0})}),fe,st=b(()=>{Pe(),fe=pe}),tt,at,Tt=b(()=>{tt=(y,E)=>{let A=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);A.width=y.dims[3],A.height=y.dims[2];let D=A.getContext("2d");if(D!=null){let P,G;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[3]):(P=y.dims[3],G=y.dims[2]);let U=E?.format!==void 0?E.format:"RGB",L=E?.norm,V,ne;L===void 0||L.mean===void 0?V=[255,255,255,255]:typeof L.mean=="number"?V=[L.mean,L.mean,L.mean,L.mean]:(V=[L.mean[0],L.mean[1],L.mean[2],0],L.mean[3]!==void 0&&(V[3]=L.mean[3])),L===void 0||L.bias===void 0?ne=[0,0,0,0]:typeof L.bias=="number"?ne=[L.bias,L.bias,L.bias,L.bias]:(ne=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(ne[3]=L.bias[3]));let ie=G*P,ee=0,K=ie,xe=ie*2,F=-1;U==="RGBA"?(ee=0,K=ie,xe=ie*2,F=ie*3):U==="RGB"?(ee=0,K=ie,xe=ie*2):U==="RBG"&&(ee=0,xe=ie,K=ie*2);for(let de=0;de<G;de++)for(let wt=0;wt<P;wt++){let qe=(y.data[ee++]-ne[0])*V[0],Ce=(y.data[K++]-ne[1])*V[1],We=(y.data[xe++]-ne[2])*V[2],_e=F===-1?255:(y.data[F++]-ne[3])*V[3];D.fillStyle="rgba("+qe+","+Ce+","+We+","+_e+")",D.fillRect(wt,de,1,1)}if("toDataURL"in A)return A.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},at=(y,E)=>{let A=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),D;if(A!=null){let P,G,U;E?.tensorLayout!==void 0&&E.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[1],U=y.dims[3]):(P=y.dims[3],G=y.dims[2],U=y.dims[1]);let L=E!==void 0&&E.format!==void 0?E.format:"RGB",V=E?.norm,ne,ie;V===void 0||V.mean===void 0?ne=[255,255,255,255]:typeof V.mean=="number"?ne=[V.mean,V.mean,V.mean,V.mean]:(ne=[V.mean[0],V.mean[1],V.mean[2],255],V.mean[3]!==void 0&&(ne[3]=V.mean[3])),V===void 0||V.bias===void 0?ie=[0,0,0,0]:typeof V.bias=="number"?ie=[V.bias,V.bias,V.bias,V.bias]:(ie=[V.bias[0],V.bias[1],V.bias[2],0],V.bias[3]!==void 0&&(ie[3]=V.bias[3]));let ee=G*P;if(E!==void 0&&(E.format!==void 0&&U===4&&E.format!=="RGBA"||U===3&&E.format!=="RGB"&&E.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let K=4,xe=0,F=1,de=2,wt=3,qe=0,Ce=ee,We=ee*2,_e=-1;L==="RGBA"?(qe=0,Ce=ee,We=ee*2,_e=ee*3):L==="RGB"?(qe=0,Ce=ee,We=ee*2):L==="RBG"&&(qe=0,We=ee,Ce=ee*2),D=A.createImageData(P,G);for(let zt=0;zt<G*P;xe+=K,F+=K,de+=K,wt+=K,zt++)D.data[xe]=(y.data[qe++]-ie[0])*ne[0],D.data[F]=(y.data[Ce++]-ie[1])*ne[1],D.data[de]=(y.data[We++]-ie[2])*ne[2],D.data[wt]=_e===-1?255:(y.data[_e++]-ie[3])*ne[3]}else throw new Error("Can not access image data");return D}}),Re,Ye,_t,ot,je,Le,Ke=b(()=>{Xt(),Re=(y,E)=>{if(y===void 0)throw new Error("Image buffer must be defined");if(E.height===void 0||E.width===void 0)throw new Error("Image height and width must be defined");if(E.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:A,width:D}=E,P=E.norm??{mean:255,bias:0},G,U;typeof P.mean=="number"?G=[P.mean,P.mean,P.mean,P.mean]:G=[P.mean[0],P.mean[1],P.mean[2],P.mean[3]??255],typeof P.bias=="number"?U=[P.bias,P.bias,P.bias,P.bias]:U=[P.bias[0],P.bias[1],P.bias[2],P.bias[3]??0];let L=E.format!==void 0?E.format:"RGBA",V=E.tensorFormat!==void 0&&E.tensorFormat!==void 0?E.tensorFormat:"RGB",ne=A*D,ie=V==="RGBA"?new Float32Array(ne*4):new Float32Array(ne*3),ee=4,K=0,xe=1,F=2,de=3,wt=0,qe=ne,Ce=ne*2,We=-1;L==="RGB"&&(ee=3,K=0,xe=1,F=2,de=-1),V==="RGBA"?We=ne*3:V==="RBG"?(wt=0,Ce=ne,qe=ne*2):V==="BGR"&&(Ce=0,qe=ne,wt=ne*2);for(let _e=0;_e<ne;_e++,K+=ee,F+=ee,xe+=ee,de+=ee)ie[wt++]=(y[K]+U[0])/G[0],ie[qe++]=(y[xe]+U[1])/G[1],ie[Ce++]=(y[F]+U[2])/G[2],We!==-1&&de!==-1&&(ie[We++]=(y[de]+U[3])/G[3]);return V==="RGBA"?new nt("float32",ie,[1,4,A,D]):new nt("float32",ie,[1,3,A,D])},Ye=async(y,E)=>{let A=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,D=typeof ImageData<"u"&&y instanceof ImageData,P=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,G=typeof y=="string",U,L=E??{},V=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},ne=ie=>typeof HTMLCanvasElement<"u"&&ie instanceof HTMLCanvasElement||ie instanceof OffscreenCanvas?ie.getContext("2d"):null;if(A){let ie=V();ie.width=y.width,ie.height=y.height;let ee=ne(ie);if(ee!=null){let K=y.height,xe=y.width;if(E!==void 0&&E.resizedHeight!==void 0&&E.resizedWidth!==void 0&&(K=E.resizedHeight,xe=E.resizedWidth),E!==void 0){if(L=E,E.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");L.tensorFormat="RGBA",L.height=K,L.width=xe}else L.tensorFormat="RGBA",L.height=K,L.width=xe;ee.drawImage(y,0,0),U=ee.getImageData(0,0,xe,K).data}else throw new Error("Can not access image data")}else if(D){let ie,ee;if(E!==void 0&&E.resizedWidth!==void 0&&E.resizedHeight!==void 0?(ie=E.resizedHeight,ee=E.resizedWidth):(ie=y.height,ee=y.width),E!==void 0&&(L=E),L.format="RGBA",L.height=ie,L.width=ee,E!==void 0){let K=V();K.width=ee,K.height=ie;let xe=ne(K);if(xe!=null)xe.putImageData(y,0,0),U=xe.getImageData(0,0,ee,ie).data;else throw new Error("Can not access image data")}else U=y.data}else if(P){if(E===void 0)throw new Error("Please provide image config with format for Imagebitmap");let ie=V();ie.width=y.width,ie.height=y.height;let ee=ne(ie);if(ee!=null){let K=y.height,xe=y.width;return ee.drawImage(y,0,0,xe,K),U=ee.getImageData(0,0,xe,K).data,L.height=K,L.width=xe,Re(U,L)}else throw new Error("Can not access image data")}else{if(G)return new Promise((ie,ee)=>{let K=V(),xe=ne(K);if(!y||!xe)return ee();let F=new Image;F.crossOrigin="Anonymous",F.src=y,F.onload=()=>{K.width=F.width,K.height=F.height,xe.drawImage(F,0,0,K.width,K.height);let de=xe.getImageData(0,0,K.width,K.height);L.height=K.height,L.width=K.width,ie(Re(de.data,L))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(U!==void 0)return Re(U,L);throw new Error("Input data provided is not supported - aborted tensor creation")},_t=(y,E)=>{let{width:A,height:D,download:P,dispose:G}=E,U=[1,D,A,4];return new nt({location:"texture",type:"float32",texture:y,dims:U,download:P,dispose:G})},ot=(y,E)=>{let{dataType:A,dims:D,download:P,dispose:G}=E;return new nt({location:"gpu-buffer",type:A??"float32",gpuBuffer:y,dims:D,download:P,dispose:G})},je=(y,E)=>{let{dataType:A,dims:D,download:P,dispose:G}=E;return new nt({location:"ml-tensor",type:A??"float32",mlTensor:y,dims:D,download:P,dispose:G})},Le=(y,E,A)=>new nt({location:"cpu-pinned",type:y,data:E,dims:A??[E.length]})}),Ze,Z,Oe,et,pt=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]]),Z=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Oe=!1,et=()=>{if(!Oe){Oe=!0;let y=typeof BigInt64Array<"u"&&BigInt64Array.from,E=typeof BigUint64Array<"u"&&BigUint64Array.from,A=globalThis.Float16Array,D=typeof A<"u"&&A.from;y&&(Ze.set("int64",BigInt64Array),Z.set(BigInt64Array,"int64")),E&&(Ze.set("uint64",BigUint64Array),Z.set(BigUint64Array,"uint64")),D?(Ze.set("float16",A),Z.set(A,"float16")):Ze.set("float16",Uint16Array)}}}),Ft,$t,dt=b(()=>{Xt(),Ft=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},$t=(y,E)=>{switch(y.location){case"cpu":return new nt(y.type,y.data,E);case"cpu-pinned":return new nt({location:"cpu-pinned",data:y.data,type:y.type,dims:E});case"texture":return new nt({location:"texture",texture:y.texture,type:y.type,dims:E});case"gpu-buffer":return new nt({location:"gpu-buffer",gpuBuffer:y.gpuBuffer,type:y.type,dims:E});case"ml-tensor":return new nt({location:"ml-tensor",mlTensor:y.mlTensor,type:y.type,dims:E});default:throw new Error(`tensorReshape: tensor location ${y.location} is not supported`)}}}),nt,Xt=b(()=>{Tt(),Ke(),pt(),dt(),nt=class{constructor(y,E,A){et();let D,P;if(typeof y=="object"&&"location"in y)switch(this.dataLocation=y.location,D=y.type,P=y.dims,y.location){case"cpu-pinned":{let U=Ze.get(D);if(!U)throw new TypeError(`unsupported type "${D}" to create tensor from pinned buffer`);if(!(y.data instanceof U))throw new TypeError(`buffer should be of type ${U.name}`);this.cpuData=y.data;break}case"texture":{if(D!=="float32")throw new TypeError(`unsupported type "${D}" to create tensor from texture`);this.gpuTextureData=y.texture,this.downloader=y.download,this.disposer=y.dispose;break}case"gpu-buffer":{if(D!=="float32"&&D!=="float16"&&D!=="int32"&&D!=="int64"&&D!=="uint32"&&D!=="uint8"&&D!=="bool"&&D!=="uint4"&&D!=="int4")throw new TypeError(`unsupported type "${D}" to create tensor from gpu buffer`);this.gpuBufferData=y.gpuBuffer,this.downloader=y.download,this.disposer=y.dispose;break}case"ml-tensor":{if(D!=="float32"&&D!=="float16"&&D!=="int32"&&D!=="int64"&&D!=="uint32"&&D!=="uint64"&&D!=="int8"&&D!=="uint8"&&D!=="bool"&&D!=="uint4"&&D!=="int4")throw new TypeError(`unsupported type "${D}" to create tensor from MLTensor`);this.mlTensorData=y.mlTensor,this.downloader=y.download,this.disposer=y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let U,L;if(typeof y=="string")if(D=y,L=A,y==="string"){if(!Array.isArray(E))throw new TypeError("A string tensor's data must be a string array.");U=E}else{let V=Ze.get(y);if(V===void 0)throw new TypeError(`Unsupported tensor type: ${y}.`);if(Array.isArray(E)){if(y==="float16"&&V===Uint16Array||y==="uint4"||y==="int4")throw new TypeError(`Creating a ${y} tensor from number array is not supported. Please use ${V.name} as data.`);y==="uint64"||y==="int64"?U=V.from(E,BigInt):U=V.from(E)}else if(E instanceof V)U=E;else if(E instanceof Uint8ClampedArray)if(y==="uint8")U=Uint8Array.from(E);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(y==="float16"&&E instanceof Uint16Array&&V!==Uint16Array)U=new globalThis.Float16Array(E.buffer,E.byteOffset,E.length);else throw new TypeError(`A ${D} tensor's data must be type of ${V}`)}else if(L=E,Array.isArray(y)){if(y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let V=typeof y[0];if(V==="string")D="string",U=y;else if(V==="boolean")D="bool",U=Uint8Array.from(y);else throw new TypeError(`Invalid element type of data array: ${V}.`)}else if(y instanceof Uint8ClampedArray)D="uint8",U=Uint8Array.from(y);else{let V=Z.get(y.constructor);if(V===void 0)throw new TypeError(`Unsupported type for tensor data: ${y.constructor}.`);D=V,U=y}if(L===void 0)L=[U.length];else if(!Array.isArray(L))throw new TypeError("A tensor's dims must be a number array");P=L,this.cpuData=U,this.dataLocation="cpu"}let G=Ft(P);if(this.cpuData&&G!==this.cpuData.length&&!((D==="uint4"||D==="int4")&&Math.ceil(G/2)===this.cpuData.length))throw new Error(`Tensor's size(${G}) does not match data length(${this.cpuData.length}).`);this.type=D,this.dims=P,this.size=G}static async fromImage(y,E){return Ye(y,E)}static fromTexture(y,E){return _t(y,E)}static fromGpuBuffer(y,E){return ot(y,E)}static fromMLTensor(y,E){return je(y,E)}static fromPinnedBuffer(y,E,A){return Le(y,E,A)}toDataURL(y){return tt(this,y)}toImageData(y){return at(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 $t(this,y)}}}),gt,Se=b(()=>{Xt(),gt=nt}),Fe,ft,mt,rt,ue,De,Dt=b(()=>{Pe(),Fe=(y,E)=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeStamp(`${y}::ORT::${E}`)},ft=(y,E)=>{let A=new Error().stack?.split(/\r\n|\r|\n/g)||[],D=!1;for(let P=0;P<A.length;P++){if(D&&!A[P].includes("TRACE_FUNC")){let G=`FUNC_${y}::${A[P].trim().split(" ")[1]}`;E&&(G+=`::${E}`),Fe("CPU",G);return}A[P].includes("TRACE_FUNC")&&(D=!0)}},mt=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||ft("BEGIN",y)},rt=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||ft("END",y)},ue=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.time(`ORT::${y}`)},De=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeEnd(`ORT::${y}`)}}),Ht,Dr=b(()=>{Te(),Se(),Dt(),Ht=class Sf{constructor(E){this.handler=E}async run(E,A,D){mt(),ue("InferenceSession.run");let P={},G={};if(typeof E!="object"||E===null||E instanceof gt||Array.isArray(E))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let U=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof gt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");U=!1;for(let ne of A){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);P[ne]=null}if(typeof D=="object"&&D!==null)G=D;else if(typeof D<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1,ie=Object.getOwnPropertyNames(A);for(let ee of this.outputNames)if(ie.indexOf(ee)!==-1){let K=A[ee];(K===null||K instanceof gt)&&(ne=!0,U=!1,P[ee]=K)}if(ne){if(typeof D=="object"&&D!==null)G=D;else if(typeof D<"u")throw new TypeError("'options' must be an object.")}else G=A}}else if(typeof A<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let ne of this.inputNames)if(typeof E[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(U)for(let ne of this.outputNames)P[ne]=null;let L=await this.handler.run(E,P,G),V={};for(let ne in L)if(Object.hasOwnProperty.call(L,ne)){let ie=L[ne];ie instanceof gt?V[ne]=ie:V[ne]=new gt(ie.type,ie.data,ie.dims)}return De("InferenceSession.run"),rt(),V}async release(){return this.handler.dispose()}static async create(E,A,D,P){mt(),ue("InferenceSession.create");let G,U={};if(typeof E=="string"){if(G=E,typeof A=="object"&&A!==null)U=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(E instanceof Uint8Array){if(G=E,typeof A=="object"&&A!==null)U=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(E instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&E instanceof SharedArrayBuffer){let ie=E,ee=0,K=E.byteLength;if(typeof A=="object"&&A!==null)U=A;else if(typeof A=="number"){if(ee=A,!Number.isSafeInteger(ee))throw new RangeError("'byteOffset' must be an integer.");if(ee<0||ee>=ie.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${ie.byteLength}).`);if(K=E.byteLength-ee,typeof D=="number"){if(K=D,!Number.isSafeInteger(K))throw new RangeError("'byteLength' must be an integer.");if(K<=0||ee+K>ie.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${ie.byteLength-ee}].`);if(typeof P=="object"&&P!==null)U=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(typeof D<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof A<"u")throw new TypeError("'options' must be an object.");G=new Uint8Array(ie,ee,K)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[L,V]=await ae(U),ne=await L.createInferenceSessionHandler(G,V);return De("InferenceSession.create"),rt(),new Sf(ne)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),an,Hi=b(()=>{Dr(),an=Ht}),ji=b(()=>{}),Ki=b(()=>{}),Qi=b(()=>{}),Xi=b(()=>{}),ls={};N(ls,{InferenceSession:()=>an,TRACE:()=>Fe,TRACE_EVENT_BEGIN:()=>ue,TRACE_EVENT_END:()=>De,TRACE_FUNC_BEGIN:()=>mt,TRACE_FUNC_END:()=>rt,Tensor:()=>gt,env:()=>fe,registerBackend:()=>te});var Mt=b(()=>{Ee(),st(),Hi(),Se(),ji(),Ki(),Dt(),Qi(),Xi()}),on=b(()=>{}),us={};N(us,{default:()=>ds});var ln,un,ds,Yi=b(()=>{Rs(),Yt(),fn(),ln="ort-wasm-proxy-worker",un=globalThis.self?.name===ln,un&&(self.onmessage=y=>{let{type:E,in:A}=y.data;try{switch(E){case"init-wasm":yn(A.wasm).then(()=>{Fn(A).then(()=>{postMessage({type:E})},D=>{postMessage({type:E,err:D})})},D=>{postMessage({type:E,err:D})});break;case"init-ep":{let{epName:D,env:P}=A;Vn(P,D).then(()=>{postMessage({type:E})},G=>{postMessage({type:E,err:G})});break}case"copy-from":{let{buffer:D}=A,P=Je(D);postMessage({type:E,out:P});break}case"create":{let{model:D,options:P}=A;rr(D,P).then(G=>{postMessage({type:E,out:G})},G=>{postMessage({type:E,err:G})});break}case"release":Wn(A),postMessage({type:E});break;case"run":{let{sessionId:D,inputIndices:P,inputs:G,outputIndices:U,options:L}=A;j(D,P,G,U,new Array(U.length).fill(null),L).then(V=>{V.some(ne=>ne[3]!=="cpu")?postMessage({type:E,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:E,out:V},Hn([...G,...V]))},V=>{postMessage({type:E,err:V})});break}case"end-profiling":Qr(A),postMessage({type:E});break;default:}}catch(D){postMessage({type:E,err:D})}}),ds=un?null:y=>new Worker(y??yt,{type:"classic",name:ln})}),cs,hs,yt,dn,zr,ps,fs,cn,ms,hn,gs,pn,ys,fn=b(()=>{on(),cs=typeof location>"u"?void 0:location.origin,hs=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,yt=hs(),dn=()=>{if(yt&&!yt.startsWith("blob:"))return yt.substring(0,yt.lastIndexOf("/")+1)},zr=(y,E)=>{try{let A=E??yt;return(A?new URL(y,A):new URL(y)).origin===cs}catch{return!1}},ps=(y,E)=>{let A=E??yt;try{return(A?new URL(y,A):new URL(y)).href}catch{return}},fs=(y,E)=>`${E??"./"}${y}`,cn=async y=>{let E=await(await fetch(y,{credentials:"same-origin"})).blob();return URL.createObjectURL(E)},ms=async y=>(await import(y)).default,hn=(Yi(),re(us)).default,gs=async()=>{if(!yt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(zr(yt))return[void 0,hn()];let y=await cn(yt);return[y,hn(y)]},pn=void 0,ys=async(y,E,A,D)=>{let P=pn&&!(y||E);if(P)if(yt)P=zr(yt)||D&&!A;else if(D&&!A)P=!0;else throw new Error("cannot determine the script source URL.");if(P)return[void 0,pn];{let G="ort-wasm-simd-threaded.mjs",U=y??ps(G,E),L=A&&U&&!zr(U,E),V=L?await cn(U):U??fs(G,E);return[L?V:void 0,await ms(V)]}}}),mn,Lr,dr,gn,ws,vs,_s,yn,Ne,Yt=b(()=>{fn(),Lr=!1,dr=!1,gn=!1,ws=()=>{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}},vs=()=>{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}},_s=()=>{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}},yn=async y=>{if(Lr)return Promise.resolve();if(dr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(gn)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(!_s())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!vs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let D=ws();A>1&&!D&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+A+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),y.numThreads=A=1);let P=y.wasmPaths,G=typeof P=="string"?P:void 0,U=P?.mjs,L=U?.href??U,V=P?.wasm,ne=V?.href??V,ie=y.wasmBinary,[ee,K]=await ys(L,G,A>1,!!ie||!!ne),xe=!1,F=[];if(E>0&&F.push(new Promise(de=>{setTimeout(()=>{xe=!0,de()},E)})),F.push(new Promise((de,wt)=>{let qe={numThreads:A};if(ie)qe.wasmBinary=ie,qe.locateFile=Ce=>Ce;else if(ne||G)qe.locateFile=Ce=>ne??G+Ce;else if(L&&L.indexOf("blob:")!==0)qe.locateFile=Ce=>new URL(Ce,L).href;else if(ee){let Ce=dn();Ce&&(qe.locateFile=We=>Ce+We)}K(qe).then(Ce=>{dr=!1,Lr=!0,mn=Ce,de(),ee&&URL.revokeObjectURL(ee)},Ce=>{dr=!1,gn=!0,wt(Ce)})})),await Promise.race(F),xe)throw new Error(`WebAssembly backend initializing failed due to timeout: ${E}ms`)},Ne=()=>{if(Lr&&mn)return mn;throw new Error("WebAssembly is not initialized yet.")}}),Et,Br,Ie,wn=b(()=>{Yt(),Et=(y,E)=>{let A=Ne(),D=A.lengthBytesUTF8(y)+1,P=A._malloc(D);return A.stringToUTF8(y,P,D),E.push(P),P},Br=(y,E,A,D)=>{if(typeof y=="object"&&y!==null){if(A.has(y))throw new Error("Circular reference in options");A.add(y)}Object.entries(y).forEach(([P,G])=>{let U=E?E+P:P;if(typeof G=="object")Br(G,U+".",A,D);else if(typeof G=="string"||typeof G=="number")D(U,G.toString());else if(typeof G=="boolean")D(U,G?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof G}`)})},Ie=y=>{let E=Ne(),A=E.stackSave();try{let D=E.PTR_SIZE,P=E.stackAlloc(2*D);E._OrtGetLastError(P,P+D);let G=Number(E.getValue(P,D===4?"i32":"i64")),U=E.getValue(P+D,"*"),L=U?E.UTF8ToString(U):"";throw new Error(`${y} ERROR_CODE: ${G}, ERROR_MESSAGE: ${L}`)}finally{E.stackRestore(A)}}}),bs,Ji=b(()=>{Yt(),wn(),bs=y=>{let E=Ne(),A=0,D=[],P=y||{};try{if(y?.logSeverityLevel===void 0)P.logSeverityLevel=2;else if(typeof y.logSeverityLevel!="number"||!Number.isInteger(y.logSeverityLevel)||y.logSeverityLevel<0||y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${y.logSeverityLevel}`);if(y?.logVerbosityLevel===void 0)P.logVerbosityLevel=0;else if(typeof y.logVerbosityLevel!="number"||!Number.isInteger(y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${y.logVerbosityLevel}`);y?.terminate===void 0&&(P.terminate=!1);let G=0;return y?.tag!==void 0&&(G=Et(y.tag,D)),A=E._OrtCreateRunOptions(P.logSeverityLevel,P.logVerbosityLevel,!!P.terminate,G),A===0&&Ie("Can't create run options."),y?.extra!==void 0&&Br(y.extra,"",new WeakSet,(U,L)=>{let V=Et(U,D),ne=Et(L,D);E._OrtAddRunConfigEntry(A,V,ne)!==0&&Ie(`Can't set a run config entry: ${U} - ${L}.`)}),[A,D]}catch(G){throw A!==0&&E._OrtReleaseRunOptions(A),D.forEach(U=>E._free(U)),G}}}),Ss,Ts,Es,cr,$s,xs,Zi=b(()=>{Yt(),wn(),Ss=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}`)}},Ts=y=>{switch(y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${y}`)}},Es=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)},cr=(y,E,A,D)=>{let P=Et(E,D),G=Et(A,D);Ne()._OrtAddSessionConfigEntry(y,P,G)!==0&&Ie(`Can't set a session config entry: ${E} - ${A}.`)},$s=async(y,E,A)=>{let D=E.executionProviders;for(let P of D){let G=typeof P=="string"?P:P.name,U=[];switch(G){case"webnn":if(G="WEBNN",typeof P!="string"){let ee=P?.deviceType;ee&&cr(y,"deviceType",ee,A)}break;case"webgpu":if(G="JS",typeof P!="string"){let ee=P;if(ee?.preferredLayout){if(ee.preferredLayout!=="NCHW"&&ee.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${ee.preferredLayout}`);cr(y,"preferredLayout",ee.preferredLayout,A)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${G}`)}let L=Et(G,A),V=U.length,ne=0,ie=0;if(V>0){ne=Ne()._malloc(V*Ne().PTR_SIZE),A.push(ne),ie=Ne()._malloc(V*Ne().PTR_SIZE),A.push(ie);for(let ee=0;ee<V;ee++)Ne().setValue(ne+ee*Ne().PTR_SIZE,U[ee][0],"*"),Ne().setValue(ie+ee*Ne().PTR_SIZE,U[ee][1],"*")}await Ne()._OrtAppendExecutionProvider(y,L,ne,ie,V)!==0&&Ie(`Can't append execution provider: ${G}.`)}},xs=async y=>{let E=Ne(),A=0,D=[],P=y||{};Es(P);try{let G=Ss(P.graphOptimizationLevel??"all"),U=Ts(P.executionMode??"sequential"),L=typeof P.logId=="string"?Et(P.logId,D):0,V=P.logSeverityLevel??2;if(!Number.isInteger(V)||V<0||V>4)throw new Error(`log severity level is not valid: ${V}`);let ne=P.logVerbosityLevel??0;if(!Number.isInteger(ne)||ne<0||ne>4)throw new Error(`log verbosity level is not valid: ${ne}`);let ie=typeof P.optimizedModelFilePath=="string"?Et(P.optimizedModelFilePath,D):0;if(A=E._OrtCreateSessionOptions(G,!!P.enableCpuMemArena,!!P.enableMemPattern,U,!!P.enableProfiling,0,L,V,ne,ie),A===0&&Ie("Can't create session options."),P.executionProviders&&await $s(A,P,D),P.enableGraphCapture!==void 0){if(typeof P.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${P.enableGraphCapture}`);cr(A,"enableGraphCapture",P.enableGraphCapture.toString(),D)}if(P.freeDimensionOverrides)for(let[ee,K]of Object.entries(P.freeDimensionOverrides)){if(typeof ee!="string")throw new Error(`free dimension override name must be a string: ${ee}`);if(typeof K!="number"||!Number.isInteger(K)||K<0)throw new Error(`free dimension override value must be a non-negative integer: ${K}`);let xe=Et(ee,D);E._OrtAddFreeDimensionOverride(A,xe,K)!==0&&Ie(`Can't set a free dimension override: ${ee} - ${K}.`)}return P.extra!==void 0&&Br(P.extra,"",new WeakSet,(ee,K)=>{cr(A,ee,K,D)}),[A,D]}catch(G){throw A!==0&&E._OrtReleaseSessionOptions(A)!==0&&Ie("Can't release session options."),D.forEach(U=>E._free(U)),G}}}),Jt,Zt,er,vn,_n,bn,Sn,Un,ze=b(()=>{Jt=y=>{switch(y){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${y}`)}},Zt=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}`)}},er=(y,E)=>{let A=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][y],D=typeof E=="number"?E:E.reduce((P,G)=>P*G,1);return A>0?Math.ceil(D*A):void 0},vn=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}`)}},_n=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}`)}},bn=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Sn=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint64"||y==="int8"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Un=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}`)}}}),Tn,Cs=b(()=>{on(),Tn=async y=>{if(typeof y=="string"){let E=await fetch(y);if(!E.ok)throw new Error(`failed to load external data file: ${y}`);let A=E.headers.get("Content-Length"),D=A?parseInt(A,10):0;if(D<1073741824)return new Uint8Array(await E.arrayBuffer());{if(!E.body)throw new Error(`failed to load external data file: ${y}, no response body.`);let P=E.body.getReader(),G;try{G=new ArrayBuffer(D)}catch(L){if(L instanceof RangeError){let V=Math.ceil(D/65536);G=new WebAssembly.Memory({initial:V,maximum:V}).buffer}else throw L}let U=0;for(;;){let{done:L,value:V}=await P.read();if(L)break;let ne=V.byteLength;new Uint8Array(G,U,ne).set(V),U+=ne}return new Uint8Array(G,0,D)}}else return y instanceof Blob?new Uint8Array(await y.arrayBuffer()):y instanceof Uint8Array?y:new Uint8Array(y)}}),ks,Fn,Vn,Er,Gn,qn,Je,rr,Wn,$r,j,Qr,Hn,Rs=b(()=>{Mt(),Ji(),Zi(),ze(),Yt(),wn(),Cs(),ks=(y,E)=>{Ne()._OrtInit(y,E)!==0&&Ie("Can't initialize onnxruntime.")},Fn=async y=>{ks(y.wasm.numThreads,_n(y.logLevel))},Vn=async(y,E)=>{Ne().asyncInit?.();let A=y.webgpu.adapter;if(E==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(A){if(typeof A.limits!="object"||typeof A.features!="object"||typeof A.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let D=y.webgpu.powerPreference;if(D!==void 0&&D!=="low-power"&&D!=="high-performance")throw new Error(`Invalid powerPreference setting: "${D}"`);let P=y.webgpu.forceFallbackAdapter;if(P!==void 0&&typeof P!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${P}"`);if(A=await navigator.gpu.requestAdapter({powerPreference:D,forceFallbackAdapter:P}),!A)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(E==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Er=new Map,Gn=y=>{let E=Ne(),A=E.stackSave();try{let D=E.PTR_SIZE,P=E.stackAlloc(2*D);E._OrtGetInputOutputCount(y,P,P+D)!==0&&Ie("Can't get session input/output count.");let G=D===4?"i32":"i64";return[Number(E.getValue(P,G)),Number(E.getValue(P+D,G))]}finally{E.stackRestore(A)}},qn=(y,E)=>{let A=Ne(),D=A.stackSave(),P=0;try{let G=A.PTR_SIZE,U=A.stackAlloc(2*G);A._OrtGetInputOutputMetadata(y,E,U,U+G)!==0&&Ie("Can't get session input/output metadata.");let L=Number(A.getValue(U,"*"));P=Number(A.getValue(U+G,"*"));let V=A.HEAP32[P/4];if(V===0)return[L,0];let ne=A.HEAPU32[P/4+1],ie=[];for(let ee=0;ee<ne;ee++){let K=Number(A.getValue(P+8+ee*G,"*"));ie.push(K!==0?A.UTF8ToString(K):Number(A.getValue(P+8+(ee+ne)*G,"*")))}return[L,V,ie]}finally{A.stackRestore(D),P!==0&&A._OrtFree(P)}},Je=y=>{let E=Ne(),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]},rr=async(y,E)=>{let A,D,P=Ne();Array.isArray(y)?[A,D]=y:y.buffer===P.HEAPU8.buffer?[A,D]=[y.byteOffset,y.byteLength]:[A,D]=Je(y);let G=0,U=0,L=[],V=[],ne=[];try{if([U,L]=await xs(E),E?.externalData&&P.mountExternalData){let Ce=[];for(let We of E.externalData){let _e=typeof We=="string"?We:We.path;Ce.push(Tn(typeof We=="string"?We:We.data).then(zt=>{P.mountExternalData(_e,zt)}))}await Promise.all(Ce)}for(let Ce of E?.executionProviders??[])if((typeof Ce=="string"?Ce:Ce.name)==="webnn"){if(P.shouldTransferToMLTensor=!1,typeof Ce!="string"){let We=Ce,_e=We?.context,zt=We?.gpuDevice,Lt=We?.deviceType,kr=We?.powerPreference;_e?P.currentContext=_e:zt?P.currentContext=await P.webnnCreateMLContext(zt):P.currentContext=await P.webnnCreateMLContext({deviceType:Lt,powerPreference:kr})}else P.currentContext=await P.webnnCreateMLContext();break}G=await P._OrtCreateSession(A,D,U),P.webgpuOnCreateSession?.(G),G===0&&Ie("Can't create a session."),P.jsepOnCreateSession?.(),P.currentContext&&(P.webnnRegisterMLContext(G,P.currentContext),P.currentContext=void 0,P.shouldTransferToMLTensor=!0);let[ie,ee]=Gn(G),K=!!E?.enableGraphCapture,xe=[],F=[],de=[],wt=[],qe=[];for(let Ce=0;Ce<ie;Ce++){let[We,_e,zt]=qn(G,Ce);We===0&&Ie("Can't get an input name."),V.push(We);let Lt=P.UTF8ToString(We);xe.push(Lt),de.push(_e===0?{name:Lt,isTensor:!1}:{name:Lt,isTensor:!0,type:Zt(_e),shape:zt})}for(let Ce=0;Ce<ee;Ce++){let[We,_e,zt]=qn(G,Ce+ie);We===0&&Ie("Can't get an output name."),ne.push(We);let Lt=P.UTF8ToString(We);F.push(Lt),wt.push(_e===0?{name:Lt,isTensor:!1}:{name:Lt,isTensor:!0,type:Zt(_e),shape:zt})}return Er.set(G,[G,V,ne,null,K,!1]),[G,xe,F,de,wt]}catch(ie){throw V.forEach(ee=>P._OrtFree(ee)),ne.forEach(ee=>P._OrtFree(ee)),G!==0&&P._OrtReleaseSession(G)!==0&&Ie("Can't release session."),ie}finally{P._free(A),U!==0&&P._OrtReleaseSessionOptions(U)!==0&&Ie("Can't release session options."),L.forEach(ie=>P._free(ie)),P.unmountExternalData?.()}},Wn=y=>{let E=Ne(),A=Er.get(y);if(!A)throw new Error(`cannot release session. invalid session id: ${y}`);let[D,P,G,U,L]=A;U&&(L&&E._OrtClearBoundOutputs(U.handle)!==0&&Ie("Can't clear bound outputs."),E._OrtReleaseBinding(U.handle)!==0&&Ie("Can't release IO binding.")),E.jsepOnReleaseSession?.(y),E.webnnOnReleaseSession?.(y),E.webgpuOnReleaseSession?.(y),P.forEach(V=>E._OrtFree(V)),G.forEach(V=>E._OrtFree(V)),E._OrtReleaseSession(D)!==0&&Ie("Can't release session."),Er.delete(y)},$r=async(y,E,A,D,P,G,U=!1)=>{if(!y){E.push(0);return}let L=Ne(),V=L.PTR_SIZE,ne=y[0],ie=y[1],ee=y[3],K=ee,xe,F;if(ne==="string"&&(ee==="gpu-buffer"||ee==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(U&&ee!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${G} when enableGraphCapture is true.`);if(ee==="gpu-buffer"){let qe=y[2].gpuBuffer;F=er(Jt(ne),ie);{let Ce=L.jsepRegisterBuffer;if(!Ce)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');xe=Ce(D,G,qe,F)}}else if(ee==="ml-tensor"){let qe=y[2].mlTensor;F=er(Jt(ne),ie);let Ce=L.webnnRegisterMLTensor;if(!Ce)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');xe=Ce(D,qe,Jt(ne),ie)}else{let qe=y[2];if(Array.isArray(qe)){F=V*qe.length,xe=L._malloc(F),A.push(xe);for(let Ce=0;Ce<qe.length;Ce++){if(typeof qe[Ce]!="string")throw new TypeError(`tensor data at index ${Ce} is not a string`);L.setValue(xe+Ce*V,Et(qe[Ce],A),"*")}}else{let Ce=L.webnnIsGraphInput,We=L.webnnIsGraphOutput;if(ne!=="string"&&Ce&&We){let _e=L.UTF8ToString(P);if(Ce(D,_e)||We(D,_e)){let zt=Jt(ne);F=er(zt,ie),K="ml-tensor";let Lt=L.webnnCreateTemporaryTensor,kr=L.webnnUploadTensor;if(!Lt||!kr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Zr=await Lt(D,zt,ie);kr(Zr,new Uint8Array(qe.buffer,qe.byteOffset,qe.byteLength)),xe=Zr}else F=qe.byteLength,xe=L._malloc(F),A.push(xe),L.HEAPU8.set(new Uint8Array(qe.buffer,qe.byteOffset,F),xe)}else F=qe.byteLength,xe=L._malloc(F),A.push(xe),L.HEAPU8.set(new Uint8Array(qe.buffer,qe.byteOffset,F),xe)}}let de=L.stackSave(),wt=L.stackAlloc(4*ie.length);try{ie.forEach((Ce,We)=>L.setValue(wt+We*V,Ce,V===4?"i32":"i64"));let qe=L._OrtCreateTensor(Jt(ne),xe,F,wt,ie.length,Un(K));qe===0&&Ie(`Can't create tensor for input/output. session=${D}, index=${G}.`),E.push(qe)}finally{L.stackRestore(de)}},j=async(y,E,A,D,P,G)=>{let U=Ne(),L=U.PTR_SIZE,V=Er.get(y);if(!V)throw new Error(`cannot run inference. invalid session id: ${y}`);let ne=V[0],ie=V[1],ee=V[2],K=V[3],xe=V[4];V[5];let F=E.length,de=D.length,wt=0,qe=[],Ce=[],We=[],_e=[],zt=[],Lt=U.stackSave(),kr=U.stackAlloc(F*L),Zr=U.stackAlloc(F*L),rs=U.stackAlloc(de*L),Ls=U.stackAlloc(de*L);try{[wt,qe]=bs(G),ue("wasm prepareInputOutputTensor");for(let He=0;He<F;He++)await $r(A[He],Ce,_e,y,ie[E[He]],E[He],xe);for(let He=0;He<de;He++)await $r(P[He],We,_e,y,ee[D[He]],F+D[He],xe);De("wasm prepareInputOutputTensor");for(let He=0;He<F;He++)U.setValue(kr+He*L,Ce[He],"*"),U.setValue(Zr+He*L,ie[E[He]],"*");for(let He=0;He<de;He++)U.setValue(rs+He*L,We[He],"*"),U.setValue(Ls+He*L,ee[D[He]],"*");U.jsepOnRunStart?.(ne),U.webnnOnRunStart?.(ne);let bt;bt=await U._OrtRun(ne,Zr,kr,F,Ls,de,rs,wt),bt!==0&&Ie("failed to call OrtRun().");let sr=[],Bs=[];ue("wasm ProcessOutputTensor");for(let He=0;He<de;He++){let nr=Number(U.getValue(rs+He*L,"*"));if(nr===We[He]||zt.includes(We[He])){sr.push(P[He]),nr!==We[He]&&U._OrtReleaseTensor(nr)!==0&&Ie("Can't release tensor.");continue}let mi=U.stackSave(),fr=U.stackAlloc(4*L),Cn=!1,xt,qt=0;try{U._OrtGetTensorData(nr,fr,fr+L,fr+2*L,fr+3*L)!==0&&Ie(`Can't access output tensor data on index ${He}.`);let ns=L===4?"i32":"i64",kn=Number(U.getValue(fr,ns));qt=U.getValue(fr+L,"*");let Ns=U.getValue(fr+L*2,"*"),gi=Number(U.getValue(fr+L*3,ns)),Pt=[];for(let Ct=0;Ct<gi;Ct++)Pt.push(Number(U.getValue(Ns+Ct*L,ns)));U._OrtFree(Ns)!==0&&Ie("Can't free memory for tensor dims.");let mr=Pt.reduce((Ct,St)=>Ct*St,1);xt=Zt(kn);let en=K?.outputPreferredLocations[D[He]];if(xt==="string"){if(en==="gpu-buffer"||en==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ct=[];for(let St=0;St<mr;St++){let ir=U.getValue(qt+St*L,"*"),yi=U.getValue(qt+(St+1)*L,"*"),wi=St===mr-1?void 0:yi-ir;Ct.push(U.UTF8ToString(ir,wi))}sr.push([xt,Pt,Ct,"cpu"])}else if(en==="gpu-buffer"&&mr>0){let Ct=U.jsepGetBuffer;if(!Ct)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let St=Ct(qt),ir=er(kn,mr);if(ir===void 0||!bn(xt))throw new Error(`Unsupported data type: ${xt}`);Cn=!0,sr.push([xt,Pt,{gpuBuffer:St,download:U.jsepCreateDownloader(St,ir,xt),dispose:()=>{U._OrtReleaseTensor(nr)!==0&&Ie("Can't release tensor.")}},"gpu-buffer"])}else if(en==="ml-tensor"&&mr>0){let Ct=U.webnnEnsureTensor,St=U.webnnIsGraphInputOutputTypeSupported;if(!Ct||!St)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(er(kn,mr)===void 0||!Sn(xt))throw new Error(`Unsupported data type: ${xt}`);if(!St(y,xt,!1))throw new Error(`preferredLocation "ml-tensor" for ${xt} output is not supported by current WebNN Context.`);let ir=await Ct(y,qt,kn,Pt,!1);Cn=!0,sr.push([xt,Pt,{mlTensor:ir,download:U.webnnCreateMLTensorDownloader(qt,xt),dispose:()=>{U.webnnReleaseTensorId(qt),U._OrtReleaseTensor(nr)}},"ml-tensor"])}else if(en==="ml-tensor-cpu-output"&&mr>0){let Ct=U.webnnCreateMLTensorDownloader(qt,xt)(),St=sr.length;Cn=!0,Bs.push((async()=>{let ir=[St,await Ct];return U.webnnReleaseTensorId(qt),U._OrtReleaseTensor(nr),ir})()),sr.push([xt,Pt,[],"cpu"])}else{let Ct=vn(xt),St=new Ct(mr);new Uint8Array(St.buffer,St.byteOffset,St.byteLength).set(U.HEAPU8.subarray(qt,qt+St.byteLength)),sr.push([xt,Pt,St,"cpu"])}}finally{U.stackRestore(mi),xt==="string"&&qt&&U._free(qt),Cn||U._OrtReleaseTensor(nr)}}K&&!xe&&(U._OrtClearBoundOutputs(K.handle)!==0&&Ie("Can't clear bound outputs."),Er.set(y,[ne,ie,ee,K,xe,!1]));for(let[He,nr]of await Promise.all(Bs))sr[He][2]=nr;return De("wasm ProcessOutputTensor"),sr}finally{U.webnnOnRunEnd?.(ne),U.stackRestore(Lt),Ce.forEach(bt=>U._OrtReleaseTensor(bt)),We.forEach(bt=>U._OrtReleaseTensor(bt)),_e.forEach(bt=>U._free(bt)),wt!==0&&U._OrtReleaseRunOptions(wt),qe.forEach(bt=>U._free(bt))}},Qr=y=>{let E=Ne(),A=Er.get(y);if(!A)throw new Error("invalid session id");let D=A[0],P=E._OrtEndProfiling(D);P===0&&Ie("Can't get an profile file name."),E._OrtFree(P)},Hn=y=>{let E=[];for(let A of y){let D=A[2];!Array.isArray(D)&&"buffer"in D&&E.push(D.buffer)}return E}}),hr,Me,xr,Xr,Nr,Yr,En,$n,pr,Cr,jn,Kn,Qn,As,Is,pi,Jr,Ms,Ps=b(()=>{Mt(),Rs(),Yt(),fn(),hr=()=>!!fe.wasm.proxy&&typeof document<"u",xr=!1,Xr=!1,Nr=!1,$n=new Map,pr=(y,E)=>{let A=$n.get(y);A?A.push(E):$n.set(y,[E])},Cr=()=>{if(xr||!Xr||Nr||!Me)throw new Error("worker not ready")},jn=y=>{switch(y.data.type){case"init-wasm":xr=!1,y.data.err?(Nr=!0,En[1](y.data.err)):(Xr=!0,En[0]()),Yr&&(URL.revokeObjectURL(Yr),Yr=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let E=$n.get(y.data.type);y.data.err?E.shift()[1](y.data.err):E.shift()[0](y.data.out);break}}},Kn=async()=>{if(!Xr){if(xr)throw new Error("multiple calls to 'initWasm()' detected.");if(Nr)throw new Error("previous call to 'initWasm()' failed.");if(xr=!0,hr())return new Promise((y,E)=>{Me?.terminate(),gs().then(([A,D])=>{try{Me=D,Me.onerror=G=>E(G),Me.onmessage=jn,En=[y,E];let P={type:"init-wasm",in:fe};if(!P.in.wasm.wasmPaths&&A){let G=dn();G&&(P.in.wasm.wasmPaths=G)}Me.postMessage(P),Yr=A}catch(P){E(P)}},E)});try{await yn(fe.wasm),await Fn(fe),Xr=!0}catch(y){throw Nr=!0,y}finally{xr=!1}}},Qn=async y=>{if(hr())return Cr(),new Promise((E,A)=>{pr("init-ep",[E,A]);let D={type:"init-ep",in:{epName:y,env:fe}};Me.postMessage(D)});await Vn(fe,y)},As=async y=>hr()?(Cr(),new Promise((E,A)=>{pr("copy-from",[E,A]);let D={type:"copy-from",in:{buffer:y}};Me.postMessage(D,[y.buffer])})):Je(y),Is=async(y,E)=>{if(hr()){if(E?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Cr(),new Promise((A,D)=>{pr("create",[A,D]);let P={type:"create",in:{model:y,options:{...E}}},G=[];y instanceof Uint8Array&&G.push(y.buffer),Me.postMessage(P,G)})}else return rr(y,E)},pi=async y=>{if(hr())return Cr(),new Promise((E,A)=>{pr("release",[E,A]);let D={type:"release",in:y};Me.postMessage(D)});Wn(y)},Jr=async(y,E,A,D,P,G)=>{if(hr()){if(A.some(U=>U[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(P.some(U=>U))throw new Error("pre-allocated output tensor is not supported for proxy.");return Cr(),new Promise((U,L)=>{pr("run",[U,L]);let V=A,ne={type:"run",in:{sessionId:y,inputIndices:E,inputs:V,outputIndices:D,options:G}};Me.postMessage(ne,Hn(V))})}else return j(y,E,A,D,P,G)},Ms=async y=>{if(hr())return Cr(),new Promise((E,A)=>{pr("end-profiling",[E,A]);let D={type:"end-profiling",in:y};Me.postMessage(D)});Qr(y)}}),Os,Xn,Yn,Jn=b(()=>{Mt(),Ps(),ze(),on(),Cs(),Os=(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()}`)}},Xn=y=>{switch(y[3]){case"cpu":return new gt(y[0],y[2],y[1]);case"gpu-buffer":{let E=y[0];if(!bn(E))throw new Error(`not supported data type: ${E} for deserializing GPU tensor`);let{gpuBuffer:A,download:D,dispose:P}=y[2];return gt.fromGpuBuffer(A,{dataType:E,dims:y[1],download:D,dispose:P})}case"ml-tensor":{let E=y[0];if(!Sn(E))throw new Error(`not supported data type: ${E} for deserializing MLTensor tensor`);let{mlTensor:A,download:D,dispose:P}=y[2];return gt.fromMLTensor(A,{dataType:E,dims:y[1],download:D,dispose:P})}default:throw new Error(`invalid data location: ${y[3]}`)}},Yn=class{async fetchModelAndCopyToWasmMemory(y){return As(await Tn(y))}async loadModel(y,E){mt();let A;typeof y=="string"?A=await this.fetchModelAndCopyToWasmMemory(y):A=y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Is(A,E),rt()}async dispose(){return pi(this.sessionId)}async run(y,E,A){mt();let D=[],P=[];Object.entries(y).forEach(ee=>{let K=ee[0],xe=ee[1],F=this.inputNames.indexOf(K);if(F===-1)throw new Error(`invalid input '${K}'`);D.push(xe),P.push(F)});let G=[],U=[];Object.entries(E).forEach(ee=>{let K=ee[0],xe=ee[1],F=this.outputNames.indexOf(K);if(F===-1)throw new Error(`invalid output '${K}'`);G.push(xe),U.push(F)});let L=D.map((ee,K)=>Os(ee,()=>`input "${this.inputNames[P[K]]}"`)),V=G.map((ee,K)=>ee?Os(ee,()=>`output "${this.outputNames[U[K]]}"`):null),ne=await Jr(this.sessionId,P,L,U,V,A),ie={};for(let ee=0;ee<ne.length;ee++)ie[this.outputNames[U[ee]]]=G[ee]??Xn(ne[ee]);return rt(),ie}startProfiling(){}endProfiling(){Ms(this.sessionId)}}}),xn={};N(xn,{OnnxruntimeWebAssemblyBackend:()=>es,initializeFlags:()=>Zn,wasmBackend:()=>ts});var Zn,es,ts,Ds=b(()=>{Mt(),Ps(),Jn(),Zn=()=>{(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))}},es=class{async init(y){Zn(),await Kn(),await Qn(y)}async createInferenceSessionHandler(y,E){let A=new Yn;return await A.loadModel(y,E),A}},ts=new es}),zs={};N(zs,{InferenceSession:()=>an,TRACE:()=>Fe,TRACE_EVENT_BEGIN:()=>ue,TRACE_EVENT_END:()=>De,TRACE_FUNC_BEGIN:()=>mt,TRACE_FUNC_END:()=>rt,Tensor:()=>gt,default:()=>ea,env:()=>fe,registerBackend:()=>te}),Mt(),Mt(),Mt();var fi="1.24.3",ea=ls;{let y=(Ds(),re(xn)).wasmBackend;te("cpu",y,10),te("wasm",y,10)}return Object.defineProperty(fe.versions,"web",{value:fi,enumerable:!0}),re(zs)})();d.exports=n})(fo)),fo.exports}var Gp;function Hy(){return Gp||(Gp=1,(function(d){var r=Wr&&Wr.__createBinding||(Object.create?(function(ce,le,he,pe){pe===void 0&&(pe=he);var Pe=Object.getOwnPropertyDescriptor(le,he);(!Pe||("get"in Pe?!le.__esModule:Pe.writable||Pe.configurable))&&(Pe={enumerable:!0,get:function(){return le[he]}}),Object.defineProperty(ce,pe,Pe)}):(function(ce,le,he,pe){pe===void 0&&(pe=he),ce[pe]=le[he]})),n=Wr&&Wr.__setModuleDefault||(Object.create?(function(ce,le){Object.defineProperty(ce,"default",{enumerable:!0,value:le})}):function(ce,le){ce.default=le}),a=Wr&&Wr.__importStar||function(ce){if(ce&&ce.__esModule)return ce;var le={};if(ce!=null)for(var he in ce)he!=="default"&&Object.prototype.hasOwnProperty.call(ce,he)&&r(le,ce,he);return n(le,ce),le};Object.defineProperty(d,"__esModule",{value:!0}),d.MicVAD=d.getDefaultRealTimeVADOptions=d.ort=d.DEFAULT_MODEL=void 0;const f=a(Wy()),v=Lo(),$=Bo(),R=ci(),b=Wi(),N=_f(),B=bf();d.DEFAULT_MODEL="legacy",d.ort=f;const re="vad.worklet.bundle.min.js",X="silero_vad_v5.onnx",Y="silero_vad_legacy.onnx",te=ce=>({...$.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:ce,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async le=>{le.getTracks().forEach(he=>{he.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:le=>{le.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});d.getDefaultRealTimeVADOptions=te;const H=ce=>"audioWorklet"in ce&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function ae(ce,le,he,pe,Pe){await he.audioWorklet.addModule(ce),le.processorOptions={...le.processorOptions??{},frameSamples:pe};const fe=new AudioWorkletNode(he,"vad-helper-worklet",le);return fe.port.onmessage=async st=>{const tt=st.data;if(!(typeof tt=="object"&&tt&&"message"in tt)){console.error("Invalid message event",tt);return}switch(tt.message){case b.Message.AudioFrame:{if(!("data"in tt&&tt.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const at=new Float32Array(tt.data);await Pe(at);break}}},fe}async function Te(ce,le,he){const pe=new B.Resampler({nativeSampleRate:ce.sampleRate,targetSampleRate:16e3,targetFrameSize:le});R.log.debug("using script processor");const fe=ce.createScriptProcessor(4096,1,1);let st=!1;return fe.onaudioprocess=async tt=>{if(!st){st=!0;try{const at=tt.inputBuffer.getChannelData(0);tt.outputBuffer.getChannelData(0).fill(0);const Re=pe.process(at);for(const Ye of Re)await he(Ye)}catch(at){console.error("Error processing audio:",at)}finally{st=!1}}},fe.connect(ce.destination),fe}class Ee{constructor(le,he,pe,Pe,fe=!1,st=null,tt=null,at=null,Tt=null,Re=null,Ye=null,_t="uninitialized",ot=!1){this.options=le,this.frameProcessor=he,this.model=pe,this.frameSamples=Pe,this.listening=fe,this.errored=st,this._stream=tt,this._audioContext=at,this._vadNode=Tt,this._mediaStreamAudioSourceNode=Re,this._audioProcessorAdapterType=Ye,this.initializationState=_t,this.ownsAudioContext=ot,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"?H(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await ae(this.options.baseAssetPath+re,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await Te(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:Le,vadNode:Ke}=this.getAudioInstances();this._stream=await this.options.resumeStream(je);const Ze=new MediaStreamAudioSourceNode(Le,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Ze,Ze.connect(Ke);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:Le}=this.getAudioInstances();await this.options.pauseStream(je),Le.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(le={}){const he={...(0,d.getDefaultRealTimeVADOptions)(le.model??d.DEFAULT_MODEL),...le};(0,$.validateOptions)(he),d.ort.env.wasm.wasmPaths=he.onnxWASMBasePath,he.ortConfig!==void 0&&he.ortConfig(d.ort);const pe=he.model==="v5"?X:Y,Pe=he.baseAssetPath+pe,fe=he.model==="v5"?N.SileroV5.new:N.SileroLegacy.new;let st;try{st=await fe(d.ort,()=>(0,v.defaultModelFetcher)(Pe))}catch(Ye){throw console.error(`Encountered an error while loading model file ${Pe}`),Ye}const tt=he.model==="v5"?512:1536,at=tt/16,Tt=new $.FrameProcessor(st.process,st.reset_state,{positiveSpeechThreshold:he.positiveSpeechThreshold,negativeSpeechThreshold:he.negativeSpeechThreshold,redemptionMs:he.redemptionMs,preSpeechPadMs:he.preSpeechPadMs,minSpeechMs:he.minSpeechMs,submitUserSpeechOnPause:he.submitUserSpeechOnPause},at),Re=new Ee(he,Tt,st,tt);if(he.startOnLoad)try{await Re.start()}catch(Ye){throw console.error("Error starting micVad",Ye),Ye}return Re}}d.MicVAD=Ee})(Wr)),Wr}var qp;function Wp(){return qp||(qp=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=yf();Object.defineProperty(d,"baseAssetPath",{enumerable:!0,get:function(){return r.baseAssetPath}});var n=Lo();Object.defineProperty(d,"defaultModelFetcher",{enumerable:!0,get:function(){return n.defaultModelFetcher}});var a=Bo();Object.defineProperty(d,"FrameProcessor",{enumerable:!0,get:function(){return a.FrameProcessor}});var f=Wi();Object.defineProperty(d,"Message",{enumerable:!0,get:function(){return f.Message}});var v=Gy();Object.defineProperty(d,"NonRealTimeVAD",{enumerable:!0,get:function(){return v.NonRealTimeVAD}});const $=qy();d.utils={audioFileToArray:$.audioFileToArray,minFramesForTargetMS:$.minFramesForTargetMS,arrayBufferToBase64:$.arrayBufferToBase64,encodeWAV:$.encodeWAV};var R=Hy();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}})})(co)),co}var Hp;function jy(){return Hp||(Hp=1,(function(d){Object.defineProperty(d,"__esModule",{value:!0}),d.useMicVAD=d.getDefaultReactRealTimeVADOptions=d.utils=void 0;const r=Wp(),n=me;var a=Wp();Object.defineProperty(d,"utils",{enumerable:!0,get:function(){return a.utils}});const f={userSpeakingThreshold:.6},v=b=>({...(0,r.getDefaultRealTimeVADOptions)(b),...f});d.getDefaultReactRealTimeVADOptions=v;function $(b){const N=b.model??r.DEFAULT_MODEL,B={...(0,d.getDefaultReactRealTimeVADOptions)(N),...b},re={userSpeakingThreshold:B.userSpeakingThreshold},X={positiveSpeechThreshold:B.positiveSpeechThreshold,negativeSpeechThreshold:B.negativeSpeechThreshold,redemptionMs:B.redemptionMs,preSpeechPadMs:B.preSpeechPadMs,minSpeechMs:B.minSpeechMs,submitUserSpeechOnPause:B.submitUserSpeechOnPause,onFrameProcessed:B.onFrameProcessed,onVADMisfire:B.onVADMisfire,onSpeechStart:B.onSpeechStart,onSpeechEnd:B.onSpeechEnd,onSpeechRealStart:B.onSpeechRealStart,baseAssetPath:B.baseAssetPath,onnxWASMBasePath:B.onnxWASMBasePath,model:B.model,workletOptions:B.workletOptions,getStream:B.getStream,pauseStream:B.pauseStream,resumeStream:B.resumeStream,startOnLoad:B.startOnLoad,processorType:B.processorType};return B.ortConfig&&(X.ortConfig=B.ortConfig),B.audioContext&&(X.audioContext=B.audioContext),[re,X]}function R(b){const[N,B]=$(b),re=b.model??r.DEFAULT_MODEL,[X,Y]=(0,n.useState)(!1),[te,H]=(0,n.useState)(!0),[ae,Te]=(0,n.useState)(!1),[Ee,ce]=(0,n.useState)(!1),[le,he]=(0,n.useState)(null),pe=(0,n.useRef)(B.onFrameProcessed),Pe=(0,n.useRef)(B.onSpeechEnd),fe=(0,n.useRef)(B.onSpeechStart),st=(0,n.useRef)(B.onSpeechRealStart),tt=(0,n.useRef)(B.onVADMisfire),at=(0,n.useRef)(B.getStream);(0,n.useEffect)(()=>{pe.current=B.onFrameProcessed,Pe.current=B.onSpeechEnd,fe.current=B.onSpeechStart,st.current=B.onSpeechRealStart,tt.current=B.onVADMisfire},[B.onFrameProcessed,B.onSpeechEnd,B.onSpeechStart,B.onSpeechRealStart,B.onVADMisfire]),(0,n.useEffect)(()=>{at.current=B.getStream},[B.getStream]);const Tt=B.getStream.toString();(0,n.useEffect)(()=>{let ot=null,je=!1;return(async()=>{try{H(!0),Te(!1);const Ke={...B,onFrameProcessed:(Ze,Z)=>{const Oe=Ze.isSpeech>N.userSpeakingThreshold;Y(Oe),pe.current(Ze,Z)},onSpeechEnd:Ze=>{Pe.current(Ze)},onSpeechStart:()=>{fe.current()},onSpeechRealStart:()=>{st.current()},onVADMisfire:()=>{tt.current()},getStream:()=>at.current()};if(ot=await r.MicVAD.new(Ke),je){await ot.destroy();return}he(ot),B.startOnLoad&&(await ot.start(),ce(!0)),H(!1)}catch(Ke){H(!1),Ke instanceof Error?Te(Ke.message):Te(String(Ke))}})().catch(()=>{}),function(){je=!0,ot&&ot.destroy(),!te&&!ae&&ce(!1)}},[Tt,re]);const Re=(0,n.useCallback)(async()=>{!te&&!ae&&(await le?.pause(),ce(!1))},[te,ae,le]),Ye=(0,n.useCallback)(async()=>{!te&&!ae&&(await le?.start(),ce(!0))},[te,ae,le]),_t=(0,n.useCallback)(async()=>{Ee?await Re():await Ye()},[Ee,Re,Ye]);return{listening:Ee,errored:ae,loading:te,userSpeaking:X,pause:Re,start:Ye,toggle:_t}}d.useMicVAD=R})(uo)),uo}var Ky=jy();gf();const jp={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},Ui=16e3,Tf=512,Ef=700,Qy=300,Xy=Tf/Ui*1e3,Yy=Math.ceil(Ef/Xy);function Jy(d={}){const{onAudioChunk:r,onAudioEnd:n,onSpeechStart:a,onSpeechEnd:f,onVADMisfire:v,onError:$,interruptOnSpeechStart:R=!0,forceAudioMp4:b=!1}=d,{sendAudioChunk:N,endAudioStream:B,interrupt:re}=Or(),[X,Y]=me.useState(!1),[te,H]=me.useState(null),ae=me.useRef(null),Te=me.useRef(null),Ee=me.useRef(null),ce=me.useRef(!1),le=me.useRef(null),he=me.useRef([]),pe=me.useCallback(()=>{if(!(typeof window>"u")){if(!Ee.current){const Le=window.AudioContext||window.webkitAudioContext;if(!Le)return;Ee.current=new Le({sampleRate:Ui})}Ee.current.state==="suspended"&&Ee.current.resume().catch(()=>{})}},[]);me.useEffect(()=>{typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||navigator.mediaDevices.getUserMedia({audio:jp}).then(Le=>{ae.current=Le,H(null)}).catch(Le=>{H("permission_denied"),$?.(Le)})},[$]);const Pe=me.useCallback(async()=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone APIs are unavailable in this browser");if(ae.current&&ae.current.getTracks()[0]?.readyState==="live")return ae.current;const Le=await navigator.mediaDevices.getUserMedia({audio:jp});return ae.current=Le,H(null),Le},[]),fe=me.useCallback(async Le=>{Le.getTracks().forEach(Ke=>{Ke.enabled=!1})},[]),st=me.useCallback(async()=>ae.current&&ae.current.getTracks()[0]?.readyState==="live"?(ae.current.getTracks().forEach(Le=>{Le.enabled=!0}),ae.current):Pe(),[Pe]),tt=me.useCallback(()=>{const Le=he.current;if(!Le.length)return{samples:new Float32Array(0),duration:0};const Ke=Le.reduce((Oe,et)=>Oe+et.length,0),Ze=new Float32Array(Ke);let Z=0;for(const Oe of Le)Ze.set(Oe,Z),Z+=Oe.length;return{samples:Ze,duration:Ke/Ui}},[]),at=me.useCallback(()=>{const Le=ae.current,Ke=Ee.current;if(!Le||!Ke||Te.current)return;const{samples:Ze,duration:Z}=tt();he.current=[];const Oe=!b&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/mp4")?"audio/mp4":"";try{const et=Ke.createMediaStreamDestination();if(Ze.length>0){const $t=Ke.createBuffer(1,Ze.length,Ui);$t.getChannelData(0).set(Ze);const dt=Ke.createBufferSource();dt.buffer=$t,dt.connect(et),dt.start(0)}const pt=Ke.createMediaStreamSource(Le);if(Z>0){const $t=Ke.createDelay(Z+.1);$t.delayTime.value=Z,pt.connect($t).connect(et)}else pt.connect(et);const Ft=new MediaRecorder(et.stream,Oe?{mimeType:Oe}:{});Ft.ondataavailable=async $t=>{if(!$t.data||$t.data.size<=0)return;const dt=await $t.data.arrayBuffer();r?r(dt):N(dt)},Te.current=Ft,Ft.start(100)}catch(et){$?.(et)}},[tt,b,r,$,N]),Tt=me.useCallback(()=>{const Le=Te.current;if(Le){if(Te.current=null,Le.state==="inactive"){n?n():B();return}Le.onstop=()=>{n?n():B()},Le.stop()}},[B,n]),Re=me.useCallback(()=>{const Le=Te.current;if(Le&&(Te.current=null,Le.state!=="inactive"))try{Le.stop()}catch{}},[]),Ye=me.useCallback(()=>{Ee.current&&(Ee.current.close().catch(()=>{}),Ee.current=null)},[]),_t=me.useCallback(()=>{ae.current&&(ae.current.getTracks().forEach(Le=>Le.stop()),ae.current=null)},[]),ot=Ky.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:Ef,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:Tf}},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:Le=>{Le.env.wasm.numThreads=1,Le.env.logLevel="error"},getStream:Pe,pauseStream:fe,resumeStream:st,onFrameProcessed:(Le,Ke)=>{if(!Ke)return;const Ze=he.current;Ze.push(new Float32Array(Ke)),Ze.length>Yy&&Ze.shift()},onSpeechStart:()=>{ce.current||(le.current&&(clearTimeout(le.current),le.current=null),Y(!0),R&&re(),at(),a?.())},onSpeechEnd:()=>{le.current=setTimeout(()=>{Y(!1),Tt(),ce.current=!0,setTimeout(()=>{ce.current=!1},300),f?.()},Qy)},onVADMisfire:()=>{le.current&&(clearTimeout(le.current),le.current=null),Y(!1),Re(),v?.()}}),je=me.useCallback(()=>{pe(),ot.listening&&Te.current&&(le.current&&(clearTimeout(le.current),le.current=null),Y(!1),Tt()),ot.toggle()},[Tt,pe,ot]);return me.useEffect(()=>()=>{le.current&&clearTimeout(le.current),Re(),Ye(),_t()},[Ye,_t,Re]),{isListening:ot.listening,isLoading:ot.loading,isSpeaking:X,micError:te,toggle:je,start:ot.start,pause:ot.pause,userSpeaking:ot.userSpeaking}}const Zy=()=>Or(),$f=()=>{const{connectionState:d,isConnected:r,isSessionReady:n,error:a,reconnectAttempt:f,session:v,creditExhausted:$,creditError:R,sessionState:b,isSessionTerminated:N,isSessionTerminating:B,isAgentThinking:re,isAgentSpeaking:X,isToolExecuting:Y,initializeSession:te,joinDesktopSession:H,disconnect:ae,terminateSession:Te,interrupt:Ee,clearSessionHistory:ce,changeSessionLanguage:le}=Or();return{connectionState:d,isConnected:r,isSessionReady:n,error:a,reconnectAttempt:f,session:v,creditExhausted:$,creditError:R,sessionState:b,isSessionTerminated:N,isSessionTerminating:B,isAgentThinking:re,isAgentSpeaking:X,isToolExecuting:Y,initializeSession:te,joinDesktopSession:H,disconnect:ae,terminateSession:Te,interrupt:Ee,clearSessionHistory:ce,changeSessionLanguage:le}},ew=()=>{const{sessionState:d,isSessionTerminated:r,isSessionTerminating:n,isAgentThinking:a,isAgentSpeaking:f,isToolExecuting:v}=Or();return{sessionState:d,isSessionTerminated:r,isSessionTerminating:n,isAgentThinking:a,isAgentSpeaking:f,isToolExecuting:v}},tw=()=>{const{messages:d,sendTextMessage:r,clearMessages:n}=Or();return{messages:d,sendTextMessage:r,clearMessages:n}},rw=()=>{const{sendAudioChunk:d,endAudioStream:r,isAudioPlaying:n,transcript:a,partialTranscript:f,interrupt:v,resumeAudioPlayback:$,attachAudioElement:R}=Or();return{sendAudioChunk:d,endAudioStream:r,isAudioPlaying:n,transcript:a,partialTranscript:f,interrupt:v,resumeAudioPlayback:$,attachAudioElement:R}},xf=()=>{const{session:d,isAvatarSpeaking:r,cloudStream:n,setCloudStreamState:a}=Or(),f=n?.state||tr.IDLE;return{streamingUrl:d.streamingUrl,isAvatarSpeaking:r,speakingSource:"avatar_events",isCloudAvatar:d.agentType===Hr.CLOUD_AVATAR,isDesktopAvatar:d.agentType===Hr.DESKTOP_AVATAR,cloudStreamState:f,cloudStreamError:n?.error||null,isCloudStreamConnected:f===tr.CONNECTED,isCloudStreamLoading:f===tr.CONNECTING||f===tr.LOADING,setCloudStreamState:a}},nw=d=>{const{attachAudioElement:r,resumeAudioPlayback:n}=Or();me.useEffect(()=>{if(!d?.current)return;r(d.current);const a=()=>{n()},f=d.current;return f.addEventListener("click",a),f.addEventListener("touchstart",a),()=>{f.removeEventListener("click",a),f.removeEventListener("touchstart",a),r(null)}},[r,d,n])};function sw({connect:d=!0,session:r,onError:n,onInitialized:a,children:f}){const{initializeSession:v,joinDesktopSession:$,disconnect:R}=$f(),b=me.useRef(!1);return me.useEffect(()=>{if(!d||b.current)return;let N=!1;return b.current=!0,(async()=>{try{if(r?.mode==="join_desktop"){const X=await $({uniqueId:r.uniqueId});N||a?.(X);return}const re=await v({apiKey:r?.apiKey,publicChatId:r?.publicChatId,agentId:r?.agentId,language:r?.language||"en"});N||a?.(re)}catch(re){N||n?.(re)}})(),()=>{N=!0,R(),b.current=!1}},[d,R,v,$,n,a,r]),f}function iw({children:d,wsUrl:r,restUrl:n,session:a,connect:f=!0,reconnectOptions:v,enableAudio:$=!0,pcmOptions:R,debug:b=!1,onError:N,onInitialized:B}){return or.jsx(mf,{wsUrl:r,restUrl:n,reconnectOptions:v,enableAudio:$,pcmOptions:R,debug:b,children:or.jsx(sw,{connect:f,session:a,onError:N,onInitialized:B,children:d})})}var mo={exports:{}},Kp;function aw(){return Kp||(Kp=1,(function(d){const r={};r.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},r.localCName=r.generateIdentifier(),r.splitLines=function(n){return n.trim().split(`
|
|
2859
|
+
`).map(a=>a.trim())},r.splitSections=function(n){return n.split(`
|
|
2860
|
+
m=`).map((f,v)=>(v>0?"m="+f:f).trim()+`\r
|
|
2861
|
+
`)},r.getDescription=function(n){const a=r.splitSections(n);return a&&a[0]},r.getMediaSections=function(n){const a=r.splitSections(n);return a.shift(),a},r.matchPrefix=function(n,a){return r.splitLines(n).filter(f=>f.indexOf(a)===0)},r.parseCandidate=function(n){let a;n.indexOf("a=candidate:")===0?a=n.substring(12).split(" "):a=n.substring(10).split(" ");const f={foundation:a[0],component:{1:"rtp",2:"rtcp"}[a[1]]||a[1],protocol:a[2].toLowerCase(),priority:parseInt(a[3],10),ip:a[4],address:a[4],port:parseInt(a[5],10),type:a[7]};for(let v=8;v<a.length;v+=2)switch(a[v]){case"raddr":f.relatedAddress=a[v+1];break;case"rport":f.relatedPort=parseInt(a[v+1],10);break;case"tcptype":f.tcpType=a[v+1];break;case"ufrag":f.ufrag=a[v+1],f.usernameFragment=a[v+1];break;default:f[a[v]]===void 0&&(f[a[v]]=a[v+1]);break}return f},r.writeCandidate=function(n){const a=[];a.push(n.foundation);const f=n.component;f==="rtp"?a.push(1):f==="rtcp"?a.push(2):a.push(f),a.push(n.protocol.toUpperCase()),a.push(n.priority),a.push(n.address||n.ip),a.push(n.port);const v=n.type;return a.push("typ"),a.push(v),v!=="host"&&n.relatedAddress&&n.relatedPort&&(a.push("raddr"),a.push(n.relatedAddress),a.push("rport"),a.push(n.relatedPort)),n.tcpType&&n.protocol.toLowerCase()==="tcp"&&(a.push("tcptype"),a.push(n.tcpType)),(n.usernameFragment||n.ufrag)&&(a.push("ufrag"),a.push(n.usernameFragment||n.ufrag)),"candidate:"+a.join(" ")},r.parseIceOptions=function(n){return n.substring(14).split(" ")},r.parseRtpMap=function(n){let a=n.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(n){let a=n.payloadType;n.preferredPayloadType!==void 0&&(a=n.preferredPayloadType);const f=n.channels||n.numChannels||1;return"a=rtpmap:"+a+" "+n.name+"/"+n.clockRate+(f!==1?"/"+f:"")+`\r
|
|
2862
|
+
`},r.parseExtmap=function(n){const a=n.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(n){return"a=extmap:"+(n.id||n.preferredId)+(n.direction&&n.direction!=="sendrecv"?"/"+n.direction:"")+" "+n.uri+(n.attributes?" "+n.attributes:"")+`\r
|
|
2863
|
+
`},r.parseFmtp=function(n){const a={};let f;const v=n.substring(n.indexOf(" ")+1).split(";");for(let $=0;$<v.length;$++)f=v[$].trim().split("="),a[f[0].trim()]=f[1];return a},r.writeFmtp=function(n){let a="",f=n.payloadType;if(n.preferredPayloadType!==void 0&&(f=n.preferredPayloadType),n.parameters&&Object.keys(n.parameters).length){const v=[];Object.keys(n.parameters).forEach($=>{n.parameters[$]!==void 0?v.push($+"="+n.parameters[$]):v.push($)}),a+="a=fmtp:"+f+" "+v.join(";")+`\r
|
|
2864
|
+
`}return a},r.parseRtcpFb=function(n){const a=n.substring(n.indexOf(" ")+1).split(" ");return{type:a.shift(),parameter:a.join(" ")}},r.writeRtcpFb=function(n){let a="",f=n.payloadType;return n.preferredPayloadType!==void 0&&(f=n.preferredPayloadType),n.rtcpFeedback&&n.rtcpFeedback.length&&n.rtcpFeedback.forEach(v=>{a+="a=rtcp-fb:"+f+" "+v.type+(v.parameter&&v.parameter.length?" "+v.parameter:"")+`\r
|
|
2865
|
+
`}),a},r.parseSsrcMedia=function(n){const a=n.indexOf(" "),f={ssrc:parseInt(n.substring(7,a),10)},v=n.indexOf(":",a);return v>-1?(f.attribute=n.substring(a+1,v),f.value=n.substring(v+1)):f.attribute=n.substring(a+1),f},r.parseSsrcGroup=function(n){const a=n.substring(13).split(" ");return{semantics:a.shift(),ssrcs:a.map(f=>parseInt(f,10))}},r.getMid=function(n){const a=r.matchPrefix(n,"a=mid:")[0];if(a)return a.substring(6)},r.parseFingerprint=function(n){const a=n.substring(14).split(" ");return{algorithm:a[0].toLowerCase(),value:a[1].toUpperCase()}},r.getDtlsParameters=function(n,a){return{role:"auto",fingerprints:r.matchPrefix(n+a,"a=fingerprint:").map(r.parseFingerprint)}},r.writeDtlsParameters=function(n,a){let f="a=setup:"+a+`\r
|
|
2866
|
+
`;return n.fingerprints.forEach(v=>{f+="a=fingerprint:"+v.algorithm+" "+v.value+`\r
|
|
2867
|
+
`}),f},r.parseCryptoLine=function(n){const a=n.substring(9).split(" ");return{tag:parseInt(a[0],10),cryptoSuite:a[1],keyParams:a[2],sessionParams:a.slice(3)}},r.writeCryptoLine=function(n){return"a=crypto:"+n.tag+" "+n.cryptoSuite+" "+(typeof n.keyParams=="object"?r.writeCryptoKeyParams(n.keyParams):n.keyParams)+(n.sessionParams?" "+n.sessionParams.join(" "):"")+`\r
|
|
2868
|
+
`},r.parseCryptoKeyParams=function(n){if(n.indexOf("inline:")!==0)return null;const a=n.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(n){return n.keyMethod+":"+n.keySalt+(n.lifeTime?"|"+n.lifeTime:"")+(n.mkiValue&&n.mkiLength?"|"+n.mkiValue+":"+n.mkiLength:"")},r.getCryptoParameters=function(n,a){return r.matchPrefix(n+a,"a=crypto:").map(r.parseCryptoLine)},r.getIceParameters=function(n,a){const f=r.matchPrefix(n+a,"a=ice-ufrag:")[0],v=r.matchPrefix(n+a,"a=ice-pwd:")[0];return f&&v?{usernameFragment:f.substring(12),password:v.substring(10)}:null},r.writeIceParameters=function(n){let a="a=ice-ufrag:"+n.usernameFragment+`\r
|
|
2869
|
+
a=ice-pwd:`+n.password+`\r
|
|
2870
|
+
`;return n.iceLite&&(a+=`a=ice-lite\r
|
|
2871
|
+
`),a},r.parseRtpParameters=function(n){const a={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},v=r.splitLines(n)[0].split(" ");a.profile=v[2];for(let R=3;R<v.length;R++){const b=v[R],N=r.matchPrefix(n,"a=rtpmap:"+b+" ")[0];if(N){const B=r.parseRtpMap(N),re=r.matchPrefix(n,"a=fmtp:"+b+" ");switch(B.parameters=re.length?r.parseFmtp(re[0]):{},B.rtcpFeedback=r.matchPrefix(n,"a=rtcp-fb:"+b+" ").map(r.parseRtcpFb),a.codecs.push(B),B.name.toUpperCase()){case"RED":case"ULPFEC":a.fecMechanisms.push(B.name.toUpperCase());break}}}r.matchPrefix(n,"a=extmap:").forEach(R=>{a.headerExtensions.push(r.parseExtmap(R))});const $=r.matchPrefix(n,"a=rtcp-fb:* ").map(r.parseRtcpFb);return a.codecs.forEach(R=>{$.forEach(b=>{R.rtcpFeedback.find(B=>B.type===b.type&&B.parameter===b.parameter)||R.rtcpFeedback.push(b)})}),a},r.writeRtpDescription=function(n,a){let f="";f+="m="+n+" ",f+=a.codecs.length>0?"9":"0",f+=" "+(a.profile||"UDP/TLS/RTP/SAVPF")+" ",f+=a.codecs.map($=>$.preferredPayloadType!==void 0?$.preferredPayloadType:$.payloadType).join(" ")+`\r
|
|
2872
|
+
`,f+=`c=IN IP4 0.0.0.0\r
|
|
2873
|
+
`,f+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
2874
|
+
`,a.codecs.forEach($=>{f+=r.writeRtpMap($),f+=r.writeFmtp($),f+=r.writeRtcpFb($)});let v=0;return a.codecs.forEach($=>{$.maxptime>v&&(v=$.maxptime)}),v>0&&(f+="a=maxptime:"+v+`\r
|
|
2875
|
+
`),a.headerExtensions&&a.headerExtensions.forEach($=>{f+=r.writeExtmap($)}),f},r.parseRtpEncodingParameters=function(n){const a=[],f=r.parseRtpParameters(n),v=f.fecMechanisms.indexOf("RED")!==-1,$=f.fecMechanisms.indexOf("ULPFEC")!==-1,R=r.matchPrefix(n,"a=ssrc:").map(X=>r.parseSsrcMedia(X)).filter(X=>X.attribute==="cname"),b=R.length>0&&R[0].ssrc;let N;const B=r.matchPrefix(n,"a=ssrc-group:FID").map(X=>X.substring(17).split(" ").map(te=>parseInt(te,10)));B.length>0&&B[0].length>1&&B[0][0]===b&&(N=B[0][1]),f.codecs.forEach(X=>{if(X.name.toUpperCase()==="RTX"&&X.parameters.apt){let Y={ssrc:b,codecPayloadType:parseInt(X.parameters.apt,10)};b&&N&&(Y.rtx={ssrc:N}),a.push(Y),v&&(Y=JSON.parse(JSON.stringify(Y)),Y.fec={ssrc:b,mechanism:$?"red+ulpfec":"red"},a.push(Y))}}),a.length===0&&b&&a.push({ssrc:b});let re=r.matchPrefix(n,"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(X=>{X.maxBitrate=re})),a},r.parseRtcpParameters=function(n){const a={},f=r.matchPrefix(n,"a=ssrc:").map(R=>r.parseSsrcMedia(R)).filter(R=>R.attribute==="cname")[0];f&&(a.cname=f.value,a.ssrc=f.ssrc);const v=r.matchPrefix(n,"a=rtcp-rsize");a.reducedSize=v.length>0,a.compound=v.length===0;const $=r.matchPrefix(n,"a=rtcp-mux");return a.mux=$.length>0,a},r.writeRtcpParameters=function(n){let a="";return n.reducedSize&&(a+=`a=rtcp-rsize\r
|
|
2876
|
+
`),n.mux&&(a+=`a=rtcp-mux\r
|
|
2877
|
+
`),n.ssrc!==void 0&&n.cname&&(a+="a=ssrc:"+n.ssrc+" cname:"+n.cname+`\r
|
|
2878
|
+
`),a},r.parseMsid=function(n){let a;const f=r.matchPrefix(n,"a=msid:");if(f.length===1)return a=f[0].substring(7).split(" "),{stream:a[0],track:a[1]};const v=r.matchPrefix(n,"a=ssrc:").map($=>r.parseSsrcMedia($)).filter($=>$.attribute==="msid");if(v.length>0)return a=v[0].value.split(" "),{stream:a[0],track:a[1]}},r.parseSctpDescription=function(n){const a=r.parseMLine(n),f=r.matchPrefix(n,"a=max-message-size:");let v;f.length>0&&(v=parseInt(f[0].substring(19),10)),isNaN(v)&&(v=65536);const $=r.matchPrefix(n,"a=sctp-port:");if($.length>0)return{port:parseInt($[0].substring(12),10),protocol:a.fmt,maxMessageSize:v};const R=r.matchPrefix(n,"a=sctpmap:");if(R.length>0){const b=R[0].substring(10).split(" ");return{port:parseInt(b[0],10),protocol:b[1],maxMessageSize:v}}},r.writeSctpDescription=function(n,a){let f=[];return n.protocol!=="DTLS/SCTP"?f=["m="+n.kind+" 9 "+n.protocol+" "+a.protocol+`\r
|
|
2879
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
2880
|
+
`,"a=sctp-port:"+a.port+`\r
|
|
2881
|
+
`]:f=["m="+n.kind+" 9 "+n.protocol+" "+a.port+`\r
|
|
2882
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
2883
|
+
`,"a=sctpmap:"+a.port+" "+a.protocol+` 65535\r
|
|
2884
|
+
`],a.maxMessageSize!==void 0&&f.push("a=max-message-size:"+a.maxMessageSize+`\r
|
|
2885
|
+
`),f.join("")},r.generateSessionId=function(){return Math.random().toString().substr(2,22)},r.writeSessionBoilerplate=function(n,a,f){let v;const $=a!==void 0?a:2;return n?v=n:v=r.generateSessionId(),`v=0\r
|
|
2886
|
+
o=`+(f||"thisisadapterortc")+" "+v+" "+$+` IN IP4 127.0.0.1\r
|
|
2887
|
+
s=-\r
|
|
2888
|
+
t=0 0\r
|
|
2889
|
+
`},r.getDirection=function(n,a){const f=r.splitLines(n);for(let v=0;v<f.length;v++)switch(f[v]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return f[v].substring(2)}return a?r.getDirection(a):"sendrecv"},r.getKind=function(n){return r.splitLines(n)[0].split(" ")[0].substring(2)},r.isRejected=function(n){return n.split(" ",2)[1]==="0"},r.parseMLine=function(n){const f=r.splitLines(n)[0].substring(2).split(" ");return{kind:f[0],port:parseInt(f[1],10),protocol:f[2],fmt:f.slice(3).join(" ")}},r.parseOLine=function(n){const f=r.matchPrefix(n,"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(n){if(typeof n!="string"||n.length===0)return!1;const a=r.splitLines(n);for(let f=0;f<a.length;f++)if(a[f].length<2||a[f].charAt(1)!=="=")return!1;return!0},d.exports=r})(mo)),mo.exports}var Qp=aw(),Tr,At,Fi={d:(d,r)=>{for(var n in r)Fi.o(r,n)&&!Fi.o(d,n)&&Object.defineProperty(d,n,{enumerable:!0,get:r[n]})},o:(d,r)=>Object.prototype.hasOwnProperty.call(d,r)},be={};Fi.d(be,{Dz:()=>um,g$:()=>Mf,Lt:()=>Af,Q9:()=>If,qf:()=>ko,hV:()=>fm,z$:()=>Zw,J0:()=>Ao,De:()=>xw,$C:()=>Nn,al:()=>Ff,_W:()=>Vf,Gv:()=>rm,m:()=>nm,tz:()=>Uf,Nu:()=>hm,zg:()=>ym,vp:()=>lm,vU:()=>Q,wF:()=>Yf,rv:()=>dm,Nh:()=>cm,ss:()=>gm,qW:()=>sm,QL:()=>tm,cf:()=>vm,eM:()=>Xf,Yd:()=>T,Tk:()=>$e,iM:()=>Cf,qy:()=>Kr,ce:()=>gw,sK:()=>ye,Ok:()=>vt,q5:()=>pm,g:()=>Jw,xl:()=>Kf,I:()=>Qf,bx:()=>Ro,dD:()=>am,Ib:()=>hi,Az:()=>Rt,Iw:()=>Ir,qY:()=>Co,db:()=>Rf,mR:()=>ui,Tn:()=>xo,rV:()=>Jf,gh:()=>qf,Mi:()=>Wf,j:()=>Hf,YB:()=>jf,Yt:()=>em,i5:()=>Zf,x_:()=>jr,Am:()=>Io,eR:()=>Pf,r8:()=>Gf,u3:()=>wm,vd:()=>Df,iV:()=>Lf,jZ:()=>zf,SW:()=>Nf,ZH:()=>Bf,Ni:()=>_m,lh:()=>Of,ZP:()=>om,bq:()=>kf,$f:()=>bm,eu:()=>im,Ax:()=>bw,Mc:()=>_w});class T{static GetStackTrace(){const r=new Error;let n="No Stack Available for this browser";return r.stack&&(n=r.stack.toString().replace(/Error/g,"")),n}static SetLoggerVerbosity(r){this.verboseLogLevel!=null&&(this.verboseLogLevel=r)}static Log(r,n,a){if(a>this.verboseLogLevel)return;const f=`Level: Log
|
|
2890
|
+
Msg: ${n}
|
|
2891
|
+
Caller: ${r}`;console.log(f)}static Info(r,n,a){if(a>this.verboseLogLevel)return;const f=`Level: Info
|
|
2892
|
+
Msg: ${n}`;console.info(f)}static Error(r,n){const a=`Level: Error
|
|
2893
|
+
Msg: ${n}
|
|
2894
|
+
Caller: ${r}`;console.error(a)}static Warning(r,n){const a=`Level: Warning
|
|
2895
|
+
Caller: ${r}
|
|
2896
|
+
Msg: ${n}`;console.warn(a)}}T.verboseLogLevel=5,(function(d){d.LIST_STREAMERS="listStreamers",d.SUBSCRIBE="subscribe",d.UNSUBSCRIBE="unsubscribe",d.ICE_CANDIDATE="iceCandidate",d.OFFER="offer",d.ANSWER="answer",d.DATACHANNELREQUEST="dataChannelRequest",d.SFURECVDATACHANNELREADY="peerDataChannelsReady",d.PONG="pong"})(Tr||(Tr={}));class Kr{sendFilter(r,n){return n}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2897
|
+
`+JSON.stringify(this,this.sendFilter,4),6),JSON.stringify(this,this.sendFilter)}}class ow extends Kr{constructor(){super(),this.type=Tr.LIST_STREAMERS}}class lw extends Kr{constructor(r){super(),this.type=Tr.SUBSCRIBE,this.streamerId=r}}class uw extends Kr{constructor(){super(),this.type=Tr.UNSUBSCRIBE}}class dw extends Kr{constructor(r){super(),this.type=Tr.PONG,this.time=r}}class cw extends Kr{constructor(r,n){super(),this.type=Tr.OFFER,this.minBitrate=0,this.maxBitrate=0,r&&(this.type=r.type,this.sdp=r.sdp,this.minBitrate=n.minBitrateBps,this.maxBitrate=n.maxBitrateBps)}sendFilter(r,n){if(r!="minBitrate"&&r!="maxBitrate"||!(n<=0))return n}}class hw extends Kr{constructor(r,n){super(),this.type=Tr.ANSWER,this.minBitrate=0,this.maxBitrate=0,r&&(this.type=r.type,this.sdp=r.sdp,this.minBitrate=n.minBitrateBps,this.maxBitrate=n.maxBitrateBps)}sendFilter(r,n){if(r!="minBitrate"&&r!="maxBitrate"||!(n<=0))return n}}class pw extends Kr{constructor(){super(),this.type=Tr.DATACHANNELREQUEST}}class fw extends Kr{constructor(){super(),this.type=Tr.SFURECVDATACHANNELREADY}}class mw{constructor(r){this.type=Tr.ICE_CANDIDATE,this.candidate=r}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2898
|
+
`+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"})(At||(At={}));class Cf{}class gw extends Cf{}class xo{constructor(){this.FromUEMessageHandlers=new Map}addMessageHandler(r,n){this.FromUEMessageHandlers.set(r,n)}handleMessage(r,n){this.FromUEMessageHandlers.has(r)?this.FromUEMessageHandlers.get(r)(n):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(At.PING,(n=>{const a=new dw(new Date().getTime()).payload();T.Log(T.GetStackTrace(),At.PING+": "+n,6),r.webSocket.send(a)})),r.signallingProtocol.addMessageHandler(At.CONFIG,(n=>{T.Log(T.GetStackTrace(),At.CONFIG,6);const a=JSON.parse(n);r.onConfig(a)})),r.signallingProtocol.addMessageHandler(At.STREAMER_LIST,(n=>{T.Log(T.GetStackTrace(),At.STREAMER_LIST,6);const a=JSON.parse(n);r.onStreamerList(a)})),r.signallingProtocol.addMessageHandler(At.STREAMER_ID_CHANGED,(n=>{T.Log(T.GetStackTrace(),At.STREAMER_ID_CHANGED,6);const a=JSON.parse(n);r.onStreamerIDChanged(a)})),r.signallingProtocol.addMessageHandler(At.PLAYER_COUNT,(n=>{T.Log(T.GetStackTrace(),At.PLAYER_COUNT,6);const a=JSON.parse(n);T.Log(T.GetStackTrace(),"Player Count: "+a.count,6),r.onPlayerCount(a)})),r.signallingProtocol.addMessageHandler(At.ANSWER,(n=>{T.Log(T.GetStackTrace(),At.ANSWER,6);const a=JSON.parse(n);r.onWebRtcAnswer(a)})),r.signallingProtocol.addMessageHandler(At.OFFER,(n=>{T.Log(T.GetStackTrace(),At.OFFER,6);const a=JSON.parse(n);r.onWebRtcOffer(a)})),r.signallingProtocol.addMessageHandler(At.ICE_CANDIDATE,(n=>{T.Log(T.GetStackTrace(),At.ICE_CANDIDATE,6);const a=JSON.parse(n);r.onIceCandidate(a.candidate)})),r.signallingProtocol.addMessageHandler(At.WARNING,(n=>{T.Warning(T.GetStackTrace(),`Warning received: ${n}`)})),r.signallingProtocol.addMessageHandler(At.PEER_DATA_CHANNELS,(n=>{T.Log(T.GetStackTrace(),At.PEER_DATA_CHANNELS,6);const a=JSON.parse(n);r.onWebRtcPeerDataChannels(a)}))}}class kf{constructor(){this.WS_OPEN_STATE=1,this.onOpen=new EventTarget,this.onClose=new EventTarget,this.signallingProtocol=new xo,xo.setupDefaultHandlers(this)}connect(r){T.Log(T.GetStackTrace(),r,6);try{return this.webSocket=new WebSocket(r),this.webSocket.onopen=n=>this.handleOnOpen(n),this.webSocket.onerror=()=>this.handleOnError(),this.webSocket.onclose=n=>this.handleOnClose(n),this.webSocket.onmessage=n=>this.handleOnMessage(n),this.webSocket.onmessagebinary=n=>this.handleOnMessageBinary(n),!0}catch(n){return T.Error(n,n),!1}}handleOnMessageBinary(r){r&&r.data&&r.data.text().then((n=>{const a=new MessageEvent("messageFromBinary",{data:n});this.handleOnMessage(a)})).catch((n=>{T.Error(T.GetStackTrace(),`Failed to parse binary blob from websocket, reason: ${n}`)}))}handleOnMessage(r){if(r.data&&r.data instanceof Blob)return void this.handleOnMessageBinary(r);const n=JSON.parse(r.data);T.Log(T.GetStackTrace(),`received =>
|
|
2899
|
+
`+JSON.stringify(JSON.parse(r.data),void 0,4),6),this.signallingProtocol.handleMessage(n.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 ow;this.webSocket.send(r.payload())}sendSubscribe(r){const n=new lw(r);this.webSocket.send(n.payload())}sendUnsubscribe(){const r=new uw;this.webSocket.send(r.payload())}sendWebRtcOffer(r,n){const a=new cw(r,n);this.webSocket.send(a.payload())}sendWebRtcAnswer(r,n){const a=new hw(r,n);this.webSocket.send(a.payload())}sendWebRtcDatachannelRequest(){const r=new pw;this.webSocket.send(r.payload())}sendSFURecvDataChannelReady(){const r=new fw;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 n=new mw(r);this.webSocket.send(n.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 yw{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 n=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"&&n.srcObject!==r.streams[0]?(n.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 n=this.videoElementProvider.getVideoElement();n.srcObject!=r&&n.srcObject&&n.srcObject!==r&&(this.audioElement.srcObject=r,T.Log(T.GetStackTrace(),"Created new audio element to play separate audio stream."))}}class ww{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 n=btoa(r.reduce(((a,f)=>a+String.fromCharCode(f)),""));this.imageElement.src="data:image/jpeg;base64,"+n}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(this.freezeFrameWidth!==0&&this.freezeFrameHeight!==0){let r=0,n=0,a=0,f=0;const v=this.rootDiv.clientWidth/this.rootDiv.clientHeight,$=this.freezeFrameWidth/this.freezeFrameHeight;v<$?(r=this.rootDiv.clientWidth,n=Math.floor(this.rootDiv.clientWidth/$),a=Math.floor(.5*(this.rootDiv.clientHeight-n)),f=0):(r=Math.floor(this.rootDiv.clientHeight*$),n=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=n+"px",this.imageElement.style.left=f+"px",this.imageElement.style.top=a+"px"}}}class vw{constructor(r){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new ww(r)}showFreezeFrame(){this.valid&&this.freezeFrame.setElementForShow()}hideFreezeFrame(){this.valid=!1,this.freezeFrame.setElementForHide()}updateFreezeFrameAndShow(r,n){this.freezeFrame.updateImageElementSource(r),this.freezeFrame.imageElement.onload=()=>{this.freezeFrame.setDimensionsFromElementAndResize(),n()}}processFreezeFrameMessage(r,n){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,n)):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,n,a,f,v=(()=>{})){this.onChange=v,this.onChangeEmit=()=>{},this.id=r,this.description=a,this.label=n,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 Rt extends hi{constructor(r,n,a,f,v,$=(()=>{})){super(r,n,a,f,$);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const b=this.getUrlParamFlag();this.flag=b}else this.flag=f;this.useUrlParams=v}getUrlParamFlag(){const r=new URLSearchParams(window.location.search);return!!r.has(this.id)&&r.get(this.id)!=="false"&&r.get(this.id)!=="False"}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);this.flag===!0?r.set(this.id,"true"):r.set(this.id,"false"),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}enable(){this.flag=!0}get flag(){return!!this.value}set flag(r){this.value=r}}class Ir extends hi{constructor(r,n,a,f,v,$,R,b=(()=>{})){super(r,n,a,$,b),this._min=f,this._max=v;const N=new URLSearchParams(window.location.search);if(R&&N.has(this.id)){const B=Number.parseFloat(N.get(this.id));this.number=Number.isNaN(B)?$:B}else this.number=$;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 Rf extends hi{constructor(r,n,a,f,v,$=(()=>{})){super(r,n,a,f,$);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const b=this.getUrlParamText();this.text=b}else this.text=f;this.useUrlParams=v}getUrlParamText(){var r;const n=new URLSearchParams(window.location.search);return n.has(this.id)&&(r=n.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 Co extends hi{constructor(r,n,a,f,v,$,R=(()=>{})){super(r,n,a,f,R),this.options=v;const b=new URLSearchParams(window.location.search),N=$&&b.has(this.id)?this.getUrlParamText():f;this.selected=N,this.useUrlParams=$}getUrlParamText(){var r;const n=new URLSearchParams(window.location.search);return n.has(this.id)&&(r=n.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 n=this.options.filter((a=>a.indexOf(r)!==-1));n.length?this.value=n[0]:(n=this.options.filter((a=>a.indexOf(r.split(" ")[0])!==-1)),n.length&&(this.value=n[0]))}}class Af extends Event{constructor(r){super("afkWarningActivate"),this.data=r}}class ko extends Event{constructor(r){super("afkWarningUpdate"),this.data=r}}class If extends Event{constructor(){super("afkWarningDeactivate")}}class Mf extends Event{constructor(){super("afkTimedOut")}}class Pf extends Event{constructor(r){super("videoEncoderAvgQP"),this.data=r}}class Of extends Event{constructor(){super("webRtcSdp")}}class Df extends Event{constructor(){super("webRtcAutoConnect")}}class zf extends Event{constructor(){super("webRtcConnecting")}}class Lf extends Event{constructor(){super("webRtcConnected")}}class Bf extends Event{constructor(){super("webRtcFailed")}}class Nf extends Event{constructor(r){super("webRtcDisconnected"),this.data=r}}class Uf extends Event{constructor(r){super("dataChannelOpen"),this.data=r}}class Ff extends Event{constructor(r){super("dataChannelClose"),this.data=r}}class Vf extends Event{constructor(r){super("dataChannelError"),this.data=r}}class Gf extends Event{constructor(){super("videoInitialized")}}class qf extends Event{constructor(){super("streamLoading")}}class Wf extends Event{constructor(){super("streamConnect")}}class Hf extends Event{constructor(){super("streamDisconnect")}}class jf extends Event{constructor(){super("streamReconnect")}}class Kf extends Event{constructor(r){super("playStreamError"),this.data=r}}class Qf extends Event{constructor(){super("playStream")}}class Ro extends Event{constructor(r){super("playStreamRejected"),this.data=r}}class Xf extends Event{constructor(r){super("loadFreezeFrame"),this.data=r}}class Yf extends Event{constructor(){super("hideFreezeFrame")}}class Jf extends Event{constructor(r){super("statsReceived"),this.data=r}}class Zf extends Event{constructor(r){super("streamerListMessage"),this.data=r}}class em extends Event{constructor(r){super("StreamerIDChangedMessage"),this.data=r}}class tm extends Event{constructor(r){super("latencyTestResult"),this.data=r}}class rm extends Event{constructor(r){super("dataChannelLatencyTestResponse"),this.data=r}}class nm extends Event{constructor(r){super("dataChannelLatencyTestResult"),this.data=r}}class sm extends Event{constructor(r){super("initialSettings"),this.data=r}}class ui extends Event{constructor(r){super("settingsChanged"),this.data=r}}class _w extends Event{constructor(){super("xrSessionStarted")}}class bw extends Event{constructor(){super("xrSessionEnded")}}class im extends Event{constructor(r){super("xrFrame"),this.data=r}}class am extends Event{constructor(r){super("playerCount"),this.data=r}}class om extends Event{constructor(){super("webRtcTCPRelayDetected")}}class lm extends EventTarget{dispatchEvent(r){return super.dispatchEvent(r)}addEventListener(r,n){super.addEventListener(r,n)}removeEventListener(r,n){super.removeEventListener(r,n)}}class Q{}Q.AutoConnect="AutoConnect",Q.AutoPlayVideo="AutoPlayVideo",Q.AFKDetection="TimeoutIfIdle",Q.BrowserSendOffer="OfferToReceive",Q.HoveringMouseMode="HoveringMouse",Q.ForceMonoAudio="ForceMonoAudio",Q.ForceTURN="ForceTURN",Q.FakeMouseWithTouches="FakeMouseWithTouches",Q.IsQualityController="ControlsQuality",Q.MatchViewportResolution="MatchViewportRes",Q.StartVideoMuted="StartVideoMuted",Q.SuppressBrowserKeys="SuppressBrowserKeys",Q.UseMic="UseMic",Q.KeyboardInput="KeyboardInput",Q.MouseInput="MouseInput",Q.TouchInput="TouchInput",Q.GamepadInput="GamepadInput",Q.XRControllerInput="XRControllerInput",Q.WaitForStreamer="WaitForStreamer",Q.HideUI="HideUI";const Sw=d=>Object.getOwnPropertyNames(Q).some((r=>Q[r]===d));class ye{}ye.AFKTimeoutSecs="AFKTimeout",ye.AFKCountdownSecs="AFKCountdown",ye.MinQP="MinQP",ye.MaxQP="MaxQP",ye.WebRTCFPS="WebRTCFPS",ye.WebRTCMinBitrate="WebRTCMinBitrate",ye.WebRTCMaxBitrate="WebRTCMaxBitrate",ye.MaxReconnectAttempts="MaxReconnectAttempts",ye.StreamerAutoJoinInterval="StreamerAutoJoinInterval";const Tw=d=>Object.getOwnPropertyNames(ye).some((r=>ye[r]===d));class jr{}jr.SignallingServerUrl="ss";const Ew=d=>Object.getOwnPropertyNames(jr).some((r=>jr[r]===d));class vt{}vt.PreferredCodec="PreferredCodec",vt.StreamerId="StreamerId";const $w=d=>Object.getOwnPropertyNames(vt).some((r=>vt[r]===d));class xw{constructor(r={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:n,useUrlParams:a}=r;this._useUrlParams=!!a,this.populateDefaultSettings(this._useUrlParams,n)}get useUrlParams(){return this._useUrlParams}populateDefaultSettings(r,n){this.textParameters.set(jr.SignallingServerUrl,new Rf(jr.SignallingServerUrl,"Signalling url","Url of the signalling server",n&&n.hasOwnProperty(jr.SignallingServerUrl)?n[jr.SignallingServerUrl]:(location.protocol==="https:"?"wss://":"ws://")+window.location.hostname+(window.location.port==="80"||window.location.port===""?"":`:${window.location.port}`),r)),this.optionParameters.set(vt.StreamerId,new Co(vt.StreamerId,"Streamer ID","The ID of the streamer to stream.",n&&n.hasOwnProperty(vt.StreamerId)?n[vt.StreamerId]:"",[],r)),this.optionParameters.set(vt.PreferredCodec,new Co(vt.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation","H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",n&&n.hasOwnProperty(vt.PreferredCodec)?[n[vt.PreferredCodec]]:(function(){const a=[];if(!RTCRtpReceiver.getCapabilities)return a.push("Only available on Chrome"),a;const f=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((v=>{const $=v.mimeType.split("/")[1]+" "+(v.sdpFmtpLine||"");f.exec($)!==null&&a.push($)})),a})(),r)),this.flags.set(Q.AutoConnect,new Rt(Q.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",!(!n||!n.hasOwnProperty(Q.AutoConnect))&&n[Q.AutoConnect],r)),this.flags.set(Q.AutoPlayVideo,new Rt(Q.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!n||!n.hasOwnProperty(Q.AutoPlayVideo)||n[Q.AutoPlayVideo],r)),this.flags.set(Q.BrowserSendOffer,new Rt(Q.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!n||!n.hasOwnProperty(Q.BrowserSendOffer))&&n[Q.BrowserSendOffer],r)),this.flags.set(Q.UseMic,new Rt(Q.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!n||!n.hasOwnProperty(Q.UseMic))&&n[Q.UseMic],r)),this.flags.set(Q.StartVideoMuted,new Rt(Q.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!n||!n.hasOwnProperty(Q.StartVideoMuted))&&n[Q.StartVideoMuted],r)),this.flags.set(Q.SuppressBrowserKeys,new Rt(Q.SuppressBrowserKeys,"Suppress browser keys","Suppress certain browser keys that we use in UE, for example F5 to show shader complexity instead of refresh the page.",!n||!n.hasOwnProperty(Q.SuppressBrowserKeys)||n[Q.SuppressBrowserKeys],r)),this.flags.set(Q.IsQualityController,new Rt(Q.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!n||!n.hasOwnProperty(Q.IsQualityController)||n[Q.IsQualityController],r)),this.flags.set(Q.ForceMonoAudio,new Rt(Q.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!n||!n.hasOwnProperty(Q.ForceMonoAudio))&&n[Q.ForceMonoAudio],r)),this.flags.set(Q.ForceTURN,new Rt(Q.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!n||!n.hasOwnProperty(Q.ForceTURN))&&n[Q.ForceTURN],r)),this.flags.set(Q.AFKDetection,new Rt(Q.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!n||!n.hasOwnProperty(Q.AFKDetection))&&n[Q.AFKDetection],r)),this.flags.set(Q.MatchViewportResolution,new Rt(Q.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",!(!n||!n.hasOwnProperty(Q.MatchViewportResolution))&&n[Q.MatchViewportResolution],r)),this.flags.set(Q.HoveringMouseMode,new Rt(Q.HoveringMouseMode,"Control Scheme: Locked Mouse","Either locked mouse, where the pointer is consumed by the video and locked to it, or hovering mouse, where the mouse is not consumed.",!(!n||!n.hasOwnProperty(Q.HoveringMouseMode))&&n[Q.HoveringMouseMode],r,((a,f)=>{f.label=`Control Scheme: ${a?"Hovering":"Locked"} Mouse`}))),this.flags.set(Q.FakeMouseWithTouches,new Rt(Q.FakeMouseWithTouches,"Fake mouse with touches","A single finger touch is converted into a mouse event. This allows a non-touch application to be controlled partially via a touch device.",!(!n||!n.hasOwnProperty(Q.FakeMouseWithTouches))&&n[Q.FakeMouseWithTouches],r)),this.flags.set(Q.KeyboardInput,new Rt(Q.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!n||!n.hasOwnProperty(Q.KeyboardInput)||n[Q.KeyboardInput],r)),this.flags.set(Q.MouseInput,new Rt(Q.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!n||!n.hasOwnProperty(Q.MouseInput)||n[Q.MouseInput],r)),this.flags.set(Q.TouchInput,new Rt(Q.TouchInput,"Touch input","If enabled, send touch events to streamer",!n||!n.hasOwnProperty(Q.TouchInput)||n[Q.TouchInput],r)),this.flags.set(Q.GamepadInput,new Rt(Q.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!n||!n.hasOwnProperty(Q.GamepadInput)||n[Q.GamepadInput],r)),this.flags.set(Q.XRControllerInput,new Rt(Q.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!n||!n.hasOwnProperty(Q.XRControllerInput)||n[Q.XRControllerInput],r)),this.flags.set(Q.WaitForStreamer,new Rt(Q.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!n||!n.hasOwnProperty(Q.WaitForStreamer)||n[Q.WaitForStreamer],r)),this.flags.set(Q.HideUI,new Rt(Q.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!n||!n.hasOwnProperty(Q.HideUI))&&n[Q.HideUI],r)),this.numericParameters.set(ye.AFKTimeoutSecs,new Ir(ye.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,n&&n.hasOwnProperty(ye.AFKTimeoutSecs)?n[ye.AFKTimeoutSecs]:120,r)),this.numericParameters.set(ye.AFKCountdownSecs,new Ir(ye.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(ye.MaxReconnectAttempts,new Ir(ye.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,n&&n.hasOwnProperty(ye.MaxReconnectAttempts)?n[ye.MaxReconnectAttempts]:3,r)),this.numericParameters.set(ye.MinQP,new Ir(ye.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,n&&n.hasOwnProperty(ye.MinQP)?n[ye.MinQP]:0,r)),this.numericParameters.set(ye.MaxQP,new Ir(ye.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,n&&n.hasOwnProperty(ye.MaxQP)?n[ye.MaxQP]:51,r)),this.numericParameters.set(ye.WebRTCFPS,new Ir(ye.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,n&&n.hasOwnProperty(ye.WebRTCFPS)?n[ye.WebRTCFPS]:60,r)),this.numericParameters.set(ye.WebRTCMinBitrate,new Ir(ye.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,n&&n.hasOwnProperty(ye.WebRTCMinBitrate)?n[ye.WebRTCMinBitrate]:0,r)),this.numericParameters.set(ye.WebRTCMaxBitrate,new Ir(ye.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,n&&n.hasOwnProperty(ye.WebRTCMaxBitrate)?n[ye.WebRTCMaxBitrate]:0,r)),this.numericParameters.set(ye.StreamerAutoJoinInterval,new Ir(ye.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,n&&n.hasOwnProperty(ye.StreamerAutoJoinInterval)?n[ye.StreamerAutoJoinInterval]:3e3,r))}_addOnNumericSettingChangedListener(r,n){this.numericParameters.has(r)&&this.numericParameters.get(r).addOnChangedListener(n)}_addOnOptionSettingChangedListener(r,n){this.optionParameters.has(r)&&this.optionParameters.get(r).addOnChangedListener(n)}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,n){if(!this.numericParameters.has(r))throw new Error(`There is no numeric setting with the id of ${r}`);this.numericParameters.get(r).number=n}_addOnSettingChangedListener(r,n){this.flags.has(r)&&(this.flags.get(r).onChange=n)}_addOnTextSettingChangedListener(r,n){this.textParameters.has(r)&&(this.textParameters.get(r).onChange=n)}getSettingOption(r){return this.optionParameters.get(r)}isFlagEnabled(r){return this.flags.get(r).flag}setFlagEnabled(r,n){this.flags.has(r)?this.flags.get(r).flag=n:T.Warning(T.GetStackTrace(),`Cannot toggle flag called ${r} - it does not exist in the Config.flags map.`)}setTextSetting(r,n){this.textParameters.has(r)?this.textParameters.get(r).text=n:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.textParameters map.`)}setOptionSettingOptions(r,n){this.optionParameters.has(r)?this.optionParameters.get(r).options=n:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(r,n){if(this.optionParameters.has(r)){const a=this.optionParameters.get(r),f=a.options;f.includes(n)||(f.push(n),a.options=f),a.selected=n}else T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.enumParameters map.`)}setFlagLabel(r,n){this.flags.has(r)?this.flags.get(r).label=n:T.Warning(T.GetStackTrace(),`Cannot set label for flag called ${r} - it does not exist in the Config.flags map.`)}setSettings(r){for(const n of Object.keys(r))Sw(n)?this.setFlagEnabled(n,r[n]):Tw(n)?this.setNumericSetting(n,r[n]):Ew(n)?this.setTextSetting(n,r[n]):$w(n)&&this.setOptionSettingValue(n,r[n])}getSettings(){const r={};for(const[n,a]of this.flags.entries())r[n]=a.flag;for(const[n,a]of this.numericParameters.entries())r[n]=a.number;for(const[n,a]of this.textParameters.entries())r[n]=a.text;for(const[n,a]of this.optionParameters.entries())r[n]=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 n of this.flags.keys()){const a=this.flags.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"flag",value:f,target:a})))}for(const n of this.numericParameters.keys()){const a=this.numericParameters.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"number",value:f,target:a})))}for(const n of this.textParameters.keys()){const a=this.textParameters.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"text",value:f,target:a})))}for(const n of this.optionParameters.keys()){const a=this.optionParameters.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ui({id:a.id,type:"option",value:f,target:a})))}}}var Nn;(function(d){d[d.LockedMouse=0]="LockedMouse",d[d.HoveringMouse=1]="HoveringMouse"})(Nn||(Nn={}));class um{constructor(r,n,a){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=r,this.pixelStreaming=n,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 If))}startAfkWarningTimer(){this.config.getNumericSettingValue(ye.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(Q.AFKDetection)?this.active=!0:this.active=!1,this.resetAfkWarningTimer()}stopAfkWarningTimer(){this.active=!1,this.countdownActive=!1,clearTimeout(this.warnTimer),clearInterval(this.countDownTimer)}pauseAfkWarningTimer(){this.active=!1}resetAfkWarningTimer(){this.active&&this.config.isFlagEnabled(Q.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(ye.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new Af({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(ye.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new ko({countDown:this.countDown})),this.config.isFlagEnabled(Q.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new Mf),this.onAFKTimedOutCallback(),T.Log(T.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new ko({countDown:this.countDown}))}),1e3)}}class Xp{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(r,n,a){this.peerConnection=r,this.label=n,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 n;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) opened.`,7),this.onOpen((n=this.dataChannel)===null||n===void 0?void 0:n.label,r)}handleOnClose(r){var n;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) closed.`,7),this.onClose((n=this.dataChannel)===null||n===void 0?void 0:n.label,r)}handleOnMessage(r){T.Log(T.GetStackTrace(),`Data Channel (${this.label}) message: ${r}`,8)}handleOnError(r){var n;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) error: ${r}`,7),this.onError((n=this.dataChannel)===null||n===void 0?void 0:n.label,r)}onOpen(r,n){}onClose(r,n){}onError(r,n){}}class dm{}class cm{}class hm{}class Ao{}class pm{}class Cw{}class kw{}class fm{constructor(){this.inboundVideoStats=new cm,this.inboundAudioStats=new dm,this.DataChannelStats=new hm,this.outBoundVideoStats=new pm,this.sessionStats=new Cw,this.streamStats=new kw,this.codecs=new Map}processStats(r){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,r.forEach((n=>{switch(n.type){case"candidate-pair":this.handleCandidatePair(n);break;case"certificate":case"media-source":case"media-playout":case"outbound-rtp":case"peer-connection":case"remote-inbound-rtp":break;case"codec":this.handleCodec(n);break;case"data-channel":this.handleDataChannel(n);break;case"inbound-rtp":this.handleInBoundRTP(n);break;case"local-candidate":this.handleLocalCandidate(n);break;case"remote-candidate":this.handleRemoteCandidate(n);break;case"remote-outbound-rtp":this.handleRemoteOutBound(n);break;case"track":this.handleTrack(n);break;case"transport":this.handleTransport(n);break;case"stream":this.handleStream(n);break;default:T.Error(T.GetStackTrace(),"unhandled Stat Type"),T.Log(T.GetStackTrace(),n)}}))}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 n=new Ao;n.label="local-candidate",n.address=r.address,n.port=r.port,n.protocol=r.protocol,n.candidateType=r.candidateType,n.id=r.id,n.relayProtocol=r.relayProtocol,n.transportId=r.transportId,this.localCandidates.push(n)}handleRemoteCandidate(r){const n=new Ao;n.label="remote-candidate",n.address=r.address,n.port=r.port,n.protocol=r.protocol,n.id=r.id,n.candidateType=r.candidateType,n.relayProtocol=r.relayProtocol,n.transportId=r.transportId,this.remoteCandidates.push(n)}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 n=r.id,a=`${r.mimeType.replace("video/","").replace("audio/","")}${r.sdpFmtpLine?` ${r.sdpFmtpLine}`:""}`;this.codecs.set(n,a)}handleSessionStatistics(r,n,a){const f=Date.now()-r;this.sessionStats.runTime=new Date(f).toISOString().substr(11,8).toString();const v=n===null?"Not sent yet":n?"true":"false";this.sessionStats.controlsStreamInput=v,this.sessionStats.videoEncoderAvgQP=a}isNumber(r){return typeof r=="number"&&isFinite(r)}getActiveCandidatePair(){return this.transportStats?this.candidatePairs.find((r=>r.id===this.transportStats.selectedCandidatePairId),null):this.candidatePairs.find((r=>r.selected),null)}}const Yp=(Jp={parseRtpParameters:()=>Qp.parseRtpParameters,splitSections:()=>Qp.splitSections},go={},Fi.d(go,Jp),go);var Jp,go;class mm{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 is,$e,yo=function(d,r,n,a){return new(n||(n=Promise))((function(f,v){function $(N){try{b(a.next(N))}catch(B){v(B)}}function R(N){try{b(a.throw(N))}catch(B){v(B)}}function b(N){var B;N.done?f(N.value):(B=N.value,B instanceof n?B:new n((function(re){re(B)}))).then($,R)}b((a=a.apply(d,[])).next())}))};class Rw{constructor(r,n,a){this.config=n,this.createPeerConnection(r,a)}createPeerConnection(r,n){this.config.isFlagEnabled(Q.ForceTURN)&&(r.iceTransportPolicy="relay",T.Log(T.GetStackTrace(),"Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(r),this.peerConnection.onsignalingstatechange=a=>this.handleSignalStateChange(a),this.peerConnection.oniceconnectionstatechange=a=>this.handleIceConnectionStateChange(a),this.peerConnection.onicegatheringstatechange=a=>this.handleIceGatheringStateChange(a),this.peerConnection.ontrack=a=>this.handleOnTrack(a),this.peerConnection.onicecandidate=a=>this.handleIceCandidate(a),this.peerConnection.ondatachannel=a=>this.handleDataChannel(a),this.aggregatedStats=new fm,this.preferredCodec=n,this.updateCodecSelection=!0}createOffer(r,n){return yo(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Create Offer",6);const a=location.hostname==="localhost"||location.hostname==="127.0.0.1",f=location.protocol==="https:";let v=n.isFlagEnabled(Q.UseMic);!v||a||f||(v=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(v).finally((()=>{var $;($=this.peerConnection)===null||$===void 0||$.createOffer(r).then((R=>{var b;this.showTextOverlayConnecting(),R.sdp=this.mungeSDP(R.sdp,v),(b=this.peerConnection)===null||b===void 0||b.setLocalDescription(R),this.onSendWebRTCOffer(R)})).catch((()=>{this.showTextOverlaySetupFailure()}))}))}))}receiveOffer(r,n){var a;return yo(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Receive Offer",6),(a=this.peerConnection)===null||a===void 0||a.setRemoteDescription(r).then((()=>{const f=location.hostname==="localhost"||location.hostname==="127.0.0.1",v=location.protocol==="https:";let $=n.isFlagEnabled(Q.UseMic);!$||f||v||($=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(vt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r)),this.setupTransceiversAsync($).finally((()=>{var R;(R=this.peerConnection)===null||R===void 0||R.createAnswer().then((b=>{var N;return b.sdp=this.mungeSDP(b.sdp,$),(N=this.peerConnection)===null||N===void 0?void 0:N.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 n;(n=this.peerConnection)===null||n===void 0||n.setRemoteDescription(r),this.config.setOptionSettingOptions(vt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r))}generateStats(){var r;(r=this.peerConnection)===null||r===void 0||r.getStats(null).then((n=>{this.aggregatedStats.processStats(n),this.onVideoStats(this.aggregatedStats),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId&&this.config.setOptionSettingValue(vt.PreferredCodec,this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId))}))}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(r,n){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
|
|
2900
|
+
`),f="maxaveragebitrate=510000;";return n&&(f+="sprop-maxcapturerate=48000;"),f+=this.config.isFlagEnabled(Q.ForceMonoAudio)?"stereo=0;":"stereo=1;",f+="useinbandfec=1",a=a.replace("useinbandfec=1",f),a}handleOnIce(r){var n;T.Log(T.GetStackTrace(),"peerconnection handleOnIce",6),this.config.isFlagEnabled(Q.ForceTURN)&&r.candidate.indexOf("relay")<0?T.Info(T.GetStackTrace(),`Dropping candidate because it was not TURN relay. | Type= ${r.type} | Protocol= ${r.protocol} | Address=${r.address} | Port=${r.port} |`,6):(n=this.peerConnection)===null||n===void 0||n.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 n=new Array,a=this.parseAvailableCodecs(r),f=this.config.getSettingOption(vt.PreferredCodec).options;for(const v of a)if(f.includes(v))n.push(v);else{const $=v.split(" ")[0];for(const R of f)if(R.includes($)){n.push(R);break}}return n}setupTransceiversAsync(r){var n,a,f,v,$,R,b,N,B,re,X,Y;return yo(this,void 0,void 0,(function*(){let te=!1;for(const ae of(a=(n=this.peerConnection)===null||n===void 0?void 0:n.getTransceivers())!==null&&a!==void 0?a:[])if(ae&&ae.receiver&&ae.receiver.track&&ae.receiver.track.kind==="video"){te=!0;break}if(te||(f=this.peerConnection)===null||f===void 0||f.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&this.preferredCodec!=""){for(const ae of($=(v=this.peerConnection)===null||v===void 0?void 0:v.getTransceivers())!==null&&$!==void 0?$:[])if(ae&&ae.receiver&&ae.receiver.track&&ae.receiver.track.kind==="video"&&ae.setCodecPreferences){const Te=this.preferredCodec.split(" "),Ee={mimeType:"video/"+Te[0],clockRate:9e4,sdpFmtpLine:Te[1]?Te[1]:""},ce=[Ee];RTCRtpReceiver.getCapabilities("video").codecs.forEach((le=>{(le.mimeType!=Ee.mimeType||le?.sdpFmtpLine!=Ee?.sdpFmtpLine)&&ce.push(le)}));for(const le of ce)le?.sdpFmtpLine!==void 0&&le.sdpFmtpLine!==""||delete le.sdpFmtpLine;ae.setCodecPreferences(ce)}}let H=!1;for(const ae of(b=(R=this.peerConnection)===null||R===void 0?void 0:R.getTransceivers())!==null&&b!==void 0?b:[])if(ae&&ae.receiver&&ae.receiver.track&&ae.receiver.track.kind==="audio"){H=!0;break}if(r){const ae={video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}},Te=yield navigator.mediaDevices.getUserMedia(ae);if(Te)if(H){for(const Ee of(re=(B=this.peerConnection)===null||B===void 0?void 0:B.getTransceivers())!==null&&re!==void 0?re:[])if(mm.canTransceiverReceiveAudio(Ee))for(const ce of Te.getTracks())ce.kind&&ce.kind=="audio"&&(Ee.sender.replaceTrack(ce),Ee.direction="sendrecv")}else for(const Ee of Te.getTracks())Ee.kind&&Ee.kind=="audio"&&((X=this.peerConnection)===null||X===void 0||X.addTransceiver(Ee,{direction:"sendrecv"}));else H||(Y=this.peerConnection)===null||Y===void 0||Y.addTransceiver("audio",{direction:"recvonly"})}else H||(N=this.peerConnection)===null||N===void 0||N.addTransceiver("audio",{direction:"recvonly"})}))}onVideoStats(r){}onSendWebRTCOffer(r){}onSendWebRTCAnswer(r){}showTextOverlayConnecting(){}showTextOverlaySetupFailure(){}parseAvailableCodecs(r){if(!RTCRtpReceiver.getCapabilities)return["Only available on Chrome"];const n=[],a=(0,Yp.splitSections)(r.sdp);return a.shift(),a.forEach((f=>{const{codecs:v}=(0,Yp.parseRtpParameters)(f),$=/(VP\d|H26\d|AV1).*/;v.forEach((R=>{const b=R.name+" "+Object.keys(R.parameters||{}).map((N=>N+"="+R.parameters[N])).join(";");if($.exec(b)!==null){R.name=="VP9"&&(R.parameters={"profile-id":"0"});const N=R.name+" "+Object.keys(R.parameters||{}).map((B=>B+"="+R.parameters[B])).join(";");n.push(N)}}))})),n}}class gm{constructor(){this.PixelStreamingSettings=new Aw,this.EncoderSettings=new ym,this.WebRTCSettings=new wm}ueCompatible(){this.WebRTCSettings.MaxFPS!=null&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class Aw{}class ym{}class wm{}class vm{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
|
|
2901
|
+
${this.PostEncodeTimeMs}
|
|
2902
|
+
${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
|
|
2903
|
+
${this.PostCaptureTimeMs}
|
|
2904
|
+
${this.PreCaptureTimeMs}`,6),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class wo{static setExtensionFromBytes(r,n){n.receiving||(n.mimetype="",n.extension="",n.receiving=!0,n.valid=!1,n.chunks=0,n.data=[],n.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),n.extension=a}static setMimeTypeFromBytes(r,n){n.receiving||(n.mimetype="",n.extension="",n.receiving=!0,n.valid=!1,n.chunks=0,n.data=[],n.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),n.mimetype=a}static setContentsFromBytes(r,n){if(!n.receiving)return;n.chunks=Math.ceil(new DataView(r.slice(1,5).buffer).getInt32(0,!0)/16379);const a=r.slice(5);if(n.data.push(a),T.Log(T.GetStackTrace(),`Received file chunk: ${n.data.length}/${n.chunks}`,6),n.data.length===n.chunks){n.receiving=!1,n.valid=!0,T.Log(T.GetStackTrace(),"Received complete file",6);const f=new Date().getTime()-n.timestampStart,v=Math.round(16384*n.chunks/f);T.Log(T.GetStackTrace(),`Average transfer bitrate: ${v}kb/s over ${f/1e3} seconds`,6);const $=new Blob(n.data,{type:n.mimetype}),R=document.createElement("a");R.setAttribute("href",URL.createObjectURL($)),R.setAttribute("download",`transfer.${n.extension}`),document.body.append(R),R.remove()}else n.data.length>n.chunks&&(n.receiving=!1,T.Error(T.GetStackTrace(),`Received bigger file than advertised: ${n.data.length}/${n.chunks}`))}}class Iw{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}}class Gt{}Gt.mainButton=0,Gt.auxiliaryButton=1,Gt.secondaryButton=2,Gt.fourthButton=3,Gt.fifthButton=4;class Kt{}Kt.primaryButton=1,Kt.secondaryButton=2,Kt.auxiliaryButton=4,Kt.fourthButton=8,Kt.fifthButton=16;class os{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(r){this.unregisterCallbacks.push(r)}unregisterAll(){for(const r of this.unregisterCallbacks)r();this.unregisterCallbacks=[]}}class Mw{constructor(r,n,a){this.touchEventListenerTracker=new os,this.toStreamerMessagesProvider=r,this.videoElementProvider=n,this.coordinateConverter=a;const f=R=>this.onTouchStart(R),v=R=>this.onTouchEnd(R),$=R=>this.onTouchMove(R);document.addEventListener("touchstart",f,{passive:!1}),document.addEventListener("touchend",v,{passive:!1}),document.addEventListener("touchmove",$,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchend",v))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",$)))}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 n=r.changedTouches[0];this.fakeTouchFinger=new Pw(n.identifier,n.clientX-this.videoElementParentClientRect.left,n.clientY-this.videoElementParentClientRect.top);const a=this.videoElementProvider.getVideoParentElement(),f=new MouseEvent("mouseenter",n);a.dispatchEvent(f);const v=this.coordinateConverter.normalizeAndQuantizeUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([Gt.mainButton,v.x,v.y])}r.preventDefault()}}onTouchEnd(r){if(!this.videoElementProvider.isVideoReady()||this.fakeTouchFinger==null)return;const n=this.videoElementProvider.getVideoParentElement(),a=this.toStreamerMessagesProvider.toStreamerHandlers;for(let f=0;f<r.changedTouches.length;f++){const v=r.changedTouches[f];if(v.identifier===this.fakeTouchFinger.id){const $=v.clientX-this.videoElementParentClientRect.left,R=v.clientY-this.videoElementParentClientRect.top,b=this.coordinateConverter.normalizeAndQuantizeUnsigned($,R);a.get("MouseUp")([Gt.mainButton,b.x,b.y]);const N=new MouseEvent("mouseleave",v);n.dispatchEvent(N),this.fakeTouchFinger=null;break}}r.preventDefault()}onTouchMove(r){if(!this.videoElementProvider.isVideoReady()||this.fakeTouchFinger==null)return;const n=this.toStreamerMessagesProvider.toStreamerHandlers;for(let a=0;a<r.touches.length;a++){const f=r.touches[a];if(f.identifier===this.fakeTouchFinger.id){const v=f.clientX-this.videoElementParentClientRect.left,$=f.clientY-this.videoElementParentClientRect.top,R=this.coordinateConverter.normalizeAndQuantizeUnsigned(v,$),b=this.coordinateConverter.normalizeAndQuantizeSigned(v-this.fakeTouchFinger.x,$-this.fakeTouchFinger.y);n.get("MouseMove")([R.x,R.y,b.x,b.y]),this.fakeTouchFinger.x=v,this.fakeTouchFinger.y=$;break}}r.preventDefault()}}class Pw{constructor(r,n,a){this.id=r,this.x=n,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,n,a){this.keyboardEventListenerTracker=new os,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=n,this.activeKeysProvider=a}registerKeyBoardEvents(){const r=v=>this.handleOnCompositionEnd(v),n=v=>this.handleOnKeyDown(v),a=v=>this.handleOnKeyUp(v),f=v=>this.handleOnKeyPress(v);document.addEventListener("compositionend",r),document.addEventListener("keydown",n),document.addEventListener("keyup",a),document.addEventListener("keypress",f),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("compositionend",r))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keydown",n))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keyup",a))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keypress",f)))}unregisterKeyBoardEvents(){this.keyboardEventListenerTracker.unregisterAll()}handleOnKeyDown(r){const n=this.getKeycode(r);n&&n!==229&&(T.Log(T.GetStackTrace(),`key down ${n}, repeat = ${r.repeat}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyDown")([this.getKeycode(r),r.repeat?1:0]),this.activeKeysProvider.getActiveKeys().push(n),n===Qt.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:Qt.backSpace})),this.config.isFlagEnabled(Q.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&r.preventDefault())}handleOnKeyUp(r){const n=this.getKeycode(r);n&&(T.Log(T.GetStackTrace(),`key up ${n}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyUp")([n]),this.config.isFlagEnabled(Q.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&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 n=r.charCode;T.Log(T.GetStackTrace(),`key press ${n}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyPress")([n])}handleOnCompositionEnd(r){r.data&&r.data.length&&r.data.split("").forEach((n=>{this.handleOnKeyDown(new KeyboardEvent("keydown",{keyCode:n.toUpperCase().charCodeAt(0),charCode:n.charCodeAt(0)})),this.handleOnKeyPress(new KeyboardEvent("keypress",{keyCode:n.toUpperCase().charCodeAt(0),charCode:n.charCodeAt(0)})),this.handleOnKeyUp(new KeyboardEvent("keyup",{keyCode:n.toUpperCase().charCodeAt(0),charCode:n.charCodeAt(0)}))}))}getKeycode(r){if(!("keyCode"in r)){const n=r;return n.code in this.CodeToKeyCode?this.CodeToKeyCode[n.code]:(T.Warning(T.GetStackTrace(),`Keyboard code of ${n.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 Dw{constructor(r,n,a){this.x=0,this.y=0,this.updateMouseMovePositionEvent=v=>{this.updateMouseMovePosition(v)},this.mouseEventListenerTracker=new os,this.videoElementProvider=r,this.mouseController=n,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(),n=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers;if(document.pointerLockElement===r||document.mozPointerLockElement===r)T.Log(T.GetStackTrace(),"Pointer locked",6),document.addEventListener("mousemove",this.updateMouseMovePositionEvent,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1)));else{T.Log(T.GetStackTrace(),"The pointer lock status is now unlocked",6),document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1);let a=this.activeKeysProvider.getActiveKeys();const f=new Set(a),v=[];f.forEach(($=>{})),v.forEach(($=>{n.get("KeyUp")([$])})),a=[]}}updateMouseMovePosition(r){if(!this.videoElementProvider.isVideoReady())return;const n=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers,a=this.videoElementProvider.getVideoParentElement().clientWidth,f=this.videoElementProvider.getVideoParentElement().clientHeight;this.x+=r.movementX,this.y+=r.movementY,this.x>a&&(this.x-=a),this.y>f&&(this.y-=f),this.x<0&&(this.x=a+this.x),this.y<0&&(this.y=f-this.y),this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y);const v=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(r.movementX,r.movementY);n.get("MouseMove")([this.coord.x,this.coord.y,v.x,v.y])}handleMouseDown(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([r.button,this.coord.x,this.coord.y])}handleMouseUp(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r.button,this.coord.x,this.coord.y])}handleMouseWheel(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([r.wheelDelta,this.coord.x,this.coord.y])}handleMouseDouble(r){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([r.button,this.coord.x,this.coord.y])}handlePressMouseButtons(r){this.videoElementProvider.isVideoReady()&&this.mouseController.pressMouseButtons(r.buttons,this.x,this.y)}handleReleaseMouseButtons(r){this.videoElementProvider.isVideoReady()&&this.mouseController.releaseMouseButtons(r.buttons,this.x,this.y)}}class zw{constructor(r){this.mouseController=r}unregisterMouseEvents(){}updateMouseMovePosition(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),"MouseMove",6);const n=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY),a=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(r.movementX,r.movementY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseMove")([n.x,n.y,a.x,a.y]),r.preventDefault()}handleMouseDown(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),"onMouse Down",6);const n=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([r.button,n.x,n.y]),r.preventDefault()}handleMouseUp(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),"onMouse Up",6);const n=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r.button,n.x,n.y]),r.preventDefault()}handleContextMenu(r){this.mouseController.videoElementProvider.isVideoReady()&&r.preventDefault()}handleMouseWheel(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;const n=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([r.wheelDelta,n.x,n.y]),r.preventDefault()}handleMouseDouble(r){if(!this.mouseController.videoElementProvider.isVideoReady())return;const n=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(r.offsetX,r.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([r.button,n.x,n.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 Lw{constructor(r,n,a,f){this.mouseEventListenerTracker=new os,this.toStreamerMessagesProvider=r,this.coordinateConverter=a,this.videoElementProvider=n,this.activeKeysProvider=f,this.registerMouseEnterAndLeaveEvents()}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}registerLockedMouseEvents(r){const n=this.videoElementProvider.getVideoParentElement(),a=new Dw(this.videoElementProvider,r,this.activeKeysProvider);if(n.requestPointerLock=n.requestPointerLock||n.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,n.requestPointerLock){const N=()=>{n.requestPointerLock()};n.addEventListener("click",N),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("click",N)))}const f=()=>a.lockStateChange();document.addEventListener("pointerlockchange",f,!1),document.addEventListener("mozpointerlockchange",f,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("pointerlockchange",f,!1))),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mozpointerlockchange",f,!1)));const v=N=>a.handleMouseDown(N),$=N=>a.handleMouseUp(N),R=N=>a.handleMouseWheel(N),b=N=>a.handleMouseDouble(N);n.addEventListener("mousedown",v),n.addEventListener("mouseup",$),n.addEventListener("wheel",R),n.addEventListener("dblclick",b),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousedown",v))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mouseup",$))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("wheel",R))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("dblclick",b))),this.mouseEventListenerTracker.addUnregisterCallback((()=>a.unregisterMouseEvents())),this.mouseEventListenerTracker.addUnregisterCallback((()=>{!document.exitPointerLock||document.pointerLockElement!==n&&document.mozPointerLockElement!==n||document.exitPointerLock()}))}registerHoveringMouseEvents(r){const n=this.videoElementProvider.getVideoParentElement(),a=new zw(r),f=B=>a.updateMouseMovePosition(B),v=B=>a.handleMouseDown(B),$=B=>a.handleMouseUp(B),R=B=>a.handleContextMenu(B),b=B=>a.handleMouseWheel(B),N=B=>a.handleMouseDouble(B);n.addEventListener("mousemove",f),n.addEventListener("mousedown",v),n.addEventListener("mouseup",$),n.addEventListener("contextmenu",R),n.addEventListener("wheel",b),n.addEventListener("dblclick",N),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousemove",f))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousedown",v))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mouseup",$))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("contextmenu",R))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("wheel",b))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("dblclick",N))),this.mouseEventListenerTracker.addUnregisterCallback((()=>a.unregisterMouseEvents()))}registerMouseEnterAndLeaveEvents(){const r=this.videoElementProvider.getVideoParentElement(),n=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",n),r.addEventListener("mouseleave",a),this.mouseEventListenerTracker.addUnregisterCallback((()=>r.removeEventListener("mouseenter",n))),this.mouseEventListenerTracker.addUnregisterCallback((()=>r.removeEventListener("mouseleave",a)))}releaseMouseButtons(r,n,a){const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(n,a);r&Kt.primaryButton&&this.sendMouseUp(Gt.mainButton,f.x,f.y),r&Kt.secondaryButton&&this.sendMouseUp(Gt.secondaryButton,f.x,f.y),r&Kt.auxiliaryButton&&this.sendMouseUp(Gt.auxiliaryButton,f.x,f.y),r&Kt.fourthButton&&this.sendMouseUp(Gt.fourthButton,f.x,f.y),r&Kt.fifthButton&&this.sendMouseUp(Gt.fifthButton,f.x,f.y)}pressMouseButtons(r,n,a){if(!this.videoElementProvider.isVideoReady())return;const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(n,a);r&Kt.primaryButton&&this.sendMouseDown(Gt.mainButton,f.x,f.y),r&Kt.secondaryButton&&this.sendMouseDown(Gt.secondaryButton,f.x,f.y),r&Kt.auxiliaryButton&&this.sendMouseDown(Gt.auxiliaryButton,f.x,f.y),r&Kt.fourthButton&&this.sendMouseDown(Gt.fourthButton,f.x,f.y),r&Kt.fifthButton&&this.sendMouseDown(Gt.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,n,a){this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),`mouse button ${r} down at (${n}, ${a})`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([r,n,a]))}sendMouseUp(r,n,a){if(!this.videoElementProvider.isVideoReady())return;T.Log(T.GetStackTrace(),`mouse button ${r} up at (${n}, ${a})`,6);const f=this.coordinateConverter.normalizeAndQuantizeUnsigned(n,a);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([r,f.x,f.y])}}class Bw{constructor(r,n,a){this.fingers=[9,8,7,6,5,4,3,2,1,0],this.fingerIds=new Map,this.maxByteValue=255,this.touchEventListenerTracker=new os,this.toStreamerMessagesProvider=r,this.videoElementProvider=n,this.coordinateConverter=a,this.videoElementParent=n.getVideoElement();const f=b=>this.onTouchStart(b),v=b=>this.onTouchEnd(b),$=b=>this.onTouchMove(b);this.videoElementParent.addEventListener("touchstart",f),this.videoElementParent.addEventListener("touchend",v),this.videoElementParent.addEventListener("touchmove",$),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchend",v))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchmove",$))),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 n=this.fingers.pop();n===void 0&&T.Log(T.GetStackTrace(),"exhausted touch identifiers",6),this.fingerIds.set(r.identifier,n)}forgetTouch(r){this.fingers.push(this.fingerIds.get(r.identifier)),this.fingers.sort((function(n,a){return a-n})),this.fingerIds.delete(r.identifier)}onTouchStart(r){if(this.videoElementProvider.isVideoReady()){for(let n=0;n<r.changedTouches.length;n++)this.rememberTouch(r.changedTouches[n]);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 n=0;n<r.changedTouches.length;n++)this.forgetTouch(r.changedTouches[n]);r.preventDefault()}}onTouchMove(r){this.videoElementProvider.isVideoReady()&&(T.Log(T.GetStackTrace(),"touch move",6),this.emitTouchData("TouchMove",r.touches),r.preventDefault())}emitTouchData(r,n){if(!this.videoElementProvider.isVideoReady())return;const a=this.videoElementProvider.getVideoParentElement().getBoundingClientRect(),f=this.toStreamerMessagesProvider.toStreamerHandlers;for(let v=0;v<n.length;v++){const R=n[v],b=R.clientX-a.left,N=R.clientY-a.top;T.Log(T.GetStackTrace(),`F${this.fingerIds.get(R.identifier)}=(${b}, ${N})`,6);const B=this.coordinateConverter.normalizeAndQuantizeUnsigned(b,N);switch(r){case"TouchStart":f.get("TouchStart")([1,B.x,B.y,this.fingerIds.get(R.identifier),this.maxByteValue*(R.force>0?R.force:1),B.inRange?1:0]);break;case"TouchEnd":f.get("TouchEnd")([1,B.x,B.y,this.fingerIds.get(R.identifier),this.maxByteValue*R.force,B.inRange?1:0]);break;case"TouchMove":f.get("TouchMove")([1,B.x,B.y,this.fingerIds.get(R.identifier),this.maxByteValue*(R.force>0?R.force:1),B.inRange?1:0])}}}}class Nw{constructor(r){this.gamePadEventListenerTracker=new os,this.toStreamerMessagesProvider=r,this.requestAnimationFrame=(window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.requestAnimationFrame).bind(window);const n=window;if(window.addEventListener("beforeunload",(a=>this.onBeforeUnload(a))),"GamepadEvent"in n){const a=v=>this.gamePadConnectHandler(v),f=v=>this.gamePadDisconnectHandler(v);window.addEventListener("gamepadconnected",a),window.addEventListener("gamepaddisconnected",f),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepadconnected",a))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepaddisconnected",f)))}else if("WebKitGamepadEvent"in n){const a=v=>this.gamePadConnectHandler(v),f=v=>this.gamePadDisconnectHandler(v);window.addEventListener("webkitgamepadconnected",a),window.addEventListener("webkitgamepaddisconnected",f),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepadconnected",a))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepaddisconnected",f)))}if(this.controllers=[],navigator.getGamepads)for(const a of navigator.getGamepads())a&&this.gamePadConnectHandler(new GamepadEvent("gamepadconnected",{gamepad:a}))}unregisterGamePadEvents(){this.gamePadEventListenerTracker.unregisterAll();for(const r of this.controllers)r.id!==void 0&&this.onGamepadDisconnected(r.id);this.controllers=[],this.onGamepadConnected=()=>{},this.onGamepadDisconnected=()=>{}}gamePadConnectHandler(r){T.Log(T.GetStackTrace(),"Gamepad connect handler",6);const n=r.gamepad,a={currentState:n,prevState:n,id:void 0};this.controllers.push(a),this.controllers[n.index].currentState=n,this.controllers[n.index].prevState=n,T.Log(T.GetStackTrace(),"gamepad: "+n.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 n=this.controllers[r.gamepad.index];delete this.controllers[r.gamepad.index],this.controllers=this.controllers.filter((a=>a!==void 0)),this.onGamepadDisconnected(n.id)}scanGamePads(){const r=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[];for(let n=0;n<r.length;n++)r[n]&&r[n].index in this.controllers&&(this.controllers[r[n].index].currentState=r[n])}updateStatus(){this.scanGamePads();const r=this.toStreamerMessagesProvider.toStreamerHandlers;for(const n of this.controllers){const a=n.id===void 0?this.controllers.indexOf(n):n.id,f=n.currentState;for(let v=0;v<n.currentState.buttons.length;v++){const $=n.currentState.buttons[v],R=n.prevState.buttons[v];$.pressed?v==is.LeftTrigger?r.get("GamepadAnalog")([a,5,$.value]):v==is.RightTrigger?r.get("GamepadAnalog")([a,6,$.value]):r.get("GamepadButtonPressed")([a,v,R.pressed?1:0]):!$.pressed&&R.pressed&&(v==is.LeftTrigger?r.get("GamepadAnalog")([a,5,0]):v==is.RightTrigger?r.get("GamepadAnalog")([a,6,0]):r.get("GamepadButtonReleased")([a,v,0]))}for(let v=0;v<f.axes.length;v+=2){const $=parseFloat(f.axes[v].toFixed(4)),R=-parseFloat(f.axes[v+1].toFixed(4));r.get("GamepadAnalog")([a,v+1,$]),r.get("GamepadAnalog")([a,v+2,R])}this.controllers[a].prevState=f}this.controllers.length>0&&this.requestAnimationFrame((()=>this.updateStatus()))}onGamepadResponseReceived(r){for(const n of this.controllers)if(n.id===void 0){n.id=r;break}}onGamepadConnected(){}onGamepadDisconnected(r){}onBeforeUnload(r){for(const n of this.controllers)this.onGamepadDisconnected(n.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"})(is||(is={}));class Uw{constructor(r,n,a){this.activeKeys=new Fw,this.toStreamerMessagesProvider=r,this.videoElementProvider=n,this.coordinateConverter=a}registerKeyBoard(r){T.Log(T.GetStackTrace(),"Register Keyboard Events",7);const n=new Ow(this.toStreamerMessagesProvider,r,this.activeKeys);return n.registerKeyBoardEvents(),n}registerMouse(r){T.Log(T.GetStackTrace(),"Register Mouse Events",7);const n=new Lw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys);switch(r){case Nn.LockedMouse:n.registerLockedMouseEvents(n);break;case Nn.HoveringMouse:n.registerHoveringMouseEvents(n);break;default:T.Info(T.GetStackTrace(),"unknown Control Scheme Type Defaulting to Locked Mouse Events"),n.registerLockedMouseEvents(n)}return n}registerTouch(r,n){if(T.Log(T.GetStackTrace(),"Registering Touch",6),r){const a=new Mw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return a.setVideoElementParentClientRect(n),a}return new Bw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return T.Log(T.GetStackTrace(),"Register Game Pad",7),new Nw(this.toStreamerMessagesProvider)}}class Fw{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class Vw{constructor(r,n){this.lastTimeResized=new Date().getTime(),this.videoElement=document.createElement("video"),this.config=n,this.videoElement.id="streamingVideo",this.videoElement.disablePictureInPicture=!0,this.videoElement.playsInline=!0,this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.pointerEvents="all",r.appendChild(this.videoElement),this.onResizePlayerCallback=()=>{console.log("Resolution changed, restyling player, did you forget to override this function?")},this.onMatchViewportResolutionCallback=()=>{console.log("Resolution changed and match viewport resolution is turned on, did you forget to override this function?")},this.videoElement.onclick=()=>{this.audioElement!=null&&this.audioElement.paused&&this.audioElement.play(),this.videoElement.paused&&this.videoElement.play()},this.videoElement.onloadedmetadata=()=>{this.onVideoInitialized()},window.addEventListener("resize",(()=>this.resizePlayerStyle()),!0),window.addEventListener("orientationchange",(()=>this.onOrientationChange()))}setAudioElement(r){this.audioElement=r}play(){return this.videoElement.muted=this.config.isFlagEnabled(Q.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(Q.AutoPlayVideo),this.videoElement.play()}isPaused(){return this.videoElement.paused}isVideoReady(){return this.videoElement.readyState!==void 0&&this.videoElement.readyState>0}hasVideoSource(){return this.videoElement.srcObject!==void 0&&this.videoElement.srcObject!==null}getVideoElement(){return this.videoElement}getVideoParentElement(){return this.videoElement.parentElement}setVideoEnabled(r){this.videoElement.srcObject.getTracks().forEach((n=>n.enabled=r))}onVideoInitialized(){}onOrientationChange(){clearTimeout(this.orientationChangeTimeout),this.orientationChangeTimeout=window.setTimeout((()=>{this.resizePlayerStyle()}),500)}resizePlayerStyle(){const r=this.getVideoParentElement();r&&(this.updateVideoStreamSize(),r.classList.contains("fixed-size")||this.resizePlayerStyleToFillParentElement(),this.onResizePlayerCallback())}resizePlayerStyleToFillParentElement(){this.getVideoParentElement().setAttribute("style","top: 0px; left: 0px; width: 100%; height: 100%; cursor: default;")}updateVideoStreamSize(){if(this.config.isFlagEnabled(Q.MatchViewportResolution))if(new Date().getTime()-this.lastTimeResized>300){const r=this.getVideoParentElement();if(!r)return;this.onMatchViewportResolutionCallback(r.clientWidth,r.clientHeight),this.lastTimeResized=new Date().getTime()}else T.Log(T.GetStackTrace(),"Resizing too often - skipping",6),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout((()=>this.updateVideoStreamSize()),100)}}class 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,n,a){switch(r){case $e.ToStreamer:this.toStreamerHandlers.set(n,a);break;case $e.FromStreamer:this.fromStreamerHandlers.set(n,a);break;default:T.Log(T.GetStackTrace(),`Unknown message direction ${r}`)}}}(function(d){d[d.ToStreamer=0]="ToStreamer",d[d.FromStreamer=1]="FromStreamer"})($e||($e={}));class qw{constructor(){this.responseEventListeners=new Map}addResponseEventListener(r,n){this.responseEventListeners.set(r,n)}removeResponseEventListener(r){this.responseEventListeners.delete(r)}onResponse(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.Response",6);const n=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),n,6),this.responseEventListeners.forEach((a=>{a(n)}))}}class Ww{constructor(r,n){this.dataChannelSender=r,this.toStreamerMessagesMapProvider=n}sendMessageToStreamer(r,n){n===void 0&&(n=[]);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&&n&&a.structure.length!==n.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 [ ${n.map((b=>typeof b)).toString()} ]`);let f=0;const v=new TextEncoder;n.forEach(((b,N)=>{switch(a.structure[N]){case"uint8":f+=1;break;case"uint16":case"int16":f+=2;break;case"float":f+=4;break;case"double":f+=8;break;case"string":f+=2,f+=2*v.encode(b).length}}));const $=new DataView(new ArrayBuffer(f+1));$.setUint8(0,a.id);let R=1;n.forEach(((b,N)=>{switch(a.structure[N]){case"uint8":$.setUint8(R,b),R+=1;break;case"uint16":$.setUint16(R,b,!0),R+=2;break;case"int16":$.setInt16(R,b,!0),R+=2;break;case"float":$.setFloat32(R,b,!0),R+=4;break;case"double":$.setFloat64(R,b,!0),R+=8;break;case"string":$.setUint16(R,b.length,!0),R+=2;for(let B=0;B<b.length;B++)$.setUint16(R,b.charCodeAt(B),!0),R+=2}})),this.dataChannelSender.canSend()?this.dataChannelSender.sendData($.buffer):T.Info(T.GetStackTrace(),`Data channel cannot send yet, skipping sending message: ${r} - ${new Uint8Array($.buffer)}`)}}class Hw{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 jw{constructor(r){this.dataChannelProvider=r}canSend(){return this.dataChannelProvider.getDataChannelInstance().dataChannel!==void 0&&this.dataChannelProvider.getDataChannelInstance().dataChannel.readyState=="open"}sendData(r){const n=this.dataChannelProvider.getDataChannelInstance();n.dataChannel.readyState=="open"?(n.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 Kw{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,n){return this.normalizeAndQuantizeUnsignedFunc(r,n)}unquantizeAndDenormalizeUnsigned(r,n){return this.denormalizeAndUnquantizeUnsignedFunc(r,n)}normalizeAndQuantizeSigned(r,n){return this.normalizeAndQuantizeSignedFunc(r,n)}setupNormalizeAndQuantize(){if(this.videoElementParent=this.videoElementProvider.getVideoParentElement(),this.videoElement=this.videoElementProvider.getVideoElement(),this.videoElementParent&&this.videoElement){const r=this.videoElementParent.clientWidth||1,n=this.videoElementParent.clientHeight||1,a=this.videoElement.videoWidth||1,f=n/r,v=(this.videoElement.videoHeight||1)/a;f>v?(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio > videoAspectRatio",6),this.ratio=f/v,this.normalizeAndQuantizeUnsignedFunc=($,R)=>this.normalizeAndQuantizeUnsignedPlayerBigger($,R),this.normalizeAndQuantizeSignedFunc=($,R)=>this.normalizeAndQuantizeSignedPlayerBigger($,R),this.denormalizeAndUnquantizeUnsignedFunc=($,R)=>this.denormalizeAndUnquantizeUnsignedPlayerBigger($,R)):(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio <= videoAspectRatio",6),this.ratio=v/f,this.normalizeAndQuantizeUnsignedFunc=($,R)=>this.normalizeAndQuantizeUnsignedPlayerSmaller($,R),this.normalizeAndQuantizeSignedFunc=($,R)=>this.normalizeAndQuantizeSignedPlayerSmaller($,R),this.denormalizeAndUnquantizeUnsignedFunc=($,R)=>this.denormalizeAndUnquantizeUnsignedPlayerSmaller($,R))}}normalizeAndQuantizeUnsignedPlayerBigger(r,n){const a=r/this.videoElementParent.clientWidth,f=this.ratio*(n/this.videoElementParent.clientHeight-.5)+.5;return a<0||a>1||f<0||f>1?new Di(!1,65535,65535):new Di(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerBigger(r,n){const a=r/65536,f=(n/65536-.5)/this.ratio+.5;return new Io(a*this.videoElementParent.clientWidth,f*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerBigger(r,n){const a=r/(.5*this.videoElementParent.clientWidth),f=this.ratio*n/(.5*this.videoElementParent.clientHeight);return new Zp(32767*a,32767*f)}normalizeAndQuantizeUnsignedPlayerSmaller(r,n){const a=this.ratio*(r/this.videoElementParent.clientWidth-.5)+.5,f=n/this.videoElementParent.clientHeight;return a<0||a>1||f<0||f>1?new Di(!1,65535,65535):new Di(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerSmaller(r,n){const a=(r/65536-.5)/this.ratio+.5,f=n/65536;return new Io(a*this.videoElementParent.clientWidth,f*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerSmaller(r,n){const a=this.ratio*r/(.5*this.videoElementParent.clientWidth),f=n/(.5*this.videoElementParent.clientHeight);return new Zp(32767*a,32767*f)}}class Di{constructor(r,n,a){this.inRange=r,this.x=n,this.y=a}}class Io{constructor(r,n){this.x=r,this.y=n}}class Zp{constructor(r,n){this.x=r,this.y=n}}class _m{constructor(r,n){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=r,this.pixelStreaming=n,this.responseController=new qw,this.file=new Iw,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new um(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new vw(this.pixelStreaming.videoElementParent),this.videoPlayer=new Vw(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(a,f)=>{const v={"Resolution.Width":a,"Resolution.Height":f};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(v)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new yw(this.videoPlayer),this.coordinateConverter=new Kw(this.videoPlayer),this.sendrecvDataChannelController=new Xp,this.recvDataChannelController=new Xp,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new jw(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new Gw,this.webSocketController=new kf,this.webSocketController.onConfig=a=>this.handleOnConfigMessage(a),this.webSocketController.onStreamerList=a=>this.handleStreamerListMessage(a),this.webSocketController.onStreamerIDChanged=a=>this.handleStreamerIDChangedMessage(a),this.webSocketController.onPlayerCount=a=>{this.pixelStreaming._onPlayerCount(a.count)},this.webSocketController.onOpen.addEventListener("open",(()=>{this.config.isFlagEnabled(Q.BrowserSendOffer)||this.webSocketController.requestStreamerList()})),this.webSocketController.onClose.addEventListener("close",(a=>{const f=this.shouldReconnect&&a.detail.code!=1001&&this.config.getNumericSettingValue(ye.MaxReconnectAttempts)>0,v=this.disconnectMessage?this.disconnectMessage:a.detail.reason;this.pixelStreaming._onDisconnect(v,!f&&!this.isReconnecting),this.afkController.stopAfkWarningTimer(),this.statsTimerHandle&&this.statsTimerHandle!==void 0&&window.clearInterval(this.statsTimerHandle),this.setVideoEncoderAvgQP(0),this.setTouchInputEnabled(!1),this.setMouseInputEnabled(!1),this.setKeyboardInputEnabled(!1),this.setGamePadInputEnabled(!1),f&&setTimeout((()=>{this.isReconnecting=!0,this.reconnectAttempt++,this.tryReconnect(a.detail.reason)}),2e3)})),this.sendMessageController=new Ww(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new Hw(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new Uw(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(vt.StreamerId,(a=>{a!==""&&(this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=a,this.webSocketController.sendSubscribe(a))})),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>{let a=this.config.getTextSettingValue(jr.SignallingServerUrl);return this.config.isFlagEnabled(Q.BrowserSendOffer)&&(a+="?"+Q.BrowserSendOffer+"=true"),a}}requestUnquantizedAndDenormalizeUnsigned(r,n){return this.coordinateConverter.unquantizeAndDenormalizeUnsigned(r,n)}handleOnMessage(r){const n=new Uint8Array(r.data);T.Log(T.GetStackTrace(),"Message incoming:"+n,6);const a=this.streamMessageController.fromStreamerMessages.get(n[0]);this.streamMessageController.fromStreamerHandlers.get(a)(r.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler($e.FromStreamer,"QualityControlOwnership",(r=>this.onQualityControlOwnership(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"Response",(r=>this.responseController.onResponse(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"Command",(r=>{this.onCommand(r)})),this.streamMessageController.registerMessageHandler($e.FromStreamer,"FreezeFrame",(r=>this.onFreezeFrameMessage(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"UnfreezeFrame",(()=>this.invalidateFreezeFrameAndEnableVideo())),this.streamMessageController.registerMessageHandler($e.FromStreamer,"VideoEncoderAvgQP",(r=>this.handleVideoEncoderAvgQP(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"LatencyTest",(r=>this.handleLatencyTestResult(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"DataChannelLatencyTest",(r=>this.handleDataChannelLatencyTestResponse(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"InitialSettings",(r=>this.handleInitialSettings(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"FileExtension",(r=>this.onFileExtension(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"FileMimeType",(r=>this.onFileMimeType(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"FileContents",(r=>this.onFileContents(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler($e.FromStreamer,"InputControlOwnership",(r=>this.onInputControlOwnership(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"GamepadResponse",(r=>this.onGamepadResponse(r))),this.streamMessageController.registerMessageHandler($e.FromStreamer,"Protocol",(r=>this.onProtocolMessage(r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"IFrameRequest",(()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest"))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"RequestQualityControl",(()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl"))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"FpsRequest",(()=>this.sendMessageController.sendMessageToStreamer("FpsRequest"))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"AverageBitrateRequest",(()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest"))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"StartStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StartStreaming"))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"StopStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StopStreaming"))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"LatencyTest",(r=>this.sendMessageController.sendMessageToStreamer("LatencyTest",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"RequestInitialSettings",(()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings"))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler($e.ToStreamer,"UIInteraction",(r=>this.sendMessageController.sendMessageToStreamer("UIInteraction",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"Command",(r=>this.sendMessageController.sendMessageToStreamer("Command",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"TextboxEntry",(r=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"KeyDown",(r=>this.sendMessageController.sendMessageToStreamer("KeyDown",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"KeyUp",(r=>this.sendMessageController.sendMessageToStreamer("KeyUp",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"KeyPress",(r=>this.sendMessageController.sendMessageToStreamer("KeyPress",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"MouseEnter",(r=>this.sendMessageController.sendMessageToStreamer("MouseEnter",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"MouseLeave",(r=>this.sendMessageController.sendMessageToStreamer("MouseLeave",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"MouseDown",(r=>this.sendMessageController.sendMessageToStreamer("MouseDown",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"MouseUp",(r=>this.sendMessageController.sendMessageToStreamer("MouseUp",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"MouseMove",(r=>this.sendMessageController.sendMessageToStreamer("MouseMove",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"MouseWheel",(r=>this.sendMessageController.sendMessageToStreamer("MouseWheel",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"MouseDouble",(r=>this.sendMessageController.sendMessageToStreamer("MouseDouble",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"TouchStart",(r=>this.sendMessageController.sendMessageToStreamer("TouchStart",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"TouchEnd",(r=>this.sendMessageController.sendMessageToStreamer("TouchEnd",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"TouchMove",(r=>this.sendMessageController.sendMessageToStreamer("TouchMove",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"GamepadConnected",(()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected"))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"GamepadButtonPressed",(r=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"GamepadButtonReleased",(r=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"GamepadAnalog",(r=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"GamepadDisconnected",(r=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"XREyeViews",(r=>this.sendMessageController.sendMessageToStreamer("XREyeViews",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"XRHMDTransform",(r=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"XRControllerTransform",(r=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"XRSystem",(r=>this.sendMessageController.sendMessageToStreamer("XRSystem",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"XRButtonTouched",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"XRButtonTouchReleased",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"XRButtonPressed",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"XRButtonReleased",(r=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",r))),this.streamMessageController.registerMessageHandler($e.ToStreamer,"XRAnalog",(r=>this.sendMessageController.sendMessageToStreamer("XRAnalog",r)))}onCommand(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.Command",6);const n=new TextDecoder("utf-16").decode(r.slice(1));T.Log(T.GetStackTrace(),"Data Channel Command: "+n,6);const a=JSON.parse(n);a.command==="onScreenKeyboard"&&this.pixelStreaming._activateOnScreenKeyboard(a)}onProtocolMessage(r){try{const n=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(n);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==$e.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(a).forEach((v=>{const $=a[v];switch(f){case $e.ToStreamer:if(!Object.prototype.hasOwnProperty.call($,"id"))return void T.Error(T.GetStackTrace(),`ToStreamer->${v} protocol definition was malformed as it didn't contain at least an id
|
|
2905
|
+
|
|
2906
|
+
Definition was: ${JSON.stringify($,null,2)}`);if(v==="UIInteraction"||v==="Command"||v==="LatencyTest")return;this.streamMessageController.toStreamerHandlers.get(v)?this.streamMessageController.toStreamerMessages.set(v,$):T.Error(T.GetStackTrace(),`There was no registered handler for "${v}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${v}", myHandler)`);break;case $e.FromStreamer:if(!Object.prototype.hasOwnProperty.call($,"id"))return void T.Error(T.GetStackTrace(),`FromStreamer->${v} protocol definition was malformed as it didn't contain at least an id
|
|
2907
|
+
|
|
2908
|
+
Definition was: ${JSON.stringify($,null,2)}`);this.streamMessageController.fromStreamerHandlers.get(v)?this.streamMessageController.fromStreamerMessages.set($.id,v):T.Error(T.GetStackTrace(),`There was no registered handler for "${$}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${v}", myHandler)`);break;default:T.Error(T.GetStackTrace(),`Unknown direction: ${f}`)}})),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(n){T.Log(T.GetStackTrace(),n)}}onInputControlOwnership(r){const n=new Uint8Array(r);T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.InputControlOwnership",6);const a=new Boolean(n[1]).valueOf();T.Log(T.GetStackTrace(),`Received input controller message - will your input control the stream: ${a}`),this.pixelStreaming._onInputControlOwnership(a)}onGamepadResponse(r){const n=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(n);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 Xf({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 n=new Uint8Array(r);this.freezeFrameController.processFreezeFrameMessage(n,(()=>this.loadFreezeFrameOrShowPlayOverlay()))}invalidateFreezeFrameAndEnableVideo(){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6),setTimeout((()=>{this.pixelStreaming.dispatchEvent(new Yf),this.freezeFrameController.hideFreezeFrame()}),this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(r){const n=new Uint8Array(r);wo.setExtensionFromBytes(n,this.file)}onFileMimeType(r){const n=new Uint8Array(r);wo.setMimeTypeFromBytes(n,this.file)}onFileContents(r){const n=new Uint8Array(r);wo.setContentsFromBytes(n,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 Kf({message:r})),T.Error(T.GetStackTrace(),r),void this.closeSignalingServer("Stream not initialized correctly")}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(Q.TouchInput)),this.pixelStreaming.dispatchEvent(new Qf),this.streamController.audioElement.srcObject){const r=this.config.isFlagEnabled(Q.StartVideoMuted);this.streamController.audioElement.muted=r,r?this.playVideo():this.streamController.audioElement.play().then((()=>{this.playVideo()})).catch((n=>{T.Log(T.GetStackTrace(),n),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 Ro({reason:n}))}))}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 Ro({reason:r}))}))}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(Q.AutoPlayVideo)&&this.playStream(),this.resizePlayerStyle()}connectToSignallingServer(){this.locallyClosed=!1,this.shouldReconnect=!0,this.disconnectMessage=null;const r=this.signallingUrlBuilder();this.webSocketController.connect(r)}startSession(r){if(this.peerConfig=r,this.config.isFlagEnabled(Q.ForceTURN)&&!this.checkTurnServerAvailability(r))return T.Info(T.GetStackTrace(),"No turn server was found in the Peer Connection Options. TURN cannot be forced, closing connection. Please use STUN instead"),void this.closeSignalingServer("TURN cannot be forced, closing connection. Please use STUN instead.");this.peerConnectionController=new 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 n=!1;this.peerConnectionController.onIceConnectionStateChange=()=>{!n&&["connected","completed"].includes(this.peerConnectionController.peerConnection.iceConnectionState)&&(this.pixelStreaming._onWebRtcConnected(),n=!0)},this.peerConnectionController.onTrack=a=>this.streamController.handleOnTrack(a),this.config.isFlagEnabled(Q.BrowserSendOffer)&&(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"cirrus",this.datachannelOptions),this.sendrecvDataChannelController.handleOnMessage=a=>this.handleOnMessage(a),this.peerConnectionController.createOffer(this.sdpConstraints,this.config))}checkTurnServerAvailability(r){if(!r.iceServers)return T.Info(T.GetStackTrace(),"A turn sever was not found"),!1;for(const n of r.iceServers)for(const a of n.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=n=>this.handleWebRtcAnswer(n),this.webSocketController.onWebRtcOffer=n=>this.handleWebRtcOffer(n),this.webSocketController.onWebRtcPeerDataChannels=n=>this.handleWebRtcSFUPeerDatachannels(n),this.webSocketController.onIceCandidate=n=>this.handleIceCandidate(n)}handleStreamerListMessage(r){T.Log(T.GetStackTrace(),`Got streamer list ${r.ids}`,6);let n=null;var a=this.config.getSettingOption(vt.StreamerId);a.selected.toString().trim()&&(n=a.selected);const f=[...r.ids];f.unshift(""),this.config.setOptionSettingOptions(vt.StreamerId,f);let v=null;const $=this.config.isFlagEnabled(Q.WaitForStreamer),R=this.config.getNumericSettingValue(ye.MaxReconnectAttempts),b=this.config.getNumericSettingValue(ye.StreamerAutoJoinInterval),N=this.config.useUrlParams,B=new URLSearchParams(window.location.search);N&&B.has(vt.StreamerId)?n=B.get(vt.StreamerId):this.subscribedStream&&(n=this.subscribedStream),n&&r.ids.includes(n)?v=n:n&&$||r.ids.length!=1||(v=r.ids[0]),v?(this.isReconnecting=!1,this.reconnectAttempt=0,this.config.setOptionSettingValue(vt.StreamerId,v)):$&&(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 Zf({messageStreamerList:r,autoSelectedStreamerId:v,wantedStreamerId:n}))}handleStreamerIDChangedMessage(r){const n=r.newID;var a=this.config.getSettingOption(vt.StreamerId),f=a.onChange;a.onChange=()=>{};for(var v=a.options,$=0;$<v.length;++$)if(v[$]==this.subscribedStream){v[$]=n;break}a.options=v,a.selected=n,a.onChange=f,this.subscribedStream=r.newID,this.pixelStreaming.dispatchEvent(new em({newID:n}))}handleWebRtcAnswer(r){T.Log(T.GetStackTrace(),`Got answer sdp ${r.sdp}`,6);const n={sdp:r.sdp,type:"answer"};this.peerConnectionController.receiveAnswer(n),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 n={sdp:r.sdp,type:"offer"};this.peerConnectionController.receiveOffer(n,this.config),this.handlePostWebrtcNegotiation()}handleWebRtcSFUPeerDatachannels(r){const n={ordered:!0,negotiated:!0,id:r.sendStreamId},a=r.sendStreamId!=r.recvStreamId;if(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,a?"send-datachannel":"datachannel",n),a){const f={ordered:!0,negotiated:!0,id:r.recvStreamId};this.recvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"recv-datachannel",f),this.recvDataChannelController.handleOnOpen=()=>this.webSocketController.sendSFURecvDataChannelReady(),this.recvDataChannelController.handleOnMessage=v=>this.handleOnMessage(v)}else this.sendrecvDataChannelController.handleOnMessage=f=>this.handleOnMessage(f)}handlePostWebrtcNegotiation(){this.afkController.startAfkWarningTimer(),this.pixelStreaming._onWebRtcSdp(),this.statsTimerHandle&&this.statsTimerHandle!==void 0&&window.clearInterval(this.statsTimerHandle),this.statsTimerHandle=window.setInterval((()=>this.getStats()),1e3),this.setMouseInputEnabled(this.config.isFlagEnabled(Q.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(Q.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(Q.GamepadInput))}handleIceCandidate(r){T.Log(T.GetStackTrace(),"Web RTC Controller: onWebRtcIce",6);const n=new RTCIceCandidate(r);this.peerConnectionController.handleOnIce(n)}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=n=>this.handleOnMessage(n)}handleSendWebRTCOffer(r){T.Log(T.GetStackTrace(),"Sending the offer to the Server",6);const n={minBitrateBps:1e3*this.config.getNumericSettingValue(ye.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(ye.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcOffer(r,n)}handleSendWebRTCAnswer(r){T.Log(T.GetStackTrace(),"Sending the answer to the Server",6);const n={minBitrateBps:1e3*this.config.getNumericSettingValue(ye.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(ye.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcAnswer(r,n),this.isUsingSFU&&this.webSocketController.sendWebRtcDatachannelRequest()}setUpMouseAndFreezeFrame(){this.videoElementParentClientRect=this.videoPlayer.getVideoParentElement().getBoundingClientRect(),this.coordinateConverter.setupNormalizeAndQuantize(),this.freezeFrameController.freezeFrame.resize()}closeSignalingServer(r){var n;this.locallyClosed=!0,this.shouldReconnect=!1,this.disconnectMessage=r,(n=this.webSocketController)===null||n===void 0||n.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}
|
|
2909
|
+
`,6),r!=null&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQP":r})])}sendEncoderMaxQP(r){T.Log(T.GetStackTrace(),`MaxQP=${r}
|
|
2910
|
+
`,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 n=new TextDecoder("utf-16").decode(r.slice(1)),a=new vm;Object.assign(a,JSON.parse(n)),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 n=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(n);this.pixelStreaming._onDataChannelLatencyTestResponse(a)}handleInitialSettings(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.InitialSettings",6);const n=new TextDecoder("utf-16").decode(r.slice(1)),a=JSON.parse(n),f=new gm;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(Q.HoveringMouseMode,!!a.ConfigOptions.DefaultToHover),f.ueCompatible(),T.Log(T.GetStackTrace(),n,6),this.pixelStreaming._onInitialSettings(f)}handleVideoEncoderAvgQP(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.VideoEncoderAvgQP",6);const n=Number(new TextDecoder("utf-16").decode(r.slice(1)));this.setVideoEncoderAvgQP(n)}handleVideoInitialized(){this.pixelStreaming._onVideoInitialized(),this.autoPlayVideoOrSetUpPlayOverlay(),this.resizePlayerStyle(),this.videoPlayer.updateVideoStreamSize()}onQualityControlOwnership(r){const n=new Uint8Array(r);T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.QualityControlOwnership",6),this.isQualityController=new Boolean(n[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 n;(n=this.keyboardController)===null||n===void 0||n.unregisterKeyBoardEvents(),r&&(this.keyboardController=this.inputClassesFactory.registerKeyBoard(this.config))}setMouseInputEnabled(r){var n;if((n=this.mouseController)===null||n===void 0||n.unregisterMouseEvents(),r){const a=this.config.isFlagEnabled(Q.HoveringMouseMode)?Nn.HoveringMouse:Nn.LockedMouse;this.mouseController=this.inputClassesFactory.registerMouse(a)}}setTouchInputEnabled(r){var n;(n=this.touchController)===null||n===void 0||n.unregisterTouchEvents(),r&&(this.touchController=this.inputClassesFactory.registerTouch(this.config.isFlagEnabled(Q.FakeMouseWithTouches),this.videoElementParentClientRect))}setGamePadInputEnabled(r){var n;(n=this.gamePadController)===null||n===void 0||n.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=(n,a)=>this.pixelStreaming.dispatchEvent(new Uf({label:n,event:a})),r.onClose=(n,a)=>this.pixelStreaming.dispatchEvent(new Ff({label:n,event:a})),r.onError=(n,a)=>this.pixelStreaming.dispatchEvent(new Vf({label:n,event:a}))}registerMessageHandler(r,n,a){n===$e.FromStreamer&&a===void 0&&T.Warning(T.GetStackTrace(),`Unable to register handler for ${r} as no handler was passed`),this.streamMessageController.registerMessageHandler(n,r,(f=>a===void 0&&n===$e.ToStreamer?this.sendMessageController.sendMessageToStreamer(r,f):a(f)))}}class Vi{constructor(r){this.toStreamerMessagesProvider=r,this.controllers=[]}static deepCopyGamepad(r){return JSON.parse(JSON.stringify({buttons:r.buttons.map((n=>JSON.parse(JSON.stringify({pressed:n.pressed,touched:n.touched,value:n.value})))),axes:r.axes}))}updateStatus(r,n,a){if(r.gamepad){const f=n.getPose(r.gripSpace,a);if(!f)return;let v=0;r.profiles.includes("htc-vive")?v=1:r.profiles.includes("oculus-touch")&&(v=2),this.toStreamerMessagesProvider.toStreamerHandlers.get("XRSystem")([v]);let $=2;switch(r.handedness){case"left":$=0;break;case"right":$=1}const R=f.transform.matrix,b=[];for(let X=0;X<16;X++)b[X]=new Float32Array([R[X]])[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],$]),this.controllers[$]===void 0&&(this.controllers[$]={prevState:void 0,currentState:void 0,id:void 0},this.controllers[$].prevState=Vi.deepCopyGamepad(r.gamepad)),this.controllers[$].currentState=Vi.deepCopyGamepad(r.gamepad);const N=this.controllers[$],B=N.currentState,re=N.prevState;for(let X=0;X<B.buttons.length;X++){const Y=B.buttons[X],te=re.buttons[X];if(Y.pressed){let H=te.pressed?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonPressed")([$,X,H])}else te.pressed&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonReleased")([$,X,0]);if(Y.touched){let H=te.touched?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouched")([$,X,H])}else te.touched&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouchReleased")([$,X,0])}for(let X=0;X<B.axes.length;X++){let Y=B.axes[X];Y!=re.axes[X]&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRAnalog")([$,X,Y])}this.controllers[$].prevState=B}}}class bm{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 Vi(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,`
|
|
2911
|
+
attribute vec2 a_position;
|
|
2912
|
+
attribute vec2 a_texCoord;
|
|
2913
|
+
|
|
2914
|
+
// varyings
|
|
2915
|
+
varying vec2 v_texCoord;
|
|
2916
|
+
|
|
2917
|
+
void main() {
|
|
2918
|
+
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
2919
|
+
// pass the texCoord to the fragment shader
|
|
2920
|
+
// The GPU will interpolate this value between points.
|
|
2921
|
+
v_texCoord = a_texCoord;
|
|
2922
|
+
}
|
|
2923
|
+
`),this.gl.compileShader(r);const n=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(n,`
|
|
2924
|
+
precision mediump float;
|
|
2925
|
+
|
|
2926
|
+
// our texture
|
|
2927
|
+
uniform sampler2D u_image;
|
|
2928
|
+
|
|
2929
|
+
// the texCoords passed in from the vertex shader.
|
|
2930
|
+
varying vec2 v_texCoord;
|
|
2931
|
+
|
|
2932
|
+
void main() {
|
|
2933
|
+
gl_FragColor = texture2D(u_image, v_texCoord);
|
|
2934
|
+
}
|
|
2935
|
+
`),this.gl.compileShader(n);const a=this.gl.createProgram();this.gl.attachShader(a,r),this.gl.attachShader(a,n),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,n=this.webRtcController.videoPlayer.getVideoElement().videoWidth;this.prevVideoHeight!=r||this.prevVideoWidth!=n?this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,n,r,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()):this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,0,0,n,r,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()),this.prevVideoHeight=r,this.prevVideoWidth=n}initBuffers(){this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.positionLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-1,1,1,1,-1,-1,-1,-1,1,1,1,-1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.positionLocation,2,this.gl.FLOAT,!1,0,0),this.texcoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texcoordBuffer),this.gl.enableVertexAttribArray(this.texcoordLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.texcoordLocation,2,this.gl.FLOAT,!1,0,0)}onXrSessionStarted(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((n=>{if(this.xrRefSpace=n,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,n=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],n[0],n[4],n[8],n[12],n[1],n[5],n[9],n[13],n[2],n[6],n[10],n[14],n[3],n[7],n[11],n[15],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,n){if(this.xrViewerPose=n.getViewerPose(this.xrRefSpace),this.xrViewerPose){if(this.updateViews(),this.leftView==null||this.rightView==null)return;this.sendXRDataToUE(),this.updateVideoTexture(),this.render()}this.webRtcController.config.isFlagEnabled(Q.XRControllerInput)&&this.xrSession.inputSources.forEach(((a,f,v)=>{this.xrGamepadController.updateStatus(a,n,this.xrRefSpace)}),this),this.xrSession.requestAnimationFrame(((a,f)=>this.onXrFrame(a,f))),this.onFrame.dispatchEvent(new im({time:r,frame:n}))}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 Qw{constructor(r){this.editTextButton=null,this.hiddenInput=null,"ontouchstart"in document.documentElement&&this.createOnScreenKeyboardHelpers(r)}unquantizeAndDenormalizeUnsigned(r,n){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",(n=>{this.hiddenInput.focus(),n.preventDefault()})))}showOnScreenKeyboard(r){if(r.showOnScreenKeyboard){this.editTextButton.style.display="default";const n=this.unquantizeAndDenormalizeUnsigned(r.x,r.y);this.editTextButton.style.top=n.y.toString()+"px",this.editTextButton.style.left=(n.x-40).toString()+"px"}else this.editTextButton.style.display="none",this.hiddenInput.blur()}}class Xw{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 Yw{constructor(r,n){this.sink=r,this.callback=n,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(((n,a)=>n+(a.playerReceivedTimestamp-a.playerSentTimestamp)),0)/this.records.size),playerToStreamerTime:Math.ceil(Array.from(this.records.values()).reduce(((n,a)=>n+(a.streamerReceivedTimestamp-a.playerSentTimestamp)),0)/this.records.size),streamerToPlayerTime:Math.ceil(Array.from(this.records.values()).reduce(((n,a)=>n+(a.playerReceivedTimestamp-a.streamerSentTimestamp)),0)/this.records.size),exportLatencyAsCSV:()=>{let n=`Timestamp;RTT;PlayerToStreamer;StreamerToPlayer;
|
|
2936
|
+
`;return r.forEach((a=>{n+=a.playerSentTimestamp+";",n+=a.playerReceivedTimestamp-a.playerSentTimestamp+";",n+=a.streamerReceivedTimestamp-a.playerSentTimestamp+";",n+=a.playerReceivedTimestamp-a.streamerSentTimestamp+";",n+=`
|
|
2937
|
+
`})),n}}}isRunning(){return!!this.interval}receive(r){if(!this.isRunning())return;if(!r)return void T.Error(T.GetStackTrace(),"Undefined response from server");let n=this.records.get(r.Seq);n&&n.update(r)}sendRequest(r,n){let a=this.createRequest(r,n),f=new Xw(a);this.records.set(f.seq,f),this.sink(a)}createRequest(r,n){return{Seq:this.seq++,FillResponseSize:n,Filler:r?"A".repeat(r):""}}}class Jw{constructor(r,n){this.allowConsoleCommands=!1,this.config=r,n?.videoElementParent&&(this._videoElementParent=n.videoElementParent),this._eventEmitter=new lm,this.configureSettings(),this.setWebRtcPlayerController(new _m(this.config,this)),this.onScreenKeyboardHelper=new Qw(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(a,f)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(a,f),this._activateOnScreenKeyboard=a=>this.onScreenKeyboardHelper.showOnScreenKeyboard(a),this._webXrController=new bm(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",(a=>{this._eventEmitter.addEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}))}get videoElementParent(){return this._videoElementParent||(this._videoElementParent=document.createElement("div"),this._videoElementParent.id="videoElementParent"),this._videoElementParent}configureSettings(){this.config._addOnSettingChangedListener(Q.IsQualityController,(r=>{r!==!0||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(Q.AFKDetection,(r=>{this._webRtcController.setAfkEnabled(r)})),this.config._addOnSettingChangedListener(Q.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(Q.HoveringMouseMode,(r=>{this.config.setFlagLabel(Q.HoveringMouseMode,`Control Scheme: ${r?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(Q.MouseInput))})),this.config._addOnSettingChangedListener(Q.KeyboardInput,(r=>{this._webRtcController.setKeyboardInputEnabled(r)})),this.config._addOnSettingChangedListener(Q.MouseInput,(r=>{this._webRtcController.setMouseInputEnabled(r)})),this.config._addOnSettingChangedListener(Q.FakeMouseWithTouches,(r=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(Q.TouchInput))})),this.config._addOnSettingChangedListener(Q.TouchInput,(r=>{this._webRtcController.setTouchInputEnabled(r)})),this.config._addOnSettingChangedListener(Q.GamepadInput,(r=>{this._webRtcController.setGamePadInputEnabled(r)})),this.config._addOnNumericSettingChangedListener(ye.MinQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending MinQP --------",7),this._webRtcController.sendEncoderMinQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ye.MaxQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending encoder settings --------",7),this._webRtcController.sendEncoderMaxQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ye.WebRTCMinBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMinBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ye.WebRTCMaxBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMaxBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ye.WebRTCFPS,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCFps(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnOptionSettingChangedListener(vt.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(vt.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Wf),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new jf),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Hf),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(Q.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(r=!1){if(!this.config.isFlagEnabled("UseMic"))return r?(this.config.setFlagEnabled("UseMic",!0),void this.reconnect()):void T.Warning(T.GetStackTrace(),"Trying to unmute mic, but PixelStreaming was initialized with no microphone track. Call with forceEnable == true to re-connect with a mic track.");this.setMicrophoneMuted(!1)}muteMicrophone(){this.config.isFlagEnabled("UseMic")?this.setMicrophoneMuted(!0):T.Info(T.GetStackTrace(),"Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(r){var n,a,f,v;for(const $ of(v=(f=(a=(n=this._webRtcController)===null||n===void 0?void 0:n.peerConnectionController)===null||a===void 0?void 0:a.peerConnection)===null||f===void 0?void 0:f.getTransceivers())!==null&&v!==void 0?v:[])mm.canTransceiverSendAudio($)&&($.sender.track.enabled=!r)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new Df)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new Of)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new qf)}_onDisconnect(r,n){this._eventEmitter.dispatchEvent(new Nf({eventString:r,allowClickToReconnect:n}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new zf)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Lf)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new Bf)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new Gf),this._videoStartTime=Date.now()}_onLatencyTestResult(r){this._eventEmitter.dispatchEvent(new tm({latencyTimings:r}))}_onDataChannelLatencyTestResponse(r){this._eventEmitter.dispatchEvent(new rm({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 Jf({aggregatedStats:r}))}_onVideoEncoderAvgQP(r){this._eventEmitter.dispatchEvent(new Pf({avgQP:r}))}_onInitialSettings(r){var n;this._eventEmitter.dispatchEvent(new sm({settings:r})),r.PixelStreamingSettings&&(this.allowConsoleCommands=(n=r.PixelStreamingSettings.AllowPixelStreamingCommands)!==null&&n!==void 0&&n,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(ye.MinQP,a&&f.has(ye.MinQP)?Number.parseFloat(f.get(ye.MinQP)):r.EncoderSettings.MinQP),this.config.setNumericSetting(ye.MaxQP,a&&f.has(ye.MaxQP)?Number.parseFloat(f.get(ye.MaxQP)):r.EncoderSettings.MaxQP)),r.WebRTCSettings&&(this.config.setNumericSetting(ye.WebRTCMinBitrate,a&&f.has(ye.WebRTCMinBitrate)?Number.parseFloat(f.get(ye.WebRTCMinBitrate)):r.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(ye.WebRTCMaxBitrate,a&&f.has(ye.WebRTCMaxBitrate)?Number.parseFloat(f.get(ye.WebRTCMaxBitrate)):r.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(ye.WebRTCFPS,a&&f.has(ye.WebRTCFPS)?Number.parseFloat(f.get(ye.WebRTCFPS)):r.WebRTCSettings.FPS))}_onQualityControlOwnership(r){this.config.setFlagEnabled(Q.IsQualityController,r)}_onPlayerCount(r){this._eventEmitter.dispatchEvent(new am({count:r}))}_setupWebRtcTCPRelayDetection(r){let n=r.data.aggregatedStats.getActiveCandidatePair();if(n!=null){let a=r.data.aggregatedStats.localCandidates.find((f=>f.id==n.localCandidateId),null);a!=null&&a.candidateType=="relay"&&a.relayProtocol=="tcp"&&this._eventEmitter.dispatchEvent(new om),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 Yw(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(n=>{this._eventEmitter.dispatchEvent(new nm({result:n}))})),this.addEventListener("dataChannelLatencyTestResponse",(({data:{response:n}})=>{this._dataChannelLatencyTestController.receive(n)}))),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,n){this._webRtcController.responseController.addResponseEventListener(r,n)}removeResponseEventListener(r){this._webRtcController.responseController.removeResponseEventListener(r)}dispatchEvent(r){return this._eventEmitter.dispatchEvent(r)}addEventListener(r,n){this._eventEmitter.addEventListener(r,n)}removeEventListener(r,n){this._eventEmitter.removeEventListener(r,n)}toggleXR(){this.webXrController.xrClicked()}setSignallingUrlBuilder(r){this._webRtcController.signallingUrlBuilder=r}get webSocketController(){return this._webRtcController.webSocketController}get webXrController(){return this._webXrController}registerMessageHandler(r,n,a){n!==$e.FromStreamer||a!==void 0?n===$e.ToStreamer&&a===void 0?this._webRtcController.streamMessageController.registerMessageHandler(n,r,(f=>this._webRtcController.sendMessageController.sendMessageToStreamer(r,f))):this._webRtcController.streamMessageController.registerMessageHandler(n,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 Zw{}be.Dz;be.g$;be.Lt;be.Q9;be.qf;be.hV;be.z$;be.J0;var ev=be.De;be.$C;be.al;be._W;be.Gv;be.m;be.tz;be.Nu;be.zg;be.vp;be.vU;be.wF;be.rv;be.Nh;be.ss;be.qW;be.QL;be.cf;be.eM;be.Yd;be.Tk;be.iM;be.qy;be.ce;be.sK;be.Ok;be.q5;var tv=be.g;be.xl;be.I;be.bx;be.dD;be.Ib;be.Az;be.Iw;be.qY;be.db;be.mR;be.Tn;be.rV;be.gh;be.Mi;be.j;be.YB;be.Yt;be.i5;be.x_;be.Am;be.eR;be.r8;be.u3;be.vd;be.iV;be.jZ;be.SW;be.ZH;be.Ni;be.lh;be.ZP;be.bq;be.$f;be.eu;be.Ax;be.Mc;const Sm=({signallingUrl:d,autoConnect:r=!0,width:n,height:a,onConnecting:f,onLoading:v,onConnected:$,onDisconnected:R,onError:b,muted:N=!1})=>{const B=me.useRef(null),re=me.useRef(null),X=me.useRef(!1),[Y,te]=me.useState(!1),[H,ae]=me.useState(!1),[Te,Ee]=me.useState(null);return me.useEffect(()=>{if(!(!B.current||!d)){f&&f(),console.log("🎮 Initializing Epic Pixel Streaming with URL:",d),navigator.mediaDevices||(navigator.mediaDevices={}),navigator.mediaDevices.getUserMedia||(navigator.mediaDevices.getUserMedia=function(){return Promise.reject(new Error("getUserMedia is not supported"))});try{const ce=new ev({useUrlParams:!1,initialSettings:{ss:d,AutoConnect:r,AutoPlayVideo:!0,StartVideoMuted:N,UseMic:!1,HoveringMouse:!1,FakeMouseWithTouches:!0,TouchInput:!1,MouseInput:!1,KeyboardInput:!1,WaitForStreamer:!0}}),le=new tv(ce,{videoElementParent:B.current});le.addEventListener("webRtcConnected",()=>{console.log("✅ WebRTC Connected"),X.current=!0,te(!0),ae(!1),Ee(null),$&&$()}),le.addEventListener("webRtcDisconnected",()=>{console.log("🔌 WebRTC Disconnected"),X.current=!1,te(!1),R&&R()}),le.addEventListener("streamLoading",()=>{console.log("⏳ Stream Loading"),ae(!0),v&&v()}),le.addEventListener("playStreamError",he=>{console.error("❌ Play Stream Error:",he),Ee("Failed to play stream"),ae(!1),b&&b("Failed to play stream")}),le.addEventListener("playStream",()=>{console.log("▶️ Stream Playing"),ae(!1),X.current||(console.log("✅ Stream Playing - Setting connected (fallback)"),X.current=!0,te(!0),$&&$())}),le.addEventListener("videoInitialized",()=>{console.log("📹 Video Initialized"),ae(!1)}),le.addEventListener("streamerListMessage",he=>{console.log("📋 Streamer list received:",he.data);const pe=he.data?.ids||he.data;pe&&pe.length>0&&console.log("🎯 Streamer available, subscribing to:",pe[0])}),re.current=le}catch(ce){console.error("❌ Failed to initialize Pixel Streaming:",ce),Ee("Failed to initialize streaming: "+ce.message),ae(!1),b&&b(ce.message)}return()=>{if(console.log("🧹 Cleaning up Epic Pixel Streaming"),re.current){try{re.current._webSocketController&&(console.info("PX websocket connection closed"),re.current._webSocketController.close()),re.current.disconnect()}catch(ce){console.error("Error during cleanup:",ce)}re.current=null}}}},[d,r,f,v,$,R,b]),me.useEffect(()=>{if(re.current)try{const ce=re.current._webRtcController?.videoPlayer;if(!ce){console.log("⚠️ Video player not found");return}let le=!1;if(ce.audioElement){const pe=ce.audioElement.srcObject;if(pe){const Pe=pe.getAudioTracks();Pe.length>0&&(Pe.forEach(fe=>{fe.enabled=!N}),console.log("🔊 Audio element tracks",N?"disabled":"enabled","- Track count:",Pe.length),le=!0)}}const he=ce.getVideoElement();if(he&&he.srcObject){const Pe=he.srcObject.getAudioTracks();Pe.length>0&&(Pe.forEach(fe=>{fe.enabled=!N}),console.log("🔊 Video element audio tracks",N?"disabled":"enabled","- Track count:",Pe.length),le=!0)}!le&&he&&(he.muted=N,console.log("🔊 Video element muted property set to:",N)),le||console.log("⚠️ No audio tracks found, using video element muted property")}catch(ce){console.error("Error controlling audio:",ce)}},[N]),or.jsxs("div",{className:"pixel-streaming-container",style:{width:n||"100%",height:a||"100%",position:"relative",display:"flex",flexDirection:"column",touchAction:"none",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},children:[or.jsx("div",{ref:B,className:"player-container",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"hidden",touchAction:"none"}}),H&&or.jsxs("div",{className:"loading-overlay",children:[or.jsx("div",{className:"loading-spinner"}),or.jsx("div",{className:"loading-text",children:"Connecting to stream..."})]}),!Y&&!H&&Te&&or.jsx("div",{className:"connection-overlay",children:or.jsx("div",{className:"error-message",children:Te})})]})};function rv({className:d,style:r,autoConnect:n=!0,muted:a=!1,onConnected:f,onDisconnected:v,onError:$}){const{streamingUrl:R,setCloudStreamState:b}=xf();if(!R)return null;const N=()=>{b(tr.CONNECTING)},B=()=>{b(tr.LOADING)},re=()=>{b(tr.CONNECTED),f?.()},X=()=>{b(tr.DISCONNECTED),v?.()},Y=te=>{b(tr.ERROR,te),$?.(te)};return or.jsx("div",{className:d,style:r,children:or.jsx(Sm,{signallingUrl:R,autoConnect:n,muted:a,onConnecting:N,onLoading:B,onConnected:re,onDisconnected:X,onError:Y})})}exports.AGENT_TYPES=Hr;exports.CLOUD_STREAM_STATE=tr;exports.CONNECTION_STATE=It;exports.EpicPixelStreamingPlayer=Sm;exports.RqmiiAgentProvider=mf;exports.RqmiiAgentRoom=iw;exports.RqmiiCloudAvatarPlayer=rv;exports.SESSION_STATE=Bn;exports.SOCKET_EVENTS=Wt;exports.useRqmiiAgent=Zy;exports.useRqmiiAgentContext=Or;exports.useRqmiiAudioElement=nw;exports.useRqmiiAvatar=xf;exports.useRqmiiConnection=$f;exports.useRqmiiMessages=tw;exports.useRqmiiPressToTalk=By;exports.useRqmiiSessionState=ew;exports.useRqmiiVAD=Jy;exports.useRqmiiVoice=rw;
|
|
2938
|
+
//# sourceMappingURL=RqmiiCloudAvatarPlayer-lqCz2xlU.cjs.map
|