@rqmii_immersive/agent-react-sdk 1.0.1 โ 1.0.2
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/index.d.ts +5 -1
- package/dist/rqmii-react-agent-sdk.cjs +361 -361
- package/dist/rqmii-react-agent-sdk.cjs.map +1 -1
- package/dist/rqmii-react-agent-sdk.js +2361 -2347
- package/dist/rqmii-react-agent-sdk.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const he=require("react");var Ei={exports:{}},js={};/**
|
|
2
2
|
* @license React
|
|
3
3
|
* react-jsx-runtime.production.js
|
|
4
4
|
*
|
|
@@ -14,46 +14,46 @@
|
|
|
14
14
|
*
|
|
15
15
|
* This source code is licensed under the MIT license found in the
|
|
16
16
|
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var cp;function pg(){return cp||(cp=1,process.env.NODE_ENV!=="production"&&(function(){function c(Y){if(Y==null)return null;if(typeof Y=="function")return Y.$$typeof===
|
|
17
|
+
*/var cp;function pg(){return cp||(cp=1,process.env.NODE_ENV!=="production"&&(function(){function c(Y){if(Y==null)return null;if(typeof Y=="function")return Y.$$typeof===ft?null:Y.displayName||Y.name||null;if(typeof Y=="string")return Y;switch(Y){case ue:return"Fragment";case Te:return"Profiler";case Be:return"StrictMode";case pe:return"Suspense";case Ne:return"SuspenseList";case Xe:return"Activity"}if(typeof Y=="object")switch(typeof Y.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),Y.$$typeof){case ce:return"Portal";case ne:return Y.displayName||"Context";case oe:return(Y._context.displayName||"Context")+".Consumer";case me:var Ie=Y.render;return Y=Y.displayName,Y||(Y=Ie.displayName||Ie.name||"",Y=Y!==""?"ForwardRef("+Y+")":"ForwardRef"),Y;case ge:return Ie=Y.displayName||null,Ie!==null?Ie:c(Y.type)||"Memo";case rt:Ie=Y._payload,Y=Y._init;try{return c(Y(Ie))}catch{}}return null}function r(Y){return""+Y}function n(Y){try{r(Y);var Ie=!1}catch{Ie=!0}if(Ie){Ie=console;var tt=Ie.error,gt=typeof Symbol=="function"&&Symbol.toStringTag&&Y[Symbol.toStringTag]||Y.constructor.name||"Object";return tt.call(Ie,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",gt),r(Y)}}function a(Y){if(Y===ue)return"<>";if(typeof Y=="object"&&Y!==null&&Y.$$typeof===rt)return"<...>";try{var Ie=c(Y);return Ie?"<"+Ie+">":"<...>"}catch{return"<...>"}}function f(){var Y=Ge.A;return Y===null?null:Y.getOwner()}function v(){return Error("react-stack-top-frame")}function C(Y){if(Ye.call(Y,"key")){var Ie=Object.getOwnPropertyDescriptor(Y,"key").get;if(Ie&&Ie.isReactWarning)return!1}return Y.key!==void 0}function R(Y,Ie){function tt(){ut||(ut=!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)",Ie))}tt.isReactWarning=!0,Object.defineProperty(Y,"key",{get:tt,configurable:!0})}function _(){var Y=c(this.type);return Je[Y]||(Je[Y]=!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.")),Y=this.props.ref,Y!==void 0?Y:null}function U(Y,Ie,tt,gt,Vt,Et){var dt=tt.ref;return Y={$$typeof:ie,type:Y,key:Ie,props:tt,_owner:gt},(dt!==void 0?dt:null)!==null?Object.defineProperty(Y,"ref",{enumerable:!1,get:_}):Object.defineProperty(Y,"ref",{enumerable:!1,value:null}),Y._store={},Object.defineProperty(Y._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(Y,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(Y,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:Vt}),Object.defineProperty(Y,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:Et}),Object.freeze&&(Object.freeze(Y.props),Object.freeze(Y)),Y}function B(Y,Ie,tt,gt,Vt,Et){var dt=Ie.children;if(dt!==void 0)if(gt)if(st(dt)){for(gt=0;gt<dt.length;gt++)te(dt[gt]);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 te(dt);if(Ye.call(Ie,"key")){dt=c(Y);var nt=Object.keys(Ie).filter(function(xe){return xe!=="key"});gt=0<nt.length?"{key: someKey, "+nt.join(": ..., ")+": ...}":"{key: someKey}",et[dt+gt]||(nt=0<nt.length?"{"+nt.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
|
|
18
18
|
let props = %s;
|
|
19
19
|
<%s {...props} />
|
|
20
20
|
React keys must be passed directly to JSX without using spread:
|
|
21
21
|
let props = %s;
|
|
22
|
-
<%s key={someKey} {...props} />`,gt,ct,te,ct),tt[ct+gt]=!0)}if(ct=null,rt!==void 0&&(n(rt),ct=""+rt),C(Me)&&(n(Me.key),ct=""+Me.key),"key"in Me){rt={};for(var Ne in Me)Ne!=="key"&&(rt[Ne]=Me[Ne])}else rt=Me;return ct&&R(rt,typeof Y=="function"?Y.displayName||Y.name||"Unknown":Y),F(Y,ct,rt,f(),Vt,$t)}function re(Y){X(Y)?Y._store&&(Y._store.validated=1):typeof Y=="object"&&Y!==null&&Y.$$typeof===nt&&(Y._payload.status==="fulfilled"?X(Y._payload.value)&&Y._payload.value._store&&(Y._payload.value._store.validated=1):Y._store&&(Y._store.validated=1))}function X(Y){return typeof Y=="object"&&Y!==null&&Y.$$typeof===ae}var ee=pe,ae=Symbol.for("react.transitional.element"),ce=Symbol.for("react.portal"),de=Symbol.for("react.fragment"),Le=Symbol.for("react.strict_mode"),Te=Symbol.for("react.profiler"),le=Symbol.for("react.consumer"),se=Symbol.for("react.context"),fe=Symbol.for("react.forward_ref"),he=Symbol.for("react.suspense"),Be=Symbol.for("react.suspense_list"),me=Symbol.for("react.memo"),nt=Symbol.for("react.lazy"),Ye=Symbol.for("react.activity"),mt=Symbol.for("react.client.reference"),Ge=ee.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Je=Object.prototype.hasOwnProperty,st=Array.isArray,bt=console.createTask?console.createTask:function(){return null};ee={react_stack_bottom_frame:function(Y){return Y()}};var ut,Ze={},De=ee.react_stack_bottom_frame.bind(ee,v)(),Ke=bt(a(v)),tt={};Ks.Fragment=de,Ks.jsx=function(Y,Me,rt){var gt=1e4>Ge.recentlyCreatedOwnerStacks++;return B(Y,Me,rt,!1,gt?Error("react-stack-top-frame"):De,gt?bt(a(Y)):Ke)},Ks.jsxs=function(Y,Me,rt){var gt=1e4>Ge.recentlyCreatedOwnerStacks++;return B(Y,Me,rt,!0,gt?Error("react-stack-top-frame"):De,gt?bt(a(Y)):Ke)}})()),Ks}var hp;function fg(){return hp||(hp=1,process.env.NODE_ENV==="production"?Ei.exports=hg():Ei.exports=pg()),Ei.exports}var sr=fg();const Ar=Object.create(null);Ar.open="0";Ar.close="1";Ar.ping="2";Ar.pong="3";Ar.message="4";Ar.upgrade="5";Ar.noop="6";const Ai=Object.create(null);Object.keys(Ar).forEach(c=>{Ai[Ar[c]]=c});const ho={type:"error",data:"parser error"},Hp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",jp=typeof ArrayBuffer=="function",Kp=c=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(c):c&&c.buffer instanceof ArrayBuffer,$o=({type:c,data:r},n,a)=>Hp&&r instanceof Blob?n?a(r):pp(r,a):jp&&(r instanceof ArrayBuffer||Kp(r))?n?a(r):pp(new Blob([r]),a):a(Ar[c]+(r||"")),pp=(c,r)=>{const n=new FileReader;return n.onload=function(){const a=n.result.split(",")[1];r("b"+(a||""))},n.readAsDataURL(c)};function fp(c){return c instanceof Uint8Array?c:c instanceof ArrayBuffer?new Uint8Array(c):new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let Za;function mg(c,r){if(Hp&&c.data instanceof Blob)return c.data.arrayBuffer().then(fp).then(r);if(jp&&(c.data instanceof ArrayBuffer||Kp(c.data)))return r(fp(c.data));$o(c,!1,n=>{Za||(Za=new TextEncoder),r(Za.encode(n))})}const mp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ni=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let c=0;c<mp.length;c++)ni[mp.charCodeAt(c)]=c;const gg=c=>{let r=c.length*.75,n=c.length,a,f=0,v,C,R,b;c[c.length-1]==="="&&(r--,c[c.length-2]==="="&&r--);const F=new ArrayBuffer(r),B=new Uint8Array(F);for(a=0;a<n;a+=4)v=ni[c.charCodeAt(a)],C=ni[c.charCodeAt(a+1)],R=ni[c.charCodeAt(a+2)],b=ni[c.charCodeAt(a+3)],B[f++]=v<<2|C>>4,B[f++]=(C&15)<<4|R>>2,B[f++]=(R&3)<<6|b&63;return F},yg=typeof ArrayBuffer=="function",xo=(c,r)=>{if(typeof c!="string")return{type:"message",data:Qp(c,r)};const n=c.charAt(0);return n==="b"?{type:"message",data:wg(c.substring(1),r)}:Ai[n]?c.length>1?{type:Ai[n],data:c.substring(1)}:{type:Ai[n]}:ho},wg=(c,r)=>{if(yg){const n=gg(c);return Qp(n,r)}else return{base64:!0,data:c}},Qp=(c,r)=>{switch(r){case"blob":return c instanceof Blob?c:new Blob([c]);case"arraybuffer":default:return c instanceof ArrayBuffer?c:c.buffer}},Xp="",vg=(c,r)=>{const n=c.length,a=new Array(n);let f=0;c.forEach((v,C)=>{$o(v,!1,R=>{a[C]=R,++f===n&&r(a.join(Xp))})})},bg=(c,r)=>{const n=c.split(Xp),a=[];for(let f=0;f<n.length;f++){const v=xo(n[f],r);if(a.push(v),v.type==="error")break}return a};function _g(){return new TransformStream({transform(c,r){mg(c,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))}c.data&&typeof c.data!="string"&&(f[0]|=128),r.enqueue(f),r.enqueue(n)})}})}let eo;function Ci(c){return c.reduce((r,n)=>r+n.length,0)}function ki(c,r){if(c[0].length===r)return c.shift();const n=new Uint8Array(r);let a=0;for(let f=0;f<r;f++)n[f]=c[0][a++],a===c[0].length&&(c.shift(),a=0);return c.length&&a<c[0].length&&(c[0]=c[0].slice(a)),n}function Sg(c,r){eo||(eo=new TextDecoder);const n=[];let a=0,f=-1,v=!1;return new TransformStream({transform(C,R){for(n.push(C);;){if(a===0){if(Ci(n)<1)break;const b=ki(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(Ci(n)<2)break;const b=ki(n,2);f=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(Ci(n)<8)break;const b=ki(n,8),F=new DataView(b.buffer,b.byteOffset,b.length),B=F.getUint32(0);if(B>Math.pow(2,21)-1){R.enqueue(ho);break}f=B*Math.pow(2,32)+F.getUint32(4),a=3}else{if(Ci(n)<f)break;const b=ki(n,f);R.enqueue(xo(v?b:eo.decode(b),r)),a=0}if(f===0||f>c){R.enqueue(ho);break}}}})}const Yp=4;function Ot(c){if(c)return Tg(c)}function Tg(c){for(var r in Ot.prototype)c[r]=Ot.prototype[r];return c}Ot.prototype.on=Ot.prototype.addEventListener=function(c,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+c]=this._callbacks["$"+c]||[]).push(r),this};Ot.prototype.once=function(c,r){function n(){this.off(c,n),r.apply(this,arguments)}return n.fn=r,this.on(c,n),this};Ot.prototype.off=Ot.prototype.removeListener=Ot.prototype.removeAllListeners=Ot.prototype.removeEventListener=function(c,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+c];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+c],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["$"+c],this};Ot.prototype.emit=function(c){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),n=this._callbacks["$"+c],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(c){return this._callbacks=this._callbacks||{},this._callbacks["$"+c]||[]};Ot.prototype.hasListeners=function(c){return!!this.listeners(c).length};const Bi=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,n)=>n(r,0),ir=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),$g="arraybuffer";function Jp(c,...r){return r.reduce((n,a)=>(c.hasOwnProperty(a)&&(n[a]=c[a]),n),{})}const xg=ir.setTimeout,Eg=ir.clearTimeout;function Ni(c,r){r.useNativeTimers?(c.setTimeoutFn=xg.bind(ir),c.clearTimeoutFn=Eg.bind(ir)):(c.setTimeoutFn=ir.setTimeout.bind(ir),c.clearTimeoutFn=ir.clearTimeout.bind(ir))}const Cg=1.33;function kg(c){return typeof c=="string"?Rg(c):Math.ceil((c.byteLength||c.size)*Cg)}function Rg(c){let r=0,n=0;for(let a=0,f=c.length;a<f;a++)r=c.charCodeAt(a),r<128?n+=1:r<2048?n+=2:r<55296||r>=57344?n+=3:(a++,n+=4);return n}function Zp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ag(c){let r="";for(let n in c)c.hasOwnProperty(n)&&(r.length&&(r+="&"),r+=encodeURIComponent(n)+"="+encodeURIComponent(c[n]));return r}function Mg(c){let r={},n=c.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 Ig extends Error{constructor(r,n,a){super(r),this.description=n,this.context=a,this.type="TransportError"}}class Eo extends Ot{constructor(r){super(),this.writable=!1,Ni(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 Ig(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=xo(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=Ag(r);return n.length?"?"+n:""}}class Pg extends Eo{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)};bg(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,vg(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]=Zp()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(r,n)}}let ef=!1;try{ef=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Og=ef;function zg(){}class Dg extends Pg{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 Rr extends Ot{constructor(r,n,a){super(),this.createRequest=r,Ni(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=Jp(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=Rr.requestsCount++,Rr.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=zg,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Rr.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()}}Rr.requestsCount=0;Rr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",gp);else if(typeof addEventListener=="function"){const c="onpagehide"in ir?"pagehide":"unload";addEventListener(c,gp,!1)}}function gp(){for(let c in Rr.requests)Rr.requests.hasOwnProperty(c)&&Rr.requests[c].abort()}const Lg=(function(){const c=tf({xdomain:!1});return c&&c.responseType!==null})();class Bg extends Dg{constructor(r){super(r);const n=r&&r.forceBase64;this.supportsBinary=Lg&&!n}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Rr(tf,this.uri(),r)}}function tf(c){const r=c.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||Og))return new XMLHttpRequest}catch{}if(!r)try{return new ir[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const rf=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Ng extends Eo{get name(){return"websocket"}doOpen(){const r=this.uri(),n=this.opts.protocols,a=rf?{}:Jp(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;$o(a,this.supportsBinary,v=>{try{this.doWrite(a,v)}catch{}f&&Bi(()=>{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]=Zp()),this.supportsBinary||(n.b64=1),this.createUri(r,n)}}const to=ir.WebSocket||ir.MozWebSocket;class Ug extends Ng{createSocket(r,n,a){return rf?new to(r,n,a):n?new to(r,n):new to(r)}doWrite(r,n){this.ws.send(n)}}class Fg extends Eo{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=Sg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(n).getReader(),f=_g();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 C={type:"open"};this.query.sid&&(C.data=`{"sid":"${this.query.sid}"}`),this._writer.write(C).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let n=0;n<r.length;n++){const a=r[n],f=n===r.length-1;this._writer.write(a).then(()=>{f&&Bi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const Vg={websocket:Ug,webtransport:Fg,polling:Bg},Gg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,qg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function po(c){if(c.length>8e3)throw"URI too long";const r=c,n=c.indexOf("["),a=c.indexOf("]");n!=-1&&a!=-1&&(c=c.substring(0,n)+c.substring(n,a).replace(/:/g,";")+c.substring(a,c.length));let f=Gg.exec(c||""),v={},C=14;for(;C--;)v[qg[C]]=f[C]||"";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=Wg(v,v.path),v.queryKey=Hg(v,v.query),v}function Wg(c,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 Hg(c,r){const n={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,v){f&&(n[f]=v)}),n}const fo=typeof addEventListener=="function"&&typeof removeEventListener=="function",Mi=[];fo&&addEventListener("offline",()=>{Mi.forEach(c=>c())},!1);class en extends Ot{constructor(r,n){if(super(),this.binaryType=$g,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=po(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=po(n.host).host);Ni(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=Mg(this.opts.query)),fo&&(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"})},Mi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const n=Object.assign({},this.opts.query);n.EIO=Yp,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&&en.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",en.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+=kg(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,Bi(()=>{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(en.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(),fo&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=Mi.indexOf(this._offlineEventListener);a!==-1&&Mi.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,n),this.writeBuffer=[],this._prevBufferLen=0}}}en.protocol=Yp;class jg extends en{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;en.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;en.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 C=re=>{const X=new Error("probe error: "+re);X.transport=n.name,v(),this.emitReserved("upgradeError",X)};function R(){C("transport closed")}function b(){C("socket closed")}function F(re){n&&re.name!==n.name&&v()}const B=()=>{n.removeListener("open",f),n.removeListener("error",C),n.removeListener("close",R),this.off("close",b),this.off("upgrading",F)};n.once("open",f),n.once("error",C),n.once("close",R),this.once("close",b),this.once("upgrading",F),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 Kg=class extends jg{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=>Vg[f]).filter(f=>!!f)),super(r,a)}};function Qg(c,r="",n){let a=c;n=n||typeof location<"u"&&location,c==null&&(c=n.protocol+"//"+n.host),typeof c=="string"&&(c.charAt(0)==="/"&&(c.charAt(1)==="/"?c=n.protocol+c:c=n.host+c),/^(https?|wss?):\/\//.test(c)||(typeof n<"u"?c=n.protocol+"//"+c:c="https://"+c),a=po(c)),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 Xg=typeof ArrayBuffer=="function",Yg=c=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(c):c.buffer instanceof ArrayBuffer,nf=Object.prototype.toString,Jg=typeof Blob=="function"||typeof Blob<"u"&&nf.call(Blob)==="[object BlobConstructor]",Zg=typeof File=="function"||typeof File<"u"&&nf.call(File)==="[object FileConstructor]";function Co(c){return Xg&&(c instanceof ArrayBuffer||Yg(c))||Jg&&c instanceof Blob||Zg&&c instanceof File}function Ii(c,r){if(!c||typeof c!="object")return!1;if(Array.isArray(c)){for(let n=0,a=c.length;n<a;n++)if(Ii(c[n]))return!0;return!1}if(Co(c))return!0;if(c.toJSON&&typeof c.toJSON=="function"&&arguments.length===1)return Ii(c.toJSON(),!0);for(const n in c)if(Object.prototype.hasOwnProperty.call(c,n)&&Ii(c[n]))return!0;return!1}function ey(c){const r=[],n=c.data,a=c;return a.data=mo(n,r),a.attachments=r.length,{packet:a,buffers:r}}function mo(c,r){if(!c)return c;if(Co(c)){const n={_placeholder:!0,num:r.length};return r.push(c),n}else if(Array.isArray(c)){const n=new Array(c.length);for(let a=0;a<c.length;a++)n[a]=mo(c[a],r);return n}else if(typeof c=="object"&&!(c instanceof Date)){const n={};for(const a in c)Object.prototype.hasOwnProperty.call(c,a)&&(n[a]=mo(c[a],r));return n}return c}function ty(c,r){return c.data=go(c.data,r),delete c.attachments,c}function go(c,r){if(!c)return c;if(c&&c._placeholder===!0){if(typeof c.num=="number"&&c.num>=0&&c.num<r.length)return r[c.num];throw new Error("illegal attachments")}else if(Array.isArray(c))for(let n=0;n<c.length;n++)c[n]=go(c[n],r);else if(typeof c=="object")for(const n in c)Object.prototype.hasOwnProperty.call(c,n)&&(c[n]=go(c[n],r));return c}const ry=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var at;(function(c){c[c.CONNECT=0]="CONNECT",c[c.DISCONNECT=1]="DISCONNECT",c[c.EVENT=2]="EVENT",c[c.ACK=3]="ACK",c[c.CONNECT_ERROR=4]="CONNECT_ERROR",c[c.BINARY_EVENT=5]="BINARY_EVENT",c[c.BINARY_ACK=6]="BINARY_ACK"})(at||(at={}));class ny{constructor(r){this.replacer=r}encode(r){return(r.type===at.EVENT||r.type===at.ACK)&&Ii(r)?this.encodeAsBinary({type:r.type===at.EVENT?at.BINARY_EVENT:at.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let n=""+r.type;return(r.type===at.BINARY_EVENT||r.type===at.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=ey(r),a=this.encodeAsString(n.packet),f=n.buffers;return f.unshift(a),f}}class ko 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===at.BINARY_EVENT;a||n.type===at.BINARY_ACK?(n.type=a?at.EVENT:at.ACK,this.reconstructor=new sy(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(Co(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(at[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===at.BINARY_EVENT||a.type===at.BINARY_ACK){const v=n+1;for(;r.charAt(++n)!=="-"&&n!=r.length;);const C=r.substring(v,n);if(C!=Number(C)||r.charAt(n)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!iy(R)||R<0)throw new Error("Illegal attachments");if(R>this.opts.maxAttachments)throw new Error("too many attachments");a.attachments=R}if(r.charAt(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 C=r.charAt(n);if(C==null||Number(C)!=C){--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(ko.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 at.CONNECT:return yp(n);case at.DISCONNECT:return n===void 0;case at.CONNECT_ERROR:return typeof n=="string"||yp(n);case at.EVENT:case at.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&ry.indexOf(n[0])===-1);case at.ACK:case at.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class sy{constructor(r){this.packet=r,this.buffers=[],this.reconPack=r}takeBinaryData(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){const n=ty(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const iy=Number.isInteger||function(c){return typeof c=="number"&&isFinite(c)&&Math.floor(c)===c};function yp(c){return Object.prototype.toString.call(c)==="[object Object]"}const ay=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ko,Encoder:ny,get PacketType(){return at}},Symbol.toStringTag,{value:"Module"}));function vr(c,r,n){return c.on(r,n),function(){c.off(r,n)}}const oy=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class sf 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=[vr(r,"open",this.onopen.bind(this)),vr(r,"packet",this.onpacket.bind(this)),vr(r,"error",this.onerror.bind(this)),vr(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(oy.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 C={type:at.EVENT,data:n};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const B=this.ids++,re=n.pop();this._registerAckCallback(B,re),C.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(C),this.packet(C)):this.sendBuffer.push(C)),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),C=(...R)=>{this.io.clearTimeoutFn(v),n.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...n){return new Promise((a,f)=>{const v=(C,R)=>C?f(C):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:at.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 at.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 at.EVENT:case at.BINARY_EVENT:this.onevent(r);break;case at.ACK:case at.BINARY_ACK:this.onack(r);break;case at.DISCONNECT:this.ondisconnect();break;case at.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:at.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:at.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 ts(c){c=c||{},this.ms=c.min||100,this.max=c.max||1e4,this.factor=c.factor||2,this.jitter=c.jitter>0&&c.jitter<=1?c.jitter:0,this.attempts=0}ts.prototype.duration=function(){var c=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),n=Math.floor(r*this.jitter*c);c=(Math.floor(r*10)&1)==0?c-n:c+n}return Math.min(c,this.max)|0};ts.prototype.reset=function(){this.attempts=0};ts.prototype.setMin=function(c){this.ms=c};ts.prototype.setMax=function(c){this.max=c};ts.prototype.setJitter=function(c){this.jitter=c};class yo 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,Ni(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 ts({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||ay;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 Kg(this.uri,this.opts);const n=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const f=vr(n,"open",function(){a.onopen(),r&&r()}),v=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=vr(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(C),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(vr(r,"ping",this.onping.bind(this)),vr(r,"data",this.ondata.bind(this)),vr(r,"error",this.onerror.bind(this)),vr(r,"close",this.onclose.bind(this)),vr(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){Bi(()=>{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 sf(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 Qs={};function Pi(c,r){typeof c=="object"&&(r=c,c=void 0),r=r||{};const n=Qg(c,r.path||"/socket.io"),a=n.source,f=n.id,v=n.path,C=Qs[f]&&v in Qs[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let b;return R?b=new yo(a,r):(Qs[f]||(Qs[f]=new yo(a,r)),b=Qs[f]),n.query&&!r.query&&(r.query=n.queryKey),b.socket(n.path,r)}Object.assign(Pi,{Manager:yo,Socket:sf,io:Pi,connect:Pi});const ly=c=>{if(window.audioCtx=c,c.state!=="suspended")return;const r=document.body,n=["touchstart","touchend","mousedown","keydown"];n.forEach(v=>r.addEventListener(v,a,!1));function a(){c.resume().then(f)}function f(){n.forEach(v=>r.removeEventListener(v,a))}};function Ft(c){this.init(c)}Ft.prototype.init=function(c){var r={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},r,c),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};Ft.prototype.getMaxValue=function(){var c={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return c[this.option.encoding]?c[this.option.encoding]:c["16bitInt"]};Ft.prototype.getTypedArray=function(){var c={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return c[this.option.encoding]?c[this.option.encoding]:c["16bitInt"]};Ft.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),ly(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Ft.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};Ft.prototype.isTypedArray=function(c){return c.byteLength&&c.buffer&&c.buffer.constructor==ArrayBuffer};Ft.prototype.feed=function(c){if(this.isTypedArray(c)){c=this.getFormatedValue(c);var r=new Float32Array(this.samples.length+c.length);r.set(this.samples,0),r.set(c,this.samples.length),this.samples=r,this.timeout||this.flush()}};Ft.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};Ft.prototype.volume=function(c){this.gainNode.gain.value=c};Ft.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Ft.prototype.getTimestamp=function(c){if(this.playingStartTime>=0){if(!c)return this.audioCtx.currentTime-this.playingStartTime;const r=this.lastGotTimestamp;return this.lastGotTimestamp+=c/1e3,r}return 0};Ft.prototype.setRequestStop=function(){this.flag_request_stop=!0};Ft.prototype.setOnEnd=function(c){this.onEnd=c};Ft.prototype.interrupt=function(c){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};Ft.prototype.ensuredSetTimeout=(function(){let c;return function(r,n){c=performance.now();const a=f=>{f-c>=n?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Ft.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Ft.prototype.flush=function(){if(this.samples.length){var c=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,n=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,f,v,C,R;for(f=0;f<this.option.channels;f++)for(a=n.getChannelData(f),v=f,R=50,C=0;C<r;C++)a[C]=this.samples[v],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),v+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,c.buffer=n,c.connect(this.gainNode),c.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=c,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=n.duration,this.flag_request_stop)this.flag_request_stop=!1,c.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const b=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,b-50)}}};const Fr={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},dt={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",REFRESH_SESSION_ACTIVITY:"refresh_session_activity",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"},Dt={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",FAILED:"failed",ENDED:"ended"},Kt={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},wp={enabled:!0,maxAttempts:8,initialDelayMs:500,maxDelayMs:5e3,timeoutMs:8e3},uy={encoding:"16bitInt",channels:1,sampleRate:16e3},dy=c=>new Promise(r=>setTimeout(r,c)),cy=c=>{if(!c)return null;if(c instanceof Uint8Array)return c;if(c instanceof ArrayBuffer)return new Uint8Array(c);if(c?.buffer instanceof ArrayBuffer)return new Uint8Array(c.buffer);if(typeof c=="object"&&c.type==="Buffer"&&Array.isArray(c.data))return new Uint8Array(c.data);try{return new Uint8Array(c)}catch{return null}},hy=c=>String(c||"").toLowerCase().replaceAll("-","_"),py=()=>{const c=new Map;return{addChunk:(f,v)=>{const C=f||`request-${Date.now()}`,b=`${c.get(C)||""}${v||""}`;return c.set(C,b),{id:C,text:b}},consume:(f,v="")=>{const C=f||`request-${Date.now()}`,R=c.get(C)||v||"";return c.delete(C),{id:C,text:R}},clear:()=>{c.clear()}}},af=pe.createContext(null),fy={connectionState:Dt.IDLE,isConnected:!1,isSessionReady:!1,error:null,reconnectAttempt:0,isAudioPlaying:!1,isAvatarSpeaking:!1,cloudStream:{state:Kt.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[]},my=(c,r)=>{const n=new Ft(c),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},vp=async c=>{if(!c?.ok){let r=`HTTP ${c.status}`;try{const n=await c.json();r=n?.detail||n?.message||r}catch{}throw new Error(r)}return c.json()};function of({children:c,wsUrl:r,restUrl:n,reconnectOptions:a,enableAudio:f=!0,pcmOptions:v,debug:C=!1}){const[R,b]=pe.useState(fy),F=pe.useRef(null),B=pe.useRef(null),re=pe.useRef(!1),X=pe.useRef(!1),ee=pe.useRef({...wp,...a}),ae=pe.useRef(py()),ce=pe.useRef(null),de=pe.useRef(!1),Le=pe.useRef(null);pe.useEffect(()=>{ee.current={...wp,...a}},[a]);const Te=pe.useCallback((...te)=>{C&&console.log("[RqmiiSDK]",...te)},[C]),le=pe.useCallback(te=>{b(Ne=>({...Ne,connectionState:te,isConnected:te===Dt.CONNECTED}))},[]),se=pe.useCallback(te=>{b(Ne=>({...Ne,error:te?String(te):null}))},[]),fe=pe.useCallback(()=>{if(!f||ce.current)return ce.current;const te={...uy,...v||{}};return ce.current=my(te,()=>{b(Ne=>({...Ne,isAudioPlaying:!1}))}),ce.current},[f,v]),he=pe.useCallback(()=>{if(ce.current){try{ce.current.interrupt?.(),ce.current.destroy?.()}catch{}ce.current=null}},[]),Be=pe.useCallback(async()=>{const te=fe();if(te)try{te.audioCtx?.state==="suspended"&&await te.audioCtx.resume()}catch(Ne){Te("audio resume failed",Ne)}},[fe,Te]),me=pe.useCallback(te=>{Le.current=te||null},[]),nt=pe.useCallback((te,Ne=null)=>{b(He=>({...He,cloudStream:{state:te,error:Ne?String(Ne):null}}))},[]),Ye=pe.useCallback(()=>{if(F.current){try{F.current.removeAllListeners(),F.current.disconnect()}catch{}F.current=null}},[]),mt=pe.useCallback(({keepManualDisconnect:te=!1}={})=>{X.current=!0,B.current=null,re.current=!1,de.current=!1,ae.current.clear(),he(),Ye(),te||(X.current=!1),b(Ne=>({...Ne,connectionState:Dt.IDLE,isConnected:!1,isSessionReady:!1,reconnectAttempt:0,isAudioPlaying:!1,isAvatarSpeaking:!1,error:null,transcript:null,partialTranscript:null,cloudStream:{state:Kt.IDLE,error:null},session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[]}))},[Ye,he]),Ge=pe.useCallback(te=>{!te?.sessionId||!te?.reconnectToken||!te?.role||(B.current={sessionId:te.sessionId,reconnectToken:te.reconnectToken,role:te.role},b(Ne=>({...Ne,session:{...Ne.session,sessionId:te.sessionId,role:te.role}})))},[]),Je=pe.useCallback((te,{isReconnect:Ne=!1,resolve:He,reject:Lt}={})=>{const xt=(be,Ue)=>{be&&be(Ue)};te.on(dt.CONNECT,()=>{Te("socket connected"),se(null),Ne||(le(Dt.CONNECTED),xt(He))}),te.on(dt.CONNECT_ERROR,be=>{Te("socket connect_error",be),Ne||(le(Dt.FAILED),se(be?.message||"Connection error"),xt(Lt,be))}),te.on(dt.DISCONNECT,be=>{Te("socket disconnected",be),b(Ue=>({...Ue,isConnected:!1,isSessionReady:!1})),!X.current&&(ee.current.enabled?le(Dt.RECONNECTING):(le(Dt.FAILED),se("Connection lost")))}),te.on(dt.SESSION_READY,be=>{b(Ue=>({...Ue,isSessionReady:!0,error:null,session:{...Ue.session,agentType:hy(be?.agentType||Ue.session.agentType)}}))}),te.on(dt.SESSION_JOINED,()=>{b(be=>({...be,isSessionReady:!0,error:null}))}),te.on(dt.SESSION_TERMINATED,()=>{le(Dt.ENDED),b(be=>({...be,isSessionReady:!1}))}),te.on(dt.TRANSCRIPT,be=>{b(Ue=>({...Ue,transcript:be||null}))}),te.on(dt.PARTIAL_TRANSCRIPT,be=>{b(Ue=>({...Ue,partialTranscript:be||null}))}),te.on(dt.AGENT_RESPONSE_CHUNK,be=>{const{id:Ue,text:it}=ae.current.addChunk(be?.requestId,be?.text);b(ht=>{const Mt=ht.messages.filter(Mr=>Mr.id!==Ue);return{...ht,messages:[...Mt,{id:Ue,role:"assistant",text:it,streaming:!0,timestamp:new Date().toISOString()}]}})}),te.on(dt.AGENT_RESPONSE,be=>{const{id:Ue,text:it}=ae.current.consume(be?.requestId,be?.text);b(ht=>{const Mt=ht.messages.filter(Mr=>Mr.id!==Ue);return{...ht,messages:[...Mt,{id:Ue,role:"assistant",text:it,streaming:!1,timestamp:new Date().toISOString()}]}})}),te.on(dt.AVATAR_SPEAKING,()=>{b(be=>({...be,isAvatarSpeaking:!0}))}),te.on(dt.AVATAR_SPEAKING_DONE,()=>{b(be=>({...be,isAvatarSpeaking:!1}))}),te.on(dt.AGENT_AUDIO_CHUNK,be=>{if(!f||de.current||R.session.agentType===Fr.CLOUD_AVATAR||R.session.agentType===Fr.DESKTOP_AVATAR)return;const Ue=cy(be?.audio);if(!Ue)return;const it=fe();if(it)try{it.feed(Ue),b(ht=>({...ht,isAudioPlaying:!0}))}catch(ht){Te("feed pcm failed",ht)}}),te.on(dt.AGENT_AUDIO_COMPLETE,()=>{if(!(!f||!ce.current)&&!(R.session.agentType===Fr.CLOUD_AVATAR||R.session.agentType===Fr.DESKTOP_AVATAR))try{ce.current.setRequestStop()}catch{b(be=>({...be,isAudioPlaying:!1}))}}),te.on(dt.INTERRUPTED,()=>{de.current=!1,he(),b(be=>({...be,isAudioPlaying:!1}))}),te.on(dt.RECONNECT_CREDENTIAL,be=>{Te("received reconnect credential"),Ge(be)}),te.on(dt.RECONNECT_SUCCESS,be=>{Ge(be),b(Ue=>({...Ue,reconnectAttempt:0})),re.current=!1,le(Dt.CONNECTED)}),te.on(dt.RECONNECT_FAILED,be=>{Te("reconnect failed",be),le(Dt.FAILED),se(be?.reason||"Reconnect failed")}),te.on(dt.AUTH_ERROR,be=>{le(Dt.FAILED),se(be?.message||"Authentication error")}),te.on(dt.ERROR,be=>{if(be?.code==="TTS_ERROR"){Te("non-fatal TTS error",be);return}se(be?.message||be?.detail||"Server error")})},[he,f,fe,Ge,Te,le,se,R.session.agentType]),st=pe.useCallback(({authPayload:te,queryToken:Ne,expectReconnectSuccess:He=!1})=>new Promise((Lt,xt)=>{Ye();const be=Pi(r,{transports:["websocket","polling"],timeout:2e4,reconnection:!1,auth:te,query:Ne?{token:Ne}:void 0});if(F.current=be,Je(be,{isReconnect:He,resolve:Lt,reject:xt}),He){const Ue=()=>{be.off(dt.RECONNECT_FAILED,it),Lt()},it=ht=>{be.off(dt.RECONNECT_SUCCESS,Ue),xt(new Error(ht?.reason||"Reconnect failed"))};be.once(dt.RECONNECT_SUCCESS,Ue),be.once(dt.RECONNECT_FAILED,it),setTimeout(()=>{be.off(dt.RECONNECT_SUCCESS,Ue),be.off(dt.RECONNECT_FAILED,it),xt(new Error("Reconnect timed out"))},ee.current.timeoutMs)}}),[Ye,Je,r]),bt=pe.useCallback(async()=>{if(re.current)return;const te=B.current;if(!te){le(Dt.FAILED),se("Reconnect token unavailable. Please initialize a new session.");return}re.current=!0;for(let Ne=1;Ne<=ee.current.maxAttempts;Ne+=1){if(X.current){re.current=!1;return}b(He=>({...He,reconnectAttempt:Ne}));try{await st({authPayload:{reconnectToken:te.reconnectToken,sessionId:te.sessionId,role:te.role},expectReconnectSuccess:!0}),re.current=!1;return}catch(He){Te(`reconnect attempt ${Ne} failed`,He);const Lt=Math.min(ee.current.maxDelayMs,ee.current.initialDelayMs*2**(Ne-1));await dy(Lt)}}re.current=!1,le(Dt.FAILED),se("Reconnect window expired. Please initialize a new session.")},[st,Te,le,se]);pe.useEffect(()=>{R.connectionState===Dt.RECONNECTING&&ee.current.enabled&&bt()},[R.connectionState,bt]);const ut=pe.useCallback(async({apiKey:te,publicChatId:Ne,agentId:He,language:Lt="en"}={})=>{if(!n)throw new Error("Missing restUrl in RqmiiAgentProvider");if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!te&&!Ne&&!He)throw new Error("Provide one of apiKey, publicChatId, or agentId");mt(),le(Dt.INITIALIZING),se(null);const xt={...te?{api_key:te}:{},...Ne?{public_chat_id:Ne}:{},...He?{agent_id:He}:{},language:Lt},be=await fetch(`${n}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(xt)}).then(vp),Ue=be?.session_id||null,it=be?.session_token;if(!Ue||!it)throw new Error("Invalid initialize session response");return b(ht=>({...ht,session:{...ht.session,sessionId:Ue,agentType:be?.streaming_url?Fr.CLOUD_AVATAR:ht.session.agentType,streamingUrl:be?.streaming_url||null,uniqueId:be?.unique_id||null,role:null}})),le(Dt.CONNECTING),be?.streaming_url?nt(Kt.CONNECTING):nt(Kt.IDLE),await st({authPayload:{token:it},queryToken:it}),be},[st,mt,n,nt,le,se,r]),Ze=pe.useCallback(async({uniqueId:te})=>{if(!n)throw new Error("Missing restUrl in RqmiiAgentProvider");if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!te)throw new Error("uniqueId is required");mt(),le(Dt.INITIALIZING),se(null);const Ne=await fetch(`${n}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:te})}).then(vp),He=Ne?.session_id||null,Lt=Ne?.session_token;if(!He||!Lt)throw new Error("Invalid join session response");return b(xt=>({...xt,session:{...xt.session,sessionId:He,uniqueId:te,role:"user",agentType:Fr.DESKTOP_AVATAR}})),le(Dt.CONNECTING),nt(Kt.IDLE),await st({authPayload:{token:Lt},queryToken:Lt}),Ne},[st,mt,n,nt,le,se,r]),De=pe.useCallback(()=>{mt({keepManualDisconnect:!0})},[mt]),Ke=pe.useCallback((te,Ne={})=>!F.current||!R.isConnected?!1:(F.current.emit(te,Ne),!0),[R.isConnected]),tt=pe.useCallback(te=>{if(!te||!String(te).trim())return!1;const Ne={id:`user-${Date.now()}`,role:"user",text:String(te),timestamp:new Date().toISOString()};return b(He=>({...He,messages:[...He.messages,Ne]})),Ke(dt.USER_MESSAGE,{message:String(te)})},[Ke]),Y=pe.useCallback(te=>Ke(dt.AUDIO_CHUNK,{audio:te}),[Ke]),Me=pe.useCallback(()=>Ke(dt.AUDIO_END,{}),[Ke]),rt=pe.useCallback(()=>(de.current=!0,he(),b(te=>({...te,isAudioPlaying:!1})),Ke(dt.INTERRUPT,{})),[he,Ke]),gt=pe.useCallback(()=>Ke(dt.REFRESH_SESSION_ACTIVITY,{}),[Ke]),Vt=pe.useCallback(()=>Ke(dt.CLEAR_SESSION_HISTORY,{}),[Ke]),$t=pe.useCallback(()=>{ae.current.clear(),b(te=>({...te,messages:[]}))},[]);pe.useEffect(()=>()=>{X.current=!0,Ye(),he()},[Ye,he]);const ct=pe.useMemo(()=>({...R,initializeSession:ut,joinDesktopSession:Ze,disconnect:De,emit:Ke,sendTextMessage:tt,sendAudioChunk:Y,endAudioStream:Me,interrupt:rt,refreshSessionActivity:gt,clearSessionHistory:Vt,clearMessages:$t,resumeAudioPlayback:Be,attachAudioElement:me,setCloudStreamState:nt,audioElement:Le.current,socket:F.current}),[me,$t,Vt,De,Ke,Me,ut,rt,Ze,gt,Be,Y,tt,nt,R]);return sr.jsx(af.Provider,{value:ct,children:c})}const Gr=()=>{const c=pe.useContext(af);if(!c)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return c},gy=["Cannot read properties of null (reading 'state')","MicVAD has null stream"],bp=c=>c?gy.some(r=>String(c).includes(r)):!1;function lf(){typeof window>"u"||window.__rqmiiAudioErrorSuppressorsInstalled||(window.__rqmiiAudioErrorSuppressorsInstalled=!0,window.addEventListener("error",c=>{if(bp(c?.message))return c.preventDefault(),!0}),window.addEventListener("unhandledrejection",c=>{const r=c?.reason?.message||String(c?.reason||"");bp(r)&&c.preventDefault()}))}lf();const yy={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,sampleRate:16e3},wy=["audio/webm;codecs=opus","audio/webm","audio/mp4"],vy=()=>typeof window>"u"||!window.MediaRecorder?.isTypeSupported?"":wy.find(c=>window.MediaRecorder.isTypeSupported(c))||"";function by(c={}){const{onAudioChunk:r,onAudioEnd:n,onError:a,holdDelayMs:f=220,timesliceMs:v=100,interruptOnHoldStart:C=!0,audioConstraints:R=yy}=c,{sendAudioChunk:b,endAudioStream:F,interrupt:B}=Gr(),re=pe.useRef(null),X=pe.useRef(null),ee=pe.useRef(null),ae=pe.useRef(!0),[ce,de]=pe.useState(!1),[Le,Te]=pe.useState(!1),[le,se]=pe.useState(null),fe=pe.useCallback(async Ge=>{if(!Ge||Ge.size<=0)return;const Je=await Ge.arrayBuffer();if(r){r(Je);return}b(Je)},[r,b]),he=pe.useCallback(()=>{X.current&&(X.current.getTracks().forEach(Ge=>Ge.stop()),X.current=null)},[]),Be=pe.useCallback(({discard:Ge=!1}={})=>{const Je=re.current;if(!Je)return!1;if(ae.current=!Ge,re.current=null,Je.state==="inactive")return Ge||(n?n():F()),he(),Te(!1),!0;try{Je.requestData()}catch{}Je.onstop=()=>{ae.current&&(n?n():F()),he(),Te(!1)};try{Je.stop()}catch(st){he(),Te(!1),a?.(st)}return!0},[he,F,n,a]),me=pe.useCallback(async()=>{if(re.current)return!0;if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||typeof window>"u"||typeof window.MediaRecorder>"u"){const Ge=new Error("MediaRecorder or microphone APIs are unavailable in this browser");return se(Ge.message),a?.(Ge),!1}try{const Ge=await navigator.mediaDevices.getUserMedia({audio:R});X.current=Ge;const Je=vy(),st=Je?{mimeType:Je}:void 0,bt=new window.MediaRecorder(Ge,st);return bt.ondataavailable=ut=>{fe(ut.data)},bt.onerror=ut=>{const Ze=ut?.error||new Error("Microphone recording failed");se(Ze?.message||"recording_failed"),a?.(Ze)},re.current=bt,Te(!0),se(null),bt.start(v),!0}catch(Ge){return he(),Te(!1),se("permission_denied"),a?.(Ge),!1}},[R,he,fe,a,v]),nt=pe.useCallback(()=>{ee.current&&(clearTimeout(ee.current),ee.current=null),de(!0),ee.current=setTimeout(()=>{C&&B(),me()},f)},[f,B,C,me]),Ye=pe.useCallback(()=>{de(!1),ee.current&&(clearTimeout(ee.current),ee.current=null),Be()},[Be]);pe.useEffect(()=>()=>{ee.current&&(clearTimeout(ee.current),ee.current=null),Be({discard:!0}),he()},[he,Be]);const mt=pe.useMemo(()=>({onPointerDown:Ge=>{Ge.preventDefault(),nt()},onPointerUp:Ge=>{Ge.preventDefault(),Ye()},onPointerCancel:Ge=>{Ge.preventDefault(),Ye()},onPointerLeave:Ge=>{Ge.preventDefault(),Ye()}}),[nt,Ye]);return{isPressing:ce,isRecording:Le,micError:le,startRecording:me,stopRecording:Be,startPress:nt,stopPress:Ye,eventHandlers:mt}}var ro={},no={},Xs={},_p;function uf(){if(_p)return Xs;_p=1,Object.defineProperty(Xs,"__esModule",{value:!0}),Xs.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(/\/[^/]+$/,"/")),Xs.baseAssetPath=n,Xs}var Ys={},Sp;function Ro(){if(Sp)return Ys;Sp=1,Object.defineProperty(Ys,"__esModule",{value:!0}),Ys.defaultModelFetcher=void 0;const c=r=>fetch(r).then(n=>n.arrayBuffer());return Ys.defaultModelFetcher=c,Ys}var Br={},Js={},Tp;function ai(){if(Tp)return Js;Tp=1,Object.defineProperty(Js,"__esModule",{value:!0}),Js.log=void 0;const c=r=>n=>{console.log(`VAD | ${r} >`,n)};return Js.log={error:c("error"),debug:c("debug"),warn:c("warn")},Js}var Zs={},$p;function Ui(){if($p)return Zs;$p=1,Object.defineProperty(Zs,"__esModule",{value:!0}),Zs.Message=void 0;var c;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"})(c||(Zs.Message=c={})),Zs}var xp;function Ao(){if(xp)return Br;xp=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.FrameProcessor=Br.validateOptions=Br.defaultFrameProcessorOptions=void 0;const c=ai(),r=Ui();Br.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function n(C){(C.positiveSpeechThreshold<0||C.positiveSpeechThreshold>1)&&c.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(C.negativeSpeechThreshold<0||C.negativeSpeechThreshold>C.positiveSpeechThreshold)&&c.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),C.preSpeechPadMs<0&&c.log.error("preSpeechPadMs should be positive"),C.redemptionMs<0&&c.log.error("redemptionMs should be positive"),C.minSpeechMs<0&&c.log.error("minSpeechMs should be positive")}Br.validateOptions=n;const a=C=>{const R=C.reduce((F,B)=>(F.push(F.at(-1)+B.length),F),[0]),b=new Float32Array(R.at(-1));return C.forEach((F,B)=>{const re=R[B];b.set(F,re)}),b};function f(C,R){const b=Math.floor(C.redemptionMs/R),F=Math.floor(C.preSpeechPadMs/R),B=Math.floor(C.minSpeechMs/R);return{redemptionFrames:b,preSpeechPadFrames:F,minSpeechFrames:B}}class v{constructor(R,b,F,B){this.modelProcessFunc=R,this.modelResetFunc=b,this.options=F,this.msPerFrame=B,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=ae=>{this.options={...this.options,...ae};const{redemptionFrames:ce,preSpeechPadFrames:de,minSpeechFrames:Le}=f(this.options,this.msPerFrame);this.redemptionFrames=ce,this.preSpeechPadFrames=de,this.minSpeechFrames=Le},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=ae=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(ae):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=ae=>{const ce=this.audioBuffer;this.audioBuffer=[];const de=this.speaking;if(this.reset(),de)if(ce.reduce((Te,le)=>le.isSpeech?Te+1:Te,0)>=this.minSpeechFrames){const Te=a(ce.map(le=>le.frame));ae({msg:r.Message.SpeechEnd,audio:Te})}else ae({msg:r.Message.VADMisfire});return{}},this.process=async(ae,ce)=>{if(!this.active)return;const de=await this.modelProcessFunc(ae),Le=de.isSpeech>=this.options.positiveSpeechThreshold;if(ce({probs:de,msg:r.Message.FrameProcessed,frame:ae}),this.audioBuffer.push({frame:ae,isSpeech:Le}),Le&&(this.speechFrameCount++,this.redemptionCounter=0),Le&&!this.speaking&&(this.speaking=!0,ce({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,ce({msg:r.Message.SpeechRealStart})),de.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const Te=this.audioBuffer;if(this.audioBuffer=[],Te.reduce((se,fe)=>fe.isSpeech?se+1:se,0)>=this.minSpeechFrames){const se=a(Te.map(fe=>fe.frame));ce({msg:r.Message.SpeechEnd,audio:se})}else ce({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:ee}=f(this.options,this.msPerFrame);this.redemptionFrames=re,this.preSpeechPadFrames=X,this.minSpeechFrames=ee,this.reset()}}return Br.FrameProcessor=v,Br}var Nr={};function ar(c){throw new Error('Could not dynamically require "'+c+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var so={exports:{}};/*!
|
|
22
|
+
<%s key={someKey} {...props} />`,gt,dt,nt,dt),et[dt+gt]=!0)}if(dt=null,tt!==void 0&&(n(tt),dt=""+tt),C(Ie)&&(n(Ie.key),dt=""+Ie.key),"key"in Ie){tt={};for(var de in Ie)de!=="key"&&(tt[de]=Ie[de])}else tt=Ie;return dt&&R(tt,typeof Y=="function"?Y.displayName||Y.name||"Unknown":Y),U(Y,dt,tt,f(),Vt,Et)}function te(Y){Q(Y)?Y._store&&(Y._store.validated=1):typeof Y=="object"&&Y!==null&&Y.$$typeof===rt&&(Y._payload.status==="fulfilled"?Q(Y._payload.value)&&Y._payload.value._store&&(Y._payload.value._store.validated=1):Y._store&&(Y._store.validated=1))}function Q(Y){return typeof Y=="object"&&Y!==null&&Y.$$typeof===ie}var ee=he,ie=Symbol.for("react.transitional.element"),ce=Symbol.for("react.portal"),ue=Symbol.for("react.fragment"),Be=Symbol.for("react.strict_mode"),Te=Symbol.for("react.profiler"),oe=Symbol.for("react.consumer"),ne=Symbol.for("react.context"),me=Symbol.for("react.forward_ref"),pe=Symbol.for("react.suspense"),Ne=Symbol.for("react.suspense_list"),ge=Symbol.for("react.memo"),rt=Symbol.for("react.lazy"),Xe=Symbol.for("react.activity"),ft=Symbol.for("react.client.reference"),Ge=ee.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Ye=Object.prototype.hasOwnProperty,st=Array.isArray,bt=console.createTask?console.createTask:function(){return null};ee={react_stack_bottom_frame:function(Y){return Y()}};var ut,Je={},Le=ee.react_stack_bottom_frame.bind(ee,v)(),qe=bt(a(v)),et={};Ks.Fragment=ue,Ks.jsx=function(Y,Ie,tt){var gt=1e4>Ge.recentlyCreatedOwnerStacks++;return B(Y,Ie,tt,!1,gt?Error("react-stack-top-frame"):Le,gt?bt(a(Y)):qe)},Ks.jsxs=function(Y,Ie,tt){var gt=1e4>Ge.recentlyCreatedOwnerStacks++;return B(Y,Ie,tt,!0,gt?Error("react-stack-top-frame"):Le,gt?bt(a(Y)):qe)}})()),Ks}var hp;function fg(){return hp||(hp=1,process.env.NODE_ENV==="production"?Ei.exports=hg():Ei.exports=pg()),Ei.exports}var sr=fg();const Ar=Object.create(null);Ar.open="0";Ar.close="1";Ar.ping="2";Ar.pong="3";Ar.message="4";Ar.upgrade="5";Ar.noop="6";const Ai=Object.create(null);Object.keys(Ar).forEach(c=>{Ai[Ar[c]]=c});const ho={type:"error",data:"parser error"},Hp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",jp=typeof ArrayBuffer=="function",Kp=c=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(c):c&&c.buffer instanceof ArrayBuffer,$o=({type:c,data:r},n,a)=>Hp&&r instanceof Blob?n?a(r):pp(r,a):jp&&(r instanceof ArrayBuffer||Kp(r))?n?a(r):pp(new Blob([r]),a):a(Ar[c]+(r||"")),pp=(c,r)=>{const n=new FileReader;return n.onload=function(){const a=n.result.split(",")[1];r("b"+(a||""))},n.readAsDataURL(c)};function fp(c){return c instanceof Uint8Array?c:c instanceof ArrayBuffer?new Uint8Array(c):new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let Za;function mg(c,r){if(Hp&&c.data instanceof Blob)return c.data.arrayBuffer().then(fp).then(r);if(jp&&(c.data instanceof ArrayBuffer||Kp(c.data)))return r(fp(c.data));$o(c,!1,n=>{Za||(Za=new TextEncoder),r(Za.encode(n))})}const mp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ni=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let c=0;c<mp.length;c++)ni[mp.charCodeAt(c)]=c;const gg=c=>{let r=c.length*.75,n=c.length,a,f=0,v,C,R,_;c[c.length-1]==="="&&(r--,c[c.length-2]==="="&&r--);const U=new ArrayBuffer(r),B=new Uint8Array(U);for(a=0;a<n;a+=4)v=ni[c.charCodeAt(a)],C=ni[c.charCodeAt(a+1)],R=ni[c.charCodeAt(a+2)],_=ni[c.charCodeAt(a+3)],B[f++]=v<<2|C>>4,B[f++]=(C&15)<<4|R>>2,B[f++]=(R&3)<<6|_&63;return U},yg=typeof ArrayBuffer=="function",xo=(c,r)=>{if(typeof c!="string")return{type:"message",data:Qp(c,r)};const n=c.charAt(0);return n==="b"?{type:"message",data:wg(c.substring(1),r)}:Ai[n]?c.length>1?{type:Ai[n],data:c.substring(1)}:{type:Ai[n]}:ho},wg=(c,r)=>{if(yg){const n=gg(c);return Qp(n,r)}else return{base64:!0,data:c}},Qp=(c,r)=>{switch(r){case"blob":return c instanceof Blob?c:new Blob([c]);case"arraybuffer":default:return c instanceof ArrayBuffer?c:c.buffer}},Xp="",vg=(c,r)=>{const n=c.length,a=new Array(n);let f=0;c.forEach((v,C)=>{$o(v,!1,R=>{a[C]=R,++f===n&&r(a.join(Xp))})})},_g=(c,r)=>{const n=c.split(Xp),a=[];for(let f=0;f<n.length;f++){const v=xo(n[f],r);if(a.push(v),v.type==="error")break}return a};function bg(){return new TransformStream({transform(c,r){mg(c,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))}c.data&&typeof c.data!="string"&&(f[0]|=128),r.enqueue(f),r.enqueue(n)})}})}let eo;function Ci(c){return c.reduce((r,n)=>r+n.length,0)}function ki(c,r){if(c[0].length===r)return c.shift();const n=new Uint8Array(r);let a=0;for(let f=0;f<r;f++)n[f]=c[0][a++],a===c[0].length&&(c.shift(),a=0);return c.length&&a<c[0].length&&(c[0]=c[0].slice(a)),n}function Sg(c,r){eo||(eo=new TextDecoder);const n=[];let a=0,f=-1,v=!1;return new TransformStream({transform(C,R){for(n.push(C);;){if(a===0){if(Ci(n)<1)break;const _=ki(n,1);v=(_[0]&128)===128,f=_[0]&127,f<126?a=3:f===126?a=1:a=2}else if(a===1){if(Ci(n)<2)break;const _=ki(n,2);f=new DataView(_.buffer,_.byteOffset,_.length).getUint16(0),a=3}else if(a===2){if(Ci(n)<8)break;const _=ki(n,8),U=new DataView(_.buffer,_.byteOffset,_.length),B=U.getUint32(0);if(B>Math.pow(2,21)-1){R.enqueue(ho);break}f=B*Math.pow(2,32)+U.getUint32(4),a=3}else{if(Ci(n)<f)break;const _=ki(n,f);R.enqueue(xo(v?_:eo.decode(_),r)),a=0}if(f===0||f>c){R.enqueue(ho);break}}}})}const Yp=4;function Ot(c){if(c)return Tg(c)}function Tg(c){for(var r in Ot.prototype)c[r]=Ot.prototype[r];return c}Ot.prototype.on=Ot.prototype.addEventListener=function(c,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+c]=this._callbacks["$"+c]||[]).push(r),this};Ot.prototype.once=function(c,r){function n(){this.off(c,n),r.apply(this,arguments)}return n.fn=r,this.on(c,n),this};Ot.prototype.off=Ot.prototype.removeListener=Ot.prototype.removeAllListeners=Ot.prototype.removeEventListener=function(c,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+c];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+c],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["$"+c],this};Ot.prototype.emit=function(c){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),n=this._callbacks["$"+c],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(c){return this._callbacks=this._callbacks||{},this._callbacks["$"+c]||[]};Ot.prototype.hasListeners=function(c){return!!this.listeners(c).length};const Bi=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,n)=>n(r,0),ir=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),$g="arraybuffer";function Jp(c,...r){return r.reduce((n,a)=>(c.hasOwnProperty(a)&&(n[a]=c[a]),n),{})}const xg=ir.setTimeout,Eg=ir.clearTimeout;function Ni(c,r){r.useNativeTimers?(c.setTimeoutFn=xg.bind(ir),c.clearTimeoutFn=Eg.bind(ir)):(c.setTimeoutFn=ir.setTimeout.bind(ir),c.clearTimeoutFn=ir.clearTimeout.bind(ir))}const Cg=1.33;function kg(c){return typeof c=="string"?Rg(c):Math.ceil((c.byteLength||c.size)*Cg)}function Rg(c){let r=0,n=0;for(let a=0,f=c.length;a<f;a++)r=c.charCodeAt(a),r<128?n+=1:r<2048?n+=2:r<55296||r>=57344?n+=3:(a++,n+=4);return n}function Zp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ag(c){let r="";for(let n in c)c.hasOwnProperty(n)&&(r.length&&(r+="&"),r+=encodeURIComponent(n)+"="+encodeURIComponent(c[n]));return r}function Mg(c){let r={},n=c.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 Ig extends Error{constructor(r,n,a){super(r),this.description=n,this.context=a,this.type="TransportError"}}class Eo extends Ot{constructor(r){super(),this.writable=!1,Ni(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 Ig(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=xo(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=Ag(r);return n.length?"?"+n:""}}class Pg extends Eo{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)};_g(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,vg(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]=Zp()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(r,n)}}let ef=!1;try{ef=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Og=ef;function zg(){}class Dg extends Pg{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 Rr extends Ot{constructor(r,n,a){super(),this.createRequest=r,Ni(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=Jp(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=Rr.requestsCount++,Rr.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=zg,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Rr.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()}}Rr.requestsCount=0;Rr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",gp);else if(typeof addEventListener=="function"){const c="onpagehide"in ir?"pagehide":"unload";addEventListener(c,gp,!1)}}function gp(){for(let c in Rr.requests)Rr.requests.hasOwnProperty(c)&&Rr.requests[c].abort()}const Lg=(function(){const c=tf({xdomain:!1});return c&&c.responseType!==null})();class Bg extends Dg{constructor(r){super(r);const n=r&&r.forceBase64;this.supportsBinary=Lg&&!n}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Rr(tf,this.uri(),r)}}function tf(c){const r=c.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||Og))return new XMLHttpRequest}catch{}if(!r)try{return new ir[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const rf=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Ng extends Eo{get name(){return"websocket"}doOpen(){const r=this.uri(),n=this.opts.protocols,a=rf?{}:Jp(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;$o(a,this.supportsBinary,v=>{try{this.doWrite(a,v)}catch{}f&&Bi(()=>{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]=Zp()),this.supportsBinary||(n.b64=1),this.createUri(r,n)}}const to=ir.WebSocket||ir.MozWebSocket;class Ug extends Ng{createSocket(r,n,a){return rf?new to(r,n,a):n?new to(r,n):new to(r)}doWrite(r,n){this.ws.send(n)}}class Fg extends Eo{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=Sg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(n).getReader(),f=bg();f.readable.pipeTo(r.writable),this._writer=f.writable.getWriter();const v=()=>{a.read().then(({done:R,value:_})=>{R||(this.onPacket(_),v())}).catch(R=>{})};v();const C={type:"open"};this.query.sid&&(C.data=`{"sid":"${this.query.sid}"}`),this._writer.write(C).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let n=0;n<r.length;n++){const a=r[n],f=n===r.length-1;this._writer.write(a).then(()=>{f&&Bi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const Vg={websocket:Ug,webtransport:Fg,polling:Bg},Gg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,qg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function po(c){if(c.length>8e3)throw"URI too long";const r=c,n=c.indexOf("["),a=c.indexOf("]");n!=-1&&a!=-1&&(c=c.substring(0,n)+c.substring(n,a).replace(/:/g,";")+c.substring(a,c.length));let f=Gg.exec(c||""),v={},C=14;for(;C--;)v[qg[C]]=f[C]||"";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=Wg(v,v.path),v.queryKey=Hg(v,v.query),v}function Wg(c,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 Hg(c,r){const n={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,v){f&&(n[f]=v)}),n}const fo=typeof addEventListener=="function"&&typeof removeEventListener=="function",Mi=[];fo&&addEventListener("offline",()=>{Mi.forEach(c=>c())},!1);class tn extends Ot{constructor(r,n){if(super(),this.binaryType=$g,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=po(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=po(n.host).host);Ni(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=Mg(this.opts.query)),fo&&(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"})},Mi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const n=Object.assign({},this.opts.query);n.EIO=Yp,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&&tn.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",tn.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+=kg(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,Bi(()=>{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(tn.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(),fo&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=Mi.indexOf(this._offlineEventListener);a!==-1&&Mi.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,n),this.writeBuffer=[],this._prevBufferLen=0}}}tn.protocol=Yp;class jg extends tn{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;tn.priorWebsocketSuccess=!1;const f=()=>{a||(n.send([{type:"ping",data:"probe"}]),n.once("packet",te=>{if(!a)if(te.type==="pong"&&te.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;tn.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 Q=new Error("probe error");Q.transport=n.name,this.emitReserved("upgradeError",Q)}}))};function v(){a||(a=!0,B(),n.close(),n=null)}const C=te=>{const Q=new Error("probe error: "+te);Q.transport=n.name,v(),this.emitReserved("upgradeError",Q)};function R(){C("transport closed")}function _(){C("socket closed")}function U(te){n&&te.name!==n.name&&v()}const B=()=>{n.removeListener("open",f),n.removeListener("error",C),n.removeListener("close",R),this.off("close",_),this.off("upgrading",U)};n.once("open",f),n.once("error",C),n.once("close",R),this.once("close",_),this.once("upgrading",U),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 Kg=class extends jg{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=>Vg[f]).filter(f=>!!f)),super(r,a)}};function Qg(c,r="",n){let a=c;n=n||typeof location<"u"&&location,c==null&&(c=n.protocol+"//"+n.host),typeof c=="string"&&(c.charAt(0)==="/"&&(c.charAt(1)==="/"?c=n.protocol+c:c=n.host+c),/^(https?|wss?):\/\//.test(c)||(typeof n<"u"?c=n.protocol+"//"+c:c="https://"+c),a=po(c)),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 Xg=typeof ArrayBuffer=="function",Yg=c=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(c):c.buffer instanceof ArrayBuffer,nf=Object.prototype.toString,Jg=typeof Blob=="function"||typeof Blob<"u"&&nf.call(Blob)==="[object BlobConstructor]",Zg=typeof File=="function"||typeof File<"u"&&nf.call(File)==="[object FileConstructor]";function Co(c){return Xg&&(c instanceof ArrayBuffer||Yg(c))||Jg&&c instanceof Blob||Zg&&c instanceof File}function Ii(c,r){if(!c||typeof c!="object")return!1;if(Array.isArray(c)){for(let n=0,a=c.length;n<a;n++)if(Ii(c[n]))return!0;return!1}if(Co(c))return!0;if(c.toJSON&&typeof c.toJSON=="function"&&arguments.length===1)return Ii(c.toJSON(),!0);for(const n in c)if(Object.prototype.hasOwnProperty.call(c,n)&&Ii(c[n]))return!0;return!1}function ey(c){const r=[],n=c.data,a=c;return a.data=mo(n,r),a.attachments=r.length,{packet:a,buffers:r}}function mo(c,r){if(!c)return c;if(Co(c)){const n={_placeholder:!0,num:r.length};return r.push(c),n}else if(Array.isArray(c)){const n=new Array(c.length);for(let a=0;a<c.length;a++)n[a]=mo(c[a],r);return n}else if(typeof c=="object"&&!(c instanceof Date)){const n={};for(const a in c)Object.prototype.hasOwnProperty.call(c,a)&&(n[a]=mo(c[a],r));return n}return c}function ty(c,r){return c.data=go(c.data,r),delete c.attachments,c}function go(c,r){if(!c)return c;if(c&&c._placeholder===!0){if(typeof c.num=="number"&&c.num>=0&&c.num<r.length)return r[c.num];throw new Error("illegal attachments")}else if(Array.isArray(c))for(let n=0;n<c.length;n++)c[n]=go(c[n],r);else if(typeof c=="object")for(const n in c)Object.prototype.hasOwnProperty.call(c,n)&&(c[n]=go(c[n],r));return c}const ry=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var it;(function(c){c[c.CONNECT=0]="CONNECT",c[c.DISCONNECT=1]="DISCONNECT",c[c.EVENT=2]="EVENT",c[c.ACK=3]="ACK",c[c.CONNECT_ERROR=4]="CONNECT_ERROR",c[c.BINARY_EVENT=5]="BINARY_EVENT",c[c.BINARY_ACK=6]="BINARY_ACK"})(it||(it={}));class ny{constructor(r){this.replacer=r}encode(r){return(r.type===it.EVENT||r.type===it.ACK)&&Ii(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=ey(r),a=this.encodeAsString(n.packet),f=n.buffers;return f.unshift(a),f}}class ko 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 sy(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(Co(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 C=r.substring(v,n);if(C!=Number(C)||r.charAt(n)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!iy(R)||R<0)throw new Error("Illegal attachments");if(R>this.opts.maxAttachments)throw new Error("too many attachments");a.attachments=R}if(r.charAt(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 C=r.charAt(n);if(C==null||Number(C)!=C){--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(ko.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 yp(n);case it.DISCONNECT:return n===void 0;case it.CONNECT_ERROR:return typeof n=="string"||yp(n);case it.EVENT:case it.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&ry.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 sy{constructor(r){this.packet=r,this.buffers=[],this.reconPack=r}takeBinaryData(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){const n=ty(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const iy=Number.isInteger||function(c){return typeof c=="number"&&isFinite(c)&&Math.floor(c)===c};function yp(c){return Object.prototype.toString.call(c)==="[object Object]"}const ay=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ko,Encoder:ny,get PacketType(){return it}},Symbol.toStringTag,{value:"Module"}));function vr(c,r,n){return c.on(r,n),function(){c.off(r,n)}}const oy=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class sf 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=[vr(r,"open",this.onopen.bind(this)),vr(r,"packet",this.onpacket.bind(this)),vr(r,"error",this.onerror.bind(this)),vr(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(oy.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 C={type:it.EVENT,data:n};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const B=this.ids++,te=n.pop();this._registerAckCallback(B,te),C.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,_=this.connected&&!(!((v=this.io.engine)===null||v===void 0)&&v._hasPingExpired());return this.flags.volatile&&!R||(_?(this.notifyOutgoingListeners(C),this.packet(C)):this.sendBuffer.push(C)),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),C=(...R)=>{this.io.clearTimeoutFn(v),n.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...n){return new Promise((a,f)=>{const v=(C,R)=>C?f(C):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 rs(c){c=c||{},this.ms=c.min||100,this.max=c.max||1e4,this.factor=c.factor||2,this.jitter=c.jitter>0&&c.jitter<=1?c.jitter:0,this.attempts=0}rs.prototype.duration=function(){var c=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),n=Math.floor(r*this.jitter*c);c=(Math.floor(r*10)&1)==0?c-n:c+n}return Math.min(c,this.max)|0};rs.prototype.reset=function(){this.attempts=0};rs.prototype.setMin=function(c){this.ms=c};rs.prototype.setMax=function(c){this.max=c};rs.prototype.setJitter=function(c){this.jitter=c};class yo 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,Ni(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 rs({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||ay;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 Kg(this.uri,this.opts);const n=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const f=vr(n,"open",function(){a.onopen(),r&&r()}),v=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=vr(n,"error",v);if(this._timeout!==!1){const R=this._timeout,_=this.setTimeoutFn(()=>{f(),v(new Error("timeout")),n.close()},R);this.opts.autoUnref&&_.unref(),this.subs.push(()=>{this.clearTimeoutFn(_)})}return this.subs.push(f),this.subs.push(C),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(vr(r,"ping",this.onping.bind(this)),vr(r,"data",this.ondata.bind(this)),vr(r,"error",this.onerror.bind(this)),vr(r,"close",this.onclose.bind(this)),vr(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){Bi(()=>{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 sf(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 Qs={};function Pi(c,r){typeof c=="object"&&(r=c,c=void 0),r=r||{};const n=Qg(c,r.path||"/socket.io"),a=n.source,f=n.id,v=n.path,C=Qs[f]&&v in Qs[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let _;return R?_=new yo(a,r):(Qs[f]||(Qs[f]=new yo(a,r)),_=Qs[f]),n.query&&!r.query&&(r.query=n.queryKey),_.socket(n.path,r)}Object.assign(Pi,{Manager:yo,Socket:sf,io:Pi,connect:Pi});const ly=c=>{if(window.audioCtx=c,c.state!=="suspended")return;const r=document.body,n=["touchstart","touchend","mousedown","keydown"];n.forEach(v=>r.addEventListener(v,a,!1));function a(){c.resume().then(f)}function f(){n.forEach(v=>r.removeEventListener(v,a))}};function Ft(c){this.init(c)}Ft.prototype.init=function(c){var r={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},r,c),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};Ft.prototype.getMaxValue=function(){var c={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return c[this.option.encoding]?c[this.option.encoding]:c["16bitInt"]};Ft.prototype.getTypedArray=function(){var c={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return c[this.option.encoding]?c[this.option.encoding]:c["16bitInt"]};Ft.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),ly(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Ft.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};Ft.prototype.isTypedArray=function(c){return c.byteLength&&c.buffer&&c.buffer.constructor==ArrayBuffer};Ft.prototype.feed=function(c){if(this.isTypedArray(c)){c=this.getFormatedValue(c);var r=new Float32Array(this.samples.length+c.length);r.set(this.samples,0),r.set(c,this.samples.length),this.samples=r,this.timeout||this.flush()}};Ft.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};Ft.prototype.volume=function(c){this.gainNode.gain.value=c};Ft.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Ft.prototype.getTimestamp=function(c){if(this.playingStartTime>=0){if(!c)return this.audioCtx.currentTime-this.playingStartTime;const r=this.lastGotTimestamp;return this.lastGotTimestamp+=c/1e3,r}return 0};Ft.prototype.setRequestStop=function(){this.flag_request_stop=!0};Ft.prototype.setOnEnd=function(c){this.onEnd=c};Ft.prototype.interrupt=function(c){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};Ft.prototype.ensuredSetTimeout=(function(){let c;return function(r,n){c=performance.now();const a=f=>{f-c>=n?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Ft.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Ft.prototype.flush=function(){if(this.samples.length){var c=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,n=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,f,v,C,R;for(f=0;f<this.option.channels;f++)for(a=n.getChannelData(f),v=f,R=50,C=0;C<r;C++)a[C]=this.samples[v],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),v+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,c.buffer=n,c.connect(this.gainNode),c.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=c,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=n.duration,this.flag_request_stop)this.flag_request_stop=!1,c.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const _=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,_-50)}}};const Vr={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},lt={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",REFRESH_SESSION_ACTIVITY:"refresh_session_activity",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"},Lt={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",FAILED:"failed",ENDED:"ended"},Kt={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},wp={enabled:!0,maxAttempts:8,initialDelayMs:500,maxDelayMs:5e3,timeoutMs:8e3},uy={encoding:"16bitInt",channels:1,sampleRate:16e3},dy=c=>new Promise(r=>setTimeout(r,c)),cy=c=>{if(!c)return null;if(c instanceof Uint8Array)return c;if(c instanceof ArrayBuffer)return new Uint8Array(c);if(c?.buffer instanceof ArrayBuffer)return new Uint8Array(c.buffer);if(typeof c=="object"&&c.type==="Buffer"&&Array.isArray(c.data))return new Uint8Array(c.data);try{return new Uint8Array(c)}catch{return null}},hy=c=>String(c||"").toLowerCase().replaceAll("-","_"),py=()=>{const c=new Map;return{addChunk:(f,v)=>{const C=f||`request-${Date.now()}`,_=`${c.get(C)||""}${v||""}`;return c.set(C,_),{id:C,text:_}},consume:(f,v="")=>{const C=f||`request-${Date.now()}`,R=c.get(C)||v||"";return c.delete(C),{id:C,text:R}},clear:()=>{c.clear()}}},af=he.createContext(null),fy={connectionState:Lt.IDLE,isConnected:!1,isSessionReady:!1,error:null,reconnectAttempt:0,isAudioPlaying:!1,isAvatarSpeaking:!1,cloudStream:{state:Kt.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[]},my=(c,r)=>{const n=new Ft(c),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},vp=async c=>{if(!c?.ok){let r=`HTTP ${c.status}`;try{const n=await c.json();r=n?.detail||n?.message||r}catch{}throw new Error(r)}return c.json()};function of({children:c,wsUrl:r,restUrl:n,reconnectOptions:a,enableAudio:f=!0,pcmOptions:v,debug:C=!1}){const[R,_]=he.useState(fy),U=he.useRef(null),B=he.useRef(null),te=he.useRef(!1),Q=he.useRef(!1),ee=he.useRef({...wp,...a}),ie=he.useRef(py()),ce=he.useRef(null),ue=he.useRef(!1),Be=he.useRef(null);he.useEffect(()=>{ee.current={...wp,...a}},[a]);const Te=he.useCallback((...de)=>{C&&console.log("[RqmiiSDK]",...de)},[C]),oe=he.useCallback(de=>{_(xe=>({...xe,connectionState:de,isConnected:de===Lt.CONNECTED}))},[]),ne=he.useCallback(de=>{_(xe=>({...xe,error:de?String(de):null}))},[]),me=he.useCallback(()=>{if(!f||ce.current)return ce.current;const de={...uy,...v||{}};return ce.current=my(de,()=>{_(xe=>({...xe,isAudioPlaying:!1}))}),ce.current},[f,v]),pe=he.useCallback(()=>{if(ce.current){try{ce.current.interrupt?.(),ce.current.destroy?.()}catch{}ce.current=null}},[]),Ne=he.useCallback(async()=>{const de=me();if(de)try{de.audioCtx?.state==="suspended"&&await de.audioCtx.resume()}catch(xe){Te("audio resume failed",xe)}},[me,Te]),ge=he.useCallback(de=>{Be.current=de||null},[]),rt=he.useCallback((de,xe=null)=>{_(wt=>({...wt,cloudStream:{state:de,error:xe?String(xe):null}}))},[]),Xe=he.useCallback(()=>{if(U.current){try{U.current.removeAllListeners(),U.current.disconnect()}catch{}U.current=null}},[]),ft=he.useCallback(({keepManualDisconnect:de=!1}={})=>{Q.current=!0,B.current=null,te.current=!1,ue.current=!1,ie.current.clear(),pe(),Xe(),de||(Q.current=!1),_(xe=>({...xe,connectionState:Lt.IDLE,isConnected:!1,isSessionReady:!1,reconnectAttempt:0,isAudioPlaying:!1,isAvatarSpeaking:!1,error:null,transcript:null,partialTranscript:null,cloudStream:{state:Kt.IDLE,error:null},session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[]}))},[Xe,pe]),Ge=he.useCallback(de=>{!de?.sessionId||!de?.reconnectToken||!de?.role||(B.current={sessionId:de.sessionId,reconnectToken:de.reconnectToken,role:de.role},_(xe=>({...xe,session:{...xe.session,sessionId:de.sessionId,role:de.role}})))},[]),Ye=he.useCallback((de,{isReconnect:xe=!1,resolve:wt,reject:$t}={})=>{const zt=(fe,Ue)=>{fe&&fe(Ue)};de.on(lt.CONNECT,()=>{Te("socket connected"),ne(null),xe||(oe(Lt.CONNECTED),zt(wt))}),de.on(lt.CONNECT_ERROR,fe=>{Te("socket connect_error",fe),xe||(oe(Lt.FAILED),ne(fe?.message||"Connection error"),zt($t,fe))}),de.on(lt.DISCONNECT,fe=>{Te("socket disconnected",fe),_(Ue=>({...Ue,isConnected:!1,isSessionReady:!1})),!Q.current&&(ee.current.enabled?oe(Lt.RECONNECTING):(oe(Lt.FAILED),ne("Connection lost")))}),de.on(lt.SESSION_READY,fe=>{_(Ue=>({...Ue,isSessionReady:!0,error:null,session:{...Ue.session,agentType:hy(fe?.agentType||Ue.session.agentType)}}))}),de.on(lt.SESSION_JOINED,()=>{_(fe=>({...fe,isSessionReady:!0,error:null}))}),de.on(lt.SESSION_TERMINATED,()=>{oe(Lt.ENDED),_(fe=>({...fe,isSessionReady:!1}))}),de.on(lt.TRANSCRIPT,fe=>{_(Ue=>({...Ue,transcript:fe||null}))}),de.on(lt.PARTIAL_TRANSCRIPT,fe=>{_(Ue=>({...Ue,partialTranscript:fe||null}))}),de.on(lt.AGENT_RESPONSE_CHUNK,fe=>{const{id:Ue,text:mt}=ie.current.addChunk(fe?.requestId,fe?.text);_(ct=>{const Mr=ct.messages.filter(Ir=>Ir.id!==Ue);return{...ct,messages:[...Mr,{id:Ue,role:"assistant",text:mt,streaming:!0,timestamp:new Date().toISOString()}]}})}),de.on(lt.AGENT_RESPONSE,fe=>{const{id:Ue,text:mt}=ie.current.consume(fe?.requestId,fe?.text);_(ct=>{const Mr=ct.messages.filter(Ir=>Ir.id!==Ue);return{...ct,messages:[...Mr,{id:Ue,role:"assistant",text:mt,streaming:!1,timestamp:new Date().toISOString()}]}})}),de.on(lt.AVATAR_SPEAKING,()=>{_(fe=>({...fe,isAvatarSpeaking:!0}))}),de.on(lt.AVATAR_SPEAKING_DONE,()=>{_(fe=>({...fe,isAvatarSpeaking:!1}))}),de.on(lt.AGENT_AUDIO_CHUNK,fe=>{if(!f||ue.current||R.session.agentType===Vr.CLOUD_AVATAR||R.session.agentType===Vr.DESKTOP_AVATAR)return;const Ue=cy(fe?.audio);if(!Ue)return;const mt=me();if(mt)try{mt.feed(Ue),_(ct=>({...ct,isAudioPlaying:!0}))}catch(ct){Te("feed pcm failed",ct)}}),de.on(lt.AGENT_AUDIO_COMPLETE,()=>{if(!(!f||!ce.current)&&!(R.session.agentType===Vr.CLOUD_AVATAR||R.session.agentType===Vr.DESKTOP_AVATAR))try{ce.current.setRequestStop()}catch{_(fe=>({...fe,isAudioPlaying:!1}))}}),de.on(lt.INTERRUPTED,()=>{ue.current=!1,pe(),_(fe=>({...fe,isAudioPlaying:!1}))}),de.on(lt.RECONNECT_CREDENTIAL,fe=>{Te("received reconnect credential"),Ge(fe)}),de.on(lt.RECONNECT_SUCCESS,fe=>{Ge(fe),_(Ue=>({...Ue,reconnectAttempt:0})),te.current=!1,oe(Lt.CONNECTED)}),de.on(lt.RECONNECT_FAILED,fe=>{Te("reconnect failed",fe),oe(Lt.FAILED),ne(fe?.reason||"Reconnect failed")}),de.on(lt.AUTH_ERROR,fe=>{oe(Lt.FAILED),ne(fe?.message||"Authentication error")}),de.on(lt.ERROR,fe=>{if(fe?.code==="TTS_ERROR"){Te("non-fatal TTS error",fe);return}ne(fe?.message||fe?.detail||"Server error")})},[pe,f,me,Ge,Te,oe,ne,R.session.agentType]),st=he.useCallback(({authPayload:de,queryToken:xe,expectReconnectSuccess:wt=!1})=>new Promise(($t,zt)=>{Xe();const fe=Pi(r,{transports:["websocket","polling"],timeout:2e4,reconnection:!1,auth:de,query:xe?{token:xe}:void 0});if(U.current=fe,Ye(fe,{isReconnect:wt,resolve:$t,reject:zt}),wt){const Ue=()=>{fe.off(lt.RECONNECT_FAILED,mt),$t()},mt=ct=>{fe.off(lt.RECONNECT_SUCCESS,Ue),zt(new Error(ct?.reason||"Reconnect failed"))};fe.once(lt.RECONNECT_SUCCESS,Ue),fe.once(lt.RECONNECT_FAILED,mt),setTimeout(()=>{fe.off(lt.RECONNECT_SUCCESS,Ue),fe.off(lt.RECONNECT_FAILED,mt),zt(new Error("Reconnect timed out"))},ee.current.timeoutMs)}}),[Xe,Ye,r]),bt=he.useCallback(async()=>{if(te.current)return;const de=B.current;if(!de){oe(Lt.FAILED),ne("Reconnect token unavailable. Please initialize a new session.");return}te.current=!0;for(let xe=1;xe<=ee.current.maxAttempts;xe+=1){if(Q.current){te.current=!1;return}_(wt=>({...wt,reconnectAttempt:xe}));try{await st({authPayload:{reconnectToken:de.reconnectToken,sessionId:de.sessionId,role:de.role},expectReconnectSuccess:!0}),te.current=!1;return}catch(wt){Te(`reconnect attempt ${xe} failed`,wt);const $t=Math.min(ee.current.maxDelayMs,ee.current.initialDelayMs*2**(xe-1));await dy($t)}}te.current=!1,oe(Lt.FAILED),ne("Reconnect window expired. Please initialize a new session.")},[st,Te,oe,ne]);he.useEffect(()=>{R.connectionState===Lt.RECONNECTING&&ee.current.enabled&&bt()},[R.connectionState,bt]);const ut=he.useCallback(async({apiKey:de,publicChatId:xe,agentId:wt,language:$t="en"}={})=>{if(!n)throw new Error("Missing restUrl in RqmiiAgentProvider");if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!de&&!xe&&!wt)throw new Error("Provide one of apiKey, publicChatId, or agentId");ft(),oe(Lt.INITIALIZING),ne(null);const zt={...de?{api_key:de}:{},...xe?{public_chat_id:xe}:{},...wt?{agent_id:wt}:{},language:$t},fe=await fetch(`${n}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(zt)}).then(vp),Ue=fe?.session_id||null,mt=fe?.session_token;if(!Ue||!mt)throw new Error("Invalid initialize session response");return _(ct=>({...ct,session:{...ct.session,sessionId:Ue,agentType:fe?.streaming_url?Vr.CLOUD_AVATAR:ct.session.agentType,streamingUrl:fe?.streaming_url||null,uniqueId:fe?.unique_id||null,role:null}})),oe(Lt.CONNECTING),fe?.streaming_url?rt(Kt.CONNECTING):rt(Kt.IDLE),await st({authPayload:{token:mt},queryToken:mt}),fe},[st,ft,n,rt,oe,ne,r]),Je=he.useCallback(async({uniqueId:de})=>{if(!n)throw new Error("Missing restUrl in RqmiiAgentProvider");if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!de)throw new Error("uniqueId is required");ft(),oe(Lt.INITIALIZING),ne(null);const xe=await fetch(`${n}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:de})}).then(vp),wt=xe?.session_id||null,$t=xe?.session_token;if(!wt||!$t)throw new Error("Invalid join session response");return _(zt=>({...zt,session:{...zt.session,sessionId:wt,uniqueId:de,role:"user",agentType:Vr.DESKTOP_AVATAR}})),oe(Lt.CONNECTING),rt(Kt.IDLE),await st({authPayload:{token:$t},queryToken:$t}),xe},[st,ft,n,rt,oe,ne,r]),Le=he.useCallback(()=>{ft({keepManualDisconnect:!0})},[ft]),qe=he.useCallback((de,xe={})=>!U.current||!R.isConnected?!1:(U.current.emit(de,xe),!0),[R.isConnected]),et=he.useCallback(de=>{if(!de||!String(de).trim())return!1;const xe={id:`user-${Date.now()}`,role:"user",text:String(de),timestamp:new Date().toISOString()};return _(wt=>({...wt,messages:[...wt.messages,xe]})),qe(lt.USER_MESSAGE,{message:String(de)})},[qe]),Y=he.useCallback(de=>qe(lt.AUDIO_CHUNK,{audio:de}),[qe]),Ie=he.useCallback(()=>qe(lt.AUDIO_END,{}),[qe]),tt=he.useCallback(()=>(ue.current=!0,pe(),_(de=>({...de,isAudioPlaying:!1})),qe(lt.INTERRUPT,{})),[pe,qe]),gt=he.useCallback(()=>qe(lt.REFRESH_SESSION_ACTIVITY,{}),[qe]),Vt=he.useCallback(()=>qe(lt.CLEAR_SESSION_HISTORY,{}),[qe]),Et=he.useCallback(de=>de?qe(lt.CHANGE_SESSION_LANGUAGE,{language:de}):!1,[qe]),dt=he.useCallback(()=>{ie.current.clear(),_(de=>({...de,messages:[]}))},[]);he.useEffect(()=>()=>{Q.current=!0,Xe(),pe()},[Xe,pe]);const nt=he.useMemo(()=>({...R,initializeSession:ut,joinDesktopSession:Je,disconnect:Le,emit:qe,sendTextMessage:et,sendAudioChunk:Y,endAudioStream:Ie,interrupt:tt,refreshSessionActivity:gt,clearSessionHistory:Vt,changeSessionLanguage:Et,clearMessages:dt,resumeAudioPlayback:Ne,attachAudioElement:ge,setCloudStreamState:rt,audioElement:Be.current,socket:U.current}),[ge,dt,Vt,Le,qe,Ie,ut,tt,Et,Je,gt,Ne,Y,et,rt,R]);return sr.jsx(af.Provider,{value:nt,children:c})}const qr=()=>{const c=he.useContext(af);if(!c)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return c},gy=["Cannot read properties of null (reading 'state')","MicVAD has null stream"],_p=c=>c?gy.some(r=>String(c).includes(r)):!1;function lf(){typeof window>"u"||window.__rqmiiAudioErrorSuppressorsInstalled||(window.__rqmiiAudioErrorSuppressorsInstalled=!0,window.addEventListener("error",c=>{if(_p(c?.message))return c.preventDefault(),!0}),window.addEventListener("unhandledrejection",c=>{const r=c?.reason?.message||String(c?.reason||"");_p(r)&&c.preventDefault()}))}lf();const yy={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,sampleRate:16e3},wy=["audio/webm;codecs=opus","audio/webm","audio/mp4"],vy=()=>typeof window>"u"||!window.MediaRecorder?.isTypeSupported?"":wy.find(c=>window.MediaRecorder.isTypeSupported(c))||"";function _y(c={}){const{onAudioChunk:r,onAudioEnd:n,onError:a,holdDelayMs:f=220,timesliceMs:v=100,interruptOnHoldStart:C=!0,audioConstraints:R=yy}=c,{sendAudioChunk:_,endAudioStream:U,interrupt:B}=qr(),te=he.useRef(null),Q=he.useRef(null),ee=he.useRef(null),ie=he.useRef(!0),[ce,ue]=he.useState(!1),[Be,Te]=he.useState(!1),[oe,ne]=he.useState(null),me=he.useCallback(async Ge=>{if(!Ge||Ge.size<=0)return;const Ye=await Ge.arrayBuffer();if(r){r(Ye);return}_(Ye)},[r,_]),pe=he.useCallback(()=>{Q.current&&(Q.current.getTracks().forEach(Ge=>Ge.stop()),Q.current=null)},[]),Ne=he.useCallback(({discard:Ge=!1}={})=>{const Ye=te.current;if(!Ye)return!1;if(ie.current=!Ge,te.current=null,Ye.state==="inactive")return Ge||(n?n():U()),pe(),Te(!1),!0;try{Ye.requestData()}catch{}Ye.onstop=()=>{ie.current&&(n?n():U()),pe(),Te(!1)};try{Ye.stop()}catch(st){pe(),Te(!1),a?.(st)}return!0},[pe,U,n,a]),ge=he.useCallback(async()=>{if(te.current)return!0;if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||typeof window>"u"||typeof window.MediaRecorder>"u"){const Ge=new Error("MediaRecorder or microphone APIs are unavailable in this browser");return ne(Ge.message),a?.(Ge),!1}try{const Ge=await navigator.mediaDevices.getUserMedia({audio:R});Q.current=Ge;const Ye=vy(),st=Ye?{mimeType:Ye}:void 0,bt=new window.MediaRecorder(Ge,st);return bt.ondataavailable=ut=>{me(ut.data)},bt.onerror=ut=>{const Je=ut?.error||new Error("Microphone recording failed");ne(Je?.message||"recording_failed"),a?.(Je)},te.current=bt,Te(!0),ne(null),bt.start(v),!0}catch(Ge){return pe(),Te(!1),ne("permission_denied"),a?.(Ge),!1}},[R,pe,me,a,v]),rt=he.useCallback(()=>{ee.current&&(clearTimeout(ee.current),ee.current=null),ue(!0),ee.current=setTimeout(()=>{C&&B(),ge()},f)},[f,B,C,ge]),Xe=he.useCallback(()=>{ue(!1),ee.current&&(clearTimeout(ee.current),ee.current=null),Ne()},[Ne]);he.useEffect(()=>()=>{ee.current&&(clearTimeout(ee.current),ee.current=null),Ne({discard:!0}),pe()},[pe,Ne]);const ft=he.useMemo(()=>({onPointerDown:Ge=>{Ge.preventDefault(),rt()},onPointerUp:Ge=>{Ge.preventDefault(),Xe()},onPointerCancel:Ge=>{Ge.preventDefault(),Xe()},onPointerLeave:Ge=>{Ge.preventDefault(),Xe()}}),[rt,Xe]);return{isPressing:ce,isRecording:Be,micError:oe,startRecording:ge,stopRecording:Ne,startPress:rt,stopPress:Xe,eventHandlers:ft}}var ro={},no={},Xs={},bp;function uf(){if(bp)return Xs;bp=1,Object.defineProperty(Xs,"__esModule",{value:!0}),Xs.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(/\/[^/]+$/,"/")),Xs.baseAssetPath=n,Xs}var Ys={},Sp;function Ro(){if(Sp)return Ys;Sp=1,Object.defineProperty(Ys,"__esModule",{value:!0}),Ys.defaultModelFetcher=void 0;const c=r=>fetch(r).then(n=>n.arrayBuffer());return Ys.defaultModelFetcher=c,Ys}var Nr={},Js={},Tp;function ai(){if(Tp)return Js;Tp=1,Object.defineProperty(Js,"__esModule",{value:!0}),Js.log=void 0;const c=r=>n=>{console.log(`VAD | ${r} >`,n)};return Js.log={error:c("error"),debug:c("debug"),warn:c("warn")},Js}var Zs={},$p;function Ui(){if($p)return Zs;$p=1,Object.defineProperty(Zs,"__esModule",{value:!0}),Zs.Message=void 0;var c;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"})(c||(Zs.Message=c={})),Zs}var xp;function Ao(){if(xp)return Nr;xp=1,Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.FrameProcessor=Nr.validateOptions=Nr.defaultFrameProcessorOptions=void 0;const c=ai(),r=Ui();Nr.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function n(C){(C.positiveSpeechThreshold<0||C.positiveSpeechThreshold>1)&&c.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(C.negativeSpeechThreshold<0||C.negativeSpeechThreshold>C.positiveSpeechThreshold)&&c.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),C.preSpeechPadMs<0&&c.log.error("preSpeechPadMs should be positive"),C.redemptionMs<0&&c.log.error("redemptionMs should be positive"),C.minSpeechMs<0&&c.log.error("minSpeechMs should be positive")}Nr.validateOptions=n;const a=C=>{const R=C.reduce((U,B)=>(U.push(U.at(-1)+B.length),U),[0]),_=new Float32Array(R.at(-1));return C.forEach((U,B)=>{const te=R[B];_.set(U,te)}),_};function f(C,R){const _=Math.floor(C.redemptionMs/R),U=Math.floor(C.preSpeechPadMs/R),B=Math.floor(C.minSpeechMs/R);return{redemptionFrames:_,preSpeechPadFrames:U,minSpeechFrames:B}}class v{constructor(R,_,U,B){this.modelProcessFunc=R,this.modelResetFunc=_,this.options=U,this.msPerFrame=B,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=ie=>{this.options={...this.options,...ie};const{redemptionFrames:ce,preSpeechPadFrames:ue,minSpeechFrames:Be}=f(this.options,this.msPerFrame);this.redemptionFrames=ce,this.preSpeechPadFrames=ue,this.minSpeechFrames=Be},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=ie=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(ie):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=ie=>{const ce=this.audioBuffer;this.audioBuffer=[];const ue=this.speaking;if(this.reset(),ue)if(ce.reduce((Te,oe)=>oe.isSpeech?Te+1:Te,0)>=this.minSpeechFrames){const Te=a(ce.map(oe=>oe.frame));ie({msg:r.Message.SpeechEnd,audio:Te})}else ie({msg:r.Message.VADMisfire});return{}},this.process=async(ie,ce)=>{if(!this.active)return;const ue=await this.modelProcessFunc(ie),Be=ue.isSpeech>=this.options.positiveSpeechThreshold;if(ce({probs:ue,msg:r.Message.FrameProcessed,frame:ie}),this.audioBuffer.push({frame:ie,isSpeech:Be}),Be&&(this.speechFrameCount++,this.redemptionCounter=0),Be&&!this.speaking&&(this.speaking=!0,ce({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,ce({msg:r.Message.SpeechRealStart})),ue.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const Te=this.audioBuffer;if(this.audioBuffer=[],Te.reduce((ne,me)=>me.isSpeech?ne+1:ne,0)>=this.minSpeechFrames){const ne=a(Te.map(me=>me.frame));ce({msg:r.Message.SpeechEnd,audio:ne})}else ce({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:te,preSpeechPadFrames:Q,minSpeechFrames:ee}=f(this.options,this.msPerFrame);this.redemptionFrames=te,this.preSpeechPadFrames=Q,this.minSpeechFrames=ee,this.reset()}}return Nr.FrameProcessor=v,Nr}var Ur={};function ar(c){throw new Error('Could not dynamically require "'+c+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var so={exports:{}};/*!
|
|
23
23
|
* ONNX Runtime Web v1.24.3
|
|
24
24
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
25
25
|
* Licensed under the MIT License.
|
|
26
|
-
*/var Ep;function _y(){return Ep||(Ep=1,(function(c,r){var n=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(e=>typeof ar<"u"?ar:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof ar<"u"?ar:t)[s]}):e)(function(e){if(typeof ar<"u")return ar.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),b=(e,t)=>()=>(e&&(t=e(e=0)),t),F=(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))!C.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,ee,ae,ce,de,Le=b(()=>{X=new Map,ee=[],ae=(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=ee.indexOf(e);o!==-1&&ee.splice(o,1);for(let l=0;l<ee.length;l++)if(X.get(ee[l]).priority<=s){ee.splice(l,0,e);return}ee.push(e)}return}throw new TypeError("not a valid backend")},ce=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}}},de=async e=>{let t=e.executionProviders||[],s=t.map(h=>typeof h=="string"?h:h.name),i=s.length===0?ee:s,o,l=[],u=new Set;for(let h of i){let p=await ce(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 d=t.filter(h=>u.has(typeof h=="string"?h:h.name));return[o,new Proxy(e,{get:(h,p)=>p==="executionProviders"?d:Reflect.get(h,p)})]}}),Te=b(()=>{Le()}),le,se=b(()=>{le="1.24.3"}),fe,he,Be=b(()=>{se(),fe="warning",he={wasm:{},webgl:{},webgpu:{},versions:{common:le},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}`);fe=e}},get logLevel(){return fe}},Object.defineProperty(he,"logLevel",{enumerable:!0})}),me,nt=b(()=>{Be(),me=he}),Ye,mt,Ge=b(()=>{Ye=(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",d=t?.norm,h,p;d===void 0||d.mean===void 0?h=[255,255,255,255]:typeof d.mean=="number"?h=[d.mean,d.mean,d.mean,d.mean]:(h=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(h[3]=d.mean[3])),d===void 0||d.bias===void 0?p=[0,0,0,0]:typeof d.bias=="number"?p=[d.bias,d.bias,d.bias,d.bias]:(p=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(p[3]=d.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 E=0;E<l;E++)for(let I=0;I<o;I++){let k=(e.data[m++]-p[0])*h[0],x=(e.data[w++]-p[1])*h[1],O=(e.data[_++]-p[2])*h[2],M=S===-1?255:(e.data[S++]-p[3])*h[3];i.fillStyle="rgba("+k+","+x+","+O+","+M+")",i.fillRect(I,E,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")},mt=(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 d=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,E=2,I=3,k=0,x=m,O=m*2,M=-1;d==="RGBA"?(k=0,x=m,O=m*2,M=m*3):d==="RGB"?(k=0,x=m,O=m*2):d==="RBG"&&(k=0,O=m,x=m*2),i=s.createImageData(o,l);for(let D=0;D<l*o;_+=w,S+=w,E+=w,I+=w,D++)i.data[_]=(e.data[k++]-g[0])*p[0],i.data[S]=(e.data[x++]-g[1])*p[1],i.data[E]=(e.data[O++]-g[2])*p[2],i.data[I]=M===-1?255:(e.data[M++]-g[3])*p[3]}else throw new Error("Can not access image data");return i}}),Je,st,bt,ut,Ze,De,Ke=b(()=>{Ne(),Je=(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 d=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,E=3,I=0,k=p,x=p*2,O=-1;d==="RGB"&&(m=3,w=0,_=1,S=2,E=-1),h==="RGBA"?O=p*3:h==="RBG"?(I=0,x=p,k=p*2):h==="BGR"&&(x=0,k=p,I=p*2);for(let M=0;M<p;M++,w+=m,S+=m,_+=m,E+=m)g[I++]=(e[w]+u[0])/l[0],g[k++]=(e[_]+u[1])/l[1],g[x++]=(e[S]+u[2])/l[2],O!==-1&&E!==-1&&(g[O++]=(e[E]+u[3])/l[3]);return h==="RGBA"?new te("float32",g,[1,4,s,i]):new te("float32",g,[1,3,s,i])},st=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,d=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(d=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=w,d.width=_}else d.tensorFormat="RGBA",d.height=w,d.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&&(d=t),d.format="RGBA",d.height=g,d.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,d.height=w,d.width=_,Je(u,d)}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 E=_.getImageData(0,0,w.width,w.height);d.height=w.height,d.width=w.width,g(Je(E.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return Je(u,d);throw new Error("Input data provided is not supported - aborted tensor creation")},bt=(e,t)=>{let{width:s,height:i,download:o,dispose:l}=t,u=[1,i,s,4];return new te({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:l})},ut=(e,t)=>{let{dataType:s,dims:i,download:o,dispose:l}=t;return new te({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:i,download:o,dispose:l})},Ze=(e,t)=>{let{dataType:s,dims:i,download:o,dispose:l}=t;return new te({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:i,download:o,dispose:l})},De=(e,t,s)=>new te({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),tt,Y,Me,rt,gt=b(()=>{tt=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Y=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Me=!1,rt=()=>{if(!Me){Me=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=globalThis.Float16Array,i=typeof s<"u"&&s.from;e&&(tt.set("int64",BigInt64Array),Y.set(BigInt64Array,"int64")),t&&(tt.set("uint64",BigUint64Array),Y.set(BigUint64Array,"uint64")),i?(tt.set("float16",s),Y.set(s,"float16")):tt.set("float16",Uint16Array)}}}),Vt,$t,ct=b(()=>{Ne(),Vt=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 te(e.type,e.data,t);case"cpu-pinned":return new te({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new te({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new te({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new te({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),te,Ne=b(()=>{Ge(),Ke(),gt(),ct(),te=class{constructor(e,t,s){rt();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=tt.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,d;if(typeof e=="string")if(i=e,d=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=tt.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(d=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=Y.get(e.constructor);if(h===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=h,u=e}if(d===void 0)d=[u.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");o=d,this.cpuData=u,this.dataLocation="cpu"}let l=Vt(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 st(e,t)}static fromTexture(e,t){return bt(e,t)}static fromGpuBuffer(e,t){return ut(e,t)}static fromMLTensor(e,t){return Ze(e,t)}static fromPinnedBuffer(e,t,s){return De(e,t,s)}toDataURL(e){return Ye(this,e)}toImageData(e){return mt(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)}}}),He,Lt=b(()=>{Ne(),He=te}),xt,be,Ue,it,ht,Mt,Mr=b(()=>{Be(),xt=(e,t)=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeStamp(`${e}::ORT::${t}`)},be=(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}`),xt("CPU",l);return}s[o].includes("TRACE_FUNC")&&(i=!0)}},Ue=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||be("BEGIN",e)},it=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||be("END",e)},ht=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.time(`ORT::${e}`)},Mt=e=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeEnd(`ORT::${e}`)}}),ns,Fi=b(()=>{Le(),Lt(),Mr(),ns=class df{constructor(t){this.handler=t}async run(t,s,i){Ue(),ht("InferenceSession.run");let o={},l={};if(typeof t!="object"||t===null||t instanceof He||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 He)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 He)&&(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 d=await this.handler.run(t,o,l),h={};for(let p in d)if(Object.hasOwnProperty.call(d,p)){let g=d[p];g instanceof He?h[p]=g:h[p]=new He(g.type,g.data,g.dims)}return Mt("InferenceSession.run"),it(),h}async release(){return this.handler.dispose()}static async create(t,s,i,o){Ue(),ht("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[d,h]=await de(u),p=await d.createInferenceSessionHandler(l,h);return Mt("InferenceSession.create"),it(),new df(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),tn,Vi=b(()=>{Fi(),tn=ns}),Gi=b(()=>{}),qi=b(()=>{}),Wi=b(()=>{}),Hi=b(()=>{}),ss={};F(ss,{InferenceSession:()=>tn,TRACE:()=>xt,TRACE_EVENT_BEGIN:()=>ht,TRACE_EVENT_END:()=>Mt,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>it,Tensor:()=>He,env:()=>me,registerBackend:()=>ae});var It=b(()=>{Te(),nt(),Vi(),Lt(),Gi(),qi(),Mr(),Wi(),Hi()}),rn=b(()=>{}),is={};F(is,{default:()=>as});var nn,sn,as,ji=b(()=>{Qh(),Qt(),dn(),nn="ort-wasm-proxy-worker",sn=globalThis.self?.name===nn,sn&&(self.onmessage=e=>{let{type:t,in:s}=e.data;try{switch(t){case"init-wasm":pn(s.wasm).then(()=>{Ua(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;Fa(o,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=s,o=Ti(i);postMessage({type:t,out:o});break}case"create":{let{model:i,options:o}=s;Ga(i,o).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":qa(s),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:o,inputs:l,outputIndices:u,options:d}=s;Ha(i,o,l,u,new Array(u.length).fill(null),d).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},Ka([...l,...h]))},h=>{postMessage({type:t,err:h})});break}case"end-profiling":ja(s),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),as=sn?null:e=>new Worker(e??yt,{type:"classic",name:nn})}),os,ls,yt,an,Ir,us,ds,on,cs,ln,hs,un,ps,dn=b(()=>{rn(),os=typeof location>"u"?void 0:location.origin,ls=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,yt=ls(),an=()=>{if(yt&&!yt.startsWith("blob:"))return yt.substring(0,yt.lastIndexOf("/")+1)},Ir=(e,t)=>{try{let s=t??yt;return(s?new URL(e,s):new URL(e)).origin===os}catch{return!1}},us=(e,t)=>{let s=t??yt;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},ds=(e,t)=>`${t??"./"}${e}`,on=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},cs=async e=>(await import(e)).default,ln=(ji(),re(is)).default,hs=async()=>{if(!yt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ir(yt))return[void 0,ln()];let e=await on(yt);return[e,ln(e)]},un=void 0,ps=async(e,t,s,i)=>{let o=un&&!(e||t);if(o)if(yt)o=Ir(yt)||i&&!s;else if(i&&!s)o=!0;else throw new Error("cannot determine the script source URL.");if(o)return[void 0,un];{let l="ort-wasm-simd-threaded.jsep.mjs",u=e??us(l,t),d=s&&u&&!Ir(u,t),h=d?await on(u):u??ds(l,t);return[d?h:void 0,await cs(h)]}}}),cn,Pr,or,hn,fs,ms,gs,pn,Oe,Qt=b(()=>{dn(),Pr=!1,or=!1,hn=!1,fs=()=>{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}},ms=()=>{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}},gs=()=>{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}},pn=async e=>{if(Pr)return Promise.resolve();if(or)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(hn)throw new Error("previous call to 'initializeWebAssembly()' failed.");or=!0;let t=e.initTimeout,s=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!gs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ms())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=fs();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,d=u?.href??u,h=o?.wasm,p=h?.href??h,g=e.wasmBinary,[m,w]=await ps(d,l,s>1,!!g||!!p),_=!1,S=[];if(t>0&&S.push(new Promise(E=>{setTimeout(()=>{_=!0,E()},t)})),S.push(new Promise((E,I)=>{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(d&&d.indexOf("blob:")!==0)k.locateFile=x=>new URL(x,d).href;else if(m){let x=an();x&&(k.locateFile=O=>x+O)}w(k).then(x=>{or=!1,Pr=!0,cn=x,E(),m&&URL.revokeObjectURL(m)},x=>{or=!1,hn=!0,I(x)})})),await Promise.race(S),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Oe=()=>{if(Pr&&cn)return cn;throw new Error("WebAssembly is not initialized yet.")}}),Tt,Or,Re,fn=b(()=>{Qt(),Tt=(e,t)=>{let s=Oe(),i=s.lengthBytesUTF8(e)+1,o=s._malloc(i);return s.stringToUTF8(e,o,i),t.push(o),o},Or=(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")Or(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}`)})},Re=e=>{let t=Oe(),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,"*"),d=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${d}`)}finally{t.stackRestore(s)}}}),ys,Ki=b(()=>{Qt(),fn(),ys=e=>{let t=Oe(),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=Tt(e.tag,i)),s=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,l),s===0&&Re("Can't create run options."),e?.extra!==void 0&&Or(e.extra,"",new WeakSet,(u,d)=>{let h=Tt(u,i),p=Tt(d,i);t._OrtAddRunConfigEntry(s,h,p)!==0&&Re(`Can't set a run config entry: ${u} - ${d}.`)}),[s,i]}catch(l){throw s!==0&&t._OrtReleaseRunOptions(s),i.forEach(u=>t._free(u)),l}}}),ws,vs,bs,lr,_s,Ss,Qi=b(()=>{Qt(),fn(),ws=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}`)}},vs=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},bs=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)},lr=(e,t,s,i)=>{let o=Tt(t,i),l=Tt(s,i);Oe()._OrtAddSessionConfigEntry(e,o,l)!==0&&Re(`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&&lr(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}`);lr(e,"preferredLayout",m.preferredLayout,s)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let d=Tt(l,s),h=u.length,p=0,g=0;if(h>0){p=Oe()._malloc(h*Oe().PTR_SIZE),s.push(p),g=Oe()._malloc(h*Oe().PTR_SIZE),s.push(g);for(let m=0;m<h;m++)Oe().setValue(p+m*Oe().PTR_SIZE,u[m][0],"*"),Oe().setValue(g+m*Oe().PTR_SIZE,u[m][1],"*")}await Oe()._OrtAppendExecutionProvider(e,d,p,g,h)!==0&&Re(`Can't append execution provider: ${l}.`)}},Ss=async e=>{let t=Oe(),s=0,i=[],o=e||{};bs(o);try{let l=ws(o.graphOptimizationLevel??"all"),u=vs(o.executionMode??"sequential"),d=typeof o.logId=="string"?Tt(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"?Tt(o.optimizedModelFilePath,i):0;if(s=t._OrtCreateSessionOptions(l,!!o.enableCpuMemArena,!!o.enableMemPattern,u,!!o.enableProfiling,0,d,h,p,g),s===0&&Re("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}`);lr(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 _=Tt(m,i);t._OrtAddFreeDimensionOverride(s,_,w)!==0&&Re(`Can't set a free dimension override: ${m} - ${w}.`)}return o.extra!==void 0&&Or(o.extra,"",new WeakSet,(m,w)=>{lr(s,m,w,i)}),[s,i]}catch(l){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&Re("Can't release session options."),i.forEach(u=>t._free(u)),l}}}),Xt,Yt,Jt,mn,gn,yn,wn,zn,Ie=b(()=>{Xt=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}`)}},Yt=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}`)}},Jt=(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},mn=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}`)}},gn=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}`)}},yn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",wn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",zn=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}`)}}}),vn,Ts=b(()=>{rn(),vn=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(d){if(d instanceof RangeError){let h=Math.ceil(i/65536);l=new WebAssembly.Memory({initial:h,maximum:h}).buffer}else throw d}let u=0;for(;;){let{done:d,value:h}=await o.read();if(d)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)}}),$s,Dn,Ln,_r,Bn,Nn,et,Zt=b(()=>{Ie(),$s=["V","I","W","E","F"],Dn=(e,t)=>{console.log(`[${$s[e]},${new Date().toISOString()}]${t}`)},Bn=(e,t)=>{Ln=e,_r=t},Nn=(e,t)=>{let s=gn(e),i=gn(Ln);s>=i&&Dn(s,typeof t=="function"?t():t)},et=(...e)=>{_r&&Nn(...e)}}),Un,Sr,H,Wr,Fn,xs,ur,Ae=b(()=>{Un=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Sr=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 d=Un.calcMatMulShape([e[i-2],e[i-1]],[t[o-2],t[o-1]]);if(d===void 0)return;[u[l-2],u[l-1]]=d}for(let d=s?3:1;d<=l;d++){let h=i-d<0?1:e[i-d],p=o-d<0?1:t[o-d];if(h!==p&&h>1&&p>1)return;let g=Math.max(h,p);if(h&&p)u[l-d]=Math.max(h,p);else{if(g>1)return;u[l-d]=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}},H=class Oi{static size(t){return Oi.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 Oi.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 Oi.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])}},Wr=class si{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 d=0;d<s.length-2;d++)d>=i.length?i.push(s[d+2]):i[d]=s[d+2];for(let d=0;d<i.length;d++)if(d<o.length){if(o[d]<0)throw new Error("strides should be greater than or equal to 1")}else o.push(1);for(let d=0;d<i.length;d++)if(d<l.length){if(l[d]<0)throw new Error("dilations should be greater than or equal to 1")}else l.push(1);for(let d=0;d<i.length*2;d++)if(d<u.length){if(u[d]<0)throw new Error("pad should be greater than or equal to 1")}else u.push(0);for(let d=0;d<i.length;d++){if(i[d]<=0)throw new Error("kernel shapes need to be greater than 0");if(u[d]>=i[d]||u[d+i.length]>=i[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,i,o,l,u,d){if(d){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++)si.adjustPadAndReturnShape(t[h+(u?1:2)],s[h],i[h],o[h],l,h,h+t.length-2,d)}}static computePoolOutputShape(t,s,i,o,l,u,d){if(s.length<=0)throw new Error("input shape must be of size greater than 0");let h=[s[0],s[1]];return si.computeShapeHelper(t,s,h,i,o,l,u,d),h}static computeConvOutputShape(t,s,i,o,l,u,d){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 si.computeShapeHelper(!1,t,h,i,o,l,u,d),h}static computeShapeHelper(t,s,i,o,l,u,d,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(si.adjustPadAndReturnShape(s[p+2],o[p],l[p],u[p],d,p,p+s.length-2,h))}static adjustPadAndReturnShape(t,s,i,o,l,u,d,h){let p=i*(o-1)+1;if(h&&h!=="NOTSET")switch(h){case"VALID":return l[u]=0,l[d]=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[d]=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[d]-p)/s+1)}},Fn=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,d;t?(l=e[1],u=e[0]):(l=e[0],u=e[1]);let h=-1;if(i?(d=s[0],h=1):(d=s[1],h=0),s[h]!==u)throw new Error("dimension mismatch");if(l<=0||d<=0||u<=0)throw new Error("invalid shape specified");if(o&&!Sr.isValidBroadcast(o,[l,d]))throw new Error("gemm: invalid bias shape for broadcast");return[l,d,u]}},xs=-34028234663852886e22,ur=34028234663852886e22}),Tr,Hr=b(()=>{Ie(),Tr=(e,t)=>new(mn(t))(e)}),zr,jr,bn,_n,dr,$r,Vn,Gn,qn,Es,Cs,li=b(()=>{Ie(),Zt(),zr=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),jr=(e,t)=>{if(t==="int32")return e;let s=zr.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(mn(t))(e.buffer,e.byteOffset,o);switch(t){case"int64":case"uint64":{let u=new Int32Array(o);for(let d=0;d<o;d++){let h=l[d];if(h>2147483647n||h<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");u[d]=Number(h)}return new Uint8Array(u.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(d=>d>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'`)}},bn=(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,dr=()=>_n++,$r=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Vn=(e,t)=>{let s=zr.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},Gn=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 Vn(this.dataType,this.tensorShape)}destroy(){et("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=bn(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=$r.get(t),!u||l?.input.dataTypes.includes(u))throw new Error(`WebNN backend does not support data type: ${t}`);et("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!==Vn(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 d=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,s,d,!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=jr(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 et("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?bn(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()}},Es=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=dr();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){et("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){et("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=dr(),u=new Gn({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 d=this.getMLContext(e);for(let[p,g]of this.freeTensors.entries())if(g.canReuseTensor(d,t,s)){et("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${s}`);let m=this.freeTensors.splice(p,1)[0];return m.sessionId=e,m}et("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${s}}`);let h=await d.createTensor({dataType:u??t,shape:s,dimensions:s,usage:i,writable:o,readable:l});return new Gn({sessionId:e,context:d,tensor:h,dataType:t,shape:s,fallbackDataType:u})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Cs=(...e)=>new Es(...e)}),Kr,ks,Rs,As=b(()=>{Ie(),Qt(),Hr(),li(),Zt(),Kr=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),ks=(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])},Rs=class{constructor(e){this.tensorManager=Cs(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,Bn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){et("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){et("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let s of t)et("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=>ks(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){et("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,i,o){let l=Kr.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){et("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${s}}`);let i=Kr.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(!Oe().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");et("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 Tr(s,t)}}registerMLTensor(e,t,s,i){let o=Kr.get(s);if(!o)throw new Error(`Unsupported ONNX data type: ${s}`);let l=this.tensorManager.registerTensor(e,t,o,i);return et("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 d=e;e.startsWith("./")&&(d=e.substring(2));let h=l.get(d);if(!h)throw new Error(`File with name ${d} 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=jr(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 et("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=Kr.get(Xt(t)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:s?!!o?.input.dataTypes.includes(i):!!o?.output.dataTypes.includes(i)}flush(){}}}),Wn=b(()=>{}),Hn,jn,Sn,Kn,Qn,Xn,Ms,Is,ui,Xi=b(()=>{Zt(),Wn(),Hn=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=[],Sn=e=>Math.ceil(Number(e)/16)*16,Kn=e=>{for(let t=0;t<jn.length;t++){let s=jn[t];if(e<=s)return s}return Math.ceil(e/16)*16},Qn=1,Xn=()=>Qn++,Ms=async(e,t,s,i)=>{let o=Sn(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 d=l.getMappedRange();if(i){let h=i();return h.set(new Uint8Array(d,0,s)),h}else return new Uint8Array(d.slice(0,s))}finally{l.destroy()}},Is=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 Hn)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=Sn(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 d=this.backend.device.createBuffer({mappedAtCreation:!0,size:l,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),h=d.getMappedRange();new Uint8Array(h).set(new Uint8Array(s,i,o)),d.unmap();let p=this.backend.device.createCommandEncoder();p.copyBufferToBuffer(d,0,u.gpuData.buffer,0,l),this.backend.device.queue.submit([p.finish()]),d.destroy(),et("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=Sn(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 et("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=
|
|
28
|
-
let dim${
|
|
29
|
-
let rest${
|
|
30
|
-
indices[${
|
|
31
|
-
current = rest${
|
|
26
|
+
*/var Ep;function by(){return Ep||(Ep=1,(function(c,r){var n=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(e=>typeof ar<"u"?ar:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof ar<"u"?ar:t)[s]}):e)(function(e){if(typeof ar<"u")return ar.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),_=(e,t)=>()=>(e&&(t=e(e=0)),t),U=(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))!C.call(e,o)&&o!==s&&a(e,o,{get:()=>t[o],enumerable:!(i=f(t,o))||i.enumerable});return e},te=e=>B(a({},"__esModule",{value:!0}),e),Q,ee,ie,ce,ue,Be=_(()=>{Q=new Map,ee=[],ie=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=Q.get(e);if(i===void 0)Q.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=ee.indexOf(e);o!==-1&&ee.splice(o,1);for(let l=0;l<ee.length;l++)if(Q.get(ee[l]).priority<=s){ee.splice(l,0,e);return}ee.push(e)}return}throw new TypeError("not a valid backend")},ce=async e=>{let t=Q.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}}},ue=async e=>{let t=e.executionProviders||[],s=t.map(h=>typeof h=="string"?h:h.name),i=s.length===0?ee:s,o,l=[],u=new Set;for(let h of i){let p=await ce(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 d=t.filter(h=>u.has(typeof h=="string"?h:h.name));return[o,new Proxy(e,{get:(h,p)=>p==="executionProviders"?d:Reflect.get(h,p)})]}}),Te=_(()=>{Be()}),oe,ne=_(()=>{oe="1.24.3"}),me,pe,Ne=_(()=>{ne(),me="warning",pe={wasm:{},webgl:{},webgpu:{},versions:{common:oe},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}`);me=e}},get logLevel(){return me}},Object.defineProperty(pe,"logLevel",{enumerable:!0})}),ge,rt=_(()=>{Ne(),ge=pe}),Xe,ft,Ge=_(()=>{Xe=(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",d=t?.norm,h,p;d===void 0||d.mean===void 0?h=[255,255,255,255]:typeof d.mean=="number"?h=[d.mean,d.mean,d.mean,d.mean]:(h=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(h[3]=d.mean[3])),d===void 0||d.bias===void 0?p=[0,0,0,0]:typeof d.bias=="number"?p=[d.bias,d.bias,d.bias,d.bias]:(p=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(p[3]=d.bias[3]));let g=l*o,m=0,w=g,b=g*2,S=-1;u==="RGBA"?(m=0,w=g,b=g*2,S=g*3):u==="RGB"?(m=0,w=g,b=g*2):u==="RBG"&&(m=0,b=g,w=g*2);for(let E=0;E<l;E++)for(let I=0;I<o;I++){let k=(e.data[m++]-p[0])*h[0],x=(e.data[w++]-p[1])*h[1],O=(e.data[b++]-p[2])*h[2],M=S===-1?255:(e.data[S++]-p[3])*h[3];i.fillStyle="rgba("+k+","+x+","+O+","+M+")",i.fillRect(I,E,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")},ft=(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 d=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,b=0,S=1,E=2,I=3,k=0,x=m,O=m*2,M=-1;d==="RGBA"?(k=0,x=m,O=m*2,M=m*3):d==="RGB"?(k=0,x=m,O=m*2):d==="RBG"&&(k=0,O=m,x=m*2),i=s.createImageData(o,l);for(let D=0;D<l*o;b+=w,S+=w,E+=w,I+=w,D++)i.data[b]=(e.data[k++]-g[0])*p[0],i.data[S]=(e.data[x++]-g[1])*p[1],i.data[E]=(e.data[O++]-g[2])*p[2],i.data[I]=M===-1?255:(e.data[M++]-g[3])*p[3]}else throw new Error("Can not access image data");return i}}),Ye,st,bt,ut,Je,Le,qe=_(()=>{de(),Ye=(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 d=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,b=1,S=2,E=3,I=0,k=p,x=p*2,O=-1;d==="RGB"&&(m=3,w=0,b=1,S=2,E=-1),h==="RGBA"?O=p*3:h==="RBG"?(I=0,x=p,k=p*2):h==="BGR"&&(x=0,k=p,I=p*2);for(let M=0;M<p;M++,w+=m,S+=m,b+=m,E+=m)g[I++]=(e[w]+u[0])/l[0],g[k++]=(e[b]+u[1])/l[1],g[x++]=(e[S]+u[2])/l[2],O!==-1&&E!==-1&&(g[O++]=(e[E]+u[3])/l[3]);return h==="RGBA"?new nt("float32",g,[1,4,s,i]):new nt("float32",g,[1,3,s,i])},st=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,d=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,b=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(w=t.resizedHeight,b=t.resizedWidth),t!==void 0){if(d=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=w,d.width=b}else d.tensorFormat="RGBA",d.height=w,d.width=b;m.drawImage(e,0,0),u=m.getImageData(0,0,b,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&&(d=t),d.format="RGBA",d.height=g,d.width=m,t!==void 0){let w=h();w.width=m,w.height=g;let b=p(w);if(b!=null)b.putImageData(e,0,0),u=b.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,b=e.width;return m.drawImage(e,0,0,b,w),u=m.getImageData(0,0,b,w).data,d.height=w,d.width=b,Ye(u,d)}else throw new Error("Can not access image data")}else{if(l)return new Promise((g,m)=>{let w=h(),b=p(w);if(!e||!b)return m();let S=new Image;S.crossOrigin="Anonymous",S.src=e,S.onload=()=>{w.width=S.width,w.height=S.height,b.drawImage(S,0,0,w.width,w.height);let E=b.getImageData(0,0,w.width,w.height);d.height=w.height,d.width=w.width,g(Ye(E.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return Ye(u,d);throw new Error("Input data provided is not supported - aborted tensor creation")},bt=(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})},ut=(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]})}),et,Y,Ie,tt,gt=_(()=>{et=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Y=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Ie=!1,tt=()=>{if(!Ie){Ie=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=globalThis.Float16Array,i=typeof s<"u"&&s.from;e&&(et.set("int64",BigInt64Array),Y.set(BigInt64Array,"int64")),t&&(et.set("uint64",BigUint64Array),Y.set(BigUint64Array,"uint64")),i?(et.set("float16",s),Y.set(s,"float16")):et.set("float16",Uint16Array)}}}),Vt,Et,dt=_(()=>{de(),Vt=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},Et=(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,de=_(()=>{Ge(),qe(),gt(),dt(),nt=class{constructor(e,t,s){tt();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=et.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,d;if(typeof e=="string")if(i=e,d=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=et.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(d=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=Y.get(e.constructor);if(h===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=h,u=e}if(d===void 0)d=[u.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");o=d,this.cpuData=u,this.dataLocation="cpu"}let l=Vt(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 st(e,t)}static fromTexture(e,t){return bt(e,t)}static fromGpuBuffer(e,t){return ut(e,t)}static fromMLTensor(e,t){return Je(e,t)}static fromPinnedBuffer(e,t,s){return Le(e,t,s)}toDataURL(e){return Xe(this,e)}toImageData(e){return ft(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 Et(this,e)}}}),xe,wt=_(()=>{de(),xe=nt}),$t,zt,fe,Ue,mt,ct,Mr=_(()=>{Ne(),$t=(e,t)=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeStamp(`${e}::ORT::${t}`)},zt=(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}`),$t("CPU",l);return}s[o].includes("TRACE_FUNC")&&(i=!0)}},fe=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||zt("BEGIN",e)},Ue=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||zt("END",e)},mt=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.time(`ORT::${e}`)},ct=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeEnd(`ORT::${e}`)}}),Ir,Fi=_(()=>{Be(),wt(),Mr(),Ir=class df{constructor(t){this.handler=t}async run(t,s,i){fe(),mt("InferenceSession.run");let o={},l={};if(typeof t!="object"||t===null||t instanceof xe||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 xe)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 xe)&&(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 d=await this.handler.run(t,o,l),h={};for(let p in d)if(Object.hasOwnProperty.call(d,p)){let g=d[p];g instanceof xe?h[p]=g:h[p]=new xe(g.type,g.data,g.dims)}return ct("InferenceSession.run"),Ue(),h}async release(){return this.handler.dispose()}static async create(t,s,i,o){fe(),mt("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[d,h]=await ue(u),p=await d.createInferenceSessionHandler(l,h);return ct("InferenceSession.create"),Ue(),new df(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),rn,Vi=_(()=>{Fi(),rn=Ir}),Gi=_(()=>{}),qi=_(()=>{}),Wi=_(()=>{}),Hi=_(()=>{}),ss={};U(ss,{InferenceSession:()=>rn,TRACE:()=>$t,TRACE_EVENT_BEGIN:()=>mt,TRACE_EVENT_END:()=>ct,TRACE_FUNC_BEGIN:()=>fe,TRACE_FUNC_END:()=>Ue,Tensor:()=>xe,env:()=>ge,registerBackend:()=>ie});var It=_(()=>{Te(),rt(),Vi(),wt(),Gi(),qi(),Mr(),Wi(),Hi()}),nn=_(()=>{}),is={};U(is,{default:()=>as});var sn,an,as,ji=_(()=>{Qh(),Qt(),cn(),sn="ort-wasm-proxy-worker",an=globalThis.self?.name===sn,an&&(self.onmessage=e=>{let{type:t,in:s}=e.data;try{switch(t){case"init-wasm":fn(s.wasm).then(()=>{Ua(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;Fa(o,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=s,o=Ti(i);postMessage({type:t,out:o});break}case"create":{let{model:i,options:o}=s;Ga(i,o).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":qa(s),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:o,inputs:l,outputIndices:u,options:d}=s;Ha(i,o,l,u,new Array(u.length).fill(null),d).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},Ka([...l,...h]))},h=>{postMessage({type:t,err:h})});break}case"end-profiling":ja(s),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),as=an?null:e=>new Worker(e??yt,{type:"classic",name:sn})}),os,ls,yt,on,Pr,us,ds,ln,cs,un,hs,dn,ps,cn=_(()=>{nn(),os=typeof location>"u"?void 0:location.origin,ls=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,yt=ls(),on=()=>{if(yt&&!yt.startsWith("blob:"))return yt.substring(0,yt.lastIndexOf("/")+1)},Pr=(e,t)=>{try{let s=t??yt;return(s?new URL(e,s):new URL(e)).origin===os}catch{return!1}},us=(e,t)=>{let s=t??yt;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},ds=(e,t)=>`${t??"./"}${e}`,ln=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},cs=async e=>(await import(e)).default,un=(ji(),te(is)).default,hs=async()=>{if(!yt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Pr(yt))return[void 0,un()];let e=await ln(yt);return[e,un(e)]},dn=void 0,ps=async(e,t,s,i)=>{let o=dn&&!(e||t);if(o)if(yt)o=Pr(yt)||i&&!s;else if(i&&!s)o=!0;else throw new Error("cannot determine the script source URL.");if(o)return[void 0,dn];{let l="ort-wasm-simd-threaded.jsep.mjs",u=e??us(l,t),d=s&&u&&!Pr(u,t),h=d?await ln(u):u??ds(l,t);return[d?h:void 0,await cs(h)]}}}),hn,Or,or,pn,fs,ms,gs,fn,ze,Qt=_(()=>{cn(),Or=!1,or=!1,pn=!1,fs=()=>{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}},ms=()=>{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}},gs=()=>{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}},fn=async e=>{if(Or)return Promise.resolve();if(or)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(pn)throw new Error("previous call to 'initializeWebAssembly()' failed.");or=!0;let t=e.initTimeout,s=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!gs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ms())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=fs();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,d=u?.href??u,h=o?.wasm,p=h?.href??h,g=e.wasmBinary,[m,w]=await ps(d,l,s>1,!!g||!!p),b=!1,S=[];if(t>0&&S.push(new Promise(E=>{setTimeout(()=>{b=!0,E()},t)})),S.push(new Promise((E,I)=>{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(d&&d.indexOf("blob:")!==0)k.locateFile=x=>new URL(x,d).href;else if(m){let x=on();x&&(k.locateFile=O=>x+O)}w(k).then(x=>{or=!1,Or=!0,hn=x,E(),m&&URL.revokeObjectURL(m)},x=>{or=!1,pn=!0,I(x)})})),await Promise.race(S),b)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},ze=()=>{if(Or&&hn)return hn;throw new Error("WebAssembly is not initialized yet.")}}),xt,zr,Ae,mn=_(()=>{Qt(),xt=(e,t)=>{let s=ze(),i=s.lengthBytesUTF8(e)+1,o=s._malloc(i);return s.stringToUTF8(e,o,i),t.push(o),o},zr=(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")zr(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}`)})},Ae=e=>{let t=ze(),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,"*"),d=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${d}`)}finally{t.stackRestore(s)}}}),ys,Ki=_(()=>{Qt(),mn(),ys=e=>{let t=ze(),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=xt(e.tag,i)),s=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,l),s===0&&Ae("Can't create run options."),e?.extra!==void 0&&zr(e.extra,"",new WeakSet,(u,d)=>{let h=xt(u,i),p=xt(d,i);t._OrtAddRunConfigEntry(s,h,p)!==0&&Ae(`Can't set a run config entry: ${u} - ${d}.`)}),[s,i]}catch(l){throw s!==0&&t._OrtReleaseRunOptions(s),i.forEach(u=>t._free(u)),l}}}),ws,vs,_s,lr,bs,Ss,Qi=_(()=>{Qt(),mn(),ws=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}`)}},vs=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},_s=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)},lr=(e,t,s,i)=>{let o=xt(t,i),l=xt(s,i);ze()._OrtAddSessionConfigEntry(e,o,l)!==0&&Ae(`Can't set a session config entry: ${t} - ${s}.`)},bs=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&&lr(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}`);lr(e,"preferredLayout",m.preferredLayout,s)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let d=xt(l,s),h=u.length,p=0,g=0;if(h>0){p=ze()._malloc(h*ze().PTR_SIZE),s.push(p),g=ze()._malloc(h*ze().PTR_SIZE),s.push(g);for(let m=0;m<h;m++)ze().setValue(p+m*ze().PTR_SIZE,u[m][0],"*"),ze().setValue(g+m*ze().PTR_SIZE,u[m][1],"*")}await ze()._OrtAppendExecutionProvider(e,d,p,g,h)!==0&&Ae(`Can't append execution provider: ${l}.`)}},Ss=async e=>{let t=ze(),s=0,i=[],o=e||{};_s(o);try{let l=ws(o.graphOptimizationLevel??"all"),u=vs(o.executionMode??"sequential"),d=typeof o.logId=="string"?xt(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"?xt(o.optimizedModelFilePath,i):0;if(s=t._OrtCreateSessionOptions(l,!!o.enableCpuMemArena,!!o.enableMemPattern,u,!!o.enableProfiling,0,d,h,p,g),s===0&&Ae("Can't create session options."),o.executionProviders&&await bs(s,o,i),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);lr(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 b=xt(m,i);t._OrtAddFreeDimensionOverride(s,b,w)!==0&&Ae(`Can't set a free dimension override: ${m} - ${w}.`)}return o.extra!==void 0&&zr(o.extra,"",new WeakSet,(m,w)=>{lr(s,m,w,i)}),[s,i]}catch(l){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&Ae("Can't release session options."),i.forEach(u=>t._free(u)),l}}}),Xt,Yt,Jt,gn,yn,wn,vn,Dn,Pe=_(()=>{Xt=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}`)}},Yt=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}`)}},Jt=(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},gn=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}`)}},yn=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}`)}},wn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",vn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Dn=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}`)}}}),_n,Ts=_(()=>{nn(),_n=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(d){if(d instanceof RangeError){let h=Math.ceil(i/65536);l=new WebAssembly.Memory({initial:h,maximum:h}).buffer}else throw d}let u=0;for(;;){let{done:d,value:h}=await o.read();if(d)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)}}),$s,Ln,Bn,br,Nn,Un,Ze,Zt=_(()=>{Pe(),$s=["V","I","W","E","F"],Ln=(e,t)=>{console.log(`[${$s[e]},${new Date().toISOString()}]${t}`)},Nn=(e,t)=>{Bn=e,br=t},Un=(e,t)=>{let s=yn(e),i=yn(Bn);s>=i&&Ln(s,typeof t=="function"?t():t)},Ze=(...e)=>{br&&Un(...e)}}),Fn,Sr,H,Hr,Vn,xs,ur,Me=_(()=>{Fn=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Sr=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 d=Fn.calcMatMulShape([e[i-2],e[i-1]],[t[o-2],t[o-1]]);if(d===void 0)return;[u[l-2],u[l-1]]=d}for(let d=s?3:1;d<=l;d++){let h=i-d<0?1:e[i-d],p=o-d<0?1:t[o-d];if(h!==p&&h>1&&p>1)return;let g=Math.max(h,p);if(h&&p)u[l-d]=Math.max(h,p);else{if(g>1)return;u[l-d]=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}},H=class Oi{static size(t){return Oi.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 Oi.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 Oi.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])}},Hr=class si{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 d=0;d<s.length-2;d++)d>=i.length?i.push(s[d+2]):i[d]=s[d+2];for(let d=0;d<i.length;d++)if(d<o.length){if(o[d]<0)throw new Error("strides should be greater than or equal to 1")}else o.push(1);for(let d=0;d<i.length;d++)if(d<l.length){if(l[d]<0)throw new Error("dilations should be greater than or equal to 1")}else l.push(1);for(let d=0;d<i.length*2;d++)if(d<u.length){if(u[d]<0)throw new Error("pad should be greater than or equal to 1")}else u.push(0);for(let d=0;d<i.length;d++){if(i[d]<=0)throw new Error("kernel shapes need to be greater than 0");if(u[d]>=i[d]||u[d+i.length]>=i[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,i,o,l,u,d){if(d){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++)si.adjustPadAndReturnShape(t[h+(u?1:2)],s[h],i[h],o[h],l,h,h+t.length-2,d)}}static computePoolOutputShape(t,s,i,o,l,u,d){if(s.length<=0)throw new Error("input shape must be of size greater than 0");let h=[s[0],s[1]];return si.computeShapeHelper(t,s,h,i,o,l,u,d),h}static computeConvOutputShape(t,s,i,o,l,u,d){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 si.computeShapeHelper(!1,t,h,i,o,l,u,d),h}static computeShapeHelper(t,s,i,o,l,u,d,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(si.adjustPadAndReturnShape(s[p+2],o[p],l[p],u[p],d,p,p+s.length-2,h))}static adjustPadAndReturnShape(t,s,i,o,l,u,d,h){let p=i*(o-1)+1;if(h&&h!=="NOTSET")switch(h){case"VALID":return l[u]=0,l[d]=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[d]=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[d]-p)/s+1)}},Vn=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,d;t?(l=e[1],u=e[0]):(l=e[0],u=e[1]);let h=-1;if(i?(d=s[0],h=1):(d=s[1],h=0),s[h]!==u)throw new Error("dimension mismatch");if(l<=0||d<=0||u<=0)throw new Error("invalid shape specified");if(o&&!Sr.isValidBroadcast(o,[l,d]))throw new Error("gemm: invalid bias shape for broadcast");return[l,d,u]}},xs=-34028234663852886e22,ur=34028234663852886e22}),Tr,jr=_(()=>{Pe(),Tr=(e,t)=>new(gn(t))(e)}),Dr,Kr,bn,Sn,dr,$r,Gn,qn,Wn,Es,Cs,li=_(()=>{Pe(),Zt(),Dr=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Kr=(e,t)=>{if(t==="int32")return e;let s=Dr.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(gn(t))(e.buffer,e.byteOffset,o);switch(t){case"int64":case"uint64":{let u=new Int32Array(o);for(let d=0;d<o;d++){let h=l[d];if(h>2147483647n||h<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");u[d]=Number(h)}return new Uint8Array(u.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(d=>d>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'`)}},bn=(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}`)}},Sn=1,dr=()=>Sn++,$r=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Gn=(e,t)=>{let s=Dr.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},qn=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 Gn(this.dataType,this.tensorShape)}destroy(){Ze("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=bn(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}},Wn=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=$r.get(t),!u||l?.input.dataTypes.includes(u))throw new Error(`WebNN backend does not support data type: ${t}`);Ze("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!==Gn(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 d=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,s,d,!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=Kr(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 Ze("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?bn(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()}},Es=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=dr();return this.tensorTrackersById.set(e,new Wn(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){Ze("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){Ze("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=dr(),u=new qn({sessionId:e,context:o,tensor:t,dataType:s,shape:i});return this.tensorTrackersById.set(l,new Wn(this,u)),this.externalTensors.add(u),l}async getCachedTensor(e,t,s,i,o,l,u){let d=this.getMLContext(e);for(let[p,g]of this.freeTensors.entries())if(g.canReuseTensor(d,t,s)){Ze("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${s}`);let m=this.freeTensors.splice(p,1)[0];return m.sessionId=e,m}Ze("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${s}}`);let h=await d.createTensor({dataType:u??t,shape:s,dimensions:s,usage:i,writable:o,readable:l});return new qn({sessionId:e,context:d,tensor:h,dataType:t,shape:s,fallbackDataType:u})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Cs=(...e)=>new Es(...e)}),Qr,ks,Rs,As=_(()=>{Pe(),Qt(),jr(),li(),Zt(),Qr=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),ks=(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])},Rs=class{constructor(e){this.tensorManager=Cs(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,Nn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Ze("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Ze("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let s of t)Ze("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=>ks(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){Ze("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,i,o){let l=Qr.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){Ze("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${s}}`);let i=Qr.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(!ze().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Ze("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 Tr(s,t)}}registerMLTensor(e,t,s,i){let o=Qr.get(s);if(!o)throw new Error(`Unsupported ONNX data type: ${s}`);let l=this.tensorManager.registerTensor(e,t,o,i);return Ze("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 d=e;e.startsWith("./")&&(d=e.substring(2));let h=l.get(d);if(!h)throw new Error(`File with name ${d} 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=Kr(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 Ze("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=Qr.get(Xt(t)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:s?!!o?.input.dataTypes.includes(i):!!o?.output.dataTypes.includes(i)}flush(){}}}),Hn=_(()=>{}),jn,Kn,Tn,Qn,Xn,Yn,Ms,Is,ui,Xi=_(()=>{Zt(),Hn(),jn=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]]),Kn=[],Tn=e=>Math.ceil(Number(e)/16)*16,Qn=e=>{for(let t=0;t<Kn.length;t++){let s=Kn[t];if(e<=s)return s}return Math.ceil(e/16)*16},Xn=1,Yn=()=>Xn++,Ms=async(e,t,s,i)=>{let o=Tn(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 d=l.getMappedRange();if(i){let h=i();return h.set(new Uint8Array(d,0,s)),h}else return new Uint8Array(d.slice(0,s))}finally{l.destroy()}},Is=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 jn)Kn.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=Tn(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 d=this.backend.device.createBuffer({mappedAtCreation:!0,size:l,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),h=d.getMappedRange();new Uint8Array(h).set(new Uint8Array(s,i,o)),d.unmap();let p=this.backend.device.createCommandEncoder();p.copyBufferToBuffer(d,0,u.gpuData.buffer,0,l),this.backend.device.queue.submit([p.finish()]),d.destroy(),Ze("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=Tn(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 Ze("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=Yn();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:t}),Ze("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Ze("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=Qn(e),i,o=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,l=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||l){let d=(o?this.freeBuffers:this.freeUniformBuffers).get(s);d?d.length>0?i=d.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:Yn(),type:0,buffer:i};return this.storageCache.set(u.id,{gpuData:u,originalSize:Number(e)}),Ze("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 Ze("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 Ms(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=jn.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&&(Ze("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ui=(...e)=>new Is(...e)}),y,$,A=_(()=>{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=>new y(e)}),z,P,G,N,L,V,Z,se,J,j,Ee,F,le,vt,We,Ce,He,be=_(()=>{Pe(),Me(),z=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]},N=(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:H.computeStrides(s)})}),t},V=e=>e%4===0?4:e%2===0?2:1,Z=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,se=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}<f32>(${s})`,J=(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,j=(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,Ee=(e,t,s,i,o)=>{let l=typeof s=="number",u=l?s:s.length,d=[...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},b=re=>typeof re=="string"?re:`${re}u`,S={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},E=l?"uniforms.":"",I=`${E}${e}_shape`,k=`${E}${e}_strides`,x="";for(let re=0;re<u-1;re++)x+=`
|
|
28
|
+
let dim${re} = current / ${j(k,re,u)};
|
|
29
|
+
let rest${re} = current % ${j(k,re,u)};
|
|
30
|
+
indices[${re}] = dim${re};
|
|
31
|
+
current = rest${re};
|
|
32
32
|
`;x+=`indices[${u-1}] = current;`;let O=u<2?"":`
|
|
33
33
|
fn o2i_${e}(offset: u32) -> ${w.indices} {
|
|
34
34
|
var indices: ${w.indices};
|
|
35
35
|
var current = offset;
|
|
36
36
|
${x}
|
|
37
37
|
return indices;
|
|
38
|
-
}`,M=
|
|
38
|
+
}`,M=re=>(S.offsetToIndices=!0,u<2?re:`o2i_${e}(${re})`),D=[];if(u>=2)for(let re=u-1;re>=0;re--)D.push(`${j(k,re,u)} * (indices[${re}])`);let W=u<2?"":`
|
|
39
39
|
fn i2o_${e}(indices: ${w.indices}) -> u32 {
|
|
40
40
|
return ${D.join("+")};
|
|
41
|
-
}`,q=
|
|
42
|
-
return ${
|
|
43
|
-
}`,`${Ve}(${
|
|
41
|
+
}`,q=re=>(S.indicesToOffset=!0,u<2?re:`i2o_${e}(${re})`),X=(...re)=>u===0?"0u":`${w.indices}(${re.map(b).join(",")})`,ae=(re,_e)=>u<2?`${re}`:`${j(re,_e,u)}`,ye=(re,_e,Ve)=>u<2?`${re}=${Ve};`:`${j(re,_e,u)}=${Ve};`,Ke={},Re=(re,_e)=>{S.broadcastedIndicesToOffset=!0;let Ve=`${_e.name}broadcastedIndicesTo${e}Offset`;if(Ve in Ke)return`${Ve}(${re})`;let pt=[];for(let yr=u-1;yr>=0;yr--){let Cr=_e.indicesGet("outputIndices",yr+_e.rank-u);pt.push(`${ae(k,yr)} * (${Cr} % ${ae(I,yr)})`)}return Ke[Ve]=`fn ${Ve}(outputIndices: ${_e.type.indices}) -> u32 {
|
|
42
|
+
return ${pt.length>0?pt.join("+"):"0u"};
|
|
43
|
+
}`,`${Ve}(${re})`},Oe=(re,_e)=>(()=>{if(w.storage===w.value)return`${e}[${re}]=${_e};`;if(w.storage==="vec2<u32>"&&w.value==="i32")return`${e}[${re}]=vec2<u32>(u32(${_e}), select(0u, 0xFFFFFFFFu, ${_e} < 0));`;if(w.storage==="vec2<u32>"&&w.value==="u32")return`${e}[${re}]=vec2<u32>(u32(${_e}), 0u);`;if(w.storage==="u32"&&w.value==="vec4<bool>")return`${e}[${re}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${_e}));`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),ot=re=>(()=>{if(w.storage===w.value)return`${e}[${re}]`;if(w.storage==="vec2<u32>"&&w.value==="i32")return`i32(${e}[${re}].x)`;if(w.storage==="vec2<u32>"&&w.value==="u32")return`u32(${e}[${re}].x)`;if(w.storage==="u32"&&w.value==="vec4<bool>")return`vec4<bool>(bool(${e}[${re}] & 0xFFu), bool(${e}[${re}] & 0xFF00u), bool(${e}[${re}] & 0xFF0000u), bool(${e}[${re}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),ve=u<2?"":`
|
|
44
44
|
fn get_${e}ByIndices(indices: ${w.indices}) -> ${g} {
|
|
45
|
-
return ${
|
|
46
|
-
}`,
|
|
47
|
-
fn get_${e}(${
|
|
48
|
-
return get_${e}ByIndices(${
|
|
49
|
-
}`})(),
|
|
45
|
+
return ${ot(`i2o_${e}(indices)`)};
|
|
46
|
+
}`,ke=u<2?"":(()=>{let re=d.map(Ve=>`d${Ve}: u32`).join(", "),_e=d.map(Ve=>`d${Ve}`).join(", ");return`
|
|
47
|
+
fn get_${e}(${re}) -> ${g} {
|
|
48
|
+
return get_${e}ByIndices(${X(_e)});
|
|
49
|
+
}`})(),Qe=(...re)=>{if(re.length!==u)throw new Error(`indices length must be ${u}`);let _e=re.map(b).join(",");return u===0?ot("0u"):u===1?ot(_e[0]):(S.get=!0,S.getByIndices=!0,S.indicesToOffset=!0,`get_${e}(${_e})`)},Fe=re=>u<2?ot(re):(S.getByIndices=!0,S.indicesToOffset=!0,`get_${e}ByIndices(${re})`),De=u<2?"":`
|
|
50
50
|
fn set_${e}ByIndices(indices: ${w.indices}, value: ${g}) {
|
|
51
|
-
${
|
|
52
|
-
}`,
|
|
53
|
-
fn set_${e}(${
|
|
54
|
-
set_${e}ByIndices(${
|
|
55
|
-
}`})();return{impl:()=>{let
|
|
56
|
-
`)},type:w,offsetToIndices:M,indicesToOffset:q,broadcastedIndicesToOffset:
|
|
51
|
+
${Oe(`i2o_${e}(indices)`,"value")}
|
|
52
|
+
}`,ht=u<2?"":(()=>{let re=d.map(Ve=>`d${Ve}: u32`).join(", "),_e=d.map(Ve=>`d${Ve}`).join(", ");return`
|
|
53
|
+
fn set_${e}(${re}, value: ${g}) {
|
|
54
|
+
set_${e}ByIndices(${X(_e)}, value);
|
|
55
|
+
}`})();return{impl:()=>{let re=[],_e=!1;return S.offsetToIndices&&(re.push(O),_e=!0),S.indicesToOffset&&(re.push(W),_e=!0),S.broadcastedIndicesToOffset&&(Object.values(Ke).forEach(Ve=>re.push(Ve)),_e=!0),S.set&&(re.push(ht),_e=!0),S.setByIndices&&(re.push(De),_e=!0),S.get&&(re.push(ke),_e=!0),S.getByIndices&&(re.push(ve),_e=!0),!l&&_e&&re.unshift(`const ${I} = ${w.indices}(${s.join(",")});`,`const ${k} = ${w.indices}(${H.computeStrides(s).join(",")});`),re.join(`
|
|
56
|
+
`)},type:w,offsetToIndices:M,indicesToOffset:q,broadcastedIndicesToOffset:Re,indices:X,indicesGet:ae,indicesSet:ye,set:(...re)=>{if(re.length!==u+1)throw new Error(`indices length must be ${u}`);let _e=re[u];if(typeof _e!="string")throw new Error("value must be string");let Ve=re.slice(0,u).map(b).join(",");return u===0?Oe("0u",_e):u===1?Oe(Ve[0],_e):(S.set=!0,S.setByIndices=!0,S.indicesToOffset=!0,`set_${e}(${Ve}, ${_e})`)},setByOffset:Oe,setByIndices:(re,_e)=>u<2?Oe(re,_e):(S.setByIndices=!0,S.indicesToOffset=!0,`set_${e}ByIndices(${re}, ${_e});`),get:Qe,getByOffset:ot,getByIndices:Fe,usage:i,name:e,strides:k,shape:I,rank:u}},F=(e,t,s,i=1)=>Ee(e,t,s,"input",i),le=(e,t,s,i=1)=>Ee(e,t,s,"output",i),vt=(e,t,s)=>Ee(e,t,s,"atomicOutput",1),We=(e,t,s,i=1)=>Ee(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=z){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
57
|
@builtin(workgroup_id) workgroup_id : vec3<u32>,
|
|
58
58
|
@builtin(local_invocation_index) local_idx : u32,
|
|
59
59
|
@builtin(local_invocation_id) local_id : vec3<u32>`:`@builtin(global_invocation_id) global_id : vec3<u32>,
|
|
@@ -71,13 +71,13 @@ React keys must be passed directly to JSX without using spread:
|
|
|
71
71
|
struct Uniforms { ${e.join(", ")} };
|
|
72
72
|
@group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(`
|
|
73
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])}},
|
|
75
|
-
var a: ${s.type.indices};`;for(let l=0;l<t;++l)o+=`a[${e[l]}]=i[${l}];`;return o+="return a;}"},
|
|
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])}},He=(e,t)=>new Ce(e,t)}),Dt,Bt,xr,Xr,Jn,Ps,St,tr,Os,je=_(()=>{Pe(),Me(),A(),be(),Dt=(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}`)},Bt=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),xr=(e,t)=>H.sortBasedOnPerm(e,Bt(e.length,t)),Xr=(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;}"},Jn=(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}},Ps=(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},St=(e,t)=>{let s=e.dataType,i=e.dims.length,o=Bt(i,t),l=xr(e.dims,o),u=e.dims,d=l,h=i<2||Ps(o,e.dims),p;if(h)return p=S=>{let E=F("input",s,u,4),I=le("output",s,d,4);return`
|
|
76
76
|
${S.registerUniform("output_size","u32").declareVariables(E,I)}
|
|
77
77
|
${S.mainStart()}
|
|
78
78
|
${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
79
79
|
output[global_idx] = input[global_idx];
|
|
80
|
-
}`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let S=H.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}=
|
|
80
|
+
}`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let S=H.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}=Jn(e.dims,o),w=H.areEqual(m,[2,3,1]),b=H.areEqual(m,[3,1,2]);if(g.length===2||w||b){u=w?[g[0],g[1]*g[2]]:b?[g[0]*g[1],g[2]]:g,d=[u[1],u[0]];let S=16;return p=E=>{let I=F("a",s,u.length),k=le("output",s,d.length);return`
|
|
81
81
|
${E.registerUniform("output_size","u32").declareVariables(I,k)}
|
|
82
82
|
var<workgroup> tile : array<array<${k.type.value}, ${S+1}>, ${S}>;
|
|
83
83
|
${E.mainStart([S,S,1])}
|
|
@@ -96,10 +96,10 @@ React keys must be passed directly to JSX without using spread:
|
|
|
96
96
|
if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {
|
|
97
97
|
${k.setByIndices(`${k.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")}
|
|
98
98
|
}
|
|
99
|
-
}`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let E=H.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d[1]/S),y:Math.ceil(d[0]/S)},programUniforms:[{type:12,data:E},...L(u,d)]}},getShaderSource:p}}return p=S=>{let E=
|
|
99
|
+
}`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let E=H.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d[1]/S),y:Math.ceil(d[0]/S)},programUniforms:[{type:12,data:E},...L(u,d)]}},getShaderSource:p}}return p=S=>{let E=F("a",s,u.length),I=le("output",s,d.length);return`
|
|
100
100
|
${S.registerUniform("output_size","u32").declareVariables(E,I)}
|
|
101
101
|
|
|
102
|
-
${
|
|
102
|
+
${Xr(o,i,E,I)}
|
|
103
103
|
|
|
104
104
|
${S.mainStart()}
|
|
105
105
|
${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -108,11 +108,11 @@ React keys must be passed directly to JSX without using spread:
|
|
|
108
108
|
let aIndices = perm(indices);
|
|
109
109
|
|
|
110
110
|
${I.setByOffset("global_idx",E.getByIndices("aIndices"))}
|
|
111
|
-
}`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let S=H.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...L(u,d)]}},getShaderSource:p}},tr=(e,t)=>{
|
|
111
|
+
}`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let S=H.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...L(u,d)]}},getShaderSource:p}},tr=(e,t)=>{Dt(e.inputs,t.perm),e.compute(St(e.inputs[0],t.perm))},Os=e=>$({perm:e.perm})}),er,di,cr,$n,Ct,qt,Zn,xn,zs,ci,Pt,hr,Yr,kt,Tt,rr,hi,pi,Mo,Io,Po,mm=_(()=>{Pe(),Me(),be(),Ji(),je(),er={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"},di={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"},cr={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},$n={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Ct=(e,t)=>{let 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]},Zn=(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},xn=(e,t)=>{for(let s=0;s<e.length;++s)if(e[e.length-s-1]!==t-1-s)return!1;return!0},zs=(e,t)=>{let s=[];if(!xn(e,t)){for(let i=0;i<t;++i)e.indexOf(i)===-1&&s.push(i);e.forEach(i=>s.push(i))}return s},ci=(e,t,s,i,o,l,u)=>{let d=s[0].dims,h=H.size(l),p=H.size(u),g=F("_A",s[0].dataType,d),m=le("output",o,l),w=64;h===1&&(w=256);let b=`
|
|
112
112
|
var<workgroup> aBestValues : array<f32, ${w}>;
|
|
113
113
|
`,S=E=>`
|
|
114
114
|
${E.registerUniform("reduceSize","u32").declareVariables(g,m)}
|
|
115
|
-
${
|
|
115
|
+
${b}
|
|
116
116
|
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
117
117
|
return ((a - 1u) / b + 1u);
|
|
118
118
|
}
|
|
@@ -144,9 +144,9 @@ React keys must be passed directly to JSX without using spread:
|
|
|
144
144
|
}
|
|
145
145
|
|
|
146
146
|
if (local_idx == 0u) {
|
|
147
|
-
${m.setByOffset("outputIndex",`${i==="mean"?`${m.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${m.type.storage}(${
|
|
147
|
+
${m.setByOffset("outputIndex",`${i==="mean"?`${m.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${m.type.storage}(${$n[i]})`}`)};
|
|
148
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:Yi(e.inputs,s),l=o.axes;l.length===0&&!o.noopWithEmptyAxes&&(l=e.inputs[0].dims.map((
|
|
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:Yi(e.inputs,s),l=o.axes;l.length===0&&!o.noopWithEmptyAxes&&(l=e.inputs[0].dims.map((b,S)=>S));let u=H.normalizeAxes(l,e.inputs[0].dims.length),d=u,h=e.inputs[0],p=zs(d,e.inputs[0].dims.length);p.length>0&&(h=e.compute(St(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],d=Ct(d.length,h.dims.length));let[g,m]=qt(h.dims,d),w=g;o.keepDims&&(w=Zn(g,u)),e.compute(ci(t,o.cacheKey,[h],i,e.inputs[0].dataType,w,m),{inputs:[h]})},hr=(e,t)=>{Pt(e,"ReduceMeanShared",t,"mean")},Yr=(e,t)=>{Pt(e,"ReduceL1Shared",t,"l1")},kt=(e,t)=>{Pt(e,"ReduceL2Shared",t,"l2")},Tt=(e,t)=>{Pt(e,"ReduceLogSumExpShared",t,"logSumExp")},rr=(e,t)=>{Pt(e,"ReduceMaxShared",t,"max")},hi=(e,t)=>{Pt(e,"ReduceMinShared",t,"min")},pi=(e,t)=>{Pt(e,"ReduceProdShared",t,"prod")},Mo=(e,t)=>{Pt(e,"ReduceSumShared",t,"sum")},Io=(e,t)=>{Pt(e,"ReduceSumSquareShared",t,"sumSquare")},Po=(e,t)=>{Pt(e,"ReduceLogSumShared",t,"logSum")}}),pr,Oo,fi,Yi,fr,zo,Do,Lo,Bo,No,Uo,Fo,Vo,Go,qo,mr,Wo,Ho,jo,Ko,Qo,Xo,Yo,Jo,Zo,el,Ji=_(()=>{Pe(),Me(),A(),be(),mm(),pr=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.")},Oo=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],fi=(e,t,s,i,o,l,u=!1,d=!1)=>{let h=[],p=s[0].dims,g=p.length,m=H.normalizeAxes(o,g),w=!d&&m.length===0;p.forEach((E,I)=>{w||m.indexOf(I)>=0?u&&h.push(1):h.push(E)});let b=h.length,S=H.size(h);return{name:e,shaderCache:t,getShaderSource:E=>{let I=[],k=F("_A",s[0].dataType,g),x=le("output",l,b),O=i(k,x,m),M=O[2];for(let D=0,W=0;D<g;D++)w||m.indexOf(D)>=0?(u&&W++,M=`for(var j${D}: u32 = 0; j${D} < ${p[D]}; j${D}++) {
|
|
150
150
|
${O[2].includes("last_index")?`let last_index = j${D};`:""}
|
|
151
151
|
${k.indicesSet("input_indices",D,`j${D}`)}
|
|
152
152
|
${M}
|
|
@@ -169,7 +169,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
169
169
|
`)}
|
|
170
170
|
}`},getRunData:()=>({outputs:[{dims:h,dataType:l}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...L(p,h)]})}},Yi=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(i=>s.push(Number(i))),$({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},fr=(e,t,s,i)=>{let o=e.inputs,l=o.length===1?s:Yi(o,s);e.compute(fi(t,{hint:l.cacheKey,inputDependencies:["rank"]},[o[0]],l.noopWithEmptyAxes&&l.axes.length===0?Oo:i,l.axes,o[0].dataType,l.keepDims,l.noopWithEmptyAxes),{inputs:[0]})},zo=(e,t)=>{pr(e.inputs),fr(e,"ReduceLogSum",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},Do=(e,t)=>{pr(e.inputs),fr(e,"ReduceL1",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},Lo=(e,t)=>{pr(e.inputs),fr(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);"])},Bo=(e,t)=>{pr(e.inputs),fr(e,"ReduceLogSumExp",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},No=(e,t)=>{pr(e.inputs),fr(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
171
|
`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},Uo=(e,t)=>{pr(e.inputs),fr(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});`]})},Fo=(e,t)=>{pr(e.inputs),fr(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")});`,""]})},Vo=(e,t)=>{pr(e.inputs),fr(e,"ReduceProd",t,(s,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},Go=(e,t)=>{pr(e.inputs),fr(e,"ReduceSum",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},qo=(e,t)=>{pr(e.inputs),fr(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;`,""])},mr=(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},Wo=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Uo(e,t):hr(e,t)},Ho=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Do(e,t):
|
|
172
|
+
`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},Vo=(e,t)=>{pr(e.inputs),fr(e,"ReduceProd",t,(s,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},Go=(e,t)=>{pr(e.inputs),fr(e,"ReduceSum",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},qo=(e,t)=>{pr(e.inputs),fr(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;`,""])},mr=(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},Wo=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Uo(e,t):hr(e,t)},Ho=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Do(e,t):Yr(e,t)},jo=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Lo(e,t):kt(e,t)},Ko=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bo(e,t):Tt(e,t)},Qo=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?No(e,t):rr(e,t)},Xo=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fo(e,t):hi(e,t)},Yo=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Vo(e,t):pi(e,t)},Jo=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Go(e,t):Mo(e,t)},Zo=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qo(e,t):Io(e,t)},el=(e,t)=>{mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zo(e,t):Po(e,t)}}),Zi,tl,rl,ea,gm=_(()=>{Pe(),A(),Ji(),Zi=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.")},tl=(e,t)=>{Zi(e.inputs);let s=(i,o,l)=>{let u=[];for(let d=0;d<i.rank;d++)(l.indexOf(d)>=0||l.length===0)&&u.push(`input_indices[${d}] = 0;`);return[`${u.join(`
|
|
173
173
|
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
174
174
|
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {
|
|
175
175
|
value = ${i.getByIndices("input_indices")};
|
|
@@ -179,7 +179,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
179
179
|
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {
|
|
180
180
|
value = ${i.getByIndices("input_indices")};
|
|
181
181
|
best_index = i32(last_index);
|
|
182
|
-
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(fi("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},ea=e=>$(e)}),nl,mi,sl,il,al,Ds,ol,ll,ta=
|
|
182
|
+
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(fi("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},ea=e=>$(e)}),nl,mi,sl,il,al,Ds,ol,ll,ta=_(()=>{Pe(),Me(),Hn(),be(),nl=(e,t)=>{let s=e[0],i=e[1],o=e[2],l=e[3],u=e[4],d=e[5];if(u&&d)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,b=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],b=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+b)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let E=0;if(u){if(w!==b)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||(E=u.dims[3])}let I=S+E,k=-1,x=0;if(l)throw new Error("Mask not supported");if(u)throw new Error("past is not supported");if(d){if(d.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(d.dims[0]!==h||d.dims[1]!==t.numHeads||d.dims[2]!==p||d.dims[3]!==I)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:h,sequenceLength:p,pastSequenceLength:E,kvSequenceLength:S,totalSequenceLength:I,maxSequenceLength:k,inputHiddenSize:g,hiddenSize:m,vHiddenSize:b,headSize:Math.floor(m/t.numHeads),vHeadSize:Math.floor(b/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:x,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},mi=(e,t,s)=>t&&e?`
|
|
183
183
|
let total_sequence_length_input = u32(${t.getByOffset("0")});
|
|
184
184
|
let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);
|
|
185
185
|
let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;
|
|
@@ -192,7 +192,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
192
192
|
`:`
|
|
193
193
|
${s?"let past_sequence_length = uniforms.past_sequence_length":""};
|
|
194
194
|
let present_sequence_length = total_sequence_length;
|
|
195
|
-
`,sl=(e,t,s,i,o,l,u,d)=>{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}],
|
|
195
|
+
`,sl=(e,t,s,i,o,l,u,d)=>{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}],b=G(e.dataType,h),S=N(1,h),E=["type"];u&&E.push("type"),d&&E.push("type");let I=k=>{let x=le("x",e.dataType,e.dims,h),O=[x],M=u?F("seq_lens",u.dataType,u.dims):void 0;M&&O.push(M);let D=d?F("total_sequence_length_input",d.dataType,d.dims):void 0;D&&O.push(D);let W=N(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
196
|
var<workgroup> thread_max: array<f32, ${p}>;
|
|
197
197
|
var<workgroup> thread_sum: array<f32, ${p}>;
|
|
198
198
|
${k.registerUniforms(q).declareVariables(...O)}
|
|
@@ -243,13 +243,13 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
243
243
|
for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {
|
|
244
244
|
x[offset + total_seq_id] = ${x.type.value}(${W}(0));
|
|
245
245
|
}`:""};
|
|
246
|
-
}`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${p};${
|
|
246
|
+
}`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${p};${b};${h}`,inputDependencies:E},getShaderSource:I,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:t*s},programUniforms:w})}},il=(e,t,s,i,o,l,u,d,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,b=m?[l.batchSize,w,p,l.headSize]:void 0,S=l.nReps?l.nReps:1,E=l.scale===0?1/Math.sqrt(l.headSize):l.scale,I=V(l.headSize),k=l.headSize/I,x=12,O={x:Math.ceil(p/x),y:Math.ceil(l.sequenceLength/x),z:l.batchSize*l.numHeads},M=[{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:E},{type:12,data:u},{type:12,data:l.kvSequenceLength},{type:12,data:S}],D=m&&i&&H.size(i.dims)>0,W=["type","type"];D&&W.push("type"),o&&W.push("type"),d&&W.push("type"),h&&W.push("type");let q=[{dims:g,dataType:t.dataType,gpuDataType:0}];m&&q.push({dims:b,dataType:t.dataType,gpuDataType:0});let X=ae=>{let ye=F("q",t.dataType,t.dims,I),Ke=F("key",s.dataType,s.dims,I),Re=[ye,Ke];if(D){let De=F("past_key",i.dataType,i.dims,I);Re.push(De)}o&&Re.push(F("attention_bias",o.dataType,o.dims));let Oe=d?F("seq_lens",d.dataType,d.dims):void 0;Oe&&Re.push(Oe);let ot=h?F("total_sequence_length_input",h.dataType,h.dims):void 0;ot&&Re.push(ot);let ve=le("output",t.dataType,g),ke=[ve];m&&ke.push(le("present_key",t.dataType,b,I));let Qe=N(1,I),Fe=[{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
247
|
const TILE_SIZE = ${x}u;
|
|
248
248
|
|
|
249
|
-
var<workgroup> tileQ: array<${
|
|
250
|
-
var<workgroup> tileK: array<${
|
|
251
|
-
${
|
|
252
|
-
${
|
|
249
|
+
var<workgroup> tileQ: array<${ye.type.storage}, ${x*x}>;
|
|
250
|
+
var<workgroup> tileK: array<${ye.type.storage}, ${x*x}>;
|
|
251
|
+
${ae.registerUniforms(Fe).declareVariables(...Re,...ke)}
|
|
252
|
+
${ae.mainStart([x,x,1])}
|
|
253
253
|
// x holds the N and y holds the M
|
|
254
254
|
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
255
255
|
let kvHeadIdx = ${S===1?"headIdx":"headIdx / uniforms.n_reps"};
|
|
@@ -259,13 +259,13 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
259
259
|
let n = workgroup_id.x * TILE_SIZE;
|
|
260
260
|
let sequence_length = uniforms.M;
|
|
261
261
|
var total_sequence_length = uniforms.N;
|
|
262
|
-
${mi(
|
|
262
|
+
${mi(Oe,ot,!0)}
|
|
263
263
|
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;
|
|
264
264
|
let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
265
265
|
${D&&m?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};
|
|
266
266
|
let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;
|
|
267
267
|
${m?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""}
|
|
268
|
-
var value = ${
|
|
268
|
+
var value = ${Qe}(0);
|
|
269
269
|
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
|
|
270
270
|
if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {
|
|
271
271
|
tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];
|
|
@@ -288,7 +288,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
288
288
|
workgroupBarrier();
|
|
289
289
|
|
|
290
290
|
for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {
|
|
291
|
-
value += ${
|
|
291
|
+
value += ${Qe}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);
|
|
292
292
|
}
|
|
293
293
|
|
|
294
294
|
workgroupBarrier();
|
|
@@ -298,13 +298,13 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
298
298
|
let headOffset = workgroup_id.z * uniforms.M * uniforms.N;
|
|
299
299
|
let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;
|
|
300
300
|
var sum: f32 = ${(()=>{switch(I){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: ${I}`)}})()};
|
|
301
|
-
output[outputIdx] = ${
|
|
301
|
+
output[outputIdx] = ${ve.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"};
|
|
302
302
|
}
|
|
303
|
-
}`};return{name:"AttentionProbs",shaderCache:{hint:`${I};${o!==void 0};${i!==void 0};${e}`,inputDependencies:W},getRunData:()=>({outputs:q,dispatchGroup:O,programUniforms:M}),getShaderSource:
|
|
303
|
+
}`};return{name:"AttentionProbs",shaderCache:{hint:`${I};${o!==void 0};${i!==void 0};${e}`,inputDependencies:W},getRunData:()=>({outputs:q,dispatchGroup:O,programUniforms:M}),getShaderSource:X}},al=(e,t,s,i,o,l,u=void 0,d=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,b=m?[o.batchSize,w,h,o.headSize]:void 0,S=[o.batchSize,o.sequenceLength,g],E=12,I={x:Math.ceil(o.vHeadSize/E),y:Math.ceil(o.sequenceLength/E),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&&H.size(i.dims)>0,O=["type","type"];x&&O.push("type"),u&&O.push("type"),d&&O.push("type");let M=[{dims:S,dataType:t.dataType,gpuDataType:0}];m&&M.push({dims:b,dataType:t.dataType,gpuDataType:0});let D=W=>{let q=F("probs",t.dataType,t.dims),X=F("v",s.dataType,s.dims),ae=[q,X];x&&ae.push(F("past_value",i.dataType,i.dims));let ye=u?F("seq_lens",u.dataType,u.dims):void 0;u&&ae.push(ye);let Ke=d?F("total_sequence_length_input",d.dataType,d.dims):void 0;d&&ae.push(Ke);let Re=[le("output",t.dataType,S)];m&&Re.push(le("present_value",t.dataType,b));let Oe=[{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
304
|
const TILE_SIZE = ${E}u;
|
|
305
305
|
var<workgroup> tileQ: array<${q.type.value}, ${E*E}>;
|
|
306
306
|
var<workgroup> tileV: array<${q.type.value}, ${E*E}>;
|
|
307
|
-
${W.registerUniforms(
|
|
307
|
+
${W.registerUniforms(Oe).declareVariables(...ae,...Re)}
|
|
308
308
|
${W.mainStart([E,E,1])}
|
|
309
309
|
let headIdx = workgroup_id.z % uniforms.num_heads;
|
|
310
310
|
let batchIdx = workgroup_id.z / uniforms.num_heads;
|
|
@@ -314,7 +314,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
314
314
|
let n = global_id.x;
|
|
315
315
|
let sequence_length = uniforms.M;
|
|
316
316
|
var total_sequence_length = uniforms.K;
|
|
317
|
-
${mi(
|
|
317
|
+
${mi(ye,Ke,!0)}
|
|
318
318
|
let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
|
|
319
319
|
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch
|
|
320
320
|
${x&&m?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};
|
|
@@ -355,13 +355,13 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
355
355
|
+ headIdx * uniforms.N + n;
|
|
356
356
|
output[outputIdx] = value;
|
|
357
357
|
}
|
|
358
|
-
}`};return{name:"AttentionScore",shaderCache:{hint:`${i!==void 0};${e}`,inputDependencies:O},getRunData:()=>({outputs:M,dispatchGroup:I,programUniforms:k}),getShaderSource:D}},Ds=(e,t,s,i,o,l,u,d,h,p,g=void 0,m=void 0)=>{let w=Math.min(e.outputCount,1+(u?1:0)+(d?1:0)),
|
|
358
|
+
}`};return{name:"AttentionScore",shaderCache:{hint:`${i!==void 0};${e}`,inputDependencies:O},getRunData:()=>({outputs:M,dispatchGroup:I,programUniforms:k}),getShaderSource:D}},Ds=(e,t,s,i,o,l,u,d,h,p,g=void 0,m=void 0)=>{let w=Math.min(e.outputCount,1+(u?1:0)+(d?1:0)),b=w>1?p.pastSequenceLength:0,S=b+p.kvSequenceLength,E=h&&H.size(h.dims)>0?h:void 0,I=[t,s];w>1&&u&&H.size(u.dims)>0&&I.push(u),E&&I.push(E),g&&I.push(g),m&&I.push(m);let k=e.compute(il(w,t,s,u,E,p,b,g,m),{inputs:I,outputs:w>1?[-1,1]:[-1]})[0];e.compute(sl(k,p.batchSize,p.numHeads,b,p.sequenceLength,S,g,m),{inputs:g&&m?[k,g,m]:[k],outputs:[]});let x=[k,i];w>1&&d&&H.size(d.dims)>0&&x.push(d),g&&x.push(g),m&&x.push(m),e.compute(al(w,k,i,d,p,b,g,m),{inputs:x,outputs:w>1?[0,2]:[0]})},ol=(e,t)=>{let s=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],i=t.sequenceLength,o=t.inputHiddenSize,l=t.headSize,u=12,d={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=le("output_q",h[0].dataType,s),b=le("output_k",h[0].dataType,s),S=le("output_v",h[0].dataType,s),E=F("input",h[0].dataType,h[0].dims),I=F("weight",h[1].dataType,h[1].dims),k=F("bias",h[2].dataType,h[2].dims),x=E.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
359
|
const TILE_SIZE = ${u}u;
|
|
360
360
|
var<workgroup> tileInput: array<${x}, ${u*u}>;
|
|
361
361
|
var<workgroup> tileWeightQ: array<${x}, ${u*u}>;
|
|
362
362
|
var<workgroup> tileWeightK: array<${x}, ${u*u}>;
|
|
363
363
|
var<workgroup> tileWeightV: array<${x}, ${u*u}>;
|
|
364
|
-
${m.registerUniforms(O).declareVariables(E,I,k,w,
|
|
364
|
+
${m.registerUniforms(O).declareVariables(E,I,k,w,b,S)}
|
|
365
365
|
${m.mainStart([u,u,1])}
|
|
366
366
|
let batchIndex = workgroup_id.z / uniforms.num_heads;
|
|
367
367
|
let headNumber = workgroup_id.z % uniforms.num_heads;
|
|
@@ -410,24 +410,24 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
410
410
|
output_k[outputIdx] = valueK;
|
|
411
411
|
output_v[outputIdx] = valueV;
|
|
412
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:d,programUniforms:p}),getShaderSource:g},{inputs:h,outputs:[-1,-1,-1]})},ll=(e,t)=>{let s=nl(e.inputs,t),[i,o,l]=ol(e,s);return Ds(e,i,o,l,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),ul,dl,cl,hl,ym=
|
|
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:d,programUniforms:p}),getShaderSource:g},{inputs:h,outputs:[-1,-1,-1]})},ll=(e,t)=>{let s=nl(e.inputs,t),[i,o,l]=ol(e,s);return Ds(e,i,o,l,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),ul,dl,cl,hl,ym=_(()=>{It(),Pe(),Me(),A(),be(),ul=(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((d,h)=>{if(d!==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")},dl=(e,t)=>{let{epsilon:s,spatial:i,format:o}=t,l=e[0].dims,u=i?V(l[l.length-1]):1,d=o==="NHWC"&&l.length>1?u:1,h=H.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,d),b=F("bias",e[2].dataType,e[2].dims,d),S=F("inputMean",e[3].dataType,e[3].dims,d),E=F("inputVar",e[4].dataType,e[4].dims,d),I=le("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
414
|
${I.indicesSet("outputIndices","0","0")}
|
|
415
415
|
let cOffset = ${I.indicesToOffset("outputIndices")};`;else{O=`var cIndices = ${w.type.indices}(0);
|
|
416
416
|
cIndices[0] = outputIndices[${l.length-1}];`;for(let M=1;M<w.rank;M++)O+=`cIndices[${M}] = outputIndices[${M}];`;O+=`let cOffset = ${w.indicesToOffset("cIndices")};`}return O},x=O=>`
|
|
417
417
|
const epsilon = ${s};
|
|
418
|
-
${O.registerUniform("outputSize","u32").declareVariables(m,w,
|
|
418
|
+
${O.registerUniform("outputSize","u32").declareVariables(m,w,b,S,E,I)}
|
|
419
419
|
${O.mainStart()}
|
|
420
420
|
${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
421
421
|
var outputIndices = ${I.offsetToIndices(`global_idx * ${u}`)};
|
|
422
422
|
${k()}
|
|
423
423
|
let scale = ${w.getByOffset("cOffset")};
|
|
424
|
-
let bias = ${
|
|
424
|
+
let bias = ${b.getByOffset("cOffset")};
|
|
425
425
|
let inputMean = ${S.getByOffset("cOffset")};
|
|
426
426
|
let inputVar = ${E.getByOffset("cOffset")};
|
|
427
427
|
let x = ${m.getByOffset("global_idx")};
|
|
428
428
|
let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;
|
|
429
429
|
${I.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}]})}},cl=e=>$(e),hl=(e,t)=>{let{inputs:s,outputCount:i}=e,o=cl({...t,outputCount:i});if(
|
|
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}]})}},cl=e=>$(e),hl=(e,t)=>{let{inputs:s,outputCount:i}=e,o=cl({...t,outputCount:i});if(ge.webgpu.validateInputContent&&ul(s,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(dl(s,o))}}),pl,fl,ml,wm=_(()=>{Me(),be(),pl=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")},fl=e=>{let t=e[0].dims,s=e[0].dims[2],i=H.size(t)/4,o=e[0].dataType,l=F("input",o,t,4),u=F("bias",o,[s],4),d=F("residual",o,t,4),h=le("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:p=>`
|
|
431
431
|
const channels = ${s}u / 4;
|
|
432
432
|
${p.declareVariables(l,u,d,h)}
|
|
433
433
|
|
|
@@ -436,7 +436,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
436
436
|
let value = ${l.getByOffset("global_idx")}
|
|
437
437
|
+ ${u.getByOffset("global_idx % channels")} + ${d.getByOffset("global_idx")};
|
|
438
438
|
${h.setByOffset("global_idx","value")}
|
|
439
|
-
}`}},ml=e=>{pl(e.inputs),e.compute(fl(e.inputs))}}),gl,
|
|
439
|
+
}`}},ml=e=>{pl(e.inputs),e.compute(fl(e.inputs))}}),gl,at,yl,wl,vl,_l,bl,Sl,Tl,$l,xl,El,Cl,kl,Rl,Al,Ls,Ml,gi,Il,Pl,Ol,zl,Dl,Ll,Bl,Nl,Ul,Fl,Vl,Gl,ql,Wl,Hl,jl,ra,Kl,na,sa,Ql,Xl,Yl,Jl,Zl,eu,ia=_(()=>{Pe(),Me(),A(),be(),gl=(e,t,s,i,o,l,u)=>{let d=Math.ceil(t/4),h="";typeof o=="string"?h=`${o}(a)`:h=o("a");let p=F("inputData",s,[d],4),g=le("outputData",i,[d],4),m=[{name:"vec_size",type:"u32"}];return u&&m.push(...u),`
|
|
440
440
|
${e.registerUniforms(m).declareVariables(p,g)}
|
|
441
441
|
|
|
442
442
|
${l??""}
|
|
@@ -446,7 +446,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas
|
|
|
446
446
|
|
|
447
447
|
let a = ${p.getByOffset("global_idx")};
|
|
448
448
|
${g.setByOffset("global_idx",h)}
|
|
449
|
-
}`},
|
|
449
|
+
}`},at=(e,t,s,i,o,l=e.dataType,u,d)=>{let h=[{type:12,data:Math.ceil(H.size(e.dims)/4)}];return u&&h.push(...u),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:p=>gl(p,H.size(e.dims),e.dataType,l,s,i,d),getRunData:p=>({outputs:[{dims:e.dims,dataType:l}],dispatchGroup:{x:Math.ceil(H.size(p[0].dims)/64/4)},programUniforms:h})}},yl=e=>{e.compute(at(e.inputs[0],"Abs","abs"))},wl=e=>{e.compute(at(e.inputs[0],"Acos","acos"))},vl=e=>{e.compute(at(e.inputs[0],"Acosh","acosh"))},_l=e=>{e.compute(at(e.inputs[0],"Asin","asin"))},bl=e=>{e.compute(at(e.inputs[0],"Asinh","asinh"))},Sl=e=>{e.compute(at(e.inputs[0],"Atan","atan"))},Tl=e=>{e.compute(at(e.inputs[0],"Atanh","atanh"))},$l=e=>$(e),xl=(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(at(e.inputs[0],"Cast",s,void 0,t.cacheKey,t.to))},El=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 $({min:t,max:s})},Cl=(e,t)=>{let s=t||El(e.inputs),i=N(e.inputs[0].dataType);e.compute(at(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]})},kl=e=>{e.compute(at(e.inputs[0],"Ceil","ceil"))},Rl=e=>{e.compute(at(e.inputs[0],"Cos","cos"))},Al=e=>{e.compute(at(e.inputs[0],"Cosh","cosh"))},Ls=e=>$(e),Ml=(e,t)=>{let s=N(e.inputs[0].dataType);e.compute(at(e.inputs[0],"Elu",i=>`elu_vf32(${i})`,`
|
|
450
450
|
const elu_alpha_ = ${s}(${t.alpha});
|
|
451
451
|
|
|
452
452
|
fn elu_f32(a: ${s}) -> ${s} {
|
|
@@ -467,7 +467,7 @@ fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {
|
|
|
467
467
|
let absv = abs(v);
|
|
468
468
|
let x = 1.0 / (1.0 + r0 * absv);
|
|
469
469
|
return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));
|
|
470
|
-
}`,Il=e=>{let t=N(e.inputs[0].dataType);e.compute(
|
|
470
|
+
}`,Il=e=>{let t=N(e.inputs[0].dataType);e.compute(at(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,gi(t)))},Pl=e=>{e.compute(at(e.inputs[0],"Exp","exp"))},Ol=e=>{e.compute(at(e.inputs[0],"Floor","floor"))},zl=e=>{let t=N(e.inputs[0].dataType);e.compute(at(e.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,gi(t)))},Dl=(e,t)=>{let s=N(e.inputs[0].dataType);e.compute(at(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))},Ll=e=>{e.compute(at(e.inputs[0],"Not",t=>`!${t}`))},Bl=e=>{e.compute(at(e.inputs[0],"Neg",t=>`-${t}`))},Nl=e=>{e.compute(at(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Ul=e=>{let t=N(e.inputs[0].dataType);e.compute(at(e.inputs[0],"Relu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`))},Fl=e=>{e.compute(at(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Vl=e=>$(e),Gl=(e,t)=>{let s=N(e.inputs[0].dataType);e.compute(at(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))},ql=e=>{e.compute(at(e.inputs[0],"Sin","sin"))},Wl=e=>{e.compute(at(e.inputs[0],"Sinh","sinh"))},Hl=e=>{e.compute(at(e.inputs[0],"Sqrt","sqrt"))},jl=e=>{e.compute(at(e.inputs[0],"Tan","tan"))},ra=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Kl=e=>{e.compute(at(e.inputs[0],"Tanh",ra))},na=(e="f32")=>`
|
|
471
471
|
const fast_gelu_a: ${e} = 0.5;
|
|
472
472
|
const fast_gelu_b: ${e} = 0.7978845608028654;
|
|
473
473
|
const fast_gelu_c: ${e} = 0.035677408136300125;
|
|
@@ -475,7 +475,7 @@ const fast_gelu_c: ${e} = 0.035677408136300125;
|
|
|
475
475
|
fn tanh_v(v: vec4<${e}>) -> vec4<${e}> {
|
|
476
476
|
return ${ra("v")};
|
|
477
477
|
}
|
|
478
|
-
`,sa=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Ql=e=>{let t=N(e.inputs[0].dataType);e.compute(
|
|
478
|
+
`,sa=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Ql=e=>{let t=N(e.inputs[0].dataType);e.compute(at(e.inputs[0],"FastGelu",sa,na(t),void 0,e.inputs[0].dataType))},Xl=(e,t)=>{let s=N(e.inputs[0].dataType);return e.compute(at(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},Yl=e=>{e.compute(at(e.inputs[0],"Log","log"))},Jl=(e,t)=>`
|
|
479
479
|
const alpha = vec4<${e}>(${t});
|
|
480
480
|
const one = ${e}(1.0);
|
|
481
481
|
const zero = ${e}(0.0);
|
|
@@ -492,7 +492,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
492
492
|
}
|
|
493
493
|
return x * x1;
|
|
494
494
|
}
|
|
495
|
-
`,Zl=e=>`quick_gelu_impl(${e})`,eu=(e,t)=>{let s=N(e.inputs[0].dataType);e.compute(
|
|
495
|
+
`,Zl=e=>`quick_gelu_impl(${e})`,eu=(e,t)=>{let s=N(e.inputs[0].dataType);e.compute(at(e.inputs[0],"QuickGelu",Zl,Jl(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),tu,ru,nu,vm=_(()=>{Me(),be(),ia(),tu=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")},ru=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=le("output",e[0].dataType,t,4),l=H.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:d=>`
|
|
496
496
|
const M_SQRT2 = sqrt(2.0);
|
|
497
497
|
const halfChannels = ${e[0].dims[2]/4/2}u;
|
|
498
498
|
|
|
@@ -510,12 +510,12 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
510
510
|
let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);
|
|
511
511
|
|
|
512
512
|
${o.setByOffset("global_idx","valueLeft * geluRight")}
|
|
513
|
-
}`}},nu=e=>{tu(e.inputs),e.compute(ru(e.inputs))}}),su,iu,gr,au,ou,lu,uu,du,cu,hu,pu,fu,mu,
|
|
513
|
+
}`}},nu=e=>{tu(e.inputs),e.compute(ru(e.inputs))}}),su,iu,gr,au,ou,lu,uu,du,cu,hu,pu,fu,mu,_m=_(()=>{Pe(),Me(),be(),su=(e,t,s,i,o,l,u,d,h,p,g,m)=>{let w,b;typeof d=="string"?w=b=(x,O)=>`${d}((${x}),(${O}))`:typeof d=="function"?w=b=d:(w=d.scalar,b=d.vector);let S=le("outputData",g,i.length,4),E=F("aData",h,t.length,4),I=F("bData",p,s.length,4),k;if(o)if(l){let x=H.size(t)===1,O=H.size(s)===1,M=t.length>0&&t[t.length-1]%4===0,D=s.length>0&&s[s.length-1]%4===0;x||O?k=S.setByOffset("global_idx",b(x?`${E.type.value}(${E.getByOffset("0")}.x)`:E.getByOffset("global_idx"),O?`${I.type.value}(${I.getByOffset("0")}.x)`:I.getByOffset("global_idx"))):k=`
|
|
514
514
|
let outputIndices = ${S.offsetToIndices("global_idx * 4u")};
|
|
515
515
|
let offsetA = ${E.broadcastedIndicesToOffset("outputIndices",S)};
|
|
516
516
|
let offsetB = ${I.broadcastedIndicesToOffset("outputIndices",S)};
|
|
517
|
-
${S.setByOffset("global_idx",
|
|
518
|
-
`}else k=S.setByOffset("global_idx",
|
|
517
|
+
${S.setByOffset("global_idx",b(u||M?E.getByOffset("offsetA / 4u"):`${E.type.value}(${E.getByOffset("offsetA / 4u")}[offsetA % 4u])`,u||D?I.getByOffset("offsetB / 4u"):`${I.type.value}(${I.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}
|
|
518
|
+
`}else k=S.setByOffset("global_idx",b(E.getByOffset("global_idx"),I.getByOffset("global_idx")));else{if(!l)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let x=(O,M,D="")=>{let W=`aData[indexA${M}][componentA${M}]`,q=`bData[indexB${M}][componentB${M}]`;return`
|
|
519
519
|
let outputIndices${M} = ${S.offsetToIndices(`global_idx * 4u + ${M}u`)};
|
|
520
520
|
let offsetA${M} = ${E.broadcastedIndicesToOffset(`outputIndices${M}`,S)};
|
|
521
521
|
let offsetB${M} = ${I.broadcastedIndicesToOffset(`outputIndices${M}`,S)};
|
|
@@ -543,7 +543,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
543
543
|
${e.mainStart()}
|
|
544
544
|
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
545
545
|
${k}
|
|
546
|
-
}`},iu=(e,t,s,i,o,l,u=s.dataType)=>{let d=s.dims.map(Number),h=i.dims.map(Number),p=!H.areEqual(d,h),g=d,m=H.size(d),w=!1,
|
|
546
|
+
}`},iu=(e,t,s,i,o,l,u=s.dataType)=>{let d=s.dims.map(Number),h=i.dims.map(Number),p=!H.areEqual(d,h),g=d,m=H.size(d),w=!1,b=!1,S=[p];if(p){let E=Sr.calcShape(d,h,!1);if(!E)throw new Error("Can't perform binary op on the given tensors");g=E.slice(),m=H.size(g);let I=H.size(d)===1,k=H.size(h)===1,x=d.length>0&&d[d.length-1]%4===0,O=h.length>0&&h[h.length-1]%4===0;S.push(I),S.push(k),S.push(x),S.push(O);let M=1;for(let D=1;D<g.length;D++){let W=d[d.length-D],q=h[h.length-D];if(W===q)M*=W;else break}M%4===0?(b=!0,w=!0):(I||k||x||O)&&(w=!0)}else w=!0;return S.push(w),{name:e,shaderCache:{hint:t+S.map(E=>E.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:E=>su(E,d,h,g,w,p,b,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(H.size(g)/4)},...L(d,h,g)]})}},gr=(e,t,s,i,o,l)=>{e.compute(iu(t,o??"",e.inputs[0],e.inputs[1],s,i,l))},au=e=>{gr(e,"Add",(t,s)=>`${t}+${s}`)},ou=e=>{gr(e,"Div",(t,s)=>`${t}/${s}`)},lu=e=>{gr(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4<u32>(${t}==${s})`},void 0,void 0,9)},uu=e=>{gr(e,"Mul",(t,s)=>`${t}*${s}`)},du=e=>{let t=F("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;gr(e,"Pow",{scalar:(s,i)=>`pow_custom(${s},${i})`,vector:(s,i)=>`pow_vector_custom(${s},${i})`},`
|
|
547
547
|
fn pow_custom(a : ${t}, b : ${t}) -> ${t} {
|
|
548
548
|
if (b == ${t}(0.0)) {
|
|
549
549
|
return ${t}(1.0);
|
|
@@ -556,7 +556,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
556
556
|
// TODO: implement vectorized pow
|
|
557
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
558
|
}
|
|
559
|
-
`)},cu=e=>{gr(e,"Sub",(t,s)=>`${t}-${s}`)},hu=e=>{gr(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4<u32>(${t}>${s})`},void 0,void 0,9)},pu=e=>{gr(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4<u32>(${t}<${s})`},void 0,void 0,9)},fu=e=>{gr(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4<u32>(${t}>=${s})`},void 0,void 0,9)},mu=e=>{gr(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4<u32>(${t}<=${s})`},void 0,void 0,9)}}),gu,yu,wu,vu,bu,
|
|
559
|
+
`)},cu=e=>{gr(e,"Sub",(t,s)=>`${t}-${s}`)},hu=e=>{gr(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4<u32>(${t}>${s})`},void 0,void 0,9)},pu=e=>{gr(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4<u32>(${t}<${s})`},void 0,void 0,9)},fu=e=>{gr(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4<u32>(${t}>=${s})`},void 0,void 0,9)},mu=e=>{gr(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4<u32>(${t}<=${s})`},void 0,void 0,9)}}),gu,yu,wu,vu,_u,bu,bm=_(()=>{Pe(),Me(),A(),be(),gu=(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,d)=>{if(d!==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")})}})},yu=(e,t)=>`
|
|
560
560
|
fn calculateInputIndex(index: u32) -> u32 {
|
|
561
561
|
let sizeInConcatAxis = array<u32, ${e}u>(${t});
|
|
562
562
|
for (var i: u32 = 0u; i < ${e}; i += 1u ) {
|
|
@@ -566,11 +566,11 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
566
566
|
}
|
|
567
567
|
return ${e}u;
|
|
568
568
|
}`,wu=(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
|
-
`)},vu=(e,t,s,i)=>{let o=H.size(s),l=new Array(e.length),u=new Array(e.length),d=0,h=[],p=[],g=[{type:12,data:o}];for(let E=0;E<e.length;++E)d+=e[E].dims[t],l[E]=d,p.push(e[E].dims.length),u[E]=
|
|
569
|
+
`)},vu=(e,t,s,i)=>{let o=H.size(s),l=new Array(e.length),u=new Array(e.length),d=0,h=[],p=[],g=[{type:12,data:o}];for(let E=0;E<e.length;++E)d+=e[E].dims[t],l[E]=d,p.push(e[E].dims.length),u[E]=F(`input${E}`,i,p[E]),h.push("rank"),g.push({type:12,data:l[E]});for(let E=0;E<e.length;++E)g.push(...L(e[E].dims));g.push(...L(s));let m=le("output",i,s.length),w=m.indicesGet("indices",t),b=Array.from(Array(l.length).keys()).map(E=>`uniforms.sizeInConcatAxis${E}`).join(","),S=E=>`
|
|
570
570
|
|
|
571
571
|
${(()=>{E.registerUniform("outputSize","u32");for(let I=0;I<e.length;I++)E.registerUniform(`sizeInConcatAxis${I}`,"u32");return E.declareVariables(...u,m)})()}
|
|
572
572
|
|
|
573
|
-
${yu(l.length,
|
|
573
|
+
${yu(l.length,b)}
|
|
574
574
|
|
|
575
575
|
${E.mainStart()}
|
|
576
576
|
${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
@@ -579,16 +579,16 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
579
579
|
|
|
580
580
|
let inputIndex = calculateInputIndex(${w});
|
|
581
581
|
if (inputIndex != 0u) {
|
|
582
|
-
let sizeInConcatAxis = array<u32, ${l.length}u>(${
|
|
582
|
+
let sizeInConcatAxis = array<u32, ${l.length}u>(${b});
|
|
583
583
|
${w} -= sizeInConcatAxis[inputIndex - 1u];
|
|
584
584
|
}
|
|
585
585
|
|
|
586
586
|
${wu(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}},
|
|
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}},_u=(e,t)=>{let s=e.inputs,i=s[0].dims,o=H.normalizeAxis(t.axis,i.length);gu(s,o);let l=i.slice();l[o]=s.reduce((d,h)=>d+(h.dims.length>o?h.dims[o]:0),0);let u=s.filter(d=>H.size(d.dims)>0);e.compute(vu(u,o,l,s[0].dataType),{inputs:u})},bu=e=>$({axis:e.axis})}),En,Cn,kn,aa,Rn=_(()=>{Pe(),Me(),En=(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
588
|
value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
|
|
589
|
-
`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},
|
|
589
|
+
`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Cn=(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})},kn=(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"})},aa=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||[xs,ur];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}}}),Nt,Su,oa=_(()=>{Nt=(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.`)}},Su=e=>`
|
|
590
590
|
${e?"value = value + getBiasByOutputCoords(coords);":""}
|
|
591
|
-
`}),Tu,Sm=
|
|
591
|
+
`}),Tu,Sm=_(()=>{Tu=e=>`
|
|
592
592
|
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
|
|
593
593
|
return dot(coords, vec4<i32>(
|
|
594
594
|
shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
|
|
@@ -597,24 +597,24 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
|
|
|
597
597
|
return dot(coords, vec4<i32>(
|
|
598
598
|
i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));
|
|
599
599
|
}
|
|
600
|
-
`}),Bs,la,ua=
|
|
600
|
+
`}),Bs,la,ua=_(()=>{Pe(),Me(),be(),Rn(),Bs=(e,t,s,i,o)=>{let l=i-s;return`
|
|
601
601
|
${Array.from({length:s}).map((u,d)=>`
|
|
602
602
|
if (${j(t.shape,d,t.rank)} != 1) {
|
|
603
603
|
${t.indicesSet(e,d,j(o,d+l,i))}
|
|
604
604
|
} else {
|
|
605
605
|
${t.indicesSet(e,d,0)}
|
|
606
606
|
}`).join("")}
|
|
607
|
-
`},la=(e,t,s,i,o=!1,l)=>{let u=e[0].dims,d=e[1].dims,h=u[u.length-2],p=d[d.length-1],g=u[u.length-1],m=V(p),w=V(g),
|
|
608
|
-
let b_data${
|
|
609
|
-
values[${
|
|
610
|
-
`}return
|
|
611
|
-
${M.registerUniforms(
|
|
607
|
+
`},la=(e,t,s,i,o=!1,l)=>{let u=e[0].dims,d=e[1].dims,h=u[u.length-2],p=d[d.length-1],g=u[u.length-1],m=V(p),w=V(g),b=V(h),S=H.size(s)/m/b,E=e.length>2,I=i?i.slice(0,-2):s.slice(0,-2),k=[H.size(I),h,p],x=[{type:12,data:S},{type:12,data:h},{type:12,data:p},{type:12,data:g}];Cn(t,x),x.push(...L(I,u,d)),E&&x.push(...L(e[2].dims)),x.push(...L(k));let O=M=>{let D=We("batch_dims",e[0].dataType,I.length),W=F("a",e[0].dataType,u.length,w),q=F("b",e[1].dataType,d.length,m),X=le("output",e[0].dataType,k.length,m),ae=G(X.type.tensor),ye=En(t,X.type.value,ae),Ke=[W,q],Re="";if(E){let ve=o?m:1;Ke.push(F("bias",e[2].dataType,e[2].dims.length,ve)),Re=`${o?`value += bias[col / ${ve}];`:`value += ${X.type.value}(bias[row + i]);`}`}let Oe=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];kn(t,Oe);let ot=()=>{let ve=`var a_data: ${W.type.value};`;for(let ke=0;ke<w;ke++)ve+=`
|
|
608
|
+
let b_data${ke} = b[(b_offset + (k + ${ke}) * uniforms.N + col) / ${m}];`;for(let ke=0;ke<b;ke++){ve+=`a_data = a[(a_offset + (row + ${ke}) * uniforms.K + k) / ${w}];`;for(let Qe=0;Qe<w;Qe++)ve+=`
|
|
609
|
+
values[${ke}] = fma(${q.type.value}(a_data${w===1?"":`[${Qe}]`}), b_data${Qe}, values[${ke}]);
|
|
610
|
+
`}return ve};return`
|
|
611
|
+
${M.registerUniforms(Oe).registerInternalVariables(D).declareVariables(...Ke,X)}
|
|
612
612
|
${M.mainStart()}
|
|
613
613
|
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
614
614
|
let col = (global_idx % (uniforms.N / ${m})) * ${m};
|
|
615
615
|
var index1 = global_idx / (uniforms.N / ${m});
|
|
616
|
-
let stride1 = uniforms.M / ${
|
|
617
|
-
let row = (index1 % stride1) * ${
|
|
616
|
+
let stride1 = uniforms.M / ${b};
|
|
617
|
+
let row = (index1 % stride1) * ${b};
|
|
618
618
|
let batch = index1 / stride1;
|
|
619
619
|
|
|
620
620
|
${s.length===2?"":`let batch_indices = ${D.offsetToIndices("batch")};`}
|
|
@@ -630,20 +630,20 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
|
|
|
630
630
|
${q.indicesSet("b_indices",q.rank-2,0)}
|
|
631
631
|
${q.indicesSet("b_indices",q.rank-1,0)}
|
|
632
632
|
let b_offset = ${q.indicesToOffset("b_indices")};
|
|
633
|
-
var values: array<${
|
|
633
|
+
var values: array<${X.type.value}, ${b}>;
|
|
634
634
|
for (var k: u32 = 0u; k < uniforms.K; k = k + ${w}) {
|
|
635
|
-
${
|
|
635
|
+
${ot()}
|
|
636
636
|
}
|
|
637
|
-
for (var i = 0u; i < ${
|
|
637
|
+
for (var i = 0u; i < ${b}u; i++) {
|
|
638
638
|
var value = values[i];
|
|
639
|
-
${
|
|
640
|
-
${
|
|
641
|
-
let cur_indices = ${
|
|
642
|
-
let offset = ${
|
|
643
|
-
${
|
|
639
|
+
${Re}
|
|
640
|
+
${ye}
|
|
641
|
+
let cur_indices = ${X.type.indices}(batch, row + i, col);
|
|
642
|
+
let offset = ${X.indicesToOffset("cur_indices")};
|
|
643
|
+
${X.setByOffset(`offset / ${m}`,"value")};
|
|
644
644
|
}
|
|
645
645
|
}
|
|
646
|
-
`};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${m};${w};${
|
|
646
|
+
`};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${m};${w};${b};${o}`,inputDependencies:E?["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}}}),$u,xu,da,ca,Eu,ha,Cu,yi,pa=_(()=>{Pe(),Me(),be(),Rn(),ua(),oa(),$u=(e,t)=>e?`
|
|
647
647
|
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
648
648
|
kStart + inputRow,
|
|
649
649
|
globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});
|
|
@@ -668,7 +668,7 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
|
|
|
668
668
|
acc[i] = BCached1 * ACached.y + acc[i];
|
|
669
669
|
acc[i] = BCached2 * ACached.z + acc[i];
|
|
670
670
|
${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}
|
|
671
|
-
}`,da=(e,t,s="f32",i,o=!1,l=32,u=!1,d=32)=>{let h=t[1]*e[1],p=t[0]*e[0],g=o?h:l,m=o?l:h,w=g/t[0],
|
|
671
|
+
}`,da=(e,t,s="f32",i,o=!1,l=32,u=!1,d=32)=>{let h=t[1]*e[1],p=t[0]*e[0],g=o?h:l,m=o?l:h,w=g/t[0],b=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
672
|
Otherwise, innerElementSize ${w} must be 3 or 4.
|
|
673
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
674
|
var<workgroup> mm_Asub: array<array<vec${w}<${s}>, ${g/w}>, ${m}>;
|
|
@@ -699,7 +699,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
699
699
|
var acc: array<vec4<${s}>, rowPerThread>;
|
|
700
700
|
|
|
701
701
|
// Loop over shared dimension.
|
|
702
|
-
let tileRowB = localRow * ${
|
|
702
|
+
let tileRowB = localRow * ${b};
|
|
703
703
|
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
704
704
|
// Load one tile of A into local memory.
|
|
705
705
|
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
|
|
@@ -709,7 +709,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
709
709
|
}
|
|
710
710
|
|
|
711
711
|
// Load one tile of B into local memory.
|
|
712
|
-
for (var innerRow = 0; innerRow < ${
|
|
712
|
+
for (var innerRow = 0; innerRow < ${b}; innerRow = innerRow + 1) {
|
|
713
713
|
let inputRow = tileRowB + innerRow;
|
|
714
714
|
let inputCol = tileCol;
|
|
715
715
|
mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${i?", batchIndices":""});
|
|
@@ -741,7 +741,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
741
741
|
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
742
742
|
globalRowStart + inputRow,
|
|
743
743
|
kStart + inputCol${t?", batchIndices":""});
|
|
744
|
-
`,Eu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ha=(e,t,s="f32",i,o=!1,l=32,u=!1,d=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
|
|
744
|
+
`,Eu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ha=(e,t,s="f32",i,o=!1,l=32,u=!1,d=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 b=w/t[1],S=m/t[0],E=l/t[1],I=h?`
|
|
745
745
|
let localRow = i32(localId.y);
|
|
746
746
|
let localCol = i32(localId.x);
|
|
747
747
|
let globalRowStart = i32(workgroupId.y) * ${p};
|
|
@@ -797,13 +797,13 @@ let globalRow = i32(globalId.y) * rowPerThread;
|
|
|
797
797
|
let globalCol = i32(globalId.x) * colPerThread;
|
|
798
798
|
let globalRowStart = i32(workgroupId.y) * ${p};
|
|
799
799
|
|
|
800
|
-
let tileRowA = i32(localId.y) * ${
|
|
800
|
+
let tileRowA = i32(localId.y) * ${b};
|
|
801
801
|
let tileColA = i32(localId.x) * ${S};
|
|
802
802
|
let tileRowB = i32(localId.y) * ${E};
|
|
803
803
|
// Loop over shared dimension.
|
|
804
804
|
for (var t = 0; t < num_tiles; t = t + 1) {
|
|
805
805
|
// Load one tile of A into local memory.
|
|
806
|
-
for (var innerRow = 0; innerRow < ${
|
|
806
|
+
for (var innerRow = 0; innerRow < ${b}; innerRow = innerRow + 1) {
|
|
807
807
|
for (var innerCol = 0; innerCol < ${S}; innerCol = innerCol + 1) {
|
|
808
808
|
let inputRow = tileRowA + innerRow;
|
|
809
809
|
let inputCol = tileColA + innerCol;
|
|
@@ -906,15 +906,15 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
906
906
|
${h.setByIndices("vec3<u32>(coords)","value")}
|
|
907
907
|
}
|
|
908
908
|
}
|
|
909
|
-
`},yi=(e,t,s,i,o=!1,l)=>{let u=e[0].dims,d=e[1].dims,h=u.slice(0,-2),p=d.slice(0,-2),g=i?i.slice(0,-2):s.slice(0,-2),m=H.size(g),w=u[u.length-2],
|
|
910
|
-
${
|
|
911
|
-
${
|
|
912
|
-
${E?da(I,k,
|
|
913
|
-
`};return{name:"MatMul",shaderCache:{hint:`${I};${t.activation};${E};${o}`,inputDependencies:
|
|
909
|
+
`},yi=(e,t,s,i,o=!1,l)=>{let u=e[0].dims,d=e[1].dims,h=u.slice(0,-2),p=d.slice(0,-2),g=i?i.slice(0,-2):s.slice(0,-2),m=H.size(g),w=u[u.length-2],b=u[u.length-1],S=d[d.length-1],E=b%4===0&&S%4===0,I=w<=8?[4,1,1]:[4,4,1],k=[8,8,1],x=[Math.ceil(S/k[0]/I[0]),Math.ceil(w/k[1]/I[1]),Math.ceil(m/k[2]/I[2])],O=E?4:1,M=[...h,w,b/O],D=M.length,W=[...p,b,S/O],q=W.length,X=[m,w,S/O],ae=[{type:6,data:w},{type:6,data:S},{type:6,data:b}];Cn(t,ae),ae.push(...L(g,M,W));let ye=["rank","rank"],Ke=e.length>2;Ke&&(ae.push(...L(e[2].dims)),ye.push("rank")),ae.push(...L(X));let Re=Oe=>{let ot=g.length,ve=We("batchDims",e[0].dataType,ot,1),ke=G(e[0].dataType),Qe=F("a",e[0].dataType,D,O),Fe=F("b",e[1].dataType,q,O),De=le("result",e[0].dataType,X.length,O),ht=[Qe,Fe];if(Ke){let yr=o?O:1;ht.push(F("bias",e[2].dataType,e[2].dims.length,yr))}let re=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];kn(t,re);let _e=G(De.type.tensor),Ve=En(t,De.type.value,_e),pt=Cu(O,Ke,Ve,[ve,Qe,Fe,De],o);return`
|
|
910
|
+
${Oe.registerUniforms(re).registerInternalVariables(ve).declareVariables(...ht,De)}
|
|
911
|
+
${pt}
|
|
912
|
+
${E?da(I,k,ke,ve):ha(I,k,ke,ve)}
|
|
913
|
+
`};return{name:"MatMul",shaderCache:{hint:`${I};${t.activation};${E};${o}`,inputDependencies:ye},getRunData:()=>({outputs:[{dims:l?l(s):s,dataType:e[0].dataType}],dispatchGroup:{x:x[0],y:x[1],z:x[2]},programUniforms:ae}),getShaderSource:Re}}}),ku,Ru,Tm=_(()=>{Pe(),Zt(),be(),Rn(),oa(),Sm(),pa(),ku=(e,t,s,i,o=!1,l,u=4,d=4,h=4,p="f32")=>{let g=ae=>{switch(ae){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 ${ae} is not supported.`)}},m=ae=>{switch(ae){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 ${ae} is not supported.`)}},w=e?`
|
|
914
914
|
let coord = vec4<i32>(batch, xRow, xCol, xCh);
|
|
915
915
|
`:`
|
|
916
916
|
let coord = vec4<i32>(batch, xCh, xRow, xCol);
|
|
917
|
-
`,
|
|
917
|
+
`,b=e?`
|
|
918
918
|
let coords = vec4<i32>(
|
|
919
919
|
batch,
|
|
920
920
|
row / outWidth,
|
|
@@ -969,7 +969,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
969
969
|
if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {
|
|
970
970
|
${m(d)}
|
|
971
971
|
}
|
|
972
|
-
return ${Nt(d,p)}(0.0);`,D=Nt(h,p),W=Nt(e?u:d,p),q=Nt(e?d:u,p),
|
|
972
|
+
return ${Nt(d,p)}(0.0);`,D=Nt(h,p),W=Nt(e?u:d,p),q=Nt(e?d:u,p),X=En(l,D,p);return`
|
|
973
973
|
fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${W} {
|
|
974
974
|
${e?O:M}
|
|
975
975
|
}
|
|
@@ -984,34 +984,34 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
984
984
|
{
|
|
985
985
|
var value = valueIn;
|
|
986
986
|
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
|
|
987
|
-
${
|
|
987
|
+
${b}
|
|
988
988
|
${Su(o)}
|
|
989
|
-
${
|
|
989
|
+
${X}
|
|
990
990
|
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
|
|
991
991
|
}
|
|
992
|
-
}`},Ru=(e,t,s,i,o,l,u,d,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],
|
|
993
|
-
fn setOutputAtIndex(flatIndex : i32, value : ${E?`vec4<${
|
|
994
|
-
result[flatIndex] = ${E?`vec4<${
|
|
992
|
+
}`},Ru=(e,t,s,i,o,l,u,d,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],b=p?s[1]:s[2],S=p?s[3]:s[1],E=p&&(g%4===0||g%3===0)&&S%4===0,I=p?S:w*b,k=p?w*b:S,x=[8,8,1],O=i<=8?[4,1,1]:[4,4,1],M=[Math.ceil(I/x[0]/O[0]),Math.ceil(k/x[1]/O[1]),Math.ceil(m/x[2]/O[2])];Ze("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${M}`);let D=E?p&&g%4!==0?3:4:1,W=x[1]*O[1],q=x[0]*O[0],X=Math.max(x[0]*D,x[1]),ae=i%W===0,ye=o%q===0,Ke=l%X===0,Re=E?[D,4,4]:[1,1,1],Oe=[{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}];Cn(t,Oe),Oe.push(...L(e[0].dims,e[1].dims));let ot=["rank","rank"];u&&(Oe.push(...L(e[2].dims)),ot.push("rank")),Oe.push(...L(s));let ve=ke=>{let Qe=[{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}];kn(t,Qe);let Fe=E?4:1,De=G(e[0].dataType),ht=`
|
|
993
|
+
fn setOutputAtIndex(flatIndex : i32, value : ${E?`vec4<${De}>`:De}) {
|
|
994
|
+
result[flatIndex] = ${E?`vec4<${De}>`:De}(value);
|
|
995
995
|
}
|
|
996
|
-
fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${E?`vec4<${
|
|
996
|
+
fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${E?`vec4<${De}>`:De}) {
|
|
997
997
|
let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));
|
|
998
998
|
setOutputAtIndex(flatIndex ${E?"/ 4":""}, value);
|
|
999
|
-
}`,
|
|
1000
|
-
fn getBiasByOutputCoords(coords : vec4<i32>) -> ${E?`vec4<${
|
|
999
|
+
}`,re=F("x",e[0].dataType,e[0].dims.length,D===3?1:D),_e=F("w",e[1].dataType,e[1].dims.length,Fe),Ve=[re,_e],pt=le("result",e[0].dataType,s.length,Fe);if(u){let yr=F("bias",e[2].dataType,e[2].dims.length,Fe);Ve.push(yr),ht+=`
|
|
1000
|
+
fn getBiasByOutputCoords(coords : vec4<i32>) -> ${E?`vec4<${De}>`:De} {
|
|
1001
1001
|
return bias[coords.${p?"w":"y"}${E?"/ 4":""}];
|
|
1002
1002
|
}`}return`
|
|
1003
1003
|
${Tu("uniforms.result_strides")}
|
|
1004
1004
|
//struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>,
|
|
1005
1005
|
// outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>,
|
|
1006
1006
|
// dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };
|
|
1007
|
-
${
|
|
1008
|
-
${
|
|
1009
|
-
${ku(p,
|
|
1010
|
-
${E?da(O,x,
|
|
1007
|
+
${ke.registerUniforms(Qe).declareVariables(...Ve,pt)}
|
|
1008
|
+
${ht}
|
|
1009
|
+
${ku(p,ae,ye,Ke,u,t,Re[0],Re[1],Re[2],De)}
|
|
1010
|
+
${E?da(O,x,De,void 0,!p,X):ha(O,x,De,void 0,!p,X,!1,void 0,d)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${D};${E};${ae};${ye};${Ke};${W};${q};${X}`,inputDependencies:ot},getRunData:()=>({outputs:[{dims:h?h(s):s,dataType:e[0].dataType}],dispatchGroup:{x:M[0],y:M[1],z:M[2]},programUniforms:Oe}),getShaderSource:ve}}}),Au,fa,Ns,Mu,ma,Iu,Pu,Ou,$m=_(()=>{Pe(),Zt(),Me(),be(),Rn(),oa(),Au=e=>{let t=1;for(let s=0;s<e.length;s++)t*=e[s];return t},fa=e=>typeof e=="number"?[e,e,e]:e,Ns=(e,t)=>t<=1?e:e+(e-1)*(t-1),Mu=(e,t,s,i=1)=>{let o=Ns(t,i);return Math.floor((e[0]*(s-1)-s+o)/2)},ma=(e,t,s,i,o)=>{o==null&&(o=Mu(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},Iu=(e,t,s,i,o,l,u,d,h,p)=>{let g,m,w,b;if(e==="VALID"&&(e=0),typeof e=="number"){g={top:e,bottom:e,left:e,right:e,front:e,back:e};let S=ma([t,s,i,1],[d,h,p],1,[o,l,u],e);m=S[0],w=S[1],b=S[2]}else if(Array.isArray(e)){if(!e.every((E,I,k)=>E===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=ma([t,s,i,1],[d,h,p],1,[o,l,u],e[0]);m=S[0],w=S[1],b=S[2]}else if(e==="SAME_UPPER"){m=Math.ceil(t/o),w=Math.ceil(s/l),b=Math.ceil(i/u);let S=(m-1)*o+d-t,E=(w-1)*l+h-s,I=(b-1)*u+p-i,k=Math.floor(S/2),x=S-k,O=Math.floor(E/2),M=E-O,D=Math.floor(I/2),W=I-D;g={top:O,bottom:M,left:D,right:W,front:k,back:x}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:g,outDepth:m,outHeight:w,outWidth:b}},Pu=(e,t,s,i,o,l=!1,u="channelsLast")=>{let d,h,p,g,m;if(u==="channelsLast")[d,h,p,g,m]=e;else if(u==="channelsFirst")[d,m,h,p,g]=e;else throw new Error(`Unknown dataFormat ${u}`);let[w,,b,S,E]=t,[I,k,x]=fa(s),[O,M,D]=fa(i),W=Ns(b,O),q=Ns(S,M),X=Ns(E,D),{padInfo:ae,outDepth:ye,outHeight:Ke,outWidth:Re}=Iu(o,h,p,g,I,k,x,W,q,X),Oe=l?w*m:w,ot=[0,0,0,0,0];return u==="channelsFirst"?ot=[d,Oe,ye,Ke,Re]:u==="channelsLast"&&(ot=[d,ye,Ke,Re,Oe]),{batchSize:d,dataFormat:u,inDepth:h,inHeight:p,inWidth:g,inChannels:m,outDepth:ye,outHeight:Ke,outWidth:Re,outChannels:Oe,padInfo:ae,strideDepth:I,strideHeight:k,strideWidth:x,filterDepth:b,filterHeight:S,filterWidth:E,effectiveFilterDepth:W,effectiveFilterHeight:q,effectiveFilterWidth:X,dilationDepth:O,dilationHeight:M,dilationWidth:D,inShape:e,outShape:ot,filterShape:t}},Ou=(e,t,s,i,o,l)=>{let u=l==="channelsLast";u?e[0].dims[3]:e[0].dims[1];let d=[64,1,1],h={x:s.map((I,k)=>k)},p=[Math.ceil(Au(h.x.map(I=>s[I]))/d[0]),1,1];Ze("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${p}`);let g=1,m=H.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}];Cn(t,w),w.push(...L(e[0].dims,e[1].dims));let b=["rank","rank"],S=e.length===3;S&&(w.push(...L(e[2].dims)),b.push("rank")),w.push(...L(s));let E=I=>{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}];kn(t,k);let x=1,O=G(e[0].dataType),M=F("x",e[0].dataType,e[0].dims.length,g),D=F("W",e[1].dataType,e[1].dims.length,x),W=[M,D],q=le("result",e[0].dataType,s.length,x),X="";if(S){let Ke=F("bias",e[2].dataType,e[2].dims.length,x);W.push(Ke),X+=`
|
|
1011
1011
|
fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${O} {
|
|
1012
1012
|
return bias[${u?j("coords",4,5):j("coords",1,5)}];
|
|
1013
|
-
}`}let
|
|
1014
|
-
${
|
|
1013
|
+
}`}let ae=Nt(g,O),ye=En(t,ae,O);return`
|
|
1014
|
+
${X}
|
|
1015
1015
|
fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
|
|
1016
1016
|
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
|
|
1017
1017
|
return ${M.getByIndices("aIndices")};
|
|
@@ -1113,9 +1113,9 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1113
1113
|
}
|
|
1114
1114
|
}
|
|
1115
1115
|
${S?"value = value + getBiasByOutputCoords(coords)":""};
|
|
1116
|
-
${
|
|
1116
|
+
${ye}
|
|
1117
1117
|
result[global_idx] = f32(value);
|
|
1118
|
-
}`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${u};${g};${S}`,inputDependencies:
|
|
1118
|
+
}`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${u};${g};${S}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:p[0],y:p[1],z:p[2]},programUniforms:w}),getShaderSource:E}}}),zu,Du,xm=_(()=>{Pe(),Me(),be(),Rn(),zu=(e,t,s,i)=>{let o=e.length>2,l=o?"value += b[output_channel];":"",u=e[0].dims,d=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=H.size(s)/m,b=[{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}];Cn(t,b),b.push(...L(u,[d[0],d[1],d[2],d[3]/m]));let S=o?["rank","rank","rank"]:["rank","rank"];b.push(...L([s[0],s[1],s[2],s[3]/m]));let E=I=>{let k=le("output",e[0].dataType,s.length,m),x=G(k.type.tensor),O=En(t,k.type.value,x),M=F("x",e[0].dataType,u.length),D=F("w",e[1].dataType,d.length,m),W=[M,D];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"}];kn(t,q);let X=h?`
|
|
1119
1119
|
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {
|
|
1120
1120
|
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
|
|
1121
1121
|
|
|
@@ -1173,11 +1173,11 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1173
1173
|
var in_channel_offset = group_id * uniforms.w_shape[${h?2:1}];
|
|
1174
1174
|
|
|
1175
1175
|
var value: ${k.type.value} = ${k.type.value}(0);
|
|
1176
|
-
${
|
|
1176
|
+
${X}
|
|
1177
1177
|
${l}
|
|
1178
1178
|
${O}
|
|
1179
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:
|
|
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:b}),getShaderSource:E}},Du=(e,t,s,i)=>{let o=e.length>2,l=V(s[3]),u=V(s[2]),d=H.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:d},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Cn(t,m),m.push(...L(h,p,g));let w=(u-1)*t.strides[1]+p[1],b=S=>{let E=le("output",e[0].dataType,g.length,l),I=G(E.type.tensor),k=En(t,E.type.value,I),x=F("x",e[0].dataType,h.length,l),O=F("w",e[1].dataType,p.length,l),M=[x,O];o&&M.push(F("b",e[2].dataType,e[2].dims,l));let D=o?"value += b[output_channel];":"",W=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return kn(t,W),`
|
|
1181
1181
|
${S.registerUniforms(W).declareVariables(...M,E)}
|
|
1182
1182
|
${S.mainStart()}
|
|
1183
1183
|
${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1222,34 +1222,34 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1222
1222
|
${k}
|
|
1223
1223
|
${E.set("batch","row","col + i","output_channel","value")};
|
|
1224
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(d/64)},programUniforms:m}),getShaderSource:
|
|
1226
|
-
let xValue = ${
|
|
1227
|
-
let wValue = ${
|
|
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(d/64)},programUniforms:m}),getShaderSource:b}}}),Lu,wi,Bu,vi,ga,ya,Nu,Uu,wa,Em=_(()=>{Me(),Tm(),$m(),pa(),xm(),Rn(),ua(),je(),Lu=(e,t,s,i,o,l)=>{let u=e[0],d=e.slice(l?1:2,l?3:4),h=d.length,p=t[0],g=t.slice(2).map((w,b)=>w+(w-1)*(s[b]-1)),m=d.map((w,b)=>w+i[b]+i[b+h]).map((w,b)=>Math.floor((w-g[b]+o[b])/o[b]));return m.splice(0,0,u),m.splice(l?3:1,0,p),m},wi=[2,3,1,0],Bu=(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")},vi=(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();Hr.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},ga=e=>{let t=aa(e),s=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,l=e.group,u=e.kernel_shape,d=e.pads,h=e.strides,p=e.w_is_const();return{autoPad:i,format:s,dilations:o,group:l,kernelShape:u,pads:d,strides:h,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},ya=(e,t,s,i)=>{let o=s.format==="NHWC",l=Lu(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(St(t[1],wi),{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(Du(W,s,l,i),{inputs:W}):e.compute(zu(W,s,l,i),{inputs:W});return}let u=t.length===3,d=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],b=l[o?2:3],S=l[o?3:1],E=o&&g===d&&m===h&&s.pads[0]===0&&s.pads[1]===0;if(E||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,X,ae,ye=[];if(o){let Oe=e.kernelCustomData.wT??e.compute(St(t[1],wi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Oe),E){let ot=d*h*p;q=t[0].reshape([1,W,ot]),X=Oe.reshape([1,ot,S]),ae=[1,W,S]}else q=t[0].reshape([W,d*h,p]),X=Oe.reshape([1,p,S]),ae=[W,w*b,S];ye.push(q),ye.push(X)}else q=t[0].reshape([W,p,d*h]),X=t[1].reshape([1,S,p]),ae=[W,S,w*b],ye.push(X),ye.push(q);u&&ye.push(t[2]);let Ke=ae[2],Re=ye[0].dims[ye[0].dims.length-1];Ke<8&&Re<8?e.compute(la(ye,s,l,ae,o,i),{inputs:ye}):e.compute(yi(ye,s,l,ae,o,i),{inputs:ye});return}let I=!0,k=e.kernelCustomData.wT??e.compute(St(t[1],wi),{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*b:S,M=o?S:w*b,D=g*m*p;e.compute(Ru(x,s,l,O,M,D,u,I,i),{inputs:x})},Nu=(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),d=[1].concat(t.kernelShape),h=vi({...t,pads:o,strides:l,dilations:u,kernelShape:d},i);ya(e,i,h,p=>s?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Uu=(e,t,s)=>{let i=s.format==="NHWC"?"channelsLast":"channelsFirst",o=vi(s,t),l=s.autoPad==="NOTSET"?s.pads:s.autoPad,u=Pu(t[0].dims,t[1].dims,s.strides,s.dilations,l,!1,i);e.compute(Ou(t,o,u.outShape,[u.filterDepth,u.filterHeight,u.filterWidth],[u.padInfo.front,u.padInfo.top,u.padInfo.left],i))},wa=(e,t)=>{if(Bu(e.inputs,t),e.inputs[0].dims.length===3)Nu(e,t);else if(e.inputs[0].dims.length===5)Uu(e,e.inputs,t);else{let s=vi(t,e.inputs);ya(e,e.inputs,s)}}}),Fu,Cm=_(()=>{Pe(),Zt(),Me(),be(),Fu=(e,t,s)=>{let i=e.length>2,o=t.outputShape,l=t.format==="NHWC",u=t.group,d=e[1].dims,h=d[2]/u,p=d[3],g=l?V(h):1,m=l&&p===1&&h>=4,w=m?Math.floor(h/4)*4:Math.floor(h/g)*g,b=h-w,S=l?V(p):1,E=l?p===1?g:S:1,I=H.size(o)/S,k=[Math.ceil(I/64),1,1];Ze("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${k}`);let x=["rank","rank"],O=[t.strides[0],t.strides[1]],M=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],D=[t.dilations[0],t.dilations[1]],W=[M[0]+(t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)),M[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)],X=[{type:12,data:I},{type:12,data:O},{type:12,data:M},{type:12,data:D},{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&&(X.push(...L(e[2].dims)),x.push("rank")),X.push(...L(o));let ae=ye=>{let Ke=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:O.length},{name:"filter_dims",type:"u32",length:M.length},{name:"dilations",type:"u32",length:M.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"}],Re=G(e[0].dataType),Oe=l?1:2,ot=l?2:3,ve=l?3:1,ke=F("W",e[1].dataType,e[1].dims.length,E),Qe=F("Dy",e[0].dataType,e[0].dims.length,g),Fe=[Qe,ke];i&&Fe.push(F("bias",e[2].dataType,[o[ve]].length,S));let De=le("result",e[0].dataType,o.length,S),ht=()=>{let Ve="";if(m)g===4?Ve+=`
|
|
1226
|
+
let xValue = ${Qe.getByOffset("x_offset")};
|
|
1227
|
+
let wValue = ${ke.getByOffset("w_offset")};
|
|
1228
1228
|
dotProd = dotProd + dot(xValue, wValue);
|
|
1229
1229
|
x_offset += 1u;
|
|
1230
1230
|
w_offset += 1u;`:g===2?Ve+=`
|
|
1231
|
-
dotProd = dotProd + dot(vec4<${
|
|
1231
|
+
dotProd = dotProd + dot(vec4<${Re}>(${Qe.getByOffset("x_offset")}, ${Qe.getByOffset("x_offset + 1u")}), vec4<${Re}>(${ke.getByOffset("w_offset")}, ${ke.getByOffset("w_offset + 1u")}));
|
|
1232
1232
|
x_offset += 2u;
|
|
1233
1233
|
w_offset += 2u;`:g===1&&(Ve+=`
|
|
1234
|
-
dotProd = dotProd + dot(vec4<${
|
|
1234
|
+
dotProd = dotProd + dot(vec4<${Re}>(${Qe.getByOffset("x_offset")}, ${Qe.getByOffset("x_offset + 1u")}, ${Qe.getByOffset("x_offset + 2u")}, ${Qe.getByOffset("x_offset + 3u")}), vec4<${Re}>(${ke.getByOffset("w_offset")}, ${ke.getByOffset("w_offset + 1u")}, ${ke.getByOffset("w_offset + 2u")}, ${ke.getByOffset("w_offset + 3u")}));
|
|
1235
1235
|
x_offset += 4u;
|
|
1236
1236
|
w_offset += 4u;`);else if(Ve+=`
|
|
1237
|
-
let xValue = ${l?
|
|
1237
|
+
let xValue = ${l?Qe.getByOffset(`${Qe.indicesToOffset(`${Qe.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${g}`):Qe.get("batch","inputChannel","idyR","idyC")};
|
|
1238
1238
|
`,g===1)Ve+=`
|
|
1239
|
-
let w_offset = ${
|
|
1240
|
-
let wValue = ${
|
|
1241
|
-
dotProd = dotProd + xValue * wValue;`;else for(let
|
|
1242
|
-
let wValue${
|
|
1243
|
-
dotProd = dotProd + xValue[${
|
|
1244
|
-
+ ${
|
|
1245
|
-
let xValue = ${
|
|
1246
|
-
let wValue = ${
|
|
1247
|
-
dotProd = dotProd + dot(xValue, wValue);`}return Ve},
|
|
1248
|
-
let outputIndices = ${
|
|
1249
|
-
let batch = ${
|
|
1250
|
-
let d1 = ${
|
|
1251
|
-
let r = ${
|
|
1252
|
-
let c = ${
|
|
1239
|
+
let w_offset = ${ke.indicesToOffset(`${ke.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};
|
|
1240
|
+
let wValue = ${ke.getByOffset(`w_offset / ${E}`)};
|
|
1241
|
+
dotProd = dotProd + xValue * wValue;`;else for(let pt=0;pt<g;pt++)Ve+=`
|
|
1242
|
+
let wValue${pt} = ${ke.getByOffset(`${ke.indicesToOffset(`${ke.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${pt}, wOutChannel)`)} / ${E}`)};
|
|
1243
|
+
dotProd = dotProd + xValue[${pt}] * wValue${pt};`;return Ve},re=()=>{if(b===0)return"";if(!m)throw new Error(`packInputAs4 ${m} is not true.`);let Ve="";if(g===1){Ve+="dotProd = dotProd";for(let pt=0;pt<b;pt++)Ve+=`
|
|
1244
|
+
+ ${Qe.getByOffset(`x_offset + ${pt}`)} * ${ke.getByOffset(`w_offset + ${pt}`)}`;Ve+=";"}else if(g===2){if(b!==2)throw new Error(`Invalid inputChannelsRemainder ${b}.`);Ve+=`
|
|
1245
|
+
let xValue = ${Qe.getByOffset("x_offset")};
|
|
1246
|
+
let wValue = ${ke.getByOffset("w_offset")};
|
|
1247
|
+
dotProd = dotProd + dot(xValue, wValue);`}return Ve},_e=`
|
|
1248
|
+
let outputIndices = ${De.offsetToIndices(`global_idx * ${S}`)};
|
|
1249
|
+
let batch = ${De.indicesGet("outputIndices",0)};
|
|
1250
|
+
let d1 = ${De.indicesGet("outputIndices",ve)};
|
|
1251
|
+
let r = ${De.indicesGet("outputIndices",Oe)};
|
|
1252
|
+
let c = ${De.indicesGet("outputIndices",ot)};
|
|
1253
1253
|
let dyCorner = vec2<i32>(i32(r), i32(c)) - uniforms.pads;
|
|
1254
1254
|
let dyRCorner = dyCorner.x;
|
|
1255
1255
|
let dyCCorner = dyCorner.y;
|
|
@@ -1257,7 +1257,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1257
1257
|
let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;
|
|
1258
1258
|
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
1259
1259
|
// ? = to be determined. : = across all values in that axis.
|
|
1260
|
-
var dotProd = ${
|
|
1260
|
+
var dotProd = ${De.type.value}(0.0);
|
|
1261
1261
|
var wR: u32 = 0;
|
|
1262
1262
|
if (uniforms.dilations.x == 1) {
|
|
1263
1263
|
// Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0
|
|
@@ -1267,9 +1267,9 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1267
1267
|
if (wR % uniforms.dilations.x != 0) {
|
|
1268
1268
|
continue;
|
|
1269
1269
|
}
|
|
1270
|
-
let dyR = (${
|
|
1270
|
+
let dyR = (${Re}(dyRCorner) + ${Re}(wR)) / ${Re}(uniforms.strides[0]);
|
|
1271
1271
|
let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;
|
|
1272
|
-
if (dyR < 0.0 || dyR >= ${
|
|
1272
|
+
if (dyR < 0.0 || dyR >= ${Re}(uniforms.Dy_shape[${Oe}]) || fract(dyR) > 0.0 ||
|
|
1273
1273
|
wRPerm < 0) {
|
|
1274
1274
|
continue;
|
|
1275
1275
|
}
|
|
@@ -1283,34 +1283,34 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1283
1283
|
if (wC % uniforms.dilations.y != 0) {
|
|
1284
1284
|
continue;
|
|
1285
1285
|
}
|
|
1286
|
-
let dyC = (${
|
|
1286
|
+
let dyC = (${Re}(dyCCorner) + ${Re}(wC)) / ${Re}(uniforms.strides.y);
|
|
1287
1287
|
let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;
|
|
1288
|
-
if (dyC < 0.0 || dyC >= ${
|
|
1288
|
+
if (dyC < 0.0 || dyC >= ${Re}(uniforms.Dy_shape[${ot}]) ||
|
|
1289
1289
|
fract(dyC) > 0.0 || wCPerm < 0) {
|
|
1290
1290
|
continue;
|
|
1291
1291
|
}
|
|
1292
1292
|
let idyC: u32 = u32(dyC);
|
|
1293
1293
|
var inputChannel = groupId * uniforms.input_channels_per_group;
|
|
1294
1294
|
${m?`
|
|
1295
|
-
var x_offset = ${
|
|
1296
|
-
var w_offset = ${
|
|
1295
|
+
var x_offset = ${Qe.indicesToOffset(`${Qe.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${g};
|
|
1296
|
+
var w_offset = ${ke.indicesToOffset(`${ke.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${E};
|
|
1297
1297
|
`:""}
|
|
1298
1298
|
for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${m?4:g}) {
|
|
1299
|
-
${
|
|
1299
|
+
${ht()}
|
|
1300
1300
|
inputChannel = inputChannel + ${m?4:g};
|
|
1301
1301
|
}
|
|
1302
|
-
${
|
|
1302
|
+
${re()}
|
|
1303
1303
|
wC = wC + uniforms.strides.y - 1;
|
|
1304
1304
|
}
|
|
1305
1305
|
wR = wR + uniforms.strides[0] - 1;
|
|
1306
1306
|
}
|
|
1307
1307
|
let value = dotProd${i?` + bias[d1 / ${S}]`:""};
|
|
1308
|
-
${
|
|
1308
|
+
${De.setByOffset("global_idx","value")};
|
|
1309
1309
|
`;return`
|
|
1310
|
-
${
|
|
1311
|
-
${
|
|
1312
|
-
${
|
|
1313
|
-
${
|
|
1310
|
+
${ye.registerUniforms(Ke).declareVariables(...Fe,De)}
|
|
1311
|
+
${ye.mainStart()}
|
|
1312
|
+
${ye.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};
|
|
1313
|
+
${_e}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${g}${E}${S}${m}${b}`,inputDependencies:x},getRunData:()=>({dispatchGroup:{x:k[0],y:k[1],z:k[2]},outputs:[{dims:s?s(o):o,dataType:e[0].dataType}],programUniforms:X}),getShaderSource:ae}}}),Vu,Gu,qu,va,Wu,Hu,_a,ju,Ku,km=_(()=>{Cm(),Rn(),je(),Vu=(e,t,s,i,o,l)=>(e-1)*t+s+(i-1)*o+1-l,Gu=(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)},qu=(e,t,s,i,o,l,u,d,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],b=t[d?3:1]*o;for(let S=0,E=e.length-g-(d?1:0);S<g;++S,++E){let I=e[E],k=m?I*u[S]:p[S],x=Vu(I,u[S],l[S],t[E],s[S],k);Gu(x,i,l,S,S+g),m&&p.push(u[S]*(I-1)+h[S]+(t[E]-1)*s[S]+1-l[S]-l[S+g])}p.splice(0,0,w),p.splice(d?3:1,0,b)},va=(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(),d=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)}qu(d,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},Wu=e=>{let t=aa(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,d=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:d,strides:h,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},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!==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,d)=>u+d,0)>0&&t.dilations.length!==l)throw new Error(`dilations should be ${l}D`);if(t.strides.reduce((u,d)=>u+d,0)>0&&t.strides.length!==l)throw new Error(`strides should be ${l}D`);if(t.pads.reduce((u,d)=>u+d,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,d)=>u+d,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")},_a=(e,t,s,i)=>{let o=e.kernelCustomData.wT??e.compute(St(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(Fu(l,s,i),{inputs:l})},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=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 d=t.pads;d.length===0&&(d=[0,0]),d=[0,d[0],0,d[1]],u=[1].concat(u),l=[1].concat(l),o=[1].concat(o);let h=t.outputPadding;h=[0].concat(h);let p=va({...t,pads:d,strides:u,dilations:l,kernelShape:o,outputPadding:h},i);_a(e,i,p,g=>s?[g[0],g[2],g[3]]:[g[0],g[1],g[3]])},Ku=(e,t)=>{if(Hu(e.inputs,t),e.inputs[0].dims.length===3)ju(e,t);else{let s=va(t,e.inputs);_a(e,e.inputs,s)}}}),Qu,Xu,Yu,Rm=_(()=>{Pe(),Me(),A(),be(),Qu=(e,t,s,i)=>{let o=H.size(t),l=t.length,u=F("input",e,l),d=le("output",e,l),h=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),p=H.normalizeAxis(h,l),g=m=>{let w=` i32(${u.indicesGet("inputIndices","uniforms.axis")}) `,b=j("uniforms.input_shape","uniforms.axis",l),S=i.reverse?w+(i.exclusive?" + 1":""):"0",E=i.reverse?b:w+(i.exclusive?"":" + 1");return`
|
|
1314
1314
|
${m.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(u,d)}
|
|
1315
1315
|
${m.mainStart()}
|
|
1316
1316
|
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
@@ -1323,9 +1323,9 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1323
1323
|
sum = sum + ${u.getByIndices("inputIndices")};
|
|
1324
1324
|
}
|
|
1325
1325
|
${d.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}},Xu=(e,t)=>{let s=e.inputs[0].dims,i=e.inputs[0].dataType,o=e.inputs[1];e.compute(Qu(i,s,o,t),{inputs:[0]})},Yu=e=>{let t=e.exclusive===1,s=e.reverse===1;return $({exclusive:t,reverse:s})}}),Ju,Zu,ed,td,rd,Am=
|
|
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}},Xu=(e,t)=>{let s=e.inputs[0].dims,i=e.inputs[0].dataType,o=e.inputs[1];e.compute(Qu(i,s,o,t),{inputs:[0]})},Yu=e=>{let t=e.exclusive===1,s=e.reverse===1;return $({exclusive:t,reverse:s})}}),Ju,Zu,ed,td,rd,Am=_(()=>{Pe(),Me(),A(),be(),Ju=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.")},Zu=(e,t,s,i)=>{let o=[];o.push(`fn perm(i: ${i.type.indices}) -> ${s.type.indices} {
|
|
1327
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
|
-
`)},ed=(e,t)=>{let s,i,o,l,u,d,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],d=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],d=g?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let m=e.reshape(u),w=m.dims.length,
|
|
1328
|
+
`)},ed=(e,t)=>{let s,i,o,l,u,d,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],d=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],d=g?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let m=e.reshape(u),w=m.dims.length,b=e.dataType,S=F("a",b,w),E=le("output",b,w),I=k=>`
|
|
1329
1329
|
${k.registerUniform("output_size","u32").declareVariables(S,E)}
|
|
1330
1330
|
|
|
1331
1331
|
${Zu(d,w,S,E)}
|
|
@@ -1337,7 +1337,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1337
1337
|
let aIndices = perm(indices);
|
|
1338
1338
|
|
|
1339
1339
|
${E.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=H.size(x),M=m.dims,D=H.sortBasedOnPerm(M,d);return{outputs:[{dims:x,dataType:k[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:[{type:12,data:O},...L(M,D)]}},getShaderSource:I}},td=(e,t)=>{Ju(e.inputs),e.compute(ed(e.inputs[0],t))},rd=e=>$({blocksize:e.blocksize,mode:e.mode,format:e.format})}),
|
|
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=H.size(x),M=m.dims,D=H.sortBasedOnPerm(M,d);return{outputs:[{dims:x,dataType:k[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:[{type:12,data:O},...L(M,D)]}},getShaderSource:I}},td=(e,t)=>{Ju(e.inputs),e.compute(ed(e.inputs[0],t))},rd=e=>$({blocksize:e.blocksize,mode:e.mode,format:e.format})}),_i,Us,ba,nd,sd,id,ad,Sa,od,ld,ud,Mm=_(()=>{Pe(),Me(),A(),be(),_i="[a-zA-Z]|\\.\\.\\.",Us="("+_i+")+",ba="^"+Us+"$",nd="("+Us+",)*"+Us,sd="^"+nd+"$",id=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)}},ad=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(sd)))throw new Error("Invalid LHS term");if(s.split(",").forEach((o,l)=>{let u=e[l].dims.slice();if(!o.match(RegExp(ba)))throw new Error("Invalid LHS term");let d=this.processTerm(o,!0,u,l);this.lhs.push(d)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([o,l])=>l.count===1||o==="...").map(([o])=>o).join("");else if(!i.match(RegExp(Us)))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=[],d=0;if(!e.match(RegExp(ba))&&!t&&e!=="")throw new Error("Invalid LHS term");let h=e.match(RegExp(_i,"g")),p=new id(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(d,d+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 b=0;b<u.length;b++){let S=String.fromCharCode(48+b);p.addSymbol(S,m+b),this.addSymbol(S,s[d++],i)}}else p.addSymbol(g,m+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(g,s[d++],i)}),p}},Sa=e=>e+"_max",od=(e,t,s,i)=>{let o=e.map(p=>p.length).map((p,g)=>F(`input${g}`,t,p)),l=H.size(i),u=le("output",t,i.length),d=[...s.symbolToInfo.keys()].filter(p=>!s.rhs.symbolToIndices.has(p)),h=p=>{let g=[],m="var prod = 1.0;",w="var sum = 0.0;",b="sum += prod;",S=[],E=[],I=[],k=[],x=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((M,D)=>{if(s.rhs.symbolToIndices.has(D)){let W=s.rhs.symbolToIndices.get(D)?.[0];W!==void 0&&s.lhs.forEach((q,X)=>{if(M.inputIndices.includes(X)){let ae=q.symbolToIndices.get(D);if(ae===void 0)throw new Error("Invalid symbol error");ae.forEach(ye=>{g.push(`${o[X].indicesSet(`input${X}Indices`,ye,u.indicesGet("outputIndices",W))}`)})}})}else s.lhs.forEach((W,q)=>{if(M.inputIndices.includes(q)){let X=W.symbolToIndices.get(D);if(X===void 0)throw new Error("Invalid symbol error");X.forEach(ae=>{S.push(`${o[q].indicesSet(`input${q}Indices`,ae,`${D}`)}`)}),k.push(`prod *= ${o[q].getByIndices(`input${q}Indices`)};`)}}),E.push(`for(var ${D}: u32 = 0; ${D} < uniforms.${Sa(D)}; ${D}++) {`),I.push("}")});let O=x?[...g,`let sum = ${o.map((M,D)=>M.getByIndices(`input${D}Indices`)).join(" * ")};`]:[...g,w,...E,...S,m,...k,b,...I];return`
|
|
1341
1341
|
${p.registerUniforms(d.map(M=>({name:`${Sa(M)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,u)}
|
|
1342
1342
|
|
|
1343
1343
|
${p.mainStart()}
|
|
@@ -1348,9 +1348,9 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1348
1348
|
${O.join(`
|
|
1349
1349
|
`)};
|
|
1350
1350
|
${u.setByOffset("global_idx","sum")};
|
|
1351
|
-
}`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=d.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}},ld=(e,t)=>{let s=new ad(e.inputs,t.equation),i=s.outputDims,o=e.inputs.map((l,u)=>l.dims);e.compute(od(o,e.inputs[0].dataType,s,i))},ud=e=>{let t=e.equation.replace(/\s+/g,"");return $({equation:t})}}),dd,Ta,cd,hd,pd,Im=
|
|
1352
|
-
let outputIndices${k} = ${
|
|
1353
|
-
let offset${k} = ${w.broadcastedIndicesToOffset(`outputIndices${k}`,
|
|
1351
|
+
}`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=d.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}},ld=(e,t)=>{let s=new ad(e.inputs,t.equation),i=s.outputDims,o=e.inputs.map((l,u)=>l.dims);e.compute(od(o,e.inputs[0].dataType,s,i))},ud=e=>{let t=e.equation.replace(/\s+/g,"");return $({equation:t})}}),dd,Ta,cd,hd,pd,Im=_(()=>{Pe(),Me(),be(),dd=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")},Ta=(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},cd=(e,t)=>e.length>t.length?Ta(e,t):Ta(t,e),hd=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),i=cd(t,s),o=e[0].dataType,l=o===9||H.size(t)===1,u=o===9||t.length>0&&t[t.length-1]%4===0?4:1,d=l||i.length>0&&i[i.length-1]%4===0?4:1,h=Math.ceil(H.size(i)/d),p=m=>{let w=F("input",o,t.length,u),b=le("output",o,i.length,d),S;if(o===9){let E=(I,k,x="")=>`
|
|
1352
|
+
let outputIndices${k} = ${b.offsetToIndices(`outputOffset + ${k}u`)};
|
|
1353
|
+
let offset${k} = ${w.broadcastedIndicesToOffset(`outputIndices${k}`,b)};
|
|
1354
1354
|
let index${k} = offset${k} / 4u;
|
|
1355
1355
|
let component${k} = offset${k} % 4u;
|
|
1356
1356
|
${I}[${k}] = ${x}(${w.getByOffset(`index${k}`)}[component${k}]);
|
|
@@ -1361,19 +1361,19 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1361
1361
|
${E("data",1,"u32")}
|
|
1362
1362
|
${E("data",2,"u32")}
|
|
1363
1363
|
${E("data",3,"u32")}
|
|
1364
|
-
${
|
|
1364
|
+
${b.setByOffset("global_idx","data")}
|
|
1365
1365
|
}`}else S=`
|
|
1366
|
-
let outputIndices = ${
|
|
1367
|
-
let inputOffset = ${w.broadcastedIndicesToOffset("outputIndices",
|
|
1368
|
-
let data = ${
|
|
1369
|
-
${
|
|
1366
|
+
let outputIndices = ${b.offsetToIndices(`global_idx * ${d}`)};
|
|
1367
|
+
let inputOffset = ${w.broadcastedIndicesToOffset("outputIndices",b)};
|
|
1368
|
+
let data = ${b.type.value}(${w.getByOffset(`inputOffset / ${u}`)});
|
|
1369
|
+
${b.setByOffset("global_idx","data")}
|
|
1370
1370
|
}`;return`
|
|
1371
|
-
${m.registerUniform("vec_size","u32").declareVariables(w,
|
|
1371
|
+
${m.registerUniform("vec_size","u32").declareVariables(w,b)}
|
|
1372
1372
|
${m.mainStart()}
|
|
1373
1373
|
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
1374
|
-
${S}`},g=[{type:12,data:h},...L(t,i)];return{name:"Expand",shaderCache:{hint:`${i.length};${u}${d}`,inputDependencies:["rank"]},getShaderSource:p,getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:g})}},pd=e=>{dd(e.inputs),e.compute(hd(e.inputs),{inputs:[0]})}}),fd,md,Pm=
|
|
1375
|
-
let bias${
|
|
1376
|
-
let bias${
|
|
1374
|
+
${S}`},g=[{type:12,data:h},...L(t,i)];return{name:"Expand",shaderCache:{hint:`${i.length};${u}${d}`,inputDependencies:["rank"]},getShaderSource:p,getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:g})}},pd=e=>{dd(e.inputs),e.compute(hd(e.inputs),{inputs:[0]})}}),fd,md,Pm=_(()=>{Pe(),Me(),be(),ia(),fd=e=>{let t=e[0].dataType,s=H.size(e[0].dims),i=H.size(e[1].dims),o=i%4===0,l=u=>{let d=F("x",t,[1],4),h=F("bias",t,[1],4),p=le("y",t,[1],4),g=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],m=b=>`
|
|
1375
|
+
let bias${b}_offset: u32 = (global_idx * 4 + ${b}) % uniforms.bias_size;
|
|
1376
|
+
let bias${b} = ${h.getByOffset(`bias${b}_offset / 4`)}[bias${b}_offset % 4];`,w=o?`
|
|
1377
1377
|
let bias = ${h.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${m(0)}${m(1)}${m(2)}${m(3)}
|
|
1378
1378
|
let bias = ${d.type.value}(bias0, bias1, bias2, bias3);`;return`${u.registerUniforms(g).declareVariables(d,h,p)}
|
|
1379
1379
|
|
|
@@ -1386,19 +1386,19 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1386
1386
|
${w}
|
|
1387
1387
|
let x_in = x + bias;
|
|
1388
1388
|
${p.setByOffset("global_idx",sa("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/z/4)}})}},md=e=>{e.inputs.length<2||H.size(e.inputs[1].dims)===0?Ql(e):e.compute(fd(e.inputs))}}),gd,yd,wd,vd,Om=
|
|
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/z/4)}})}},md=e=>{e.inputs.length<2||H.size(e.inputs[1].dims)===0?Ql(e):e.compute(fd(e.inputs))}}),gd,yd,wd,vd,Om=_(()=>{Pe(),Me(),A(),be(),gd=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},yd=(e,t)=>{let s=e[0].dims,i=e[1].dims,o=s.length,l=H.normalizeAxis(t.axis,o),u=s.slice(0);u.splice(l,1,...i);let d=s[l],h=e[0].dataType===9?4:1,p=Math.ceil(H.size(u)/h),g=[{type:12,data:p},{type:6,data:d},{type:12,data:l},...L(e[0].dims,e[1].dims,u)],m=w=>{let b=F("data",e[0].dataType,e[0].dims.length,h),S=F("inputIndices",e[1].dataType,e[1].dims.length),E=le("output",e[0].dataType,u.length,h),I=x=>{let O=i.length,M=`var indicesIndices${x} = ${S.type.indices}(0);`;for(let D=0;D<O;D++)M+=`${O>1?`indicesIndices${x}[${D}]`:`indicesIndices${x}`} = ${u.length>1?`outputIndices${x}[uniforms.axis + ${D}]`:`outputIndices${x}`};`;M+=`
|
|
1390
1390
|
var idx${x} = ${S.getByIndices(`indicesIndices${x}`)};
|
|
1391
1391
|
if (idx${x} < 0) {
|
|
1392
1392
|
idx${x} = idx${x} + uniforms.axisDimLimit;
|
|
1393
1393
|
}
|
|
1394
|
-
var dataIndices${x} : ${
|
|
1394
|
+
var dataIndices${x} : ${b.type.indices};
|
|
1395
1395
|
`;for(let D=0,W=0;D<o;D++)D===l?(M+=`${o>1?`dataIndices${x}[${D}]`:`dataIndices${x}`} = u32(idx${x});`,W+=O):(M+=`${o>1?`dataIndices${x}[${D}]`:`dataIndices${x}`} = ${u.length>1?`outputIndices${x}[${W}]`:`outputIndices${x}`};`,W++);return M},k;if(e[0].dataType===9){let x=(O,M,D="")=>`
|
|
1396
1396
|
let outputIndices${M} = ${E.offsetToIndices(`outputOffset + ${M}u`)};
|
|
1397
1397
|
${I(M)};
|
|
1398
|
-
let offset${M} = ${
|
|
1398
|
+
let offset${M} = ${b.indicesToOffset(`dataIndices${M}`)};
|
|
1399
1399
|
let index${M} = offset${M} / 4u;
|
|
1400
1400
|
let component${M} = offset${M} % 4u;
|
|
1401
|
-
${O}[${M}] = ${D}(${
|
|
1401
|
+
${O}[${M}] = ${D}(${b.getByOffset(`index${M}`)}[component${M}]);
|
|
1402
1402
|
`;k=`
|
|
1403
1403
|
let outputOffset = global_idx * ${h};
|
|
1404
1404
|
var value = vec4<u32>(0);
|
|
@@ -1410,14 +1410,14 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1410
1410
|
`}else k=`
|
|
1411
1411
|
let outputIndices = ${E.offsetToIndices("global_idx")};
|
|
1412
1412
|
${I("")};
|
|
1413
|
-
let value = ${
|
|
1413
|
+
let value = ${b.getByIndices("dataIndices")};
|
|
1414
1414
|
${E.setByOffset("global_idx","value")};
|
|
1415
1415
|
`;return`
|
|
1416
|
-
${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(
|
|
1416
|
+
${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(b,S,E)}
|
|
1417
1417
|
${w.mainStart()}
|
|
1418
1418
|
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1419
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}},wd=e=>$({axis:e.axis}),vd=(e,t)=>{let s=e.inputs;gd(s),e.compute(yd(e.inputs,t))}}),bd,
|
|
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}},wd=e=>$({axis:e.axis}),vd=(e,t)=>{let s=e.inputs;gd(s),e.compute(yd(e.inputs,t))}}),_d,bd,Sd,zm=_(()=>{Pe(),Me(),be(),_d=(e,t,s,i,o,l,u,d,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:d},{type:12,data:h}],g=[l];p.push(...L(t.dims,g));let m=w=>{let b=F("indices_data",t.dataType,t.dims.length),S=le("input_slice_offsets_data",12,1,1),E=[b,S],I=[{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
1421
|
${w.registerUniforms(I).declareVariables(...E)}
|
|
1422
1422
|
${w.mainStart()}
|
|
1423
1423
|
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1436,15 +1436,15 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1436
1436
|
}
|
|
1437
1437
|
|
|
1438
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]},
|
|
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]},bd=(e,t)=>{let s=e.inputs,i=s[0].dims,o=s[0].dataType,l=s[1].dims,u=l[l.length-1],d=H.sizeToDimension(l,l.length-1),h=H.sizeFromDimension(i,t.batchDims+u),p=H.sizeToDimension(i,t.batchDims),g=H.sizeFromDimension(i,t.batchDims),m=d/p,w=new Array(u),b=h;for(let M=0;M<u;++M)w[u-1-M]=b,b*=i[t.batchDims+u-1-M];let S=_d(e,s[1],w,t.batchDims,i,d,m,g,u),E=t.batchDims+u;if(E>i.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let I=l.slice(0,-1).concat(i.slice(E)),k=H.size(I),x=[{type:12,data:k},{type:12,data:h},...L(s[0].dims,S.dims,I)],O=M=>{let D=F("data",s[0].dataType,s[0].dims.length),W=F("slice_offsets",12,S.dims.length),q=le("output",s[0].dataType,I.length);return`
|
|
1440
1440
|
${M.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(D,W,q)}
|
|
1441
1441
|
${M.mainStart()}
|
|
1442
1442
|
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1443
1443
|
let slice_offset = slice_offsets[global_idx / uniforms.slice_size];
|
|
1444
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:I,dataType:o}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:x}),getShaderSource:O},{inputs:[s[0],S]})},Sd=e=>({batchDims:e.batch_dims,cacheKey:""})}),Td,$d,xd,Ed,Dm=
|
|
1446
|
-
${
|
|
1447
|
-
${
|
|
1445
|
+
}`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:I,dataType:o}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:x}),getShaderSource:O},{inputs:[s[0],S]})},Sd=e=>({batchDims:e.batch_dims,cacheKey:""})}),Td,$d,xd,Ed,Dm=_(()=>{Pe(),Me(),A(),be(),Td=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=H.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((d,h)=>h===s?Math.ceil(d/i)===l.dims[h]:d===l.dims[h]).reduce((d,h)=>d&&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((d,h)=>d===l.dims[h]).reduce((d,h)=>d&&h,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},$d=(e,t)=>{let s=e[0].dims,i=e[1].dims,o=s.length,l=H.normalizeAxis(t.gatherAxis,o),u=H.normalizeAxis(t.quantizeAxis,o),d=s.slice(0);d.splice(l,1,...i);let h=H.size(d),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((b,S)=>b.dims),d)],w=b=>{let S=F("data",e[0].dataType,e[0].dims.length),E=F("inputIndices",e[1].dataType,e[1].dims.length),I=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=le("output",p,d.length),O=[S,E,I];k&&O.push(k);let M=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
1446
|
+
${b.registerUniforms(M).declareVariables(...O,x)}
|
|
1447
|
+
${b.mainStart()}
|
|
1448
1448
|
let output_indices = ${x.offsetToIndices("global_idx")};
|
|
1449
1449
|
var indices_indices = ${E.type.indices}(0);
|
|
1450
1450
|
${i.length>1?`
|
|
@@ -1487,13 +1487,13 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1487
1487
|
let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};
|
|
1488
1488
|
let dequantized_data = ${N(p)}(quantized_data - zero_point) * scale;
|
|
1489
1489
|
${x.setByOffset("global_idx","dequantized_data")};
|
|
1490
|
-
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((
|
|
1491
|
-
indices input tensors be of same rank.`)},kd=(e,t)=>{let s=e[0].dims,i=e[0].dataType,o=s.length,l=e[1].dims,u=e[1].dataType,d=H.normalizeAxis(t.axis,o),h=s[d],p=l.slice(0),g=H.size(p),m=
|
|
1492
|
-
${E.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(m,w,
|
|
1490
|
+
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((b,S)=>S!==1).map(b=>b.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(b,S)=>"rank")},getRunData:()=>({outputs:[{dims:d,dataType:p}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:m}),getShaderSource:w}},xd=(e,t)=>{let s=e.inputs;Td(s,t),e.compute($d(e.inputs,t))},Ed=e=>$({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Cd,kd,Rd,Ad,Lm=_(()=>{Pe(),Me(),A(),be(),Cd=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.`)},kd=(e,t)=>{let s=e[0].dims,i=e[0].dataType,o=s.length,l=e[1].dims,u=e[1].dataType,d=H.normalizeAxis(t.axis,o),h=s[d],p=l.slice(0),g=H.size(p),m=F("input",i,o),w=F("indicesInput",u,l.length),b=le("output",i,p.length),S=[{type:12,data:g},{type:6,data:h},{type:12,data:d}];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:E=>`
|
|
1492
|
+
${E.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(m,w,b)}
|
|
1493
1493
|
${E.mainStart()}
|
|
1494
1494
|
${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1495
1495
|
|
|
1496
|
-
let outputIndices = ${
|
|
1496
|
+
let outputIndices = ${b.offsetToIndices("global_idx")};
|
|
1497
1497
|
|
|
1498
1498
|
var idx = ${w.getByOffset("global_idx")};
|
|
1499
1499
|
if (idx < 0) {
|
|
@@ -1503,9 +1503,9 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1503
1503
|
${m.indicesSet("inputIndices","uniforms.axis","u32(idx)")};
|
|
1504
1504
|
let value = ${m.getByIndices("inputIndices")};
|
|
1505
1505
|
|
|
1506
|
-
${
|
|
1507
|
-
}`}},Rd=e=>$({axis:e.axis}),Ad=(e,t)=>{let s=e.inputs;Cd(s),e.compute(kd(e.inputs,t))}}),Md,Id,Pd,Od,Bm=
|
|
1508
|
-
${k.registerUniforms(
|
|
1506
|
+
${b.setByOffset("global_idx","value")};
|
|
1507
|
+
}`}},Rd=e=>$({axis:e.axis}),Ad=(e,t)=>{let s=e.inputs;Cd(s),e.compute(kd(e.inputs,t))}}),Md,Id,Pd,Od,Bm=_(()=>{Pe(),Me(),be(),Md=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")},Id=(e,t)=>{let s=e[0].dims.slice(),i=e[1].dims.slice(),[o,l,u]=Vn.getShapeOfGemmResult(s,t.transA,i,t.transB,e.length===3?e[2].dims:void 0),d=[o,l];if(!d)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=H.size(d),b=[{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&&(b.push(...L(e[2].dims)),S.push("rank")),b.push(...L(d));let E=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;",M=F("a",e[0].dataType,e[0].dims),D=F("b",e[1].dataType,e[1].dims),W=M.type.value,q=null,X=[M,D];e.length===3&&(q=F("c",e[2].dataType,e[2].dims.length),X.push(q));let ae=le("output",e[0].dataType,d.length);X.push(ae);let ye=[{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(ye).declareVariables(...X)}
|
|
1509
1509
|
|
|
1510
1510
|
${k.mainStart()}
|
|
1511
1511
|
${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1519,9 +1519,9 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1519
1519
|
}
|
|
1520
1520
|
|
|
1521
1521
|
${O}
|
|
1522
|
-
${q!=null?`let cOffset = ${q.broadcastedIndicesToOffset("vec2(m, n)",
|
|
1522
|
+
${q!=null?`let cOffset = ${q.broadcastedIndicesToOffset("vec2(m, n)",ae)}; value += ${W}(uniforms.beta) * ${q.getByOffset("cOffset")};`:""}
|
|
1523
1523
|
output[global_idx] = value;
|
|
1524
|
-
}`},I=k=>{let x=
|
|
1524
|
+
}`},I=k=>{let x=F("a",e[0].dataType,e[0].dims),O=F("b",e[1].dataType,e[1].dims),M=null,D=[x,O];e.length===3&&(M=F("c",e[2].dataType,e[2].dims.length),D.push(M));let W=le("output",e[0].dataType,d.length);D.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"}],X="",ae="";t.transA&&t.transB?(ae=`
|
|
1525
1525
|
var col = tile_row_start + local_id.x;
|
|
1526
1526
|
var row = k_start + local_id.y;
|
|
1527
1527
|
if (col < uniforms.M && row < uniforms.K) {
|
|
@@ -1537,7 +1537,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1537
1537
|
} else {
|
|
1538
1538
|
tile_b[local_id.y][local_id.x] = ${O.type.value}(0);
|
|
1539
1539
|
}
|
|
1540
|
-
`,
|
|
1540
|
+
`,X="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(ae=`
|
|
1541
1541
|
var col = tile_row_start + local_id.x;
|
|
1542
1542
|
var row = k_start + local_id.y;
|
|
1543
1543
|
if (col < uniforms.M && row < uniforms.K) {
|
|
@@ -1553,7 +1553,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1553
1553
|
} else {
|
|
1554
1554
|
tile_b[local_id.y][local_id.x] = ${O.type.value}(0);
|
|
1555
1555
|
}
|
|
1556
|
-
`,
|
|
1556
|
+
`,X="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(ae=`
|
|
1557
1557
|
var col = k_start + local_id.x;
|
|
1558
1558
|
var row = tile_row_start + local_id.y;
|
|
1559
1559
|
if (col < uniforms.K && row < uniforms.M) {
|
|
@@ -1569,7 +1569,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1569
1569
|
} else {
|
|
1570
1570
|
tile_b[local_id.y][local_id.x] = ${O.type.value}(0);
|
|
1571
1571
|
}
|
|
1572
|
-
`,
|
|
1572
|
+
`,X="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(ae=`
|
|
1573
1573
|
var col = k_start + local_id.x;
|
|
1574
1574
|
var row = tile_row_start + local_id.y;
|
|
1575
1575
|
if (col < uniforms.K && row < uniforms.M) {
|
|
@@ -1585,7 +1585,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1585
1585
|
} else {
|
|
1586
1586
|
tile_b[local_id.y][local_id.x] = ${O.type.value}(0);
|
|
1587
1587
|
}
|
|
1588
|
-
`,
|
|
1588
|
+
`,X="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let ye=t.alpha===1?"":"value *= uniforms.alpha;";return`
|
|
1589
1589
|
${k.registerUniforms(q).declareVariables(...D)}
|
|
1590
1590
|
var<workgroup> tile_a: array<array<${x.type.storage}, ${h}>, ${h}>;
|
|
1591
1591
|
var<workgroup> tile_b: array<array<${O.type.storage}, ${h}>, ${h}>;
|
|
@@ -1596,24 +1596,24 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1596
1596
|
var k_start = 0u;
|
|
1597
1597
|
var value = ${W.type.value}(0);
|
|
1598
1598
|
for (var t: u32 = 0u; t < num_tiles; t++) {
|
|
1599
|
-
${
|
|
1599
|
+
${ae}
|
|
1600
1600
|
k_start = k_start + ${h};
|
|
1601
1601
|
workgroupBarrier();
|
|
1602
1602
|
|
|
1603
1603
|
for (var k: u32 = 0u; k < ${h}; k++) {
|
|
1604
|
-
${
|
|
1604
|
+
${X}
|
|
1605
1605
|
}
|
|
1606
1606
|
workgroupBarrier();
|
|
1607
1607
|
}
|
|
1608
1608
|
|
|
1609
|
-
${
|
|
1609
|
+
${ye}
|
|
1610
1610
|
let m = tile_row_start + local_id.y;
|
|
1611
1611
|
let n = tile_col_start + local_id.x;
|
|
1612
1612
|
${M!=null?`let cOffset = ${M.broadcastedIndicesToOffset("vec2(m, n)",W)}; value += ${W.type.value}(uniforms.beta) * ${M.getByOffset("cOffset")};`:""}
|
|
1613
1613
|
if (m < uniforms.M && n < uniforms.N) {
|
|
1614
1614
|
output[m * uniforms.N + n] = value;
|
|
1615
1615
|
}
|
|
1616
|
-
}`};return m?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:p*g},programUniforms:
|
|
1616
|
+
}`};return m?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:p*g},programUniforms:b}),getShaderSource:I}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:b}),getShaderSource:E}},Pd=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}`}},Od=(e,t)=>{Md(e.inputs),e.compute(Id(e.inputs,t))}}),Er,Lr,An,Mn,zd,Dd,Ld,Bd,Nd,Ud,Fd,Vd,Gd,qd,Nm=_(()=>{Pe(),Me(),A(),be(),[Er,Lr,An,Mn]=[0,1,2,3],zd=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")},Dd=`
|
|
1617
1617
|
fn gs_get_cubic_coeffs(x: f32) -> vec4<f32> {
|
|
1618
1618
|
let cubic_alpha = -0.75f;
|
|
1619
1619
|
let x_abs = abs(x);
|
|
@@ -1677,34 +1677,34 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1677
1677
|
var pixel = ${t}(0);
|
|
1678
1678
|
var indices = vec4<u32>(0);
|
|
1679
1679
|
indices[${Er}] = batch;
|
|
1680
|
-
indices[${
|
|
1680
|
+
indices[${Lr}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return`
|
|
1681
1681
|
if (r >= 0 && r < H && c >=0 && c < W) {
|
|
1682
|
-
indices[${
|
|
1683
|
-
indices[${
|
|
1682
|
+
indices[${An}] = u32(r);
|
|
1683
|
+
indices[${Mn}] = u32(c);
|
|
1684
1684
|
} else {
|
|
1685
1685
|
return ${t}(0);
|
|
1686
1686
|
}
|
|
1687
1687
|
`;case"border":return`
|
|
1688
|
-
indices[${
|
|
1689
|
-
indices[${
|
|
1688
|
+
indices[${An}] = u32(clamp(r, 0, H - 1));
|
|
1689
|
+
indices[${Mn}] = u32(clamp(c, 0, W - 1));
|
|
1690
1690
|
`;case"reflection":return`
|
|
1691
|
-
indices[${
|
|
1692
|
-
indices[${
|
|
1691
|
+
indices[${An}] = gs_reflect(r, border[1], border[3]);
|
|
1692
|
+
indices[${Mn}] = gs_reflect(c, border[0], border[2]);
|
|
1693
1693
|
`;default:throw new Error(`padding mode ${s.paddingMode} is not supported`)}})()+`
|
|
1694
1694
|
return ${e.getByIndices("indices")};
|
|
1695
1695
|
}
|
|
1696
1696
|
`,Fd=(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[${Er}], indices[${
|
|
1697
|
+
let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Er}], indices[${Lr}], border);
|
|
1698
1698
|
`;case"bilinear":return`
|
|
1699
1699
|
let x1 = i32(floor(x));
|
|
1700
1700
|
let y1 = i32(floor(y));
|
|
1701
1701
|
let x2 = x1 + 1;
|
|
1702
1702
|
let y2 = y1 + 1;
|
|
1703
1703
|
|
|
1704
|
-
let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Er}], indices[${
|
|
1705
|
-
let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Er}], indices[${
|
|
1706
|
-
let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Er}], indices[${
|
|
1707
|
-
let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Er}], indices[${
|
|
1704
|
+
let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Er}], indices[${Lr}], border);
|
|
1705
|
+
let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Er}], indices[${Lr}], border);
|
|
1706
|
+
let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Er}], indices[${Lr}], border);
|
|
1707
|
+
let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Er}], indices[${Lr}], border);
|
|
1708
1708
|
|
|
1709
1709
|
let dx2 = ${t}(f32(x2) - x);
|
|
1710
1710
|
let dx1 = ${t}(x - f32(x1));
|
|
@@ -1717,14 +1717,14 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1717
1717
|
var p: mat4x4<${t}>;
|
|
1718
1718
|
for (var h = 0; h < 4; h++) {
|
|
1719
1719
|
for (var w = 0; w < 4; w++) {
|
|
1720
|
-
p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Er}], indices[${
|
|
1720
|
+
p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Er}], indices[${Lr}], border);
|
|
1721
1721
|
}
|
|
1722
1722
|
}
|
|
1723
1723
|
|
|
1724
1724
|
let dx = x - f32(x0 + 1);
|
|
1725
1725
|
let dy = y - f32(y0 + 1);
|
|
1726
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")}`,Vd=(e,t)=>{let s=
|
|
1727
|
+
`;default:throw new Error(`mode ${s.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Vd=(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]],[Er,Lr,An,Mn]=[0,3,1,2]);let u=le("output",e[0].dataType,l.length),d=s.type.value,h=H.size(l),p=[{type:12,data:h},...L(e[0].dims,i,l)],g=m=>`
|
|
1728
1728
|
${m.registerUniform("output_size","u32").declareVariables(s,o,u)}
|
|
1729
1729
|
${Dd}
|
|
1730
1730
|
${Ld(d)}
|
|
@@ -1734,8 +1734,8 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1734
1734
|
|
|
1735
1735
|
${m.mainStart()}
|
|
1736
1736
|
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1737
|
-
let H_in = i32(uniforms.x_shape[${
|
|
1738
|
-
let W_in = i32(uniforms.x_shape[${
|
|
1737
|
+
let H_in = i32(uniforms.x_shape[${An}]);
|
|
1738
|
+
let W_in = i32(uniforms.x_shape[${Mn}]);
|
|
1739
1739
|
|
|
1740
1740
|
${t.alignCorners===0?`
|
|
1741
1741
|
let x_min = -0.5;
|
|
@@ -1751,20 +1751,20 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1751
1751
|
let border = vec4<f32>(x_min, y_min, x_max, y_max);
|
|
1752
1752
|
|
|
1753
1753
|
let indices = ${u.offsetToIndices("global_idx")};
|
|
1754
|
-
var grid_indices = vec3<u32>(indices[${Er}], indices[${
|
|
1754
|
+
var grid_indices = vec3<u32>(indices[${Er}], indices[${An}], indices[${Mn}]);
|
|
1755
1755
|
let nxy = ${o.getByIndices("grid_indices")};
|
|
1756
1756
|
var x = gs_denormalize(f32(nxy[0]), W_in);
|
|
1757
1757
|
var y = gs_denormalize(f32(nxy[1]), H_in);
|
|
1758
1758
|
|
|
1759
1759
|
${Fd(u,d,t)}
|
|
1760
|
-
}`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:m=>{let w=H.size(l);return{outputs:[{dims:l,dataType:m[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:p}},getShaderSource:g}},Gd=(e,t)=>{zd(e.inputs),e.compute(Vd(e.inputs,t))},qd=e=>$({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Wt,Wd,Hd,$a,jd,Fs,Kd,Qd=
|
|
1761
|
-
${m.registerUniforms(E).declareVariables(
|
|
1760
|
+
}`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:m=>{let w=H.size(l);return{outputs:[{dims:l,dataType:m[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:p}},getShaderSource:g}},Gd=(e,t)=>{zd(e.inputs),e.compute(Vd(e.inputs,t))},qd=e=>$({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Wt,Wd,Hd,$a,jd,Fs,Kd,Qd=_(()=>{Pe(),Me(),A(),Hn(),ta(),be(),je(),Wt=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Wd=(e,t)=>{let s=e[0],i=Wt(e,1),o=Wt(e,2),l=Wt(e,3),u=Wt(e,4),d=Wt(e,5),h=Wt(e,6),p=Wt(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],b=m,S=0,E=0,I=Math.floor(w/t.numHeads);if(h&&p&&H.size(h.dims)&&H.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]!==I)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]!==I)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],E=h.dims[2]}else if(h&&H.size(h.dims)||p&&H.size(p.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let k;if(i&&H.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,b=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==I)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,b=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==I)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');k=0,b=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&&H.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+b,O=0;if(u&&H.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 M=!1,D=w;if(o&&H.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(b!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');D=o.dims[2]}else{if(b!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');D=o.dims[1]*o.dims[3],M=!0}}let W=!1;if(u&&H.size(u.dims)>0)throw new Error("Key padding mask is not supported");if(d&&H.size(d.dims)>0){if(d.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(d.dims[0]!==g||d.dims[1]!==t.numHeads||d.dims[2]!==m||d.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:b,totalSequenceLength:x,maxSequenceLength:E,inputHiddenSize:0,hiddenSize:w,vHiddenSize:D,headSize:I,vHeadSize:Math.floor(D/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:O,scale:t.scale,broadcastResPosBias:W,passPastInKv:M,qkvFormat:k}},Hd=e=>$({...e}),$a=$({perm:[0,2,1,3]}),jd=(e,t,s,i,o,l,u)=>{let d=[i,o,l],h=H.size(d),p=[{type:12,data:h},{type:12,data:u},{type:12,data:l}],g=m=>{let w=le("qkv_with_bias",t.dataType,d),b=F("qkv",t.dataType,d),S=F("bias",s.dataType,d),E=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`
|
|
1761
|
+
${m.registerUniforms(E).declareVariables(b,S,w)}
|
|
1762
1762
|
${m.mainStart()}
|
|
1763
1763
|
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1764
1764
|
let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
|
|
1765
1765
|
|
|
1766
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:d,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p}),getShaderSource:g},{inputs:[t,s],outputs:[-1]})[0]},Fs=(e,t,s,i,o,l,u,d)=>{let h=l;if(u&&H.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=jd(e,l,u,t,i,s*o,d),h=h.reshape([t,i,s,o]),s===1||i===1?h:e.compute(
|
|
1767
|
+
}`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:d,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p}),getShaderSource:g},{inputs:[t,s],outputs:[-1]})[0]},Fs=(e,t,s,i,o,l,u,d)=>{let h=l;if(u&&H.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=jd(e,l,u,t,i,s*o,d),h=h.reshape([t,i,s,o]),s===1||i===1?h:e.compute(St(h,$a.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(St(h,$a.perm),{inputs:[h],outputs:[-1]})[0]},Kd=(e,t)=>{let s=Wd(e.inputs,t),i=e.inputs[0],o=Wt(e.inputs,1),l=Wt(e.inputs,2),u=Wt(e.inputs,3),d=Wt(e.inputs,4),h=Wt(e.inputs,5),p=Wt(e.inputs,6),g=Wt(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=Fs(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,i,u,0);if(m)return Ds(e,w,o,l,d,void 0,p,g,h,s);if(!o||!l)throw new Error("key and value must be provided");let b=Fs(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,o,u,s.hiddenSize),S=Fs(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,l,u,2*s.hiddenSize);Ds(e,w,b,S,d,void 0,p,g,h,s)}}),Xd,Yd,Jd,Zd,xa,ec,tc,rc=_(()=>{Pe(),Me(),A(),be(),Xd=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Yd=(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),$({numOutputs:i,axis:t.axis,splitSizes:s})},Jd=e=>`
|
|
1768
1768
|
fn calculateOutputIndex(index: u32) -> u32 {
|
|
1769
1769
|
for (var i: u32 = 0u; i < ${e}u; i += 1u ) {
|
|
1770
1770
|
if (index < ${j("uniforms.size_in_split_axis","i",e)}) {
|
|
@@ -1776,7 +1776,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1776
1776
|
fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) {
|
|
1777
1777
|
${s.join(`
|
|
1778
1778
|
`)}
|
|
1779
|
-
}`},xa=(e,t)=>{let s=e[0].dims,i=H.size(s),o=e[0].dataType,l=H.normalizeAxis(t.axis,s.length),u=new Array(t.numOutputs),d=
|
|
1779
|
+
}`},xa=(e,t)=>{let s=e[0].dims,i=H.size(s),o=e[0].dataType,l=H.normalizeAxis(t.axis,s.length),u=new Array(t.numOutputs),d=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 E=s.slice();E[l]=t.splitSizes[S],g.push(E),u[S]=le(`output${S}`,o,E.length),p.push({dims:g[S],dataType:e[0].dataType})}w.push({type:12,data:h},...L(s,...g));let b=S=>`
|
|
1780
1780
|
${S.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",h.length).declareVariables(d,...u)}
|
|
1781
1781
|
${Jd(h.length)}
|
|
1782
1782
|
${Zd(u)}
|
|
@@ -1792,7 +1792,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1792
1792
|
${d.indicesSet("indices",l,"index")};
|
|
1793
1793
|
}
|
|
1794
1794
|
writeBufferData(output_number, indices, global_idx);
|
|
1795
|
-
}`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:
|
|
1795
|
+
}`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:b,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(i/64)},programUniforms:w})}},ec=(e,t)=>{Xd(e.inputs);let s=e.inputs.length===1?t:Yd(e.inputs,t);e.compute(xa(e.inputs,s),{inputs:[0]})},tc=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 $({axis:t,numOutputs:i,splitSizes:s})}}),nc,bi,sc,ic=_(()=>{Pe(),Me(),A(),be(),nc=(e,t)=>{let[s,i,o,l]=e,{numHeads:u,rotaryEmbeddingDim:d}=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(!H.areEqual(i.dims,[])&&!H.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(!H.areEqual(o.dims,l.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(d>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=H.sizeFromDimension(s.dims,1)/p,w=d===0?o.dims[1]*2:m/u;if(d>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]&&d/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")},bi=(e,t)=>{let{interleaved:s,numHeads:i,rotaryEmbeddingDim:o,scale:l}=t,u=e[0].dims[0],d=H.sizeFromDimension(e[0].dims,1),h=e[0].dims[e[0].dims.length-2],p=d/h,g=e[2].dims[1],m=o===0?g*2:p/i,w=new Array(u,h,p/m,m-g),b=H.computeStrides(w),S=[{type:1,data:l},{type:12,data:w},{type:12,data:b},...e[0].dims.length===3?new Array({type:12,data:[d,p,m,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[d,m,h*m,1]}):[],...L(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],E=I=>{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),M=F("sin_cache",e[3].dataType,e[3].dims.length),D=le("output",e[0].dataType,e[0].dims.length);return I.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:w.length},{name:"global_strides",type:"u32",length:b.length},{name:"input_output_strides",type:"u32",length:b.length}]),`
|
|
1796
1796
|
${I.declareVariables(k,x,O,M,D)}
|
|
1797
1797
|
|
|
1798
1798
|
${I.mainStart(z)}
|
|
@@ -1803,7 +1803,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1803
1803
|
|
|
1804
1804
|
if (bsnh[3] < half_rotary_emb_dim) {
|
|
1805
1805
|
let position_ids_idx =
|
|
1806
|
-
${x.broadcastedIndicesToOffset("bsnh.xy",
|
|
1806
|
+
${x.broadcastedIndicesToOffset("bsnh.xy",le("",x.type.tensor,2))};
|
|
1807
1807
|
let position_id =
|
|
1808
1808
|
u32(${x.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);
|
|
1809
1809
|
let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${s});
|
|
@@ -1818,8 +1818,8 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1818
1818
|
let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
|
|
1819
1819
|
${D.setByOffset("k",k.getByOffset("k"))}
|
|
1820
1820
|
}
|
|
1821
|
-
}`};return{name:"RotaryEmbedding",shaderCache:{hint:$({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:E,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(H.size(w)/z)},programUniforms:S})}},sc=(e,t)=>{nc(e.inputs,t),e.compute(
|
|
1822
|
-
${g.registerUniforms(S).declareVariables(m,w,
|
|
1821
|
+
}`};return{name:"RotaryEmbedding",shaderCache:{hint:$({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:E,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(H.size(w)/z)},programUniforms:S})}},sc=(e,t)=>{nc(e.inputs,t),e.compute(bi(e.inputs,t))}}),ac,oc,Ea,lc,uc,Um=_(()=>{A(),Pe(),ta(),Qd(),rc(),je(),ic(),be(),ac=(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 d=!1,h=s.dims[0],p=s.dims[1],g=s.dims.length===3?d?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],m=p,w=0,b=!i||i.dims.length===0,S=Math.floor(b?g/(t.numHeads+2*t.kvNumHeads):g/t.numHeads);b&&(g=S*t.numHeads);let E=l&&l.dims.length!==0,I=u&&u.dims.length!==0;if(E&&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(E&&I){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(E||I)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,M=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)');M=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)');M=o.dims[1]*o.dims[3],O=!0}}let D=e.length>4?e[5]:void 0;if(D&&D.dims.length!==1&&D.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:M,headSize:S,vHeadSize:Math.floor(M/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}},oc=$({perm:[0,2,1,3]}),Ea=(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(St(i,oc.perm),{inputs:[i],outputs:[-1]})[0]),i},lc=(e,t,s,i)=>{let o=7,l=["type","type"],u=[e*t],d=e*t,h=[{type:12,data:d},{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),b=le("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,b)}
|
|
1823
1823
|
${g.mainStart()}
|
|
1824
1824
|
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1825
1825
|
let total_sequence_length = u32(${w.getByOffset("0")});
|
|
@@ -1836,7 +1836,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1836
1836
|
} else {
|
|
1837
1837
|
pos_id = 1;
|
|
1838
1838
|
}
|
|
1839
|
-
${
|
|
1839
|
+
${b.setByOffset("global_idx","pos_id")}
|
|
1840
1840
|
} else if (is_subsequent_prompt) {
|
|
1841
1841
|
let past_seqlen = total_seqlen - i32(uniforms.sequence_length);
|
|
1842
1842
|
if (past_seqlen + sequence_idx < total_seqlen) {
|
|
@@ -1844,12 +1844,12 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1844
1844
|
} else {
|
|
1845
1845
|
pos_id = 1;
|
|
1846
1846
|
}
|
|
1847
|
-
${
|
|
1847
|
+
${b.setByOffset("global_idx","pos_id")}
|
|
1848
1848
|
} else if (global_idx < uniforms.batch_size) {
|
|
1849
|
-
${
|
|
1849
|
+
${b.setByOffset("global_idx","seqlen")}
|
|
1850
1850
|
};
|
|
1851
1851
|
}
|
|
1852
|
-
`};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}),getShaderSource:p}},uc=(e,t)=>{let s=ac(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,d=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=$({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,g*s.headSize,g*s.headSize]}),[w,
|
|
1852
|
+
`};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}),getShaderSource:p}},uc=(e,t)=>{let s=ac(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,d=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=$({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,g*s.headSize,g*s.headSize]}),[w,b,S]=!o&&!l?e.compute(xa([i],m),{inputs:[i],outputs:[-1,-1,-1]}):[i,o,l],E,I;if(t.doRotary){let M=e.compute(lc(s.batchSize,s.sequenceLength,h,p),{inputs:[h,p],outputs:[-1]})[0],D=e.inputs[7],W=e.inputs[8],q=$({interleaved:t.rotaryInterleaved!==0,numHeads:s.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),X=[w,M,D,W],ae=[-1];E=e.compute(bi(X,q),{inputs:X,outputs:ae})[0],X.splice(0,1,b);let ye=$({interleaved:t.rotaryInterleaved!==0,numHeads:s.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});I=e.compute(bi(X,ye),{inputs:X,outputs:ae})[0]}let k=Fs(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,t.doRotary?E:w,void 0,0),x=Ea(e,t.doRotary?I:b,s),O=Ea(e,S,s);Ds(e,k,x,O,void 0,void 0,u,d,void 0,s,h,p)}}),Ca,dc,cc,hc,Fm=_(()=>{Pe(),Me(),je(),be(),Ca=(e,t,s,i,o,l,u,d)=>{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 b=[o,u,l/h],S=[o,u,2],E=["rank","type","type"],I=[];I.push(...L(b,S));let k=x=>{let O=F("x",t.dataType,3,h),M=F("scale",s.dataType,s.dims),D=F("bias",i.dataType,i.dims),W=le("output",1,3,2),q=[O,M,D,W];return`
|
|
1853
1853
|
var<workgroup> workgroup_shared : array<${g}, ${w}>;
|
|
1854
1854
|
const workgroup_size = ${w}u;
|
|
1855
1855
|
${x.declareVariables(...q)}
|
|
@@ -1883,7 +1883,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1883
1883
|
let channel_shift = f32(bias[channel]) - sum_final * channel_scale;
|
|
1884
1884
|
output[workgroup_index] = vec2f(channel_scale, channel_shift);
|
|
1885
1885
|
}
|
|
1886
|
-
}`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${h};${d};${w}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:S,dataType:1}],dispatchGroup:{x:m},programUniforms:I}),getShaderSource:k},{inputs:[t,s,i],outputs:[-1]})[0]},dc=(e,t,s)=>{let i=t[0].dims,o=i,l=2,u=i[0],d=i[1],h=H.sizeFromDimension(i,l),p=V(h),g=H.size(o)/p,m=Ca(e,t[0],t[1],t[2],u,h,d,s.epsilon),w=[u,d,h/p],
|
|
1886
|
+
}`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${h};${d};${w}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:S,dataType:1}],dispatchGroup:{x:m},programUniforms:I}),getShaderSource:k},{inputs:[t,s,i],outputs:[-1]})[0]},dc=(e,t,s)=>{let i=t[0].dims,o=i,l=2,u=i[0],d=i[1],h=H.sizeFromDimension(i,l),p=V(h),g=H.size(o)/p,m=Ca(e,t[0],t[1],t[2],u,h,d,s.epsilon),w=[u,d,h/p],b=[u,d],S=["type","none"],E=I=>{let k=F("x",t[0].dataType,w.length,p),x=F("scale_shift",1,b.length,2),O=le("output",t[0].dataType,w.length,p),M=[k,x,O];return`
|
|
1887
1887
|
${I.registerUniform("output_size","u32").declareVariables(...M)}
|
|
1888
1888
|
${I.mainStart()}
|
|
1889
1889
|
${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1893,7 +1893,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1893
1893
|
let scale_shift = ${x.getByIndices("vec2<u32>(batch, channel)")};
|
|
1894
1894
|
let value = ${k.getByOffset("global_idx")} * ${O.type.value}(scale_shift.x) + ${O.type.value}(scale_shift.y);
|
|
1895
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,
|
|
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,b,w)]}),getShaderSource:E},{inputs:[t[0],m]})},cc=(e,t,s)=>{let i=t[0].dims,o=i,l=i[0],u=i[i.length-1],d=H.sizeFromDimension(i,1)/u,h=V(u),p=H.size(o)/h,g=[{type:12,data:d},{type:12,data:Math.floor(u/h)}],m=["type","type"],w=!1,b=[0,i.length-1];for(let k=0;k<i.length-2;k++)w=w||i[k+1]!==1,b.push(k+1);w=w&&i[i.length-1]!==1;let S=w?e.compute(St(e.inputs[0],b),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:i.length},(k,x)=>i[b[x]])),E=Ca(e,S,t[1],t[2],l,d,u,s.epsilon),I=k=>{let x=G(t[0].dataType),O=h===1?"vec2f":`mat${h}x2f`,M=q=>{let X=q===0?"x":"y",ae=h===1?"f32":`vec${h}f`;switch(h){case 1:return`${x}(${ae}(scale.${X}))`;case 2:return`vec2<${x}>(${ae}(scale[0].${X}, scale[1].${X}))`;case 4:return`vec4<${x}>(${ae}(scale[0].${X}, scale[1].${X}, scale[2].${X}, scale[3].${X}))`;default:throw new Error(`Not supported compoents ${h}`)}},D=F("input",t[0].dataType,t[0].dims,h),W=le("output",t[0].dataType,o,h);return`
|
|
1897
1897
|
@group(0) @binding(0) var<storage, read> input : array<${D.type.storage}>;
|
|
1898
1898
|
@group(0) @binding(1) var<storage, read> scale_input : array<${O}>;
|
|
1899
1899
|
@group(0) @binding(2) var<storage, read_write> output : array<${W.type.storage}>;
|
|
@@ -1907,10 +1907,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1907
1907
|
let scale_offset = current_image_number * uniforms.C + current_channel_number;
|
|
1908
1908
|
let scale = scale_input[scale_offset];
|
|
1909
1909
|
output[global_idx] = fma(input[global_idx], ${M(0)}, ${M(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:I},{inputs:[t[0],E]})},hc=(e,t)=>{t.format==="NHWC"?cc(e,e.inputs,t):dc(e,e.inputs,t)}}),pc,fc,mc,Vm=
|
|
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:I},{inputs:[t[0],E]})},hc=(e,t)=>{t.format==="NHWC"?cc(e,e.inputs,t):dc(e,e.inputs,t)}}),pc,fc,mc,Vm=_(()=>{Pe(),Me(),be(),pc=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},fc=(e,t,s)=>{let i=t.simplified,o=e[0].dims,l=e[1],u=!i&&e[2],d=o,h=H.normalizeAxis(t.axis,o.length),p=H.sizeToDimension(o,h),g=H.sizeFromDimension(o,h),m=H.size(l.dims),w=u?H.size(u.dims):0;if(m!==g||u&&w!==g)throw new Error(`Size of X.shape()[axis:] == ${g}.
|
|
1911
1911
|
Size of scale and bias (if provided) must match this.
|
|
1912
|
-
Got scale size of ${m} and bias size of ${w}`);let
|
|
1913
|
-
${D.registerUniforms(
|
|
1912
|
+
Got scale size of ${m} and bias size of ${w}`);let b=[];for(let D=0;D<o.length;++D)D<h?b.push(o[D]):b.push(1);let S=V(g),E=["type","type"],I=[{type:12,data:p},{type:1,data:g},{type:12,data:Math.floor(g/S)},{type:1,data:t.epsilon}];u&&E.push("type");let k=s>1,x=s>2,O=D=>{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(le("output",e[0].dataType,d,S)),k&&q.push(le("mean_data_output",1,b)),x&&q.push(le("inv_std_output",1,b));let X=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`
|
|
1913
|
+
${D.registerUniforms(X).declareVariables(...q)}
|
|
1914
1914
|
${D.mainStart()}
|
|
1915
1915
|
${D.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}
|
|
1916
1916
|
let offset = global_idx * uniforms.norm_size_vectorized;
|
|
@@ -1918,7 +1918,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1918
1918
|
var mean_square_vector = ${Z("f32",S)};
|
|
1919
1919
|
|
|
1920
1920
|
for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {
|
|
1921
|
-
let value = ${
|
|
1921
|
+
let value = ${se(W,S,"x[h + offset]")};
|
|
1922
1922
|
mean_vector += value;
|
|
1923
1923
|
mean_square_vector += value * value;
|
|
1924
1924
|
}
|
|
@@ -1926,33 +1926,33 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1926
1926
|
let inv_std_dev = inverseSqrt(${J("mean_square_vector",S)} / uniforms.norm_size ${i?"":"- mean * mean"} + uniforms.epsilon);
|
|
1927
1927
|
|
|
1928
1928
|
for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {
|
|
1929
|
-
let f32input = ${
|
|
1930
|
-
let f32scale = ${
|
|
1929
|
+
let f32input = ${se(W,S,"x[j + offset]")};
|
|
1930
|
+
let f32scale = ${se(W,S,"scale[j]")};
|
|
1931
1931
|
output[j + offset] = ${q[0].type.value}((f32input ${i?"":"- mean"}) * inv_std_dev * f32scale
|
|
1932
|
-
${u?`+ ${
|
|
1932
|
+
${u?`+ ${se(W,S,"bias[j]")}`:""}
|
|
1933
1933
|
);
|
|
1934
1934
|
}
|
|
1935
1935
|
|
|
1936
1936
|
${k?"mean_data_output[global_idx] = mean":""};
|
|
1937
1937
|
${x?"inv_std_output[global_idx] = inv_std_dev":""};
|
|
1938
|
-
}`},M=[{dims:d,dataType:e[0].dataType}];return k&&M.push({dims:
|
|
1938
|
+
}`},M=[{dims:d,dataType:e[0].dataType}];return k&&M.push({dims:b,dataType:1}),x&&M.push({dims:b,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${S};${s};${i}`,inputDependencies:E},getRunData:()=>({outputs:M,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:I}),getShaderSource:O}},mc=(e,t)=>{pc(e.inputs),e.compute(fc(e.inputs,t,e.outputCount))}}),gc,yc,Gm=_(()=>{Me(),ua(),pa(),gc=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.")},yc=e=>{gc(e.inputs);let t=Sr.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(la(e.inputs,{activation:""},t));else{let o=t[t.length-2],l=H.size(e.inputs[0].dims.slice(0,-2)),u=H.size(e.inputs[1].dims.slice(0,-2));if(l!==1&&o===1&&u===1){let d=e.inputs[0].reshape([1,l,i]),h=e.inputs[1].reshape([1,i,s]),p=[1,l,s],g=[d,h];e.compute(yi(g,{activation:""},t,p),{inputs:g})}else e.compute(yi(e.inputs,{activation:""},t))}}}),wc,vc,_c,bc,Sc,qm=_(()=>{Pe(),Me(),A(),be(),wc=(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(!H.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 d=e[2].dims;if(H.size(d)!==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(H.size(h)!==p)throw new Error("zeroPoints input size error.")}},vc=(e,t)=>{let s=e[0].dims,i=s.length,o=s[i-2],l=t.k,u=t.n,d=s.slice(0,i-2),h=H.size(d),p=e[1].dims[2]/4,g=e[0].dataType,m=V(t.k),w=V(p),b=V(u),S=d.concat([o,u]),E=o>1&&u/b%2===0?2:1,I=H.size(S)/b/E,k=64,x=[],O=[h,o,l/m],M=H.convertShape(e[1].dims).slice();M.splice(-1,1,p/w),x.push(...L(O)),x.push(...L(M)),x.push(...L(e[2].dims)),e.length===4&&x.push(...L(H.convertShape(e[3].dims)));let D=[h,o,u/b];x.push(...L(D));let W=q=>{let X=O.length,ae=F("a",e[0].dataType,X,m),ye=F("b",12,M.length,w),Ke=F("scales",e[2].dataType,e[2].dims.length),Re=[ae,ye,Ke],Oe=e.length===4?F("zero_points",12,e[3].dims.length):void 0;Oe&&Re.push(Oe);let ot=D.length,ve=le("output",e[0].dataType,ot,b),ke=G(e[0].dataType),Qe=(()=>{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.`)}})(),Fe=()=>{let re=`
|
|
1939
1939
|
// reuse a data
|
|
1940
|
-
var input_offset = ${
|
|
1941
|
-
var a_data: ${
|
|
1940
|
+
var input_offset = ${ae.indicesToOffset(`${ae.type.indices}(batch, row, word_offset)`)};
|
|
1941
|
+
var a_data: ${Qe};
|
|
1942
1942
|
for (var j: u32 = 0; j < ${8/m}; j++) {
|
|
1943
|
-
a_data[j] = ${
|
|
1943
|
+
a_data[j] = ${ae.getByOffset("input_offset")};
|
|
1944
1944
|
input_offset++;
|
|
1945
1945
|
}
|
|
1946
|
-
`;for(let
|
|
1947
|
-
b_value = ${w===1?`b${
|
|
1946
|
+
`;for(let _e=0;_e<b*E;_e++)re+=`
|
|
1947
|
+
b_value = ${w===1?`b${_e}_data`:`b${_e}_data[i]`};
|
|
1948
1948
|
b_value_lower = unpack4xU8(b_value & b_mask);
|
|
1949
1949
|
b_value_upper = unpack4xU8((b_value >> 4) & b_mask);
|
|
1950
|
-
b_quantized_values = ${
|
|
1951
|
-
b_dequantized_values = ${m===1?`${
|
|
1952
|
-
workgroup_shared[local_id.x * ${E} + ${Math.floor(
|
|
1953
|
-
`;return
|
|
1954
|
-
var col_index = col * ${
|
|
1955
|
-
${
|
|
1950
|
+
b_quantized_values = ${Qe}(${Array.from({length:4},(Ve,pt)=>`${ke}(b_value_lower[${pt}]), ${ke}(b_value_upper[${pt}])`).join(", ")});
|
|
1951
|
+
b_dequantized_values = ${m===1?`${Qe}(${Array.from({length:8},(Ve,pt)=>`(b_quantized_values[${pt}] - ${Oe?`zero_point${_e}`:"zero_point"}) * scale${_e}`).join(", ")});`:`(b_quantized_values - ${Qe}(${Array(8).fill(`${Oe?`zero_point${_e}`:"zero_point"}`).join(",")})) * scale${_e};`};
|
|
1952
|
+
workgroup_shared[local_id.x * ${E} + ${Math.floor(_e/b)}]${b>1?`[${_e%b}]`:""} += ${Array.from({length:8/m},(Ve,pt)=>`${m===1?`a_data[${pt}] * b_dequantized_values[${pt}]`:`dot(a_data[${pt}], b_dequantized_values[${pt}])`}`).join(" + ")};
|
|
1953
|
+
`;return re},De=()=>{let re=`
|
|
1954
|
+
var col_index = col * ${b};
|
|
1955
|
+
${Oe?`
|
|
1956
1956
|
let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;
|
|
1957
1957
|
var zero_point_byte_count: u32;
|
|
1958
1958
|
var zero_point_word_index: u32;
|
|
@@ -1961,29 +1961,29 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1961
1961
|
var zero_point_bits_offset: u32;
|
|
1962
1962
|
var zero_point_word: u32;`:`
|
|
1963
1963
|
// The default zero point is 8 for unsigned 4-bit quantization.
|
|
1964
|
-
let zero_point = ${
|
|
1965
|
-
`;for(let
|
|
1966
|
-
let scale${
|
|
1967
|
-
${
|
|
1964
|
+
let zero_point = ${ke}(8);`}
|
|
1965
|
+
`;for(let _e=0;_e<b*E;_e++)re+=`
|
|
1966
|
+
let scale${_e} = ${Ke.getByOffset("col_index * nBlocksPerCol + block")};
|
|
1967
|
+
${Oe?`
|
|
1968
1968
|
zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u);
|
|
1969
1969
|
zero_point_word_index = zero_point_byte_count >> 0x2u;
|
|
1970
1970
|
zero_point_byte_offset = zero_point_byte_count & 0x3u;
|
|
1971
1971
|
zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);
|
|
1972
|
-
zero_point_word = ${
|
|
1973
|
-
let zero_point${
|
|
1974
|
-
col_index += 1;`;return
|
|
1975
|
-
let b${
|
|
1976
|
-
col_index += 1;`;return
|
|
1972
|
+
zero_point_word = ${Oe.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
1973
|
+
let zero_point${_e} = ${ke}((zero_point_word) & 0xFu);`:""}
|
|
1974
|
+
col_index += 1;`;return re},ht=()=>{let re=`col_index = col * ${b};`;for(let _e=0;_e<b*E;_e++)re+=`
|
|
1975
|
+
let b${_e}_data = ${ye.getByIndices(`${ye.type.indices}(col_index, block, word)`)};
|
|
1976
|
+
col_index += 1;`;return re+=`
|
|
1977
1977
|
var b_value: u32;
|
|
1978
1978
|
let b_mask: u32 = 0x0F0F0F0Fu;
|
|
1979
1979
|
var b_value_lower: vec4<u32>;
|
|
1980
1980
|
var b_value_upper: vec4<u32>;
|
|
1981
|
-
var b_quantized_values: ${
|
|
1982
|
-
var b_dequantized_values: ${
|
|
1983
|
-
var<workgroup> workgroup_shared: array<${
|
|
1984
|
-
${q.declareVariables(...
|
|
1981
|
+
var b_quantized_values: ${Qe};
|
|
1982
|
+
var b_dequantized_values: ${Qe};`,re};return`
|
|
1983
|
+
var<workgroup> workgroup_shared: array<${ve.type.value}, ${E*k}>;
|
|
1984
|
+
${q.declareVariables(...Re,ve)}
|
|
1985
1985
|
${q.mainStart([k,1,1])}
|
|
1986
|
-
let output_indices = ${
|
|
1986
|
+
let output_indices = ${ve.offsetToIndices(`(global_idx / ${k}) * ${E}`)};
|
|
1987
1987
|
let col = output_indices[2];
|
|
1988
1988
|
let row = output_indices[1];
|
|
1989
1989
|
let batch = output_indices[0];
|
|
@@ -1992,9 +1992,9 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1992
1992
|
for (var block = local_id.x; block < nBlocksPerCol; block += ${k}) {
|
|
1993
1993
|
//process one block
|
|
1994
1994
|
var word_offset: u32 = block * ${t.blockSize/m};
|
|
1995
|
-
${
|
|
1995
|
+
${De()}
|
|
1996
1996
|
for (var word: u32 = 0; word < ${p}; word += ${w}) {
|
|
1997
|
-
${
|
|
1997
|
+
${ht()}
|
|
1998
1998
|
for (var i: u32 = 0; i < ${w}; i++) {
|
|
1999
1999
|
${Fe()}
|
|
2000
2000
|
word_offset += ${8/m};
|
|
@@ -2004,25 +2004,25 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2004
2004
|
workgroupBarrier();
|
|
2005
2005
|
|
|
2006
2006
|
if (local_id.x < ${E}) {
|
|
2007
|
-
var output_value: ${
|
|
2007
|
+
var output_value: ${ve.type.value} = ${ve.type.value}(0);
|
|
2008
2008
|
var workgroup_shared_offset: u32 = local_id.x;
|
|
2009
2009
|
for (var b: u32 = 0u; b < ${k}u; b++) {
|
|
2010
2010
|
output_value += workgroup_shared[workgroup_shared_offset];
|
|
2011
2011
|
workgroup_shared_offset += ${E};
|
|
2012
2012
|
}
|
|
2013
|
-
${
|
|
2013
|
+
${ve.setByIndices(`${ve.type.indices}(batch, row, col + local_id.x)`,"output_value")};
|
|
2014
2014
|
}
|
|
2015
|
-
}`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${m};${w};${
|
|
2016
|
-
let a_data0 = vec4<${
|
|
2017
|
-
let a_data1 = vec4<${
|
|
2018
|
-
let a_data0 = vec4<${
|
|
2019
|
-
let a_data1 = vec4<${
|
|
2015
|
+
}`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${m};${w};${b};${E};${k}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:S,dataType:g}],dispatchGroup:{x:I},programUniforms:x}),getShaderSource:W}},_c=(e,t)=>{let s=e[0].dims,i=s.length,o=s[i-2],l=t.k,u=t.n,d=s.slice(0,i-2),h=H.size(d),p=e[1].dims[2]/4,g=e[0].dataType,m=V(t.k),w=V(p),b=d.concat([o,u]),S=128,E=u%8===0?8:u%4===0?4:1,I=S/E,k=I*w*8,x=k/m,O=k/t.blockSize,M=H.size(b)/E,D=[],W=[h,o,l/m],q=H.convertShape(e[1].dims).slice();q.splice(-1,1,p/w),D.push(...L(W)),D.push(...L(q)),D.push(...L(e[2].dims)),e.length===4&&D.push(...L(H.convertShape(e[3].dims)));let X=[h,o,u];D.push(...L(X));let ae=ye=>{let Ke=W.length,Re=F("a",e[0].dataType,Ke,m),Oe=F("b",12,q.length,w),ot=F("scales",e[2].dataType,e[2].dims.length),ve=[Re,Oe,ot],ke=e.length===4?F("zero_points",12,e[3].dims.length):void 0;ke&&ve.push(ke);let Qe=X.length,Fe=le("output",e[0].dataType,Qe),De=G(e[0].dataType),ht=()=>{switch(m){case 1:return`
|
|
2016
|
+
let a_data0 = vec4<${De}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);
|
|
2017
|
+
let a_data1 = vec4<${De}>(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<${De}>(sub_a[word_offset], sub_a[word_offset + 1]);
|
|
2019
|
+
let a_data1 = vec4<${De}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`
|
|
2020
2020
|
let a_data0 = sub_a[word_offset];
|
|
2021
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<${
|
|
2022
|
+
var<workgroup> sub_a: array<${Re.type.value}, ${x}>;
|
|
2023
2023
|
var<workgroup> inter_results: array<array<${Fe.type.value}, ${I}>, ${E}>;
|
|
2024
|
-
${
|
|
2025
|
-
${
|
|
2024
|
+
${ye.declareVariables(...ve,Fe)}
|
|
2025
|
+
${ye.mainStart([I,E,1])}
|
|
2026
2026
|
let output_indices = ${Fe.offsetToIndices(`workgroup_index * ${E}`)};
|
|
2027
2027
|
let col = output_indices[2];
|
|
2028
2028
|
let row = output_indices[1];
|
|
@@ -2039,9 +2039,9 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2039
2039
|
let a_col = a_col_start + a_offset;
|
|
2040
2040
|
if (a_col < uniforms.a_shape[2])
|
|
2041
2041
|
{
|
|
2042
|
-
sub_a[a_offset] = ${
|
|
2042
|
+
sub_a[a_offset] = ${Re.getByIndices(`${Re.type.indices}(batch, row, a_col)`)};
|
|
2043
2043
|
} else {
|
|
2044
|
-
sub_a[a_offset] = ${
|
|
2044
|
+
sub_a[a_offset] = ${Re.type.value}(0);
|
|
2045
2045
|
}
|
|
2046
2046
|
}
|
|
2047
2047
|
workgroupBarrier();
|
|
@@ -2049,28 +2049,28 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2049
2049
|
// each thread process one block
|
|
2050
2050
|
let b_row = col + local_id.y;
|
|
2051
2051
|
let block = tile * ${O} + local_id.x;
|
|
2052
|
-
${
|
|
2052
|
+
${ke?`
|
|
2053
2053
|
let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;
|
|
2054
2054
|
let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);
|
|
2055
2055
|
let zero_point_word_index = zero_point_byte_count >> 0x2u;
|
|
2056
2056
|
let zero_point_byte_offset = zero_point_byte_count & 0x3u;
|
|
2057
2057
|
let zero_point_nibble_offset: u32 = block & 0x1u;
|
|
2058
2058
|
let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);
|
|
2059
|
-
let zero_point_word = ${
|
|
2060
|
-
let zero_point = ${
|
|
2059
|
+
let zero_point_word = ${ke.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
|
|
2060
|
+
let zero_point = ${De}((zero_point_word) & 0xFu);`:`
|
|
2061
2061
|
// The default zero point is 8 for unsigned 4-bit quantization.
|
|
2062
|
-
let zero_point = ${
|
|
2063
|
-
let scale = ${
|
|
2064
|
-
let b_data = ${
|
|
2062
|
+
let zero_point = ${De}(8);`}
|
|
2063
|
+
let scale = ${ot.getByOffset("b_row * n_blocks_per_col + block")};
|
|
2064
|
+
let b_data = ${Oe.getByIndices(`${Oe.type.indices}(b_row, block, 0)`)};
|
|
2065
2065
|
var word_offset = local_id.x * ${t.blockSize/m};
|
|
2066
2066
|
for (var i: u32 = 0; i < ${w}; i++) {
|
|
2067
|
-
${
|
|
2067
|
+
${ht()}
|
|
2068
2068
|
let b_value = ${w===1?"b_data":"b_data[i]"};
|
|
2069
2069
|
let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);
|
|
2070
2070
|
let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);
|
|
2071
|
-
let b_quantized_values = mat2x4<${
|
|
2072
|
-
let b_dequantized_values = (b_quantized_values - mat2x4<${
|
|
2073
|
-
inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(
|
|
2071
|
+
let b_quantized_values = mat2x4<${De}>(${Array.from({length:4},(re,_e)=>`${De}(b_value_lower[${_e}]), ${De}(b_value_upper[${_e}])`).join(", ")});
|
|
2072
|
+
let b_dequantized_values = (b_quantized_values - mat2x4<${De}>(${Array(8).fill("zero_point").join(",")})) * scale;
|
|
2073
|
+
inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(re,_e)=>`${`dot(a_data${_e}, b_dequantized_values[${_e}])`}`).join(" + ")};
|
|
2074
2074
|
word_offset += ${8/m};
|
|
2075
2075
|
}
|
|
2076
2076
|
workgroupBarrier();
|
|
@@ -2086,7 +2086,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2086
2086
|
${Fe.setByIndices(`${Fe.type.indices}(batch, row, col + local_idx)`,"output_value")}
|
|
2087
2087
|
}
|
|
2088
2088
|
}
|
|
2089
|
-
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${m};${w};${I};${E}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:
|
|
2089
|
+
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${m};${w};${I};${E}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:b,dataType:g}],dispatchGroup:{x:M},programUniforms:D}),getShaderSource:ae}},bc=(e,t)=>{wc(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(_c(e.inputs,t)):e.compute(vc(e.inputs,t))},Sc=e=>$(e)}),Tc,$c,xc,Ec,Cc,kc,Rc,Ac,Mc,Wm=_(()=>{Pe(),Me(),be(),Tc=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].")}},$c=(e,t,s)=>{let i="";for(let o=t-1;o>=0;--o)i+=`
|
|
2090
2090
|
k = i32(${e.indicesGet("indices",o)}) - ${j("uniforms.pads",o,s)};
|
|
2091
2091
|
if (k < 0) {
|
|
2092
2092
|
break;
|
|
@@ -2149,7 +2149,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2149
2149
|
var k = 0;
|
|
2150
2150
|
${i}
|
|
2151
2151
|
value = x[offset];
|
|
2152
|
-
`},kc=(e,t,s)=>{switch(s.mode){case 0:return $c(e,t,s.pads.length);case 1:return xc(e,t,s.pads.length);case 2:return Ec(e,t,s.pads.length);case 3:return Cc(e,t,s.pads.length);default:throw new Error("Invalid mode")}},Rc=(e,t)=>{let s=H.padShape(e[0].dims.slice(),t.pads),i=e[0].dims,o=H.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 d=["rank"],h=p=>{let g=
|
|
2152
|
+
`},kc=(e,t,s)=>{switch(s.mode){case 0:return $c(e,t,s.pads.length);case 1:return xc(e,t,s.pads.length);case 2:return Ec(e,t,s.pads.length);case 3:return Cc(e,t,s.pads.length);default:throw new Error("Invalid mode")}},Rc=(e,t)=>{let s=H.padShape(e[0].dims.slice(),t.pads),i=e[0].dims,o=H.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 d=["rank"],h=p=>{let g=le("output",e[0].dataType,s.length),m=F("x",e[0].dataType,i.length),w=m.type.value,b=kc(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
2153
|
${p.registerUniforms(S).declareVariables(m,g)}
|
|
2154
2154
|
${p.mainStart()}
|
|
2155
2155
|
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -2157,9 +2157,9 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2157
2157
|
let indices = ${g.offsetToIndices("global_idx")};
|
|
2158
2158
|
|
|
2159
2159
|
var value = ${w}(0);
|
|
2160
|
-
${
|
|
2160
|
+
${b}
|
|
2161
2161
|
output[global_idx] = value;
|
|
2162
|
-
}`};return{name:"Pad",shaderCache:{hint:`${t.mode}${u}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(H.size(s)/64)},programUniforms:l}),getShaderSource:h}},Ac=(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 d=e[3].getBigInt64Array();for(let h=0;h<d.length;h++)l[Number(d[h])]=Number(s[h]),l[Number(d[h])+o]=Number(s[h+d.length])}else s.forEach((d,h)=>l[Number(h)]=Number(d));let u=[];return l.forEach(d=>u.push(d)),{mode:t.mode,value:i,pads:u}}else return t},Mc=(e,t)=>{Tc(e.inputs);let s=Ac(e.inputs,t);e.compute(Rc(e.inputs,s),{inputs:[0]})}}),Vs,ka,Ra,Aa,Ma,Ic,Pc,Ia,Pa,Oc,zc,Oa,Dc,Lc,za,Bc,Nc,Uc,Fc,Hm=
|
|
2162
|
+
}`};return{name:"Pad",shaderCache:{hint:`${t.mode}${u}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(H.size(s)/64)},programUniforms:l}),getShaderSource:h}},Ac=(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 d=e[3].getBigInt64Array();for(let h=0;h<d.length;h++)l[Number(d[h])]=Number(s[h]),l[Number(d[h])+o]=Number(s[h+d.length])}else s.forEach((d,h)=>l[Number(h)]=Number(d));let u=[];return l.forEach(d=>u.push(d)),{mode:t.mode,value:i,pads:u}}else return t},Mc=(e,t)=>{Tc(e.inputs);let s=Ac(e.inputs,t);e.compute(Rc(e.inputs,s),{inputs:[0]})}}),Vs,ka,Ra,Aa,Ma,Ic,Pc,Ia,Pa,Oc,zc,Oa,Dc,Lc,za,Bc,Nc,Uc,Fc,Hm=_(()=>{It(),Pe(),Me(),be(),Vs=e=>{if(ge.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},ka=(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(),d=t.strides.slice(),h=l?t.dilations.slice():[],p=t.pads.slice();Hr.adjustPoolAttributes(s,o,u,d,h,p);let g=Hr.computePoolOutputShape(s,o,d,h,u,p,t.autoPad),m=Object.assign({},t);l?Object.assign(m,{kernelShape:u,strides:d,pads:p,dilations:h,cacheKey:t.cacheKey}):Object.assign(m,{kernelShape:u,strides:d,pads:p,cacheKey:t.cacheKey});let w=g.slice();return w.push(w.splice(1,1)[0]),[m,i?w:g]},Ra=(e,t)=>{let s=t.format==="NHWC",i=H.size(e),o=H.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 d=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:d},{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 b=t.kernelShape[t.kernelShape.length-2],S=t.strides[t.strides.length-2],E=t.pads[t.pads.length/2-2],I=t.pads[t.pads.length-2];w=!!(E+I),l.push({type:12,data:b},{type:12,data:S},{type:12,data:E},{type:12,data:I}),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 d=H.computeStrides(t.kernelShape);l.push({type:12,data:d},{type:12,data:t.pads},{type:12,data:t.strides}),u.push({name:"kernelStrides",type:"u32",length:d.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]}},Aa=(e,t,s,i,o,l,u,d,h,p,g,m)=>{let w=o.format==="NHWC",b=t.type.value,S=le("output",t.type.tensor,i);if(o.kernelShape.length<=2){let E="",I="",k="",x=s-(w?2:1);if(g?E=`
|
|
2163
2163
|
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2164
2164
|
xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;
|
|
2165
2165
|
if (xIndices[${x}] < 0 || xIndices[${x}]
|
|
@@ -2195,7 +2195,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2195
2195
|
let indices = ${S.offsetToIndices("global_idx")};
|
|
2196
2196
|
var xIndices = ${S.offsetToIndices("global_idx")};
|
|
2197
2197
|
|
|
2198
|
-
var value = ${
|
|
2198
|
+
var value = ${b}(${d});
|
|
2199
2199
|
var pad = 0;
|
|
2200
2200
|
${I}
|
|
2201
2201
|
${E}
|
|
@@ -2227,7 +2227,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2227
2227
|
|
|
2228
2228
|
var offsets: array<u32, ${E}>;
|
|
2229
2229
|
|
|
2230
|
-
var value = ${
|
|
2230
|
+
var value = ${b}(${d});
|
|
2231
2231
|
var pad = 0;
|
|
2232
2232
|
var isPad = false;
|
|
2233
2233
|
|
|
@@ -2248,12 +2248,12 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2248
2248
|
${u}
|
|
2249
2249
|
|
|
2250
2250
|
output[global_idx] = value;
|
|
2251
|
-
}`}},Ma=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Ic=e=>`${Ma(e)};${e.countIncludePad}`,Pc=e=>`${Ma(e)};${e.storageOrder};${e.dilations}`,Ia=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Pa=(e,t,s,i)=>{let[o,l]=ka(t,i,s),u=
|
|
2251
|
+
}`}},Ma=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Ic=e=>`${Ma(e)};${e.countIncludePad}`,Pc=e=>`${Ma(e)};${e.storageOrder};${e.dilations}`,Ia=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Pa=(e,t,s,i)=>{let[o,l]=ka(t,i,s),u=F("x",t.dataType,t.dims.length),d=u.type.value,h="value += x_val;",p="";o.countIncludePad?p+=`value /= ${d}(uniforms.kernelSize);`:p+=`value /= ${d}(i32(uniforms.kernelSize) - pad);`;let[g,m,w,b,S]=Ra(l,o);g.push(...L(t.dims,l));let E=["rank"];return{name:e,shaderCache:{hint:`${i.cacheKey};${w};${b};${S}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(H.size(l)/64)},programUniforms:g}),getShaderSource:I=>Aa(I,u,t.dims.length,l.length,o,h,p,0,m,w,b,S)}},Oc=e=>{let t=e.count_include_pad!==0,s=Ia(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:Ic(i)}},zc=(e,t)=>{Vs(e.inputs),e.compute(Pa("AveragePool",e.inputs[0],!1,t))},Oa={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Dc=e=>{let t=e.format;return{format:t,...Oa,cacheKey:t}},Lc=(e,t)=>{Vs(e.inputs),e.compute(Pa("GlobalAveragePool",e.inputs[0],!0,t))},za=(e,t,s,i)=>{let[o,l]=ka(t,i,s),u=`
|
|
2252
2252
|
value = max(x_val, value);
|
|
2253
|
-
`,d="",h=
|
|
2254
|
-
${
|
|
2255
|
-
${
|
|
2256
|
-
${
|
|
2253
|
+
`,d="",h=F("x",t.dataType,t.dims.length),p=["rank"],[g,m,w,b,S]=Ra(l,o);return g.push(...L(t.dims,l)),{name:e,shaderCache:{hint:`${i.cacheKey};${w};${b};${S}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(H.size(l)/64)},programUniforms:g}),getShaderSource:E=>Aa(E,h,t.dims.length,l.length,o,u,d,t.dataType===10?-65504:-1e5,m,w,b,S)}},Bc=(e,t)=>{Vs(e.inputs),e.compute(za("MaxPool",e.inputs[0],!1,t))},Nc=e=>{let t=e.storage_order,s=e.dilations,i=Ia(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:Pc(o)}},Uc=e=>{let t=e.format;return{format:t,...Oa,cacheKey:t}},Fc=(e,t)=>{Vs(e.inputs),e.compute(za("GlobalMaxPool",e.inputs[0],!0,t))}}),Vc,Gc,qc,Wc,jm=_(()=>{Pe(),Me(),A(),be(),Vc=(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)].")}},Gc=(e,t)=>{let s=H.normalizeAxis(t.axis,e[0].dims.length),i=e[0].dataType,o=i===3,l=e[0].dims,u=e[1].dataType,d=H.size(l),h=i===3||i===2,p=h?[Math.ceil(H.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(H.size(m.dims)/4)]:m.dims:void 0,b=g.length===0||g.length===1&&g[0]===1,S=b===!1&&g.length===1,E=V(d),I=b&&(!h||E===4),k=I?E:1,x=I&&!h?E:1,O=F("input",h?12:i,p.length,x),M=F("scale",u,g.length),D=m?F("zero_point",h?12:i,w.length):void 0,W=le("output",u,l.length,k),q=[O,M];D&&q.push(D);let X=[p,g];m&&X.push(w);let ae=[{type:12,data:d/k},{type:12,data:s},{type:12,data:t.blockSize},...L(...X,l)],ye=Ke=>{let Re=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
2254
|
+
${Ke.registerUniforms(Re).declareVariables(...q,W)}
|
|
2255
|
+
${Ke.mainStart()}
|
|
2256
|
+
${Ke.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2257
2257
|
let output_indices = ${W.offsetToIndices("global_idx")};
|
|
2258
2258
|
|
|
2259
2259
|
// Set input x
|
|
@@ -2263,7 +2263,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2263
2263
|
let x_value = ${k===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${O.getByOffset("global_idx")};`};
|
|
2264
2264
|
|
|
2265
2265
|
// Set scale input
|
|
2266
|
-
${
|
|
2266
|
+
${b?`let scale_value= ${M.getByOffset("0")}`:S?`
|
|
2267
2267
|
let scale_index = ${W.indicesGet("output_indices","uniforms.axis")};
|
|
2268
2268
|
let scale_value= ${M.getByOffset("scale_index")};`:`
|
|
2269
2269
|
var scale_indices: ${M.type.indices} = output_indices;
|
|
@@ -2272,7 +2272,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2272
2272
|
let scale_value= ${M.getByIndices("scale_indices")};`};
|
|
2273
2273
|
|
|
2274
2274
|
// Set zero-point input
|
|
2275
|
-
${D?
|
|
2275
|
+
${D?b?h?`
|
|
2276
2276
|
let zero_point_input = ${D.getByOffset("0")};
|
|
2277
2277
|
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
|
|
2278
2278
|
let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${D.getByOffset("0")}`:S?h?`
|
|
@@ -2288,12 +2288,12 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2288
2288
|
let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${D.getByIndices("scale_indices")};`:`let zero_point_value = ${h?o?"i32":"u32":O.type.value}(0);`};
|
|
2289
2289
|
// Compute and write output
|
|
2290
2290
|
${W.setByOffset("global_idx",`${W.type.value}(x_value - zero_point_value) * scale_value`)};
|
|
2291
|
-
}`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:D?["rank","rank","rank"]:["rank","rank"]},getShaderSource:
|
|
2291
|
+
}`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:D?["rank","rank","rank"]:["rank","rank"]},getShaderSource:ye,getRunData:()=>({outputs:[{dims:l,dataType:u}],dispatchGroup:{x:Math.ceil(d/k/64),y:1,z:1},programUniforms:ae})}},qc=(e,t)=>{Vc(e.inputs,t),e.compute(Gc(e.inputs,t))},Wc=e=>$({axis:e.axis,blockSize:e.blockSize})}),Hc,jc,Kc,Km=_(()=>{It(),Pe(),be(),Hc=(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.")},jc=(e,t,s,i)=>{let o=Math.abs(Math.ceil((t-e)/s)),l=[o],u=o,d=[{type:12,data:u},{type:i,data:e},{type:i,data:s},...L(l)],h=p=>{let g=le("output",i,l.length),m=g.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:m},{name:"delta",type:m}];return`
|
|
2292
2292
|
${p.registerUniforms(w).declareVariables(g)}
|
|
2293
2293
|
${p.mainStart()}
|
|
2294
2294
|
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
2295
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:d})}},Kc=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]),
|
|
2296
|
+
}`};return{name:"Range",shaderCache:{hint:`${i}`},getShaderSource:h,getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d})}},Kc=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]),ge.webgpu.validateInputContent&&Hc(t,s,i),e.compute(jc(t,s,i,e.inputs[0].dataType),{inputs:[]})}}),Qc,Xc,Yc,Jc,Qm=_(()=>{Pe(),Me(),A(),be(),Qc=(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
2297
|
var oldValue = 0;
|
|
2298
2298
|
loop {
|
|
2299
2299
|
let newValueF32 =`,l=`;
|
|
@@ -2306,8 +2306,8 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2306
2306
|
}
|
|
2307
2307
|
}`;switch(e){case"none":return`${t}=${s};`;case"add":return i==="i32"||i==="u32"?`atomicAdd(&${t}, bitcast<${i}>(${s}));`:`
|
|
2308
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.`)}},Xc=(e,t)=>{let s=e[0].dims,i=e[1].dims,o=s,l=1,u=Math.ceil(H.sizeToDimension(i,i.length-1)/l),d=i[i.length-1],h=H.sizeFromDimension(s,d),p=[{type:12,data:u},{type:12,data:d},{type:12,data:h},...L(e[1].dims,e[2].dims,o)],g=m=>{let w=
|
|
2310
|
-
${m.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(w,
|
|
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.`)}},Xc=(e,t)=>{let s=e[0].dims,i=e[1].dims,o=s,l=1,u=Math.ceil(H.sizeToDimension(i,i.length-1)/l),d=i[i.length-1],h=H.sizeFromDimension(s,d),p=[{type:12,data:u},{type:12,data:d},{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),b=F("updates",e[2].dataType,e[2].dims.length,l),S=t.reduction!=="none"&&t.reduction!==""?vt("output",e[0].dataType,o.length):le("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,b,S)}
|
|
2311
2311
|
${m.mainStart()}
|
|
2312
2312
|
${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2313
2313
|
var data_offset = 0u;
|
|
@@ -2339,7 +2339,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2339
2339
|
${Qc(t.reduction,"output[data_offset + i]","value",S.type.value)}
|
|
2340
2340
|
}
|
|
2341
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}},Yc=e=>$({reduction:e.reduction}),Jc=(e,t)=>{e.compute(Xc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Zc,eh,th,Da,rh,nh,sh,ih,ah,oh,lh,uh,La,dh,ch,hh,ph,fh,mh,gh,Xm=
|
|
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}},Yc=e=>$({reduction:e.reduction}),Jc=(e,t)=>{e.compute(Xc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Zc,eh,th,Da,rh,nh,sh,ih,ah,oh,lh,uh,La,dh,ch,hh,ph,fh,mh,gh,Xm=_(()=>{Pe(),Me(),A(),be(),Zc=(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
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")}},eh=(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},th=(e,t,s,i,o,l)=>{let[u,d,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(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0){if(e[d].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");Zc(i,t),t.axes.length>0&&eh(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")},Da=(e,t,s,i)=>`
|
|
2344
2344
|
// The whole part and the fractional part are calculated separately due to inaccuracy of floating
|
|
2345
2345
|
// point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
|
|
@@ -2475,20 +2475,20 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2475
2475
|
dy2 = 0.5;
|
|
2476
2476
|
}
|
|
2477
2477
|
return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);
|
|
2478
|
-
}`},ch=(e,t,s,i,o,l,u,d,h,p)=>{let g=s.length===2,[m,w]=g?[0,1]:[2,3],
|
|
2479
|
-
fn ${I}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${
|
|
2478
|
+
}`},ch=(e,t,s,i,o,l,u,d,h,p)=>{let g=s.length===2,[m,w]=g?[0,1]:[2,3],b=e.type.value,S=E=>{let I=E===m?"row":"col";return`
|
|
2479
|
+
fn ${I}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${b} {
|
|
2480
2480
|
var output_index = ${t.indicesGet("output_indices",E)};
|
|
2481
|
-
var originalIdx: ${
|
|
2481
|
+
var originalIdx: ${b} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[E]},
|
|
2482
2482
|
${i[E]}, ${s[E]}, ${l[E]}, ${l[E]} + ${s.length});
|
|
2483
|
-
var fractOriginalIdx: ${
|
|
2483
|
+
var fractOriginalIdx: ${b} = originalIdx - floor(originalIdx);
|
|
2484
2484
|
var coefs = getCubicInterpolationCoefs(fractOriginalIdx);
|
|
2485
2485
|
|
|
2486
2486
|
if (${d} && (originalIdx < 0 || originalIdx > (${s[E]} - 1))) {
|
|
2487
2487
|
return ${h};
|
|
2488
2488
|
}
|
|
2489
|
-
var data: array<${
|
|
2489
|
+
var data: array<${b}, 4> = array<${b}, 4>(0.0, 0.0, 0.0, 0.0);
|
|
2490
2490
|
for (var i: i32 = -1; i < 3; i++) {
|
|
2491
|
-
var ${I}: ${
|
|
2491
|
+
var ${I}: ${b} = originalIdx + ${b}(i);
|
|
2492
2492
|
if (${I} < 0 || ${I} >= ${s[E]}) {
|
|
2493
2493
|
${p?`coefs[i + 1] = 0.0;
|
|
2494
2494
|
continue;`:d?`return ${h};`:`${I} = max(0, min(${I}, ${s[E]} - 1));`};
|
|
@@ -2501,12 +2501,12 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2501
2501
|
}`};return`
|
|
2502
2502
|
${S(m)};
|
|
2503
2503
|
${S(w)};
|
|
2504
|
-
fn getCubicInterpolationCoefs(s: ${
|
|
2504
|
+
fn getCubicInterpolationCoefs(s: ${b}) -> array<${b}, 4> {
|
|
2505
2505
|
var absS = abs(s);
|
|
2506
|
-
var coeffs: array<${
|
|
2507
|
-
var oneMinusAbsS: ${
|
|
2508
|
-
var twoMinusAbsS: ${
|
|
2509
|
-
var onePlusAbsS: ${
|
|
2506
|
+
var coeffs: array<${b}, 4> = array<${b}, 4>(0.0, 0.0, 0.0, 0.0);
|
|
2507
|
+
var oneMinusAbsS: ${b} = 1.0 - absS;
|
|
2508
|
+
var twoMinusAbsS: ${b} = 2.0 - absS;
|
|
2509
|
+
var onePlusAbsS: ${b} = 1.0 + absS;
|
|
2510
2510
|
coeffs[0] = ((${u} * onePlusAbsS - 5 * ${u}) * onePlusAbsS + 8 * ${u}) * onePlusAbsS - 4 * ${u};
|
|
2511
2511
|
coeffs[1] = ((${u} + 2) * absS - (${u} + 3)) * absS * absS + 1;
|
|
2512
2512
|
coeffs[2] = ((${u} + 2) * oneMinusAbsS - (${u} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;
|
|
@@ -2514,12 +2514,12 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2514
2514
|
return coeffs;
|
|
2515
2515
|
}
|
|
2516
2516
|
|
|
2517
|
-
fn cubicInterpolation1D(x: array<${
|
|
2518
|
-
var coefsSum: ${
|
|
2517
|
+
fn cubicInterpolation1D(x: array<${b}, 4>, coefs: array<${b}, 4>) -> ${b} {
|
|
2518
|
+
var coefsSum: ${b} = coefs[0] + coefs[1] + coefs[2] + coefs[3];
|
|
2519
2519
|
return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;
|
|
2520
2520
|
}
|
|
2521
2521
|
|
|
2522
|
-
fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${
|
|
2522
|
+
fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${b} {
|
|
2523
2523
|
var input_indices: ${e.type.indices} = output_indices;
|
|
2524
2524
|
return colCubicInterpolation(input_indices, output_indices);
|
|
2525
2525
|
}
|
|
@@ -2582,8 +2582,8 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2582
2582
|
}
|
|
2583
2583
|
return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +
|
|
2584
2584
|
x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);
|
|
2585
|
-
}`},ph=(e,t,s,i,o,l)=>{let u=e.dims,d=sh(l,t.axes,u.length),h=ih(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=ah(u,p,t)));let g=
|
|
2586
|
-
${
|
|
2585
|
+
}`},ph=(e,t,s,i,o,l)=>{let u=e.dims,d=sh(l,t.axes,u.length),h=ih(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=ah(u,p,t)));let g=le("output",e.dataType,h.length),m=F("input",e.dataType,u.length),w=H.size(h),b=u.length===h.length&&u.every((x,O)=>x===h[O]),S=t.coordinateTransformMode==="tf_crop_and_resize",E=t.extrapolationValue,I=m.type.value,k=x=>`
|
|
2586
|
+
${b?"":`
|
|
2587
2587
|
${rh(t.coordinateTransformMode,I)};
|
|
2588
2588
|
${(()=>{switch(t.mode){case"nearest":return`
|
|
2589
2589
|
${uh(m,u)};
|
|
@@ -2599,7 +2599,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2599
2599
|
${x.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",d.length).declareVariables(m,g)}
|
|
2600
2600
|
${x.mainStart()}
|
|
2601
2601
|
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
2602
|
-
${
|
|
2602
|
+
${b?"output[global_idx] = input[global_idx];":`
|
|
2603
2603
|
let output_indices = ${g.offsetToIndices("global_idx")};
|
|
2604
2604
|
var input_indices: ${m.type.indices};
|
|
2605
2605
|
${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);
|
|
@@ -2609,11 +2609,11 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2609
2609
|
output[global_idx] = ${t.extrapolationValue};
|
|
2610
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
2611
|
`}
|
|
2612
|
-
}`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${s}|${p.length>0?t.mode==="cubic"?p:p.length:""}|${o.length>0?o:""}|${d.length>0?d:""}|${
|
|
2612
|
+
}`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${s}|${p.length>0?t.mode==="cubic"?p:p.length:""}|${o.length>0?o:""}|${d.length>0?d:""}|${b}|${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:d},...L(u,h)]})}},fh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},mh=(e,t)=>{let s=[],i=[],o=[],l=fh(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");th(e.inputs,t,l,s,i,o),e.compute(ph(e.inputs[0],t,l,s,i,o),{inputs:[0]})},gh=e=>{let t=e.antialias,s=e.axes,i=e.coordinateTransformMode,o=e.cubicCoeffA,l=e.excludeOutside!==0,u=e.extrapolationValue,d=e.keepAspectRatioPolicy,h=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return $({antialias:t,axes:s,coordinateTransformMode:i,cubicCoeffA:o,excludeOutside:l,extrapolationValue:u,keepAspectRatioPolicy:d,mode:h,nearestMode:p})}}),yh,wh,vh,Ym=_(()=>{Pe(),Me(),be(),yh=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")}},wh=(e,t,s,i)=>{let o=t.simplified,l=e[0].dims,u=H.size(l),d=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,b=i&&s>1,S=i&&s>2,E=s>3,I=64,k=V(p),x=[{type:12,data:h},{type:12,data:k},{type:12,data:p},{type:1,data:t.epsilon}],O=D=>{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(le("output",e[0].dataType,d,k)),b&&q.push(le("mean_output",1,g)),S&&q.push(le("inv_std_output",1,g)),E&&q.push(le("input_skip_bias_sum",e[0].dataType,d,k));let X=G(e[0].dataType),ae=G(1,k);return`
|
|
2613
2613
|
|
|
2614
2614
|
${D.registerUniforms(W).declareVariables(...q)}
|
|
2615
|
-
var<workgroup> sum_shared : array<${
|
|
2616
|
-
var<workgroup> sum_squared_shared : array<${
|
|
2615
|
+
var<workgroup> sum_shared : array<${ae}, ${I}>;
|
|
2616
|
+
var<workgroup> sum_squared_shared : array<${ae}, ${I}>;
|
|
2617
2617
|
|
|
2618
2618
|
${D.mainStart([I,1,1])}
|
|
2619
2619
|
let ix = local_id.x;
|
|
@@ -2628,12 +2628,12 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2628
2628
|
}
|
|
2629
2629
|
for (var i: u32 = 0; i < stride; i++) {
|
|
2630
2630
|
let skip_value = skip[offset + i];
|
|
2631
|
-
let bias_value = ${w?"bias[offset1d + i]":
|
|
2631
|
+
let bias_value = ${w?"bias[offset1d + i]":X+"(0.0)"};
|
|
2632
2632
|
let input_value = x[offset + i];
|
|
2633
2633
|
let value = input_value + skip_value + bias_value;
|
|
2634
2634
|
${E?"input_skip_bias_sum[offset + i] = value;":""}
|
|
2635
2635
|
output[offset + i] = value;
|
|
2636
|
-
let f32_value = ${
|
|
2636
|
+
let f32_value = ${se(X,k,"value")};
|
|
2637
2637
|
sum_shared[ix] += f32_value;
|
|
2638
2638
|
sum_squared_shared[ix] += f32_value * f32_value;
|
|
2639
2639
|
}
|
|
@@ -2653,15 +2653,15 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2653
2653
|
let square_sum = sum_squared_shared[0];
|
|
2654
2654
|
let mean = ${J("sum",k)} / f32(uniforms.hidden_size);
|
|
2655
2655
|
let inv_std_dev = inverseSqrt(${J("square_sum",k)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon);
|
|
2656
|
-
${
|
|
2656
|
+
${b?"mean_output[global_idx] = mean;":""}
|
|
2657
2657
|
${S?"inv_std_output[global_idx] = inv_std_dev;":""}
|
|
2658
2658
|
|
|
2659
2659
|
for (var i: u32 = 0; i < stride; i++) {
|
|
2660
|
-
output[offset + i] = (output[offset + i] ${o?"":`- ${
|
|
2661
|
-
${
|
|
2660
|
+
output[offset + i] = (output[offset + i] ${o?"":`- ${X}(mean)`}) *
|
|
2661
|
+
${X}(inv_std_dev) * gamma[offset1d + i]
|
|
2662
2662
|
${m?"+ beta[offset1d + i]":""};
|
|
2663
2663
|
}
|
|
2664
|
-
}`},M=[{dims:d,dataType:e[0].dataType}];return s>1&&M.push({dims:g,dataType:1}),s>2&&M.push({dims:g,dataType:1}),s>3&&M.push({dims:l,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${k};${
|
|
2664
|
+
}`},M=[{dims:d,dataType:e[0].dataType}];return s>1&&M.push({dims:g,dataType:1}),s>2&&M.push({dims:g,dataType:1}),s>3&&M.push({dims:l,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${k};${b};${S};${E}`,inputDependencies:e.map((D,W)=>"type")},getShaderSource:O,getRunData:()=>({outputs:M,dispatchGroup:{x:Math.ceil(h/p)},programUniforms:x})}},vh=(e,t)=>{yh(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(wh(e.inputs,t,e.outputCount,!1),{outputs:s})}}),_h,Gs,bh,Ba,Sh,Th,$h,xh,Jm=_(()=>{Pe(),Me(),A(),be(),_h=(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`)})},Gs=(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},bh=(e,t)=>{if(e.length>1){let s=Gs(e,1),i=Gs(e,2),o=Gs(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),$({starts:s,ends:i,axes:o})}else return t},Ba=(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]]))},Sh=(e,t,s)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
|
|
2665
2665
|
var input_indices: ${e.type.indices};
|
|
2666
2666
|
var carry = 0u;
|
|
2667
2667
|
for (var i = ${s.length-1}; i >= 0; i--) {
|
|
@@ -2679,7 +2679,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2679
2679
|
${e.indicesSet("input_indices","i","input_index")};
|
|
2680
2680
|
}
|
|
2681
2681
|
return input_indices;
|
|
2682
|
-
}`,Th=(e,t)=>{let s=e[0].dims,i=H.size(s),o=t.axes.length>0?H.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],l=Gs(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)=>Ba(k,x,s,o,l)),d=t.ends.map((k,x)=>Ba(k,x,s,o,l));if(o.length!==u.length||o.length!==d.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),d.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 M=(d[x]-u[x])/k,D=u[x],W=D+M*l[x];u[x]=W,d[x]=D,O[x]=-k}});let p=s.slice(0);o.forEach((k,x)=>{p[k]=Math.ceil((d[k]-u[k])/l[k])});let g={dims:p,dataType:e[0].dataType},m=
|
|
2682
|
+
}`,Th=(e,t)=>{let s=e[0].dims,i=H.size(s),o=t.axes.length>0?H.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],l=Gs(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)=>Ba(k,x,s,o,l)),d=t.ends.map((k,x)=>Ba(k,x,s,o,l));if(o.length!==u.length||o.length!==d.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),d.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 M=(d[x]-u[x])/k,D=u[x],W=D+M*l[x];u[x]=W,d[x]=D,O[x]=-k}});let p=s.slice(0);o.forEach((k,x)=>{p[k]=Math.ceil((d[k]-u[k])/l[k])});let g={dims:p,dataType:e[0].dataType},m=le("output",e[0].dataType,p.length),w=F("input",e[0].dataType,e[0].dims.length),b=H.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}],E=[{type:12,data:b},{type:12,data:u},{type:6,data:h},{type:12,data:l},...L(e[0].dims,p)],I=k=>`
|
|
2683
2683
|
${k.registerUniforms(S).declareVariables(w,m)}
|
|
2684
2684
|
${Sh(w,m,s)}
|
|
2685
2685
|
${k.mainStart()}
|
|
@@ -2687,7 +2687,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2687
2687
|
let output_indices = ${m.offsetToIndices("global_idx")};
|
|
2688
2688
|
let input_indices = calculateInputIndices(output_indices);
|
|
2689
2689
|
${m.setByOffset("global_idx",w.getByIndices("input_indices"))}
|
|
2690
|
-
}`;return{name:"Slice",shaderCache:{hint:`${h.length}_${u.length}_${l.length}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[g],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:E})}},$h=(e,t)=>{
|
|
2690
|
+
}`;return{name:"Slice",shaderCache:{hint:`${h.length}_${u.length}_${l.length}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[g],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:E})}},$h=(e,t)=>{_h(e.inputs,t);let s=bh(e.inputs,t);e.compute(Th(e.inputs,s),{inputs:[0]})},xh=e=>{let t=e.starts,s=e.ends,i=e.axes;return $({starts:t,ends:s,axes:i})}}),Eh,Ch,kh,Rh,Zm=_(()=>{Pe(),Me(),A(),je(),be(),Eh=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Ch=(e,t)=>{let s=e.inputs[0],i=s.dims,o=H.size(i),l=i.length,u=H.normalizeAxis(t.axis,l),d=u<i.length-1,h,p=[];d?(p=Array.from({length:l},(q,X)=>X),p[u]=l-1,p[l-1]=u,h=e.compute(St(s,p),{inputs:[s],outputs:[-1]})[0]):h=s;let g=h.dims,m=g[l-1],w=o/m,b=V(m),S=m/b,E=64;w===1&&(E=256);let I=(q,X)=>X===4?`max(max(${q}.x, ${q}.y), max(${q}.z, ${q}.w))`:X===2?`max(${q}.x, ${q}.y)`:X===3?`max(max(${q}.x, ${q}.y), ${q}.z)`:q,k=F("x",h.dataType,h.dims,b),x=le("result",h.dataType,h.dims,b),O=k.type.value,M=G(h.dataType)==="f32"?`var threadMax = ${O}(-3.4028234663852886e+38f);`:`var threadMax = ${O}(-65504.0h);`,D=q=>`
|
|
2691
2691
|
var<workgroup> rowMaxShared : ${O};
|
|
2692
2692
|
var<workgroup> rowSumShared : ${O};
|
|
2693
2693
|
var<workgroup> threadShared : array<${O}, ${E}>;
|
|
@@ -2730,7 +2730,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2730
2730
|
workgroupBarrier();
|
|
2731
2731
|
}
|
|
2732
2732
|
if (lindex == 0) {
|
|
2733
|
-
rowMaxShared = ${O}(${I("threadShared[0]",
|
|
2733
|
+
rowMaxShared = ${O}(${I("threadShared[0]",b)});
|
|
2734
2734
|
}
|
|
2735
2735
|
workgroupBarrier();
|
|
2736
2736
|
|
|
@@ -2750,7 +2750,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2750
2750
|
workgroupBarrier();
|
|
2751
2751
|
}
|
|
2752
2752
|
if (lindex == 0) {
|
|
2753
|
-
rowSumShared = ${O}(${J("threadShared[0]",
|
|
2753
|
+
rowSumShared = ${O}(${J("threadShared[0]",b)});
|
|
2754
2754
|
}
|
|
2755
2755
|
workgroupBarrier();
|
|
2756
2756
|
|
|
@@ -2761,7 +2761,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2761
2761
|
value = max(value, ${O}(0.0));
|
|
2762
2762
|
setValue(row, col, row_stride, value);
|
|
2763
2763
|
}
|
|
2764
|
-
}`,W=e.compute({name:"Softmax",shaderCache:{hint:`${
|
|
2764
|
+
}`,W=e.compute({name:"Softmax",shaderCache:{hint:`${b};${E}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:g,dataType:h.dataType}],dispatchGroup:{x:w},programUniforms:[{type:6,data:S}]}),getShaderSource:D},{inputs:[h],outputs:[d?-1:0]})[0];d&&e.compute(St(W,p),{inputs:[W]})},kh=(e,t)=>{Eh(e.inputs),Ch(e,t)},Rh=e=>$({axis:e.axis})}),Na,Ah,Mh,Ih,Ph,eg=_(()=>{Pe(),Me(),be(),Na=e=>Array.from(e.getBigInt64Array(),Number),Ah=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(Na(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")},Mh=(e,t)=>{let s=[];for(let i=0;i<e.length;++i)s.push(e[i]*t[i]);return s},Ih=(e,t)=>{let s=e[0].dims,i=t??Na(e[1]),o=Mh(s,i),l=H.size(o),u=e[0].dataType,d=F("input",u,s.length),h=le("output",u,o.length),p=g=>`
|
|
2765
2765
|
const inputShape = ${d.indices(...s)};
|
|
2766
2766
|
${g.registerUniform("output_size","u32").declareVariables(d,h)}
|
|
2767
2767
|
${g.mainStart()}
|
|
@@ -2775,18 +2775,18 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2775
2775
|
${d.indicesSet("input_indices","i","input_dim_value")}
|
|
2776
2776
|
}
|
|
2777
2777
|
${h.setByOffset("global_idx",d.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}},Ph=e=>{Ah(e.inputs),e.compute(Ih(e.inputs),{inputs:[0]})}}),Oh,zh,Dh,tg=
|
|
2779
|
-
let output_indices${
|
|
2780
|
-
let offset_a${
|
|
2781
|
-
let offset_b${
|
|
2782
|
-
let offset_c${
|
|
2783
|
-
let index_a${
|
|
2784
|
-
let index_b${
|
|
2785
|
-
let index_c${
|
|
2786
|
-
let component_a${
|
|
2787
|
-
let component_b${
|
|
2788
|
-
let component_c${
|
|
2789
|
-
${w}[${
|
|
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}},Ph=e=>{Ah(e.inputs),e.compute(Ih(e.inputs),{inputs:[0]})}}),Oh,zh,Dh,tg=_(()=>{Pe(),Me(),be(),Oh=(e,t,s,i,o)=>{let l=le("output_data",o,s.length,4),u=F("a_data",t[1].dataType,t[1].dims.length,4),d=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,b)=>`select(${w}, ${m}, ${b})`;if(!i)p=l.setByOffset("global_idx",g(u.getByOffset("global_idx"),d.getByOffset("global_idx"),h.getByOffset("global_idx")));else{let m=(w,b,S="")=>{let E=`a_data[index_a${b}][component_a${b}]`,I=`b_data[index_b${b}][component_b${b}]`,k=`bool(c_data[index_c${b}] & (0xffu << (component_c${b} * 8)))`;return`
|
|
2779
|
+
let output_indices${b} = ${l.offsetToIndices(`global_idx * 4u + ${b}u`)};
|
|
2780
|
+
let offset_a${b} = ${u.broadcastedIndicesToOffset(`output_indices${b}`,l)};
|
|
2781
|
+
let offset_b${b} = ${d.broadcastedIndicesToOffset(`output_indices${b}`,l)};
|
|
2782
|
+
let offset_c${b} = ${h.broadcastedIndicesToOffset(`output_indices${b}`,l)};
|
|
2783
|
+
let index_a${b} = offset_a${b} / 4u;
|
|
2784
|
+
let index_b${b} = offset_b${b} / 4u;
|
|
2785
|
+
let index_c${b} = offset_c${b} / 4u;
|
|
2786
|
+
let component_a${b} = offset_a${b} % 4u;
|
|
2787
|
+
let component_b${b} = offset_b${b} % 4u;
|
|
2788
|
+
let component_c${b} = offset_c${b} % 4u;
|
|
2789
|
+
${w}[${b}] = ${S}(${g(E,I,k)});
|
|
2790
2790
|
`};o===9?p=`
|
|
2791
2791
|
var data = vec4<u32>(0);
|
|
2792
2792
|
${m("data",0,"u32")}
|
|
@@ -2803,10 +2803,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2803
2803
|
${e.mainStart()}
|
|
2804
2804
|
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
2805
2805
|
${p}
|
|
2806
|
-
}`},zh=e=>{let t=e[1].dims,s=e[2].dims,i=e[0].dims,o=e[1].dataType,l=!(H.areEqual(t,s)&&H.areEqual(s,i)),u=t,d=H.size(t);if(l){let p=Sr.calcShape(Sr.calcShape(t,s,!1),i,!1);if(!p)throw new Error("Can't perform where op on the given tensors");u=p,d=H.size(u)}let h=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>Oh(p,e,u,l,o),getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:h},...L(i,t,s,u)]})}},Dh=e=>{e.compute(zh(e.inputs))}}),Lh,rg=
|
|
2806
|
+
}`},zh=e=>{let t=e[1].dims,s=e[2].dims,i=e[0].dims,o=e[1].dataType,l=!(H.areEqual(t,s)&&H.areEqual(s,i)),u=t,d=H.size(t);if(l){let p=Sr.calcShape(Sr.calcShape(t,s,!1),i,!1);if(!p)throw new Error("Can't perform where op on the given tensors");u=p,d=H.size(u)}let h=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>Oh(p,e,u,l,o),getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:h},...L(i,t,s,u)]})}},Dh=e=>{e.compute(zh(e.inputs))}}),Lh,rg=_(()=>{gm(),ta(),ym(),wm(),vm(),_m(),bm(),Em(),km(),Rm(),Am(),Mm(),Im(),Pm(),Om(),zm(),Dm(),Lm(),Bm(),Nm(),Um(),Fm(),Vm(),Gm(),qm(),Qd(),Wm(),Hm(),jm(),Km(),Qm(),Ji(),Xm(),ic(),Ym(),Jm(),Zm(),rc(),eg(),je(),ia(),tg(),Lh=new Map([["Abs",[yl]],["Acos",[wl]],["Acosh",[vl]],["Add",[au]],["ArgMax",[rl,ea]],["ArgMin",[tl,ea]],["Asin",[_l]],["Asinh",[bl]],["Atan",[Sl]],["Atanh",[Tl]],["Attention",[ll]],["AveragePool",[zc,Oc]],["BatchNormalization",[hl]],["BiasAdd",[ml]],["BiasSplitGelu",[nu]],["Cast",[xl,$l]],["Ceil",[kl]],["Clip",[Cl]],["Concat",[_u,bu]],["Conv",[wa,ga]],["ConvTranspose",[Ku,Wu]],["Cos",[Rl]],["Cosh",[Al]],["CumSum",[Xu,Yu]],["DepthToSpace",[td,rd]],["DequantizeLinear",[qc,Wc]],["Div",[ou]],["Einsum",[ld,ud]],["Elu",[Ml,Ls]],["Equal",[lu]],["Erf",[Il]],["Exp",[Pl]],["Expand",[pd]],["FastGelu",[md]],["Floor",[Ol]],["FusedConv",[wa,ga]],["Gather",[vd,wd]],["GatherElements",[Ad,Rd]],["GatherBlockQuantized",[xd,Ed]],["GatherND",[bd,Sd]],["Gelu",[zl]],["Gemm",[Od,Pd]],["GlobalAveragePool",[Lc,Dc]],["GlobalMaxPool",[Fc,Uc]],["Greater",[hu]],["GreaterOrEqual",[fu]],["GridSample",[Gd,qd]],["GroupQueryAttention",[uc]],["HardSigmoid",[Gl,Vl]],["InstanceNormalization",[hc]],["LayerNormalization",[mc]],["LeakyRelu",[Dl,Ls]],["Less",[pu]],["LessOrEqual",[mu]],["Log",[Yl]],["MatMul",[yc]],["MatMulNBits",[bc,Sc]],["MaxPool",[Bc,Nc]],["Mul",[uu]],["MultiHeadAttention",[Kd,Hd]],["Neg",[Bl]],["Not",[Ll]],["Pad",[Mc]],["Pow",[du]],["QuickGelu",[eu,Ls]],["Range",[Kc]],["Reciprocal",[Nl]],["ReduceMin",[Xo]],["ReduceMean",[Wo]],["ReduceMax",[Qo]],["ReduceSum",[Jo]],["ReduceProd",[Yo]],["ReduceL1",[Ho]],["ReduceL2",[jo]],["ReduceLogSum",[el]],["ReduceLogSumExp",[Ko]],["ReduceSumSquare",[Zo]],["Relu",[Ul]],["Resize",[mh,gh]],["RotaryEmbedding",[sc]],["ScatterND",[Jc,Yc]],["Sigmoid",[Fl]],["Sin",[ql]],["Sinh",[Wl]],["Slice",[$h,xh]],["SkipLayerNormalization",[vh]],["Split",[ec,tc]],["Sqrt",[Hl]],["Softmax",[kh,Rh]],["Sub",[cu]],["Tan",[jl]],["Tanh",[Kl]],["ThresholdedRelu",[Xl,Ls]],["Tile",[Ph]],["Transpose",[tr,Os]],["Where",[Dh]]])}),Bh,ng=_(()=>{It(),Zt(),be(),Bh=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){fe(e.programInfo.name);let l=this.backend.device,u=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let p of t)d.push({binding:d.length,resource:{buffer:p.buffer}});for(let p of s)d.push({binding:d.length,resource:{buffer:p.buffer}});o&&d.push({binding:d.length,resource:o});let h=l.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:d,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(),Ue(e.programInfo.name)}dispose(){}build(e,t){fe(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=He(t,this.backend.device.limits),l=e.getShaderSource(o),u=`${i.join(`
|
|
2807
2807
|
`)}
|
|
2808
2808
|
${o.additionalImplementations}
|
|
2809
|
-
${l}`,d=s.createShaderModule({code:u,label:e.name});et("verbose",()=>`[WebGPU] ${e.name} shader code: ${u}`);let h=s.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return it(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]}}}),Nh={};F(Nh,{WebGpuBackend:()=>Gh});var Uh,Fh,Vh,Gh,sg=b(()=>{It(),Ie(),Zt(),Hr(),Xi(),rg(),ng(),Uh=(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("|")},Fh=(e,t,s)=>{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+s+`:${Uh(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},Vh=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Gh=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 Vh(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ui(this),this.programManager=new Bh(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Bn(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;Ue(),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),d=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),E=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(S)||!Number.isSafeInteger(E))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:g.map(I=>({dims:I.dims,dataType:Yt(I.dataType)})),outputsMetadata:m.map(I=>({dims:I.dims,dataType:Yt(I.dataType)})),kernelId:l,kernelType:d,kernelName:h,programName:p,startTime:S,endTime:E});else{let I="";g.forEach((x,O)=>{I+=`input[${O}]: [${x.dims}] | ${Yt(x.dataType)}, `});let k="";m.forEach((x,O)=>{k+=`output[${O}]: [${x.dims}] | ${Yt(x.dataType)}, `}),console.log(`[profiling] kernel "${l}|${d}|${h}|${p}" ${I}${k}start time: ${S} ns, execution time: ${E-S} ns`)}xt("GPU",`${p}::${w}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),it()}run(e,t,s,i,o,l){Ue(e.name);let u=[];for(let x=0;x<t.length;++x){let O=t[x].data;if(O===0)continue;let M=this.gpuDataManager.get(O);if(!M)throw new Error(`no GPU data for input: ${O}`);u.push(M)}let{outputs:d,dispatchGroup:h,programUniforms:p}=e.getRunData(t),g=s.length===0?d.map((x,O)=>O):s;if(g.length!==d.length)throw new Error(`Output size ${g.length} must be equal to ${d.length}.`);let m=[],w=[];for(let x=0;x<d.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,M=g[x]===-2,D=O||M?o(d[x].dataType,d[x].dims):i(g[x],d[x].dataType,d[x].dims);if(m.push(D),D.data===0)continue;let W=this.gpuDataManager.get(D.data);if(!W)throw new Error(`no GPU data for output: ${D.data}`);if(O&&this.temporaryData.push(W),M){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 it(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 Q=typeof q.data=="number"?[q.data]:q.data;if(Q.length===0)return;let oe=q.type===10?2:4,ge,Qe;q.type===10?(Qe=Q.length>4?16:Q.length>2?8:Q.length*oe,ge=Q.length>4?16:oe*Q.length):(Qe=Q.length<=2?Q.length*oe:16,ge=16),x=Math.ceil(x/Qe)*Qe,O.push(x);let ke=q.type===10?8:4;x+=Q.length>4?Math.ceil(Q.length/ke)*ge:Q.length*oe});let M=16;x=Math.ceil(x/M)*M;let D=new ArrayBuffer(x);p.forEach((q,Q)=>{let oe=O[Q],ge=typeof q.data=="number"?[q.data]:q.data;if(q.type===6)new Int32Array(D,oe,ge.length).set(ge);else if(q.type===12)new Uint32Array(D,oe,ge.length).set(ge);else if(q.type===10)new Uint16Array(D,oe,ge.length).set(ge);else if(q.type===1)new Float32Array(D,oe,ge.length).set(ge);else throw new Error(`Unsupported uniform type: ${Yt(q.type)}`)});let W=this.gpuDataManager.create(x,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(W.buffer,0,D,0,x),this.gpuDataManager.release(W.id),_={offset:0,size:x,buffer:W.buffer}}let S=this.programManager.normalizeDispatchGroupSize(h),E=S[1]===1&&S[2]===1,I=Fh(e,t,E),k=this.programManager.getArtifact(I);if(k||(k=this.programManager.build(e,S),this.programManager.setArtifact(I,k),et("info",()=>`[artifact] key: ${I}, 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],M=O.type,D=typeof O.data=="number"?1:O.data.length,[W,q]=k.uniformVariablesInfo[x];if(M!==W||D!==q)throw new Error(`Uniform variable ${x} mismatch: expect type ${W} with size ${q}, got type ${M} with size ${D} in program "${k.programInfo.name}".`)}}if(et("info",()=>`[ProgramManager] run "${e.name}" (key=${I}) 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,_),it(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=Lh.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,d=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${l}" is not allowed to be called recursively`);this.currentKernelId=e,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),et("info",()=>`[WebGPU] Start to run kernel "[${o}] ${l}"...`);let h=this.env.debug;this.temporaryData=[];try{return h&&this.device.pushErrorScope("validation"),u(t,d[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 Ms(this,e,t);return Tr(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(){et("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(){et("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){et("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()}}}),qh={};F(qh,{init:()=>Hh});var Si,Wh,Hh,ig=b(()=>{Ie(),Zt(),Ae(),As(),Si=class cf{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=H.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=H.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=H.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=H.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(H.size(t)!==H.size(this.dims))throw new Error("Invalid new shape");return new cf(this.module,this.dataType,this.data,t)}},Wh=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 d=[];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)));d.push(new Si(e,p,g,w))}this.inputs=d}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,d,h)=>new Si(this.module,d,this.output(u,h),h),l=(u,d)=>{let h=Jt(u,d);if(!h)throw new Error(`Unsupported data type: ${u}`);let p=h>0?this.backend.gpuDataManager.create(h).id:0;return new Si(this.module,u,p,d)};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)}}},Hh=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=(sg(),re(Nh)).WebGpuBackend,u=new l;await u.initialize(s,i),o("webgpu",[u,d=>u.alloc(Number(d)),d=>u.free(d),(d,h,p,g=!1)=>{if(g)et("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(d)}, dst=${Number(h)}, size=${Number(p)}`),u.memcpy(Number(d),Number(h));else{et("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(d)}, gpuDataId=${Number(h)}, size=${Number(p)}`);let m=t.HEAPU8.subarray(Number(d>>>0),Number(d>>>0)+Number(p));u.upload(Number(h),m)}},async(d,h,p)=>{et("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${d}, dataOffset=${h}, size=${p}`),await u.download(Number(d),()=>t.HEAPU8.subarray(Number(h)>>>0,Number(h+p)>>>0))},(d,h,p)=>u.createKernel(d,Number(h),p,t.UTF8ToString(t._JsepGetNodeName(Number(h)))),d=>u.releaseKernel(d),(d,h,p,g)=>{et("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${d}, contextDataOffset=${h}`);let m=new Wh(t,u,Number(h));return u.computeKernel(Number(d),m,g)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else{let l=new Rs(s);o("webnn",[l,()=>l.reserveTensorId(),u=>l.releaseTensorId(u),async(u,d,h,p,g)=>l.ensureTensor(u,d,h,p,g),(u,d)=>{l.uploadTensor(u,d)},async(u,d)=>l.downloadTensor(u,d),(u,d)=>l.registerMLContext(u,d),!!s.trace])}}}),jh,Ua,Fa,Yr,Kh,Va,Ti,Ga,qa,Wa,Ha,ja,Ka,Qh=b(()=>{It(),Ki(),Qi(),Ie(),Qt(),fn(),Ts(),jh=(e,t)=>{Oe()._OrtInit(e,t)!==0&&Re("Can't initialize onnxruntime.")},Ua=async e=>{jh(e.wasm.numThreads,gn(e.logLevel))},Fa=async(e,t)=>{Oe().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=(ig(),re(qh)).init;t==="webgpu"&&await i("webgpu",Oe(),e,s),t==="webnn"&&await i("webnn",Oe(),e)}},Yr=new Map,Kh=e=>{let t=Oe(),s=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,o,o+i)!==0&&Re("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)}},Va=(e,t)=>{let s=Oe(),i=s.stackSave(),o=0;try{let l=s.PTR_SIZE,u=s.stackAlloc(2*l);s._OrtGetInputOutputMetadata(e,t,u,u+l)!==0&&Re("Can't get session input/output metadata.");let d=Number(s.getValue(u,"*"));o=Number(s.getValue(u+l,"*"));let h=s.HEAP32[o/4];if(h===0)return[d,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[d,h,g]}finally{s.stackRestore(i),o!==0&&s._OrtFree(o)}},Ti=e=>{let t=Oe(),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]},Ga=async(e,t)=>{let s,i,o=Oe();Array.isArray(e)?[s,i]=e:e.buffer===o.HEAPU8.buffer?[s,i]=[e.byteOffset,e.byteLength]:[s,i]=Ti(e);let l=0,u=0,d=0,h=[],p=[],g=[];try{if([u,h]=await Ss(t),t?.externalData&&o.mountExternalData){let M=[];for(let D of t.externalData){let W=typeof D=="string"?D:D.path;M.push(vn(typeof D=="string"?D:D.data).then(q=>{o.mountExternalData(W,q)}))}await Promise.all(M)}for(let M of t?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof M!="string"){let D=M,W=D?.context,q=D?.gpuDevice,Q=D?.deviceType,oe=D?.powerPreference;W?o.currentContext=W:q?o.currentContext=await o.webnnCreateMLContext(q):o.currentContext=await o.webnnCreateMLContext({deviceType:Q,powerPreference:oe})}else o.currentContext=await o.webnnCreateMLContext();break}l=await o._OrtCreateSession(s,i,u),o.webgpuOnCreateSession?.(l),l===0&&Re("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.webnnRegisterMLContext(l,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[m,w]=Kh(l),_=!!t?.enableGraphCapture,S=[],E=[],I=[],k=[],x=[];for(let M=0;M<m;M++){let[D,W,q]=Va(l,M);D===0&&Re("Can't get an input name."),p.push(D);let Q=o.UTF8ToString(D);S.push(Q),I.push(W===0?{name:Q,isTensor:!1}:{name:Q,isTensor:!0,type:Yt(W),shape:q})}for(let M=0;M<w;M++){let[D,W,q]=Va(l,M+m);D===0&&Re("Can't get an output name."),g.push(D);let Q=o.UTF8ToString(D);E.push(Q),k.push(W===0?{name:Q,isTensor:!1}:{name:Q,isTensor:!0,type:Yt(W),shape:q});{if(_&&t?.preferredOutputLocation===void 0){x.push("gpu-buffer");continue}let oe=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[Q]??"cpu",ge=o.webnnIsGraphOutput;if(oe==="cpu"&&ge&&ge(l,Q)){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(M=>M==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(d=o._OrtCreateBinding(l),d===0&&Re("Can't create IO binding."),O={handle:d,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>zn(M))}),Yr.set(l,[l,p,g,O,_,!1]),[l,S,E,I,k]}catch(m){throw p.forEach(w=>o._OrtFree(w)),g.forEach(w=>o._OrtFree(w)),d!==0&&o._OrtReleaseBinding(d)!==0&&Re("Can't release IO binding."),l!==0&&o._OrtReleaseSession(l)!==0&&Re("Can't release session."),m}finally{o._free(s),u!==0&&o._OrtReleaseSessionOptions(u)!==0&&Re("Can't release session options."),h.forEach(m=>o._free(m)),o.unmountExternalData?.()}},qa=e=>{let t=Oe(),s=Yr.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,o,l,u,d]=s;u&&(d&&t._OrtClearBoundOutputs(u.handle)!==0&&Re("Can't clear bound outputs."),t._OrtReleaseBinding(u.handle)!==0&&Re("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&&Re("Can't release session."),Yr.delete(e)},Wa=async(e,t,s,i,o,l,u=!1)=>{if(!e){t.push(0);return}let d=Oe(),h=d.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=Jt(Xt(p),g);{let x=d.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=Jt(Xt(p),g);let x=d.webnnRegisterMLTensor;if(!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=x(i,k,Xt(p),g)}else{let k=e[2];if(Array.isArray(k)){S=h*k.length,_=d._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`);d.setValue(_+x*h,Tt(k[x],s),"*")}}else{let x=d.webnnIsGraphInput,O=d.webnnIsGraphOutput;if(p!=="string"&&x&&O){let M=d.UTF8ToString(o);if(x(i,M)||O(i,M)){let D=Xt(p);S=Jt(D,g),w="ml-tensor";let W=d.webnnCreateTemporaryTensor,q=d.webnnUploadTensor;if(!W||!q)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Q=await W(i,D,g);q(Q,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),_=Q}else S=k.byteLength,_=d._malloc(S),s.push(_),d.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),_)}else S=k.byteLength,_=d._malloc(S),s.push(_),d.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),_)}}let E=d.stackSave(),I=d.stackAlloc(4*g.length);try{g.forEach((x,O)=>d.setValue(I+O*h,x,h===4?"i32":"i64"));let k=d._OrtCreateTensor(Xt(p),_,S,I,g.length,zn(w));k===0&&Re(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(k)}finally{d.stackRestore(E)}},Ha=async(e,t,s,i,o,l)=>{let u=Oe(),d=u.PTR_SIZE,h=Yr.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],E=t.length,I=i.length,k=0,x=[],O=[],M=[],D=[],W=[],q=u.stackSave(),Q=u.stackAlloc(E*d),oe=u.stackAlloc(E*d),ge=u.stackAlloc(I*d),Qe=u.stackAlloc(I*d);try{[k,x]=ys(l),ht("wasm prepareInputOutputTensor");for(let we=0;we<E;we++)await Wa(s[we],O,D,e,g[t[we]],t[we],_);for(let we=0;we<I;we++)await Wa(o[we],M,D,e,m[i[we]],E+i[we],_);Mt("wasm prepareInputOutputTensor");for(let we=0;we<E;we++)u.setValue(Q+we*d,O[we],"*"),u.setValue(oe+we*d,g[t[we]],"*");for(let we=0;we<I;we++)u.setValue(ge+we*d,M[we],"*"),u.setValue(Qe+we*d,m[i[we]],"*");if(w&&!S){let{handle:we,outputPreferredLocations:Ce,outputPreferredLocationsEncoded:Xe}=w;if(g.length!==E)throw new Error(`input count from feeds (${E}) is expected to be always equal to model's input count (${g.length}).`);ht("wasm bindInputsOutputs");for(let Fe=0;Fe<E;Fe++){let ze=t[Fe];await u._OrtBindInput(we,g[ze],O[Fe])!==0&&Re(`Can't bind input[${Fe}] for session=${e}.`)}for(let Fe=0;Fe<I;Fe++){let ze=i[Fe];o[Fe]?.[3]?(W.push(M[Fe]),u._OrtBindOutput(we,m[ze],M[Fe],0)!==0&&Re(`Can't bind pre-allocated output[${Fe}] for session=${e}.`)):u._OrtBindOutput(we,m[ze],0,Xe[ze])!==0&&Re(`Can't bind output[${Fe}] to ${Ce[Fe]} for session=${e}.`)}Mt("wasm bindInputsOutputs"),Yr.set(e,[p,g,m,w,_,!0])}u.jsepOnRunStart?.(p),u.webnnOnRunStart?.(p);let ke;w?ke=await u._OrtRunWithBinding(p,w.handle,I,ge,k):ke=await u._OrtRun(p,oe,Q,E,Qe,I,ge,k),ke!==0&&Re("failed to call OrtRun().");let Pe=[],lt=[];ht("wasm ProcessOutputTensor");for(let we=0;we<I;we++){let Ce=Number(u.getValue(ge+we*d,"*"));if(Ce===M[we]||W.includes(M[we])){Pe.push(o[we]),Ce!==M[we]&&u._OrtReleaseTensor(Ce)!==0&&Re("Can't release tensor.");continue}let Xe=u.stackSave(),Fe=u.stackAlloc(4*d),ze=!1,pt,ne=0;try{u._OrtGetTensorData(Ce,Fe,Fe+d,Fe+2*d,Fe+3*d)!==0&&Re(`Can't access output tensor data on index ${we}.`);let ve=d===4?"i32":"i64",Ve=Number(u.getValue(Fe,ve));ne=u.getValue(Fe+d,"*");let ft=u.getValue(Fe+d*2,"*"),yr=Number(u.getValue(Fe+d*3,ve)),Cr=[];for(let Ut=0;Ut<yr;Ut++)Cr.push(Number(u.getValue(ft+Ut*d,ve)));u._OrtFree(ft)!==0&&Re("Can't free memory for tensor dims.");let Zr=Cr.reduce((Ut,kt)=>Ut*kt,1);pt=Yt(Ve);let Hs=w?.outputPreferredLocations[i[we]];if(pt==="string"){if(Hs==="gpu-buffer"||Hs==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ut=[];for(let kt=0;kt<Zr;kt++){let Lr=u.getValue(ne+kt*d,"*"),dg=u.getValue(ne+(kt+1)*d,"*"),cg=kt===Zr-1?void 0:dg-Lr;Ut.push(u.UTF8ToString(Lr,cg))}Pe.push([pt,Cr,Ut,"cpu"])}else if(Hs==="gpu-buffer"&&Zr>0){let Ut=u.jsepGetBuffer;if(!Ut)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let kt=Ut(ne),Lr=Jt(Ve,Zr);if(Lr===void 0||!yn(pt))throw new Error(`Unsupported data type: ${pt}`);ze=!0,Pe.push([pt,Cr,{gpuBuffer:kt,download:u.jsepCreateDownloader(kt,Lr,pt),dispose:()=>{u._OrtReleaseTensor(Ce)!==0&&Re("Can't release tensor.")}},"gpu-buffer"])}else if(Hs==="ml-tensor"&&Zr>0){let Ut=u.webnnEnsureTensor,kt=u.webnnIsGraphInputOutputTypeSupported;if(!Ut||!kt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Jt(Ve,Zr)===void 0||!wn(pt))throw new Error(`Unsupported data type: ${pt}`);if(!kt(e,pt,!1))throw new Error(`preferredLocation "ml-tensor" for ${pt} output is not supported by current WebNN Context.`);let Lr=await Ut(e,ne,Ve,Cr,!1);ze=!0,Pe.push([pt,Cr,{mlTensor:Lr,download:u.webnnCreateMLTensorDownloader(ne,pt),dispose:()=>{u.webnnReleaseTensorId(ne),u._OrtReleaseTensor(Ce)}},"ml-tensor"])}else if(Hs==="ml-tensor-cpu-output"&&Zr>0){let Ut=u.webnnCreateMLTensorDownloader(ne,pt)(),kt=Pe.length;ze=!0,lt.push((async()=>{let Lr=[kt,await Ut];return u.webnnReleaseTensorId(ne),u._OrtReleaseTensor(Ce),Lr})()),Pe.push([pt,Cr,[],"cpu"])}else{let Ut=mn(pt),kt=new Ut(Zr);new Uint8Array(kt.buffer,kt.byteOffset,kt.byteLength).set(u.HEAPU8.subarray(ne,ne+kt.byteLength)),Pe.push([pt,Cr,kt,"cpu"])}}finally{u.stackRestore(Xe),pt==="string"&&ne&&u._free(ne),ze||u._OrtReleaseTensor(Ce)}}w&&!_&&(u._OrtClearBoundOutputs(w.handle)!==0&&Re("Can't clear bound outputs."),Yr.set(e,[p,g,m,w,_,!1]));for(let[we,Ce]of await Promise.all(lt))Pe[we][2]=Ce;return Mt("wasm ProcessOutputTensor"),Pe}finally{u.webnnOnRunEnd?.(p),u.stackRestore(q),O.forEach(ke=>u._OrtReleaseTensor(ke)),M.forEach(ke=>u._OrtReleaseTensor(ke)),D.forEach(ke=>u._free(ke)),k!==0&&u._OrtReleaseRunOptions(k),x.forEach(ke=>u._free(ke))}},ja=e=>{let t=Oe(),s=Yr.get(e);if(!s)throw new Error("invalid session id");let i=s[0],o=t._OrtEndProfiling(i);o===0&&Re("Can't get an profile file name."),t._OrtFree(o)},Ka=e=>{let t=[];for(let s of e){let i=s[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),Jr,nr,Zn,qs,Ws,$i,Qa,xi,Mn,In,Xh,Yh,Jh,Zh,ep,tp,rp,np,sp=b(()=>{It(),Qh(),Qt(),dn(),Jr=()=>!!me.wasm.proxy&&typeof document<"u",Zn=!1,qs=!1,Ws=!1,xi=new Map,Mn=(e,t)=>{let s=xi.get(e);s?s.push(t):xi.set(e,[t])},In=()=>{if(Zn||!qs||Ws||!nr)throw new Error("worker not ready")},Xh=e=>{switch(e.data.type){case"init-wasm":Zn=!1,e.data.err?(Ws=!0,Qa[1](e.data.err)):(qs=!0,Qa[0]()),$i&&(URL.revokeObjectURL($i),$i=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=xi.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Yh=async()=>{if(!qs){if(Zn)throw new Error("multiple calls to 'initWasm()' detected.");if(Ws)throw new Error("previous call to 'initWasm()' failed.");if(Zn=!0,Jr())return new Promise((e,t)=>{nr?.terminate(),hs().then(([s,i])=>{try{nr=i,nr.onerror=l=>t(l),nr.onmessage=Xh,Qa=[e,t];let o={type:"init-wasm",in:me};if(!o.in.wasm.wasmPaths&&s){let l=an();l&&(o.in.wasm.wasmPaths=l)}nr.postMessage(o),$i=s}catch(o){t(o)}},t)});try{await pn(me.wasm),await Ua(me),qs=!0}catch(e){throw Ws=!0,e}finally{Zn=!1}}},Jh=async e=>{if(Jr())return In(),new Promise((t,s)=>{Mn("init-ep",[t,s]);let i={type:"init-ep",in:{epName:e,env:me}};nr.postMessage(i)});await Fa(me,e)},Zh=async e=>Jr()?(In(),new Promise((t,s)=>{Mn("copy-from",[t,s]);let i={type:"copy-from",in:{buffer:e}};nr.postMessage(i,[e.buffer])})):Ti(e),ep=async(e,t)=>{if(Jr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return In(),new Promise((s,i)=>{Mn("create",[s,i]);let o={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),nr.postMessage(o,l)})}else return Ga(e,t)},tp=async e=>{if(Jr())return In(),new Promise((t,s)=>{Mn("release",[t,s]);let i={type:"release",in:e};nr.postMessage(i)});qa(e)},rp=async(e,t,s,i,o,l)=>{if(Jr()){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 In(),new Promise((u,d)=>{Mn("run",[u,d]);let h=s,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:h,outputIndices:i,options:l}};nr.postMessage(p,Ka(h))})}else return Ha(e,t,s,i,o,l)},np=async e=>{if(Jr())return In(),new Promise((t,s)=>{Mn("end-profiling",[t,s]);let i={type:"end-profiling",in:e};nr.postMessage(i)});ja(e)}}),Xa,ip,ap,ag=b(()=>{It(),sp(),Ie(),rn(),Ts(),Xa=(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()}`)}},ip=e=>{switch(e[3]){case"cpu":return new He(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!yn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:i,dispose:o}=e[2];return He.fromGpuBuffer(s,{dataType:t,dims:e[1],download:i,dispose:o})}case"ml-tensor":{let t=e[0];if(!wn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:i,dispose:o}=e[2];return He.fromMLTensor(s,{dataType:t,dims:e[1],download:i,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},ap=class{async fetchModelAndCopyToWasmMemory(e){return Zh(await vn(e))}async loadModel(e,t){Ue();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ep(s,t),it()}async dispose(){return tp(this.sessionId)}async run(e,t,s){Ue();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 d=i.map((m,w)=>Xa(m,()=>`input "${this.inputNames[o[w]]}"`)),h=l.map((m,w)=>m?Xa(m,()=>`output "${this.outputNames[u[w]]}"`):null),p=await rp(this.sessionId,o,d,u,h,s),g={};for(let m=0;m<p.length;m++)g[this.outputNames[u[m]]]=l[m]??ip(p[m]);return it(),g}startProfiling(){}endProfiling(){np(this.sessionId)}}}),op={};F(op,{OnnxruntimeWebAssemblyBackend:()=>Ja,initializeFlags:()=>Ya,wasmBackend:()=>lp});var Ya,Ja,lp,og=b(()=>{It(),sp(),ag(),Ya=()=>{(typeof me.wasm.initTimeout!="number"||me.wasm.initTimeout<0)&&(me.wasm.initTimeout=0);let e=me.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),me.wasm.simd=!1),typeof me.wasm.proxy!="boolean"&&(me.wasm.proxy=!1),typeof me.wasm.trace!="boolean"&&(me.wasm.trace=!1),typeof me.wasm.numThreads!="number"||!Number.isInteger(me.wasm.numThreads)||me.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)me.wasm.numThreads=1;else{let t=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;me.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Ja=class{async init(e){Ya(),await Yh(),await Jh(e)}async createInferenceSessionHandler(e,t){let s=new ap;return await s.loadModel(e,t),s}},lp=new Ja}),up={};F(up,{InferenceSession:()=>tn,TRACE:()=>xt,TRACE_EVENT_BEGIN:()=>ht,TRACE_EVENT_END:()=>Mt,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>it,Tensor:()=>He,default:()=>ug,env:()=>me,registerBackend:()=>ae}),It(),It(),It();var lg="1.24.3",ug=ss;{let e=(og(),re(op)).wasmBackend;ae("webgpu",e,5),ae("webnn",e,5),ae("cpu",e,10),ae("wasm",e,10)}return Object.defineProperty(me.versions,"web",{value:lg,enumerable:!0}),re(up)})();/**
|
|
2809
|
+
${l}`,d=s.createShaderModule({code:u,label:e.name});Ze("verbose",()=>`[WebGPU] ${e.name} shader code: ${u}`);let h=s.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return Ue(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]}}}),Nh={};U(Nh,{WebGpuBackend:()=>Gh});var Uh,Fh,Vh,Gh,sg=_(()=>{It(),Pe(),Zt(),jr(),Xi(),rg(),ng(),Uh=(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("|")},Fh=(e,t,s)=>{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+s+`:${Uh(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},Vh=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Gh=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 Vh(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ui(this),this.programManager=new Bh(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Nn(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;fe(),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),d=u.kernelType,h=u.kernelName,p=o.programName,g=o.inputTensorViews,m=o.outputTensorViews,w=t[i*2],b=t[i*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=w);let S=Number(w-this.queryTimeBase),E=Number(b-this.queryTimeBase);if(!Number.isSafeInteger(S)||!Number.isSafeInteger(E))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:g.map(I=>({dims:I.dims,dataType:Yt(I.dataType)})),outputsMetadata:m.map(I=>({dims:I.dims,dataType:Yt(I.dataType)})),kernelId:l,kernelType:d,kernelName:h,programName:p,startTime:S,endTime:E});else{let I="";g.forEach((x,O)=>{I+=`input[${O}]: [${x.dims}] | ${Yt(x.dataType)}, `});let k="";m.forEach((x,O)=>{k+=`output[${O}]: [${x.dims}] | ${Yt(x.dataType)}, `}),console.log(`[profiling] kernel "${l}|${d}|${h}|${p}" ${I}${k}start time: ${S} ns, execution time: ${E-S} ns`)}$t("GPU",`${p}::${w}::${b}`)}e.unmap(),this.pendingQueries.delete(e)}),Ue()}run(e,t,s,i,o,l){fe(e.name);let u=[];for(let x=0;x<t.length;++x){let O=t[x].data;if(O===0)continue;let M=this.gpuDataManager.get(O);if(!M)throw new Error(`no GPU data for input: ${O}`);u.push(M)}let{outputs:d,dispatchGroup:h,programUniforms:p}=e.getRunData(t),g=s.length===0?d.map((x,O)=>O):s;if(g.length!==d.length)throw new Error(`Output size ${g.length} must be equal to ${d.length}.`);let m=[],w=[];for(let x=0;x<d.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,M=g[x]===-2,D=O||M?o(d[x].dataType,d[x].dims):i(g[x],d[x].dataType,d[x].dims);if(m.push(D),D.data===0)continue;let W=this.gpuDataManager.get(D.data);if(!W)throw new Error(`no GPU data for output: ${D.data}`);if(O&&this.temporaryData.push(W),M){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 Ue(e.name),m;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let b;if(p){let x=0,O=[];p.forEach(q=>{let X=typeof q.data=="number"?[q.data]:q.data;if(X.length===0)return;let ae=q.type===10?2:4,ye,Ke;q.type===10?(Ke=X.length>4?16:X.length>2?8:X.length*ae,ye=X.length>4?16:ae*X.length):(Ke=X.length<=2?X.length*ae:16,ye=16),x=Math.ceil(x/Ke)*Ke,O.push(x);let Re=q.type===10?8:4;x+=X.length>4?Math.ceil(X.length/Re)*ye:X.length*ae});let M=16;x=Math.ceil(x/M)*M;let D=new ArrayBuffer(x);p.forEach((q,X)=>{let ae=O[X],ye=typeof q.data=="number"?[q.data]:q.data;if(q.type===6)new Int32Array(D,ae,ye.length).set(ye);else if(q.type===12)new Uint32Array(D,ae,ye.length).set(ye);else if(q.type===10)new Uint16Array(D,ae,ye.length).set(ye);else if(q.type===1)new Float32Array(D,ae,ye.length).set(ye);else throw new Error(`Unsupported uniform type: ${Yt(q.type)}`)});let W=this.gpuDataManager.create(x,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(W.buffer,0,D,0,x),this.gpuDataManager.release(W.id),b={offset:0,size:x,buffer:W.buffer}}let S=this.programManager.normalizeDispatchGroupSize(h),E=S[1]===1&&S[2]===1,I=Fh(e,t,E),k=this.programManager.getArtifact(I);if(k||(k=this.programManager.build(e,S),this.programManager.setArtifact(I,k),Ze("info",()=>`[artifact] key: ${I}, 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],M=O.type,D=typeof O.data=="number"?1:O.data.length,[W,q]=k.uniformVariablesInfo[x];if(M!==W||D!==q)throw new Error(`Uniform variable ${x} mismatch: expect type ${W} with size ${q}, got type ${M} with size ${D} in program "${k.programInfo.name}".`)}}if(Ze("info",()=>`[ProgramManager] run "${e.name}" (key=${I}) 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,b),Ue(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=Lh.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,d=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${l}" is not allowed to be called recursively`);this.currentKernelId=e,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),Ze("info",()=>`[WebGPU] Start to run kernel "[${o}] ${l}"...`);let h=this.env.debug;this.temporaryData=[];try{return h&&this.device.pushErrorScope("validation"),u(t,d[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 Ms(this,e,t);return Tr(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(){Ze("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(){Ze("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ze("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()}}}),qh={};U(qh,{init:()=>Hh});var Si,Wh,Hh,ig=_(()=>{Pe(),Zt(),Me(),As(),Si=class cf{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=H.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=H.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=H.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=H.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(H.size(t)!==H.size(this.dims))throw new Error("Invalid new shape");return new cf(this.module,this.dataType,this.data,t)}},Wh=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 d=[];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 b=0;b<m;b++)w.push(Number(e.getValue(i*o++,l)));d.push(new Si(e,p,g,w))}this.inputs=d}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,d,h)=>new Si(this.module,d,this.output(u,h),h),l=(u,d)=>{let h=Jt(u,d);if(!h)throw new Error(`Unsupported data type: ${u}`);let p=h>0?this.backend.gpuDataManager.create(h).id:0;return new Si(this.module,u,p,d)};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)}}},Hh=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=(sg(),te(Nh)).WebGpuBackend,u=new l;await u.initialize(s,i),o("webgpu",[u,d=>u.alloc(Number(d)),d=>u.free(d),(d,h,p,g=!1)=>{if(g)Ze("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(d)}, dst=${Number(h)}, size=${Number(p)}`),u.memcpy(Number(d),Number(h));else{Ze("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(d)}, gpuDataId=${Number(h)}, size=${Number(p)}`);let m=t.HEAPU8.subarray(Number(d>>>0),Number(d>>>0)+Number(p));u.upload(Number(h),m)}},async(d,h,p)=>{Ze("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${d}, dataOffset=${h}, size=${p}`),await u.download(Number(d),()=>t.HEAPU8.subarray(Number(h)>>>0,Number(h+p)>>>0))},(d,h,p)=>u.createKernel(d,Number(h),p,t.UTF8ToString(t._JsepGetNodeName(Number(h)))),d=>u.releaseKernel(d),(d,h,p,g)=>{Ze("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${d}, contextDataOffset=${h}`);let m=new Wh(t,u,Number(h));return u.computeKernel(Number(d),m,g)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else{let l=new Rs(s);o("webnn",[l,()=>l.reserveTensorId(),u=>l.releaseTensorId(u),async(u,d,h,p,g)=>l.ensureTensor(u,d,h,p,g),(u,d)=>{l.uploadTensor(u,d)},async(u,d)=>l.downloadTensor(u,d),(u,d)=>l.registerMLContext(u,d),!!s.trace])}}}),jh,Ua,Fa,Jr,Kh,Va,Ti,Ga,qa,Wa,Ha,ja,Ka,Qh=_(()=>{It(),Ki(),Qi(),Pe(),Qt(),mn(),Ts(),jh=(e,t)=>{ze()._OrtInit(e,t)!==0&&Ae("Can't initialize onnxruntime.")},Ua=async e=>{jh(e.wasm.numThreads,yn(e.logLevel))},Fa=async(e,t)=>{ze().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=(ig(),te(qh)).init;t==="webgpu"&&await i("webgpu",ze(),e,s),t==="webnn"&&await i("webnn",ze(),e)}},Jr=new Map,Kh=e=>{let t=ze(),s=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,o,o+i)!==0&&Ae("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)}},Va=(e,t)=>{let s=ze(),i=s.stackSave(),o=0;try{let l=s.PTR_SIZE,u=s.stackAlloc(2*l);s._OrtGetInputOutputMetadata(e,t,u,u+l)!==0&&Ae("Can't get session input/output metadata.");let d=Number(s.getValue(u,"*"));o=Number(s.getValue(u+l,"*"));let h=s.HEAP32[o/4];if(h===0)return[d,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[d,h,g]}finally{s.stackRestore(i),o!==0&&s._OrtFree(o)}},Ti=e=>{let t=ze(),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]},Ga=async(e,t)=>{let s,i,o=ze();Array.isArray(e)?[s,i]=e:e.buffer===o.HEAPU8.buffer?[s,i]=[e.byteOffset,e.byteLength]:[s,i]=Ti(e);let l=0,u=0,d=0,h=[],p=[],g=[];try{if([u,h]=await Ss(t),t?.externalData&&o.mountExternalData){let M=[];for(let D of t.externalData){let W=typeof D=="string"?D:D.path;M.push(_n(typeof D=="string"?D:D.data).then(q=>{o.mountExternalData(W,q)}))}await Promise.all(M)}for(let M of t?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof M!="string"){let D=M,W=D?.context,q=D?.gpuDevice,X=D?.deviceType,ae=D?.powerPreference;W?o.currentContext=W:q?o.currentContext=await o.webnnCreateMLContext(q):o.currentContext=await o.webnnCreateMLContext({deviceType:X,powerPreference:ae})}else o.currentContext=await o.webnnCreateMLContext();break}l=await o._OrtCreateSession(s,i,u),o.webgpuOnCreateSession?.(l),l===0&&Ae("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.webnnRegisterMLContext(l,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[m,w]=Kh(l),b=!!t?.enableGraphCapture,S=[],E=[],I=[],k=[],x=[];for(let M=0;M<m;M++){let[D,W,q]=Va(l,M);D===0&&Ae("Can't get an input name."),p.push(D);let X=o.UTF8ToString(D);S.push(X),I.push(W===0?{name:X,isTensor:!1}:{name:X,isTensor:!0,type:Yt(W),shape:q})}for(let M=0;M<w;M++){let[D,W,q]=Va(l,M+m);D===0&&Ae("Can't get an output name."),g.push(D);let X=o.UTF8ToString(D);E.push(X),k.push(W===0?{name:X,isTensor:!1}:{name:X,isTensor:!0,type:Yt(W),shape:q});{if(b&&t?.preferredOutputLocation===void 0){x.push("gpu-buffer");continue}let ae=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[X]??"cpu",ye=o.webnnIsGraphOutput;if(ae==="cpu"&&ye&&ye(l,X)){x.push("ml-tensor-cpu-output");continue}if(ae!=="cpu"&&ae!=="cpu-pinned"&&ae!=="gpu-buffer"&&ae!=="ml-tensor")throw new Error(`Not supported preferred output location: ${ae}.`);if(b&&ae!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${ae}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);x.push(ae)}}let O=null;return x.some(M=>M==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(d=o._OrtCreateBinding(l),d===0&&Ae("Can't create IO binding."),O={handle:d,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>Dn(M))}),Jr.set(l,[l,p,g,O,b,!1]),[l,S,E,I,k]}catch(m){throw p.forEach(w=>o._OrtFree(w)),g.forEach(w=>o._OrtFree(w)),d!==0&&o._OrtReleaseBinding(d)!==0&&Ae("Can't release IO binding."),l!==0&&o._OrtReleaseSession(l)!==0&&Ae("Can't release session."),m}finally{o._free(s),u!==0&&o._OrtReleaseSessionOptions(u)!==0&&Ae("Can't release session options."),h.forEach(m=>o._free(m)),o.unmountExternalData?.()}},qa=e=>{let t=ze(),s=Jr.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,o,l,u,d]=s;u&&(d&&t._OrtClearBoundOutputs(u.handle)!==0&&Ae("Can't clear bound outputs."),t._OrtReleaseBinding(u.handle)!==0&&Ae("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&&Ae("Can't release session."),Jr.delete(e)},Wa=async(e,t,s,i,o,l,u=!1)=>{if(!e){t.push(0);return}let d=ze(),h=d.PTR_SIZE,p=e[0],g=e[1],m=e[3],w=m,b,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=Jt(Xt(p),g);{let x=d.jsepRegisterBuffer;if(!x)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');b=x(i,l,k,S)}}else if(m==="ml-tensor"){let k=e[2].mlTensor;S=Jt(Xt(p),g);let x=d.webnnRegisterMLTensor;if(!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');b=x(i,k,Xt(p),g)}else{let k=e[2];if(Array.isArray(k)){S=h*k.length,b=d._malloc(S),s.push(b);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`);d.setValue(b+x*h,xt(k[x],s),"*")}}else{let x=d.webnnIsGraphInput,O=d.webnnIsGraphOutput;if(p!=="string"&&x&&O){let M=d.UTF8ToString(o);if(x(i,M)||O(i,M)){let D=Xt(p);S=Jt(D,g),w="ml-tensor";let W=d.webnnCreateTemporaryTensor,q=d.webnnUploadTensor;if(!W||!q)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let X=await W(i,D,g);q(X,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),b=X}else S=k.byteLength,b=d._malloc(S),s.push(b),d.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),b)}else S=k.byteLength,b=d._malloc(S),s.push(b),d.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),b)}}let E=d.stackSave(),I=d.stackAlloc(4*g.length);try{g.forEach((x,O)=>d.setValue(I+O*h,x,h===4?"i32":"i64"));let k=d._OrtCreateTensor(Xt(p),b,S,I,g.length,Dn(w));k===0&&Ae(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(k)}finally{d.stackRestore(E)}},Ha=async(e,t,s,i,o,l)=>{let u=ze(),d=u.PTR_SIZE,h=Jr.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],b=h[4],S=h[5],E=t.length,I=i.length,k=0,x=[],O=[],M=[],D=[],W=[],q=u.stackSave(),X=u.stackAlloc(E*d),ae=u.stackAlloc(E*d),ye=u.stackAlloc(I*d),Ke=u.stackAlloc(I*d);try{[k,x]=ys(l),mt("wasm prepareInputOutputTensor");for(let ve=0;ve<E;ve++)await Wa(s[ve],O,D,e,g[t[ve]],t[ve],b);for(let ve=0;ve<I;ve++)await Wa(o[ve],M,D,e,m[i[ve]],E+i[ve],b);ct("wasm prepareInputOutputTensor");for(let ve=0;ve<E;ve++)u.setValue(X+ve*d,O[ve],"*"),u.setValue(ae+ve*d,g[t[ve]],"*");for(let ve=0;ve<I;ve++)u.setValue(ye+ve*d,M[ve],"*"),u.setValue(Ke+ve*d,m[i[ve]],"*");if(w&&!S){let{handle:ve,outputPreferredLocations:ke,outputPreferredLocationsEncoded:Qe}=w;if(g.length!==E)throw new Error(`input count from feeds (${E}) is expected to be always equal to model's input count (${g.length}).`);mt("wasm bindInputsOutputs");for(let Fe=0;Fe<E;Fe++){let De=t[Fe];await u._OrtBindInput(ve,g[De],O[Fe])!==0&&Ae(`Can't bind input[${Fe}] for session=${e}.`)}for(let Fe=0;Fe<I;Fe++){let De=i[Fe];o[Fe]?.[3]?(W.push(M[Fe]),u._OrtBindOutput(ve,m[De],M[Fe],0)!==0&&Ae(`Can't bind pre-allocated output[${Fe}] for session=${e}.`)):u._OrtBindOutput(ve,m[De],0,Qe[De])!==0&&Ae(`Can't bind output[${Fe}] to ${ke[Fe]} for session=${e}.`)}ct("wasm bindInputsOutputs"),Jr.set(e,[p,g,m,w,b,!0])}u.jsepOnRunStart?.(p),u.webnnOnRunStart?.(p);let Re;w?Re=await u._OrtRunWithBinding(p,w.handle,I,ye,k):Re=await u._OrtRun(p,ae,X,E,Ke,I,ye,k),Re!==0&&Ae("failed to call OrtRun().");let Oe=[],ot=[];mt("wasm ProcessOutputTensor");for(let ve=0;ve<I;ve++){let ke=Number(u.getValue(ye+ve*d,"*"));if(ke===M[ve]||W.includes(M[ve])){Oe.push(o[ve]),ke!==M[ve]&&u._OrtReleaseTensor(ke)!==0&&Ae("Can't release tensor.");continue}let Qe=u.stackSave(),Fe=u.stackAlloc(4*d),De=!1,ht,re=0;try{u._OrtGetTensorData(ke,Fe,Fe+d,Fe+2*d,Fe+3*d)!==0&&Ae(`Can't access output tensor data on index ${ve}.`);let _e=d===4?"i32":"i64",Ve=Number(u.getValue(Fe,_e));re=u.getValue(Fe+d,"*");let pt=u.getValue(Fe+d*2,"*"),yr=Number(u.getValue(Fe+d*3,_e)),Cr=[];for(let Ut=0;Ut<yr;Ut++)Cr.push(Number(u.getValue(pt+Ut*d,_e)));u._OrtFree(pt)!==0&&Ae("Can't free memory for tensor dims.");let en=Cr.reduce((Ut,Rt)=>Ut*Rt,1);ht=Yt(Ve);let Hs=w?.outputPreferredLocations[i[ve]];if(ht==="string"){if(Hs==="gpu-buffer"||Hs==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ut=[];for(let Rt=0;Rt<en;Rt++){let Br=u.getValue(re+Rt*d,"*"),dg=u.getValue(re+(Rt+1)*d,"*"),cg=Rt===en-1?void 0:dg-Br;Ut.push(u.UTF8ToString(Br,cg))}Oe.push([ht,Cr,Ut,"cpu"])}else if(Hs==="gpu-buffer"&&en>0){let Ut=u.jsepGetBuffer;if(!Ut)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Rt=Ut(re),Br=Jt(Ve,en);if(Br===void 0||!wn(ht))throw new Error(`Unsupported data type: ${ht}`);De=!0,Oe.push([ht,Cr,{gpuBuffer:Rt,download:u.jsepCreateDownloader(Rt,Br,ht),dispose:()=>{u._OrtReleaseTensor(ke)!==0&&Ae("Can't release tensor.")}},"gpu-buffer"])}else if(Hs==="ml-tensor"&&en>0){let Ut=u.webnnEnsureTensor,Rt=u.webnnIsGraphInputOutputTypeSupported;if(!Ut||!Rt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Jt(Ve,en)===void 0||!vn(ht))throw new Error(`Unsupported data type: ${ht}`);if(!Rt(e,ht,!1))throw new Error(`preferredLocation "ml-tensor" for ${ht} output is not supported by current WebNN Context.`);let Br=await Ut(e,re,Ve,Cr,!1);De=!0,Oe.push([ht,Cr,{mlTensor:Br,download:u.webnnCreateMLTensorDownloader(re,ht),dispose:()=>{u.webnnReleaseTensorId(re),u._OrtReleaseTensor(ke)}},"ml-tensor"])}else if(Hs==="ml-tensor-cpu-output"&&en>0){let Ut=u.webnnCreateMLTensorDownloader(re,ht)(),Rt=Oe.length;De=!0,ot.push((async()=>{let Br=[Rt,await Ut];return u.webnnReleaseTensorId(re),u._OrtReleaseTensor(ke),Br})()),Oe.push([ht,Cr,[],"cpu"])}else{let Ut=gn(ht),Rt=new Ut(en);new Uint8Array(Rt.buffer,Rt.byteOffset,Rt.byteLength).set(u.HEAPU8.subarray(re,re+Rt.byteLength)),Oe.push([ht,Cr,Rt,"cpu"])}}finally{u.stackRestore(Qe),ht==="string"&&re&&u._free(re),De||u._OrtReleaseTensor(ke)}}w&&!b&&(u._OrtClearBoundOutputs(w.handle)!==0&&Ae("Can't clear bound outputs."),Jr.set(e,[p,g,m,w,b,!1]));for(let[ve,ke]of await Promise.all(ot))Oe[ve][2]=ke;return ct("wasm ProcessOutputTensor"),Oe}finally{u.webnnOnRunEnd?.(p),u.stackRestore(q),O.forEach(Re=>u._OrtReleaseTensor(Re)),M.forEach(Re=>u._OrtReleaseTensor(Re)),D.forEach(Re=>u._free(Re)),k!==0&&u._OrtReleaseRunOptions(k),x.forEach(Re=>u._free(Re))}},ja=e=>{let t=ze(),s=Jr.get(e);if(!s)throw new Error("invalid session id");let i=s[0],o=t._OrtEndProfiling(i);o===0&&Ae("Can't get an profile file name."),t._OrtFree(o)},Ka=e=>{let t=[];for(let s of e){let i=s[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),Zr,nr,es,qs,Ws,$i,Qa,xi,In,Pn,Xh,Yh,Jh,Zh,ep,tp,rp,np,sp=_(()=>{It(),Qh(),Qt(),cn(),Zr=()=>!!ge.wasm.proxy&&typeof document<"u",es=!1,qs=!1,Ws=!1,xi=new Map,In=(e,t)=>{let s=xi.get(e);s?s.push(t):xi.set(e,[t])},Pn=()=>{if(es||!qs||Ws||!nr)throw new Error("worker not ready")},Xh=e=>{switch(e.data.type){case"init-wasm":es=!1,e.data.err?(Ws=!0,Qa[1](e.data.err)):(qs=!0,Qa[0]()),$i&&(URL.revokeObjectURL($i),$i=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=xi.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Yh=async()=>{if(!qs){if(es)throw new Error("multiple calls to 'initWasm()' detected.");if(Ws)throw new Error("previous call to 'initWasm()' failed.");if(es=!0,Zr())return new Promise((e,t)=>{nr?.terminate(),hs().then(([s,i])=>{try{nr=i,nr.onerror=l=>t(l),nr.onmessage=Xh,Qa=[e,t];let o={type:"init-wasm",in:ge};if(!o.in.wasm.wasmPaths&&s){let l=on();l&&(o.in.wasm.wasmPaths=l)}nr.postMessage(o),$i=s}catch(o){t(o)}},t)});try{await fn(ge.wasm),await Ua(ge),qs=!0}catch(e){throw Ws=!0,e}finally{es=!1}}},Jh=async e=>{if(Zr())return Pn(),new Promise((t,s)=>{In("init-ep",[t,s]);let i={type:"init-ep",in:{epName:e,env:ge}};nr.postMessage(i)});await Fa(ge,e)},Zh=async e=>Zr()?(Pn(),new Promise((t,s)=>{In("copy-from",[t,s]);let i={type:"copy-from",in:{buffer:e}};nr.postMessage(i,[e.buffer])})):Ti(e),ep=async(e,t)=>{if(Zr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Pn(),new Promise((s,i)=>{In("create",[s,i]);let o={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),nr.postMessage(o,l)})}else return Ga(e,t)},tp=async e=>{if(Zr())return Pn(),new Promise((t,s)=>{In("release",[t,s]);let i={type:"release",in:e};nr.postMessage(i)});qa(e)},rp=async(e,t,s,i,o,l)=>{if(Zr()){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 Pn(),new Promise((u,d)=>{In("run",[u,d]);let h=s,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:h,outputIndices:i,options:l}};nr.postMessage(p,Ka(h))})}else return Ha(e,t,s,i,o,l)},np=async e=>{if(Zr())return Pn(),new Promise((t,s)=>{In("end-profiling",[t,s]);let i={type:"end-profiling",in:e};nr.postMessage(i)});ja(e)}}),Xa,ip,ap,ag=_(()=>{It(),sp(),Pe(),nn(),Ts(),Xa=(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()}`)}},ip=e=>{switch(e[3]){case"cpu":return new xe(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!wn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:i,dispose:o}=e[2];return xe.fromGpuBuffer(s,{dataType:t,dims:e[1],download:i,dispose:o})}case"ml-tensor":{let t=e[0];if(!vn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:i,dispose:o}=e[2];return xe.fromMLTensor(s,{dataType:t,dims:e[1],download:i,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},ap=class{async fetchModelAndCopyToWasmMemory(e){return Zh(await _n(e))}async loadModel(e,t){fe();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ep(s,t),Ue()}async dispose(){return tp(this.sessionId)}async run(e,t,s){fe();let i=[],o=[];Object.entries(e).forEach(m=>{let w=m[0],b=m[1],S=this.inputNames.indexOf(w);if(S===-1)throw new Error(`invalid input '${w}'`);i.push(b),o.push(S)});let l=[],u=[];Object.entries(t).forEach(m=>{let w=m[0],b=m[1],S=this.outputNames.indexOf(w);if(S===-1)throw new Error(`invalid output '${w}'`);l.push(b),u.push(S)});let d=i.map((m,w)=>Xa(m,()=>`input "${this.inputNames[o[w]]}"`)),h=l.map((m,w)=>m?Xa(m,()=>`output "${this.outputNames[u[w]]}"`):null),p=await rp(this.sessionId,o,d,u,h,s),g={};for(let m=0;m<p.length;m++)g[this.outputNames[u[m]]]=l[m]??ip(p[m]);return Ue(),g}startProfiling(){}endProfiling(){np(this.sessionId)}}}),op={};U(op,{OnnxruntimeWebAssemblyBackend:()=>Ja,initializeFlags:()=>Ya,wasmBackend:()=>lp});var Ya,Ja,lp,og=_(()=>{It(),sp(),ag(),Ya=()=>{(typeof ge.wasm.initTimeout!="number"||ge.wasm.initTimeout<0)&&(ge.wasm.initTimeout=0);let e=ge.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.`),ge.wasm.simd=!1),typeof ge.wasm.proxy!="boolean"&&(ge.wasm.proxy=!1),typeof ge.wasm.trace!="boolean"&&(ge.wasm.trace=!1),typeof ge.wasm.numThreads!="number"||!Number.isInteger(ge.wasm.numThreads)||ge.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)ge.wasm.numThreads=1;else{let t=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;ge.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Ja=class{async init(e){Ya(),await Yh(),await Jh(e)}async createInferenceSessionHandler(e,t){let s=new ap;return await s.loadModel(e,t),s}},lp=new Ja}),up={};U(up,{InferenceSession:()=>rn,TRACE:()=>$t,TRACE_EVENT_BEGIN:()=>mt,TRACE_EVENT_END:()=>ct,TRACE_FUNC_BEGIN:()=>fe,TRACE_FUNC_END:()=>Ue,Tensor:()=>xe,default:()=>ug,env:()=>ge,registerBackend:()=>ie}),It(),It(),It();var lg="1.24.3",ug=ss;{let e=(og(),te(op)).wasmBackend;ie("webgpu",e,5),ie("webnn",e,5),ie("cpu",e,10),ie("wasm",e,10)}return Object.defineProperty(ge.versions,"web",{value:lg,enumerable:!0}),te(up)})();/**
|
|
2810
2810
|
* @license
|
|
2811
2811
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
2812
2812
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
@@ -2851,11 +2851,11 @@ ${l}`,d=s.createShaderModule({code:u,label:e.name});et("verbose",()=>`[WebGPU] $
|
|
|
2851
2851
|
* See the License for the specific language governing permissions and
|
|
2852
2852
|
* limitations under the License.
|
|
2853
2853
|
* =============================================================================
|
|
2854
|
-
*/c.exports=n})(so)),so.exports}var
|
|
2854
|
+
*/c.exports=n})(so)),so.exports}var On={},io={},Cp;function Sy(){return Cp||(Cp=1,Object.defineProperty(io,"__esModule",{value:!0})),io}var ei={},kp;function Ty(){if(kp)return ei;kp=1;var c;Object.defineProperty(ei,"__esModule",{value:!0}),ei.SileroLegacy=void 0;const r=ai();class n{constructor(f,v,C,R,_){this.ortInstance=f,this._session=v,this._h=C,this._c=R,this._sr=_,this.reset_state=()=>{const U=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",U,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",U,[2,1,64])},this.process=async U=>{const te={input:new this.ortInstance.Tensor("float32",U,[1,U.length]),h:this._h,c:this._c,sr:this._sr},Q=await this._session.run(te);this._h=Q.hn,this._c=Q.cn;const[ee]=Q.output?.data;return{notSpeech:1-ee,isSpeech:ee}},this.release=async()=>{await this._session.release(),this._h.dispose(),this._c.dispose(),this._sr.dispose()}}}return ei.SileroLegacy=n,c=n,n.new=async(a,f)=>{r.log.debug("initializing vad");const v=await f(),C=await a.InferenceSession.create(v),R=new a.Tensor("int64",[16000n]),_=Array(128).fill(0),U=new a.Tensor("float32",_,[2,1,64]),B=new a.Tensor("float32",_,[2,1,64]);return r.log.debug("vad is initialized"),new c(a,C,U,B,R)},ei}var ti={},Rp;function $y(){if(Rp)return ti;Rp=1;var c;Object.defineProperty(ti,"__esModule",{value:!0}),ti.SileroV5=void 0;const r=ai();function n(f){const v=Array(256).fill(0);return new f.Tensor("float32",v,[2,1,128])}class a{constructor(v,C,R,_){this._session=v,this._state=C,this._sr=R,this.ortInstance=_,this.reset_state=()=>{this._state=n(this.ortInstance)},this.process=async U=>{const te={input:new this.ortInstance.Tensor("float32",U,[1,U.length]),state:this._state,sr:this._sr},Q=await this._session.run(te);if(!Q.stateN)throw new Error("No state from model");if(this._state=Q.stateN,!Q.output?.data)throw new Error("No output from model");const ee=Q.output.data[0];if(typeof ee!="number")throw new Error("Weird output data");return{notSpeech:1-ee,isSpeech:ee}},this.release=async()=>{await this._session.release(),this._state.dispose(),this._sr.dispose()}}}return ti.SileroV5=a,c=a,a.new=async(f,v)=>{r.log.debug("Loading VAD...");const C=await v(),R=await f.InferenceSession.create(C),_=new f.Tensor("int64",[16000n]),U=n(f);return r.log.debug("...finished loading VAD"),new c(R,U,_,f)},ti}var Ap;function hf(){return Ap||(Ap=1,(function(c){var r=On&&On.__createBinding||(Object.create?(function(v,C,R,_){_===void 0&&(_=R);var U=Object.getOwnPropertyDescriptor(C,R);(!U||("get"in U?!C.__esModule:U.writable||U.configurable))&&(U={enumerable:!0,get:function(){return C[R]}}),Object.defineProperty(v,_,U)}):(function(v,C,R,_){_===void 0&&(_=R),v[_]=C[R]})),n=On&&On.__exportStar||function(v,C){for(var R in v)R!=="default"&&!Object.prototype.hasOwnProperty.call(C,R)&&r(C,v,R)};Object.defineProperty(c,"__esModule",{value:!0}),c.SileroV5=c.SileroLegacy=void 0,n(Sy(),c);var a=Ty();Object.defineProperty(c,"SileroLegacy",{enumerable:!0,get:function(){return a.SileroLegacy}});var f=$y();Object.defineProperty(c,"SileroV5",{enumerable:!0,get:function(){return f.SileroV5}})})(On)),On}var ri={},Mp;function pf(){if(Mp)return ri;Mp=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.Resampler=void 0;const c=ai();class r{constructor(a){this.options=a,this.process=f=>{const v=[];for(const C of f)for(this.inputBuffer.push(C);this.hasEnoughDataForFrame();){const R=this.generateOutputFrame();v.push(R)}return v},a.nativeSampleRate<16e3&&c.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(a){for(const f of a)for(this.inputBuffer.push(f);this.hasEnoughDataForFrame();)yield this.generateOutputFrame()}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){const a=new Float32Array(this.options.targetFrameSize);let f=0,v=0;for(;f<this.options.targetFrameSize;){let C=0,R=0;for(;v<Math.min(this.inputBuffer.length,(f+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const _=this.inputBuffer[v];_!==void 0&&(C+=_,R++),v++}a[f]=C/R,f++}return this.inputBuffer=this.inputBuffer.slice(v),a}}return ri.Resampler=r,ri}var Ip;function xy(){return Ip||(Ip=1,(function(c){var r=Ur&&Ur.__createBinding||(Object.create?(function(Q,ee,ie,ce){ce===void 0&&(ce=ie);var ue=Object.getOwnPropertyDescriptor(ee,ie);(!ue||("get"in ue?!ee.__esModule:ue.writable||ue.configurable))&&(ue={enumerable:!0,get:function(){return ee[ie]}}),Object.defineProperty(Q,ce,ue)}):(function(Q,ee,ie,ce){ce===void 0&&(ce=ie),Q[ce]=ee[ie]})),n=Ur&&Ur.__setModuleDefault||(Object.create?(function(Q,ee){Object.defineProperty(Q,"default",{enumerable:!0,value:ee})}):function(Q,ee){Q.default=ee}),a=Ur&&Ur.__importStar||function(Q){if(Q&&Q.__esModule)return Q;var ee={};if(Q!=null)for(var ie in Q)ie!=="default"&&Object.prototype.hasOwnProperty.call(Q,ie)&&r(ee,Q,ie);return n(ee,Q),ee};Object.defineProperty(c,"__esModule",{value:!0}),c.NonRealTimeVAD=c.defaultNonRealTimeVADOptions=void 0;const f=a(by()),v=uf(),C=Ro(),R=Ao(),_=Ui(),U=hf(),B=pf();c.defaultNonRealTimeVADOptions={...R.defaultFrameProcessorOptions,modelURL:v.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:C.defaultModelFetcher};class te{static async new(ee={}){const ie={...c.defaultNonRealTimeVADOptions,...ee};(0,R.validateOptions)(ie),ie.ortConfig!==void 0&&ie.ortConfig(f);const ce=()=>ie.modelFetcher(ie.modelURL),ue=await U.SileroLegacy.new(f,ce),Be=new R.FrameProcessor(ue.process,ue.reset_state,{positiveSpeechThreshold:ie.positiveSpeechThreshold,negativeSpeechThreshold:ie.negativeSpeechThreshold,redemptionMs:ie.redemptionMs,preSpeechPadMs:ie.preSpeechPadMs,minSpeechMs:ie.minSpeechMs,submitUserSpeechOnPause:ie.submitUserSpeechOnPause},1536/16);return Be.resume(),new this(ce,f,ie,Be)}constructor(ee,ie,ce,ue){this.modelFetcher=ee,this.ort=ie,this.options=ce,this.frameProcessor=ue,this.frameSamples=1536}async*run(ee,ie){const ce={nativeSampleRate:ie,targetSampleRate:16e3,targetFrameSize:this.frameSamples},ue=new B.Resampler(ce);let Be=0,Te=0,oe=0;for await(const me of ue.stream(ee)){const pe=[];await this.frameProcessor.process(me,Ne=>{pe.push(Ne)});for(const Ne of pe)switch(Ne.msg){case _.Message.SpeechStart:Be=oe*this.frameSamples/16;break;case _.Message.SpeechEnd:Te=(oe+1)*this.frameSamples/16,yield{audio:Ne.audio,start:Be,end:Te};break}oe++}const ne=[];this.frameProcessor.endSegment(me=>{ne.push(me)});for(const me of ne)switch(me.msg){case _.Message.SpeechEnd:yield{audio:me.audio,start:Be,end:oe*this.frameSamples/16}}}}c.NonRealTimeVAD=te})(Ur)),Ur}var wr={},Pp;function Ey(){if(Pp)return wr;Pp=1,Object.defineProperty(wr,"__esModule",{value:!0}),wr.audioFileToArray=wr.encodeWAV=wr.arrayBufferToBase64=wr.minFramesForTargetMS=void 0;function c(R,_,U=16e3){return Math.ceil(R*U/1e3/_)}wr.minFramesForTargetMS=c;function r(R){const _=new Uint8Array(R),U=_.byteLength,B=new Array(U);for(let te=0;te<U;te++){const Q=_[te];if(Q===void 0)break;B[te]=String.fromCharCode(Q)}return btoa(B.join(""))}wr.arrayBufferToBase64=r;function n(R,_=3,U=16e3,B=1,te=32){const Q=te/8,ee=B*Q,ie=new ArrayBuffer(44+R.length*Q),ce=new DataView(ie);return v(ce,0,"RIFF"),ce.setUint32(4,36+R.length*Q,!0),v(ce,8,"WAVE"),v(ce,12,"fmt "),ce.setUint32(16,16,!0),ce.setUint16(20,_,!0),ce.setUint16(22,B,!0),ce.setUint32(24,U,!0),ce.setUint32(28,U*ee,!0),ce.setUint16(32,ee,!0),ce.setUint16(34,te,!0),v(ce,36,"data"),ce.setUint32(40,R.length*Q,!0),_===1?f(ce,44,R):a(ce,44,R),ie}wr.encodeWAV=n;function a(R,_,U){for(let B=0;B<U.length;B++,_+=4)R.setFloat32(_,U[B],!0)}function f(R,_,U){for(let B=0;B<U.length;B++,_+=2){const te=Math.max(-1,Math.min(1,U[B]));R.setInt16(_,te<0?te*32768:te*32767,!0)}}function v(R,_,U){for(let B=0;B<U.length;B++)R.setUint8(_+B,U.charCodeAt(B))}async function C(R){const _=new OfflineAudioContext(1,1,44100),U=new FileReader;let B=null;if(await new Promise(ee=>{U.addEventListener("loadend",()=>{const ie=U.result;_.decodeAudioData(ie,ce=>{B=ce,_.startRendering().then(()=>{console.log("Rendering completed successfully"),ee()}).catch(ue=>{console.error("Rendering failed: ",ue)})},ce=>{console.log("Error with decoding audio data: ",ce)})}),U.readAsArrayBuffer(R)}),B===null)throw Error("some shit");const te=B,Q=new Float32Array(te.length);for(let ee=0;ee<te.length;ee++)for(let ie=0;ie<te.numberOfChannels;ie++){const ce=te.getChannelData(ie)[ee],ue=Q[ee];if(ce===void 0||ue===void 0)throw new Error("sample or out[i] is undefined");Q[ee]=ue+ce}return{audio:Q,sampleRate:te.sampleRate}}return wr.audioFileToArray=C,wr}var Fr={},ao={exports:{}};/*!
|
|
2855
2855
|
* ONNX Runtime Web v1.24.3
|
|
2856
2856
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2857
2857
|
* Licensed under the MIT License.
|
|
2858
|
-
*/var Op;function Cy(){return Op||(Op=1,(function(c,r){var n=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(y=>typeof ar<"u"?ar:typeof Proxy<"u"?new Proxy(y,{get:($,A)=>(typeof ar<"u"?ar:$)[A]}):y)(function(y){if(typeof ar<"u")return ar.apply(this,arguments);throw Error('Dynamic require of "'+y+'" is not supported')}),b=(y,$)=>()=>(y&&($=y(y=0)),$),F=(y,$)=>{for(var A in $)a(y,A,{get:$[A],enumerable:!0})},B=(y,$,A,z)=>{if($&&typeof $=="object"||typeof $=="function")for(let P of v($))!C.call(y,P)&&P!==A&&a(y,P,{get:()=>$[P],enumerable:!(z=f($,P))||z.enumerable});return y},re=y=>B(a({},"__esModule",{value:!0}),y),X,ee,ae,ce,de,Le=b(()=>{X=new Map,ee=[],ae=(y,$,A)=>{if($&&typeof $.init=="function"&&typeof $.createInferenceSessionHandler=="function"){let z=X.get(y);if(z===void 0)X.set(y,{backend:$,priority:A});else{if(z.priority>A)return;if(z.priority===A&&z.backend!==$)throw new Error(`cannot register backend "${y}" using priority ${A}`)}if(A>=0){let P=ee.indexOf(y);P!==-1&&ee.splice(P,1);for(let G=0;G<ee.length;G++)if(X.get(ee[G]).priority<=A){ee.splice(G,0,y);return}ee.push(y)}return}throw new TypeError("not a valid backend")},ce=async y=>{let $=X.get(y);if(!$)return"backend not found.";if($.initialized)return $.backend;if($.aborted)return $.error;{let A=!!$.initPromise;try{return A||($.initPromise=$.backend.init(y)),await $.initPromise,$.initialized=!0,$.backend}catch(z){return A||($.error=`${z}`,$.aborted=!0),$.error}finally{delete $.initPromise}}},de=async y=>{let $=y.executionProviders||[],A=$.map(V=>typeof V=="string"?V:V.name),z=A.length===0?ee:A,P,G=[],N=new Set;for(let V of z){let Z=await ce(V);typeof Z=="string"?G.push({name:V,err:Z}):(P||(P=Z),P===Z&&N.add(V))}if(!P)throw new Error(`no available backend found. ERR: ${G.map(V=>`[${V.name}] ${V.err}`).join(", ")}`);for(let{name:V,err:Z}of G)A.includes(V)&&console.warn(`removing requested execution provider "${V}" from session options because it is not available: ${Z}`);let L=$.filter(V=>N.has(typeof V=="string"?V:V.name));return[P,new Proxy(y,{get:(V,Z)=>Z==="executionProviders"?L:Reflect.get(V,Z)})]}}),Te=b(()=>{Le()}),le,se=b(()=>{le="1.24.3"}),fe,he,Be=b(()=>{se(),fe="warning",he={wasm:{},webgl:{},webgpu:{},versions:{common:le},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}`);fe=y}},get logLevel(){return fe}},Object.defineProperty(he,"logLevel",{enumerable:!0})}),me,nt=b(()=>{Be(),me=he}),Ye,mt,Ge=b(()=>{Ye=(y,$)=>{let A=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);A.width=y.dims[3],A.height=y.dims[2];let z=A.getContext("2d");if(z!=null){let P,G;$?.tensorLayout!==void 0&&$.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[3]):(P=y.dims[3],G=y.dims[2]);let N=$?.format!==void 0?$.format:"RGB",L=$?.norm,V,Z;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?Z=[0,0,0,0]:typeof L.bias=="number"?Z=[L.bias,L.bias,L.bias,L.bias]:(Z=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(Z[3]=L.bias[3]));let ie=G*P,J=0,j=ie,xe=ie*2,U=-1;N==="RGBA"?(J=0,j=ie,xe=ie*2,U=ie*3):N==="RGB"?(J=0,j=ie,xe=ie*2):N==="RBG"&&(J=0,xe=ie,j=ie*2);for(let ue=0;ue<G;ue++)for(let wt=0;wt<P;wt++){let qe=(y.data[J++]-Z[0])*V[0],Ee=(y.data[j++]-Z[1])*V[1],We=(y.data[xe++]-Z[2])*V[2],_e=U===-1?255:(y.data[U++]-Z[3])*V[3];z.fillStyle="rgba("+qe+","+Ee+","+We+","+_e+")",z.fillRect(wt,ue,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")},mt=(y,$)=>{let A=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),z;if(A!=null){let P,G,N;$?.tensorLayout!==void 0&&$.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[1],N=y.dims[3]):(P=y.dims[3],G=y.dims[2],N=y.dims[1]);let L=$!==void 0&&$.format!==void 0?$.format:"RGB",V=$?.norm,Z,ie;V===void 0||V.mean===void 0?Z=[255,255,255,255]:typeof V.mean=="number"?Z=[V.mean,V.mean,V.mean,V.mean]:(Z=[V.mean[0],V.mean[1],V.mean[2],255],V.mean[3]!==void 0&&(Z[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 J=G*P;if($!==void 0&&($.format!==void 0&&N===4&&$.format!=="RGBA"||N===3&&$.format!=="RGB"&&$.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let j=4,xe=0,U=1,ue=2,wt=3,qe=0,Ee=J,We=J*2,_e=-1;L==="RGBA"?(qe=0,Ee=J,We=J*2,_e=J*3):L==="RGB"?(qe=0,Ee=J,We=J*2):L==="RBG"&&(qe=0,We=J,Ee=J*2),z=A.createImageData(P,G);for(let zt=0;zt<G*P;xe+=j,U+=j,ue+=j,wt+=j,zt++)z.data[xe]=(y.data[qe++]-ie[0])*Z[0],z.data[U]=(y.data[Ee++]-ie[1])*Z[1],z.data[ue]=(y.data[We++]-ie[2])*Z[2],z.data[wt]=_e===-1?255:(y.data[_e++]-ie[3])*Z[3]}else throw new Error("Can not access image data");return z}}),Je,st,bt,ut,Ze,De,Ke=b(()=>{Ne(),Je=(y,$)=>{if(y===void 0)throw new Error("Image buffer must be defined");if($.height===void 0||$.width===void 0)throw new Error("Image height and width must be defined");if($.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:A,width:z}=$,P=$.norm??{mean:255,bias:0},G,N;typeof P.mean=="number"?G=[P.mean,P.mean,P.mean,P.mean]:G=[P.mean[0],P.mean[1],P.mean[2],P.mean[3]??255],typeof P.bias=="number"?N=[P.bias,P.bias,P.bias,P.bias]:N=[P.bias[0],P.bias[1],P.bias[2],P.bias[3]??0];let L=$.format!==void 0?$.format:"RGBA",V=$.tensorFormat!==void 0&&$.tensorFormat!==void 0?$.tensorFormat:"RGB",Z=A*z,ie=V==="RGBA"?new Float32Array(Z*4):new Float32Array(Z*3),J=4,j=0,xe=1,U=2,ue=3,wt=0,qe=Z,Ee=Z*2,We=-1;L==="RGB"&&(J=3,j=0,xe=1,U=2,ue=-1),V==="RGBA"?We=Z*3:V==="RBG"?(wt=0,Ee=Z,qe=Z*2):V==="BGR"&&(Ee=0,qe=Z,wt=Z*2);for(let _e=0;_e<Z;_e++,j+=J,U+=J,xe+=J,ue+=J)ie[wt++]=(y[j]+N[0])/G[0],ie[qe++]=(y[xe]+N[1])/G[1],ie[Ee++]=(y[U]+N[2])/G[2],We!==-1&&ue!==-1&&(ie[We++]=(y[ue]+N[3])/G[3]);return V==="RGBA"?new te("float32",ie,[1,4,A,z]):new te("float32",ie,[1,3,A,z])},st=async(y,$)=>{let A=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,z=typeof ImageData<"u"&&y instanceof ImageData,P=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,G=typeof y=="string",N,L=$??{},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")},Z=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 J=Z(ie);if(J!=null){let j=y.height,xe=y.width;if($!==void 0&&$.resizedHeight!==void 0&&$.resizedWidth!==void 0&&(j=$.resizedHeight,xe=$.resizedWidth),$!==void 0){if(L=$,$.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");L.tensorFormat="RGBA",L.height=j,L.width=xe}else L.tensorFormat="RGBA",L.height=j,L.width=xe;J.drawImage(y,0,0),N=J.getImageData(0,0,xe,j).data}else throw new Error("Can not access image data")}else if(z){let ie,J;if($!==void 0&&$.resizedWidth!==void 0&&$.resizedHeight!==void 0?(ie=$.resizedHeight,J=$.resizedWidth):(ie=y.height,J=y.width),$!==void 0&&(L=$),L.format="RGBA",L.height=ie,L.width=J,$!==void 0){let j=V();j.width=J,j.height=ie;let xe=Z(j);if(xe!=null)xe.putImageData(y,0,0),N=xe.getImageData(0,0,J,ie).data;else throw new Error("Can not access image data")}else N=y.data}else if(P){if($===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 J=Z(ie);if(J!=null){let j=y.height,xe=y.width;return J.drawImage(y,0,0,xe,j),N=J.getImageData(0,0,xe,j).data,L.height=j,L.width=xe,Je(N,L)}else throw new Error("Can not access image data")}else{if(G)return new Promise((ie,J)=>{let j=V(),xe=Z(j);if(!y||!xe)return J();let U=new Image;U.crossOrigin="Anonymous",U.src=y,U.onload=()=>{j.width=U.width,j.height=U.height,xe.drawImage(U,0,0,j.width,j.height);let ue=xe.getImageData(0,0,j.width,j.height);L.height=j.height,L.width=j.width,ie(Je(ue.data,L))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(N!==void 0)return Je(N,L);throw new Error("Input data provided is not supported - aborted tensor creation")},bt=(y,$)=>{let{width:A,height:z,download:P,dispose:G}=$,N=[1,z,A,4];return new te({location:"texture",type:"float32",texture:y,dims:N,download:P,dispose:G})},ut=(y,$)=>{let{dataType:A,dims:z,download:P,dispose:G}=$;return new te({location:"gpu-buffer",type:A??"float32",gpuBuffer:y,dims:z,download:P,dispose:G})},Ze=(y,$)=>{let{dataType:A,dims:z,download:P,dispose:G}=$;return new te({location:"ml-tensor",type:A??"float32",mlTensor:y,dims:z,download:P,dispose:G})},De=(y,$,A)=>new te({location:"cpu-pinned",type:y,data:$,dims:A??[$.length]})}),tt,Y,Me,rt,gt=b(()=>{tt=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Y=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Me=!1,rt=()=>{if(!Me){Me=!0;let y=typeof BigInt64Array<"u"&&BigInt64Array.from,$=typeof BigUint64Array<"u"&&BigUint64Array.from,A=globalThis.Float16Array,z=typeof A<"u"&&A.from;y&&(tt.set("int64",BigInt64Array),Y.set(BigInt64Array,"int64")),$&&(tt.set("uint64",BigUint64Array),Y.set(BigUint64Array,"uint64")),z?(tt.set("float16",A),Y.set(A,"float16")):tt.set("float16",Uint16Array)}}}),Vt,$t,ct=b(()=>{Ne(),Vt=y=>{let $=1;for(let A=0;A<y.length;A++){let z=y[A];if(typeof z!="number"||!Number.isSafeInteger(z))throw new TypeError(`dims[${A}] must be an integer, got: ${z}`);if(z<0)throw new RangeError(`dims[${A}] must be a non-negative integer, got: ${z}`);$*=z}return $},$t=(y,$)=>{switch(y.location){case"cpu":return new te(y.type,y.data,$);case"cpu-pinned":return new te({location:"cpu-pinned",data:y.data,type:y.type,dims:$});case"texture":return new te({location:"texture",texture:y.texture,type:y.type,dims:$});case"gpu-buffer":return new te({location:"gpu-buffer",gpuBuffer:y.gpuBuffer,type:y.type,dims:$});case"ml-tensor":return new te({location:"ml-tensor",mlTensor:y.mlTensor,type:y.type,dims:$});default:throw new Error(`tensorReshape: tensor location ${y.location} is not supported`)}}}),te,Ne=b(()=>{Ge(),Ke(),gt(),ct(),te=class{constructor(y,$,A){rt();let z,P;if(typeof y=="object"&&"location"in y)switch(this.dataLocation=y.location,z=y.type,P=y.dims,y.location){case"cpu-pinned":{let N=tt.get(z);if(!N)throw new TypeError(`unsupported type "${z}" to create tensor from pinned buffer`);if(!(y.data instanceof N))throw new TypeError(`buffer should be of type ${N.name}`);this.cpuData=y.data;break}case"texture":{if(z!=="float32")throw new TypeError(`unsupported type "${z}" to create tensor from texture`);this.gpuTextureData=y.texture,this.downloader=y.download,this.disposer=y.dispose;break}case"gpu-buffer":{if(z!=="float32"&&z!=="float16"&&z!=="int32"&&z!=="int64"&&z!=="uint32"&&z!=="uint8"&&z!=="bool"&&z!=="uint4"&&z!=="int4")throw new TypeError(`unsupported type "${z}" to create tensor from gpu buffer`);this.gpuBufferData=y.gpuBuffer,this.downloader=y.download,this.disposer=y.dispose;break}case"ml-tensor":{if(z!=="float32"&&z!=="float16"&&z!=="int32"&&z!=="int64"&&z!=="uint32"&&z!=="uint64"&&z!=="int8"&&z!=="uint8"&&z!=="bool"&&z!=="uint4"&&z!=="int4")throw new TypeError(`unsupported type "${z}" to create tensor from MLTensor`);this.mlTensorData=y.mlTensor,this.downloader=y.download,this.disposer=y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let N,L;if(typeof y=="string")if(z=y,L=A,y==="string"){if(!Array.isArray($))throw new TypeError("A string tensor's data must be a string array.");N=$}else{let V=tt.get(y);if(V===void 0)throw new TypeError(`Unsupported tensor type: ${y}.`);if(Array.isArray($)){if(y==="float16"&&V===Uint16Array||y==="uint4"||y==="int4")throw new TypeError(`Creating a ${y} tensor from number array is not supported. Please use ${V.name} as data.`);y==="uint64"||y==="int64"?N=V.from($,BigInt):N=V.from($)}else if($ instanceof V)N=$;else if($ instanceof Uint8ClampedArray)if(y==="uint8")N=Uint8Array.from($);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(y==="float16"&&$ instanceof Uint16Array&&V!==Uint16Array)N=new globalThis.Float16Array($.buffer,$.byteOffset,$.length);else throw new TypeError(`A ${z} tensor's data must be type of ${V}`)}else if(L=$,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")z="string",N=y;else if(V==="boolean")z="bool",N=Uint8Array.from(y);else throw new TypeError(`Invalid element type of data array: ${V}.`)}else if(y instanceof Uint8ClampedArray)z="uint8",N=Uint8Array.from(y);else{let V=Y.get(y.constructor);if(V===void 0)throw new TypeError(`Unsupported type for tensor data: ${y.constructor}.`);z=V,N=y}if(L===void 0)L=[N.length];else if(!Array.isArray(L))throw new TypeError("A tensor's dims must be a number array");P=L,this.cpuData=N,this.dataLocation="cpu"}let G=Vt(P);if(this.cpuData&&G!==this.cpuData.length&&!((z==="uint4"||z==="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=z,this.dims=P,this.size=G}static async fromImage(y,$){return st(y,$)}static fromTexture(y,$){return bt(y,$)}static fromGpuBuffer(y,$){return ut(y,$)}static fromMLTensor(y,$){return Ze(y,$)}static fromPinnedBuffer(y,$,A){return De(y,$,A)}toDataURL(y){return Ye(this,y)}toImageData(y){return mt(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 $=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=$,y&&this.disposer&&(this.disposer(),this.disposer=void 0),$}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)}}}),He,Lt=b(()=>{Ne(),He=te}),xt,be,Ue,it,ht,Mt,Mr=b(()=>{Be(),xt=(y,$)=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeStamp(`${y}::ORT::${$}`)},be=(y,$)=>{let A=new Error().stack?.split(/\r\n|\r|\n/g)||[],z=!1;for(let P=0;P<A.length;P++){if(z&&!A[P].includes("TRACE_FUNC")){let G=`FUNC_${y}::${A[P].trim().split(" ")[1]}`;$&&(G+=`::${$}`),xt("CPU",G);return}A[P].includes("TRACE_FUNC")&&(z=!0)}},Ue=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||be("BEGIN",y)},it=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||be("END",y)},ht=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.time(`ORT::${y}`)},Mt=y=>{(typeof he.trace>"u"?!he.wasm.trace:!he.trace)||console.timeEnd(`ORT::${y}`)}}),ns,Fi=b(()=>{Le(),Lt(),Mr(),ns=class ff{constructor($){this.handler=$}async run($,A,z){Ue(),ht("InferenceSession.run");let P={},G={};if(typeof $!="object"||$===null||$ instanceof He||Array.isArray($))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let N=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof He)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");N=!1;for(let Z of A){if(typeof Z!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(Z)===-1)throw new RangeError(`'fetches' contains invalid output name: ${Z}.`);P[Z]=null}if(typeof z=="object"&&z!==null)G=z;else if(typeof z<"u")throw new TypeError("'options' must be an object.")}else{let Z=!1,ie=Object.getOwnPropertyNames(A);for(let J of this.outputNames)if(ie.indexOf(J)!==-1){let j=A[J];(j===null||j instanceof He)&&(Z=!0,N=!1,P[J]=j)}if(Z){if(typeof z=="object"&&z!==null)G=z;else if(typeof z<"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 Z of this.inputNames)if(typeof $[Z]>"u")throw new Error(`input '${Z}' is missing in 'feeds'.`);if(N)for(let Z of this.outputNames)P[Z]=null;let L=await this.handler.run($,P,G),V={};for(let Z in L)if(Object.hasOwnProperty.call(L,Z)){let ie=L[Z];ie instanceof He?V[Z]=ie:V[Z]=new He(ie.type,ie.data,ie.dims)}return Mt("InferenceSession.run"),it(),V}async release(){return this.handler.dispose()}static async create($,A,z,P){Ue(),ht("InferenceSession.create");let G,N={};if(typeof $=="string"){if(G=$,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if($ instanceof Uint8Array){if(G=$,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if($ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer){let ie=$,J=0,j=$.byteLength;if(typeof A=="object"&&A!==null)N=A;else if(typeof A=="number"){if(J=A,!Number.isSafeInteger(J))throw new RangeError("'byteOffset' must be an integer.");if(J<0||J>=ie.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${ie.byteLength}).`);if(j=$.byteLength-J,typeof z=="number"){if(j=z,!Number.isSafeInteger(j))throw new RangeError("'byteLength' must be an integer.");if(j<=0||J+j>ie.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${ie.byteLength-J}].`);if(typeof P=="object"&&P!==null)N=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(typeof z<"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,J,j)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[L,V]=await de(N),Z=await L.createInferenceSessionHandler(G,V);return Mt("InferenceSession.create"),it(),new ff(Z)}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}}}),tn,Vi=b(()=>{Fi(),tn=ns}),Gi=b(()=>{}),qi=b(()=>{}),Wi=b(()=>{}),Hi=b(()=>{}),ss={};F(ss,{InferenceSession:()=>tn,TRACE:()=>xt,TRACE_EVENT_BEGIN:()=>ht,TRACE_EVENT_END:()=>Mt,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>it,Tensor:()=>He,env:()=>me,registerBackend:()=>ae});var It=b(()=>{Te(),nt(),Vi(),Lt(),Gi(),qi(),Mr(),Wi(),Hi()}),rn=b(()=>{}),is={};F(is,{default:()=>as});var nn,sn,as,ji=b(()=>{xs(),Qt(),dn(),nn="ort-wasm-proxy-worker",sn=globalThis.self?.name===nn,sn&&(self.onmessage=y=>{let{type:$,in:A}=y.data;try{switch($){case"init-wasm":pn(A.wasm).then(()=>{Dn(A).then(()=>{postMessage({type:$})},z=>{postMessage({type:$,err:z})})},z=>{postMessage({type:$,err:z})});break;case"init-ep":{let{epName:z,env:P}=A;Ln(P,z).then(()=>{postMessage({type:$})},G=>{postMessage({type:$,err:G})});break}case"copy-from":{let{buffer:z}=A,P=et(z);postMessage({type:$,out:P});break}case"create":{let{model:z,options:P}=A;Zt(z,P).then(G=>{postMessage({type:$,out:G})},G=>{postMessage({type:$,err:G})});break}case"release":Un(A),postMessage({type:$});break;case"run":{let{sessionId:z,inputIndices:P,inputs:G,outputIndices:N,options:L}=A;H(z,P,G,N,new Array(N.length).fill(null),L).then(V=>{V.some(Z=>Z[3]!=="cpu")?postMessage({type:$,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:$,out:V},Fn([...G,...V]))},V=>{postMessage({type:$,err:V})});break}case"end-profiling":Wr(A),postMessage({type:$});break;default:}}catch(z){postMessage({type:$,err:z})}}),as=sn?null:y=>new Worker(y??yt,{type:"classic",name:nn})}),os,ls,yt,an,Ir,us,ds,on,cs,ln,hs,un,ps,dn=b(()=>{rn(),os=typeof location>"u"?void 0:location.origin,ls=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,yt=ls(),an=()=>{if(yt&&!yt.startsWith("blob:"))return yt.substring(0,yt.lastIndexOf("/")+1)},Ir=(y,$)=>{try{let A=$??yt;return(A?new URL(y,A):new URL(y)).origin===os}catch{return!1}},us=(y,$)=>{let A=$??yt;try{return(A?new URL(y,A):new URL(y)).href}catch{return}},ds=(y,$)=>`${$??"./"}${y}`,on=async y=>{let $=await(await fetch(y,{credentials:"same-origin"})).blob();return URL.createObjectURL($)},cs=async y=>(await import(y)).default,ln=(ji(),re(is)).default,hs=async()=>{if(!yt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ir(yt))return[void 0,ln()];let y=await on(yt);return[y,ln(y)]},un=void 0,ps=async(y,$,A,z)=>{let P=un&&!(y||$);if(P)if(yt)P=Ir(yt)||z&&!A;else if(z&&!A)P=!0;else throw new Error("cannot determine the script source URL.");if(P)return[void 0,un];{let G="ort-wasm-simd-threaded.mjs",N=y??us(G,$),L=A&&N&&!Ir(N,$),V=L?await on(N):N??ds(G,$);return[L?V:void 0,await cs(V)]}}}),cn,Pr,or,hn,fs,ms,gs,pn,Oe,Qt=b(()=>{dn(),Pr=!1,or=!1,hn=!1,fs=()=>{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}},ms=()=>{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}},gs=()=>{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}},pn=async y=>{if(Pr)return Promise.resolve();if(or)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(hn)throw new Error("previous call to 'initializeWebAssembly()' failed.");or=!0;let $=y.initTimeout,A=y.numThreads;if(y.simd!==!1){if(y.simd==="relaxed"){if(!gs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ms())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let z=fs();A>1&&!z&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+A+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),y.numThreads=A=1);let P=y.wasmPaths,G=typeof P=="string"?P:void 0,N=P?.mjs,L=N?.href??N,V=P?.wasm,Z=V?.href??V,ie=y.wasmBinary,[J,j]=await ps(L,G,A>1,!!ie||!!Z),xe=!1,U=[];if($>0&&U.push(new Promise(ue=>{setTimeout(()=>{xe=!0,ue()},$)})),U.push(new Promise((ue,wt)=>{let qe={numThreads:A};if(ie)qe.wasmBinary=ie,qe.locateFile=Ee=>Ee;else if(Z||G)qe.locateFile=Ee=>Z??G+Ee;else if(L&&L.indexOf("blob:")!==0)qe.locateFile=Ee=>new URL(Ee,L).href;else if(J){let Ee=an();Ee&&(qe.locateFile=We=>Ee+We)}j(qe).then(Ee=>{or=!1,Pr=!0,cn=Ee,ue(),J&&URL.revokeObjectURL(J)},Ee=>{or=!1,hn=!0,wt(Ee)})})),await Promise.race(U),xe)throw new Error(`WebAssembly backend initializing failed due to timeout: ${$}ms`)},Oe=()=>{if(Pr&&cn)return cn;throw new Error("WebAssembly is not initialized yet.")}}),Tt,Or,Re,fn=b(()=>{Qt(),Tt=(y,$)=>{let A=Oe(),z=A.lengthBytesUTF8(y)+1,P=A._malloc(z);return A.stringToUTF8(y,P,z),$.push(P),P},Or=(y,$,A,z)=>{if(typeof y=="object"&&y!==null){if(A.has(y))throw new Error("Circular reference in options");A.add(y)}Object.entries(y).forEach(([P,G])=>{let N=$?$+P:P;if(typeof G=="object")Or(G,N+".",A,z);else if(typeof G=="string"||typeof G=="number")z(N,G.toString());else if(typeof G=="boolean")z(N,G?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof G}`)})},Re=y=>{let $=Oe(),A=$.stackSave();try{let z=$.PTR_SIZE,P=$.stackAlloc(2*z);$._OrtGetLastError(P,P+z);let G=Number($.getValue(P,z===4?"i32":"i64")),N=$.getValue(P+z,"*"),L=N?$.UTF8ToString(N):"";throw new Error(`${y} ERROR_CODE: ${G}, ERROR_MESSAGE: ${L}`)}finally{$.stackRestore(A)}}}),ys,Ki=b(()=>{Qt(),fn(),ys=y=>{let $=Oe(),A=0,z=[],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=Tt(y.tag,z)),A=$._OrtCreateRunOptions(P.logSeverityLevel,P.logVerbosityLevel,!!P.terminate,G),A===0&&Re("Can't create run options."),y?.extra!==void 0&&Or(y.extra,"",new WeakSet,(N,L)=>{let V=Tt(N,z),Z=Tt(L,z);$._OrtAddRunConfigEntry(A,V,Z)!==0&&Re(`Can't set a run config entry: ${N} - ${L}.`)}),[A,z]}catch(G){throw A!==0&&$._OrtReleaseRunOptions(A),z.forEach(N=>$._free(N)),G}}}),ws,vs,bs,lr,_s,Ss,Qi=b(()=>{Qt(),fn(),ws=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}`)}},vs=y=>{switch(y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${y}`)}},bs=y=>{y.extra||(y.extra={}),y.extra.session||(y.extra.session={});let $=y.extra.session;$.use_ort_model_bytes_directly||($.use_ort_model_bytes_directly="1"),y.executionProviders&&y.executionProviders.some(A=>(typeof A=="string"?A:A.name)==="webgpu")&&(y.enableMemPattern=!1)},lr=(y,$,A,z)=>{let P=Tt($,z),G=Tt(A,z);Oe()._OrtAddSessionConfigEntry(y,P,G)!==0&&Re(`Can't set a session config entry: ${$} - ${A}.`)},_s=async(y,$,A)=>{let z=$.executionProviders;for(let P of z){let G=typeof P=="string"?P:P.name,N=[];switch(G){case"webnn":if(G="WEBNN",typeof P!="string"){let J=P?.deviceType;J&&lr(y,"deviceType",J,A)}break;case"webgpu":if(G="JS",typeof P!="string"){let J=P;if(J?.preferredLayout){if(J.preferredLayout!=="NCHW"&&J.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${J.preferredLayout}`);lr(y,"preferredLayout",J.preferredLayout,A)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${G}`)}let L=Tt(G,A),V=N.length,Z=0,ie=0;if(V>0){Z=Oe()._malloc(V*Oe().PTR_SIZE),A.push(Z),ie=Oe()._malloc(V*Oe().PTR_SIZE),A.push(ie);for(let J=0;J<V;J++)Oe().setValue(Z+J*Oe().PTR_SIZE,N[J][0],"*"),Oe().setValue(ie+J*Oe().PTR_SIZE,N[J][1],"*")}await Oe()._OrtAppendExecutionProvider(y,L,Z,ie,V)!==0&&Re(`Can't append execution provider: ${G}.`)}},Ss=async y=>{let $=Oe(),A=0,z=[],P=y||{};bs(P);try{let G=ws(P.graphOptimizationLevel??"all"),N=vs(P.executionMode??"sequential"),L=typeof P.logId=="string"?Tt(P.logId,z):0,V=P.logSeverityLevel??2;if(!Number.isInteger(V)||V<0||V>4)throw new Error(`log severity level is not valid: ${V}`);let Z=P.logVerbosityLevel??0;if(!Number.isInteger(Z)||Z<0||Z>4)throw new Error(`log verbosity level is not valid: ${Z}`);let ie=typeof P.optimizedModelFilePath=="string"?Tt(P.optimizedModelFilePath,z):0;if(A=$._OrtCreateSessionOptions(G,!!P.enableCpuMemArena,!!P.enableMemPattern,N,!!P.enableProfiling,0,L,V,Z,ie),A===0&&Re("Can't create session options."),P.executionProviders&&await _s(A,P,z),P.enableGraphCapture!==void 0){if(typeof P.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${P.enableGraphCapture}`);lr(A,"enableGraphCapture",P.enableGraphCapture.toString(),z)}if(P.freeDimensionOverrides)for(let[J,j]of Object.entries(P.freeDimensionOverrides)){if(typeof J!="string")throw new Error(`free dimension override name must be a string: ${J}`);if(typeof j!="number"||!Number.isInteger(j)||j<0)throw new Error(`free dimension override value must be a non-negative integer: ${j}`);let xe=Tt(J,z);$._OrtAddFreeDimensionOverride(A,xe,j)!==0&&Re(`Can't set a free dimension override: ${J} - ${j}.`)}return P.extra!==void 0&&Or(P.extra,"",new WeakSet,(J,j)=>{lr(A,J,j,z)}),[A,z]}catch(G){throw A!==0&&$._OrtReleaseSessionOptions(A)!==0&&Re("Can't release session options."),z.forEach(N=>$._free(N)),G}}}),Xt,Yt,Jt,mn,gn,yn,wn,zn,Ie=b(()=>{Xt=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}`)}},Yt=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}`)}},Jt=(y,$)=>{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],z=typeof $=="number"?$:$.reduce((P,G)=>P*G,1);return A>0?Math.ceil(z*A):void 0},mn=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}`)}},gn=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}`)}},yn=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",wn=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint64"||y==="int8"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",zn=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}`)}}}),vn,Ts=b(()=>{rn(),vn=async y=>{if(typeof y=="string"){let $=await fetch(y);if(!$.ok)throw new Error(`failed to load external data file: ${y}`);let A=$.headers.get("Content-Length"),z=A?parseInt(A,10):0;if(z<1073741824)return new Uint8Array(await $.arrayBuffer());{if(!$.body)throw new Error(`failed to load external data file: ${y}, no response body.`);let P=$.body.getReader(),G;try{G=new ArrayBuffer(z)}catch(L){if(L instanceof RangeError){let V=Math.ceil(z/65536);G=new WebAssembly.Memory({initial:V,maximum:V}).buffer}else throw L}let N=0;for(;;){let{done:L,value:V}=await P.read();if(L)break;let Z=V.byteLength;new Uint8Array(G,N,Z).set(V),N+=Z}return new Uint8Array(G,0,z)}}else return y instanceof Blob?new Uint8Array(await y.arrayBuffer()):y instanceof Uint8Array?y:new Uint8Array(y)}}),$s,Dn,Ln,_r,Bn,Nn,et,Zt,Un,Sr,H,Wr,Fn,xs=b(()=>{It(),Ki(),Qi(),Ie(),Qt(),fn(),Ts(),$s=(y,$)=>{Oe()._OrtInit(y,$)!==0&&Re("Can't initialize onnxruntime.")},Dn=async y=>{$s(y.wasm.numThreads,gn(y.logLevel))},Ln=async(y,$)=>{Oe().asyncInit?.();let A=y.webgpu.adapter;if($==="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 z=y.webgpu.powerPreference;if(z!==void 0&&z!=="low-power"&&z!=="high-performance")throw new Error(`Invalid powerPreference setting: "${z}"`);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:z,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($==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},_r=new Map,Bn=y=>{let $=Oe(),A=$.stackSave();try{let z=$.PTR_SIZE,P=$.stackAlloc(2*z);$._OrtGetInputOutputCount(y,P,P+z)!==0&&Re("Can't get session input/output count.");let G=z===4?"i32":"i64";return[Number($.getValue(P,G)),Number($.getValue(P+z,G))]}finally{$.stackRestore(A)}},Nn=(y,$)=>{let A=Oe(),z=A.stackSave(),P=0;try{let G=A.PTR_SIZE,N=A.stackAlloc(2*G);A._OrtGetInputOutputMetadata(y,$,N,N+G)!==0&&Re("Can't get session input/output metadata.");let L=Number(A.getValue(N,"*"));P=Number(A.getValue(N+G,"*"));let V=A.HEAP32[P/4];if(V===0)return[L,0];let Z=A.HEAPU32[P/4+1],ie=[];for(let J=0;J<Z;J++){let j=Number(A.getValue(P+8+J*G,"*"));ie.push(j!==0?A.UTF8ToString(j):Number(A.getValue(P+8+(J+Z)*G,"*")))}return[L,V,ie]}finally{A.stackRestore(z),P!==0&&A._OrtFree(P)}},et=y=>{let $=Oe(),A=$._malloc(y.byteLength);if(A===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${y.byteLength}.`);return $.HEAPU8.set(y,A),[A,y.byteLength]},Zt=async(y,$)=>{let A,z,P=Oe();Array.isArray(y)?[A,z]=y:y.buffer===P.HEAPU8.buffer?[A,z]=[y.byteOffset,y.byteLength]:[A,z]=et(y);let G=0,N=0,L=[],V=[],Z=[];try{if([N,L]=await Ss($),$?.externalData&&P.mountExternalData){let Ee=[];for(let We of $.externalData){let _e=typeof We=="string"?We:We.path;Ee.push(vn(typeof We=="string"?We:We.data).then(zt=>{P.mountExternalData(_e,zt)}))}await Promise.all(Ee)}for(let Ee of $?.executionProviders??[])if((typeof Ee=="string"?Ee:Ee.name)==="webnn"){if(P.shouldTransferToMLTensor=!1,typeof Ee!="string"){let We=Ee,_e=We?.context,zt=We?.gpuDevice,Bt=We?.deviceType,xr=We?.powerPreference;_e?P.currentContext=_e:zt?P.currentContext=await P.webnnCreateMLContext(zt):P.currentContext=await P.webnnCreateMLContext({deviceType:Bt,powerPreference:xr})}else P.currentContext=await P.webnnCreateMLContext();break}G=await P._OrtCreateSession(A,z,N),P.webgpuOnCreateSession?.(G),G===0&&Re("Can't create a session."),P.jsepOnCreateSession?.(),P.currentContext&&(P.webnnRegisterMLContext(G,P.currentContext),P.currentContext=void 0,P.shouldTransferToMLTensor=!0);let[ie,J]=Bn(G),j=!!$?.enableGraphCapture,xe=[],U=[],ue=[],wt=[],qe=[];for(let Ee=0;Ee<ie;Ee++){let[We,_e,zt]=Nn(G,Ee);We===0&&Re("Can't get an input name."),V.push(We);let Bt=P.UTF8ToString(We);xe.push(Bt),ue.push(_e===0?{name:Bt,isTensor:!1}:{name:Bt,isTensor:!0,type:Yt(_e),shape:zt})}for(let Ee=0;Ee<J;Ee++){let[We,_e,zt]=Nn(G,Ee+ie);We===0&&Re("Can't get an output name."),Z.push(We);let Bt=P.UTF8ToString(We);U.push(Bt),wt.push(_e===0?{name:Bt,isTensor:!1}:{name:Bt,isTensor:!0,type:Yt(_e),shape:zt})}return _r.set(G,[G,V,Z,null,j,!1]),[G,xe,U,ue,wt]}catch(ie){throw V.forEach(J=>P._OrtFree(J)),Z.forEach(J=>P._OrtFree(J)),G!==0&&P._OrtReleaseSession(G)!==0&&Re("Can't release session."),ie}finally{P._free(A),N!==0&&P._OrtReleaseSessionOptions(N)!==0&&Re("Can't release session options."),L.forEach(ie=>P._free(ie)),P.unmountExternalData?.()}},Un=y=>{let $=Oe(),A=_r.get(y);if(!A)throw new Error(`cannot release session. invalid session id: ${y}`);let[z,P,G,N,L]=A;N&&(L&&$._OrtClearBoundOutputs(N.handle)!==0&&Re("Can't clear bound outputs."),$._OrtReleaseBinding(N.handle)!==0&&Re("Can't release IO binding.")),$.jsepOnReleaseSession?.(y),$.webnnOnReleaseSession?.(y),$.webgpuOnReleaseSession?.(y),P.forEach(V=>$._OrtFree(V)),G.forEach(V=>$._OrtFree(V)),$._OrtReleaseSession(z)!==0&&Re("Can't release session."),_r.delete(y)},Sr=async(y,$,A,z,P,G,N=!1)=>{if(!y){$.push(0);return}let L=Oe(),V=L.PTR_SIZE,Z=y[0],ie=y[1],J=y[3],j=J,xe,U;if(Z==="string"&&(J==="gpu-buffer"||J==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(N&&J!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${G} when enableGraphCapture is true.`);if(J==="gpu-buffer"){let qe=y[2].gpuBuffer;U=Jt(Xt(Z),ie);{let Ee=L.jsepRegisterBuffer;if(!Ee)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');xe=Ee(z,G,qe,U)}}else if(J==="ml-tensor"){let qe=y[2].mlTensor;U=Jt(Xt(Z),ie);let Ee=L.webnnRegisterMLTensor;if(!Ee)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');xe=Ee(z,qe,Xt(Z),ie)}else{let qe=y[2];if(Array.isArray(qe)){U=V*qe.length,xe=L._malloc(U),A.push(xe);for(let Ee=0;Ee<qe.length;Ee++){if(typeof qe[Ee]!="string")throw new TypeError(`tensor data at index ${Ee} is not a string`);L.setValue(xe+Ee*V,Tt(qe[Ee],A),"*")}}else{let Ee=L.webnnIsGraphInput,We=L.webnnIsGraphOutput;if(Z!=="string"&&Ee&&We){let _e=L.UTF8ToString(P);if(Ee(z,_e)||We(z,_e)){let zt=Xt(Z);U=Jt(zt,ie),j="ml-tensor";let Bt=L.webnnCreateTemporaryTensor,xr=L.webnnUploadTensor;if(!Bt||!xr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Qr=await Bt(z,zt,ie);xr(Qr,new Uint8Array(qe.buffer,qe.byteOffset,qe.byteLength)),xe=Qr}else U=qe.byteLength,xe=L._malloc(U),A.push(xe),L.HEAPU8.set(new Uint8Array(qe.buffer,qe.byteOffset,U),xe)}else U=qe.byteLength,xe=L._malloc(U),A.push(xe),L.HEAPU8.set(new Uint8Array(qe.buffer,qe.byteOffset,U),xe)}}let ue=L.stackSave(),wt=L.stackAlloc(4*ie.length);try{ie.forEach((Ee,We)=>L.setValue(wt+We*V,Ee,V===4?"i32":"i64"));let qe=L._OrtCreateTensor(Xt(Z),xe,U,wt,ie.length,zn(j));qe===0&&Re(`Can't create tensor for input/output. session=${z}, index=${G}.`),$.push(qe)}finally{L.stackRestore(ue)}},H=async(y,$,A,z,P,G)=>{let N=Oe(),L=N.PTR_SIZE,V=_r.get(y);if(!V)throw new Error(`cannot run inference. invalid session id: ${y}`);let Z=V[0],ie=V[1],J=V[2],j=V[3],xe=V[4];V[5];let U=$.length,ue=z.length,wt=0,qe=[],Ee=[],We=[],_e=[],zt=[],Bt=N.stackSave(),xr=N.stackAlloc(U*L),Qr=N.stackAlloc(U*L),Yn=N.stackAlloc(ue*L),Ps=N.stackAlloc(ue*L);try{[wt,qe]=ys(G),ht("wasm prepareInputOutputTensor");for(let je=0;je<U;je++)await Sr(A[je],Ee,_e,y,ie[$[je]],$[je],xe);for(let je=0;je<ue;je++)await Sr(P[je],We,_e,y,J[z[je]],U+z[je],xe);Mt("wasm prepareInputOutputTensor");for(let je=0;je<U;je++)N.setValue(xr+je*L,Ee[je],"*"),N.setValue(Qr+je*L,ie[$[je]],"*");for(let je=0;je<ue;je++)N.setValue(Yn+je*L,We[je],"*"),N.setValue(Ps+je*L,J[z[je]],"*");N.jsepOnRunStart?.(Z),N.webnnOnRunStart?.(Z);let _t;_t=await N._OrtRun(Z,Qr,xr,U,Ps,ue,Yn,wt),_t!==0&&Re("failed to call OrtRun().");let tr=[],Os=[];ht("wasm ProcessOutputTensor");for(let je=0;je<ue;je++){let er=Number(N.getValue(Yn+je*L,"*"));if(er===We[je]||zt.includes(We[je])){tr.push(P[je]),er!==We[je]&&N._OrtReleaseTensor(er)!==0&&Re("Can't release tensor.");continue}let di=N.stackSave(),cr=N.stackAlloc(4*L),Tn=!1,Et,qt=0;try{N._OrtGetTensorData(er,cr,cr+L,cr+2*L,cr+3*L)!==0&&Re(`Can't access output tensor data on index ${je}.`);let Jn=L===4?"i32":"i64",$n=Number(N.getValue(cr,Jn));qt=N.getValue(cr+L,"*");let zs=N.getValue(cr+L*2,"*"),ci=Number(N.getValue(cr+L*3,Jn)),Pt=[];for(let Ct=0;Ct<ci;Ct++)Pt.push(Number(N.getValue(zs+Ct*L,Jn)));N._OrtFree(zs)!==0&&Re("Can't free memory for tensor dims.");let hr=Pt.reduce((Ct,St)=>Ct*St,1);Et=Yt($n);let Xr=j?.outputPreferredLocations[z[je]];if(Et==="string"){if(Xr==="gpu-buffer"||Xr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ct=[];for(let St=0;St<hr;St++){let rr=N.getValue(qt+St*L,"*"),hi=N.getValue(qt+(St+1)*L,"*"),pi=St===hr-1?void 0:hi-rr;Ct.push(N.UTF8ToString(rr,pi))}tr.push([Et,Pt,Ct,"cpu"])}else if(Xr==="gpu-buffer"&&hr>0){let Ct=N.jsepGetBuffer;if(!Ct)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let St=Ct(qt),rr=Jt($n,hr);if(rr===void 0||!yn(Et))throw new Error(`Unsupported data type: ${Et}`);Tn=!0,tr.push([Et,Pt,{gpuBuffer:St,download:N.jsepCreateDownloader(St,rr,Et),dispose:()=>{N._OrtReleaseTensor(er)!==0&&Re("Can't release tensor.")}},"gpu-buffer"])}else if(Xr==="ml-tensor"&&hr>0){let Ct=N.webnnEnsureTensor,St=N.webnnIsGraphInputOutputTypeSupported;if(!Ct||!St)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Jt($n,hr)===void 0||!wn(Et))throw new Error(`Unsupported data type: ${Et}`);if(!St(y,Et,!1))throw new Error(`preferredLocation "ml-tensor" for ${Et} output is not supported by current WebNN Context.`);let rr=await Ct(y,qt,$n,Pt,!1);Tn=!0,tr.push([Et,Pt,{mlTensor:rr,download:N.webnnCreateMLTensorDownloader(qt,Et),dispose:()=>{N.webnnReleaseTensorId(qt),N._OrtReleaseTensor(er)}},"ml-tensor"])}else if(Xr==="ml-tensor-cpu-output"&&hr>0){let Ct=N.webnnCreateMLTensorDownloader(qt,Et)(),St=tr.length;Tn=!0,Os.push((async()=>{let rr=[St,await Ct];return N.webnnReleaseTensorId(qt),N._OrtReleaseTensor(er),rr})()),tr.push([Et,Pt,[],"cpu"])}else{let Ct=mn(Et),St=new Ct(hr);new Uint8Array(St.buffer,St.byteOffset,St.byteLength).set(N.HEAPU8.subarray(qt,qt+St.byteLength)),tr.push([Et,Pt,St,"cpu"])}}finally{N.stackRestore(di),Et==="string"&&qt&&N._free(qt),Tn||N._OrtReleaseTensor(er)}}j&&!xe&&(N._OrtClearBoundOutputs(j.handle)!==0&&Re("Can't clear bound outputs."),_r.set(y,[Z,ie,J,j,xe,!1]));for(let[je,er]of await Promise.all(Os))tr[je][2]=er;return Mt("wasm ProcessOutputTensor"),tr}finally{N.webnnOnRunEnd?.(Z),N.stackRestore(Bt),Ee.forEach(_t=>N._OrtReleaseTensor(_t)),We.forEach(_t=>N._OrtReleaseTensor(_t)),_e.forEach(_t=>N._free(_t)),wt!==0&&N._OrtReleaseRunOptions(wt),qe.forEach(_t=>N._free(_t))}},Wr=y=>{let $=Oe(),A=_r.get(y);if(!A)throw new Error("invalid session id");let z=A[0],P=$._OrtEndProfiling(z);P===0&&Re("Can't get an profile file name."),$._OrtFree(P)},Fn=y=>{let $=[];for(let A of y){let z=A[2];!Array.isArray(z)&&"buffer"in z&&$.push(z.buffer)}return $}}),ur,Ae,Tr,Hr,zr,jr,bn,_n,dr,$r,Vn,Gn,qn,Es,Cs,li,Kr,ks,Rs=b(()=>{It(),xs(),Qt(),dn(),ur=()=>!!me.wasm.proxy&&typeof document<"u",Tr=!1,Hr=!1,zr=!1,_n=new Map,dr=(y,$)=>{let A=_n.get(y);A?A.push($):_n.set(y,[$])},$r=()=>{if(Tr||!Hr||zr||!Ae)throw new Error("worker not ready")},Vn=y=>{switch(y.data.type){case"init-wasm":Tr=!1,y.data.err?(zr=!0,bn[1](y.data.err)):(Hr=!0,bn[0]()),jr&&(URL.revokeObjectURL(jr),jr=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let $=_n.get(y.data.type);y.data.err?$.shift()[1](y.data.err):$.shift()[0](y.data.out);break}}},Gn=async()=>{if(!Hr){if(Tr)throw new Error("multiple calls to 'initWasm()' detected.");if(zr)throw new Error("previous call to 'initWasm()' failed.");if(Tr=!0,ur())return new Promise((y,$)=>{Ae?.terminate(),hs().then(([A,z])=>{try{Ae=z,Ae.onerror=G=>$(G),Ae.onmessage=Vn,bn=[y,$];let P={type:"init-wasm",in:me};if(!P.in.wasm.wasmPaths&&A){let G=an();G&&(P.in.wasm.wasmPaths=G)}Ae.postMessage(P),jr=A}catch(P){$(P)}},$)});try{await pn(me.wasm),await Dn(me),Hr=!0}catch(y){throw zr=!0,y}finally{Tr=!1}}},qn=async y=>{if(ur())return $r(),new Promise(($,A)=>{dr("init-ep",[$,A]);let z={type:"init-ep",in:{epName:y,env:me}};Ae.postMessage(z)});await Ln(me,y)},Es=async y=>ur()?($r(),new Promise(($,A)=>{dr("copy-from",[$,A]);let z={type:"copy-from",in:{buffer:y}};Ae.postMessage(z,[y.buffer])})):et(y),Cs=async(y,$)=>{if(ur()){if($?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return $r(),new Promise((A,z)=>{dr("create",[A,z]);let P={type:"create",in:{model:y,options:{...$}}},G=[];y instanceof Uint8Array&&G.push(y.buffer),Ae.postMessage(P,G)})}else return Zt(y,$)},li=async y=>{if(ur())return $r(),new Promise(($,A)=>{dr("release",[$,A]);let z={type:"release",in:y};Ae.postMessage(z)});Un(y)},Kr=async(y,$,A,z,P,G)=>{if(ur()){if(A.some(N=>N[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(P.some(N=>N))throw new Error("pre-allocated output tensor is not supported for proxy.");return $r(),new Promise((N,L)=>{dr("run",[N,L]);let V=A,Z={type:"run",in:{sessionId:y,inputIndices:$,inputs:V,outputIndices:z,options:G}};Ae.postMessage(Z,Fn(V))})}else return H(y,$,A,z,P,G)},ks=async y=>{if(ur())return $r(),new Promise(($,A)=>{dr("end-profiling",[$,A]);let z={type:"end-profiling",in:y};Ae.postMessage(z)});Wr(y)}}),As,Wn,Hn,jn=b(()=>{It(),Rs(),Ie(),rn(),Ts(),As=(y,$)=>{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 ${$()}`)}},Wn=y=>{switch(y[3]){case"cpu":return new He(y[0],y[2],y[1]);case"gpu-buffer":{let $=y[0];if(!yn($))throw new Error(`not supported data type: ${$} for deserializing GPU tensor`);let{gpuBuffer:A,download:z,dispose:P}=y[2];return He.fromGpuBuffer(A,{dataType:$,dims:y[1],download:z,dispose:P})}case"ml-tensor":{let $=y[0];if(!wn($))throw new Error(`not supported data type: ${$} for deserializing MLTensor tensor`);let{mlTensor:A,download:z,dispose:P}=y[2];return He.fromMLTensor(A,{dataType:$,dims:y[1],download:z,dispose:P})}default:throw new Error(`invalid data location: ${y[3]}`)}},Hn=class{async fetchModelAndCopyToWasmMemory(y){return Es(await vn(y))}async loadModel(y,$){Ue();let A;typeof y=="string"?A=await this.fetchModelAndCopyToWasmMemory(y):A=y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Cs(A,$),it()}async dispose(){return li(this.sessionId)}async run(y,$,A){Ue();let z=[],P=[];Object.entries(y).forEach(J=>{let j=J[0],xe=J[1],U=this.inputNames.indexOf(j);if(U===-1)throw new Error(`invalid input '${j}'`);z.push(xe),P.push(U)});let G=[],N=[];Object.entries($).forEach(J=>{let j=J[0],xe=J[1],U=this.outputNames.indexOf(j);if(U===-1)throw new Error(`invalid output '${j}'`);G.push(xe),N.push(U)});let L=z.map((J,j)=>As(J,()=>`input "${this.inputNames[P[j]]}"`)),V=G.map((J,j)=>J?As(J,()=>`output "${this.outputNames[N[j]]}"`):null),Z=await Kr(this.sessionId,P,L,N,V,A),ie={};for(let J=0;J<Z.length;J++)ie[this.outputNames[N[J]]]=G[J]??Wn(Z[J]);return it(),ie}startProfiling(){}endProfiling(){ks(this.sessionId)}}}),Sn={};F(Sn,{OnnxruntimeWebAssemblyBackend:()=>Qn,initializeFlags:()=>Kn,wasmBackend:()=>Xn});var Kn,Qn,Xn,Ms=b(()=>{It(),Rs(),jn(),Kn=()=>{(typeof me.wasm.initTimeout!="number"||me.wasm.initTimeout<0)&&(me.wasm.initTimeout=0);let y=me.wasm.simd;if(typeof y!="boolean"&&y!==void 0&&y!=="fixed"&&y!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${y}". Reset it to \`false\` and ignore SIMD feature checking.`),me.wasm.simd=!1),typeof me.wasm.proxy!="boolean"&&(me.wasm.proxy=!1),typeof me.wasm.trace!="boolean"&&(me.wasm.trace=!1),typeof me.wasm.numThreads!="number"||!Number.isInteger(me.wasm.numThreads)||me.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)me.wasm.numThreads=1;else{let $=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;me.wasm.numThreads=Math.min(4,Math.ceil(($||1)/2))}},Qn=class{async init(y){Kn(),await Gn(),await qn(y)}async createInferenceSessionHandler(y,$){let A=new Hn;return await A.loadModel(y,$),A}},Xn=new Qn}),Is={};F(Is,{InferenceSession:()=>tn,TRACE:()=>xt,TRACE_EVENT_BEGIN:()=>ht,TRACE_EVENT_END:()=>Mt,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>it,Tensor:()=>He,default:()=>Xi,env:()=>me,registerBackend:()=>ae}),It(),It(),It();var ui="1.24.3",Xi=ss;{let y=(Ms(),re(Sn)).wasmBackend;ae("cpu",y,10),ae("wasm",y,10)}return Object.defineProperty(me.versions,"web",{value:ui,enumerable:!0}),re(Is)})();c.exports=n})(ao)),ao.exports}var zp;function ky(){return zp||(zp=1,(function(c){var r=Ur&&Ur.__createBinding||(Object.create?(function(le,se,fe,he){he===void 0&&(he=fe);var Be=Object.getOwnPropertyDescriptor(se,fe);(!Be||("get"in Be?!se.__esModule:Be.writable||Be.configurable))&&(Be={enumerable:!0,get:function(){return se[fe]}}),Object.defineProperty(le,he,Be)}):(function(le,se,fe,he){he===void 0&&(he=fe),le[he]=se[fe]})),n=Ur&&Ur.__setModuleDefault||(Object.create?(function(le,se){Object.defineProperty(le,"default",{enumerable:!0,value:se})}):function(le,se){le.default=se}),a=Ur&&Ur.__importStar||function(le){if(le&&le.__esModule)return le;var se={};if(le!=null)for(var fe in le)fe!=="default"&&Object.prototype.hasOwnProperty.call(le,fe)&&r(se,le,fe);return n(se,le),se};Object.defineProperty(c,"__esModule",{value:!0}),c.MicVAD=c.getDefaultRealTimeVADOptions=c.ort=c.DEFAULT_MODEL=void 0;const f=a(Cy()),v=Ro(),C=Ao(),R=ai(),b=Ui(),F=hf(),B=pf();c.DEFAULT_MODEL="legacy",c.ort=f;const re="vad.worklet.bundle.min.js",X="silero_vad_v5.onnx",ee="silero_vad_legacy.onnx",ae=le=>({...C.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{R.log.debug("VAD misfire")},onSpeechStart:()=>{R.log.debug("Detected speech start")},onSpeechEnd:()=>{R.log.debug("Detected speech end")},onSpeechRealStart:()=>{R.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:le,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async se=>{se.getTracks().forEach(fe=>{fe.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:se=>{se.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});c.getDefaultRealTimeVADOptions=ae;const ce=le=>"audioWorklet"in le&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function de(le,se,fe,he,Be){await fe.audioWorklet.addModule(le),se.processorOptions={...se.processorOptions??{},frameSamples:he};const me=new AudioWorkletNode(fe,"vad-helper-worklet",se);return me.port.onmessage=async nt=>{const Ye=nt.data;if(!(typeof Ye=="object"&&Ye&&"message"in Ye)){console.error("Invalid message event",Ye);return}switch(Ye.message){case b.Message.AudioFrame:{if(!("data"in Ye&&Ye.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const mt=new Float32Array(Ye.data);await Be(mt);break}}},me}async function Le(le,se,fe){const he=new B.Resampler({nativeSampleRate:le.sampleRate,targetSampleRate:16e3,targetFrameSize:se});R.log.debug("using script processor");const me=le.createScriptProcessor(4096,1,1);let nt=!1;return me.onaudioprocess=async Ye=>{if(!nt){nt=!0;try{const mt=Ye.inputBuffer.getChannelData(0);Ye.outputBuffer.getChannelData(0).fill(0);const Je=he.process(mt);for(const st of Je)await fe(st)}catch(mt){console.error("Error processing audio:",mt)}finally{nt=!1}}},me.connect(le.destination),me}class Te{constructor(se,fe,he,Be,me=!1,nt=null,Ye=null,mt=null,Ge=null,Je=null,st=null,bt="uninitialized",ut=!1){this.options=se,this.frameProcessor=fe,this.model=he,this.frameSamples=Be,this.listening=me,this.errored=nt,this._stream=Ye,this._audioContext=mt,this._vadNode=Ge,this._mediaStreamAudioSourceNode=Je,this._audioProcessorAdapterType=st,this.initializationState=bt,this.ownsAudioContext=ut,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=Ze=>{this.initializationState="errored",this.errored=Ze},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(Ze){throw Ze instanceof Error?this.setErrored(Ze.message):this.setErrored(String(Ze)),Ze}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"?ce(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await de(this.options.baseAssetPath+re,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await Le(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:Ze,audioContext:De,vadNode:Ke}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ze);const tt=new MediaStreamAudioSourceNode(De,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=tt,tt.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:Ze,mediaStreamAudioSourceNode:De}=this.getAudioInstances();await this.options.pauseStream(Ze),De.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{R.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ze}=this.getAudioInstances();Ze instanceof AudioWorkletNode&&Ze.port.postMessage(b.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await this._audioContext?.close()},this.setOptions=Ze=>{this.frameProcessor.setOptions(Ze)},this.processFrame=async Ze=>{await this.frameProcessor.process(Ze,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ze=>{switch(Ze.msg){case b.Message.FrameProcessed:this.options.onFrameProcessed(Ze.probs,Ze.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(Ze.audio);break}}}static async new(se={}){const fe={...(0,c.getDefaultRealTimeVADOptions)(se.model??c.DEFAULT_MODEL),...se};(0,C.validateOptions)(fe),c.ort.env.wasm.wasmPaths=fe.onnxWASMBasePath,fe.ortConfig!==void 0&&fe.ortConfig(c.ort);const he=fe.model==="v5"?X:ee,Be=fe.baseAssetPath+he,me=fe.model==="v5"?F.SileroV5.new:F.SileroLegacy.new;let nt;try{nt=await me(c.ort,()=>(0,v.defaultModelFetcher)(Be))}catch(st){throw console.error(`Encountered an error while loading model file ${Be}`),st}const Ye=fe.model==="v5"?512:1536,mt=Ye/16,Ge=new C.FrameProcessor(nt.process,nt.reset_state,{positiveSpeechThreshold:fe.positiveSpeechThreshold,negativeSpeechThreshold:fe.negativeSpeechThreshold,redemptionMs:fe.redemptionMs,preSpeechPadMs:fe.preSpeechPadMs,minSpeechMs:fe.minSpeechMs,submitUserSpeechOnPause:fe.submitUserSpeechOnPause},mt),Je=new Te(fe,Ge,nt,Ye);if(fe.startOnLoad)try{await Je.start()}catch(st){throw console.error("Error starting micVad",st),st}return Je}}c.MicVAD=Te})(Ur)),Ur}var Dp;function Lp(){return Dp||(Dp=1,(function(c){Object.defineProperty(c,"__esModule",{value:!0}),c.getDefaultRealTimeVADOptions=c.MicVAD=c.DEFAULT_MODEL=c.utils=c.NonRealTimeVAD=c.Message=c.FrameProcessor=c.defaultModelFetcher=c.baseAssetPath=void 0;var r=uf();Object.defineProperty(c,"baseAssetPath",{enumerable:!0,get:function(){return r.baseAssetPath}});var n=Ro();Object.defineProperty(c,"defaultModelFetcher",{enumerable:!0,get:function(){return n.defaultModelFetcher}});var a=Ao();Object.defineProperty(c,"FrameProcessor",{enumerable:!0,get:function(){return a.FrameProcessor}});var f=Ui();Object.defineProperty(c,"Message",{enumerable:!0,get:function(){return f.Message}});var v=xy();Object.defineProperty(c,"NonRealTimeVAD",{enumerable:!0,get:function(){return v.NonRealTimeVAD}});const C=Ey();c.utils={audioFileToArray:C.audioFileToArray,minFramesForTargetMS:C.minFramesForTargetMS,arrayBufferToBase64:C.arrayBufferToBase64,encodeWAV:C.encodeWAV};var R=ky();Object.defineProperty(c,"DEFAULT_MODEL",{enumerable:!0,get:function(){return R.DEFAULT_MODEL}}),Object.defineProperty(c,"MicVAD",{enumerable:!0,get:function(){return R.MicVAD}}),Object.defineProperty(c,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return R.getDefaultRealTimeVADOptions}})})(no)),no}var Bp;function Ry(){return Bp||(Bp=1,(function(c){Object.defineProperty(c,"__esModule",{value:!0}),c.useMicVAD=c.getDefaultReactRealTimeVADOptions=c.utils=void 0;const r=Lp(),n=pe;var a=Lp();Object.defineProperty(c,"utils",{enumerable:!0,get:function(){return a.utils}});const f={userSpeakingThreshold:.6},v=b=>({...(0,r.getDefaultRealTimeVADOptions)(b),...f});c.getDefaultReactRealTimeVADOptions=v;function C(b){const F=b.model??r.DEFAULT_MODEL,B={...(0,c.getDefaultReactRealTimeVADOptions)(F),...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[F,B]=C(b),re=b.model??r.DEFAULT_MODEL,[X,ee]=(0,n.useState)(!1),[ae,ce]=(0,n.useState)(!0),[de,Le]=(0,n.useState)(!1),[Te,le]=(0,n.useState)(!1),[se,fe]=(0,n.useState)(null),he=(0,n.useRef)(B.onFrameProcessed),Be=(0,n.useRef)(B.onSpeechEnd),me=(0,n.useRef)(B.onSpeechStart),nt=(0,n.useRef)(B.onSpeechRealStart),Ye=(0,n.useRef)(B.onVADMisfire),mt=(0,n.useRef)(B.getStream);(0,n.useEffect)(()=>{he.current=B.onFrameProcessed,Be.current=B.onSpeechEnd,me.current=B.onSpeechStart,nt.current=B.onSpeechRealStart,Ye.current=B.onVADMisfire},[B.onFrameProcessed,B.onSpeechEnd,B.onSpeechStart,B.onSpeechRealStart,B.onVADMisfire]),(0,n.useEffect)(()=>{mt.current=B.getStream},[B.getStream]);const Ge=B.getStream.toString();(0,n.useEffect)(()=>{let ut=null,Ze=!1;return(async()=>{try{ce(!0),Le(!1);const Ke={...B,onFrameProcessed:(tt,Y)=>{const Me=tt.isSpeech>F.userSpeakingThreshold;ee(Me),he.current(tt,Y)},onSpeechEnd:tt=>{Be.current(tt)},onSpeechStart:()=>{me.current()},onSpeechRealStart:()=>{nt.current()},onVADMisfire:()=>{Ye.current()},getStream:()=>mt.current()};if(ut=await r.MicVAD.new(Ke),Ze){await ut.destroy();return}fe(ut),B.startOnLoad&&(await ut.start(),le(!0)),ce(!1)}catch(Ke){ce(!1),Ke instanceof Error?Le(Ke.message):Le(String(Ke))}})().catch(()=>{}),function(){Ze=!0,ut&&ut.destroy(),!ae&&!de&&le(!1)}},[Ge,re]);const Je=(0,n.useCallback)(async()=>{!ae&&!de&&(await se?.pause(),le(!1))},[ae,de,se]),st=(0,n.useCallback)(async()=>{!ae&&!de&&(await se?.start(),le(!0))},[ae,de,se]),bt=(0,n.useCallback)(async()=>{Te?await Je():await st()},[Te,Je,st]);return{listening:Te,errored:de,loading:ae,userSpeaking:X,pause:Je,start:st,toggle:bt}}c.useMicVAD=R})(ro)),ro}var Ay=Ry();lf();const Np={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},zi=16e3,mf=512,gf=700,My=300,Iy=mf/zi*1e3,Py=Math.ceil(gf/Iy);function Oy(c={}){const{onAudioChunk:r,onAudioEnd:n,onSpeechStart:a,onSpeechEnd:f,onVADMisfire:v,onError:C,interruptOnSpeechStart:R=!0,forceAudioMp4:b=!1}=c,{sendAudioChunk:F,endAudioStream:B,interrupt:re}=Gr(),[X,ee]=pe.useState(!1),[ae,ce]=pe.useState(null),de=pe.useRef(null),Le=pe.useRef(null),Te=pe.useRef(null),le=pe.useRef(!1),se=pe.useRef(null),fe=pe.useRef([]),he=pe.useCallback(()=>{if(!(typeof window>"u")){if(!Te.current){const De=window.AudioContext||window.webkitAudioContext;if(!De)return;Te.current=new De({sampleRate:zi})}Te.current.state==="suspended"&&Te.current.resume().catch(()=>{})}},[]);pe.useEffect(()=>{typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||navigator.mediaDevices.getUserMedia({audio:Np}).then(De=>{de.current=De,ce(null)}).catch(De=>{ce("permission_denied"),C?.(De)})},[C]);const Be=pe.useCallback(async()=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone APIs are unavailable in this browser");if(de.current&&de.current.getTracks()[0]?.readyState==="live")return de.current;const De=await navigator.mediaDevices.getUserMedia({audio:Np});return de.current=De,ce(null),De},[]),me=pe.useCallback(async De=>{De.getTracks().forEach(Ke=>{Ke.enabled=!1})},[]),nt=pe.useCallback(async()=>de.current&&de.current.getTracks()[0]?.readyState==="live"?(de.current.getTracks().forEach(De=>{De.enabled=!0}),de.current):Be(),[Be]),Ye=pe.useCallback(()=>{const De=fe.current;if(!De.length)return{samples:new Float32Array(0),duration:0};const Ke=De.reduce((Me,rt)=>Me+rt.length,0),tt=new Float32Array(Ke);let Y=0;for(const Me of De)tt.set(Me,Y),Y+=Me.length;return{samples:tt,duration:Ke/zi}},[]),mt=pe.useCallback(()=>{const De=de.current,Ke=Te.current;if(!De||!Ke||Le.current)return;const{samples:tt,duration:Y}=Ye();fe.current=[];const Me=!b&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/mp4")?"audio/mp4":"";try{const rt=Ke.createMediaStreamDestination();if(tt.length>0){const $t=Ke.createBuffer(1,tt.length,zi);$t.getChannelData(0).set(tt);const ct=Ke.createBufferSource();ct.buffer=$t,ct.connect(rt),ct.start(0)}const gt=Ke.createMediaStreamSource(De);if(Y>0){const $t=Ke.createDelay(Y+.1);$t.delayTime.value=Y,gt.connect($t).connect(rt)}else gt.connect(rt);const Vt=new MediaRecorder(rt.stream,Me?{mimeType:Me}:{});Vt.ondataavailable=async $t=>{if(!$t.data||$t.data.size<=0)return;const ct=await $t.data.arrayBuffer();r?r(ct):F(ct)},Le.current=Vt,Vt.start(100)}catch(rt){C?.(rt)}},[Ye,b,r,C,F]),Ge=pe.useCallback(()=>{const De=Le.current;if(De){if(Le.current=null,De.state==="inactive"){n?n():B();return}De.onstop=()=>{n?n():B()},De.stop()}},[B,n]),Je=pe.useCallback(()=>{const De=Le.current;if(De&&(Le.current=null,De.state!=="inactive"))try{De.stop()}catch{}},[]),st=pe.useCallback(()=>{Te.current&&(Te.current.close().catch(()=>{}),Te.current=null)},[]),bt=pe.useCallback(()=>{de.current&&(de.current.getTracks().forEach(De=>De.stop()),de.current=null)},[]),ut=Ay.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:gf,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:mf}},baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.30/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.1/dist/",ortConfig:De=>{De.env.wasm.numThreads=1,De.env.logLevel="error"},getStream:Be,pauseStream:me,resumeStream:nt,onFrameProcessed:(De,Ke)=>{if(!Ke)return;const tt=fe.current;tt.push(new Float32Array(Ke)),tt.length>Py&&tt.shift()},onSpeechStart:()=>{le.current||(se.current&&(clearTimeout(se.current),se.current=null),ee(!0),R&&re(),mt(),a?.())},onSpeechEnd:()=>{se.current=setTimeout(()=>{ee(!1),Ge(),le.current=!0,setTimeout(()=>{le.current=!1},300),f?.()},My)},onVADMisfire:()=>{se.current&&(clearTimeout(se.current),se.current=null),ee(!1),Je(),v?.()}}),Ze=pe.useCallback(()=>{he(),ut.listening&&Le.current&&(se.current&&(clearTimeout(se.current),se.current=null),ee(!1),Ge()),ut.toggle()},[Ge,he,ut]);return pe.useEffect(()=>()=>{se.current&&clearTimeout(se.current),Je(),st(),bt()},[st,bt,Je]),{isListening:ut.listening,isLoading:ut.loading,isSpeaking:X,micError:ae,toggle:Ze,start:ut.start,pause:ut.pause,userSpeaking:ut.userSpeaking}}const zy=()=>Gr(),yf=()=>{const{connectionState:c,isConnected:r,isSessionReady:n,error:a,reconnectAttempt:f,session:v,initializeSession:C,joinDesktopSession:R,disconnect:b}=Gr();return{connectionState:c,isConnected:r,isSessionReady:n,error:a,reconnectAttempt:f,session:v,initializeSession:C,joinDesktopSession:R,disconnect:b}},Dy=()=>{const{messages:c,sendTextMessage:r,clearMessages:n}=Gr();return{messages:c,sendTextMessage:r,clearMessages:n}},Ly=()=>{const{sendAudioChunk:c,endAudioStream:r,isAudioPlaying:n,transcript:a,partialTranscript:f,interrupt:v,resumeAudioPlayback:C,attachAudioElement:R}=Gr();return{sendAudioChunk:c,endAudioStream:r,isAudioPlaying:n,transcript:a,partialTranscript:f,interrupt:v,resumeAudioPlayback:C,attachAudioElement:R}},wf=()=>{const{session:c,isAvatarSpeaking:r,cloudStream:n,setCloudStreamState:a}=Gr(),f=n?.state||Kt.IDLE;return{streamingUrl:c.streamingUrl,isAvatarSpeaking:r,speakingSource:"avatar_events",isCloudAvatar:c.agentType===Fr.CLOUD_AVATAR,isDesktopAvatar:c.agentType===Fr.DESKTOP_AVATAR,cloudStreamState:f,cloudStreamError:n?.error||null,isCloudStreamConnected:f===Kt.CONNECTED,isCloudStreamLoading:f===Kt.CONNECTING||f===Kt.LOADING,setCloudStreamState:a}},By=c=>{const{attachAudioElement:r,resumeAudioPlayback:n}=Gr();pe.useEffect(()=>{if(!c?.current)return;r(c.current);const a=()=>{n()},f=c.current;return f.addEventListener("click",a),f.addEventListener("touchstart",a),()=>{f.removeEventListener("click",a),f.removeEventListener("touchstart",a),r(null)}},[r,c,n])};function Ny({connect:c=!0,session:r,onError:n,onInitialized:a,children:f}){const{initializeSession:v,joinDesktopSession:C,disconnect:R}=yf(),b=pe.useRef(!1);return pe.useEffect(()=>{if(!c||b.current)return;let F=!1;return b.current=!0,(async()=>{try{if(r?.mode==="join_desktop"){const X=await C({uniqueId:r.uniqueId});F||a?.(X);return}const re=await v({apiKey:r?.apiKey,publicChatId:r?.publicChatId,agentId:r?.agentId,language:r?.language||"en"});F||a?.(re)}catch(re){F||n?.(re)}})(),()=>{F=!0,R(),b.current=!1}},[c,R,v,C,n,a,r]),f}function Uy({children:c,wsUrl:r,restUrl:n,session:a,connect:f=!0,reconnectOptions:v,enableAudio:C=!0,pcmOptions:R,debug:b=!1,onError:F,onInitialized:B}){return sr.jsx(of,{wsUrl:r,restUrl:n,reconnectOptions:v,enableAudio:C,pcmOptions:R,debug:b,children:sr.jsx(Ny,{connect:f,session:a,onError:F,onInitialized:B,children:c})})}var oo={exports:{}},Up;function Fy(){return Up||(Up=1,(function(c){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(`
|
|
2858
|
+
*/var Op;function Cy(){return Op||(Op=1,(function(c,r){var n=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(y=>typeof ar<"u"?ar:typeof Proxy<"u"?new Proxy(y,{get:($,A)=>(typeof ar<"u"?ar:$)[A]}):y)(function(y){if(typeof ar<"u")return ar.apply(this,arguments);throw Error('Dynamic require of "'+y+'" is not supported')}),_=(y,$)=>()=>(y&&($=y(y=0)),$),U=(y,$)=>{for(var A in $)a(y,A,{get:$[A],enumerable:!0})},B=(y,$,A,z)=>{if($&&typeof $=="object"||typeof $=="function")for(let P of v($))!C.call(y,P)&&P!==A&&a(y,P,{get:()=>$[P],enumerable:!(z=f($,P))||z.enumerable});return y},te=y=>B(a({},"__esModule",{value:!0}),y),Q,ee,ie,ce,ue,Be=_(()=>{Q=new Map,ee=[],ie=(y,$,A)=>{if($&&typeof $.init=="function"&&typeof $.createInferenceSessionHandler=="function"){let z=Q.get(y);if(z===void 0)Q.set(y,{backend:$,priority:A});else{if(z.priority>A)return;if(z.priority===A&&z.backend!==$)throw new Error(`cannot register backend "${y}" using priority ${A}`)}if(A>=0){let P=ee.indexOf(y);P!==-1&&ee.splice(P,1);for(let G=0;G<ee.length;G++)if(Q.get(ee[G]).priority<=A){ee.splice(G,0,y);return}ee.push(y)}return}throw new TypeError("not a valid backend")},ce=async y=>{let $=Q.get(y);if(!$)return"backend not found.";if($.initialized)return $.backend;if($.aborted)return $.error;{let A=!!$.initPromise;try{return A||($.initPromise=$.backend.init(y)),await $.initPromise,$.initialized=!0,$.backend}catch(z){return A||($.error=`${z}`,$.aborted=!0),$.error}finally{delete $.initPromise}}},ue=async y=>{let $=y.executionProviders||[],A=$.map(V=>typeof V=="string"?V:V.name),z=A.length===0?ee:A,P,G=[],N=new Set;for(let V of z){let Z=await ce(V);typeof Z=="string"?G.push({name:V,err:Z}):(P||(P=Z),P===Z&&N.add(V))}if(!P)throw new Error(`no available backend found. ERR: ${G.map(V=>`[${V.name}] ${V.err}`).join(", ")}`);for(let{name:V,err:Z}of G)A.includes(V)&&console.warn(`removing requested execution provider "${V}" from session options because it is not available: ${Z}`);let L=$.filter(V=>N.has(typeof V=="string"?V:V.name));return[P,new Proxy(y,{get:(V,Z)=>Z==="executionProviders"?L:Reflect.get(V,Z)})]}}),Te=_(()=>{Be()}),oe,ne=_(()=>{oe="1.24.3"}),me,pe,Ne=_(()=>{ne(),me="warning",pe={wasm:{},webgl:{},webgpu:{},versions:{common:oe},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}`);me=y}},get logLevel(){return me}},Object.defineProperty(pe,"logLevel",{enumerable:!0})}),ge,rt=_(()=>{Ne(),ge=pe}),Xe,ft,Ge=_(()=>{Xe=(y,$)=>{let A=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);A.width=y.dims[3],A.height=y.dims[2];let z=A.getContext("2d");if(z!=null){let P,G;$?.tensorLayout!==void 0&&$.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[3]):(P=y.dims[3],G=y.dims[2]);let N=$?.format!==void 0?$.format:"RGB",L=$?.norm,V,Z;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?Z=[0,0,0,0]:typeof L.bias=="number"?Z=[L.bias,L.bias,L.bias,L.bias]:(Z=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(Z[3]=L.bias[3]));let se=G*P,J=0,j=se,Ee=se*2,F=-1;N==="RGBA"?(J=0,j=se,Ee=se*2,F=se*3):N==="RGB"?(J=0,j=se,Ee=se*2):N==="RBG"&&(J=0,Ee=se,j=se*2);for(let le=0;le<G;le++)for(let vt=0;vt<P;vt++){let We=(y.data[J++]-Z[0])*V[0],Ce=(y.data[j++]-Z[1])*V[1],He=(y.data[Ee++]-Z[2])*V[2],be=F===-1?255:(y.data[F++]-Z[3])*V[3];z.fillStyle="rgba("+We+","+Ce+","+He+","+be+")",z.fillRect(vt,le,1,1)}if("toDataURL"in A)return A.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},ft=(y,$)=>{let A=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),z;if(A!=null){let P,G,N;$?.tensorLayout!==void 0&&$.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[1],N=y.dims[3]):(P=y.dims[3],G=y.dims[2],N=y.dims[1]);let L=$!==void 0&&$.format!==void 0?$.format:"RGB",V=$?.norm,Z,se;V===void 0||V.mean===void 0?Z=[255,255,255,255]:typeof V.mean=="number"?Z=[V.mean,V.mean,V.mean,V.mean]:(Z=[V.mean[0],V.mean[1],V.mean[2],255],V.mean[3]!==void 0&&(Z[3]=V.mean[3])),V===void 0||V.bias===void 0?se=[0,0,0,0]:typeof V.bias=="number"?se=[V.bias,V.bias,V.bias,V.bias]:(se=[V.bias[0],V.bias[1],V.bias[2],0],V.bias[3]!==void 0&&(se[3]=V.bias[3]));let J=G*P;if($!==void 0&&($.format!==void 0&&N===4&&$.format!=="RGBA"||N===3&&$.format!=="RGB"&&$.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let j=4,Ee=0,F=1,le=2,vt=3,We=0,Ce=J,He=J*2,be=-1;L==="RGBA"?(We=0,Ce=J,He=J*2,be=J*3):L==="RGB"?(We=0,Ce=J,He=J*2):L==="RBG"&&(We=0,He=J,Ce=J*2),z=A.createImageData(P,G);for(let Dt=0;Dt<G*P;Ee+=j,F+=j,le+=j,vt+=j,Dt++)z.data[Ee]=(y.data[We++]-se[0])*Z[0],z.data[F]=(y.data[Ce++]-se[1])*Z[1],z.data[le]=(y.data[He++]-se[2])*Z[2],z.data[vt]=be===-1?255:(y.data[be++]-se[3])*Z[3]}else throw new Error("Can not access image data");return z}}),Ye,st,bt,ut,Je,Le,qe=_(()=>{de(),Ye=(y,$)=>{if(y===void 0)throw new Error("Image buffer must be defined");if($.height===void 0||$.width===void 0)throw new Error("Image height and width must be defined");if($.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:A,width:z}=$,P=$.norm??{mean:255,bias:0},G,N;typeof P.mean=="number"?G=[P.mean,P.mean,P.mean,P.mean]:G=[P.mean[0],P.mean[1],P.mean[2],P.mean[3]??255],typeof P.bias=="number"?N=[P.bias,P.bias,P.bias,P.bias]:N=[P.bias[0],P.bias[1],P.bias[2],P.bias[3]??0];let L=$.format!==void 0?$.format:"RGBA",V=$.tensorFormat!==void 0&&$.tensorFormat!==void 0?$.tensorFormat:"RGB",Z=A*z,se=V==="RGBA"?new Float32Array(Z*4):new Float32Array(Z*3),J=4,j=0,Ee=1,F=2,le=3,vt=0,We=Z,Ce=Z*2,He=-1;L==="RGB"&&(J=3,j=0,Ee=1,F=2,le=-1),V==="RGBA"?He=Z*3:V==="RBG"?(vt=0,Ce=Z,We=Z*2):V==="BGR"&&(Ce=0,We=Z,vt=Z*2);for(let be=0;be<Z;be++,j+=J,F+=J,Ee+=J,le+=J)se[vt++]=(y[j]+N[0])/G[0],se[We++]=(y[Ee]+N[1])/G[1],se[Ce++]=(y[F]+N[2])/G[2],He!==-1&&le!==-1&&(se[He++]=(y[le]+N[3])/G[3]);return V==="RGBA"?new nt("float32",se,[1,4,A,z]):new nt("float32",se,[1,3,A,z])},st=async(y,$)=>{let A=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,z=typeof ImageData<"u"&&y instanceof ImageData,P=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,G=typeof y=="string",N,L=$??{},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")},Z=se=>typeof HTMLCanvasElement<"u"&&se instanceof HTMLCanvasElement||se instanceof OffscreenCanvas?se.getContext("2d"):null;if(A){let se=V();se.width=y.width,se.height=y.height;let J=Z(se);if(J!=null){let j=y.height,Ee=y.width;if($!==void 0&&$.resizedHeight!==void 0&&$.resizedWidth!==void 0&&(j=$.resizedHeight,Ee=$.resizedWidth),$!==void 0){if(L=$,$.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");L.tensorFormat="RGBA",L.height=j,L.width=Ee}else L.tensorFormat="RGBA",L.height=j,L.width=Ee;J.drawImage(y,0,0),N=J.getImageData(0,0,Ee,j).data}else throw new Error("Can not access image data")}else if(z){let se,J;if($!==void 0&&$.resizedWidth!==void 0&&$.resizedHeight!==void 0?(se=$.resizedHeight,J=$.resizedWidth):(se=y.height,J=y.width),$!==void 0&&(L=$),L.format="RGBA",L.height=se,L.width=J,$!==void 0){let j=V();j.width=J,j.height=se;let Ee=Z(j);if(Ee!=null)Ee.putImageData(y,0,0),N=Ee.getImageData(0,0,J,se).data;else throw new Error("Can not access image data")}else N=y.data}else if(P){if($===void 0)throw new Error("Please provide image config with format for Imagebitmap");let se=V();se.width=y.width,se.height=y.height;let J=Z(se);if(J!=null){let j=y.height,Ee=y.width;return J.drawImage(y,0,0,Ee,j),N=J.getImageData(0,0,Ee,j).data,L.height=j,L.width=Ee,Ye(N,L)}else throw new Error("Can not access image data")}else{if(G)return new Promise((se,J)=>{let j=V(),Ee=Z(j);if(!y||!Ee)return J();let F=new Image;F.crossOrigin="Anonymous",F.src=y,F.onload=()=>{j.width=F.width,j.height=F.height,Ee.drawImage(F,0,0,j.width,j.height);let le=Ee.getImageData(0,0,j.width,j.height);L.height=j.height,L.width=j.width,se(Ye(le.data,L))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(N!==void 0)return Ye(N,L);throw new Error("Input data provided is not supported - aborted tensor creation")},bt=(y,$)=>{let{width:A,height:z,download:P,dispose:G}=$,N=[1,z,A,4];return new nt({location:"texture",type:"float32",texture:y,dims:N,download:P,dispose:G})},ut=(y,$)=>{let{dataType:A,dims:z,download:P,dispose:G}=$;return new nt({location:"gpu-buffer",type:A??"float32",gpuBuffer:y,dims:z,download:P,dispose:G})},Je=(y,$)=>{let{dataType:A,dims:z,download:P,dispose:G}=$;return new nt({location:"ml-tensor",type:A??"float32",mlTensor:y,dims:z,download:P,dispose:G})},Le=(y,$,A)=>new nt({location:"cpu-pinned",type:y,data:$,dims:A??[$.length]})}),et,Y,Ie,tt,gt=_(()=>{et=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Y=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Ie=!1,tt=()=>{if(!Ie){Ie=!0;let y=typeof BigInt64Array<"u"&&BigInt64Array.from,$=typeof BigUint64Array<"u"&&BigUint64Array.from,A=globalThis.Float16Array,z=typeof A<"u"&&A.from;y&&(et.set("int64",BigInt64Array),Y.set(BigInt64Array,"int64")),$&&(et.set("uint64",BigUint64Array),Y.set(BigUint64Array,"uint64")),z?(et.set("float16",A),Y.set(A,"float16")):et.set("float16",Uint16Array)}}}),Vt,Et,dt=_(()=>{de(),Vt=y=>{let $=1;for(let A=0;A<y.length;A++){let z=y[A];if(typeof z!="number"||!Number.isSafeInteger(z))throw new TypeError(`dims[${A}] must be an integer, got: ${z}`);if(z<0)throw new RangeError(`dims[${A}] must be a non-negative integer, got: ${z}`);$*=z}return $},Et=(y,$)=>{switch(y.location){case"cpu":return new nt(y.type,y.data,$);case"cpu-pinned":return new nt({location:"cpu-pinned",data:y.data,type:y.type,dims:$});case"texture":return new nt({location:"texture",texture:y.texture,type:y.type,dims:$});case"gpu-buffer":return new nt({location:"gpu-buffer",gpuBuffer:y.gpuBuffer,type:y.type,dims:$});case"ml-tensor":return new nt({location:"ml-tensor",mlTensor:y.mlTensor,type:y.type,dims:$});default:throw new Error(`tensorReshape: tensor location ${y.location} is not supported`)}}}),nt,de=_(()=>{Ge(),qe(),gt(),dt(),nt=class{constructor(y,$,A){tt();let z,P;if(typeof y=="object"&&"location"in y)switch(this.dataLocation=y.location,z=y.type,P=y.dims,y.location){case"cpu-pinned":{let N=et.get(z);if(!N)throw new TypeError(`unsupported type "${z}" to create tensor from pinned buffer`);if(!(y.data instanceof N))throw new TypeError(`buffer should be of type ${N.name}`);this.cpuData=y.data;break}case"texture":{if(z!=="float32")throw new TypeError(`unsupported type "${z}" to create tensor from texture`);this.gpuTextureData=y.texture,this.downloader=y.download,this.disposer=y.dispose;break}case"gpu-buffer":{if(z!=="float32"&&z!=="float16"&&z!=="int32"&&z!=="int64"&&z!=="uint32"&&z!=="uint8"&&z!=="bool"&&z!=="uint4"&&z!=="int4")throw new TypeError(`unsupported type "${z}" to create tensor from gpu buffer`);this.gpuBufferData=y.gpuBuffer,this.downloader=y.download,this.disposer=y.dispose;break}case"ml-tensor":{if(z!=="float32"&&z!=="float16"&&z!=="int32"&&z!=="int64"&&z!=="uint32"&&z!=="uint64"&&z!=="int8"&&z!=="uint8"&&z!=="bool"&&z!=="uint4"&&z!=="int4")throw new TypeError(`unsupported type "${z}" to create tensor from MLTensor`);this.mlTensorData=y.mlTensor,this.downloader=y.download,this.disposer=y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let N,L;if(typeof y=="string")if(z=y,L=A,y==="string"){if(!Array.isArray($))throw new TypeError("A string tensor's data must be a string array.");N=$}else{let V=et.get(y);if(V===void 0)throw new TypeError(`Unsupported tensor type: ${y}.`);if(Array.isArray($)){if(y==="float16"&&V===Uint16Array||y==="uint4"||y==="int4")throw new TypeError(`Creating a ${y} tensor from number array is not supported. Please use ${V.name} as data.`);y==="uint64"||y==="int64"?N=V.from($,BigInt):N=V.from($)}else if($ instanceof V)N=$;else if($ instanceof Uint8ClampedArray)if(y==="uint8")N=Uint8Array.from($);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(y==="float16"&&$ instanceof Uint16Array&&V!==Uint16Array)N=new globalThis.Float16Array($.buffer,$.byteOffset,$.length);else throw new TypeError(`A ${z} tensor's data must be type of ${V}`)}else if(L=$,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")z="string",N=y;else if(V==="boolean")z="bool",N=Uint8Array.from(y);else throw new TypeError(`Invalid element type of data array: ${V}.`)}else if(y instanceof Uint8ClampedArray)z="uint8",N=Uint8Array.from(y);else{let V=Y.get(y.constructor);if(V===void 0)throw new TypeError(`Unsupported type for tensor data: ${y.constructor}.`);z=V,N=y}if(L===void 0)L=[N.length];else if(!Array.isArray(L))throw new TypeError("A tensor's dims must be a number array");P=L,this.cpuData=N,this.dataLocation="cpu"}let G=Vt(P);if(this.cpuData&&G!==this.cpuData.length&&!((z==="uint4"||z==="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=z,this.dims=P,this.size=G}static async fromImage(y,$){return st(y,$)}static fromTexture(y,$){return bt(y,$)}static fromGpuBuffer(y,$){return ut(y,$)}static fromMLTensor(y,$){return Je(y,$)}static fromPinnedBuffer(y,$,A){return Le(y,$,A)}toDataURL(y){return Xe(this,y)}toImageData(y){return ft(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 $=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=$,y&&this.disposer&&(this.disposer(),this.disposer=void 0),$}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 Et(this,y)}}}),xe,wt=_(()=>{de(),xe=nt}),$t,zt,fe,Ue,mt,ct,Mr=_(()=>{Ne(),$t=(y,$)=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeStamp(`${y}::ORT::${$}`)},zt=(y,$)=>{let A=new Error().stack?.split(/\r\n|\r|\n/g)||[],z=!1;for(let P=0;P<A.length;P++){if(z&&!A[P].includes("TRACE_FUNC")){let G=`FUNC_${y}::${A[P].trim().split(" ")[1]}`;$&&(G+=`::${$}`),$t("CPU",G);return}A[P].includes("TRACE_FUNC")&&(z=!0)}},fe=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||zt("BEGIN",y)},Ue=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||zt("END",y)},mt=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.time(`ORT::${y}`)},ct=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeEnd(`ORT::${y}`)}}),Ir,Fi=_(()=>{Be(),wt(),Mr(),Ir=class ff{constructor($){this.handler=$}async run($,A,z){fe(),mt("InferenceSession.run");let P={},G={};if(typeof $!="object"||$===null||$ instanceof xe||Array.isArray($))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let N=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof xe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");N=!1;for(let Z of A){if(typeof Z!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(Z)===-1)throw new RangeError(`'fetches' contains invalid output name: ${Z}.`);P[Z]=null}if(typeof z=="object"&&z!==null)G=z;else if(typeof z<"u")throw new TypeError("'options' must be an object.")}else{let Z=!1,se=Object.getOwnPropertyNames(A);for(let J of this.outputNames)if(se.indexOf(J)!==-1){let j=A[J];(j===null||j instanceof xe)&&(Z=!0,N=!1,P[J]=j)}if(Z){if(typeof z=="object"&&z!==null)G=z;else if(typeof z<"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 Z of this.inputNames)if(typeof $[Z]>"u")throw new Error(`input '${Z}' is missing in 'feeds'.`);if(N)for(let Z of this.outputNames)P[Z]=null;let L=await this.handler.run($,P,G),V={};for(let Z in L)if(Object.hasOwnProperty.call(L,Z)){let se=L[Z];se instanceof xe?V[Z]=se:V[Z]=new xe(se.type,se.data,se.dims)}return ct("InferenceSession.run"),Ue(),V}async release(){return this.handler.dispose()}static async create($,A,z,P){fe(),mt("InferenceSession.create");let G,N={};if(typeof $=="string"){if(G=$,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if($ instanceof Uint8Array){if(G=$,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if($ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer){let se=$,J=0,j=$.byteLength;if(typeof A=="object"&&A!==null)N=A;else if(typeof A=="number"){if(J=A,!Number.isSafeInteger(J))throw new RangeError("'byteOffset' must be an integer.");if(J<0||J>=se.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${se.byteLength}).`);if(j=$.byteLength-J,typeof z=="number"){if(j=z,!Number.isSafeInteger(j))throw new RangeError("'byteLength' must be an integer.");if(j<=0||J+j>se.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${se.byteLength-J}].`);if(typeof P=="object"&&P!==null)N=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(typeof z<"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(se,J,j)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[L,V]=await ue(N),Z=await L.createInferenceSessionHandler(G,V);return ct("InferenceSession.create"),Ue(),new ff(Z)}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}}}),rn,Vi=_(()=>{Fi(),rn=Ir}),Gi=_(()=>{}),qi=_(()=>{}),Wi=_(()=>{}),Hi=_(()=>{}),ss={};U(ss,{InferenceSession:()=>rn,TRACE:()=>$t,TRACE_EVENT_BEGIN:()=>mt,TRACE_EVENT_END:()=>ct,TRACE_FUNC_BEGIN:()=>fe,TRACE_FUNC_END:()=>Ue,Tensor:()=>xe,env:()=>ge,registerBackend:()=>ie});var It=_(()=>{Te(),rt(),Vi(),wt(),Gi(),qi(),Mr(),Wi(),Hi()}),nn=_(()=>{}),is={};U(is,{default:()=>as});var sn,an,as,ji=_(()=>{xs(),Qt(),cn(),sn="ort-wasm-proxy-worker",an=globalThis.self?.name===sn,an&&(self.onmessage=y=>{let{type:$,in:A}=y.data;try{switch($){case"init-wasm":fn(A.wasm).then(()=>{Ln(A).then(()=>{postMessage({type:$})},z=>{postMessage({type:$,err:z})})},z=>{postMessage({type:$,err:z})});break;case"init-ep":{let{epName:z,env:P}=A;Bn(P,z).then(()=>{postMessage({type:$})},G=>{postMessage({type:$,err:G})});break}case"copy-from":{let{buffer:z}=A,P=Ze(z);postMessage({type:$,out:P});break}case"create":{let{model:z,options:P}=A;Zt(z,P).then(G=>{postMessage({type:$,out:G})},G=>{postMessage({type:$,err:G})});break}case"release":Fn(A),postMessage({type:$});break;case"run":{let{sessionId:z,inputIndices:P,inputs:G,outputIndices:N,options:L}=A;H(z,P,G,N,new Array(N.length).fill(null),L).then(V=>{V.some(Z=>Z[3]!=="cpu")?postMessage({type:$,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:$,out:V},Vn([...G,...V]))},V=>{postMessage({type:$,err:V})});break}case"end-profiling":Hr(A),postMessage({type:$});break;default:}}catch(z){postMessage({type:$,err:z})}}),as=an?null:y=>new Worker(y??yt,{type:"classic",name:sn})}),os,ls,yt,on,Pr,us,ds,ln,cs,un,hs,dn,ps,cn=_(()=>{nn(),os=typeof location>"u"?void 0:location.origin,ls=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,yt=ls(),on=()=>{if(yt&&!yt.startsWith("blob:"))return yt.substring(0,yt.lastIndexOf("/")+1)},Pr=(y,$)=>{try{let A=$??yt;return(A?new URL(y,A):new URL(y)).origin===os}catch{return!1}},us=(y,$)=>{let A=$??yt;try{return(A?new URL(y,A):new URL(y)).href}catch{return}},ds=(y,$)=>`${$??"./"}${y}`,ln=async y=>{let $=await(await fetch(y,{credentials:"same-origin"})).blob();return URL.createObjectURL($)},cs=async y=>(await import(y)).default,un=(ji(),te(is)).default,hs=async()=>{if(!yt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Pr(yt))return[void 0,un()];let y=await ln(yt);return[y,un(y)]},dn=void 0,ps=async(y,$,A,z)=>{let P=dn&&!(y||$);if(P)if(yt)P=Pr(yt)||z&&!A;else if(z&&!A)P=!0;else throw new Error("cannot determine the script source URL.");if(P)return[void 0,dn];{let G="ort-wasm-simd-threaded.mjs",N=y??us(G,$),L=A&&N&&!Pr(N,$),V=L?await ln(N):N??ds(G,$);return[L?V:void 0,await cs(V)]}}}),hn,Or,or,pn,fs,ms,gs,fn,ze,Qt=_(()=>{cn(),Or=!1,or=!1,pn=!1,fs=()=>{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}},ms=()=>{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}},gs=()=>{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}},fn=async y=>{if(Or)return Promise.resolve();if(or)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(pn)throw new Error("previous call to 'initializeWebAssembly()' failed.");or=!0;let $=y.initTimeout,A=y.numThreads;if(y.simd!==!1){if(y.simd==="relaxed"){if(!gs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ms())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let z=fs();A>1&&!z&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+A+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),y.numThreads=A=1);let P=y.wasmPaths,G=typeof P=="string"?P:void 0,N=P?.mjs,L=N?.href??N,V=P?.wasm,Z=V?.href??V,se=y.wasmBinary,[J,j]=await ps(L,G,A>1,!!se||!!Z),Ee=!1,F=[];if($>0&&F.push(new Promise(le=>{setTimeout(()=>{Ee=!0,le()},$)})),F.push(new Promise((le,vt)=>{let We={numThreads:A};if(se)We.wasmBinary=se,We.locateFile=Ce=>Ce;else if(Z||G)We.locateFile=Ce=>Z??G+Ce;else if(L&&L.indexOf("blob:")!==0)We.locateFile=Ce=>new URL(Ce,L).href;else if(J){let Ce=on();Ce&&(We.locateFile=He=>Ce+He)}j(We).then(Ce=>{or=!1,Or=!0,hn=Ce,le(),J&&URL.revokeObjectURL(J)},Ce=>{or=!1,pn=!0,vt(Ce)})})),await Promise.race(F),Ee)throw new Error(`WebAssembly backend initializing failed due to timeout: ${$}ms`)},ze=()=>{if(Or&&hn)return hn;throw new Error("WebAssembly is not initialized yet.")}}),xt,zr,Ae,mn=_(()=>{Qt(),xt=(y,$)=>{let A=ze(),z=A.lengthBytesUTF8(y)+1,P=A._malloc(z);return A.stringToUTF8(y,P,z),$.push(P),P},zr=(y,$,A,z)=>{if(typeof y=="object"&&y!==null){if(A.has(y))throw new Error("Circular reference in options");A.add(y)}Object.entries(y).forEach(([P,G])=>{let N=$?$+P:P;if(typeof G=="object")zr(G,N+".",A,z);else if(typeof G=="string"||typeof G=="number")z(N,G.toString());else if(typeof G=="boolean")z(N,G?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof G}`)})},Ae=y=>{let $=ze(),A=$.stackSave();try{let z=$.PTR_SIZE,P=$.stackAlloc(2*z);$._OrtGetLastError(P,P+z);let G=Number($.getValue(P,z===4?"i32":"i64")),N=$.getValue(P+z,"*"),L=N?$.UTF8ToString(N):"";throw new Error(`${y} ERROR_CODE: ${G}, ERROR_MESSAGE: ${L}`)}finally{$.stackRestore(A)}}}),ys,Ki=_(()=>{Qt(),mn(),ys=y=>{let $=ze(),A=0,z=[],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=xt(y.tag,z)),A=$._OrtCreateRunOptions(P.logSeverityLevel,P.logVerbosityLevel,!!P.terminate,G),A===0&&Ae("Can't create run options."),y?.extra!==void 0&&zr(y.extra,"",new WeakSet,(N,L)=>{let V=xt(N,z),Z=xt(L,z);$._OrtAddRunConfigEntry(A,V,Z)!==0&&Ae(`Can't set a run config entry: ${N} - ${L}.`)}),[A,z]}catch(G){throw A!==0&&$._OrtReleaseRunOptions(A),z.forEach(N=>$._free(N)),G}}}),ws,vs,_s,lr,bs,Ss,Qi=_(()=>{Qt(),mn(),ws=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}`)}},vs=y=>{switch(y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${y}`)}},_s=y=>{y.extra||(y.extra={}),y.extra.session||(y.extra.session={});let $=y.extra.session;$.use_ort_model_bytes_directly||($.use_ort_model_bytes_directly="1"),y.executionProviders&&y.executionProviders.some(A=>(typeof A=="string"?A:A.name)==="webgpu")&&(y.enableMemPattern=!1)},lr=(y,$,A,z)=>{let P=xt($,z),G=xt(A,z);ze()._OrtAddSessionConfigEntry(y,P,G)!==0&&Ae(`Can't set a session config entry: ${$} - ${A}.`)},bs=async(y,$,A)=>{let z=$.executionProviders;for(let P of z){let G=typeof P=="string"?P:P.name,N=[];switch(G){case"webnn":if(G="WEBNN",typeof P!="string"){let J=P?.deviceType;J&&lr(y,"deviceType",J,A)}break;case"webgpu":if(G="JS",typeof P!="string"){let J=P;if(J?.preferredLayout){if(J.preferredLayout!=="NCHW"&&J.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${J.preferredLayout}`);lr(y,"preferredLayout",J.preferredLayout,A)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${G}`)}let L=xt(G,A),V=N.length,Z=0,se=0;if(V>0){Z=ze()._malloc(V*ze().PTR_SIZE),A.push(Z),se=ze()._malloc(V*ze().PTR_SIZE),A.push(se);for(let J=0;J<V;J++)ze().setValue(Z+J*ze().PTR_SIZE,N[J][0],"*"),ze().setValue(se+J*ze().PTR_SIZE,N[J][1],"*")}await ze()._OrtAppendExecutionProvider(y,L,Z,se,V)!==0&&Ae(`Can't append execution provider: ${G}.`)}},Ss=async y=>{let $=ze(),A=0,z=[],P=y||{};_s(P);try{let G=ws(P.graphOptimizationLevel??"all"),N=vs(P.executionMode??"sequential"),L=typeof P.logId=="string"?xt(P.logId,z):0,V=P.logSeverityLevel??2;if(!Number.isInteger(V)||V<0||V>4)throw new Error(`log severity level is not valid: ${V}`);let Z=P.logVerbosityLevel??0;if(!Number.isInteger(Z)||Z<0||Z>4)throw new Error(`log verbosity level is not valid: ${Z}`);let se=typeof P.optimizedModelFilePath=="string"?xt(P.optimizedModelFilePath,z):0;if(A=$._OrtCreateSessionOptions(G,!!P.enableCpuMemArena,!!P.enableMemPattern,N,!!P.enableProfiling,0,L,V,Z,se),A===0&&Ae("Can't create session options."),P.executionProviders&&await bs(A,P,z),P.enableGraphCapture!==void 0){if(typeof P.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${P.enableGraphCapture}`);lr(A,"enableGraphCapture",P.enableGraphCapture.toString(),z)}if(P.freeDimensionOverrides)for(let[J,j]of Object.entries(P.freeDimensionOverrides)){if(typeof J!="string")throw new Error(`free dimension override name must be a string: ${J}`);if(typeof j!="number"||!Number.isInteger(j)||j<0)throw new Error(`free dimension override value must be a non-negative integer: ${j}`);let Ee=xt(J,z);$._OrtAddFreeDimensionOverride(A,Ee,j)!==0&&Ae(`Can't set a free dimension override: ${J} - ${j}.`)}return P.extra!==void 0&&zr(P.extra,"",new WeakSet,(J,j)=>{lr(A,J,j,z)}),[A,z]}catch(G){throw A!==0&&$._OrtReleaseSessionOptions(A)!==0&&Ae("Can't release session options."),z.forEach(N=>$._free(N)),G}}}),Xt,Yt,Jt,gn,yn,wn,vn,Dn,Pe=_(()=>{Xt=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}`)}},Yt=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}`)}},Jt=(y,$)=>{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],z=typeof $=="number"?$:$.reduce((P,G)=>P*G,1);return A>0?Math.ceil(z*A):void 0},gn=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}`)}},yn=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}`)}},wn=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",vn=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint64"||y==="int8"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Dn=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}`)}}}),_n,Ts=_(()=>{nn(),_n=async y=>{if(typeof y=="string"){let $=await fetch(y);if(!$.ok)throw new Error(`failed to load external data file: ${y}`);let A=$.headers.get("Content-Length"),z=A?parseInt(A,10):0;if(z<1073741824)return new Uint8Array(await $.arrayBuffer());{if(!$.body)throw new Error(`failed to load external data file: ${y}, no response body.`);let P=$.body.getReader(),G;try{G=new ArrayBuffer(z)}catch(L){if(L instanceof RangeError){let V=Math.ceil(z/65536);G=new WebAssembly.Memory({initial:V,maximum:V}).buffer}else throw L}let N=0;for(;;){let{done:L,value:V}=await P.read();if(L)break;let Z=V.byteLength;new Uint8Array(G,N,Z).set(V),N+=Z}return new Uint8Array(G,0,z)}}else return y instanceof Blob?new Uint8Array(await y.arrayBuffer()):y instanceof Uint8Array?y:new Uint8Array(y)}}),$s,Ln,Bn,br,Nn,Un,Ze,Zt,Fn,Sr,H,Hr,Vn,xs=_(()=>{It(),Ki(),Qi(),Pe(),Qt(),mn(),Ts(),$s=(y,$)=>{ze()._OrtInit(y,$)!==0&&Ae("Can't initialize onnxruntime.")},Ln=async y=>{$s(y.wasm.numThreads,yn(y.logLevel))},Bn=async(y,$)=>{ze().asyncInit?.();let A=y.webgpu.adapter;if($==="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 z=y.webgpu.powerPreference;if(z!==void 0&&z!=="low-power"&&z!=="high-performance")throw new Error(`Invalid powerPreference setting: "${z}"`);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:z,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($==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},br=new Map,Nn=y=>{let $=ze(),A=$.stackSave();try{let z=$.PTR_SIZE,P=$.stackAlloc(2*z);$._OrtGetInputOutputCount(y,P,P+z)!==0&&Ae("Can't get session input/output count.");let G=z===4?"i32":"i64";return[Number($.getValue(P,G)),Number($.getValue(P+z,G))]}finally{$.stackRestore(A)}},Un=(y,$)=>{let A=ze(),z=A.stackSave(),P=0;try{let G=A.PTR_SIZE,N=A.stackAlloc(2*G);A._OrtGetInputOutputMetadata(y,$,N,N+G)!==0&&Ae("Can't get session input/output metadata.");let L=Number(A.getValue(N,"*"));P=Number(A.getValue(N+G,"*"));let V=A.HEAP32[P/4];if(V===0)return[L,0];let Z=A.HEAPU32[P/4+1],se=[];for(let J=0;J<Z;J++){let j=Number(A.getValue(P+8+J*G,"*"));se.push(j!==0?A.UTF8ToString(j):Number(A.getValue(P+8+(J+Z)*G,"*")))}return[L,V,se]}finally{A.stackRestore(z),P!==0&&A._OrtFree(P)}},Ze=y=>{let $=ze(),A=$._malloc(y.byteLength);if(A===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${y.byteLength}.`);return $.HEAPU8.set(y,A),[A,y.byteLength]},Zt=async(y,$)=>{let A,z,P=ze();Array.isArray(y)?[A,z]=y:y.buffer===P.HEAPU8.buffer?[A,z]=[y.byteOffset,y.byteLength]:[A,z]=Ze(y);let G=0,N=0,L=[],V=[],Z=[];try{if([N,L]=await Ss($),$?.externalData&&P.mountExternalData){let Ce=[];for(let He of $.externalData){let be=typeof He=="string"?He:He.path;Ce.push(_n(typeof He=="string"?He:He.data).then(Dt=>{P.mountExternalData(be,Dt)}))}await Promise.all(Ce)}for(let Ce of $?.executionProviders??[])if((typeof Ce=="string"?Ce:Ce.name)==="webnn"){if(P.shouldTransferToMLTensor=!1,typeof Ce!="string"){let He=Ce,be=He?.context,Dt=He?.gpuDevice,Bt=He?.deviceType,xr=He?.powerPreference;be?P.currentContext=be:Dt?P.currentContext=await P.webnnCreateMLContext(Dt):P.currentContext=await P.webnnCreateMLContext({deviceType:Bt,powerPreference:xr})}else P.currentContext=await P.webnnCreateMLContext();break}G=await P._OrtCreateSession(A,z,N),P.webgpuOnCreateSession?.(G),G===0&&Ae("Can't create a session."),P.jsepOnCreateSession?.(),P.currentContext&&(P.webnnRegisterMLContext(G,P.currentContext),P.currentContext=void 0,P.shouldTransferToMLTensor=!0);let[se,J]=Nn(G),j=!!$?.enableGraphCapture,Ee=[],F=[],le=[],vt=[],We=[];for(let Ce=0;Ce<se;Ce++){let[He,be,Dt]=Un(G,Ce);He===0&&Ae("Can't get an input name."),V.push(He);let Bt=P.UTF8ToString(He);Ee.push(Bt),le.push(be===0?{name:Bt,isTensor:!1}:{name:Bt,isTensor:!0,type:Yt(be),shape:Dt})}for(let Ce=0;Ce<J;Ce++){let[He,be,Dt]=Un(G,Ce+se);He===0&&Ae("Can't get an output name."),Z.push(He);let Bt=P.UTF8ToString(He);F.push(Bt),vt.push(be===0?{name:Bt,isTensor:!1}:{name:Bt,isTensor:!0,type:Yt(be),shape:Dt})}return br.set(G,[G,V,Z,null,j,!1]),[G,Ee,F,le,vt]}catch(se){throw V.forEach(J=>P._OrtFree(J)),Z.forEach(J=>P._OrtFree(J)),G!==0&&P._OrtReleaseSession(G)!==0&&Ae("Can't release session."),se}finally{P._free(A),N!==0&&P._OrtReleaseSessionOptions(N)!==0&&Ae("Can't release session options."),L.forEach(se=>P._free(se)),P.unmountExternalData?.()}},Fn=y=>{let $=ze(),A=br.get(y);if(!A)throw new Error(`cannot release session. invalid session id: ${y}`);let[z,P,G,N,L]=A;N&&(L&&$._OrtClearBoundOutputs(N.handle)!==0&&Ae("Can't clear bound outputs."),$._OrtReleaseBinding(N.handle)!==0&&Ae("Can't release IO binding.")),$.jsepOnReleaseSession?.(y),$.webnnOnReleaseSession?.(y),$.webgpuOnReleaseSession?.(y),P.forEach(V=>$._OrtFree(V)),G.forEach(V=>$._OrtFree(V)),$._OrtReleaseSession(z)!==0&&Ae("Can't release session."),br.delete(y)},Sr=async(y,$,A,z,P,G,N=!1)=>{if(!y){$.push(0);return}let L=ze(),V=L.PTR_SIZE,Z=y[0],se=y[1],J=y[3],j=J,Ee,F;if(Z==="string"&&(J==="gpu-buffer"||J==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(N&&J!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${G} when enableGraphCapture is true.`);if(J==="gpu-buffer"){let We=y[2].gpuBuffer;F=Jt(Xt(Z),se);{let Ce=L.jsepRegisterBuffer;if(!Ce)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Ee=Ce(z,G,We,F)}}else if(J==="ml-tensor"){let We=y[2].mlTensor;F=Jt(Xt(Z),se);let Ce=L.webnnRegisterMLTensor;if(!Ce)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Ee=Ce(z,We,Xt(Z),se)}else{let We=y[2];if(Array.isArray(We)){F=V*We.length,Ee=L._malloc(F),A.push(Ee);for(let Ce=0;Ce<We.length;Ce++){if(typeof We[Ce]!="string")throw new TypeError(`tensor data at index ${Ce} is not a string`);L.setValue(Ee+Ce*V,xt(We[Ce],A),"*")}}else{let Ce=L.webnnIsGraphInput,He=L.webnnIsGraphOutput;if(Z!=="string"&&Ce&&He){let be=L.UTF8ToString(P);if(Ce(z,be)||He(z,be)){let Dt=Xt(Z);F=Jt(Dt,se),j="ml-tensor";let Bt=L.webnnCreateTemporaryTensor,xr=L.webnnUploadTensor;if(!Bt||!xr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Xr=await Bt(z,Dt,se);xr(Xr,new Uint8Array(We.buffer,We.byteOffset,We.byteLength)),Ee=Xr}else F=We.byteLength,Ee=L._malloc(F),A.push(Ee),L.HEAPU8.set(new Uint8Array(We.buffer,We.byteOffset,F),Ee)}else F=We.byteLength,Ee=L._malloc(F),A.push(Ee),L.HEAPU8.set(new Uint8Array(We.buffer,We.byteOffset,F),Ee)}}let le=L.stackSave(),vt=L.stackAlloc(4*se.length);try{se.forEach((Ce,He)=>L.setValue(vt+He*V,Ce,V===4?"i32":"i64"));let We=L._OrtCreateTensor(Xt(Z),Ee,F,vt,se.length,Dn(j));We===0&&Ae(`Can't create tensor for input/output. session=${z}, index=${G}.`),$.push(We)}finally{L.stackRestore(le)}},H=async(y,$,A,z,P,G)=>{let N=ze(),L=N.PTR_SIZE,V=br.get(y);if(!V)throw new Error(`cannot run inference. invalid session id: ${y}`);let Z=V[0],se=V[1],J=V[2],j=V[3],Ee=V[4];V[5];let F=$.length,le=z.length,vt=0,We=[],Ce=[],He=[],be=[],Dt=[],Bt=N.stackSave(),xr=N.stackAlloc(F*L),Xr=N.stackAlloc(F*L),Jn=N.stackAlloc(le*L),Ps=N.stackAlloc(le*L);try{[vt,We]=ys(G),mt("wasm prepareInputOutputTensor");for(let je=0;je<F;je++)await Sr(A[je],Ce,be,y,se[$[je]],$[je],Ee);for(let je=0;je<le;je++)await Sr(P[je],He,be,y,J[z[je]],F+z[je],Ee);ct("wasm prepareInputOutputTensor");for(let je=0;je<F;je++)N.setValue(xr+je*L,Ce[je],"*"),N.setValue(Xr+je*L,se[$[je]],"*");for(let je=0;je<le;je++)N.setValue(Jn+je*L,He[je],"*"),N.setValue(Ps+je*L,J[z[je]],"*");N.jsepOnRunStart?.(Z),N.webnnOnRunStart?.(Z);let St;St=await N._OrtRun(Z,Xr,xr,F,Ps,le,Jn,vt),St!==0&&Ae("failed to call OrtRun().");let tr=[],Os=[];mt("wasm ProcessOutputTensor");for(let je=0;je<le;je++){let er=Number(N.getValue(Jn+je*L,"*"));if(er===He[je]||Dt.includes(He[je])){tr.push(P[je]),er!==He[je]&&N._OrtReleaseTensor(er)!==0&&Ae("Can't release tensor.");continue}let di=N.stackSave(),cr=N.stackAlloc(4*L),$n=!1,Ct,qt=0;try{N._OrtGetTensorData(er,cr,cr+L,cr+2*L,cr+3*L)!==0&&Ae(`Can't access output tensor data on index ${je}.`);let Zn=L===4?"i32":"i64",xn=Number(N.getValue(cr,Zn));qt=N.getValue(cr+L,"*");let zs=N.getValue(cr+L*2,"*"),ci=Number(N.getValue(cr+L*3,Zn)),Pt=[];for(let kt=0;kt<ci;kt++)Pt.push(Number(N.getValue(zs+kt*L,Zn)));N._OrtFree(zs)!==0&&Ae("Can't free memory for tensor dims.");let hr=Pt.reduce((kt,Tt)=>kt*Tt,1);Ct=Yt(xn);let Yr=j?.outputPreferredLocations[z[je]];if(Ct==="string"){if(Yr==="gpu-buffer"||Yr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let kt=[];for(let Tt=0;Tt<hr;Tt++){let rr=N.getValue(qt+Tt*L,"*"),hi=N.getValue(qt+(Tt+1)*L,"*"),pi=Tt===hr-1?void 0:hi-rr;kt.push(N.UTF8ToString(rr,pi))}tr.push([Ct,Pt,kt,"cpu"])}else if(Yr==="gpu-buffer"&&hr>0){let kt=N.jsepGetBuffer;if(!kt)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Tt=kt(qt),rr=Jt(xn,hr);if(rr===void 0||!wn(Ct))throw new Error(`Unsupported data type: ${Ct}`);$n=!0,tr.push([Ct,Pt,{gpuBuffer:Tt,download:N.jsepCreateDownloader(Tt,rr,Ct),dispose:()=>{N._OrtReleaseTensor(er)!==0&&Ae("Can't release tensor.")}},"gpu-buffer"])}else if(Yr==="ml-tensor"&&hr>0){let kt=N.webnnEnsureTensor,Tt=N.webnnIsGraphInputOutputTypeSupported;if(!kt||!Tt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Jt(xn,hr)===void 0||!vn(Ct))throw new Error(`Unsupported data type: ${Ct}`);if(!Tt(y,Ct,!1))throw new Error(`preferredLocation "ml-tensor" for ${Ct} output is not supported by current WebNN Context.`);let rr=await kt(y,qt,xn,Pt,!1);$n=!0,tr.push([Ct,Pt,{mlTensor:rr,download:N.webnnCreateMLTensorDownloader(qt,Ct),dispose:()=>{N.webnnReleaseTensorId(qt),N._OrtReleaseTensor(er)}},"ml-tensor"])}else if(Yr==="ml-tensor-cpu-output"&&hr>0){let kt=N.webnnCreateMLTensorDownloader(qt,Ct)(),Tt=tr.length;$n=!0,Os.push((async()=>{let rr=[Tt,await kt];return N.webnnReleaseTensorId(qt),N._OrtReleaseTensor(er),rr})()),tr.push([Ct,Pt,[],"cpu"])}else{let kt=gn(Ct),Tt=new kt(hr);new Uint8Array(Tt.buffer,Tt.byteOffset,Tt.byteLength).set(N.HEAPU8.subarray(qt,qt+Tt.byteLength)),tr.push([Ct,Pt,Tt,"cpu"])}}finally{N.stackRestore(di),Ct==="string"&&qt&&N._free(qt),$n||N._OrtReleaseTensor(er)}}j&&!Ee&&(N._OrtClearBoundOutputs(j.handle)!==0&&Ae("Can't clear bound outputs."),br.set(y,[Z,se,J,j,Ee,!1]));for(let[je,er]of await Promise.all(Os))tr[je][2]=er;return ct("wasm ProcessOutputTensor"),tr}finally{N.webnnOnRunEnd?.(Z),N.stackRestore(Bt),Ce.forEach(St=>N._OrtReleaseTensor(St)),He.forEach(St=>N._OrtReleaseTensor(St)),be.forEach(St=>N._free(St)),vt!==0&&N._OrtReleaseRunOptions(vt),We.forEach(St=>N._free(St))}},Hr=y=>{let $=ze(),A=br.get(y);if(!A)throw new Error("invalid session id");let z=A[0],P=$._OrtEndProfiling(z);P===0&&Ae("Can't get an profile file name."),$._OrtFree(P)},Vn=y=>{let $=[];for(let A of y){let z=A[2];!Array.isArray(z)&&"buffer"in z&&$.push(z.buffer)}return $}}),ur,Me,Tr,jr,Dr,Kr,bn,Sn,dr,$r,Gn,qn,Wn,Es,Cs,li,Qr,ks,Rs=_(()=>{It(),xs(),Qt(),cn(),ur=()=>!!ge.wasm.proxy&&typeof document<"u",Tr=!1,jr=!1,Dr=!1,Sn=new Map,dr=(y,$)=>{let A=Sn.get(y);A?A.push($):Sn.set(y,[$])},$r=()=>{if(Tr||!jr||Dr||!Me)throw new Error("worker not ready")},Gn=y=>{switch(y.data.type){case"init-wasm":Tr=!1,y.data.err?(Dr=!0,bn[1](y.data.err)):(jr=!0,bn[0]()),Kr&&(URL.revokeObjectURL(Kr),Kr=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let $=Sn.get(y.data.type);y.data.err?$.shift()[1](y.data.err):$.shift()[0](y.data.out);break}}},qn=async()=>{if(!jr){if(Tr)throw new Error("multiple calls to 'initWasm()' detected.");if(Dr)throw new Error("previous call to 'initWasm()' failed.");if(Tr=!0,ur())return new Promise((y,$)=>{Me?.terminate(),hs().then(([A,z])=>{try{Me=z,Me.onerror=G=>$(G),Me.onmessage=Gn,bn=[y,$];let P={type:"init-wasm",in:ge};if(!P.in.wasm.wasmPaths&&A){let G=on();G&&(P.in.wasm.wasmPaths=G)}Me.postMessage(P),Kr=A}catch(P){$(P)}},$)});try{await fn(ge.wasm),await Ln(ge),jr=!0}catch(y){throw Dr=!0,y}finally{Tr=!1}}},Wn=async y=>{if(ur())return $r(),new Promise(($,A)=>{dr("init-ep",[$,A]);let z={type:"init-ep",in:{epName:y,env:ge}};Me.postMessage(z)});await Bn(ge,y)},Es=async y=>ur()?($r(),new Promise(($,A)=>{dr("copy-from",[$,A]);let z={type:"copy-from",in:{buffer:y}};Me.postMessage(z,[y.buffer])})):Ze(y),Cs=async(y,$)=>{if(ur()){if($?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return $r(),new Promise((A,z)=>{dr("create",[A,z]);let P={type:"create",in:{model:y,options:{...$}}},G=[];y instanceof Uint8Array&&G.push(y.buffer),Me.postMessage(P,G)})}else return Zt(y,$)},li=async y=>{if(ur())return $r(),new Promise(($,A)=>{dr("release",[$,A]);let z={type:"release",in:y};Me.postMessage(z)});Fn(y)},Qr=async(y,$,A,z,P,G)=>{if(ur()){if(A.some(N=>N[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(P.some(N=>N))throw new Error("pre-allocated output tensor is not supported for proxy.");return $r(),new Promise((N,L)=>{dr("run",[N,L]);let V=A,Z={type:"run",in:{sessionId:y,inputIndices:$,inputs:V,outputIndices:z,options:G}};Me.postMessage(Z,Vn(V))})}else return H(y,$,A,z,P,G)},ks=async y=>{if(ur())return $r(),new Promise(($,A)=>{dr("end-profiling",[$,A]);let z={type:"end-profiling",in:y};Me.postMessage(z)});Hr(y)}}),As,Hn,jn,Kn=_(()=>{It(),Rs(),Pe(),nn(),Ts(),As=(y,$)=>{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 ${$()}`)}},Hn=y=>{switch(y[3]){case"cpu":return new xe(y[0],y[2],y[1]);case"gpu-buffer":{let $=y[0];if(!wn($))throw new Error(`not supported data type: ${$} for deserializing GPU tensor`);let{gpuBuffer:A,download:z,dispose:P}=y[2];return xe.fromGpuBuffer(A,{dataType:$,dims:y[1],download:z,dispose:P})}case"ml-tensor":{let $=y[0];if(!vn($))throw new Error(`not supported data type: ${$} for deserializing MLTensor tensor`);let{mlTensor:A,download:z,dispose:P}=y[2];return xe.fromMLTensor(A,{dataType:$,dims:y[1],download:z,dispose:P})}default:throw new Error(`invalid data location: ${y[3]}`)}},jn=class{async fetchModelAndCopyToWasmMemory(y){return Es(await _n(y))}async loadModel(y,$){fe();let A;typeof y=="string"?A=await this.fetchModelAndCopyToWasmMemory(y):A=y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Cs(A,$),Ue()}async dispose(){return li(this.sessionId)}async run(y,$,A){fe();let z=[],P=[];Object.entries(y).forEach(J=>{let j=J[0],Ee=J[1],F=this.inputNames.indexOf(j);if(F===-1)throw new Error(`invalid input '${j}'`);z.push(Ee),P.push(F)});let G=[],N=[];Object.entries($).forEach(J=>{let j=J[0],Ee=J[1],F=this.outputNames.indexOf(j);if(F===-1)throw new Error(`invalid output '${j}'`);G.push(Ee),N.push(F)});let L=z.map((J,j)=>As(J,()=>`input "${this.inputNames[P[j]]}"`)),V=G.map((J,j)=>J?As(J,()=>`output "${this.outputNames[N[j]]}"`):null),Z=await Qr(this.sessionId,P,L,N,V,A),se={};for(let J=0;J<Z.length;J++)se[this.outputNames[N[J]]]=G[J]??Hn(Z[J]);return Ue(),se}startProfiling(){}endProfiling(){ks(this.sessionId)}}}),Tn={};U(Tn,{OnnxruntimeWebAssemblyBackend:()=>Xn,initializeFlags:()=>Qn,wasmBackend:()=>Yn});var Qn,Xn,Yn,Ms=_(()=>{It(),Rs(),Kn(),Qn=()=>{(typeof ge.wasm.initTimeout!="number"||ge.wasm.initTimeout<0)&&(ge.wasm.initTimeout=0);let y=ge.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.`),ge.wasm.simd=!1),typeof ge.wasm.proxy!="boolean"&&(ge.wasm.proxy=!1),typeof ge.wasm.trace!="boolean"&&(ge.wasm.trace=!1),typeof ge.wasm.numThreads!="number"||!Number.isInteger(ge.wasm.numThreads)||ge.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)ge.wasm.numThreads=1;else{let $=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;ge.wasm.numThreads=Math.min(4,Math.ceil(($||1)/2))}},Xn=class{async init(y){Qn(),await qn(),await Wn(y)}async createInferenceSessionHandler(y,$){let A=new jn;return await A.loadModel(y,$),A}},Yn=new Xn}),Is={};U(Is,{InferenceSession:()=>rn,TRACE:()=>$t,TRACE_EVENT_BEGIN:()=>mt,TRACE_EVENT_END:()=>ct,TRACE_FUNC_BEGIN:()=>fe,TRACE_FUNC_END:()=>Ue,Tensor:()=>xe,default:()=>Xi,env:()=>ge,registerBackend:()=>ie}),It(),It(),It();var ui="1.24.3",Xi=ss;{let y=(Ms(),te(Tn)).wasmBackend;ie("cpu",y,10),ie("wasm",y,10)}return Object.defineProperty(ge.versions,"web",{value:ui,enumerable:!0}),te(Is)})();c.exports=n})(ao)),ao.exports}var zp;function ky(){return zp||(zp=1,(function(c){var r=Fr&&Fr.__createBinding||(Object.create?(function(oe,ne,me,pe){pe===void 0&&(pe=me);var Ne=Object.getOwnPropertyDescriptor(ne,me);(!Ne||("get"in Ne?!ne.__esModule:Ne.writable||Ne.configurable))&&(Ne={enumerable:!0,get:function(){return ne[me]}}),Object.defineProperty(oe,pe,Ne)}):(function(oe,ne,me,pe){pe===void 0&&(pe=me),oe[pe]=ne[me]})),n=Fr&&Fr.__setModuleDefault||(Object.create?(function(oe,ne){Object.defineProperty(oe,"default",{enumerable:!0,value:ne})}):function(oe,ne){oe.default=ne}),a=Fr&&Fr.__importStar||function(oe){if(oe&&oe.__esModule)return oe;var ne={};if(oe!=null)for(var me in oe)me!=="default"&&Object.prototype.hasOwnProperty.call(oe,me)&&r(ne,oe,me);return n(ne,oe),ne};Object.defineProperty(c,"__esModule",{value:!0}),c.MicVAD=c.getDefaultRealTimeVADOptions=c.ort=c.DEFAULT_MODEL=void 0;const f=a(Cy()),v=Ro(),C=Ao(),R=ai(),_=Ui(),U=hf(),B=pf();c.DEFAULT_MODEL="legacy",c.ort=f;const te="vad.worklet.bundle.min.js",Q="silero_vad_v5.onnx",ee="silero_vad_legacy.onnx",ie=oe=>({...C.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{R.log.debug("VAD misfire")},onSpeechStart:()=>{R.log.debug("Detected speech start")},onSpeechEnd:()=>{R.log.debug("Detected speech end")},onSpeechRealStart:()=>{R.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:oe,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async ne=>{ne.getTracks().forEach(me=>{me.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:ne=>{ne.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});c.getDefaultRealTimeVADOptions=ie;const ce=oe=>"audioWorklet"in oe&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function ue(oe,ne,me,pe,Ne){await me.audioWorklet.addModule(oe),ne.processorOptions={...ne.processorOptions??{},frameSamples:pe};const ge=new AudioWorkletNode(me,"vad-helper-worklet",ne);return ge.port.onmessage=async rt=>{const Xe=rt.data;if(!(typeof Xe=="object"&&Xe&&"message"in Xe)){console.error("Invalid message event",Xe);return}switch(Xe.message){case _.Message.AudioFrame:{if(!("data"in Xe&&Xe.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const ft=new Float32Array(Xe.data);await Ne(ft);break}}},ge}async function Be(oe,ne,me){const pe=new B.Resampler({nativeSampleRate:oe.sampleRate,targetSampleRate:16e3,targetFrameSize:ne});R.log.debug("using script processor");const ge=oe.createScriptProcessor(4096,1,1);let rt=!1;return ge.onaudioprocess=async Xe=>{if(!rt){rt=!0;try{const ft=Xe.inputBuffer.getChannelData(0);Xe.outputBuffer.getChannelData(0).fill(0);const Ye=pe.process(ft);for(const st of Ye)await me(st)}catch(ft){console.error("Error processing audio:",ft)}finally{rt=!1}}},ge.connect(oe.destination),ge}class Te{constructor(ne,me,pe,Ne,ge=!1,rt=null,Xe=null,ft=null,Ge=null,Ye=null,st=null,bt="uninitialized",ut=!1){this.options=ne,this.frameProcessor=me,this.model=pe,this.frameSamples=Ne,this.listening=ge,this.errored=rt,this._stream=Xe,this._audioContext=ft,this._vadNode=Ge,this._mediaStreamAudioSourceNode=Ye,this._audioProcessorAdapterType=st,this.initializationState=bt,this.ownsAudioContext=ut,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"?ce(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await ue(this.options.baseAssetPath+te,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await Be(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:qe}=this.getAudioInstances();this._stream=await this.options.resumeStream(Je);const et=new MediaStreamAudioSourceNode(Le,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=et,et.connect(qe);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(_.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 _.Message.FrameProcessed:this.options.onFrameProcessed(Je.probs,Je.frame);break;case _.Message.SpeechStart:this.options.onSpeechStart();break;case _.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case _.Message.VADMisfire:this.options.onVADMisfire();break;case _.Message.SpeechEnd:this.options.onSpeechEnd(Je.audio);break}}}static async new(ne={}){const me={...(0,c.getDefaultRealTimeVADOptions)(ne.model??c.DEFAULT_MODEL),...ne};(0,C.validateOptions)(me),c.ort.env.wasm.wasmPaths=me.onnxWASMBasePath,me.ortConfig!==void 0&&me.ortConfig(c.ort);const pe=me.model==="v5"?Q:ee,Ne=me.baseAssetPath+pe,ge=me.model==="v5"?U.SileroV5.new:U.SileroLegacy.new;let rt;try{rt=await ge(c.ort,()=>(0,v.defaultModelFetcher)(Ne))}catch(st){throw console.error(`Encountered an error while loading model file ${Ne}`),st}const Xe=me.model==="v5"?512:1536,ft=Xe/16,Ge=new C.FrameProcessor(rt.process,rt.reset_state,{positiveSpeechThreshold:me.positiveSpeechThreshold,negativeSpeechThreshold:me.negativeSpeechThreshold,redemptionMs:me.redemptionMs,preSpeechPadMs:me.preSpeechPadMs,minSpeechMs:me.minSpeechMs,submitUserSpeechOnPause:me.submitUserSpeechOnPause},ft),Ye=new Te(me,Ge,rt,Xe);if(me.startOnLoad)try{await Ye.start()}catch(st){throw console.error("Error starting micVad",st),st}return Ye}}c.MicVAD=Te})(Fr)),Fr}var Dp;function Lp(){return Dp||(Dp=1,(function(c){Object.defineProperty(c,"__esModule",{value:!0}),c.getDefaultRealTimeVADOptions=c.MicVAD=c.DEFAULT_MODEL=c.utils=c.NonRealTimeVAD=c.Message=c.FrameProcessor=c.defaultModelFetcher=c.baseAssetPath=void 0;var r=uf();Object.defineProperty(c,"baseAssetPath",{enumerable:!0,get:function(){return r.baseAssetPath}});var n=Ro();Object.defineProperty(c,"defaultModelFetcher",{enumerable:!0,get:function(){return n.defaultModelFetcher}});var a=Ao();Object.defineProperty(c,"FrameProcessor",{enumerable:!0,get:function(){return a.FrameProcessor}});var f=Ui();Object.defineProperty(c,"Message",{enumerable:!0,get:function(){return f.Message}});var v=xy();Object.defineProperty(c,"NonRealTimeVAD",{enumerable:!0,get:function(){return v.NonRealTimeVAD}});const C=Ey();c.utils={audioFileToArray:C.audioFileToArray,minFramesForTargetMS:C.minFramesForTargetMS,arrayBufferToBase64:C.arrayBufferToBase64,encodeWAV:C.encodeWAV};var R=ky();Object.defineProperty(c,"DEFAULT_MODEL",{enumerable:!0,get:function(){return R.DEFAULT_MODEL}}),Object.defineProperty(c,"MicVAD",{enumerable:!0,get:function(){return R.MicVAD}}),Object.defineProperty(c,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return R.getDefaultRealTimeVADOptions}})})(no)),no}var Bp;function Ry(){return Bp||(Bp=1,(function(c){Object.defineProperty(c,"__esModule",{value:!0}),c.useMicVAD=c.getDefaultReactRealTimeVADOptions=c.utils=void 0;const r=Lp(),n=he;var a=Lp();Object.defineProperty(c,"utils",{enumerable:!0,get:function(){return a.utils}});const f={userSpeakingThreshold:.6},v=_=>({...(0,r.getDefaultRealTimeVADOptions)(_),...f});c.getDefaultReactRealTimeVADOptions=v;function C(_){const U=_.model??r.DEFAULT_MODEL,B={...(0,c.getDefaultReactRealTimeVADOptions)(U),..._},te={userSpeakingThreshold:B.userSpeakingThreshold},Q={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&&(Q.ortConfig=B.ortConfig),B.audioContext&&(Q.audioContext=B.audioContext),[te,Q]}function R(_){const[U,B]=C(_),te=_.model??r.DEFAULT_MODEL,[Q,ee]=(0,n.useState)(!1),[ie,ce]=(0,n.useState)(!0),[ue,Be]=(0,n.useState)(!1),[Te,oe]=(0,n.useState)(!1),[ne,me]=(0,n.useState)(null),pe=(0,n.useRef)(B.onFrameProcessed),Ne=(0,n.useRef)(B.onSpeechEnd),ge=(0,n.useRef)(B.onSpeechStart),rt=(0,n.useRef)(B.onSpeechRealStart),Xe=(0,n.useRef)(B.onVADMisfire),ft=(0,n.useRef)(B.getStream);(0,n.useEffect)(()=>{pe.current=B.onFrameProcessed,Ne.current=B.onSpeechEnd,ge.current=B.onSpeechStart,rt.current=B.onSpeechRealStart,Xe.current=B.onVADMisfire},[B.onFrameProcessed,B.onSpeechEnd,B.onSpeechStart,B.onSpeechRealStart,B.onVADMisfire]),(0,n.useEffect)(()=>{ft.current=B.getStream},[B.getStream]);const Ge=B.getStream.toString();(0,n.useEffect)(()=>{let ut=null,Je=!1;return(async()=>{try{ce(!0),Be(!1);const qe={...B,onFrameProcessed:(et,Y)=>{const Ie=et.isSpeech>U.userSpeakingThreshold;ee(Ie),pe.current(et,Y)},onSpeechEnd:et=>{Ne.current(et)},onSpeechStart:()=>{ge.current()},onSpeechRealStart:()=>{rt.current()},onVADMisfire:()=>{Xe.current()},getStream:()=>ft.current()};if(ut=await r.MicVAD.new(qe),Je){await ut.destroy();return}me(ut),B.startOnLoad&&(await ut.start(),oe(!0)),ce(!1)}catch(qe){ce(!1),qe instanceof Error?Be(qe.message):Be(String(qe))}})().catch(()=>{}),function(){Je=!0,ut&&ut.destroy(),!ie&&!ue&&oe(!1)}},[Ge,te]);const Ye=(0,n.useCallback)(async()=>{!ie&&!ue&&(await ne?.pause(),oe(!1))},[ie,ue,ne]),st=(0,n.useCallback)(async()=>{!ie&&!ue&&(await ne?.start(),oe(!0))},[ie,ue,ne]),bt=(0,n.useCallback)(async()=>{Te?await Ye():await st()},[Te,Ye,st]);return{listening:Te,errored:ue,loading:ie,userSpeaking:Q,pause:Ye,start:st,toggle:bt}}c.useMicVAD=R})(ro)),ro}var Ay=Ry();lf();const Np={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},zi=16e3,mf=512,gf=700,My=300,Iy=mf/zi*1e3,Py=Math.ceil(gf/Iy);function Oy(c={}){const{onAudioChunk:r,onAudioEnd:n,onSpeechStart:a,onSpeechEnd:f,onVADMisfire:v,onError:C,interruptOnSpeechStart:R=!0,forceAudioMp4:_=!1}=c,{sendAudioChunk:U,endAudioStream:B,interrupt:te}=qr(),[Q,ee]=he.useState(!1),[ie,ce]=he.useState(null),ue=he.useRef(null),Be=he.useRef(null),Te=he.useRef(null),oe=he.useRef(!1),ne=he.useRef(null),me=he.useRef([]),pe=he.useCallback(()=>{if(!(typeof window>"u")){if(!Te.current){const Le=window.AudioContext||window.webkitAudioContext;if(!Le)return;Te.current=new Le({sampleRate:zi})}Te.current.state==="suspended"&&Te.current.resume().catch(()=>{})}},[]);he.useEffect(()=>{typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||navigator.mediaDevices.getUserMedia({audio:Np}).then(Le=>{ue.current=Le,ce(null)}).catch(Le=>{ce("permission_denied"),C?.(Le)})},[C]);const Ne=he.useCallback(async()=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone APIs are unavailable in this browser");if(ue.current&&ue.current.getTracks()[0]?.readyState==="live")return ue.current;const Le=await navigator.mediaDevices.getUserMedia({audio:Np});return ue.current=Le,ce(null),Le},[]),ge=he.useCallback(async Le=>{Le.getTracks().forEach(qe=>{qe.enabled=!1})},[]),rt=he.useCallback(async()=>ue.current&&ue.current.getTracks()[0]?.readyState==="live"?(ue.current.getTracks().forEach(Le=>{Le.enabled=!0}),ue.current):Ne(),[Ne]),Xe=he.useCallback(()=>{const Le=me.current;if(!Le.length)return{samples:new Float32Array(0),duration:0};const qe=Le.reduce((Ie,tt)=>Ie+tt.length,0),et=new Float32Array(qe);let Y=0;for(const Ie of Le)et.set(Ie,Y),Y+=Ie.length;return{samples:et,duration:qe/zi}},[]),ft=he.useCallback(()=>{const Le=ue.current,qe=Te.current;if(!Le||!qe||Be.current)return;const{samples:et,duration:Y}=Xe();me.current=[];const Ie=!_&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/mp4")?"audio/mp4":"";try{const tt=qe.createMediaStreamDestination();if(et.length>0){const Et=qe.createBuffer(1,et.length,zi);Et.getChannelData(0).set(et);const dt=qe.createBufferSource();dt.buffer=Et,dt.connect(tt),dt.start(0)}const gt=qe.createMediaStreamSource(Le);if(Y>0){const Et=qe.createDelay(Y+.1);Et.delayTime.value=Y,gt.connect(Et).connect(tt)}else gt.connect(tt);const Vt=new MediaRecorder(tt.stream,Ie?{mimeType:Ie}:{});Vt.ondataavailable=async Et=>{if(!Et.data||Et.data.size<=0)return;const dt=await Et.data.arrayBuffer();r?r(dt):U(dt)},Be.current=Vt,Vt.start(100)}catch(tt){C?.(tt)}},[Xe,_,r,C,U]),Ge=he.useCallback(()=>{const Le=Be.current;if(Le){if(Be.current=null,Le.state==="inactive"){n?n():B();return}Le.onstop=()=>{n?n():B()},Le.stop()}},[B,n]),Ye=he.useCallback(()=>{const Le=Be.current;if(Le&&(Be.current=null,Le.state!=="inactive"))try{Le.stop()}catch{}},[]),st=he.useCallback(()=>{Te.current&&(Te.current.close().catch(()=>{}),Te.current=null)},[]),bt=he.useCallback(()=>{ue.current&&(ue.current.getTracks().forEach(Le=>Le.stop()),ue.current=null)},[]),ut=Ay.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:gf,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:mf}},baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.30/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.1/dist/",ortConfig:Le=>{Le.env.wasm.numThreads=1,Le.env.logLevel="error"},getStream:Ne,pauseStream:ge,resumeStream:rt,onFrameProcessed:(Le,qe)=>{if(!qe)return;const et=me.current;et.push(new Float32Array(qe)),et.length>Py&&et.shift()},onSpeechStart:()=>{oe.current||(ne.current&&(clearTimeout(ne.current),ne.current=null),ee(!0),R&&te(),ft(),a?.())},onSpeechEnd:()=>{ne.current=setTimeout(()=>{ee(!1),Ge(),oe.current=!0,setTimeout(()=>{oe.current=!1},300),f?.()},My)},onVADMisfire:()=>{ne.current&&(clearTimeout(ne.current),ne.current=null),ee(!1),Ye(),v?.()}}),Je=he.useCallback(()=>{pe(),ut.listening&&Be.current&&(ne.current&&(clearTimeout(ne.current),ne.current=null),ee(!1),Ge()),ut.toggle()},[Ge,pe,ut]);return he.useEffect(()=>()=>{ne.current&&clearTimeout(ne.current),Ye(),st(),bt()},[st,bt,Ye]),{isListening:ut.listening,isLoading:ut.loading,isSpeaking:Q,micError:ie,toggle:Je,start:ut.start,pause:ut.pause,userSpeaking:ut.userSpeaking}}const zy=()=>qr(),yf=()=>{const{connectionState:c,isConnected:r,isSessionReady:n,error:a,reconnectAttempt:f,session:v,initializeSession:C,joinDesktopSession:R,disconnect:_,interrupt:U,refreshSessionActivity:B,clearSessionHistory:te,changeSessionLanguage:Q}=qr();return{connectionState:c,isConnected:r,isSessionReady:n,error:a,reconnectAttempt:f,session:v,initializeSession:C,joinDesktopSession:R,disconnect:_,interrupt:U,refreshSessionActivity:B,clearSessionHistory:te,changeSessionLanguage:Q}},Dy=()=>{const{messages:c,sendTextMessage:r,clearMessages:n}=qr();return{messages:c,sendTextMessage:r,clearMessages:n}},Ly=()=>{const{sendAudioChunk:c,endAudioStream:r,isAudioPlaying:n,transcript:a,partialTranscript:f,interrupt:v,resumeAudioPlayback:C,attachAudioElement:R}=qr();return{sendAudioChunk:c,endAudioStream:r,isAudioPlaying:n,transcript:a,partialTranscript:f,interrupt:v,resumeAudioPlayback:C,attachAudioElement:R}},wf=()=>{const{session:c,isAvatarSpeaking:r,cloudStream:n,setCloudStreamState:a}=qr(),f=n?.state||Kt.IDLE;return{streamingUrl:c.streamingUrl,isAvatarSpeaking:r,speakingSource:"avatar_events",isCloudAvatar:c.agentType===Vr.CLOUD_AVATAR,isDesktopAvatar:c.agentType===Vr.DESKTOP_AVATAR,cloudStreamState:f,cloudStreamError:n?.error||null,isCloudStreamConnected:f===Kt.CONNECTED,isCloudStreamLoading:f===Kt.CONNECTING||f===Kt.LOADING,setCloudStreamState:a}},By=c=>{const{attachAudioElement:r,resumeAudioPlayback:n}=qr();he.useEffect(()=>{if(!c?.current)return;r(c.current);const a=()=>{n()},f=c.current;return f.addEventListener("click",a),f.addEventListener("touchstart",a),()=>{f.removeEventListener("click",a),f.removeEventListener("touchstart",a),r(null)}},[r,c,n])};function Ny({connect:c=!0,session:r,onError:n,onInitialized:a,children:f}){const{initializeSession:v,joinDesktopSession:C,disconnect:R}=yf(),_=he.useRef(!1);return he.useEffect(()=>{if(!c||_.current)return;let U=!1;return _.current=!0,(async()=>{try{if(r?.mode==="join_desktop"){const Q=await C({uniqueId:r.uniqueId});U||a?.(Q);return}const te=await v({apiKey:r?.apiKey,publicChatId:r?.publicChatId,agentId:r?.agentId,language:r?.language||"en"});U||a?.(te)}catch(te){U||n?.(te)}})(),()=>{U=!0,R(),_.current=!1}},[c,R,v,C,n,a,r]),f}function Uy({children:c,wsUrl:r,restUrl:n,session:a,connect:f=!0,reconnectOptions:v,enableAudio:C=!0,pcmOptions:R,debug:_=!1,onError:U,onInitialized:B}){return sr.jsx(of,{wsUrl:r,restUrl:n,reconnectOptions:v,enableAudio:C,pcmOptions:R,debug:_,children:sr.jsx(Ny,{connect:f,session:a,onError:U,onInitialized:B,children:c})})}var oo={exports:{}},Up;function Fy(){return Up||(Up=1,(function(c){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
2859
|
`).map(a=>a.trim())},r.splitSections=function(n){return n.split(`
|
|
2860
2860
|
m=`).map((f,v)=>(v>0?"m="+f:f).trim()+`\r
|
|
2861
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
|
|
@@ -2868,14 +2868,14 @@ m=`).map((f,v)=>(v>0?"m="+f:f).trim()+`\r
|
|
|
2868
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
2869
|
a=ice-pwd:`+n.password+`\r
|
|
2870
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
|
|
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 _=v[R],U=r.matchPrefix(n,"a=rtpmap:"+_+" ")[0];if(U){const B=r.parseRtpMap(U),te=r.matchPrefix(n,"a=fmtp:"+_+" ");switch(B.parameters=te.length?r.parseFmtp(te[0]):{},B.rtcpFeedback=r.matchPrefix(n,"a=rtcp-fb:"+_+" ").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 C=r.matchPrefix(n,"a=rtcp-fb:* ").map(r.parseRtcpFb);return a.codecs.forEach(R=>{C.forEach(_=>{R.rtcpFeedback.find(B=>B.type===_.type&&B.parameter===_.parameter)||R.rtcpFeedback.push(_)})}),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(C=>C.preferredPayloadType!==void 0?C.preferredPayloadType:C.payloadType).join(" ")+`\r
|
|
2872
2872
|
`,f+=`c=IN IP4 0.0.0.0\r
|
|
2873
2873
|
`,f+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
2874
2874
|
`,a.codecs.forEach(C=>{f+=r.writeRtpMap(C),f+=r.writeFmtp(C),f+=r.writeRtcpFb(C)});let v=0;return a.codecs.forEach(C=>{C.maxptime>v&&(v=C.maxptime)}),v>0&&(f+="a=maxptime:"+v+`\r
|
|
2875
|
-
`),a.headerExtensions&&a.headerExtensions.forEach(C=>{f+=r.writeExtmap(C)}),f},r.parseRtpEncodingParameters=function(n){const a=[],f=r.parseRtpParameters(n),v=f.fecMechanisms.indexOf("RED")!==-1,C=f.fecMechanisms.indexOf("ULPFEC")!==-1,R=r.matchPrefix(n,"a=ssrc:").map(
|
|
2875
|
+
`),a.headerExtensions&&a.headerExtensions.forEach(C=>{f+=r.writeExtmap(C)}),f},r.parseRtpEncodingParameters=function(n){const a=[],f=r.parseRtpParameters(n),v=f.fecMechanisms.indexOf("RED")!==-1,C=f.fecMechanisms.indexOf("ULPFEC")!==-1,R=r.matchPrefix(n,"a=ssrc:").map(Q=>r.parseSsrcMedia(Q)).filter(Q=>Q.attribute==="cname"),_=R.length>0&&R[0].ssrc;let U;const B=r.matchPrefix(n,"a=ssrc-group:FID").map(Q=>Q.substring(17).split(" ").map(ie=>parseInt(ie,10)));B.length>0&&B[0].length>1&&B[0][0]===_&&(U=B[0][1]),f.codecs.forEach(Q=>{if(Q.name.toUpperCase()==="RTX"&&Q.parameters.apt){let ee={ssrc:_,codecPayloadType:parseInt(Q.parameters.apt,10)};_&&U&&(ee.rtx={ssrc:U}),a.push(ee),v&&(ee=JSON.parse(JSON.stringify(ee)),ee.fec={ssrc:_,mechanism:C?"red+ulpfec":"red"},a.push(ee))}}),a.length===0&&_&&a.push({ssrc:_});let te=r.matchPrefix(n,"b=");return te.length&&(te[0].indexOf("b=TIAS:")===0?te=parseInt(te[0].substring(7),10):te[0].indexOf("b=AS:")===0?te=parseInt(te[0].substring(5),10)*1e3*.95-2e3*8:te=void 0,a.forEach(Q=>{Q.maxBitrate=te})),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 C=r.matchPrefix(n,"a=rtcp-mux");return a.mux=C.length>0,a},r.writeRtcpParameters=function(n){let a="";return n.reducedSize&&(a+=`a=rtcp-rsize\r
|
|
2876
2876
|
`),n.mux&&(a+=`a=rtcp-mux\r
|
|
2877
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(C=>r.parseSsrcMedia(C)).filter(C=>C.attribute==="msid");if(v.length>0)return a=v[0].value.split(" "),{stream:a[0],track:a[1]}},r.parseSctpDescription=function(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 C=r.matchPrefix(n,"a=sctp-port:");if(C.length>0)return{port:parseInt(C[0].substring(12),10),protocol:a.fmt,maxMessageSize:v};const R=r.matchPrefix(n,"a=sctpmap:");if(R.length>0){const
|
|
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(C=>r.parseSsrcMedia(C)).filter(C=>C.attribute==="msid");if(v.length>0)return a=v[0].value.split(" "),{stream:a[0],track:a[1]}},r.parseSctpDescription=function(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 C=r.matchPrefix(n,"a=sctp-port:");if(C.length>0)return{port:parseInt(C[0].substring(12),10),protocol:a.fmt,maxMessageSize:v};const R=r.matchPrefix(n,"a=sctpmap:");if(R.length>0){const _=R[0].substring(10).split(" ");return{port:parseInt(_[0],10),protocol:_[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
2879
|
`,`c=IN IP4 0.0.0.0\r
|
|
2880
2880
|
`,"a=sctp-port:"+a.port+`\r
|
|
2881
2881
|
`]:f=["m="+n.kind+" 9 "+n.protocol+" "+a.port+`\r
|
|
@@ -2886,28 +2886,28 @@ a=ice-pwd:`+n.password+`\r
|
|
|
2886
2886
|
o=`+(f||"thisisadapterortc")+" "+v+" "+C+` IN IP4 127.0.0.1\r
|
|
2887
2887
|
s=-\r
|
|
2888
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},c.exports=r})(oo)),oo.exports}var Fp=Fy(),
|
|
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},c.exports=r})(oo)),oo.exports}var Fp=Fy(),_r,Mt,Di={d:(c,r)=>{for(var n in r)Di.o(r,n)&&!Di.o(c,n)&&Object.defineProperty(c,n,{enumerable:!0,get:r[n]})},o:(c,r)=>Object.prototype.hasOwnProperty.call(c,r)},Se={};Di.d(Se,{Dz:()=>tm,g$:()=>$f,Lt:()=>Sf,Q9:()=>Tf,qf:()=>_o,hV:()=>am,z$:()=>Ow,J0:()=>So,De:()=>ow,$C:()=>zn,al:()=>Pf,_W:()=>Of,Gv:()=>Kf,m:()=>Qf,tz:()=>If,Nu:()=>sm,zg:()=>um,vp:()=>em,vU:()=>K,wF:()=>Gf,rv:()=>rm,Nh:()=>nm,ss:()=>lm,qW:()=>Xf,QL:()=>jf,cf:()=>cm,eM:()=>Vf,Yd:()=>T,Tk:()=>$e,iM:()=>vf,qy:()=>Wr,ce:()=>Yy,sK:()=>we,Ok:()=>_t,q5:()=>im,g:()=>Pw,xl:()=>Uf,I:()=>Ff,bx:()=>bo,dD:()=>Jf,Ib:()=>oi,Az:()=>At,Iw:()=>kr,qY:()=>vo,db:()=>bf,mR:()=>ii,Tn:()=>wo,rV:()=>qf,gh:()=>Df,Mi:()=>Lf,j:()=>Bf,YB:()=>Nf,Yt:()=>Hf,i5:()=>Wf,x_:()=>Gr,Am:()=>To,eR:()=>xf,r8:()=>zf,u3:()=>dm,vd:()=>Cf,iV:()=>Rf,jZ:()=>kf,SW:()=>Mf,ZH:()=>Af,Ni:()=>hm,lh:()=>Ef,ZP:()=>Zf,bq:()=>_f,$f:()=>pm,eu:()=>Yf,Ax:()=>rw,Mc:()=>tw});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
2890
|
Msg: ${n}
|
|
2891
2891
|
Caller: ${r}`;console.log(f)}static Info(r,n,a){if(a>this.verboseLogLevel)return;const f=`Level: Info
|
|
2892
2892
|
Msg: ${n}`;console.info(f)}static Error(r,n){const a=`Level: Error
|
|
2893
2893
|
Msg: ${n}
|
|
2894
2894
|
Caller: ${r}`;console.error(a)}static Warning(r,n){const a=`Level: Warning
|
|
2895
2895
|
Caller: ${r}
|
|
2896
|
-
Msg: ${n}`;console.warn(a)}}T.verboseLogLevel=5,(function(c){c.LIST_STREAMERS="listStreamers",c.SUBSCRIBE="subscribe",c.UNSUBSCRIBE="unsubscribe",c.ICE_CANDIDATE="iceCandidate",c.OFFER="offer",c.ANSWER="answer",c.DATACHANNELREQUEST="dataChannelRequest",c.SFURECVDATACHANNELREADY="peerDataChannelsReady",c.PONG="pong"})(
|
|
2897
|
-
`+JSON.stringify(this,this.sendFilter,4),6),JSON.stringify(this,this.sendFilter)}}class Vy extends
|
|
2898
|
-
`+JSON.stringify(this,void 0,4),6),JSON.stringify(this)}}(function(c){c.CONFIG="config",c.STREAMER_LIST="streamerList",c.STREAMER_ID_CHANGED="streamerIDChanged",c.PLAYER_COUNT="playerCount",c.OFFER="offer",c.ANSWER="answer",c.ICE_CANDIDATE="iceCandidate",c.PEER_DATA_CHANNELS="peerDataChannels",c.PING="ping",c.WARNING="warning"})(
|
|
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 Vy;this.webSocket.send(r.payload())}sendSubscribe(r){const n=new Gy(r);this.webSocket.send(n.payload())}sendUnsubscribe(){const r=new qy;this.webSocket.send(r.payload())}sendWebRtcOffer(r,n){const a=new Hy(r,n);this.webSocket.send(a.payload())}sendWebRtcAnswer(r,n){const a=new jy(r,n);this.webSocket.send(a.payload())}sendWebRtcDatachannelRequest(){const r=new Ky;this.webSocket.send(r.payload())}sendSFURecvDataChannelReady(){const r=new Qy;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 Xy(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 Jy{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 Zy{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,C=this.freezeFrameWidth/this.freezeFrameHeight;v<C?(r=this.rootDiv.clientWidth,n=Math.floor(this.rootDiv.clientWidth/C),a=Math.floor(.5*(this.rootDiv.clientHeight-n)),f=0):(r=Math.floor(this.rootDiv.clientHeight*C),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 ew{constructor(r){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Zy(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 oi{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 oi{constructor(r,n,a,f,v,C=(()=>{})){super(r,n,a,f,C);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 kr extends oi{constructor(r,n,a,f,v,C,R,b=(()=>{})){super(r,n,a,C,b),this._min=f,this._max=v;const F=new URLSearchParams(window.location.search);if(R&&F.has(this.id)){const B=Number.parseFloat(F.get(this.id));this.number=Number.isNaN(B)?C:B}else this.number=C;this.useUrlParams=R}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.number.toString()),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}set number(r){this.value=this.clamp(r)}get number(){return this.value}clamp(r){return this._min==null&&this._max==null?r:this._min==null?Math.min(this._max,r):this._max==null?Math.max(this._min,r):Math.max(Math.min(this._max,r),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(r){this.onChange=r}}class _f extends oi{constructor(r,n,a,f,v,C=(()=>{})){super(r,n,a,f,C);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 vo extends oi{constructor(r,n,a,f,v,C,R=(()=>{})){super(r,n,a,f,R),this.options=v;const b=new URLSearchParams(window.location.search),F=C&&b.has(this.id)?this.getUrlParamText():f;this.selected=F,this.useUrlParams=C}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 Sf extends Event{constructor(r){super("afkWarningActivate"),this.data=r}}class bo extends Event{constructor(r){super("afkWarningUpdate"),this.data=r}}class Tf extends Event{constructor(){super("afkWarningDeactivate")}}class $f extends Event{constructor(){super("afkTimedOut")}}class xf extends Event{constructor(r){super("videoEncoderAvgQP"),this.data=r}}class Ef extends Event{constructor(){super("webRtcSdp")}}class Cf extends Event{constructor(){super("webRtcAutoConnect")}}class kf extends Event{constructor(){super("webRtcConnecting")}}class Rf extends Event{constructor(){super("webRtcConnected")}}class Af extends Event{constructor(){super("webRtcFailed")}}class Mf extends Event{constructor(r){super("webRtcDisconnected"),this.data=r}}class If extends Event{constructor(r){super("dataChannelOpen"),this.data=r}}class Pf extends Event{constructor(r){super("dataChannelClose"),this.data=r}}class Of extends Event{constructor(r){super("dataChannelError"),this.data=r}}class zf extends Event{constructor(){super("videoInitialized")}}class Df extends Event{constructor(){super("streamLoading")}}class Lf extends Event{constructor(){super("streamConnect")}}class Bf extends Event{constructor(){super("streamDisconnect")}}class Nf extends Event{constructor(){super("streamReconnect")}}class Uf extends Event{constructor(r){super("playStreamError"),this.data=r}}class Ff extends Event{constructor(){super("playStream")}}class _o extends Event{constructor(r){super("playStreamRejected"),this.data=r}}class Vf extends Event{constructor(r){super("loadFreezeFrame"),this.data=r}}class Gf extends Event{constructor(){super("hideFreezeFrame")}}class qf extends Event{constructor(r){super("statsReceived"),this.data=r}}class Wf extends Event{constructor(r){super("streamerListMessage"),this.data=r}}class Hf extends Event{constructor(r){super("StreamerIDChangedMessage"),this.data=r}}class jf extends Event{constructor(r){super("latencyTestResult"),this.data=r}}class Kf extends Event{constructor(r){super("dataChannelLatencyTestResponse"),this.data=r}}class Qf extends Event{constructor(r){super("dataChannelLatencyTestResult"),this.data=r}}class Xf extends Event{constructor(r){super("initialSettings"),this.data=r}}class ii extends Event{constructor(r){super("settingsChanged"),this.data=r}}class tw extends Event{constructor(){super("xrSessionStarted")}}class rw extends Event{constructor(){super("xrSessionEnded")}}class Yf extends Event{constructor(r){super("xrFrame"),this.data=r}}class Jf extends Event{constructor(r){super("playerCount"),this.data=r}}class Zf extends Event{constructor(){super("webRtcTCPRelayDetected")}}class em extends EventTarget{dispatchEvent(r){return super.dispatchEvent(r)}addEventListener(r,n){super.addEventListener(r,n)}removeEventListener(r,n){super.removeEventListener(r,n)}}class K{}K.AutoConnect="AutoConnect",K.AutoPlayVideo="AutoPlayVideo",K.AFKDetection="TimeoutIfIdle",K.BrowserSendOffer="OfferToReceive",K.HoveringMouseMode="HoveringMouse",K.ForceMonoAudio="ForceMonoAudio",K.ForceTURN="ForceTURN",K.FakeMouseWithTouches="FakeMouseWithTouches",K.IsQualityController="ControlsQuality",K.MatchViewportResolution="MatchViewportRes",K.StartVideoMuted="StartVideoMuted",K.SuppressBrowserKeys="SuppressBrowserKeys",K.UseMic="UseMic",K.KeyboardInput="KeyboardInput",K.MouseInput="MouseInput",K.TouchInput="TouchInput",K.GamepadInput="GamepadInput",K.XRControllerInput="XRControllerInput",K.WaitForStreamer="WaitForStreamer",K.HideUI="HideUI";const nw=c=>Object.getOwnPropertyNames(K).some((r=>K[r]===c));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 sw=c=>Object.getOwnPropertyNames(ye).some((r=>ye[r]===c));class Vr{}Vr.SignallingServerUrl="ss";const iw=c=>Object.getOwnPropertyNames(Vr).some((r=>Vr[r]===c));class vt{}vt.PreferredCodec="PreferredCodec",vt.StreamerId="StreamerId";const aw=c=>Object.getOwnPropertyNames(vt).some((r=>vt[r]===c));class ow{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(Vr.SignallingServerUrl,new _f(Vr.SignallingServerUrl,"Signalling url","Url of the signalling server",n&&n.hasOwnProperty(Vr.SignallingServerUrl)?n[Vr.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 vo(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 vo(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 C=v.mimeType.split("/")[1]+" "+(v.sdpFmtpLine||"");f.exec(C)!==null&&a.push(C)})),a})(),r)),this.flags.set(K.AutoConnect,new Rt(K.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(K.AutoConnect))&&n[K.AutoConnect],r)),this.flags.set(K.AutoPlayVideo,new Rt(K.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!n||!n.hasOwnProperty(K.AutoPlayVideo)||n[K.AutoPlayVideo],r)),this.flags.set(K.BrowserSendOffer,new Rt(K.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!n||!n.hasOwnProperty(K.BrowserSendOffer))&&n[K.BrowserSendOffer],r)),this.flags.set(K.UseMic,new Rt(K.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!n||!n.hasOwnProperty(K.UseMic))&&n[K.UseMic],r)),this.flags.set(K.StartVideoMuted,new Rt(K.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!n||!n.hasOwnProperty(K.StartVideoMuted))&&n[K.StartVideoMuted],r)),this.flags.set(K.SuppressBrowserKeys,new Rt(K.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(K.SuppressBrowserKeys)||n[K.SuppressBrowserKeys],r)),this.flags.set(K.IsQualityController,new Rt(K.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!n||!n.hasOwnProperty(K.IsQualityController)||n[K.IsQualityController],r)),this.flags.set(K.ForceMonoAudio,new Rt(K.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!n||!n.hasOwnProperty(K.ForceMonoAudio))&&n[K.ForceMonoAudio],r)),this.flags.set(K.ForceTURN,new Rt(K.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!n||!n.hasOwnProperty(K.ForceTURN))&&n[K.ForceTURN],r)),this.flags.set(K.AFKDetection,new Rt(K.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!n||!n.hasOwnProperty(K.AFKDetection))&&n[K.AFKDetection],r)),this.flags.set(K.MatchViewportResolution,new Rt(K.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(K.MatchViewportResolution))&&n[K.MatchViewportResolution],r)),this.flags.set(K.HoveringMouseMode,new Rt(K.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(K.HoveringMouseMode))&&n[K.HoveringMouseMode],r,((a,f)=>{f.label=`Control Scheme: ${a?"Hovering":"Locked"} Mouse`}))),this.flags.set(K.FakeMouseWithTouches,new Rt(K.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(K.FakeMouseWithTouches))&&n[K.FakeMouseWithTouches],r)),this.flags.set(K.KeyboardInput,new Rt(K.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!n||!n.hasOwnProperty(K.KeyboardInput)||n[K.KeyboardInput],r)),this.flags.set(K.MouseInput,new Rt(K.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!n||!n.hasOwnProperty(K.MouseInput)||n[K.MouseInput],r)),this.flags.set(K.TouchInput,new Rt(K.TouchInput,"Touch input","If enabled, send touch events to streamer",!n||!n.hasOwnProperty(K.TouchInput)||n[K.TouchInput],r)),this.flags.set(K.GamepadInput,new Rt(K.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!n||!n.hasOwnProperty(K.GamepadInput)||n[K.GamepadInput],r)),this.flags.set(K.XRControllerInput,new Rt(K.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!n||!n.hasOwnProperty(K.XRControllerInput)||n[K.XRControllerInput],r)),this.flags.set(K.WaitForStreamer,new Rt(K.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!n||!n.hasOwnProperty(K.WaitForStreamer)||n[K.WaitForStreamer],r)),this.flags.set(K.HideUI,new Rt(K.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!n||!n.hasOwnProperty(K.HideUI))&&n[K.HideUI],r)),this.numericParameters.set(ye.AFKTimeoutSecs,new kr(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 kr(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 kr(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 kr(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 kr(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 kr(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 kr(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 kr(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 kr(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))nw(n)?this.setFlagEnabled(n,r[n]):sw(n)?this.setNumericSetting(n,r[n]):iw(n)?this.setTextSetting(n,r[n]):aw(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 ii({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 ii({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 ii({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 ii({id:a.id,type:"option",value:f,target:a})))}}}var On;(function(c){c[c.LockedMouse=0]="LockedMouse",c[c.HoveringMouse=1]="HoveringMouse"})(On||(On={}));class tm{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 Tf))}startAfkWarningTimer(){this.config.getNumericSettingValue(ye.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(K.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(K.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(ye.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new Sf({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(ye.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new bo({countDown:this.countDown})),this.config.isFlagEnabled(K.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new $f),this.onAFKTimedOutCallback(),T.Log(T.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new bo({countDown:this.countDown}))}),1e3)}}class Vp{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 rm{}class nm{}class sm{}class So{}class im{}class lw{}class uw{}class am{constructor(){this.inboundVideoStats=new nm,this.inboundAudioStats=new rm,this.DataChannelStats=new sm,this.outBoundVideoStats=new im,this.sessionStats=new lw,this.streamStats=new uw,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 So;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 So;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 Gp=(qp={parseRtpParameters:()=>Fp.parseRtpParameters,splitSections:()=>Fp.splitSections},lo={},Di.d(lo,qp),lo);var qp,lo;class om{static isVideoTransciever(r){return this.canTransceiverReceiveVideo(r)||this.canTransceiverSendVideo(r)}static canTransceiverReceiveVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="video"}static canTransceiverSendVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="video"}static isAudioTransciever(r){return this.canTransceiverReceiveAudio(r)||this.canTransceiverSendAudio(r)}static canTransceiverReceiveAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="audio"}static canTransceiverSendAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="audio"}}var es,$e,uo=function(c,r,n,a){return new(n||(n=Promise))((function(f,v){function C(F){try{b(a.next(F))}catch(B){v(B)}}function R(F){try{b(a.throw(F))}catch(B){v(B)}}function b(F){var B;F.done?f(F.value):(B=F.value,B instanceof n?B:new n((function(re){re(B)}))).then(C,R)}b((a=a.apply(c,[])).next())}))};class dw{constructor(r,n,a){this.config=n,this.createPeerConnection(r,a)}createPeerConnection(r,n){this.config.isFlagEnabled(K.ForceTURN)&&(r.iceTransportPolicy="relay",T.Log(T.GetStackTrace(),"Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(r),this.peerConnection.onsignalingstatechange=a=>this.handleSignalStateChange(a),this.peerConnection.oniceconnectionstatechange=a=>this.handleIceConnectionStateChange(a),this.peerConnection.onicegatheringstatechange=a=>this.handleIceGatheringStateChange(a),this.peerConnection.ontrack=a=>this.handleOnTrack(a),this.peerConnection.onicecandidate=a=>this.handleIceCandidate(a),this.peerConnection.ondatachannel=a=>this.handleDataChannel(a),this.aggregatedStats=new am,this.preferredCodec=n,this.updateCodecSelection=!0}createOffer(r,n){return uo(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(K.UseMic);!v||a||f||(v=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(v).finally((()=>{var C;(C=this.peerConnection)===null||C===void 0||C.createOffer(r).then((R=>{var 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 uo(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Receive Offer",6),(a=this.peerConnection)===null||a===void 0||a.setRemoteDescription(r).then((()=>{const f=location.hostname==="localhost"||location.hostname==="127.0.0.1",v=location.protocol==="https:";let C=n.isFlagEnabled(K.UseMic);!C||f||v||(C=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(vt.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r)),this.setupTransceiversAsync(C).finally((()=>{var R;(R=this.peerConnection)===null||R===void 0||R.createAnswer().then((b=>{var F;return b.sdp=this.mungeSDP(b.sdp,C),(F=this.peerConnection)===null||F===void 0?void 0:F.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(K.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(K.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(
|
|
2896
|
+
Msg: ${n}`;console.warn(a)}}T.verboseLogLevel=5,(function(c){c.LIST_STREAMERS="listStreamers",c.SUBSCRIBE="subscribe",c.UNSUBSCRIBE="unsubscribe",c.ICE_CANDIDATE="iceCandidate",c.OFFER="offer",c.ANSWER="answer",c.DATACHANNELREQUEST="dataChannelRequest",c.SFURECVDATACHANNELREADY="peerDataChannelsReady",c.PONG="pong"})(_r||(_r={}));class Wr{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 Vy extends Wr{constructor(){super(),this.type=_r.LIST_STREAMERS}}class Gy extends Wr{constructor(r){super(),this.type=_r.SUBSCRIBE,this.streamerId=r}}class qy extends Wr{constructor(){super(),this.type=_r.UNSUBSCRIBE}}class Wy extends Wr{constructor(r){super(),this.type=_r.PONG,this.time=r}}class Hy extends Wr{constructor(r,n){super(),this.type=_r.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 jy extends Wr{constructor(r,n){super(),this.type=_r.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 Ky extends Wr{constructor(){super(),this.type=_r.DATACHANNELREQUEST}}class Qy extends Wr{constructor(){super(),this.type=_r.SFURECVDATACHANNELREADY}}class Xy{constructor(r){this.type=_r.ICE_CANDIDATE,this.candidate=r}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2898
|
+
`+JSON.stringify(this,void 0,4),6),JSON.stringify(this)}}(function(c){c.CONFIG="config",c.STREAMER_LIST="streamerList",c.STREAMER_ID_CHANGED="streamerIDChanged",c.PLAYER_COUNT="playerCount",c.OFFER="offer",c.ANSWER="answer",c.ICE_CANDIDATE="iceCandidate",c.PEER_DATA_CHANNELS="peerDataChannels",c.PING="ping",c.WARNING="warning"})(Mt||(Mt={}));class vf{}class Yy extends vf{}class wo{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(Mt.PING,(n=>{const a=new Wy(new Date().getTime()).payload();T.Log(T.GetStackTrace(),Mt.PING+": "+n,6),r.webSocket.send(a)})),r.signallingProtocol.addMessageHandler(Mt.CONFIG,(n=>{T.Log(T.GetStackTrace(),Mt.CONFIG,6);const a=JSON.parse(n);r.onConfig(a)})),r.signallingProtocol.addMessageHandler(Mt.STREAMER_LIST,(n=>{T.Log(T.GetStackTrace(),Mt.STREAMER_LIST,6);const a=JSON.parse(n);r.onStreamerList(a)})),r.signallingProtocol.addMessageHandler(Mt.STREAMER_ID_CHANGED,(n=>{T.Log(T.GetStackTrace(),Mt.STREAMER_ID_CHANGED,6);const a=JSON.parse(n);r.onStreamerIDChanged(a)})),r.signallingProtocol.addMessageHandler(Mt.PLAYER_COUNT,(n=>{T.Log(T.GetStackTrace(),Mt.PLAYER_COUNT,6);const a=JSON.parse(n);T.Log(T.GetStackTrace(),"Player Count: "+a.count,6),r.onPlayerCount(a)})),r.signallingProtocol.addMessageHandler(Mt.ANSWER,(n=>{T.Log(T.GetStackTrace(),Mt.ANSWER,6);const a=JSON.parse(n);r.onWebRtcAnswer(a)})),r.signallingProtocol.addMessageHandler(Mt.OFFER,(n=>{T.Log(T.GetStackTrace(),Mt.OFFER,6);const a=JSON.parse(n);r.onWebRtcOffer(a)})),r.signallingProtocol.addMessageHandler(Mt.ICE_CANDIDATE,(n=>{T.Log(T.GetStackTrace(),Mt.ICE_CANDIDATE,6);const a=JSON.parse(n);r.onIceCandidate(a.candidate)})),r.signallingProtocol.addMessageHandler(Mt.WARNING,(n=>{T.Warning(T.GetStackTrace(),`Warning received: ${n}`)})),r.signallingProtocol.addMessageHandler(Mt.PEER_DATA_CHANNELS,(n=>{T.Log(T.GetStackTrace(),Mt.PEER_DATA_CHANNELS,6);const a=JSON.parse(n);r.onWebRtcPeerDataChannels(a)}))}}class _f{constructor(){this.WS_OPEN_STATE=1,this.onOpen=new EventTarget,this.onClose=new EventTarget,this.signallingProtocol=new wo,wo.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 Vy;this.webSocket.send(r.payload())}sendSubscribe(r){const n=new Gy(r);this.webSocket.send(n.payload())}sendUnsubscribe(){const r=new qy;this.webSocket.send(r.payload())}sendWebRtcOffer(r,n){const a=new Hy(r,n);this.webSocket.send(a.payload())}sendWebRtcAnswer(r,n){const a=new jy(r,n);this.webSocket.send(a.payload())}sendWebRtcDatachannelRequest(){const r=new Ky;this.webSocket.send(r.payload())}sendSFURecvDataChannelReady(){const r=new Qy;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 Xy(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 Jy{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 Zy{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,C=this.freezeFrameWidth/this.freezeFrameHeight;v<C?(r=this.rootDiv.clientWidth,n=Math.floor(this.rootDiv.clientWidth/C),a=Math.floor(.5*(this.rootDiv.clientHeight-n)),f=0):(r=Math.floor(this.rootDiv.clientHeight*C),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 ew{constructor(r){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Zy(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 oi{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 At extends oi{constructor(r,n,a,f,v,C=(()=>{})){super(r,n,a,f,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const _=this.getUrlParamFlag();this.flag=_}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 kr extends oi{constructor(r,n,a,f,v,C,R,_=(()=>{})){super(r,n,a,C,_),this._min=f,this._max=v;const U=new URLSearchParams(window.location.search);if(R&&U.has(this.id)){const B=Number.parseFloat(U.get(this.id));this.number=Number.isNaN(B)?C:B}else this.number=C;this.useUrlParams=R}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.number.toString()),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}set number(r){this.value=this.clamp(r)}get number(){return this.value}clamp(r){return this._min==null&&this._max==null?r:this._min==null?Math.min(this._max,r):this._max==null?Math.max(this._min,r):Math.max(Math.min(this._max,r),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(r){this.onChange=r}}class bf extends oi{constructor(r,n,a,f,v,C=(()=>{})){super(r,n,a,f,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const _=this.getUrlParamText();this.text=_}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 vo extends oi{constructor(r,n,a,f,v,C,R=(()=>{})){super(r,n,a,f,R),this.options=v;const _=new URLSearchParams(window.location.search),U=C&&_.has(this.id)?this.getUrlParamText():f;this.selected=U,this.useUrlParams=C}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 Sf extends Event{constructor(r){super("afkWarningActivate"),this.data=r}}class _o extends Event{constructor(r){super("afkWarningUpdate"),this.data=r}}class Tf extends Event{constructor(){super("afkWarningDeactivate")}}class $f extends Event{constructor(){super("afkTimedOut")}}class xf extends Event{constructor(r){super("videoEncoderAvgQP"),this.data=r}}class Ef extends Event{constructor(){super("webRtcSdp")}}class Cf extends Event{constructor(){super("webRtcAutoConnect")}}class kf extends Event{constructor(){super("webRtcConnecting")}}class Rf extends Event{constructor(){super("webRtcConnected")}}class Af extends Event{constructor(){super("webRtcFailed")}}class Mf extends Event{constructor(r){super("webRtcDisconnected"),this.data=r}}class If extends Event{constructor(r){super("dataChannelOpen"),this.data=r}}class Pf extends Event{constructor(r){super("dataChannelClose"),this.data=r}}class Of extends Event{constructor(r){super("dataChannelError"),this.data=r}}class zf extends Event{constructor(){super("videoInitialized")}}class Df extends Event{constructor(){super("streamLoading")}}class Lf extends Event{constructor(){super("streamConnect")}}class Bf extends Event{constructor(){super("streamDisconnect")}}class Nf extends Event{constructor(){super("streamReconnect")}}class Uf extends Event{constructor(r){super("playStreamError"),this.data=r}}class Ff extends Event{constructor(){super("playStream")}}class bo extends Event{constructor(r){super("playStreamRejected"),this.data=r}}class Vf extends Event{constructor(r){super("loadFreezeFrame"),this.data=r}}class Gf extends Event{constructor(){super("hideFreezeFrame")}}class qf extends Event{constructor(r){super("statsReceived"),this.data=r}}class Wf extends Event{constructor(r){super("streamerListMessage"),this.data=r}}class Hf extends Event{constructor(r){super("StreamerIDChangedMessage"),this.data=r}}class jf extends Event{constructor(r){super("latencyTestResult"),this.data=r}}class Kf extends Event{constructor(r){super("dataChannelLatencyTestResponse"),this.data=r}}class Qf extends Event{constructor(r){super("dataChannelLatencyTestResult"),this.data=r}}class Xf extends Event{constructor(r){super("initialSettings"),this.data=r}}class ii extends Event{constructor(r){super("settingsChanged"),this.data=r}}class tw extends Event{constructor(){super("xrSessionStarted")}}class rw extends Event{constructor(){super("xrSessionEnded")}}class Yf extends Event{constructor(r){super("xrFrame"),this.data=r}}class Jf extends Event{constructor(r){super("playerCount"),this.data=r}}class Zf extends Event{constructor(){super("webRtcTCPRelayDetected")}}class em extends EventTarget{dispatchEvent(r){return super.dispatchEvent(r)}addEventListener(r,n){super.addEventListener(r,n)}removeEventListener(r,n){super.removeEventListener(r,n)}}class K{}K.AutoConnect="AutoConnect",K.AutoPlayVideo="AutoPlayVideo",K.AFKDetection="TimeoutIfIdle",K.BrowserSendOffer="OfferToReceive",K.HoveringMouseMode="HoveringMouse",K.ForceMonoAudio="ForceMonoAudio",K.ForceTURN="ForceTURN",K.FakeMouseWithTouches="FakeMouseWithTouches",K.IsQualityController="ControlsQuality",K.MatchViewportResolution="MatchViewportRes",K.StartVideoMuted="StartVideoMuted",K.SuppressBrowserKeys="SuppressBrowserKeys",K.UseMic="UseMic",K.KeyboardInput="KeyboardInput",K.MouseInput="MouseInput",K.TouchInput="TouchInput",K.GamepadInput="GamepadInput",K.XRControllerInput="XRControllerInput",K.WaitForStreamer="WaitForStreamer",K.HideUI="HideUI";const nw=c=>Object.getOwnPropertyNames(K).some((r=>K[r]===c));class we{}we.AFKTimeoutSecs="AFKTimeout",we.AFKCountdownSecs="AFKCountdown",we.MinQP="MinQP",we.MaxQP="MaxQP",we.WebRTCFPS="WebRTCFPS",we.WebRTCMinBitrate="WebRTCMinBitrate",we.WebRTCMaxBitrate="WebRTCMaxBitrate",we.MaxReconnectAttempts="MaxReconnectAttempts",we.StreamerAutoJoinInterval="StreamerAutoJoinInterval";const sw=c=>Object.getOwnPropertyNames(we).some((r=>we[r]===c));class Gr{}Gr.SignallingServerUrl="ss";const iw=c=>Object.getOwnPropertyNames(Gr).some((r=>Gr[r]===c));class _t{}_t.PreferredCodec="PreferredCodec",_t.StreamerId="StreamerId";const aw=c=>Object.getOwnPropertyNames(_t).some((r=>_t[r]===c));class ow{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(Gr.SignallingServerUrl,new bf(Gr.SignallingServerUrl,"Signalling url","Url of the signalling server",n&&n.hasOwnProperty(Gr.SignallingServerUrl)?n[Gr.SignallingServerUrl]:(location.protocol==="https:"?"wss://":"ws://")+window.location.hostname+(window.location.port==="80"||window.location.port===""?"":`:${window.location.port}`),r)),this.optionParameters.set(_t.StreamerId,new vo(_t.StreamerId,"Streamer ID","The ID of the streamer to stream.",n&&n.hasOwnProperty(_t.StreamerId)?n[_t.StreamerId]:"",[],r)),this.optionParameters.set(_t.PreferredCodec,new vo(_t.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(_t.PreferredCodec)?[n[_t.PreferredCodec]]:(function(){const a=[];if(!RTCRtpReceiver.getCapabilities)return a.push("Only available on Chrome"),a;const f=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((v=>{const C=v.mimeType.split("/")[1]+" "+(v.sdpFmtpLine||"");f.exec(C)!==null&&a.push(C)})),a})(),r)),this.flags.set(K.AutoConnect,new At(K.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(K.AutoConnect))&&n[K.AutoConnect],r)),this.flags.set(K.AutoPlayVideo,new At(K.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!n||!n.hasOwnProperty(K.AutoPlayVideo)||n[K.AutoPlayVideo],r)),this.flags.set(K.BrowserSendOffer,new At(K.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!n||!n.hasOwnProperty(K.BrowserSendOffer))&&n[K.BrowserSendOffer],r)),this.flags.set(K.UseMic,new At(K.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!n||!n.hasOwnProperty(K.UseMic))&&n[K.UseMic],r)),this.flags.set(K.StartVideoMuted,new At(K.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!n||!n.hasOwnProperty(K.StartVideoMuted))&&n[K.StartVideoMuted],r)),this.flags.set(K.SuppressBrowserKeys,new At(K.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(K.SuppressBrowserKeys)||n[K.SuppressBrowserKeys],r)),this.flags.set(K.IsQualityController,new At(K.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!n||!n.hasOwnProperty(K.IsQualityController)||n[K.IsQualityController],r)),this.flags.set(K.ForceMonoAudio,new At(K.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!n||!n.hasOwnProperty(K.ForceMonoAudio))&&n[K.ForceMonoAudio],r)),this.flags.set(K.ForceTURN,new At(K.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!n||!n.hasOwnProperty(K.ForceTURN))&&n[K.ForceTURN],r)),this.flags.set(K.AFKDetection,new At(K.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!n||!n.hasOwnProperty(K.AFKDetection))&&n[K.AFKDetection],r)),this.flags.set(K.MatchViewportResolution,new At(K.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(K.MatchViewportResolution))&&n[K.MatchViewportResolution],r)),this.flags.set(K.HoveringMouseMode,new At(K.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(K.HoveringMouseMode))&&n[K.HoveringMouseMode],r,((a,f)=>{f.label=`Control Scheme: ${a?"Hovering":"Locked"} Mouse`}))),this.flags.set(K.FakeMouseWithTouches,new At(K.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(K.FakeMouseWithTouches))&&n[K.FakeMouseWithTouches],r)),this.flags.set(K.KeyboardInput,new At(K.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!n||!n.hasOwnProperty(K.KeyboardInput)||n[K.KeyboardInput],r)),this.flags.set(K.MouseInput,new At(K.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!n||!n.hasOwnProperty(K.MouseInput)||n[K.MouseInput],r)),this.flags.set(K.TouchInput,new At(K.TouchInput,"Touch input","If enabled, send touch events to streamer",!n||!n.hasOwnProperty(K.TouchInput)||n[K.TouchInput],r)),this.flags.set(K.GamepadInput,new At(K.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!n||!n.hasOwnProperty(K.GamepadInput)||n[K.GamepadInput],r)),this.flags.set(K.XRControllerInput,new At(K.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!n||!n.hasOwnProperty(K.XRControllerInput)||n[K.XRControllerInput],r)),this.flags.set(K.WaitForStreamer,new At(K.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!n||!n.hasOwnProperty(K.WaitForStreamer)||n[K.WaitForStreamer],r)),this.flags.set(K.HideUI,new At(K.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!n||!n.hasOwnProperty(K.HideUI))&&n[K.HideUI],r)),this.numericParameters.set(we.AFKTimeoutSecs,new kr(we.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(we.AFKTimeoutSecs)?n[we.AFKTimeoutSecs]:120,r)),this.numericParameters.set(we.AFKCountdownSecs,new kr(we.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(we.MaxReconnectAttempts,new kr(we.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,n&&n.hasOwnProperty(we.MaxReconnectAttempts)?n[we.MaxReconnectAttempts]:3,r)),this.numericParameters.set(we.MinQP,new kr(we.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(we.MinQP)?n[we.MinQP]:0,r)),this.numericParameters.set(we.MaxQP,new kr(we.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(we.MaxQP)?n[we.MaxQP]:51,r)),this.numericParameters.set(we.WebRTCFPS,new kr(we.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,n&&n.hasOwnProperty(we.WebRTCFPS)?n[we.WebRTCFPS]:60,r)),this.numericParameters.set(we.WebRTCMinBitrate,new kr(we.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,n&&n.hasOwnProperty(we.WebRTCMinBitrate)?n[we.WebRTCMinBitrate]:0,r)),this.numericParameters.set(we.WebRTCMaxBitrate,new kr(we.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,n&&n.hasOwnProperty(we.WebRTCMaxBitrate)?n[we.WebRTCMaxBitrate]:0,r)),this.numericParameters.set(we.StreamerAutoJoinInterval,new kr(we.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,n&&n.hasOwnProperty(we.StreamerAutoJoinInterval)?n[we.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))nw(n)?this.setFlagEnabled(n,r[n]):sw(n)?this.setNumericSetting(n,r[n]):iw(n)?this.setTextSetting(n,r[n]):aw(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 ii({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 ii({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 ii({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 ii({id:a.id,type:"option",value:f,target:a})))}}}var zn;(function(c){c[c.LockedMouse=0]="LockedMouse",c[c.HoveringMouse=1]="HoveringMouse"})(zn||(zn={}));class tm{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 Tf))}startAfkWarningTimer(){this.config.getNumericSettingValue(we.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(K.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(K.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(we.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new Sf({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(we.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new _o({countDown:this.countDown})),this.config.isFlagEnabled(K.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new $f),this.onAFKTimedOutCallback(),T.Log(T.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new _o({countDown:this.countDown}))}),1e3)}}class Vp{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 rm{}class nm{}class sm{}class So{}class im{}class lw{}class uw{}class am{constructor(){this.inboundVideoStats=new nm,this.inboundAudioStats=new rm,this.DataChannelStats=new sm,this.outBoundVideoStats=new im,this.sessionStats=new lw,this.streamStats=new uw,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 So;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 So;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 Gp=(qp={parseRtpParameters:()=>Fp.parseRtpParameters,splitSections:()=>Fp.splitSections},lo={},Di.d(lo,qp),lo);var qp,lo;class om{static isVideoTransciever(r){return this.canTransceiverReceiveVideo(r)||this.canTransceiverSendVideo(r)}static canTransceiverReceiveVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="video"}static canTransceiverSendVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="video"}static isAudioTransciever(r){return this.canTransceiverReceiveAudio(r)||this.canTransceiverSendAudio(r)}static canTransceiverReceiveAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="audio"}static canTransceiverSendAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="audio"}}var ts,$e,uo=function(c,r,n,a){return new(n||(n=Promise))((function(f,v){function C(U){try{_(a.next(U))}catch(B){v(B)}}function R(U){try{_(a.throw(U))}catch(B){v(B)}}function _(U){var B;U.done?f(U.value):(B=U.value,B instanceof n?B:new n((function(te){te(B)}))).then(C,R)}_((a=a.apply(c,[])).next())}))};class dw{constructor(r,n,a){this.config=n,this.createPeerConnection(r,a)}createPeerConnection(r,n){this.config.isFlagEnabled(K.ForceTURN)&&(r.iceTransportPolicy="relay",T.Log(T.GetStackTrace(),"Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(r),this.peerConnection.onsignalingstatechange=a=>this.handleSignalStateChange(a),this.peerConnection.oniceconnectionstatechange=a=>this.handleIceConnectionStateChange(a),this.peerConnection.onicegatheringstatechange=a=>this.handleIceGatheringStateChange(a),this.peerConnection.ontrack=a=>this.handleOnTrack(a),this.peerConnection.onicecandidate=a=>this.handleIceCandidate(a),this.peerConnection.ondatachannel=a=>this.handleDataChannel(a),this.aggregatedStats=new am,this.preferredCodec=n,this.updateCodecSelection=!0}createOffer(r,n){return uo(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(K.UseMic);!v||a||f||(v=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(v).finally((()=>{var C;(C=this.peerConnection)===null||C===void 0||C.createOffer(r).then((R=>{var _;this.showTextOverlayConnecting(),R.sdp=this.mungeSDP(R.sdp,v),(_=this.peerConnection)===null||_===void 0||_.setLocalDescription(R),this.onSendWebRTCOffer(R)})).catch((()=>{this.showTextOverlaySetupFailure()}))}))}))}receiveOffer(r,n){var a;return uo(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Receive Offer",6),(a=this.peerConnection)===null||a===void 0||a.setRemoteDescription(r).then((()=>{const f=location.hostname==="localhost"||location.hostname==="127.0.0.1",v=location.protocol==="https:";let C=n.isFlagEnabled(K.UseMic);!C||f||v||(C=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(_t.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r)),this.setupTransceiversAsync(C).finally((()=>{var R;(R=this.peerConnection)===null||R===void 0||R.createAnswer().then((_=>{var U;return _.sdp=this.mungeSDP(_.sdp,C),(U=this.peerConnection)===null||U===void 0?void 0:U.setLocalDescription(_)})).then((()=>{var _;this.onSendWebRTCAnswer((_=this.peerConnection)===null||_===void 0?void 0:_.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(_t.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(_t.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(K.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(K.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(_t.PreferredCodec).options;for(const v of a)if(f.includes(v))n.push(v);else{const C=v.split(" ")[0];for(const R of f)if(R.includes(C)){n.push(R);break}}return n}setupTransceiversAsync(r){var n,a,f,v,C,R,_,U,B,te,Q,ee;return uo(this,void 0,void 0,(function*(){let ie=!1;for(const ue of(a=(n=this.peerConnection)===null||n===void 0?void 0:n.getTransceivers())!==null&&a!==void 0?a:[])if(ue&&ue.receiver&&ue.receiver.track&&ue.receiver.track.kind==="video"){ie=!0;break}if(ie||(f=this.peerConnection)===null||f===void 0||f.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&this.preferredCodec!=""){for(const ue of(C=(v=this.peerConnection)===null||v===void 0?void 0:v.getTransceivers())!==null&&C!==void 0?C:[])if(ue&&ue.receiver&&ue.receiver.track&&ue.receiver.track.kind==="video"&&ue.setCodecPreferences){const Be=this.preferredCodec.split(" "),Te={mimeType:"video/"+Be[0],clockRate:9e4,sdpFmtpLine:Be[1]?Be[1]:""},oe=[Te];RTCRtpReceiver.getCapabilities("video").codecs.forEach((ne=>{(ne.mimeType!=Te.mimeType||ne?.sdpFmtpLine!=Te?.sdpFmtpLine)&&oe.push(ne)}));for(const ne of oe)ne?.sdpFmtpLine!==void 0&&ne.sdpFmtpLine!==""||delete ne.sdpFmtpLine;ue.setCodecPreferences(oe)}}let ce=!1;for(const ue of(_=(R=this.peerConnection)===null||R===void 0?void 0:R.getTransceivers())!==null&&_!==void 0?_:[])if(ue&&ue.receiver&&ue.receiver.track&&ue.receiver.track.kind==="audio"){ce=!0;break}if(r){const ue={video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}},Be=yield navigator.mediaDevices.getUserMedia(ue);if(Be)if(ce){for(const Te of(te=(B=this.peerConnection)===null||B===void 0?void 0:B.getTransceivers())!==null&&te!==void 0?te:[])if(om.canTransceiverReceiveAudio(Te))for(const oe of Be.getTracks())oe.kind&&oe.kind=="audio"&&(Te.sender.replaceTrack(oe),Te.direction="sendrecv")}else for(const Te of Be.getTracks())Te.kind&&Te.kind=="audio"&&((Q=this.peerConnection)===null||Q===void 0||Q.addTransceiver(Te,{direction:"sendrecv"}));else ce||(ee=this.peerConnection)===null||ee===void 0||ee.addTransceiver("audio",{direction:"recvonly"})}else ce||(U=this.peerConnection)===null||U===void 0||U.addTransceiver("audio",{direction:"recvonly"})}))}onVideoStats(r){}onSendWebRTCOffer(r){}onSendWebRTCAnswer(r){}showTextOverlayConnecting(){}showTextOverlaySetupFailure(){}parseAvailableCodecs(r){if(!RTCRtpReceiver.getCapabilities)return["Only available on Chrome"];const n=[],a=(0,Gp.splitSections)(r.sdp);return a.shift(),a.forEach((f=>{const{codecs:v}=(0,Gp.parseRtpParameters)(f),C=/(VP\d|H26\d|AV1).*/;v.forEach((R=>{const _=R.name+" "+Object.keys(R.parameters||{}).map((U=>U+"="+R.parameters[U])).join(";");if(C.exec(_)!==null){R.name=="VP9"&&(R.parameters={"profile-id":"0"});const U=R.name+" "+Object.keys(R.parameters||{}).map((B=>B+"="+R.parameters[B])).join(";");n.push(U)}}))})),n}}class lm{constructor(){this.PixelStreamingSettings=new cw,this.EncoderSettings=new um,this.WebRTCSettings=new dm}ueCompatible(){this.WebRTCSettings.MaxFPS!=null&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class cw{}class um{}class dm{}class cm{constructor(){this.ReceiptTimeMs=null,this.TransmissionTimeMs=null,this.PreCaptureTimeMs=null,this.PostCaptureTimeMs=null,this.PreEncodeTimeMs=null,this.PostEncodeTimeMs=null,this.EncodeMs=null,this.CaptureToSendMs=null,this.testStartTimeMs=0,this.browserReceiptTimeMs=0,this.latencyExcludingDecode=0,this.testDuration=0,this.networkLatency=0,this.browserSendLatency=0,this.frameDisplayDeltaTimeMs=0,this.endToEndLatency=0,this.encodeLatency=0}setFrameDisplayDeltaTime(r){this.frameDisplayDeltaTimeMs==0&&(this.frameDisplayDeltaTimeMs=Math.round(r))}processFields(){this.EncodeMs!=null||this.PreEncodeTimeMs==null&&this.PostEncodeTimeMs==null||(T.Log(T.GetStackTrace(),`Setting Encode Ms
|
|
2901
2901
|
${this.PostEncodeTimeMs}
|
|
2902
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
2903
|
${this.PostCaptureTimeMs}
|
|
2904
|
-
${this.PreCaptureTimeMs}`,6),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class co{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 C=new Blob(n.data,{type:n.mimetype}),R=document.createElement("a");R.setAttribute("href",URL.createObjectURL(C)),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 hw{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 Ht{}Ht.primaryButton=1,Ht.secondaryButton=2,Ht.auxiliaryButton=4,Ht.fourthButton=8,Ht.fifthButton=16;class rs{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(r){this.unregisterCallbacks.push(r)}unregisterAll(){for(const r of this.unregisterCallbacks)r();this.unregisterCallbacks=[]}}class pw{constructor(r,n,a){this.touchEventListenerTracker=new rs,this.toStreamerMessagesProvider=r,this.videoElementProvider=n,this.coordinateConverter=a;const f=R=>this.onTouchStart(R),v=R=>this.onTouchEnd(R),C=R=>this.onTouchMove(R);document.addEventListener("touchstart",f,{passive:!1}),document.addEventListener("touchend",v,{passive:!1}),document.addEventListener("touchmove",C,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchend",v))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",C)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}setVideoElementParentClientRect(r){this.videoElementParentClientRect=r}onTouchStart(r){if(this.videoElementProvider.isVideoReady()&&r.target===this.videoElementProvider.getVideoElement()){if(this.fakeTouchFinger==null){const n=r.changedTouches[0];this.fakeTouchFinger=new fw(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 C=v.clientX-this.videoElementParentClientRect.left,R=v.clientY-this.videoElementParentClientRect.top,b=this.coordinateConverter.normalizeAndQuantizeUnsigned(C,R);a.get("MouseUp")([Gt.mainButton,b.x,b.y]);const F=new MouseEvent("mouseleave",v);n.dispatchEvent(F),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,C=f.clientY-this.videoElementParentClientRect.top,R=this.coordinateConverter.normalizeAndQuantizeUnsigned(v,C),b=this.coordinateConverter.normalizeAndQuantizeSigned(v-this.fakeTouchFinger.x,C-this.fakeTouchFinger.y);n.get("MouseMove")([R.x,R.y,b.x,b.y]),this.fakeTouchFinger.x=v,this.fakeTouchFinger.y=C;break}}r.preventDefault()}}class fw{constructor(r,n,a){this.id=r,this.x=n,this.y=a}}class jt{}jt.backSpace=8,jt.shift=16,jt.control=17,jt.alt=18,jt.rightShift=253,jt.rightControl=254,jt.rightAlt=255;class mw{constructor(r,n,a){this.keyboardEventListenerTracker=new rs,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===jt.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:jt.backSpace})),this.config.isFlagEnabled(K.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(K.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===jt.shift&&r.code==="ShiftRight"?jt.rightShift:r.keyCode===jt.control&&r.code==="ControlRight"?jt.rightControl:r.keyCode===jt.alt&&r.code==="AltRight"?jt.rightAlt:r.keyCode}isKeyCodeBrowserKey(r){return r>=112&&r<=123||r===9}}class gw{constructor(r,n,a){this.x=0,this.y=0,this.updateMouseMovePositionEvent=v=>{this.updateMouseMovePosition(v)},this.mouseEventListenerTracker=new rs,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((C=>{})),v.forEach((C=>{n.get("KeyUp")([C])})),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 yw{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 ww{constructor(r,n,a,f){this.mouseEventListenerTracker=new rs,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 gw(this.videoElementProvider,r,this.activeKeysProvider);if(n.requestPointerLock=n.requestPointerLock||n.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,n.requestPointerLock){const F=()=>{n.requestPointerLock()};n.addEventListener("click",F),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("click",F)))}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=F=>a.handleMouseDown(F),C=F=>a.handleMouseUp(F),R=F=>a.handleMouseWheel(F),b=F=>a.handleMouseDouble(F);n.addEventListener("mousedown",v),n.addEventListener("mouseup",C),n.addEventListener("wheel",R),n.addEventListener("dblclick",b),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousedown",v))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mouseup",C))),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 yw(r),f=B=>a.updateMouseMovePosition(B),v=B=>a.handleMouseDown(B),C=B=>a.handleMouseUp(B),R=B=>a.handleContextMenu(B),b=B=>a.handleMouseWheel(B),F=B=>a.handleMouseDouble(B);n.addEventListener("mousemove",f),n.addEventListener("mousedown",v),n.addEventListener("mouseup",C),n.addEventListener("contextmenu",R),n.addEventListener("wheel",b),n.addEventListener("dblclick",F),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousemove",f))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousedown",v))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mouseup",C))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("contextmenu",R))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("wheel",b))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("dblclick",F))),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&Ht.primaryButton&&this.sendMouseUp(Gt.mainButton,f.x,f.y),r&Ht.secondaryButton&&this.sendMouseUp(Gt.secondaryButton,f.x,f.y),r&Ht.auxiliaryButton&&this.sendMouseUp(Gt.auxiliaryButton,f.x,f.y),r&Ht.fourthButton&&this.sendMouseUp(Gt.fourthButton,f.x,f.y),r&Ht.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&Ht.primaryButton&&this.sendMouseDown(Gt.mainButton,f.x,f.y),r&Ht.secondaryButton&&this.sendMouseDown(Gt.secondaryButton,f.x,f.y),r&Ht.auxiliaryButton&&this.sendMouseDown(Gt.auxiliaryButton,f.x,f.y),r&Ht.fourthButton&&this.sendMouseDown(Gt.fourthButton,f.x,f.y),r&Ht.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 vw{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 rs,this.toStreamerMessagesProvider=r,this.videoElementProvider=n,this.coordinateConverter=a,this.videoElementParent=n.getVideoElement();const f=b=>this.onTouchStart(b),v=b=>this.onTouchEnd(b),C=b=>this.onTouchMove(b);this.videoElementParent.addEventListener("touchstart",f),this.videoElementParent.addEventListener("touchend",v),this.videoElementParent.addEventListener("touchmove",C),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchend",v))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchmove",C))),T.Log(T.GetStackTrace(),"Touch Events Registered",6);const R=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,F=R.clientY-a.top;T.Log(T.GetStackTrace(),`F${this.fingerIds.get(R.identifier)}=(${b}, ${F})`,6);const B=this.coordinateConverter.normalizeAndQuantizeUnsigned(b,F);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 bw{constructor(r){this.gamePadEventListenerTracker=new rs,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 C=n.currentState.buttons[v],R=n.prevState.buttons[v];C.pressed?v==es.LeftTrigger?r.get("GamepadAnalog")([a,5,C.value]):v==es.RightTrigger?r.get("GamepadAnalog")([a,6,C.value]):r.get("GamepadButtonPressed")([a,v,R.pressed?1:0]):!C.pressed&&R.pressed&&(v==es.LeftTrigger?r.get("GamepadAnalog")([a,5,0]):v==es.RightTrigger?r.get("GamepadAnalog")([a,6,0]):r.get("GamepadButtonReleased")([a,v,0]))}for(let v=0;v<f.axes.length;v+=2){const C=parseFloat(f.axes[v].toFixed(4)),R=-parseFloat(f.axes[v+1].toFixed(4));r.get("GamepadAnalog")([a,v+1,C]),r.get("GamepadAnalog")([a,v+2,R])}this.controllers[a].prevState=f}this.controllers.length>0&&this.requestAnimationFrame((()=>this.updateStatus()))}onGamepadResponseReceived(r){for(const 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(c){c[c.RightClusterBottomButton=0]="RightClusterBottomButton",c[c.RightClusterRightButton=1]="RightClusterRightButton",c[c.RightClusterLeftButton=2]="RightClusterLeftButton",c[c.RightClusterTopButton=3]="RightClusterTopButton",c[c.LeftShoulder=4]="LeftShoulder",c[c.RightShoulder=5]="RightShoulder",c[c.LeftTrigger=6]="LeftTrigger",c[c.RightTrigger=7]="RightTrigger",c[c.SelectOrBack=8]="SelectOrBack",c[c.StartOrForward=9]="StartOrForward",c[c.LeftAnalogPress=10]="LeftAnalogPress",c[c.RightAnalogPress=11]="RightAnalogPress",c[c.LeftClusterTopButton=12]="LeftClusterTopButton",c[c.LeftClusterBottomButton=13]="LeftClusterBottomButton",c[c.LeftClusterLeftButton=14]="LeftClusterLeftButton",c[c.LeftClusterRightButton=15]="LeftClusterRightButton",c[c.CentreButton=16]="CentreButton",c[c.LeftStickHorizontal=0]="LeftStickHorizontal",c[c.LeftStickVertical=1]="LeftStickVertical",c[c.RightStickHorizontal=2]="RightStickHorizontal",c[c.RightStickVertical=3]="RightStickVertical"})(es||(es={}));class _w{constructor(r,n,a){this.activeKeys=new Sw,this.toStreamerMessagesProvider=r,this.videoElementProvider=n,this.coordinateConverter=a}registerKeyBoard(r){T.Log(T.GetStackTrace(),"Register Keyboard Events",7);const n=new mw(this.toStreamerMessagesProvider,r,this.activeKeys);return n.registerKeyBoardEvents(),n}registerMouse(r){T.Log(T.GetStackTrace(),"Register Mouse Events",7);const n=new ww(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys);switch(r){case On.LockedMouse:n.registerLockedMouseEvents(n);break;case On.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 pw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return a.setVideoElementParentClientRect(n),a}return new vw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return T.Log(T.GetStackTrace(),"Register Game Pad",7),new bw(this.toStreamerMessagesProvider)}}class Sw{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class Tw{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(K.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(K.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(K.MatchViewportResolution))if(new Date().getTime()-this.lastTimeResized>300){const r=this.getVideoParentElement();if(!r)return;this.onMatchViewportResolutionCallback(r.clientWidth,r.clientHeight),this.lastTimeResized=new Date().getTime()}else T.Log(T.GetStackTrace(),"Resizing too often - skipping",6),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout((()=>this.updateVideoStreamSize()),100)}}class $w{constructor(){this.toStreamerHandlers=new Map,this.fromStreamerHandlers=new Map,this.toStreamerMessages=new Map,this.fromStreamerMessages=new Map}populateDefaultProtocol(){this.toStreamerMessages.set("IFrameRequest",{id:0,structure:[]}),this.toStreamerMessages.set("RequestQualityControl",{id:1,structure:[]}),this.toStreamerMessages.set("FpsRequest",{id:2,structure:[]}),this.toStreamerMessages.set("AverageBitrateRequest",{id:3,structure:[]}),this.toStreamerMessages.set("StartStreaming",{id:4,structure:[]}),this.toStreamerMessages.set("StopStreaming",{id:5,structure:[]}),this.toStreamerMessages.set("LatencyTest",{id:6,structure:["string"]}),this.toStreamerMessages.set("RequestInitialSettings",{id:7,structure:[]}),this.toStreamerMessages.set("TestEcho",{id:8,structure:[]}),this.toStreamerMessages.set("DataChannelLatencyTest",{id:9,structure:[]}),this.toStreamerMessages.set("UIInteraction",{id:50,structure:["string"]}),this.toStreamerMessages.set("Command",{id:51,structure:["string"]}),this.toStreamerMessages.set("KeyDown",{id:60,structure:["uint8","uint8"]}),this.toStreamerMessages.set("KeyUp",{id:61,structure:["uint8"]}),this.toStreamerMessages.set("KeyPress",{id:62,structure:["uint16"]}),this.toStreamerMessages.set("MouseEnter",{id:70,structure:[]}),this.toStreamerMessages.set("MouseLeave",{id:71,structure:[]}),this.toStreamerMessages.set("MouseDown",{id:72,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseUp",{id:73,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseMove",{id:74,structure:["uint16","uint16","int16","int16"]}),this.toStreamerMessages.set("MouseWheel",{id:75,structure:["int16","uint16","uint16"]}),this.toStreamerMessages.set("MouseDouble",{id:76,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("TouchStart",{id:80,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchEnd",{id:81,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchMove",{id:82,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadConnected",{id:93,structure:[]}),this.toStreamerMessages.set("GamepadButtonPressed",{id:90,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadButtonReleased",{id:91,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadAnalog",{id:92,structure:["uint8","uint8","double"]}),this.toStreamerMessages.set("GamepadDisconnected",{id:94,structure:["uint8"]}),this.fromStreamerMessages.set(0,"QualityControlOwnership"),this.fromStreamerMessages.set(1,"Response"),this.fromStreamerMessages.set(2,"Command"),this.fromStreamerMessages.set(3,"FreezeFrame"),this.fromStreamerMessages.set(4,"UnfreezeFrame"),this.fromStreamerMessages.set(5,"VideoEncoderAvgQP"),this.fromStreamerMessages.set(6,"LatencyTest"),this.fromStreamerMessages.set(7,"InitialSettings"),this.fromStreamerMessages.set(8,"FileExtension"),this.fromStreamerMessages.set(9,"FileMimeType"),this.fromStreamerMessages.set(10,"FileContents"),this.fromStreamerMessages.set(11,"TestEcho"),this.fromStreamerMessages.set(12,"InputControlOwnership"),this.fromStreamerMessages.set(13,"GamepadResponse"),this.fromStreamerMessages.set(14,"DataChannelLatencyTest"),this.fromStreamerMessages.set(255,"Protocol")}registerMessageHandler(r,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(c){c[c.ToStreamer=0]="ToStreamer",c[c.FromStreamer=1]="FromStreamer"})($e||($e={}));class xw{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 Ew{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,F)=>{switch(a.structure[F]){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 C=new DataView(new ArrayBuffer(f+1));C.setUint8(0,a.id);let R=1;n.forEach(((b,F)=>{switch(a.structure[F]){case"uint8":C.setUint8(R,b),R+=1;break;case"uint16":C.setUint16(R,b,!0),R+=2;break;case"int16":C.setInt16(R,b,!0),R+=2;break;case"float":C.setFloat32(R,b,!0),R+=4;break;case"double":C.setFloat64(R,b,!0),R+=8;break;case"string":C.setUint16(R,b.length,!0),R+=2;for(let B=0;B<b.length;B++)C.setUint16(R,b.charCodeAt(B),!0),R+=2}})),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(C.buffer):T.Info(T.GetStackTrace(),`Data channel cannot send yet, skipping sending message: ${r} - ${new Uint8Array(C.buffer)}`)}}class Cw{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 kw{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 Rw{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=(C,R)=>this.normalizeAndQuantizeUnsignedPlayerBigger(C,R),this.normalizeAndQuantizeSignedFunc=(C,R)=>this.normalizeAndQuantizeSignedPlayerBigger(C,R),this.denormalizeAndUnquantizeUnsignedFunc=(C,R)=>this.denormalizeAndUnquantizeUnsignedPlayerBigger(C,R)):(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio <= videoAspectRatio",6),this.ratio=v/f,this.normalizeAndQuantizeUnsignedFunc=(C,R)=>this.normalizeAndQuantizeUnsignedPlayerSmaller(C,R),this.normalizeAndQuantizeSignedFunc=(C,R)=>this.normalizeAndQuantizeSignedPlayerSmaller(C,R),this.denormalizeAndUnquantizeUnsignedFunc=(C,R)=>this.denormalizeAndUnquantizeUnsignedPlayerSmaller(C,R))}}normalizeAndQuantizeUnsignedPlayerBigger(r,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 Ri(!1,65535,65535):new Ri(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerBigger(r,n){const a=r/65536,f=(n/65536-.5)/this.ratio+.5;return new To(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 Wp(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 Ri(!1,65535,65535):new Ri(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerSmaller(r,n){const a=(r/65536-.5)/this.ratio+.5,f=n/65536;return new To(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 Wp(32767*a,32767*f)}}class Ri{constructor(r,n,a){this.inRange=r,this.x=n,this.y=a}}class To{constructor(r,n){this.x=r,this.y=n}}class Wp{constructor(r,n){this.x=r,this.y=n}}class hm{constructor(r,n){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=r,this.pixelStreaming=n,this.responseController=new xw,this.file=new hw,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new tm(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new ew(this.pixelStreaming.videoElementParent),this.videoPlayer=new Tw(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 Jy(this.videoPlayer),this.coordinateConverter=new Rw(this.videoPlayer),this.sendrecvDataChannelController=new Vp,this.recvDataChannelController=new Vp,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new kw(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new $w,this.webSocketController=new bf,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(K.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 Ew(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new Cw(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new _w(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(Vr.SignallingServerUrl);return this.config.isFlagEnabled(K.BrowserSendOffer)&&(a+="?"+K.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 C=a[v];switch(f){case $e.ToStreamer:if(!Object.prototype.hasOwnProperty.call(C,"id"))return void T.Error(T.GetStackTrace(),`ToStreamer->${v} protocol definition was malformed as it didn't contain at least an id
|
|
2904
|
+
${this.PreCaptureTimeMs}`,6),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class co{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 C=new Blob(n.data,{type:n.mimetype}),R=document.createElement("a");R.setAttribute("href",URL.createObjectURL(C)),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 hw{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 Ht{}Ht.primaryButton=1,Ht.secondaryButton=2,Ht.auxiliaryButton=4,Ht.fourthButton=8,Ht.fifthButton=16;class ns{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(r){this.unregisterCallbacks.push(r)}unregisterAll(){for(const r of this.unregisterCallbacks)r();this.unregisterCallbacks=[]}}class pw{constructor(r,n,a){this.touchEventListenerTracker=new ns,this.toStreamerMessagesProvider=r,this.videoElementProvider=n,this.coordinateConverter=a;const f=R=>this.onTouchStart(R),v=R=>this.onTouchEnd(R),C=R=>this.onTouchMove(R);document.addEventListener("touchstart",f,{passive:!1}),document.addEventListener("touchend",v,{passive:!1}),document.addEventListener("touchmove",C,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchend",v))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",C)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}setVideoElementParentClientRect(r){this.videoElementParentClientRect=r}onTouchStart(r){if(this.videoElementProvider.isVideoReady()&&r.target===this.videoElementProvider.getVideoElement()){if(this.fakeTouchFinger==null){const n=r.changedTouches[0];this.fakeTouchFinger=new fw(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 C=v.clientX-this.videoElementParentClientRect.left,R=v.clientY-this.videoElementParentClientRect.top,_=this.coordinateConverter.normalizeAndQuantizeUnsigned(C,R);a.get("MouseUp")([Gt.mainButton,_.x,_.y]);const U=new MouseEvent("mouseleave",v);n.dispatchEvent(U),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,C=f.clientY-this.videoElementParentClientRect.top,R=this.coordinateConverter.normalizeAndQuantizeUnsigned(v,C),_=this.coordinateConverter.normalizeAndQuantizeSigned(v-this.fakeTouchFinger.x,C-this.fakeTouchFinger.y);n.get("MouseMove")([R.x,R.y,_.x,_.y]),this.fakeTouchFinger.x=v,this.fakeTouchFinger.y=C;break}}r.preventDefault()}}class fw{constructor(r,n,a){this.id=r,this.x=n,this.y=a}}class jt{}jt.backSpace=8,jt.shift=16,jt.control=17,jt.alt=18,jt.rightShift=253,jt.rightControl=254,jt.rightAlt=255;class mw{constructor(r,n,a){this.keyboardEventListenerTracker=new ns,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===jt.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:jt.backSpace})),this.config.isFlagEnabled(K.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(K.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===jt.shift&&r.code==="ShiftRight"?jt.rightShift:r.keyCode===jt.control&&r.code==="ControlRight"?jt.rightControl:r.keyCode===jt.alt&&r.code==="AltRight"?jt.rightAlt:r.keyCode}isKeyCodeBrowserKey(r){return r>=112&&r<=123||r===9}}class gw{constructor(r,n,a){this.x=0,this.y=0,this.updateMouseMovePositionEvent=v=>{this.updateMouseMovePosition(v)},this.mouseEventListenerTracker=new ns,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((C=>{})),v.forEach((C=>{n.get("KeyUp")([C])})),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 yw{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 ww{constructor(r,n,a,f){this.mouseEventListenerTracker=new ns,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 gw(this.videoElementProvider,r,this.activeKeysProvider);if(n.requestPointerLock=n.requestPointerLock||n.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,n.requestPointerLock){const U=()=>{n.requestPointerLock()};n.addEventListener("click",U),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("click",U)))}const f=()=>a.lockStateChange();document.addEventListener("pointerlockchange",f,!1),document.addEventListener("mozpointerlockchange",f,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("pointerlockchange",f,!1))),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mozpointerlockchange",f,!1)));const v=U=>a.handleMouseDown(U),C=U=>a.handleMouseUp(U),R=U=>a.handleMouseWheel(U),_=U=>a.handleMouseDouble(U);n.addEventListener("mousedown",v),n.addEventListener("mouseup",C),n.addEventListener("wheel",R),n.addEventListener("dblclick",_),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousedown",v))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mouseup",C))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("wheel",R))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("dblclick",_))),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 yw(r),f=B=>a.updateMouseMovePosition(B),v=B=>a.handleMouseDown(B),C=B=>a.handleMouseUp(B),R=B=>a.handleContextMenu(B),_=B=>a.handleMouseWheel(B),U=B=>a.handleMouseDouble(B);n.addEventListener("mousemove",f),n.addEventListener("mousedown",v),n.addEventListener("mouseup",C),n.addEventListener("contextmenu",R),n.addEventListener("wheel",_),n.addEventListener("dblclick",U),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousemove",f))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mousedown",v))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("mouseup",C))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("contextmenu",R))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("wheel",_))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.removeEventListener("dblclick",U))),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&Ht.primaryButton&&this.sendMouseUp(Gt.mainButton,f.x,f.y),r&Ht.secondaryButton&&this.sendMouseUp(Gt.secondaryButton,f.x,f.y),r&Ht.auxiliaryButton&&this.sendMouseUp(Gt.auxiliaryButton,f.x,f.y),r&Ht.fourthButton&&this.sendMouseUp(Gt.fourthButton,f.x,f.y),r&Ht.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&Ht.primaryButton&&this.sendMouseDown(Gt.mainButton,f.x,f.y),r&Ht.secondaryButton&&this.sendMouseDown(Gt.secondaryButton,f.x,f.y),r&Ht.auxiliaryButton&&this.sendMouseDown(Gt.auxiliaryButton,f.x,f.y),r&Ht.fourthButton&&this.sendMouseDown(Gt.fourthButton,f.x,f.y),r&Ht.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 vw{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 ns,this.toStreamerMessagesProvider=r,this.videoElementProvider=n,this.coordinateConverter=a,this.videoElementParent=n.getVideoElement();const f=_=>this.onTouchStart(_),v=_=>this.onTouchEnd(_),C=_=>this.onTouchMove(_);this.videoElementParent.addEventListener("touchstart",f),this.videoElementParent.addEventListener("touchend",v),this.videoElementParent.addEventListener("touchmove",C),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",f))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchend",v))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchmove",C))),T.Log(T.GetStackTrace(),"Touch Events Registered",6);const R=_=>{_.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],_=R.clientX-a.left,U=R.clientY-a.top;T.Log(T.GetStackTrace(),`F${this.fingerIds.get(R.identifier)}=(${_}, ${U})`,6);const B=this.coordinateConverter.normalizeAndQuantizeUnsigned(_,U);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 _w{constructor(r){this.gamePadEventListenerTracker=new ns,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 C=n.currentState.buttons[v],R=n.prevState.buttons[v];C.pressed?v==ts.LeftTrigger?r.get("GamepadAnalog")([a,5,C.value]):v==ts.RightTrigger?r.get("GamepadAnalog")([a,6,C.value]):r.get("GamepadButtonPressed")([a,v,R.pressed?1:0]):!C.pressed&&R.pressed&&(v==ts.LeftTrigger?r.get("GamepadAnalog")([a,5,0]):v==ts.RightTrigger?r.get("GamepadAnalog")([a,6,0]):r.get("GamepadButtonReleased")([a,v,0]))}for(let v=0;v<f.axes.length;v+=2){const C=parseFloat(f.axes[v].toFixed(4)),R=-parseFloat(f.axes[v+1].toFixed(4));r.get("GamepadAnalog")([a,v+1,C]),r.get("GamepadAnalog")([a,v+2,R])}this.controllers[a].prevState=f}this.controllers.length>0&&this.requestAnimationFrame((()=>this.updateStatus()))}onGamepadResponseReceived(r){for(const 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(c){c[c.RightClusterBottomButton=0]="RightClusterBottomButton",c[c.RightClusterRightButton=1]="RightClusterRightButton",c[c.RightClusterLeftButton=2]="RightClusterLeftButton",c[c.RightClusterTopButton=3]="RightClusterTopButton",c[c.LeftShoulder=4]="LeftShoulder",c[c.RightShoulder=5]="RightShoulder",c[c.LeftTrigger=6]="LeftTrigger",c[c.RightTrigger=7]="RightTrigger",c[c.SelectOrBack=8]="SelectOrBack",c[c.StartOrForward=9]="StartOrForward",c[c.LeftAnalogPress=10]="LeftAnalogPress",c[c.RightAnalogPress=11]="RightAnalogPress",c[c.LeftClusterTopButton=12]="LeftClusterTopButton",c[c.LeftClusterBottomButton=13]="LeftClusterBottomButton",c[c.LeftClusterLeftButton=14]="LeftClusterLeftButton",c[c.LeftClusterRightButton=15]="LeftClusterRightButton",c[c.CentreButton=16]="CentreButton",c[c.LeftStickHorizontal=0]="LeftStickHorizontal",c[c.LeftStickVertical=1]="LeftStickVertical",c[c.RightStickHorizontal=2]="RightStickHorizontal",c[c.RightStickVertical=3]="RightStickVertical"})(ts||(ts={}));class bw{constructor(r,n,a){this.activeKeys=new Sw,this.toStreamerMessagesProvider=r,this.videoElementProvider=n,this.coordinateConverter=a}registerKeyBoard(r){T.Log(T.GetStackTrace(),"Register Keyboard Events",7);const n=new mw(this.toStreamerMessagesProvider,r,this.activeKeys);return n.registerKeyBoardEvents(),n}registerMouse(r){T.Log(T.GetStackTrace(),"Register Mouse Events",7);const n=new ww(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys);switch(r){case zn.LockedMouse:n.registerLockedMouseEvents(n);break;case zn.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 pw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return a.setVideoElementParentClientRect(n),a}return new vw(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return T.Log(T.GetStackTrace(),"Register Game Pad",7),new _w(this.toStreamerMessagesProvider)}}class Sw{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class Tw{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(K.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(K.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(K.MatchViewportResolution))if(new Date().getTime()-this.lastTimeResized>300){const r=this.getVideoParentElement();if(!r)return;this.onMatchViewportResolutionCallback(r.clientWidth,r.clientHeight),this.lastTimeResized=new Date().getTime()}else T.Log(T.GetStackTrace(),"Resizing too often - skipping",6),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout((()=>this.updateVideoStreamSize()),100)}}class $w{constructor(){this.toStreamerHandlers=new Map,this.fromStreamerHandlers=new Map,this.toStreamerMessages=new Map,this.fromStreamerMessages=new Map}populateDefaultProtocol(){this.toStreamerMessages.set("IFrameRequest",{id:0,structure:[]}),this.toStreamerMessages.set("RequestQualityControl",{id:1,structure:[]}),this.toStreamerMessages.set("FpsRequest",{id:2,structure:[]}),this.toStreamerMessages.set("AverageBitrateRequest",{id:3,structure:[]}),this.toStreamerMessages.set("StartStreaming",{id:4,structure:[]}),this.toStreamerMessages.set("StopStreaming",{id:5,structure:[]}),this.toStreamerMessages.set("LatencyTest",{id:6,structure:["string"]}),this.toStreamerMessages.set("RequestInitialSettings",{id:7,structure:[]}),this.toStreamerMessages.set("TestEcho",{id:8,structure:[]}),this.toStreamerMessages.set("DataChannelLatencyTest",{id:9,structure:[]}),this.toStreamerMessages.set("UIInteraction",{id:50,structure:["string"]}),this.toStreamerMessages.set("Command",{id:51,structure:["string"]}),this.toStreamerMessages.set("KeyDown",{id:60,structure:["uint8","uint8"]}),this.toStreamerMessages.set("KeyUp",{id:61,structure:["uint8"]}),this.toStreamerMessages.set("KeyPress",{id:62,structure:["uint16"]}),this.toStreamerMessages.set("MouseEnter",{id:70,structure:[]}),this.toStreamerMessages.set("MouseLeave",{id:71,structure:[]}),this.toStreamerMessages.set("MouseDown",{id:72,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseUp",{id:73,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseMove",{id:74,structure:["uint16","uint16","int16","int16"]}),this.toStreamerMessages.set("MouseWheel",{id:75,structure:["int16","uint16","uint16"]}),this.toStreamerMessages.set("MouseDouble",{id:76,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("TouchStart",{id:80,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchEnd",{id:81,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchMove",{id:82,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadConnected",{id:93,structure:[]}),this.toStreamerMessages.set("GamepadButtonPressed",{id:90,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadButtonReleased",{id:91,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadAnalog",{id:92,structure:["uint8","uint8","double"]}),this.toStreamerMessages.set("GamepadDisconnected",{id:94,structure:["uint8"]}),this.fromStreamerMessages.set(0,"QualityControlOwnership"),this.fromStreamerMessages.set(1,"Response"),this.fromStreamerMessages.set(2,"Command"),this.fromStreamerMessages.set(3,"FreezeFrame"),this.fromStreamerMessages.set(4,"UnfreezeFrame"),this.fromStreamerMessages.set(5,"VideoEncoderAvgQP"),this.fromStreamerMessages.set(6,"LatencyTest"),this.fromStreamerMessages.set(7,"InitialSettings"),this.fromStreamerMessages.set(8,"FileExtension"),this.fromStreamerMessages.set(9,"FileMimeType"),this.fromStreamerMessages.set(10,"FileContents"),this.fromStreamerMessages.set(11,"TestEcho"),this.fromStreamerMessages.set(12,"InputControlOwnership"),this.fromStreamerMessages.set(13,"GamepadResponse"),this.fromStreamerMessages.set(14,"DataChannelLatencyTest"),this.fromStreamerMessages.set(255,"Protocol")}registerMessageHandler(r,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(c){c[c.ToStreamer=0]="ToStreamer",c[c.FromStreamer=1]="FromStreamer"})($e||($e={}));class xw{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 Ew{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((_=>{switch(_){case"uint8":case"uint16":case"int16":case"float":case"double":return"number";case"string":return"string"}})).toString()} ] but received [ ${n.map((_=>typeof _)).toString()} ]`);let f=0;const v=new TextEncoder;n.forEach(((_,U)=>{switch(a.structure[U]){case"uint8":f+=1;break;case"uint16":case"int16":f+=2;break;case"float":f+=4;break;case"double":f+=8;break;case"string":f+=2,f+=2*v.encode(_).length}}));const C=new DataView(new ArrayBuffer(f+1));C.setUint8(0,a.id);let R=1;n.forEach(((_,U)=>{switch(a.structure[U]){case"uint8":C.setUint8(R,_),R+=1;break;case"uint16":C.setUint16(R,_,!0),R+=2;break;case"int16":C.setInt16(R,_,!0),R+=2;break;case"float":C.setFloat32(R,_,!0),R+=4;break;case"double":C.setFloat64(R,_,!0),R+=8;break;case"string":C.setUint16(R,_.length,!0),R+=2;for(let B=0;B<_.length;B++)C.setUint16(R,_.charCodeAt(B),!0),R+=2}})),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(C.buffer):T.Info(T.GetStackTrace(),`Data channel cannot send yet, skipping sending message: ${r} - ${new Uint8Array(C.buffer)}`)}}class Cw{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 kw{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 Rw{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=(C,R)=>this.normalizeAndQuantizeUnsignedPlayerBigger(C,R),this.normalizeAndQuantizeSignedFunc=(C,R)=>this.normalizeAndQuantizeSignedPlayerBigger(C,R),this.denormalizeAndUnquantizeUnsignedFunc=(C,R)=>this.denormalizeAndUnquantizeUnsignedPlayerBigger(C,R)):(T.Log(T.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio <= videoAspectRatio",6),this.ratio=v/f,this.normalizeAndQuantizeUnsignedFunc=(C,R)=>this.normalizeAndQuantizeUnsignedPlayerSmaller(C,R),this.normalizeAndQuantizeSignedFunc=(C,R)=>this.normalizeAndQuantizeSignedPlayerSmaller(C,R),this.denormalizeAndUnquantizeUnsignedFunc=(C,R)=>this.denormalizeAndUnquantizeUnsignedPlayerSmaller(C,R))}}normalizeAndQuantizeUnsignedPlayerBigger(r,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 Ri(!1,65535,65535):new Ri(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerBigger(r,n){const a=r/65536,f=(n/65536-.5)/this.ratio+.5;return new To(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 Wp(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 Ri(!1,65535,65535):new Ri(!0,65536*a,65536*f)}denormalizeAndUnquantizeUnsignedPlayerSmaller(r,n){const a=(r/65536-.5)/this.ratio+.5,f=n/65536;return new To(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 Wp(32767*a,32767*f)}}class Ri{constructor(r,n,a){this.inRange=r,this.x=n,this.y=a}}class To{constructor(r,n){this.x=r,this.y=n}}class Wp{constructor(r,n){this.x=r,this.y=n}}class hm{constructor(r,n){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=r,this.pixelStreaming=n,this.responseController=new xw,this.file=new hw,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new tm(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new ew(this.pixelStreaming.videoElementParent),this.videoPlayer=new Tw(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 Jy(this.videoPlayer),this.coordinateConverter=new Rw(this.videoPlayer),this.sendrecvDataChannelController=new Vp,this.recvDataChannelController=new Vp,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new kw(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new $w,this.webSocketController=new _f,this.webSocketController.onConfig=a=>this.handleOnConfigMessage(a),this.webSocketController.onStreamerList=a=>this.handleStreamerListMessage(a),this.webSocketController.onStreamerIDChanged=a=>this.handleStreamerIDChangedMessage(a),this.webSocketController.onPlayerCount=a=>{this.pixelStreaming._onPlayerCount(a.count)},this.webSocketController.onOpen.addEventListener("open",(()=>{this.config.isFlagEnabled(K.BrowserSendOffer)||this.webSocketController.requestStreamerList()})),this.webSocketController.onClose.addEventListener("close",(a=>{const f=this.shouldReconnect&&a.detail.code!=1001&&this.config.getNumericSettingValue(we.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 Ew(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new Cw(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new bw(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(_t.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(Gr.SignallingServerUrl);return this.config.isFlagEnabled(K.BrowserSendOffer)&&(a+="?"+K.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 C=a[v];switch(f){case $e.ToStreamer:if(!Object.prototype.hasOwnProperty.call(C,"id"))return void T.Error(T.GetStackTrace(),`ToStreamer->${v} protocol definition was malformed as it didn't contain at least an id
|
|
2905
2905
|
|
|
2906
2906
|
Definition was: ${JSON.stringify(C,null,2)}`);if(v==="UIInteraction"||v==="Command"||v==="LatencyTest")return;this.streamMessageController.toStreamerHandlers.get(v)?this.streamMessageController.toStreamerMessages.set(v,C):T.Error(T.GetStackTrace(),`There was no registered handler for "${v}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${v}", myHandler)`);break;case $e.FromStreamer:if(!Object.prototype.hasOwnProperty.call(C,"id"))return void T.Error(T.GetStackTrace(),`FromStreamer->${v} protocol definition was malformed as it didn't contain at least an id
|
|
2907
2907
|
|
|
2908
|
-
Definition was: ${JSON.stringify(C,null,2)}`);this.streamMessageController.fromStreamerHandlers.get(v)?this.streamMessageController.fromStreamerMessages.set(C.id,v):T.Error(T.GetStackTrace(),`There was no registered handler for "${C}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${v}", myHandler)`);break;default:T.Error(T.GetStackTrace(),`Unknown direction: ${f}`)}})),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(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 Vf({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),this.shouldShowPlayOverlay===!0?(T.Log(T.GetStackTrace(),"showing play overlay"),this.resizePlayerStyle()):(T.Log(T.GetStackTrace(),"showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout((()=>{this.videoPlayer.setVideoEnabled(!1)}),this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6);const n=new Uint8Array(r);this.freezeFrameController.processFreezeFrameMessage(n,(()=>this.loadFreezeFrameOrShowPlayOverlay()))}invalidateFreezeFrameAndEnableVideo(){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6),setTimeout((()=>{this.pixelStreaming.dispatchEvent(new Gf),this.freezeFrameController.hideFreezeFrame()}),this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(r){const n=new Uint8Array(r);co.setExtensionFromBytes(n,this.file)}onFileMimeType(r){const n=new Uint8Array(r);co.setMimeTypeFromBytes(n,this.file)}onFileContents(r){const n=new Uint8Array(r);co.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 Uf({message:r})),T.Error(T.GetStackTrace(),r),void this.closeSignalingServer("Stream not initialized correctly")}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(K.TouchInput)),this.pixelStreaming.dispatchEvent(new Ff),this.streamController.audioElement.srcObject){const r=this.config.isFlagEnabled(K.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 _o({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 _o({reason:r}))}))}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(K.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(K.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 dw(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(K.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 C=this.config.isFlagEnabled(K.WaitForStreamer),R=this.config.getNumericSettingValue(ye.MaxReconnectAttempts),b=this.config.getNumericSettingValue(ye.StreamerAutoJoinInterval),F=this.config.useUrlParams,B=new URLSearchParams(window.location.search);F&&B.has(vt.StreamerId)?n=B.get(vt.StreamerId):this.subscribedStream&&(n=this.subscribedStream),n&&r.ids.includes(n)?v=n:n&&C||r.ids.length!=1||(v=r.ids[0]),v?(this.isReconnecting=!1,this.reconnectAttempt=0,this.config.setOptionSettingValue(vt.StreamerId,v)):C&&(this.reconnectAttempt<R?(this.isReconnecting=!0,this.reconnectAttempt++,setTimeout((()=>{this.webSocketController.requestStreamerList()}),b)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.shouldReconnect=!1)),this.pixelStreaming.dispatchEvent(new Wf({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,C=0;C<v.length;++C)if(v[C]==this.subscribedStream){v[C]=n;break}a.options=v,a.selected=n,a.onChange=f,this.subscribedStream=r.newID,this.pixelStreaming.dispatchEvent(new Hf({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(K.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(K.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(K.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}
|
|
2908
|
+
Definition was: ${JSON.stringify(C,null,2)}`);this.streamMessageController.fromStreamerHandlers.get(v)?this.streamMessageController.fromStreamerMessages.set(C.id,v):T.Error(T.GetStackTrace(),`There was no registered handler for "${C}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${v}", myHandler)`);break;default:T.Error(T.GetStackTrace(),`Unknown direction: ${f}`)}})),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(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 Vf({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),this.shouldShowPlayOverlay===!0?(T.Log(T.GetStackTrace(),"showing play overlay"),this.resizePlayerStyle()):(T.Log(T.GetStackTrace(),"showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout((()=>{this.videoPlayer.setVideoEnabled(!1)}),this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(r){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6);const n=new Uint8Array(r);this.freezeFrameController.processFreezeFrameMessage(n,(()=>this.loadFreezeFrameOrShowPlayOverlay()))}invalidateFreezeFrameAndEnableVideo(){T.Log(T.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6),setTimeout((()=>{this.pixelStreaming.dispatchEvent(new Gf),this.freezeFrameController.hideFreezeFrame()}),this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(r){const n=new Uint8Array(r);co.setExtensionFromBytes(n,this.file)}onFileMimeType(r){const n=new Uint8Array(r);co.setMimeTypeFromBytes(n,this.file)}onFileContents(r){const n=new Uint8Array(r);co.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 Uf({message:r})),T.Error(T.GetStackTrace(),r),void this.closeSignalingServer("Stream not initialized correctly")}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(K.TouchInput)),this.pixelStreaming.dispatchEvent(new Ff),this.streamController.audioElement.srcObject){const r=this.config.isFlagEnabled(K.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 bo({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 bo({reason:r}))}))}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(K.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(K.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 dw(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(K.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(_t.StreamerId);a.selected.toString().trim()&&(n=a.selected);const f=[...r.ids];f.unshift(""),this.config.setOptionSettingOptions(_t.StreamerId,f);let v=null;const C=this.config.isFlagEnabled(K.WaitForStreamer),R=this.config.getNumericSettingValue(we.MaxReconnectAttempts),_=this.config.getNumericSettingValue(we.StreamerAutoJoinInterval),U=this.config.useUrlParams,B=new URLSearchParams(window.location.search);U&&B.has(_t.StreamerId)?n=B.get(_t.StreamerId):this.subscribedStream&&(n=this.subscribedStream),n&&r.ids.includes(n)?v=n:n&&C||r.ids.length!=1||(v=r.ids[0]),v?(this.isReconnecting=!1,this.reconnectAttempt=0,this.config.setOptionSettingValue(_t.StreamerId,v)):C&&(this.reconnectAttempt<R?(this.isReconnecting=!0,this.reconnectAttempt++,setTimeout((()=>{this.webSocketController.requestStreamerList()}),_)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.shouldReconnect=!1)),this.pixelStreaming.dispatchEvent(new Wf({messageStreamerList:r,autoSelectedStreamerId:v,wantedStreamerId:n}))}handleStreamerIDChangedMessage(r){const n=r.newID;var a=this.config.getSettingOption(_t.StreamerId),f=a.onChange;a.onChange=()=>{};for(var v=a.options,C=0;C<v.length;++C)if(v[C]==this.subscribedStream){v[C]=n;break}a.options=v,a.selected=n,a.onChange=f,this.subscribedStream=r.newID,this.pixelStreaming.dispatchEvent(new Hf({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(K.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(K.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(K.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(we.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(we.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(we.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(we.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
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 cm;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 lm;a.Encoder&&(f.EncoderSettings=a.Encoder),a.WebRTC&&(f.WebRTCSettings=a.WebRTC),a.PixelStreaming&&(f.PixelStreamingSettings=a.PixelStreaming),a.ConfigOptions&&a.ConfigOptions.DefaultToHover!==void 0&&this.config.setFlagEnabled(K.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(K.HoveringMouseMode)?
|
|
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 cm;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 lm;a.Encoder&&(f.EncoderSettings=a.Encoder),a.WebRTC&&(f.WebRTCSettings=a.WebRTC),a.PixelStreaming&&(f.PixelStreamingSettings=a.PixelStreaming),a.ConfigOptions&&a.ConfigOptions.DefaultToHover!==void 0&&this.config.setFlagEnabled(K.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(K.HoveringMouseMode)?zn.HoveringMouse:zn.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(K.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 If({label:n,event:a})),r.onClose=(n,a)=>this.pixelStreaming.dispatchEvent(new Pf({label:n,event:a})),r.onError=(n,a)=>this.pixelStreaming.dispatchEvent(new Of({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 Li{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 C=2;switch(r.handedness){case"left":C=0;break;case"right":C=1}const R=f.transform.matrix,_=[];for(let Q=0;Q<16;Q++)_[Q]=new Float32Array([R[Q]])[0];this.toStreamerMessagesProvider.toStreamerHandlers.get("XRControllerTransform")([_[0],_[4],_[8],_[12],_[1],_[5],_[9],_[13],_[2],_[6],_[10],_[14],_[3],_[7],_[11],_[15],C]),this.controllers[C]===void 0&&(this.controllers[C]={prevState:void 0,currentState:void 0,id:void 0},this.controllers[C].prevState=Li.deepCopyGamepad(r.gamepad)),this.controllers[C].currentState=Li.deepCopyGamepad(r.gamepad);const U=this.controllers[C],B=U.currentState,te=U.prevState;for(let Q=0;Q<B.buttons.length;Q++){const ee=B.buttons[Q],ie=te.buttons[Q];if(ee.pressed){let ce=ie.pressed?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonPressed")([C,Q,ce])}else ie.pressed&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonReleased")([C,Q,0]);if(ee.touched){let ce=ie.touched?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouched")([C,Q,ce])}else ie.touched&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouchReleased")([C,Q,0])}for(let Q=0;Q<B.axes.length;Q++){let ee=B.axes[Q];ee!=te.axes[Q]&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRAnalog")([C,Q,ee])}this.controllers[C].prevState=B}}}class pm{constructor(r){this.xrViewerPose=null,this.videoTexture=null,this.prevVideoWidth=0,this.prevVideoHeight=0,this.leftView=null,this.rightView=null,this.xrSession=null,this.webRtcController=r,this.xrGamepadController=new Li(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
2911
|
attribute vec2 a_position;
|
|
2912
2912
|
attribute vec2 a_texCoord;
|
|
2913
2913
|
|
|
@@ -2934,5 +2934,5 @@ Msg: ${n}`;console.warn(a)}}T.verboseLogLevel=5,(function(c){c.LIST_STREAMERS="l
|
|
|
2934
2934
|
}
|
|
2935
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(K.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 Yf({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 Aw{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 Mw{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 Iw{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
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 Mw(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 Pw{constructor(r,n){this.allowConsoleCommands=!1,this.config=r,n?.videoElementParent&&(this._videoElementParent=n.videoElementParent),this._eventEmitter=new em,this.configureSettings(),this.setWebRtcPlayerController(new hm(this.config,this)),this.onScreenKeyboardHelper=new Aw(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(a,f)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(a,f),this._activateOnScreenKeyboard=a=>this.onScreenKeyboardHelper.showOnScreenKeyboard(a),this._webXrController=new pm(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",(a=>{this._eventEmitter.addEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}))}get videoElementParent(){return this._videoElementParent||(this._videoElementParent=document.createElement("div"),this._videoElementParent.id="videoElementParent"),this._videoElementParent}configureSettings(){this.config._addOnSettingChangedListener(K.IsQualityController,(r=>{r!==!0||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(K.AFKDetection,(r=>{this._webRtcController.setAfkEnabled(r)})),this.config._addOnSettingChangedListener(K.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(K.HoveringMouseMode,(r=>{this.config.setFlagLabel(K.HoveringMouseMode,`Control Scheme: ${r?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(K.MouseInput))})),this.config._addOnSettingChangedListener(K.KeyboardInput,(r=>{this._webRtcController.setKeyboardInputEnabled(r)})),this.config._addOnSettingChangedListener(K.MouseInput,(r=>{this._webRtcController.setMouseInputEnabled(r)})),this.config._addOnSettingChangedListener(K.FakeMouseWithTouches,(r=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(K.TouchInput))})),this.config._addOnSettingChangedListener(K.TouchInput,(r=>{this._webRtcController.setTouchInputEnabled(r)})),this.config._addOnSettingChangedListener(K.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 Lf),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Nf),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Bf),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(K.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 C 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:[])om.canTransceiverSendAudio(C)&&(C.sender.track.enabled=!r)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new Cf)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new Ef)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new Df)}_onDisconnect(r,n){this._eventEmitter.dispatchEvent(new Mf({eventString:r,allowClickToReconnect:n}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new kf)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Rf)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new Af)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new zf),this._videoStartTime=Date.now()}_onLatencyTestResult(r){this._eventEmitter.dispatchEvent(new jf({latencyTimings:r}))}_onDataChannelLatencyTestResponse(r){this._eventEmitter.dispatchEvent(new Kf({response:r}))}_onVideoStats(r){this._videoStartTime&&this._videoStartTime!==void 0||(this._videoStartTime=Date.now()),r.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new qf({aggregatedStats:r}))}_onVideoEncoderAvgQP(r){this._eventEmitter.dispatchEvent(new xf({avgQP:r}))}_onInitialSettings(r){var n;this._eventEmitter.dispatchEvent(new Xf({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(K.IsQualityController,r)}_onPlayerCount(r){this._eventEmitter.dispatchEvent(new Jf({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 Zf),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new Iw(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(n=>{this._eventEmitter.dispatchEvent(new Qf({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 Ow{}Se.Dz;Se.g$;Se.Lt;Se.Q9;Se.qf;Se.hV;Se.z$;Se.J0;var zw=Se.De;Se.$C;Se.al;Se._W;Se.Gv;Se.m;Se.tz;Se.Nu;Se.zg;Se.vp;Se.vU;Se.wF;Se.rv;Se.Nh;Se.ss;Se.qW;Se.QL;Se.cf;Se.eM;Se.Yd;Se.Tk;Se.iM;Se.qy;Se.ce;Se.sK;Se.Ok;Se.q5;var Dw=Se.g;Se.xl;Se.I;Se.bx;Se.dD;Se.Ib;Se.Az;Se.Iw;Se.qY;Se.db;Se.mR;Se.Tn;Se.rV;Se.gh;Se.Mi;Se.j;Se.YB;Se.Yt;Se.i5;Se.x_;Se.Am;Se.eR;Se.r8;Se.u3;Se.vd;Se.iV;Se.jZ;Se.SW;Se.ZH;Se.Ni;Se.lh;Se.ZP;Se.bq;Se.$f;Se.eu;Se.Ax;Se.Mc;const fm=({signallingUrl:c,autoConnect:r=!0,width:n,height:a,onConnecting:f,onLoading:v,onConnected:C,onDisconnected:R,onError:b,muted:F=!1})=>{const B=pe.useRef(null),re=pe.useRef(null),X=pe.useRef(!1),[ee,ae]=pe.useState(!1),[ce,de]=pe.useState(!1),[Le,Te]=pe.useState(null);return pe.useEffect(()=>{if(!(!B.current||!c)){f&&f(),console.log("๐ฎ Initializing Epic Pixel Streaming with URL:",c),navigator.mediaDevices||(navigator.mediaDevices={}),navigator.mediaDevices.getUserMedia||(navigator.mediaDevices.getUserMedia=function(){return Promise.reject(new Error("getUserMedia is not supported"))});try{const le=new zw({useUrlParams:!1,initialSettings:{ss:c,AutoConnect:r,AutoPlayVideo:!0,StartVideoMuted:F,UseMic:!1,HoveringMouse:!1,FakeMouseWithTouches:!0,TouchInput:!1,MouseInput:!1,KeyboardInput:!1,WaitForStreamer:!0}}),se=new Dw(le,{videoElementParent:B.current});se.addEventListener("webRtcConnected",()=>{console.log("โ
WebRTC Connected"),X.current=!0,ae(!0),de(!1),Te(null),C&&C()}),se.addEventListener("webRtcDisconnected",()=>{console.log("๐ WebRTC Disconnected"),X.current=!1,ae(!1),R&&R()}),se.addEventListener("streamLoading",()=>{console.log("โณ Stream Loading"),de(!0),v&&v()}),se.addEventListener("playStreamError",fe=>{console.error("โ Play Stream Error:",fe),Te("Failed to play stream"),de(!1),b&&b("Failed to play stream")}),se.addEventListener("playStream",()=>{console.log("โถ๏ธ Stream Playing"),de(!1),X.current||(console.log("โ
Stream Playing - Setting connected (fallback)"),X.current=!0,ae(!0),C&&C())}),se.addEventListener("videoInitialized",()=>{console.log("๐น Video Initialized"),de(!1)}),se.addEventListener("streamerListMessage",fe=>{console.log("๐ Streamer list received:",fe.data);const he=fe.data?.ids||fe.data;he&&he.length>0&&console.log("๐ฏ Streamer available, subscribing to:",he[0])}),re.current=se}catch(le){console.error("โ Failed to initialize Pixel Streaming:",le),Te("Failed to initialize streaming: "+le.message),de(!1),b&&b(le.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(le){console.error("Error during cleanup:",le)}re.current=null}}}},[c,r,f,v,C,R,b]),pe.useEffect(()=>{if(re.current)try{const le=re.current._webRtcController?.videoPlayer;if(!le){console.log("โ ๏ธ Video player not found");return}let se=!1;if(le.audioElement){const he=le.audioElement.srcObject;if(he){const Be=he.getAudioTracks();Be.length>0&&(Be.forEach(me=>{me.enabled=!F}),console.log("๐ Audio element tracks",F?"disabled":"enabled","- Track count:",Be.length),se=!0)}}const fe=le.getVideoElement();if(fe&&fe.srcObject){const Be=fe.srcObject.getAudioTracks();Be.length>0&&(Be.forEach(me=>{me.enabled=!F}),console.log("๐ Video element audio tracks",F?"disabled":"enabled","- Track count:",Be.length),se=!0)}!se&&fe&&(fe.muted=F,console.log("๐ Video element muted property set to:",F)),se||console.log("โ ๏ธ No audio tracks found, using video element muted property")}catch(le){console.error("Error controlling audio:",le)}},[F]),sr.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:[sr.jsx("div",{ref:B,className:"player-container",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"hidden",touchAction:"none"}}),ce&&sr.jsxs("div",{className:"loading-overlay",children:[sr.jsx("div",{className:"loading-spinner"}),sr.jsx("div",{className:"loading-text",children:"Connecting to stream..."})]}),!ee&&!ce&&Le&&sr.jsx("div",{className:"connection-overlay",children:sr.jsx("div",{className:"error-message",children:Le})})]})};function Lw({className:c,style:r,autoConnect:n=!0,muted:a=!1,onConnected:f,onDisconnected:v,onError:C}){const{streamingUrl:R,setCloudStreamState:b}=wf();if(!R)return null;const F=()=>{b(Kt.CONNECTING)},B=()=>{b(Kt.LOADING)},re=()=>{b(Kt.CONNECTED),f?.()},X=()=>{b(Kt.DISCONNECTED),v?.()},ee=ae=>{b(Kt.ERROR,ae),C?.(ae)};return sr.jsx("div",{className:c,style:r,children:sr.jsx(fm,{signallingUrl:R,autoConnect:n,muted:a,onConnecting:F,onLoading:B,onConnected:re,onDisconnected:X,onError:ee})})}exports.AGENT_TYPES=Fr;exports.CLOUD_STREAM_STATE=Kt;exports.CONNECTION_STATE=Dt;exports.EpicPixelStreamingPlayer=fm;exports.RqmiiAgentProvider=of;exports.RqmiiAgentRoom=Uy;exports.RqmiiCloudAvatarPlayer=Lw;exports.SOCKET_EVENTS=dt;exports.useRqmiiAgent=zy;exports.useRqmiiAgentContext=Gr;exports.useRqmiiAudioElement=By;exports.useRqmiiAvatar=wf;exports.useRqmiiConnection=yf;exports.useRqmiiMessages=Dy;exports.useRqmiiPressToTalk=by;exports.useRqmiiVAD=Oy;exports.useRqmiiVoice=Ly;
|
|
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 Mw(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 Pw{constructor(r,n){this.allowConsoleCommands=!1,this.config=r,n?.videoElementParent&&(this._videoElementParent=n.videoElementParent),this._eventEmitter=new em,this.configureSettings(),this.setWebRtcPlayerController(new hm(this.config,this)),this.onScreenKeyboardHelper=new Aw(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(a,f)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(a,f),this._activateOnScreenKeyboard=a=>this.onScreenKeyboardHelper.showOnScreenKeyboard(a),this._webXrController=new pm(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",(a=>{this._eventEmitter.addEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}))}get videoElementParent(){return this._videoElementParent||(this._videoElementParent=document.createElement("div"),this._videoElementParent.id="videoElementParent"),this._videoElementParent}configureSettings(){this.config._addOnSettingChangedListener(K.IsQualityController,(r=>{r!==!0||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(K.AFKDetection,(r=>{this._webRtcController.setAfkEnabled(r)})),this.config._addOnSettingChangedListener(K.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(K.HoveringMouseMode,(r=>{this.config.setFlagLabel(K.HoveringMouseMode,`Control Scheme: ${r?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(K.MouseInput))})),this.config._addOnSettingChangedListener(K.KeyboardInput,(r=>{this._webRtcController.setKeyboardInputEnabled(r)})),this.config._addOnSettingChangedListener(K.MouseInput,(r=>{this._webRtcController.setMouseInputEnabled(r)})),this.config._addOnSettingChangedListener(K.FakeMouseWithTouches,(r=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(K.TouchInput))})),this.config._addOnSettingChangedListener(K.TouchInput,(r=>{this._webRtcController.setTouchInputEnabled(r)})),this.config._addOnSettingChangedListener(K.GamepadInput,(r=>{this._webRtcController.setGamePadInputEnabled(r)})),this.config._addOnNumericSettingChangedListener(we.MinQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending MinQP --------",7),this._webRtcController.sendEncoderMinQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(we.MaxQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending encoder settings --------",7),this._webRtcController.sendEncoderMaxQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(we.WebRTCMinBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMinBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(we.WebRTCMaxBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMaxBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(we.WebRTCFPS,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCFps(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnOptionSettingChangedListener(_t.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(_t.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Lf),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Nf),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Bf),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(K.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 C 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:[])om.canTransceiverSendAudio(C)&&(C.sender.track.enabled=!r)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new Cf)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new Ef)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new Df)}_onDisconnect(r,n){this._eventEmitter.dispatchEvent(new Mf({eventString:r,allowClickToReconnect:n}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new kf)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Rf)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new Af)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new zf),this._videoStartTime=Date.now()}_onLatencyTestResult(r){this._eventEmitter.dispatchEvent(new jf({latencyTimings:r}))}_onDataChannelLatencyTestResponse(r){this._eventEmitter.dispatchEvent(new Kf({response:r}))}_onVideoStats(r){this._videoStartTime&&this._videoStartTime!==void 0||(this._videoStartTime=Date.now()),r.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new qf({aggregatedStats:r}))}_onVideoEncoderAvgQP(r){this._eventEmitter.dispatchEvent(new xf({avgQP:r}))}_onInitialSettings(r){var n;this._eventEmitter.dispatchEvent(new Xf({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(we.MinQP,a&&f.has(we.MinQP)?Number.parseFloat(f.get(we.MinQP)):r.EncoderSettings.MinQP),this.config.setNumericSetting(we.MaxQP,a&&f.has(we.MaxQP)?Number.parseFloat(f.get(we.MaxQP)):r.EncoderSettings.MaxQP)),r.WebRTCSettings&&(this.config.setNumericSetting(we.WebRTCMinBitrate,a&&f.has(we.WebRTCMinBitrate)?Number.parseFloat(f.get(we.WebRTCMinBitrate)):r.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(we.WebRTCMaxBitrate,a&&f.has(we.WebRTCMaxBitrate)?Number.parseFloat(f.get(we.WebRTCMaxBitrate)):r.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(we.WebRTCFPS,a&&f.has(we.WebRTCFPS)?Number.parseFloat(f.get(we.WebRTCFPS)):r.WebRTCSettings.FPS))}_onQualityControlOwnership(r){this.config.setFlagEnabled(K.IsQualityController,r)}_onPlayerCount(r){this._eventEmitter.dispatchEvent(new Jf({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 Zf),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new Iw(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(n=>{this._eventEmitter.dispatchEvent(new Qf({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 Ow{}Se.Dz;Se.g$;Se.Lt;Se.Q9;Se.qf;Se.hV;Se.z$;Se.J0;var zw=Se.De;Se.$C;Se.al;Se._W;Se.Gv;Se.m;Se.tz;Se.Nu;Se.zg;Se.vp;Se.vU;Se.wF;Se.rv;Se.Nh;Se.ss;Se.qW;Se.QL;Se.cf;Se.eM;Se.Yd;Se.Tk;Se.iM;Se.qy;Se.ce;Se.sK;Se.Ok;Se.q5;var Dw=Se.g;Se.xl;Se.I;Se.bx;Se.dD;Se.Ib;Se.Az;Se.Iw;Se.qY;Se.db;Se.mR;Se.Tn;Se.rV;Se.gh;Se.Mi;Se.j;Se.YB;Se.Yt;Se.i5;Se.x_;Se.Am;Se.eR;Se.r8;Se.u3;Se.vd;Se.iV;Se.jZ;Se.SW;Se.ZH;Se.Ni;Se.lh;Se.ZP;Se.bq;Se.$f;Se.eu;Se.Ax;Se.Mc;const fm=({signallingUrl:c,autoConnect:r=!0,width:n,height:a,onConnecting:f,onLoading:v,onConnected:C,onDisconnected:R,onError:_,muted:U=!1})=>{const B=he.useRef(null),te=he.useRef(null),Q=he.useRef(!1),[ee,ie]=he.useState(!1),[ce,ue]=he.useState(!1),[Be,Te]=he.useState(null);return he.useEffect(()=>{if(!(!B.current||!c)){f&&f(),console.log("๐ฎ Initializing Epic Pixel Streaming with URL:",c),navigator.mediaDevices||(navigator.mediaDevices={}),navigator.mediaDevices.getUserMedia||(navigator.mediaDevices.getUserMedia=function(){return Promise.reject(new Error("getUserMedia is not supported"))});try{const oe=new zw({useUrlParams:!1,initialSettings:{ss:c,AutoConnect:r,AutoPlayVideo:!0,StartVideoMuted:U,UseMic:!1,HoveringMouse:!1,FakeMouseWithTouches:!0,TouchInput:!1,MouseInput:!1,KeyboardInput:!1,WaitForStreamer:!0}}),ne=new Dw(oe,{videoElementParent:B.current});ne.addEventListener("webRtcConnected",()=>{console.log("โ
WebRTC Connected"),Q.current=!0,ie(!0),ue(!1),Te(null),C&&C()}),ne.addEventListener("webRtcDisconnected",()=>{console.log("๐ WebRTC Disconnected"),Q.current=!1,ie(!1),R&&R()}),ne.addEventListener("streamLoading",()=>{console.log("โณ Stream Loading"),ue(!0),v&&v()}),ne.addEventListener("playStreamError",me=>{console.error("โ Play Stream Error:",me),Te("Failed to play stream"),ue(!1),_&&_("Failed to play stream")}),ne.addEventListener("playStream",()=>{console.log("โถ๏ธ Stream Playing"),ue(!1),Q.current||(console.log("โ
Stream Playing - Setting connected (fallback)"),Q.current=!0,ie(!0),C&&C())}),ne.addEventListener("videoInitialized",()=>{console.log("๐น Video Initialized"),ue(!1)}),ne.addEventListener("streamerListMessage",me=>{console.log("๐ Streamer list received:",me.data);const pe=me.data?.ids||me.data;pe&&pe.length>0&&console.log("๐ฏ Streamer available, subscribing to:",pe[0])}),te.current=ne}catch(oe){console.error("โ Failed to initialize Pixel Streaming:",oe),Te("Failed to initialize streaming: "+oe.message),ue(!1),_&&_(oe.message)}return()=>{if(console.log("๐งน Cleaning up Epic Pixel Streaming"),te.current){try{te.current._webSocketController&&(console.info("PX websocket connection closed"),te.current._webSocketController.close()),te.current.disconnect()}catch(oe){console.error("Error during cleanup:",oe)}te.current=null}}}},[c,r,f,v,C,R,_]),he.useEffect(()=>{if(te.current)try{const oe=te.current._webRtcController?.videoPlayer;if(!oe){console.log("โ ๏ธ Video player not found");return}let ne=!1;if(oe.audioElement){const pe=oe.audioElement.srcObject;if(pe){const Ne=pe.getAudioTracks();Ne.length>0&&(Ne.forEach(ge=>{ge.enabled=!U}),console.log("๐ Audio element tracks",U?"disabled":"enabled","- Track count:",Ne.length),ne=!0)}}const me=oe.getVideoElement();if(me&&me.srcObject){const Ne=me.srcObject.getAudioTracks();Ne.length>0&&(Ne.forEach(ge=>{ge.enabled=!U}),console.log("๐ Video element audio tracks",U?"disabled":"enabled","- Track count:",Ne.length),ne=!0)}!ne&&me&&(me.muted=U,console.log("๐ Video element muted property set to:",U)),ne||console.log("โ ๏ธ No audio tracks found, using video element muted property")}catch(oe){console.error("Error controlling audio:",oe)}},[U]),sr.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:[sr.jsx("div",{ref:B,className:"player-container",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"hidden",touchAction:"none"}}),ce&&sr.jsxs("div",{className:"loading-overlay",children:[sr.jsx("div",{className:"loading-spinner"}),sr.jsx("div",{className:"loading-text",children:"Connecting to stream..."})]}),!ee&&!ce&&Be&&sr.jsx("div",{className:"connection-overlay",children:sr.jsx("div",{className:"error-message",children:Be})})]})};function Lw({className:c,style:r,autoConnect:n=!0,muted:a=!1,onConnected:f,onDisconnected:v,onError:C}){const{streamingUrl:R,setCloudStreamState:_}=wf();if(!R)return null;const U=()=>{_(Kt.CONNECTING)},B=()=>{_(Kt.LOADING)},te=()=>{_(Kt.CONNECTED),f?.()},Q=()=>{_(Kt.DISCONNECTED),v?.()},ee=ie=>{_(Kt.ERROR,ie),C?.(ie)};return sr.jsx("div",{className:c,style:r,children:sr.jsx(fm,{signallingUrl:R,autoConnect:n,muted:a,onConnecting:U,onLoading:B,onConnected:te,onDisconnected:Q,onError:ee})})}exports.AGENT_TYPES=Vr;exports.CLOUD_STREAM_STATE=Kt;exports.CONNECTION_STATE=Lt;exports.EpicPixelStreamingPlayer=fm;exports.RqmiiAgentProvider=of;exports.RqmiiAgentRoom=Uy;exports.RqmiiCloudAvatarPlayer=Lw;exports.SOCKET_EVENTS=lt;exports.useRqmiiAgent=zy;exports.useRqmiiAgentContext=qr;exports.useRqmiiAudioElement=By;exports.useRqmiiAvatar=wf;exports.useRqmiiConnection=yf;exports.useRqmiiMessages=Dy;exports.useRqmiiPressToTalk=_y;exports.useRqmiiVAD=Oy;exports.useRqmiiVoice=Ly;
|
|
2938
2938
|
//# sourceMappingURL=rqmii-react-agent-sdk.cjs.map
|