UNPKG

lm-avatar-chat-sdk

Version:

lm avatar chat web sdk

4,398 lines 1.56 MB
(function(yt,mi){typeof exports=="object"&&typeof module<"u"?mi(exports):typeof define=="function"&&define.amd?define(["exports"],mi):(yt=typeof globalThis<"u"?globalThis:yt||self,mi(yt.lmCloudAvatarChat={}))})(this,function(yt){"use strict";var tE=Object.defineProperty;var iE=(yt,mi,Un)=>mi in yt?tE(yt,mi,{enumerable:!0,configurable:!0,writable:!0,value:Un}):yt[mi]=Un;var We=(yt,mi,Un)=>iE(yt,typeof mi!="symbol"?mi+"":mi,Un);var mi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Un(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Ll={exports:{}};/*! aliyun rts sdk - ver2.14.6 created:2026/3/25 20:14:32 */(function(i,e){(function(t,n){i.exports=n()})(self,()=>(()=>{var t={280:a=>{var s;s=()=>(()=>{var o={775:f=>{var v=Object.prototype.hasOwnProperty;function p(m){return"[Throws: "+(m?m.message:"?")+"]"}function _(m){var d=[];return function u(b){if(b===null||typeof b!="object")return b;if(d.indexOf(b)!==-1)return"[Circular]";if(d.push(b),typeof b.toJSON=="function")try{var y=u(b.toJSON());return d.pop(),y}catch(R){return p(R)}if(Array.isArray(b)){var g=b.map(u);return d.pop(),g}var S=Object.keys(b).reduce(function(R,E){return R[E]=u(function(I,C){if(v.call(I,C))try{return I[C]}catch(A){return p(A)}return I[C]}(b,E)),R},{});return d.pop(),S}(m)}f.exports=function(m,d,u){return JSON.stringify(_(m),d,u)},f.exports.ensureProperties=_},692:f=>{var v=f.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(p){return p.encoding?"rtpmap:%d %s/%s/%s":p.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(p){return p.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(p){return p.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(p){return"extmap:%d"+(p.direction?"/%s":"%v")+(p["encrypt-uri"]?" %s":"%v")+" %s"+(p.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(p){return p.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(p){var _="candidate:%s %d %s %d %s %d typ %s";return _+=p.raddr!=null?" raddr %s rport %d":"%v%v",_+=p.tcptype!=null?" tcptype %s":"%v",p.generation!=null&&(_+=" generation %d"),(_+=p["network-id"]!=null?" network-id %d":"%v")+(p["network-cost"]!=null?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(p){var _="ssrc:%d";return p.attribute!=null&&(_+=" %s",p.value!=null&&(_+=":%s")),_}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(p){return p.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(p){return p.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(p){return"imageattr:%s %s %s"+(p.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(p){return"simulcast:%s %s"+(p.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(p){return"ts-refclk:%s"+(p.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(p){var _="mediaclk:";return _+=p.id!=null?"id=%s %s":"%v%s",_+=p.mediaClockValue!=null?"=%s":"",(_+=p.rateNumerator!=null?" rate=%s":"")+(p.rateDenominator!=null?"/%s":"")}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(v).forEach(function(p){v[p].forEach(function(_){_.reg||(_.reg=/(.*)/),_.format||(_.format="%s")})})},766:(f,v,p)=>{var _=p(962),m=p(627);v.write=m,v.parse=_.parse,v.parseParams=_.parseParams,v.parseFmtpConfig=_.parseFmtpConfig,v.parsePayloads=_.parsePayloads,v.parseRemoteCandidates=_.parseRemoteCandidates,v.parseImageAttributes=_.parseImageAttributes,v.parseSimulcastStreamList=_.parseSimulcastStreamList},962:(f,v,p)=>{var _=function(y){return String(Number(y))===y?Number(y):y},m=function(y,g,S){var R=y.name&&y.names;y.push&&!g[y.push]?g[y.push]=[]:R&&!g[y.name]&&(g[y.name]={});var E=y.push?{}:R?g[y.name]:g;(function(I,C,A,w){if(w&&!A)C[w]=_(I[1]);else for(var N=0;N<A.length;N+=1)I[N+1]!=null&&(C[A[N]]=_(I[N+1]))})(S.match(y.reg),E,y.names,y.name),y.push&&g[y.push].push(E)},d=p(692),u=RegExp.prototype.test.bind(/^([a-z])=(.*)/);v.parse=function(y){var g={},S=[],R=g;return y.split(/(\r\n|\r|\n)/).filter(u).forEach(function(E){var I=E[0],C=E.slice(2);I==="m"&&(S.push({rtp:[],fmtp:[]}),R=S[S.length-1]);for(var A=0;A<(d[I]||[]).length;A+=1){var w=d[I][A];if(w.reg.test(C))return m(w,R,C)}}),g.media=S,g};var b=function(y,g){var S=g.split(/=(.+)/,2);return S.length===2?y[S[0]]=_(S[1]):S.length===1&&g.length>1&&(y[S[0]]=void 0),y};v.parseParams=function(y){return y.split(/;\s?/).reduce(b,{})},v.parseFmtpConfig=v.parseParams,v.parsePayloads=function(y){return y.toString().split(" ").map(Number)},v.parseRemoteCandidates=function(y){for(var g=[],S=y.split(" ").map(_),R=0;R<S.length;R+=3)g.push({component:S[R],ip:S[R+1],port:S[R+2]});return g},v.parseImageAttributes=function(y){return y.split(" ").map(function(g){return g.substring(1,g.length-1).split(",").reduce(b,{})})},v.parseSimulcastStreamList=function(y){return y.split(";").map(function(g){return g.split(",").map(function(S){var R,E=!1;return S[0]!=="~"?R=_(S):(R=_(S.substring(1,S.length)),E=!0),{scid:R,paused:E}})})}},627:(f,v,p)=>{var _=p(692),m=/%[sdv%]/g,d=function(g){var S=1,R=arguments,E=R.length;return g.replace(m,function(I){if(S>=E)return I;var C=R[S];switch(S+=1,I){case"%%":return"%";case"%s":return String(C);case"%d":return Number(C);case"%v":return""}})},u=function(g,S,R){var E=[g+"="+(S.format instanceof Function?S.format(S.push?R:R[S.name]):S.format)];if(S.names)for(var I=0;I<S.names.length;I+=1){var C=S.names[I];S.name?E.push(R[S.name][C]):E.push(R[S.names[I]])}else E.push(R[S.name]);return d.apply(null,E)},b=["v","o","s","i","u","e","p","c","b","t","r","z","a"],y=["i","c","b","a"];f.exports=function(g,S){S=S||{},g.version==null&&(g.version=0),g.name==null&&(g.name=" "),g.media.forEach(function(C){C.payloads==null&&(C.payloads="")});var R=S.outerOrder||b,E=S.innerOrder||y,I=[];return R.forEach(function(C){_[C].forEach(function(A){A.name in g&&g[A.name]!=null?I.push(u(C,A,g)):A.push in g&&g[A.push]!=null&&g[A.push].forEach(function(w){I.push(u(C,A,w))})})}),g.media.forEach(function(C){I.push(u("m",_.m[0],C)),E.forEach(function(A){_[A].forEach(function(w){w.name in C&&C[w.name]!=null?I.push(u(A,w,C)):w.push in C&&C[w.push]!=null&&C[w.push].forEach(function(N){I.push(u(A,w,N))})})})}),I.join(`\r
`)+`\r
`}},776:function(f,v,p){var _,m=this&&this.__extends||(_=function(W,$){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(B,F){B.__proto__=F}||function(B,F){for(var G in F)Object.prototype.hasOwnProperty.call(F,G)&&(B[G]=F[G])},_(W,$)},function(W,$){if(typeof $!="function"&&$!==null)throw new TypeError("Class extends value "+String($)+" is not a constructor or null");function B(){this.constructor=W}_(W,$),W.prototype=$===null?Object.create($):(B.prototype=$.prototype,new B)}),d=this&&this.__assign||function(){return d=Object.assign||function(W){for(var $,B=1,F=arguments.length;B<F;B++)for(var G in $=arguments[B])Object.prototype.hasOwnProperty.call($,G)&&(W[G]=$[G]);return W},d.apply(this,arguments)},u=this&&this.__awaiter||function(W,$,B,F){return new(B||(B=Promise))(function(G,q){function X(ce){try{se(F.next(ce))}catch(Y){q(Y)}}function J(ce){try{se(F.throw(ce))}catch(Y){q(Y)}}function se(ce){var Y;ce.done?G(ce.value):(Y=ce.value,Y instanceof B?Y:new B(function(fe){fe(Y)})).then(X,J)}se((F=F.apply(W,$||[])).next())})},b=this&&this.__generator||function(W,$){var B,F,G,q,X={label:0,sent:function(){if(1&G[0])throw G[1];return G[1]},trys:[],ops:[]};return q={next:J(0),throw:J(1),return:J(2)},typeof Symbol=="function"&&(q[Symbol.iterator]=function(){return this}),q;function J(se){return function(ce){return function(Y){if(B)throw new TypeError("Generator is already executing.");for(;q&&(q=0,Y[0]&&(X=0)),X;)try{if(B=1,F&&(G=2&Y[0]?F.return:Y[0]?F.throw||((G=F.return)&&G.call(F),0):F.next)&&!(G=G.call(F,Y[1])).done)return G;switch(F=0,G&&(Y=[2&Y[0],G.value]),Y[0]){case 0:case 1:G=Y;break;case 4:return X.label++,{value:Y[1],done:!1};case 5:X.label++,F=Y[1],Y=[0];continue;case 7:Y=X.ops.pop(),X.trys.pop();continue;default:if(!((G=(G=X.trys).length>0&&G[G.length-1])||Y[0]!==6&&Y[0]!==2)){X=0;continue}if(Y[0]===3&&(!G||Y[1]>G[0]&&Y[1]<G[3])){X.label=Y[1];break}if(Y[0]===6&&X.label<G[1]){X.label=G[1],G=Y;break}if(G&&X.label<G[2]){X.label=G[2],X.ops.push(Y);break}G[2]&&X.ops.pop(),X.trys.pop();continue}Y=$.call(W,X)}catch(fe){Y=[6,fe],F=0}finally{B=G=0}if(5&Y[0])throw Y[1];return{value:Y[0]?Y[1]:void 0,done:!0}}([se,ce])}}},y=this&&this.__spreadArray||function(W,$,B){if(B||arguments.length===2)for(var F,G=0,q=$.length;G<q;G++)!F&&G in $||(F||(F=Array.prototype.slice.call($,0,G)),F[G]=$[G]);return W.concat(F||Array.prototype.slice.call($))},g=this&&this.__importDefault||function(W){return W&&W.__esModule?W:{default:W}};Object.defineProperty(v,"__esModule",{value:!0}),v.PeerConnectionCore=v.DEFAULT_HEARTBEAT_INTERVAL=v.EDatachannelStatus=void 0;var S=p(887),R=p(248),E=p(237),I=p(619),C=p(628),A=p(748),w=p(961),N=p(844),M=p(651);Object.defineProperty(v,"EDatachannelStatus",{enumerable:!0,get:function(){return M.EDatachannelStatus}});var D,L=p(854),P=g(p(885)),x=p(132),T=g(p(123)),O=p(125),k="rts video",H="rts audio";v.DEFAULT_HEARTBEAT_INTERVAL=2500,function(W){W.SUB_ADD="subsribe add",W.SUB_DELETE="subscribe delete",W.SUB_ACTIVE="subscribe active",W.SUB_STOP="subscribe stop",W.PUB_ADD="publish add",W.PUB_DELETE="publish delete",W.PUB_REPLACE="publish replace",W.PUB_STOP="publish stop",W.DATACHANNEL_SUB_ADD="sub add datachannel",W.DATACHANNEL_SUB_ACTIVE="sub active datachannel",W.DATACHANNEL_SUB_DELETE="sub delete datachannel",W.DATACHANNEL_SUB_STOP="sub stop datachannel",W.DATACHANNEL_PUB_ADD="pub add datachannel",W.DATACHANNEL_PUB_DELETE="pub delete datachannel",W.DATACHANNEL_PUB_STOP="pub stop datachannel"}(D||(D={}));var U=function(W){function $(B){var F=W.call(this)||this;return F.PCCore=B,F}return m($,W),$.prototype.excuteSignal=function(B,F,G,q){var X=this;switch(B){case D.SUB_ADD:this.PCCore.proceedSubscribeAdd(q.configList,q.reconnecting).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.SUB_DELETE:this.PCCore.proceedSubscribeDeleteTracks(q.configList,q.skipError).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.SUB_ACTIVE:break;case D.SUB_STOP:this.PCCore.proceedSubscribeStop(q.configList).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.PUB_ADD:this.PCCore.proceedPublishAdd(q.configList).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.PUB_REPLACE:this.PCCore.proceedPublishReplaceTracks(q.configList).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.PUB_DELETE:this.PCCore.proceedPublishDeleteTracks(q.configList).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.PUB_STOP:this.PCCore.proceedPublishStop(q.configList).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.DATACHANNEL_SUB_ADD:this.PCCore.proceedSubscribeAddDatachannel(q.configList).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.DATACHANNEL_SUB_DELETE:this.PCCore.proceedSubscribeDeleteDatachannel(q.configList).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.DATACHANNEL_SUB_STOP:this.PCCore.proceedSubscribeStopDatachannel(q.configList).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.DATACHANNEL_PUB_ADD:this.PCCore.proceedPublishAddDatachannel(q.configList).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.DATACHANNEL_PUB_DELETE:this.PCCore.proceedPublishDeleteDatachannel(q.configList).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")});break;case D.DATACHANNEL_PUB_STOP:this.PCCore.proceedPublishStopDatachannel(q.configList).then(function(J){F(J)}).catch(function(J){G(J)}).finally(function(){X.emit("onSignalDone")})}},$}(P.default),ee=function(W){function $(B){var F=W.call(this)||this;return F.heartbeatTimelineMap=new Map,F.removeTwcc=!1,F.mutex=!1,F.eventQueue=new L.CacheBuffer("signal queue"),F.rollbackController=new x.PeerConnectionRollbackController(F),F.onInnerSubscribeDelete=function(){},F.receiverCodecPreferences={},F.senderCodecPreferences={},F.removeTrackListener=function(){},F.heartbeatTimerHandle=null,F.heartbeatTokenRing=0,F.streamManager=new C.StreamManager,F.datachannelManager=new A.DatachannelManager,B.pc?(F.pc=B.pc,F.signal=new I.Signal({pc:B.pc,onDatachannelEvent:B.onDatachannelEvent,delayOpen:B.delayOpen,initOptions:B.signalDatachannelInitOptions}),F.initSignalListener(),F.heartbeatProcessor=new T.default(F.streamManager,F.datachannelManager),F.initHeartbeatListener(),F.notifyProcessor=new O.NotifyProcessor,F.initNotifyListener(),F.onInnerSubscribeDelete=B.onInnerSubscribeDelete||function(){},F.offerSdpHook=B.offerSdpHook,F.answerSdpHook=B.answerSdpHook,F):(console.error("peerconnetion is required"),F)}return m($,W),$.prototype.getStreamManager=function(){return this.streamManager},$.prototype.getDatachannelManager=function(){return this.datachannelManager},$.prototype.getSignal=function(){return this.signal},$.prototype.setPrevOfferSdp=function(B){this.prevOfferSdp=B},$.prototype.setPrevAnswerSdp=function(B){this.prevAnswerSdp=B},$.prototype.setStreamManager=function(B){this.streamManager=B},$.prototype.getTrackIds=function(B){return B.reduce(function(F,G){return y(y([],F,!0),[G.id],!1)},[])},$.prototype.setRemoveTwcc=function(B){this.removeTwcc=B},$.prototype.setReceiverCodecPreferences=function(B){this.receiverCodecPreferences=d({},B)},$.prototype.setSenderCodecPreferences=function(B){this.senderCodecPreferences=d({},B)},$.prototype.subscribeAdd=function(B,F){var G=this;return new Promise(function(q,X){var J=new U(G);if(G.mutex){var se={type:D.SUB_ADD,excuter:J,res:q,rej:X,data:{configList:B,reconnecting:F}};G.mergeSignal(se)||G.eventQueue.cache(se)}else G.log("merge subscribeAdd 不入队直接执行"),G.atomSignalExec(D.SUB_ADD,J,q,X,{configList:B,reconnecting:F})})},$.prototype.subscribeDeleteTracks=function(B,F){var G=this;return new Promise(function(q,X){var J=new U(G);if(G.mutex){var se={type:D.SUB_DELETE,excuter:J,res:q,rej:X,data:{configList:B,skipError:F}};G.mergeSignal(se)||G.eventQueue.cache(se)}else G.log("merge subscribeDeleteTracks 不入队直接执行"),G.atomSignalExec(D.SUB_DELETE,J,q,X,{configList:B,skipError:F})})},$.prototype.subscribeStop=function(B){var F=this;return new Promise(function(G,q){var X=new U(F);if(F.mutex){var J={type:D.SUB_STOP,excuter:X,res:G,rej:q,data:{configList:B}};F.eventQueue.cache(J)}else F.atomSignalExec(D.SUB_STOP,X,G,q,{configList:B})})},$.prototype.publishAdd=function(B){var F=this;return new Promise(function(G,q){var X=new U(F);if(F.mutex){var J={type:D.PUB_ADD,excuter:X,res:G,rej:q,data:{configList:B}};F.eventQueue.cache(J)}else F.atomSignalExec(D.PUB_ADD,X,G,q,{configList:B})})},$.prototype.publishReplaceTracks=function(B){var F=this;return new Promise(function(G,q){var X=new U(F);if(F.mutex){var J={type:D.PUB_REPLACE,excuter:X,res:G,rej:q,data:{configList:B}};F.eventQueue.cache(J)}else F.atomSignalExec(D.PUB_REPLACE,X,G,q,{configList:B})})},$.prototype.publishDeleteTracks=function(B){var F=this;return new Promise(function(G,q){var X=new U(F);if(F.mutex){var J={type:D.PUB_DELETE,excuter:X,res:G,rej:q,data:{configList:B}};F.eventQueue.cache(J)}else F.atomSignalExec(D.PUB_DELETE,X,G,q,{configList:B})})},$.prototype.publishStop=function(B){var F=this;return new Promise(function(G,q){var X=new U(F);if(F.mutex){var J={type:D.PUB_STOP,excuter:X,res:G,rej:q,data:{configList:B}};F.eventQueue.cache(J)}else F.atomSignalExec(D.PUB_STOP,X,G,q,{configList:B})})},$.prototype.subscribeAddDatachannel=function(B){var F=this;return new Promise(function(G,q){var X=new U(F);if(F.mutex){var J={type:D.DATACHANNEL_SUB_ADD,excuter:X,res:G,rej:q,data:{configList:B}};F.eventQueue.cache(J)}else F.atomSignalExec(D.DATACHANNEL_SUB_ADD,X,G,q,{configList:B})})},$.prototype.subscribeDeleteDatachannel=function(B){var F=this;return new Promise(function(G,q){var X=new U(F);if(F.mutex){var J={type:D.DATACHANNEL_SUB_DELETE,excuter:X,res:G,rej:q,data:{configList:B}};F.eventQueue.cache(J)}else F.atomSignalExec(D.DATACHANNEL_SUB_DELETE,X,G,q,{configList:B})})},$.prototype.subscribeStopDatachannel=function(B){var F=this;return new Promise(function(G,q){var X=new U(F);if(F.mutex){var J={type:D.DATACHANNEL_SUB_STOP,excuter:X,res:G,rej:q,data:{configList:B}};F.eventQueue.cache(J)}else F.atomSignalExec(D.DATACHANNEL_SUB_STOP,X,G,q,{configList:B})})},$.prototype.publishAddDatachannel=function(B){var F=this;return new Promise(function(G,q){var X=new U(F);if(F.mutex){var J={type:D.DATACHANNEL_PUB_ADD,excuter:X,res:G,rej:q,data:{configList:B}};F.eventQueue.cache(J)}else F.atomSignalExec(D.DATACHANNEL_PUB_ADD,X,G,q,{configList:B})})},$.prototype.publishDeleteDatachannel=function(B){var F=this;return new Promise(function(G,q){var X=new U(F);if(F.mutex){var J={type:D.DATACHANNEL_PUB_DELETE,excuter:X,res:G,rej:q,data:{configList:B}};F.eventQueue.cache(J)}else F.atomSignalExec(D.DATACHANNEL_PUB_DELETE,X,G,q,{configList:B})})},$.prototype.publishStopDatachannel=function(B){var F=this;return new Promise(function(G,q){var X=new U(F);if(F.mutex){var J={type:D.DATACHANNEL_PUB_STOP,excuter:X,res:G,rej:q,data:{configList:B}};F.eventQueue.cache(J)}else F.atomSignalExec(D.DATACHANNEL_PUB_STOP,X,G,q,{configList:B})})},$.prototype.atomSignalExec=function(B,F,G,q,X){var J=this;this.mutex=!0,F.once("onSignalDone",function(){J.eventQueue.isEmpty()?J.mutex=!1:setTimeout(function(){if(J.eventQueue.isEmpty())J.mutex=!1;else{var se=J.eventQueue.getFirst();J.atomSignalExec(se.type,se.excuter,se.res,se.rej,se.data)}})}),F.excuteSignal(B,G,q,X)},$.prototype.getSignalMergeKey=function(B,F){if(B!==D.SUB_ADD&&B!==D.SUB_DELETE)return console.log("Only support add / delete sub operation merge"),null;var G=F;if(!G||!G.length)return null;var q=G[0],X=q.url,J=q.aMsid,se=q.vMsid,ce=(0,S.pruneSubUrl)(X,!0);return"".concat(ce,"|").concat((J==null?void 0:J[0])||"","|").concat((se==null?void 0:se[0])||"")},$.prototype.mergeSignal=function(B){var F=this.getSignalMergeKey(B.type,B.data.configList);if(!F)return console.warn("key:".concat(B.type," 不支持merge,但依然入队")),!1;var G=B.type===D.SUB_ADD?D.SUB_DELETE:D.SUB_ADD;this.log("mergeSignal:",B.type,",队列大小:",this.eventQueue.data.length);for(var q=0;q<this.eventQueue.data.length;q++){var X=this.eventQueue.data[q];if(this.getSignalMergeKey(X.type,X.data.configList)===F)return X.type===G?(this.log('merge 没入队:reject队列里的:"'.concat(X.type,'",并reject新增的"').concat(B.type,'", key=').concat(F)),X.rej(new w.RtsError(N.ErrorCode.CORE_IGNORE_SIGNAL_REQUEST,"ignore old queued opposite item","")),B.rej(new w.RtsError(N.ErrorCode.CORE_IGNORE_SIGNAL_REQUEST,"ignore current request item","")),this.eventQueue.data.splice(q,1),!0):(this.log('merge 入队:新增的"'.concat(B.type,'",但剔除队列里旧的重复的: "').concat(X.type,'", key=').concat(F)),X.rej(new w.RtsError(N.ErrorCode.CORE_IGNORE_SIGNAL_REQUEST,"ignore old same request item","")),this.eventQueue.data.splice(q,1),!1)}return this.log('merge 入队:"'.concat(B.type,'", key=').concat(F)),!1},$.prototype.proceedSubscribeAdd=function(B,F){return u(this,void 0,void 0,function(){var G,q,X,J,se,ce,Y,fe,he,pe=this;return b(this,function(ue){switch(ue.label){case 0:if(G=new Date().getTime(),q=new Date().getTime(),X=new Date().getTime(),J=this,se=this.extendUrl(B),ce=se.map(function(Te){var be=Te.urlData,Z=Te.vMsid,K=Te.aMsid;if(pe.streamManager.has(be.url)){var re=pe.streamManager.get(be.url),de=re.videoInfoList.map(function(De){return De.msid}),ye=re.audioInfoList.map(function(De){return De.msid}),Ee=(0,S.intersection)(de,Z),Ve=(0,S.intersection)(ye,K);if(Ve.length||Ee.length)return{url:be.url,vMsid:Ee,aMsid:Ve}}}).filter(function(Te){return Te}),Y=[],!(ce!=null&&ce.length))return[3,4];ue.label=1;case 1:return ue.trys.push([1,3,,4]),[4,this.proceedSubscribeDeleteTracks(ce,!0,F)];case 2:return Y=ue.sent(),this.onInnerSubscribeDelete&&this.onInnerSubscribeDelete(ce),[3,4];case 3:throw fe=ue.sent(),(he=fe).extraInfo=d(d({},he.extraInfo),{api:"subscribeAdd",signal_api:"subscribeDeleteTracks",configList:B}),he;case 4:return G=new Date().getTime(),[2,new Promise(function(Te,be){return u(pe,void 0,void 0,function(){function Z(){return u(this,void 0,void 0,function(){var te,Q;return b(this,function(ne){switch(ne.label){case 0:J.removeTrackListener(),te=J.buildUrlStreamMap(se),ne.label=1;case 1:return ne.trys.push([1,3,,4]),[4,J.subscribeActive(B)];case 2:return ne.sent(),[3,4];case 3:return(Q=ne.sent()).extraInfo=d(d({},Q.extraInfo),{api:"subscribeAdd",signal_api:"subscribeActive"}),J.rollbackController.rollback({pcTransceiversRollback:!0,streamManagerRollback:!0}),[2,be(Q)];case 4:return q=new Date().getTime(),Te({deleteRspTime:G,subAddRspTime:X,activeRspTime:q,streamList:te}),[2]}})})}var K,re,de,ye,Ee,Ve,De,Ue,Ye,Ie,Oe,$e,Ke,Fe,st,tt,z,j=this;return b(this,function(te){switch(te.label){case 0:if(!this.pc)return[2,be(new w.RtsError(N.ErrorCode.CORE_NO_PC_ERROR,"subscribeAdd: no peerconnection",""))];this.pc.addEventListener("track",Z),this.removeTrackListener=function(){var Q;(Q=j.pc)===null||Q===void 0||Q.removeEventListener("track",Z)},this.rollbackController.saveStreamManager(this.streamManager),K=[],se.forEach(function(Q){var ne,ae,oe=Q.urlData,Se=Q.vMsid,_e=Q.aMsid;if(j.pc){if(j.streamManager.init(oe.url),oe.subVideo&&!j.streamManager.isMsidSubPubDone(oe.url,{vMsid:Se[0]})){var xe=j.pc.addTransceiver("video",{direction:"recvonly"});K.push({type:"video",msid:Se[0],trans:xe});var Pe=(ne=Y.find(function(it){return it.vMsid===Se[0]}))===null||ne===void 0?void 0:ne.vStream;j.streamManager.update(oe.url,{vMsid:Se[0],vTransceiver:xe,stream:Pe,cumuDelay:j.cumuDelay}),j.setCodecPreferences(xe,j.receiverCodecPreferences.video)}if(oe.subAudio&&!j.streamManager.isMsidSubPubDone(oe.url,{aMsid:_e[0]})){var He=j.pc.addTransceiver("audio",{direction:"recvonly"});K.push({type:"audio",msid:_e[0],trans:He}),Pe=(ae=Y.find(function(it){return it.aMsid===_e[0]}))===null||ae===void 0?void 0:ae.aStream,j.streamManager.update(oe.url,{aMsid:_e[0],aTransceiver:He,stream:Pe}),j.setCodecPreferences(He,j.receiverCodecPreferences.audio)}}}),this.rollbackController.setFakeSdpMedias(K,"sub"),te.label=1;case 1:return te.trys.push([1,3,,4]),[4,this.pc.createOffer()];case 2:return re=te.sent(),[3,4];case 3:return de=te.sent(),[2,be(new w.RtsError(N.ErrorCode.DATACHANNEL_CREATE_OFFER_ERROR,"CreateOffer Error: ".concat(de),"",{api:"subscribeAdd",err:de}))];case 4:if(ye=new R.SdpUtil({sdp:re.sdp||""}),this.restorePublishedSsrc(ye),ye.addNack(),ye.updateBundle(),re=new RTCSessionDescription({type:"offer",sdp:ye.generate()}),Ee=this.findNewSubPubMids((re==null?void 0:re.sdp)||"",this.prevOfferSdp||""),this.setPrevOfferSdp(re.sdp||""),this.rollbackController.setFakeSdpMids(Ee),Ve=this.avoidMsidConflict(re.sdp),this.offerSdpHook)try{Ve=this.offerSdpHook(Ve)}catch(Q){console.log("offerSdpHook error: ",Q)}te.label=5;case 5:return te.trys.push([5,7,,9]),[4,this.pc.setLocalDescription(new RTCSessionDescription({type:"offer",sdp:Ve}))];case 6:return te.sent(),[3,9];case 7:return De=te.sent(),[4,this.rollbackController.rollback({trackListnerRollback:!0,pcTransceiversRollback:!0,streamManagerRollback:!0,runSimulateSignal:!0})];case 8:return te.sent(),[2,be(new w.RtsError(N.ErrorCode.DATACHANNEL_SET_OFFER_ERROR,"SetLocalDescription error: ".concat(De),"",{api:"subscribeAdd",sdp:re}))];case 9:if(Ue=[],Ye=[],se.forEach(function(Q){var ne=new R.SdpUtil({sdp:(re==null?void 0:re.sdp)||""}),ae=[],oe=Q.vMsid.length!==0,Se=Q.aMsid.length!==0,_e=!1,xe=!1;ne.detail.media.forEach(function(He){var it=String(He.mid);Ee.includes(it)&&(Ye.includes(it)||(He.type==="video"&&oe&&!_e?(ae.push(String(He.mid)),_e=!0):He.type==="audio"&&Se&&!xe&&(ae.push(String(He.mid)),xe=!0)))}),Ye=y(y([],Ye,!0),ae,!0),ne.keepMedia(ae);var Pe=ne.generate();j.cumuDelay&&(Pe=Pe.replace(/(m=video[^\n]*\n)/,`$1a=cumudelay
`)),Ue.push(Pe)}),this.offerSdpHook)try{Ue=Ue.map(function(Q){return j.offerSdpHook(Q)})}catch(Q){console.log("offerSdpHook error: ",Q)}te.label=10;case 10:return te.trys.push([10,12,,14]),[4,(z=this.signal)===null||z===void 0?void 0:z.subscribeAdd(se,Ue,this.streamManager)];case 11:return Ie=te.sent(),[3,14];case 12:return Oe=te.sent(),[4,this.rollbackController.rollback({trackListnerRollback:!0,pcTransceiversRollback:!0,streamManagerRollback:!0,runSimulateSignal:!0})];case 13:return te.sent(),Oe.extraInfo=d({api:"subscribeAdd",signal_api:"subscribeAdd"},Oe.extraInfo),[2,be(Oe)];case 14:if($e=[],Ie.streams.forEach(function(Q,ne){j.log("Sub TraceId[".concat(ne,"]: "),Q.traceid);var ae=new R.SdpUtil({sdp:Q.sdp});$e=y(y([],$e,!0),ae.detail.media,!0);var oe=se.find(function(Se){return Se.urlData.url===Q.url});oe&&(oe.traceId=Q.traceid,oe.urlTraceId=Q.url_traceid)}),(Ke=new R.SdpUtil({sdp:this.prevAnswerSdp||""})).addOrUpdateMedia($e),this.alignAnswerMidsWithOffer(Ke),Fe=Ke.generate(),this.setPrevAnswerSdp(Fe),st=this.avoidMsidConflict(Fe),this.answerSdpHook)try{st=this.answerSdpHook(st)}catch(Q){console.log("answerSdpHook error: ",Q)}te.label=15;case 15:return te.trys.push([15,17,,19]),[4,this.pc.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:st}))];case 16:return te.sent(),se.forEach(function(Q){j.streamManager.markAlreadySubPub(Q.urlData.url,{vMsid:Q.vMsid[0],aMsid:Q.aMsid[0]})}),[3,19];case 17:return tt=te.sent(),[4,this.rollbackController.rollback({trackListnerRollback:!0,pcTransceiversRollback:!0,streamManagerRollback:!0})];case 18:return te.sent(),[2,be(new w.RtsError(N.ErrorCode.DATACHANNEL_SET_ANSWER_ERROR,"SetRemoteDescription error: ".concat(tt),"",{api:"subscribeAdd",sdp:Fe}))];case 19:return X=new Date().getTime(),[2]}})})})]}})})},$.prototype.subscribeActive=function(B){var F;return u(this,void 0,void 0,function(){return b(this,function(G){return[2,(F=this.signal)===null||F===void 0?void 0:F.subscribeActive(this.extendUrl(B))]})})},$.prototype.proceedSubscribeDeleteTracks=function(B,F,G){var q,X,J,se;return u(this,void 0,void 0,function(){var ce,Y,fe,he,pe,ue,Te,be=this;return b(this,function(Z){switch(Z.label){case 0:B.forEach(function(K){K.rawUrl=K.url,K.url=be.streamManager.getOriginUrl(K.url)}),ce=!1,Y=!!F,fe=void 0,Z.label=1;case 1:return Z.trys.push([1,3,,4]),[4,(q=this.signal)===null||q===void 0?void 0:q.subscribeDelete(B)];case 2:return Z.sent(),[3,4];case 3:return he=Z.sent(),ce=(fe=he).errorCode===N.ErrorCode.DATACHANNEL_RESPONSE_ERROR&&((J=(X=fe.extraInfo)===null||X===void 0?void 0:X.parsedData)===null||J===void 0?void 0:J.streams)&&((se=fe.extraInfo.parsedData.streams[0])===null||se===void 0?void 0:se.res_code)===404,[3,4];case 4:if(fe&&!ce)throw fe.extraInfo=d({api:"subscribeDeleteTracks"},fe.extraInfo),fe;return pe=Y&&ce,ue=[],Te=B.map(function(K){var re=K.url,de=K.vMsid,ye=K.aMsid,Ee=K.rawUrl;return u(be,void 0,void 0,function(){var Ve,De,Ue,Ye,Ie,Oe,$e,Ke,Fe,st;return b(this,function(tt){switch(tt.label){case 0:re=(0,S.pruneSubUrl)(re),this.streamManager.has(re)&&(de&&(Ue=this.streamManager.getTransceiver(re,{vMsid:de[0]}))&&(De=Ue.receiver.track).stop(),ye&&(Ye=this.streamManager.getTransceiver(re,{aMsid:ye[0]}))&&(Ve=Ye.receiver.track).stop()),tt.label=1;case 1:return tt.trys.push([1,3,,4]),[4,this.simulateOfferAnswer()];case 2:return tt.sent(),[3,4];case 3:throw(Ie=tt.sent()).extraInfo=d({api:"subscribeDeleteTracks"},Ie.extraInfo),Ie;case 4:return De&&(Oe=this.streamManager.getStreamByMsid({url:re,vMsid:de==null?void 0:de[0]}),(Fe=Oe==null?void 0:Oe.mediastream)===null||Fe===void 0||Fe.removeTrack(De)),Ve&&($e=this.streamManager.getStreamByMsid({url:re,aMsid:ye==null?void 0:ye[0]}),(st=$e==null?void 0:$e.mediastream)===null||st===void 0||st.removeTrack(Ve)),G||this.streamManager.pruneStreamList(re),this.streamManager.removeMsid(re,{vMsid:de!=null&&de.length?this.unifyMsid(de,"video"):void 0,aMsid:ye!=null&&ye.length?this.unifyMsid(ye,"audio"):void 0}),Ke={url:Ee||"",stream:this.streamManager.getStreamByMsid({url:re,vMsid:de==null?void 0:de[0],aMsid:ye==null?void 0:ye[0]})},G&&(Ke=d(d({},Ke),{vStream:Oe,aStream:$e,vMsid:de==null?void 0:de[0],aMsid:ye==null?void 0:ye[0]})),ue.push(Ke),[2]}})})}),[4,Promise.all(Te)];case 5:if(Z.sent(),!pe&&fe)throw fe.extraInfo=d({api:"subscribeDeleteTracks"},fe.extraInfo),fe;return[2,ue]}})})},$.prototype.proceedSubscribeStop=function(B){var F;return u(this,void 0,void 0,function(){var G,q,X=this;return b(this,function(J){switch(J.label){case 0:return J.trys.push([0,2,,3]),[4,(F=this.signal)===null||F===void 0?void 0:F.subscribeStop(this.extendUrl(B))];case 1:return J.sent(),[3,3];case 2:throw(G=J.sent()).extraInfo=d({api:"subscribeStop"},G.extraInfo),G;case 3:return B.forEach(function(se){se.rawUrl=se.url,se.url=X.streamManager.getOriginUrl(se.url)}),q=B.map(function(se){var ce=se.url;return se.rawUrl,se.targetStreams,u(X,void 0,void 0,function(){var Y;return b(this,function(fe){switch(fe.label){case 0:ce=(0,S.pruneSubUrl)(ce),this.streamManager.getAllTransceivers(ce).forEach(function(he){var pe;(pe=he==null?void 0:he.receiver.track)===null||pe===void 0||pe.stop()}),this.streamManager.get(ce).streamList.forEach(function(he){return he.release()}),this.streamManager.remove(ce),fe.label=1;case 1:return fe.trys.push([1,3,,4]),[4,this.simulateOfferAnswer()];case 2:return fe.sent(),[3,4];case 3:throw(Y=fe.sent()).extraInfo=d({api:"subscribeStop"},Y.extraInfo),Y;case 4:return[2]}})})}),[4,Promise.all(q)];case 4:return J.sent(),[2]}})})},$.prototype.proceedPublishAdd=function(B){var F;return u(this,void 0,void 0,function(){var G,q,X,J,se,ce,Y,fe,he,pe,ue,Te,be,Z,K,re,de,ye,Ee,Ve,De,Ue,Ye,Ie,Oe,$e,Ke,Fe,st,tt=this;return b(this,function(z){switch(z.label){case 0:if(B.length>1)throw console.error("Only one stream is supported."),new w.RtsError(N.ErrorCode.CORE_PUBLIST_EXCEED_ERROR,"publishAdd: publishList exceed limit","",{api:"publishAdd"});if(!this.pc)throw new w.RtsError(N.ErrorCode.CORE_NO_PC_ERROR,"publishAdd: no peerconnection","",{api:"publishAdd"});G=B[0],q=G.stream,X=this.unifyMsid(G.aMsid,"audio"),J=this.unifyMsid(G.vMsid,"video"),G.rawUrl=G.url,G.url=this.streamManager.getOriginUrl(G.url),typeof G.updateSourceStream!="boolean"&&(G.updateSourceStream=!0),se=q.videoTrack,ce=q.audioTrack,this.rollbackController.saveStreamManager(this.streamManager),Y=[],fe=this.streamManager.getStreamByMsid({url:G.url,vMsid:J,aMsid:X}),this.streamManager.init(G.url,C.EStreamType.Publish),se&&(he=this.pc.addTransceiver(q.videoTrack,{direction:"sendonly"}),this.streamManager.update(G.url,{vMsid:J,vTransceiver:he,stream:q,cumuDelay:this.cumuDelay}),Y.push({type:"video",trans:he,msid:J}),this.setCodecPreferences(he,this.senderCodecPreferences.video)),ce&&(he=this.pc.addTransceiver(q.audioTrack,{direction:"sendonly"}),this.streamManager.update(G.url,{aMsid:X,aTransceiver:he,stream:q}),Y.push({type:"audio",trans:he,msid:X}),this.setCodecPreferences(he,this.senderCodecPreferences.audio)),this.rollbackController.setFakeSdpMedias(Y,"pub"),z.label=1;case 1:return z.trys.push([1,3,,4]),[4,this.pc.createOffer()];case 2:return pe=z.sent(),[3,4];case 3:throw ue=z.sent(),new w.RtsError(N.ErrorCode.DATACHANNEL_CREATE_OFFER_ERROR,"CreateOffer Error: ".concat(ue),"",{api:"publishAdd",err:ue});case 4:if(Te=new R.SdpUtil({sdp:pe.sdp||""}),be=this.parseMsidString(J),Z=this.parseMsidString(X),K=this.findNewSubPubMids(pe.sdp||"",this.prevOfferSdp||""),this.rollbackController.setFakeSdpMids(K),be.stream&&Te.detail.msidSemantic&&(Te.detail.msidSemantic.token=be.stream),re=Te.detail.media.reduce(function(j,te){return te.direction==="inactive"?y(y([],j,!0),[String(te.mid)],!1):j},[]),Te.detail.media.forEach(function(j){var te;if(j.direction!=="recvonly"&&j.type!=="application"&&K.includes(String(j.mid))){var Q=j.type==="video"?be:Z,ne=tt.parseMsidString(j.msid);ne.stream=Q.stream||ne.stream,ne.track=Q.track||ne.track;var ae=tt.stringifyMsid(ne);j.msid=ae,(te=j.ssrcs)===null||te===void 0||te.forEach(function(oe){switch(oe.attribute){case"cname":case"label":oe.value=Q.track||oe.value;break;case"msid":oe.value=ae;break;case"mslabel":oe.value=Q.stream||oe.value}})}}),this.restorePublishedSsrc(Te),this.restorePublishMsid(Te),Te.addNack(),de=Te.generate(),this.setPrevOfferSdp(de),ye=this.avoidMsidConflict(de),this.offerSdpHook)try{ye=this.offerSdpHook(ye)}catch(j){console.log("offerSdoHook error: ",j)}z.label=5;case 5:return z.trys.push([5,7,,8]),[4,this.pc.setLocalDescription(new RTCSessionDescription({type:"offer",sdp:ye}))];case 6:return z.sent(),[3,8];case 7:throw Ee=z.sent(),this.rollbackController.rollback({streamManagerRollback:!0,runSimulateSignal:!0}),new w.RtsError(N.ErrorCode.DATACHANNEL_SET_OFFER_ERROR,"SetLocalDescription error: ".concat(Ee),"",{api:"publishAdd",sdp:de});case 8:if(Te.keepMedia(K),this.updateTrackInfoList({url:G.rawUrl,stream:G.stream,vMsid:J,aMsid:X,sdpMediaList:Te.detail.media}),ye=Te.generate(),this.offerSdpHook)try{ye=this.offerSdpHook(ye)}catch(j){console.log("offerSdpHook error: ",j)}z.label=9;case 9:return z.trys.push([9,11,,12]),[4,(F=this.signal)===null||F===void 0?void 0:F.publishAdd([G.url],[ye],[se?[this.stringifyMsid(be)]:[]],[ce?[this.stringifyMsid(Z)]:[]])];case 10:return Ve=z.sent(),[3,12];case 11:throw De=z.sent(),(Ue=De).extraInfo=d({api:"publishAdd"},Ue.extraInfo),this.rollbackController.rollback({streamManagerRollback:!0,runSimulateSignal:!0}),Ue;case 12:if(Ye=Ve.streams[0],G.traceId=Ye.traceid,G.urlTraceId=Ye.url_traceid,this.log("Pub TraceId: ",G.traceId),(Ie=new R.SdpUtil({sdp:Ye.sdp})).detail.media.forEach(function(j){j.type!=="application"&&j.direction==="sendrecv"&&(j.direction="recvonly")}),(Oe=new R.SdpUtil({sdp:this.prevAnswerSdp||""})).detail.media.forEach(function(j){j.type==="application"&&(delete j.candidates,delete j.endOfCandidates)}),Oe.setMediaInactive(re),Oe.addOrUpdateMedia(Ie.detail.media,{isPublish:!0}),this.alignAnswerMidsWithOffer(Oe),this.removeTwcc&&($e=["http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"],Oe.detail.media.forEach(function(j){var te;j.ext=(te=j.ext)===null||te===void 0?void 0:te.filter(function(Q){return!$e.includes(Q.uri)})})),Ke=Oe.generate(),this.setPrevAnswerSdp(Ke),Fe=this.avoidMsidConflict(Ke),this.answerSdpHook)try{Fe=this.answerSdpHook(Fe)}catch(j){console.log("answerSdpHook error: ",j)}z.label=13;case 13:return z.trys.push([13,15,,16]),[4,this.pc.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:Fe}))];case 14:return z.sent(),this.streamManager.markAlreadySubPub(G.url,{vMsid:J,aMsid:X,isPub:!0}),[3,16];case 15:throw st=z.sent(),this.rollbackController.rollback({streamManagerRollback:!0}),new w.RtsError(N.ErrorCode.DATACHANNEL_SET_ANSWER_ERROR,"SetRemoteDescription error: ".concat(st),"",{api:"publishAdd",sdp:Ke});case 16:return fe&&G.updateSourceStream&&fe.mergeStream(q),[2,B.map(function(j){return{url:j.rawUrl,trackInfoList:tt.streamManager.getAllMediaInfoList(G.url),traceId:j.traceId,urlTraceId:j.urlTraceId}})]}})})},$.prototype.proceedPublishDeleteTracks=function(B){var F,G,q,X,J,se,ce;return u(this,void 0,void 0,function(){var Y,fe,he,pe,ue,Te,be,Z,K,re,de=this;return b(this,function(ye){switch(ye.label){case 0:B.forEach(function(Ee){Ee.rawUrl=Ee.url,Ee.url=de.streamManager.getOriginUrl(Ee.url)}),ye.label=1;case 1:return ye.trys.push([1,3,,4]),[4,(F=this.signal)===null||F===void 0?void 0:F.publishDelete(B)];case 2:return ye.sent(),[3,4];case 3:throw(Y=ye.sent()).extraInfo=d({api:"publishDeleteTracks"},Y.extraInfo),Y;case 4:if(fe=B[0],he=(0,S.pruneSubUrl)(fe.url),typeof fe.updateSourceStream!="boolean"&&(fe.updateSourceStream=!0),pe=!1,ue=!1,!this.streamManager.has(he))return[3,9];!((G=fe.vMsid)===null||G===void 0)&&G.length&&((Te=this.streamManager.getTransceiver(he,{vMsid:fe.vMsid[0]}))!=null&&Te.sender&&((q=this.pc)===null||q===void 0||q.removeTrack(Te==null?void 0:Te.sender)),pe=!0),!((X=fe.aMsid)===null||X===void 0)&&X.length&&((be=this.streamManager.getTransceiver(he,{aMsid:fe.aMsid[0]}))!=null&&be.sender&&((J=this.pc)===null||J===void 0||J.removeTrack(be==null?void 0:be.sender)),ue=!0),ye.label=5;case 5:return ye.trys.push([5,7,,8]),[4,this.simulateOfferAnswer()];case 6:return ye.sent(),[3,8];case 7:throw(Z=ye.sent()).extraInfo=d({api:"publishDeleteTracks"},Z.extraInfo),Z;case 8:return(K=this.streamManager.getStreamByMsid({url:he,vMsid:(se=fe.vMsid)===null||se===void 0?void 0:se[0],aMsid:(ce=fe.aMsid)===null||ce===void 0?void 0:ce[0]}))&&fe.updateSourceStream&&K.deleteTracks({video:pe,audio:ue}),this.streamManager.removeMsid(he,{vMsid:pe?this.unifyMsid(fe.vMsid,"video"):void 0,aMsid:ue?this.unifyMsid(fe.aMsid,"audio"):void 0}),this.streamManager.pruneStreamList(he),re=this.streamManager.getAllMediaInfoList(fe.url),[2,B.map(function(Ee){return{url:Ee.rawUrl,trackInfoList:re}})];case 9:return[2]}})})},$.prototype.proceedPublishReplaceTracks=function(B){var F,G,q,X,J;return u(this,void 0,void 0,function(){var se,ce,Y,fe,he,pe,ue,Te,be,Z,K=this;return b(this,function(re){switch(re.label){case 0:if(se=B[0],ce=se.stream,Y=se.vMsid,fe=se.aMsid,se.rawUrl=se.url,se.url=this.streamManager.getOriginUrl(se.url),!this.streamManager.has(se.url))throw new w.RtsError(N.ErrorCode.CORE_PUB_REPLACE_URL_NOT_FOUND,"No stream found for this url: ".concat(se.url),"",{api:"publishReplaceTracks",configList:B});return typeof se.updateSourceStream!="boolean"&&(se.updateSourceStream=!0),he=ce.audioTrack,pe=ce.videoTrack,ue=this.streamManager.getAllMediaInfoList(se.url,!0),he&&(be=(F=ue.find(function(de){return de.type==="audio"&&(!fe||de.msid===fe)}))===null||F===void 0?void 0:F.transceiver)&&he.id!==((q=(G=be.sender)===null||G===void 0?void 0:G.track)===null||q===void 0?void 0:q.id)?[4,be.sender.replaceTrack(he)]:[3,2];case 1:re.sent(),re.label=2;case 2:return pe?(Te=ue.find(function(de){return de.type==="video"&&(!Y||de.msid===Y)}),(be=Te==null?void 0:Te.transceiver)&&pe.id!==((J=(X=be.sender)===null||X===void 0?void 0:X.track)===null||J===void 0?void 0:J.id)?[4,be.sender.replaceTrack(pe)]:[3,4]):[3,4];case 3:re.sent(),ce.isCustomStream||(Te.from=ce.hasScreen?"screen":"camera"),re.label=4;case 4:return(Z=this.streamManager.getStreamByMsid({url:se.url,vMsid:Y,aMsid:fe}))&&se.updateSourceStream&&Z.mergeStream(ce),[2,B.map(function(de){return{url:de.rawUrl,trackInfoList:K.streamManager.getAllMediaInfoList(se.url)}})]}})})},$.prototype.proceedPublishStop=function(B){var F;return u(this,void 0,void 0,function(){var G,q,X=this;return b(this,function(J){switch(J.label){case 0:return J.trys.push([0,2,,3]),[4,(F=this.signal)===null||F===void 0?void 0:F.publishStop(B.map(function(se){return X.streamManager.getOriginUrl(se.url)}))];case 1:return J.sent(),[3,3];case 2:throw(G=J.sent()).extraInfo=d({api:"publishStop"},G.extraInfo),G;case 3:return q=B.map(function(se){var ce=se.url;return u(X,void 0,void 0,function(){var Y,fe=this;return b(this,function(he){switch(he.label){case 0:ce=(0,S.pruneSubUrl)(ce),this.streamManager.getAllTransceivers(ce).forEach(function(pe){var ue;pe!=null&&pe.sender&&((ue=fe.pc)===null||ue===void 0||ue.removeTrack(pe==null?void 0:pe.sender))}),this.streamManager.get(ce).streamList.forEach(function(pe){return pe.deleteTracks({video:!0,audio:!0})}),this.streamManager.remove(ce),he.label=1;case 1:return he.trys.push([1,3,,4]),[4,this.simulateOfferAnswer()];case 2:return he.sent(),[3,4];case 3:throw(Y=he.sent()).extraInfo=d({api:"publishStop"},Y.extraInfo),Y;case 4:return[2]}})})}),[4,Promise.all(q)];case 4:return J.sent(),[2]}})})},$.prototype.proceedSubscribeAddDatachannel=function(B){return u(this,void 0,void 0,function(){var F,G,q,X=this;return b(this,function(J){switch(J.label){case 0:if(!((F=B.map(function(se){var ce=X.datachannelManager.getByMsid({url:se.url,msid:se.msid});return ce?(ce.dispose(),{url:se.url,msid:se.msid}):null}).filter(function(se){return se})).length>0))return[3,4];J.label=1;case 1:return J.trys.push([1,3,,4]),[4,this.proceedSubscribeDeleteDatachannel(F)];case 2:return J.sent(),[3,4];case 3:throw G=J.sent(),(q=G).extraInfo=d(d({},q.extraInfo),{api:"subscribeAddDatachannel",signal_api:"subscribeDeleteDatachannel",configList:B}),q;case 4:return this.rollbackController.saveDatachannelManager(this.datachannelManager),[2,new Promise(function(se,ce){return u(X,void 0,void 0,function(){var Y,fe,he,pe,ue,Te=this;return b(this,function(be){switch(be.label){case 0:return be.trys.push([0,2,,3]),[4,(pe=this.signal)===null||pe===void 0?void 0:pe.subscribeAddDatachannel(B)];case 1:return be.sent(),[3,3];case 2:return(Y=be.sent()).extraInfo=d({api:"subscribeAddDatachannel",signal_api:"subscribeAddDatachannel"},Y.extraInfo),B.forEach(function(Z){return Z.datachannel.dispose()}),this.rollbackController.rollback({datachannelManagerRollback:!0}),[2,ce(Y)];case 3:fe={},be.label=4;case 4:return be.trys.push([4,6,,7]),[4,(ue=this.signal)===null||ue===void 0?void 0:ue.subscribeActiveDatachannel(B)];case 5:return fe=be.sent(),[3,7];case 6:return(he=be.sent()).extraInfo=d({api:"subscribeAddDatachannel",signal_api:"subscribeActiveDatachannel"},he.extraInfo),console.log("Trying to rollback datachannel"),B.forEach(function(Z){return Z.datachannel.dispose()}),this.rollbackController.rollback({datachannelManagerRollback:!0}),[2,ce(he)];case 7:return B.forEach(function(Z){Te.datachannelManager.update({type:"sub-data",url:(0,S.pruneSubUrl)(Z.url,!0),msids:[{name:Z.msid,id:Z.datachannelId,type:"data",label:Z.label,datachannel:Z.datachannel}],originUrl:Z.url,streams:[]})}),se(fe),[2]}})})})]}})})},$.prototype.proceedSubscribeDeleteDatachannel=function(B){return u(this,void 0,void 0,function(){var F=this;return b(this,function(G){return[2,new Promise(function(q,X){return u(F,void 0,void 0,function(){var J,se,ce,Y,fe,he,pe,ue=this;return b(this,function(Te){switch(Te.label){case 0:return Te.trys.push([0,2,,3]),[4,(ce=this.signal)===null||ce===void 0?void 0:ce.subscribeDeleteDatachannel(B)];case 1:return Te.sent(),[3,3];case 2:return J=Te.sent(),((pe=(he=(fe=(Y=(se=J)==null?void 0:se.extraInfo)===null||Y===void 0?void 0:Y.parsedData)===null||fe===void 0?void 0:fe.streams)===null||he===void 0?void 0:he[0])===null||pe===void 0?void 0:pe.res_code)===404?[3,3]:(se.extraInfo=d({api:"subscribeDeleteDatachannel",signal_api:"subscribeDeleteDatachannel"},se.extraInfo),[2,X(J)]);case 3:return B.forEach(function(be){ue.datachannelManager.remove({url:(0,S.pruneSubUrl)(be.url,!0)})}),q(),[2]}})})})]})})},$.prototype.proceedSubscribeStopDatachannel=function(B){return u(this,void 0,void 0,function(){var F=this;return b(this,function(G){return[2,new Promise(function(q,X){return u(F,void 0,void 0,function(){var J,se,ce,Y,fe,he,pe,ue=this;return b(this,function(Te){switch(Te.label){case 0:return Te.trys.push([0,2,,3]),[4,(ce=this.signal)===null||ce===void 0?void 0:ce.subscribeStopDatachannel(B)];case 1:return Te.sent(),[3,3];case 2:return J=Te.sent(),((pe=(he=(fe=(Y=(se=J)==null?void 0:se.extraInfo)===null||Y===void 0?void 0:Y.parsedData)===null||fe===void 0?void 0:fe.streams)===null||he===void 0?void 0:he[0])===null||pe===void 0?void 0:pe.res_code)===404?[3,3]:(se.extraInfo=d({api:"subscribeStopDatachannel",signal_api:"subscribeStopDatachannel"},se.extraInfo),[2,X(J)]);case 3:return B.forEach(function(be){ue.datachannelManager.remove({url:(0,S.pruneSubUrl)(be.url,!0)})}),q(),[2]}})})})]})})},$.prototype.proceedPublishAddDatachannel=function(B){return u(this,void 0,void 0,function(){var F=this;return b(this,function(G){return[2,new Promise(function(q,X){return u(F,void 0,void 0,function(){var J,se,ce,Y=this;return b(this,function(fe){switch(fe.label){case 0:J={},fe.label=1;case 1:return fe.trys.push([1,3,,4]),[4,(ce=this.signal)===null||ce===void 0?void 0:ce.publishAddDatachannel(B)];case 2:return J=fe.sent(),[3,4];case 3:return(se=fe.sent()).extraInfo=d({api:"publishAddDatachannel",signal_api:"publishAddDatachannel"},se.extraInfo),[2,X(se)];case 4:return B.forEach(function(he){Y.datachannelManager.update({type:"pub-data",url:(0,S.pruneSubUrl)(he.url,!0),msids:[{name:he.msid,id:he.datachannelId,type:"data",label:he.label,datachannel:he.datachannel}],originUrl:he.url,streams:[]})}),q(J),[2]}})})})]})})},$.prototype.proceedPublishDeleteDatachannel=function(B){return u(this,void 0,void 0,function(){var F=this;return b(this,function(G){return[2,new Promise(function(q,X){return u(F,void 0,void 0,function(){var J,se,ce=this;return b(this,function(Y){switch(Y.label){case 0:return Y.trys.push([0,2,,3]),[4,(se=this.signal)===null||se===void 0?void 0:se.publishDeleteDatachannel(B)];case 1:return Y.sent(),[3,3];case 2:return(J=Y.sent()).extraInfo=d({api:"publishDeleteDatachannel",signal_api:"publishDeleteDatachannel"},J.extraInfo),[2,X(J)];case 3:return B.forEach(function(fe){ce.datachannelManager.remove({url:(0,S.pruneSubUrl)(fe.url,!0)})}),q(),[2]}})})})]})})},$.prototype.proceedPublishStopDatachannel=function(B){return u(this,void 0,void 0,function(){var F=this;return b(this,function(G){return[2,new Promise(function(q,X){return u(F,void 0,void 0,function(){var J,se,ce=this;return b(this,function(Y){switch(Y.label){case 0:return Y.trys.push([0,2,,3]),[4,(se=this.signal)===null||se===void 0?void 0:se.publishStopDatachannel(B)];case 1:return Y.sent(),[3,3];case 2:return(J=Y.sent()).extraInfo=d({api:"publishStopDatachannel",signal_api:"publishStopDatachannel"},J.extraInfo),[2,X(J)];case 3:return B.forEach(function(fe){ce.datachannelManager.remove({url:(0,S.pruneSubUrl)(fe.url,!0)})}),q(),[2]}})})})]})})},$.prototype.buildUrlStreamMap=function(B){var F=this,G=[];return B.forEach(function(q){var X=q.urlData,J=q.traceId,se=q.urlTraceId,ce=q.url,Y=q.vMsid,fe=q.aMsid,he=X.url,pe=new MediaStream;F.streamManager.getAllMediaInfoList(he,!0).forEach(function(ue){var Te,be;if(ue.type==="video"&&ue.msid===Y[0]||ue.type==="audio"&&ue.msid===fe[0]){var Z=(be=(Te=ue.transceiver)===null||Te===void 0?void 0:Te.receiver)===null||be===void 0?void 0:be.track;Z&&pe.addTrack(Z)}}),G.push({url:ce,stream:pe,traceId:J,urlTraceId:se})}),G},$.prototype.extendUrl=function(B){var F=this;return B.map(function(G){var q=G.url,X=G.subAudio,J=G.subVideo,se=G.aMsid,ce=G.vMsid,Y=F.streamManager.getOriginUrl(q),fe=new E.UrlData({url:Y,subAudio:X,subVideo:J});return d(d({},G),{urlData:fe,aMsid:fe.subAudio?se||[H]:[],vMsid:fe.subVideo?ce||[k]:[]})})},$.prototype.parseSdp=function(B){return new R.SdpUtil({sdp:B})},$.prototype.getTrackInfoList=function(B,F,G){B===void 0&&(B=[]);var q=[];return B.forEach(function(X){var J,se,ce,Y;if(X.type!=="application"){var fe,he=Number(X.ssrcs&&((J=X.ssrcs[0])===null||J===void 0?void 0:J.id))||-1,pe=X.rtp.find(function(re){var de;return["opus","h264"].includes((de=re.codec)===null||de===void 0?void 0:de.toLowerCase())}),ue=(pe==null?void 0:pe.codec)||"",Te=(pe==null?void 0:pe.payload)||0;F.isCustomStream||X.type==="video"&&(fe=F.hasScreen?"screen":"camera");var be=X.msid;if(G!=null&&G.aMsid||G!=null&&G.vMsid){var Z=(X.type==="video"?G.vMsid:G.aMsid)||"";Z!=null&&Z.trim().includes(" ")||(be=(se=X.msid)===null||se===void 0?void 0:se.split(" ")[1])}var K=X.type==="video"?(ce=F.videoTrack)===null||ce===void 0?void 0:ce.id:(Y=F.audioTrack)===null||Y===void 0?void 0:Y.id;q.push({ssrc:he,codec:ue,type:X.type,pt:Te,msid:be,from:fe,trackId:K})}}),q},$.prototype.patchSubscribeStreamManagerRecord=function(B,F){var G=this;this.extendUrl([{url:B,vMsid:F.vMsid,aMsid:F.aMsid}]).forEach(function(q){var X=q.urlData,J=q.vMsid,se=q.aMsid;if(G.pc&&(G.cumuDelay=F.cumuDelay,G.streamManager.remove(X.url),G.streamManager.init(X.url),G.pc.getTransceivers)){var ce=G.pc.getTransceivers()||[];if(X.subVideo){var Y=ce.find(function(he){return he.receiver.track.kind==="video"});G.streamManager.update(X.url,{vMsid:J[0],vTransceiver:Y,stream:F.stream,cumuDelay:F.cumuDelay})}if(X.subAudio){var fe=ce.find(function(he){return he.receiver.track.kind==="audio"});G.streamManager.update(X.url,{aMsid:se[0],aTransceiver:fe,stream:F.stream})}G.streamManager.markAlreadySubPub(B,{vMsid:J[0],aMsid:se[0],isPub:!1})}})},$.prototype.patchPublishStreamManagerRecord=function(B,F){if(this.pc){var G=F.stream,q=G.videoTrack,X=G.audioTrack,J=this.unifyMsid(F.aMsid,"audio"),se=this.unifyMsid(F.vMsid,"video");if(this.streamManager.init(B,C.EStreamType.Publish),this.cumuDelay=F.cumuDelay,this.pc.getTransceivers){var ce=this.pc.getTransceivers()||[];if(q){var Y=ce.find(function(he){var pe,ue;return((ue=(pe=he.sender)===null||pe===void 0?void 0:pe.track)===null||ue===void 0?void 0:ue.id)===q.id});Y&&this.streamManager.update(B,{vMsid:se,vTransceiver:Y,stream:F.stream,cumuDelay:F.cumuDelay})}if(X){var fe=ce.find(function(he){var pe,ue;return((ue=(pe=he.sender)===null||pe===void 0?void 0:pe.track)===null||ue===void 0?void 0:ue.id)===X.id});fe&&this.streamManager.update(B,{aMsid:J,aTransceiver:fe,stream:F.stream})}this.streamManager.markAlreadySubPub(B,{vMsid:se,aMsid:J,isPub:!0})}}},$.prototype.updateTrackInfoList=function(B){var F=B.url,G=B.stream,q=B.vMsid,X=B.aMsid,J=B.sdpMediaList;F||console.error("[updateTrackInfoList] url is required");var se=this.getTrackInfoList(J,G,{vMsid:q,aMsid:X}),ce=se.find(function(fe){return fe.type==="video"}),Y=se.find(function(fe){return fe.type==="audio"});return q&&ce&&this.streamManager.updateSdpInfo(F,d({vMsid:q},ce)),X&&Y&&this.streamManager.updateSdpInfo(F,d({aMsid:X},Y)),se},$.prototype.unifyMsid=function(B,F){var G=F==="video"?k:H;return(B==null?void 0:B[0])||G},$.prototype.startSignalHeartbeatTimer=function(B){var F=this;B&&B<200?console.warn("PEER CORE: heartbeat interval ".concat(B," is too small and will not take effect. At least 200ms")):(this.stopSignalHeartbeatTimer(),this.heartbeatTimerHandle=setInterval(function(){var G=void 0,q=F.streamManager.getSubOrPubDoneMediaMapSize(),X=q+F.datachannelManager.getSize();if(F.heartbeatTokenRing%=X,F.heartbeatTokenRing<q){var J=F.heartbeatTokenRing,se=F.streamManager.getPubOrSubDoneMediaUrlByIndex(J);se&&(G=[]).push({url:se})}else if(F.heartbeatTokenRing<X){J=F.heartbeatTokenRing-q;var ce=F.datachannelManager.getUrlByIndex(J);ce&&(G=[]).push(ce)}F.heartbeatTokenRing++,F.heartbeatTokenRing%=X,F.sendOnceHeartbeat(G)},B||v.DEFAULT_HEARTBEAT_INTERVAL))},$.prototype.stopSignalHeartbeatTimer=function(){this.heartbeatTimerHandle!==null&&clearInterval(this.heartbeatTimerHandle),this.heartbeatTimerHandle=null},$.prototype.sendOnceHeartbeat=function(B){var F,G,q=(F=this.signal)===null||F===void 0?void 0:F.sendHeartbeat(B);q&&(this.hebtLog(">>> Send: heartbeat",q),this.emit("hebtSent",q),this.heartbeatTimelineMap.set(q.msg_id,performance.now()),(G=this.heartbeatProcessor)===null||G===void 0||G.setLatestHeartbeatMsgId(q.msg_id))},$.prototype.sendFalseHeartbeat=function(B){var F,G=(F=this.signal)===null||F===void 0?void 0:F.sendFalseHeartbeat(B);G&&(this.hebtLog(">>> Send: false heartbeat",B),this.heartbeatTimelineMap.set(G.msg_id,performance.now()))},$.prototype.dispose=function(){var B,F,G,q,X;this.pc=void 0,this.prevOfferSdp=void 0,this.prevAnswerSdp=void 0,(B=this.signal)===null||B===void 0||B.dispose(),(F=this.streamManager)===null||F===void 0||F.dispose(),(G=this.datachannelManager)===null||G===void 0||G.dispose(),(q=this.heartbeatProcessor)===null||q===void 0||q.dispose(),(X=this.notifyProcessor)===null||X===void 0||X.dispose(),this.stopSignalHeartbeatTimer(),this.heartbeatTimelineMap.clear(),this.eventQueue=new L.CacheBuffer("signal queue")},$.prototype.initSignalListener=function(){var B,F=this,G=(B=this.signal)===null||B===void 0?void 0:B.getDatachannelCore();G&&(G.on("atomSend",function(q){F.emit("signalSent",q)}),G.on("atomReceive",function(q){F.emit("signalReceived",q)}))},$.prototype.initHeartbeatListener=function(){var B,F,G,q,X,J,se,ce,Y=this;(B=this.heartbeatProcessor)===null||B===void 0||B.on("pcReconnect",function(fe){Y.emit("pcReconnect",fe)}),(F=this.heartbeatProcessor)===null||F===void 0||F.on("streamError",function(fe){Y.emit("streamError",fe)}),(G=this.heartbeatProcessor)===null||G===void 0||G.on("streamReconnect",function(fe){Y.emit("streamReconnect",fe)}),(q=this.heartbeatProcessor)===null||q===void 0||q.on("traceIdUpdate",function(fe){Y.emit("traceIdUpdate",fe)}),(X=this.heartbeatProcessor)===null||X===void 0||X.on("hebtDropped",function(fe){Y.emit("hebtDropped",fe)}),(J=this.heartbeatProcessor)===null||J===void 0||J.on("hebtReceived",function(fe){if(fe){var he=Y.heartbeatTimelineMap.get(fe.msg_id)||0;Y.heartbeatTimelineMap.delete(fe.msg_id),Y.hebtLog("<<< Received: heartbeat","".concat(Math.ceil(performance.now()-he),"ms"),fe)}Y.emit("hebtReceived",fe)}),(se=this.heartbeatProcessor)===null||se===void 0||se.on("datachannelNotEnabled",function(){Y.emit("datachannelNotEnabled")}),(ce=this.signal)===null||ce===void 0||ce.getDatachannelCore().on("message",function(fe){var he;(he=Y.heartbeatProcessor)===null||he===void 0||he.process(fe)})},$.prototype.initNotifyListener=function(){var B,F,G,q=this;(B=this.notifyProcessor)===null||B===void 0||B.on("pcReconnect",function(X){q.emit("pcReconnect",X)}),(F=this.notifyProcessor)===null||F===void 0||F.on("message",function(X){q.emit("message",X)}),(G=this.signal)===null||G===void 0||G.getDatachannelCore().on("message",function(X){var J,se;(J=q.notifyProcessor)===null||J===void 0||J.processIpMigration(X),(se=q.notifyProcessor)===null||se===void 0||se.processInternalException(X)})},$.prototype.findNewSubPubMids=function(B,F){var G=new R.SdpUtil({sdp:B}),q=new R.SdpUtil({sdp:F}),X=G.detail.media.filter(function(se){return se.direction!=="inactive"}).map(function(se){return se.mid}),J=q.detail.media.map(function(se){return se.mid});return this.findDiff(X,J).map(function(se){return String(se)})},$.prototype.findDiff=function(B,F){return Array.from(new Set(y([],B,!0).filter(function(G){return!F.includes(G)})))},$.prototype.parseMsidString=function(B){var F={stream:"",track:""};if(!B)return F;var G=B.trim().split(" "),q=G[0],X=G[1];return X?(F.stream=q,F.track=X):F.track=q,F},$.prototype.stringifyMsid=function(B){var F=B.stream,G=B.track;return"".concat(F).concat(F?" ":"").concat(G)},$.prototype.restorePublishedSsrc=function(B){var F=new R.SdpUtil({sdp:this.prevOfferSdp||""}).getPublishSsrcs();B.detail.media.forEach(function(G){var q;G.direction!=="recvonly"&&((q=G.ssrcs)===null||q===void 0||q.forEach(function(X){var J,se=(J=F.find(function(ce){return ce.mid===String(G.mid)}))===null||J===void 0?void 0:J.ssrc;se&&(X.id=String(se))}))})},$.prototype.restorePublishMsid=function(B){var F=this,G=new R.SdpUtil({sdp:this.prevOfferSdp||""}).getPublishMsids();G!=null&&G.length&&B.detail.media.forEach(function(q){var X,J;if(q.direction!=="recvonly"){var se=(X=G.find(function(Y){return Y.mid===String(q.mid)}))===null||X===void 0?void 0:X.msid;if(!se)return;var ce=F.parseMsidString(se);q.msid=se||q.msid,(J=q.ssrcs)===null||J===void 0||J.forEach(function(Y){switch(Y.attribute){case"cname":Y.value=ce.track||Y.value;break;case"msid":Y.value=se||Y.value}})}})},$.prototype.alignAnswerMidsWithOffer=function(B){var F=new R.SdpUtil({sdp:this.prevOfferSdp||""}).detail.media.map(function(J){return String(J.mid)}),G=B.detail.media.map(function(J){return String(J.mid)}),q=this.findDiff(G,F);B.removeMedia(q);var X=[];F.forEach(function(J){var se=B.detail.media.find(function(ce){return String(ce.mid)===J});se&&X.push(se)}),B.detail.media=X.filter(function(J){return J})},$.prototype.simulateOfferAnswer=function(B){var F,G,q;return u(this,void 0,void 0,function(){var X,J,se,ce,Y,fe,he,pe,ue,Te,be,Z,K;return b(this,function(re){switch(re.label){case 0:return re.trys.push([0,2,,3]),[4,(F=this.pc)===null||F===void 0?void 0:F.createOffer()];case 1:return X=re.sent(),J=new R.SdpUtil({sdp:(X==null?void 0:X.sdp)||""}),se=J.detail.media.filter(function(de){return de.direction==="inactive"}).map(function(de){return String(de.mid)}),this.restorePublishedSsrc(J),this.restorePublishMsid(J),this.prevOfferSdp=J.generate(),(ce=new R.SdpUtil({sdp:this.prevAnswerSdp||""})).setMediaInactive(se),B&&(Y=(0,R.generateFakeMediaSdpAnswer)(B))&&(fe=new R.SdpUtil({sdp:Y}),he=y([],fe.detail.media,!0),ce.addOrUpdateMedia(he),this.alignAnswerMidsWithOffer(ce)),pe=ce.generate(),this.setPrevAnswerSdp(pe),[3,3];case 2:throw ue=re.sent(),new w.RtsError(N.ErrorCode.DATACHANNEL_CREATE_OFFER_ERROR,"CreateOffer error: ".concat(ue),"",{pc:this.pc});case 3:if(Te=this.avoidMsidConflict(this.prevOfferSdp),this.offerSdpHook)try{Te=this.offerSdpHook(Te)}catch(de){console.log("offerSdoHook error: ",de)}re.label=4;case 4:return re.trys.push([4,6,,7]),[4,(G=this.pc)===null||G===void 0?void 0:G.setLocalDescription(new RTCSessionDescription({type:"offer",sdp:Te}))];case 5:return re.sent(),[3,7];case 6:throw be=re.sent(),new w.RtsError(N.ErrorCode.DATACHANNEL_SET_OFFER_ERROR,"SetLocalDescription error: ".concat(be),"",{sdp:this.prevOfferSdp});case 7:if(re.trys.push([7,10,,11]),!this.prevAnswerSdp)return[3,9];if(Z=this.avoidMsidConflict(this.prevAnswerSdp),this.answerSdpHook)try{Z=this.answerSdpHook(Z)}catch(de){console.log("answerSdpHook error: ",de)}return[4,(q=this.pc)===null||q===void 0?void 0:q.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:Z}))];case 8:re.sent(),re.label=9;case 9:return[3,11];case 10:throw K=re.sent(),new w.RtsError(N.ErrorCode.DATACHANNEL_SET_ANSWER_ERROR,"SetRemoteDescription error: ".concat(K),"",{sdp:this.prevAnswerSdp});case 11:return[2]}})})},$.prototype.avoidMsidConflict=function(B){var F=new R.SdpUtil({sdp:B});return F.mungleMsid(),F.generate()},$.prototype.setCodecPreferences=function(B,F){if(F)try{B.setCodecPreferences(F)}catch(G){console.warn("setCodecPreferences error",G)}},$.prototype.log=function(){for(var B=[],F=0;F<arguments.length;F++)B[F]=arguments[F];window.RTS_DATACHANNEL_DEBUG&&console.log.apply(console,y(["[PC-Core]"],B,!1))},$.prototype.hebtLog=function(){for(var B,F,G=[],q=0;q<arguments.length;q++)G[q]=arguments[q];window.RTS_HEBT_DEBUG&&console.log.apply(console,y(["".concat(this.now()," [datachannel|").concat((B=this.signal)===null||B===void 0?void 0:B.getDatachannelCore().label,"|").concat((F=this.signal)===null||F===void 0?void 0:F.getDatachannelCore().id,"]")],G,!1))},$.prototype.now=function(){var B=new Date;return"".concat(B.getHours(),":").concat(B.getMinutes(),":").concat(B.getSeconds(),".").concat(String(B.getMilliseconds()).padStart(3,"0"))},$}(P.default);v.PeerConnectionCore=ee},651:function(f,v,p){var _,m=this&&this.__extends||(_=function(w,N){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(M,D){M.__proto__=D}||function(M,D){for(var L in D)Object.prototype.hasOwnProperty.call(D,L)&&(M[L]=D[L])},_(w,N)},function(w,N){if(typeof N!="function"&&N!==null)throw new TypeError("Class extends value "+String(N)+" is not a constructor or null");function M(){this.constructor=w}_(w,N),w.prototype=N===null?Object.create(N):(M.prototype=N.prototype,new M)}),d=this&&this.__assign||function(){return d=Object.assign||function(w){for(var N,M=1,D=arguments.length;M<D;M++)for(var L in N=arguments[M])Object.prototype.hasOwnProperty.call(N,L)&&(w[L]=N[L]);return w},d.apply(this,arguments)},u=this&&this.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(v,"__esModule",{value:!0}),v.DataChannelCore=v.EDatachannelStatus=void 0;var b,y=p(844),g=p(961),S=p(854),R=u(p(885)),E=u(p(973)),I=u(p(775));function C(){}(function(w){w[w.DATACHANNEL_STATUS_CLOSE=0]="DATACHANNEL_STATUS_CLOSE",w[w.DATACHANNEL_STATUS_OPEN=1]="DATACHANNEL_STATUS_OPEN"})(b=v.EDatachannelStatus||(v.EDatachannelStatus={}));var A=function(w){function N(M){var D=w.call(this)||this;return D.mutexSendData=!1,D.timerSendData=null,D.eventQueue=new S.CacheBuffer("send tasks"),D.idle=!1,D.datachannelList=[],D.pc=M.pc,D.eventHandler=M.onDatachannelEvent||C,D.datachannelList=M.datachannelList||[],D.createDatachannel(M.label,M.assignId,M.delayOpen,M.initOptions),D}return m(N,w),N.prototype.getWebrtcDatachannel=function(){return this.datachannel},Object.defineProperty(N.prototype,"isIdle",{get:function(){return this.idle},enumerable:!1,configurable:!0}),N.prototype.markAsIdle=function(){this.idle=!0},N.prototype.reuse=function(){var M=this;this.idle=!1,console.log("REUSEING datachannel",this.datachannel.id,this.datachannel.label,this.datachannel.readyState),setTimeout(function(){M.emit("statusChange",b.DATACHANNEL_STATUS_OPEN)})},N.prototype.getNextId=function(){var M=0,D=this.datachannelList.reduce(function(L,P){return P.readyState==="open"?L+1:(M||(M=P.id),L)},0);return M||2*(D+1)},N.prototype.createDatachannel=function(M,D,L,P){var x=this,T=d({ordered:!0},P);D&&this.pc.connectionState==="connected"&&(T.id=this.getNextId()),this.datachannel=this.pc.createDataChannel(M||"GRTN_RTC_DATACHANNEL"+"_".concat(Date.now()),T),this.datachannel.addEventListener("open",function(){L?setTimeout(function(){x.eventHandler(b.DATACHANNEL_STATUS_OPEN),x.emit("statusChange",b.DATACHANNEL_STATUS_OPEN)},200):(x.eventHandler(b.DATACHANNEL_STATUS_OPEN),x.emit("statusChange",b.DATACHANNEL_STATUS_OPEN))}),this.datachannel.addEventListener("close",function(){x.eventHandler(b.DATACHANNEL_STATUS_CLOSE),x.emit("statusChange",b.DATACHANNEL_STATUS_CLOSE)}),this.datachannel.addEventListener("closing",function(){}),this.datachannel.addEventListener("error",function(O){console.log(">> error",O),x.emit("error",O)}),this.datachannel.addEventListener("bufferedamountlow",function(){}),this.datachannel.addEventListener("message",function(O){x.emit("message",O.data)})},Object.defineProperty(N.prototype,"id",{get:function(){return this.datachannel.id},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"label",{get:function(){return this.datachannel.label},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"readyState",{get:function(){return this.datachannel.readyState},enumerable:!1,configurable:!0}),N.prototype.send=function(M){if(this.datachannel.readyState!=="open")throw new Error("Datachannel(label:".concat(this.datachannel.label,",id:").concat(this.datachannel.id,") is closed."));return this.datachannel.send(M)},N.prototype.sendAsync=function(M){if(this.datachannel.readyState==="open")return this.datachannel.send((0,I.default)(M)),!0;console.log("Async signal message failed. Datachannel(label:".concat(this.datachannel.label,",id:").concat(this.datachannel.id,") is closed."))},N.prototype.sendData=function(M){var D=this;return new Promise(function(L,P){var x=new E.default(D.datachannel);if(D.mutexSendData){var T={sender:x,res:L,rej:P,data:M};D.eventQueue.cache(T)}else D.atomSend(x,L,P,M)})},N.prototype.dispose=function(M){var D;M===void 0&&(M=!1),this.emit("dispose"),this.mutexSendData=!1,this.timerSendData!==null&&clearTimeout(this.timerSendData),this.timerSendData=null,this.eventQueue=new S.CacheBuffer("send tasks"),this.markAsIdle(),this.removeAllListeners(),M&&((D=this.datachannel)===null||D===void 0||D.close())},N.prototype.atomSend=function(M,D,L,P){var x=this;this.mutexSendData=!0,M.on("onSendData",function(T){x.emit("atomSend",T)}),M.on("onReceiveData",function(T){x.emit("atomReceive",T)}),M.on("onSendDataDone",function(){if(M.dispose(),x.timerSendData!==null&&clearTimeout(x.timerSendData),x.timerSendData=null,x.mutexSendData=!1,!x.eventQueue.isEmpty()){var T=x.eventQueue.getFirst();x.atomSend(T.sender,T.res,T.rej,T.data)}}),this.timerSendData=setTimeout(function(){L(new g.RtsError(y.ErrorCode.DATACHANNEL_TIMEOUT_ERROR,"request timeout after ".concat(N.REQUEST_TIMEOUT,"ms"),"",P)),x.timerSendData=null,x.mutexSendData=!1,M.emit("onSendDataDone")},N.REQUEST_TIMEOUT),M.sendingProcess(D,L,P)},N.REQUEST_TIMEOUT=5e3,N}(R.default);v.DataChannelCore=A},973:function(f,v,p){var _,m=this&&this.__extends||(_=function(C,A){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,N){w.__proto__=N}||function(w,N){for(var M in N)Object.prototype.hasOwnProperty.call(N,M)&&(w[M]=N[M])},_(C,A)},function(C,A){if(typeof A!="function"&&A!==null)throw new TypeError("Class extends value "+String(A)+" is not a constructor or null");function w(){this.constructor=C}_(C,A),C.prototype=A===null?Object.create(A):(w.prototype=A.prototype,new w)}),d=this&&this.__spreadArray||function(C,A,w){if(w||arguments.length===2)for(var N,M=0,D=A.length;M<D;M++)!N&&M in A||(N||(N=Array.prototype.slice.call(A,0,M)),N[M]=A[M]);return C.concat(N||Array.prototype.slice.call(A))},u=this&&this.__importDefault||function(C){return C&&C.__esModule?C:{default:C}};Object.defineProperty(v,"__esModule",{value:!0}),v.EDatachannelSignalResCode=v.EMessageType=void 0;var b,y,g=p(844),S=p(961),R=u(p(885)),E=u(p(775));(function(C){C.HEBT="hebt",C.NOTI="NOTI"})(b=v.EMessageType||(v.EMessageType={})),function(C){C[C.NGX_RTC_PUBLISH_ALREADY=402]="NGX_RTC_PUBLISH_ALREADY",C[C.NGX_RTC_REQUEST_FORBIDDEN=403]="NGX_RTC_REQUEST_FORBIDDEN",C[C.NGX_RTC_STREAM_NO_FOUND=404]="NGX_RTC_STREAM_NO_FOUND",C[C.NGX_RTC_SUBSCRIBE_ALREADY=410]="NGX_RTC_SUBSCRIBE_ALREADY",C[C.NGX_RTC_NORMAL_CLOSED=200]="NGX_RTC_NORMAL_CLOSED",C[C.NGX_RTC_LIMITED=508]="NGX_RTC_LIMITED",C[C.NGX_RTC_INTERNAL_SERVER_ERROR=500]="NGX_RTC_INTERNAL_SERVER_ERROR",C[C.NGX_RTC_BAD_REQUEST=400]="NGX_RTC_BAD_REQUEST",C[C.NGX_RTC_NEED_RETRY=213]="NGX_RTC_NEED_RETRY",C[C.NGX_RTC_DATACHANNEL_HEBT_MSID_NOT_FOUND=130]="NGX_RTC_DATACHANNEL_HEBT_MSID_NOT_FOUND"}(y=v.EDatachannelSignalResCode||(v.EDatachannelSignalResCode={}));var I=function(C){function A(w){var N=C.call(this)||this;return N.datachannel=w,N}return m(A,C),A.prototype.sendingProcess=function(w,N,M){var D,L,P,x,T=this,O=performance.now(),k=this.sign(M);this.datachannel.onmessage=function(H){try{var U=JSON.parse(H.data),ee=T.checkResponse(U,k);if(ee.ignore)return;if(T.emit("onReceiveData",U),T.log("<<< Received:","".concat(Math.ceil(performance.now()-O),"ms"),U),ee.pass)w(U);else{if(ee.code===y.NGX_RTC_NEED_RETRY)return void setTimeout(function(){T.log(">>> Send:",M),T.datachannel.send((0,E.default)(M))},200);N(new S.RtsError(g.ErrorCode.DATACHANNEL_RESPONSE_ERROR,"[code]".concat(ee.code,"; [msg]").concat(ee.msg),ee.traceId,{parsedData:U}))}}catch(W){N(new S.RtsError(g.ErrorCode.DATACHANNEL_PARSE_ERROR,"datachannel message parse error","",{data:H.data,err:W}))}T.emit("onSendDataDone")};try{this.log(">>> Sent:","".concat(M.type,"-").concat(!((D=M.streams)===null||D===void 0)&&D.length?M.streams[0].method:"-"),(x=(P=(L=M.streams)===null||L===void 0?void 0:L[0])===null||P===void 0?void 0:P.msid)===null||x===void 0?void 0:x.reduce(function(H,U){return H+","+U.name},""),M)}catch{}this.emit("onSendData",M),this.datachannel.send((0,E.default)(M))},A.prototype.dispose=function(){this.removeAllListeners(),this.datachannel.onmessage=null},A.prototype.checkResponse=function(w,N){var M={pass:!0,ignore:!1,code:0,msg:"",traceId:""};if([b.HEBT,b.NOTI].includes(w.type)||N&&this.sign(w)!==N)return M.ignore=!0,M.pass=!1,M;w.recode!==0&&(M.pass=!1,M.code=w.recode,M.msg=w.msg);var D=w.streams;return D&&D.length>0&&D.forEach(function(L){L.res_code!==200&&(M.pass=!1,M.code=L.res_code,M.msg=L.res_msg,M.traceId=L.traceid)}),M},A.prototype.sign=function(w){var N,M,D="";try{D="".concat(w.msg_id,"-").concat(w.type,"-").concat((M=(N=w.streams)===null||N===void 0?void 0:N[0])===null||M===void 0?void 0:M.method)}catch{D=""}return D},A.prototype.log=function(){for(var w=[],N=0;N<arguments.length;N++)w[N]=arguments[N];window.RTS_DATACHANNEL_DEBUG&&console.log.apply(console,d(["".concat(this.now()," [datachannel|").concat(this.datachannel.label,"|").concat(this.datachannel.id,"]")],w,!1))},A.prototype.now=function(){var w=new Date;return"".concat(w.getHours(),":").concat(w.getMinutes(),":").concat(w.getSeconds(),".").concat(String(w.getMilliseconds()).padStart(3,"0"))},A}(R.default);v.default=I},844:(f,v)=>{Object.defineProperty(v,"__esModule",{value:!0}),v.ErrorCode=void 0,function(p){p[p.DATACHANNEL_SIGNAL_ERROR=15e3]="DATACHANNEL_SIGNAL_ERROR",p[p.DATACHANNEL_SET_OFFER_ERROR=15001]="DATACHANNEL_SET_OFFER_ERROR",p[p.DATACHANNEL_SET_ANSWER_ERROR=15002]="DATACHANNEL_SET_ANSWER_ERROR",p[p.DATACHANNEL_CREATE_OFFER_ERROR=15003]="DATACHANNEL_CREATE_OFFER_ERROR",p[p.DATACHANNEL_RESPONSE_ERROR=15004]="DATACHANNEL_RESPONSE_ERROR",p[p.DATACHANNEL_PARSE_ERROR=15005]="DATACHANNEL_PARSE_ERROR",p[p.DATACHANNEL_TIMEOUT_ERROR=15006]="DATACHANNEL_TIMEOUT_ERROR",p[p.CORE_NO_PC_ERROR=15007]="CORE_NO_PC_ERROR",p[p.CORE_PUBLIST_EXCEED_ERROR=15008]="CORE_PUBLIST_EXCEED_ERROR",p[p.CORE_PUB_REPLACE_URL_NOT_FOUND=15009]="CORE_PUB_REPLACE_URL_NOT_FOUND",p[p.CORE_TRANSCEIVERS_NOT_FOUND=15010]="CORE_TRANSCEIVERS_NOT_FOUND",p[p.CORE_IGNORE_SIGNAL_REQUEST=15011]="CORE_IGNORE_SIGNAL_REQUEST"}(v.ErrorCode||(v.ErrorCode={}))},961:(f,v,p)=>{Object.defineProperty(v,"__esModule",{value:!0}),v.RtsError=void 0;var _=p(844);v.RtsError=function(m,d,u,b){this.errorCode=m,this.errorCodeName=_.ErrorCode[m],this.message=d,this.traceId=u,b&&(this.extraInfo=b)}},854:(f,v)=>{Object.defineProperty(v,"__esModule",{value:!0}),v.CacheBuffer=void 0;var p=function(){function _(m){this.data=[],this.tag=m||"unknown",this.maxBufferLength=90}return _.prototype.setMaxCapacity=function(m){this.maxBufferLength=90,m>=0&&(this.maxBufferLength=m),this.maxBufferLength>200&&(this.maxBufferLength=200)},_.prototype.cache=function(m){this.data.length>this.maxBufferLength&&(this.data.shift(),console.log(this.tag+" CACHE: Reach Max Capacity")),this.data.push(m)},_.prototype.getFirst=function(){return this.data.shift()},_.prototype.isEmpty=function(){return this.data.length<=0},_}();v.CacheBuffer=p},885:(f,v)=>{Object.defineProperty(v,"__esModule",{value:!0});var p=function(){function _(){this._eventMap={}}return _.prototype.listeners=function(m){return this._eventMap[m]||[]},_.prototype.emit=function(m){for(var d=this,u=[],b=1;b<arguments.length;b++)u[b-1]=arguments[b];var y=this._eventMap[m];return!!Array.isArray(y)&&(y.forEach(function(g){return g.apply(d,u)}),!0)},_.prototype.off=function(m,d){var u=this._eventMap[m];return Array.isArray(u)&&(this._eventMap[m]=u.filter(function(b){return b!==d})),this},_.prototype.removeAllListeners=function(m){return m===void 0?this._eventMap={}:this._eventMap[m]&&(this._eventMap[m]=[]),this},_.prototype.on=function(m,d){return this._eventMap[m]?this._eventMap[m].push(d):this._eventMap[m]=[d],this},_.prototype.once=function(m,d){var u=this,b=function(){for(var y=[],g=0;g<arguments.length;g++)y[g]=arguments[g];u.off(m,b),d.apply(u,y)};return this.on(m,b),this},_}();v.default=p},887:(f,v)=>{Object.defineProperty(v,"__esModule",{value:!0}),v.intersection=v.pruneSubUrl=v.parseUrlSubParams=void 0,v.parseUrlSubParams=function(p){var _={subVideo:!0,subAudio:!0};return p&&(p.includes("@subvideo=no")&&(_.subVideo=!1),p.includes("@subaudio=no")&&(_.subAudio=!1)),_},v.pruneSubUrl=function(p,_){var m=p||"";return m=m.replace("@subaudio=no","").replace("@subvideo=no",""),_&&(m=m.split("?")[0]),m},v.intersection=function(p,_){return p.filter(function(m){return _.includes(m)})}},390:function(f,v){var p=this&&this.__spreadArray||function(m,d,u){if(u||arguments.length===2)for(var b,y=0,g=d.length;y<g;y++)!b&&y in d||(b||(b=Array.prototype.slice.call(d,0,y)),b[y]=d[y]);return m.concat(b||Array.prototype.slice.call(d))};Object.defineProperty(v,"__esModule",{value:!0}),v.Logger=void 0;var _=function(){function m(d){this.switchName=d.switchName,this.displayName=d.displayName}return m.prototype.log=function(){for(var d=[],u=0;u<arguments.length;u++)d[u]=arguments[u];window[this.switchName||Math.random()]&&console.log.apply(console,p(["".concat(this.now()," [").concat(this.displayName,"]")],d,!1))},m.prototype.now=function(){var d=new Date;return"".concat(this.padStart(d.getHours()),":").concat(this.padStart(d.getMinutes()),":").concat(this.padStart(d.getSeconds()),".").concat(this.padStart(d.getMilliseconds(),3))},m.prototype.padStart=function(d,u,b){return u===void 0&&(u=2),b===void 0&&(b="0"),String(d).padStart(u,b)},m}();v.Logger=_},248:function(f,v,p){var _=this&&this.__assign||function(){return _=Object.assign||function(b){for(var y,g=1,S=arguments.length;g<S;g++)for(var R in y=arguments[g])Object.prototype.hasOwnProperty.call(y,R)&&(b[R]=y[R]);return b},_.apply(this,arguments)},m=this&&this.__spreadArray||function(b,y,g){if(g||arguments.length===2)for(var S,R=0,E=y.length;R<E;R++)!S&&R in y||(S||(S=Array.prototype.slice.call(y,0,R)),S[R]=y[R]);return b.concat(S||Array.prototype.slice.call(y))};Object.defineProperty(v,"__esModule",{value:!0}),v.generateFakeMediaSdpAnswer=v.SdpUtil=void 0;var d=p(766),u=function(){function b(y){if(this.rawSdp=y.sdp,!y.sdp)throw new Error("No sdp to parse");this.sdpDetail=this.parse()}return Object.defineProperty(b.prototype,"detail",{get:function(){return this.sdpDetail},enumerable:!1,configurable:!0}),b.prototype.removeMedia=function(y){return this.removeMediaInner(y)},b.prototype.keepMedia=function(y){return this.removeMediaInner(y,{revert:!0})},b.prototype.removeMediaInner=function(y,g){g===void 0&&(g={revert:!1}),y.length&&this.sdpDetail.media&&this.sdpDetail.media.length&&(g.revert?this.sdpDetail.media=this.sdpDetail.media.filter(function(S){return y.includes(String(S.mid)||"")}):this.sdpDetail.media=this.sdpDetail.media.filter(function(S){return!y.includes(String(S.mid)||"")}),this.updateBundle())},b.prototype.addOrUpdateMedia=function(y,g){g===void 0&&(g={}),y=y.map(function(R){return _(_({},R),{setup:"passive"})});var S=[];this.sdpDetail.media=this.sdpDetail.media.map(function(R){var E=y.find(function(A){return A.mid===R.mid});if(E){S.push(R.mid);var I=E,C=R;return g.isPublish&&(I.ssrcs=C.ssrcs,I.ssrcGroups=C.ssrcGroups),E}return R}),this.sdpDetail.media=m(m([],this.sdpDetail.media,!0),y.filter(function(R){return!S.includes(R.mid)}),!0),this.updateBundle()},b.prototype.mungleMsid=function(){this.sdpDetail.media.forEach(function(y){if(y.msid){var g="";y.msid=y.msid.split(" ").map(function(S,R){return R===1?(g=S,S+"_"+y.mid):S}).join(" "),g&&y.ssrcs&&y.ssrcs.forEach(function(S){S.value&&(S.value=S.value.replace(g,g+"_"+y.mid))})}})},b.prototype.addMedia=function(y){var g;y=y.map(function(E){return _(_({},E),{setup:"passive"})}),this.sdpDetail.media=m(m([],this.sdpDetail.media,!0),y,!0);var S=y.reduce(function(E,I){return E+" "+I.mid},""),R=(g=this.sdpDetail.groups)===null||g===void 0?void 0:g.find(function(E){return E.type==="BUNDLE"});R&&(R.mids+="".concat(S))},b.prototype.setMediaInactive=function(y){this.sdpDetail.media.forEach(function(g){y.includes(String(g.mid))&&(g.direction="inactive")}),this.updateBundle()},b.prototype.getPublishSsrcs=function(){var y=[];return this.sdpDetail.media.forEach(function(g){g.direction!=="recvonly"&&g.ssrcs&&y.push({type:g.type,ssrc:g.ssrcs[0].id||"ERR_NOT_FOUND",mid:String(g.mid)})}),y},b.prototype.getPublishMsids=function(){var y=[];return this.sdpDetail.media.forEach(function(g){g.direction!=="recvonly"&&g.msid&&y.push({type:g.type,msid:g.msid,mid:String(g.mid)})}),y},b.prototype.generate=function(){return(0,d.write)(this.sdpDetail)},b.prototype.updateBundle=function(){var y,g=(y=this.sdpDetail.groups)===null||y===void 0?void 0:y.find(function(S){return S.type==="BUNDLE"});g&&(g.mids=this.sdpDetail.media.reduce(function(S,R){return S+R.mid+" "},"").trim())},b.prototype.addNack=function(){this.sdpDetail.media.forEach(function(y){var g,S,R;if(y.type==="audio"){if(!((g=y.rtcpFb)===null||g===void 0)&&g.some(function(I){return I.type==="nack"}))return;var E=(S=y.rtp.find(function(I){return I.codec==="opus"}))===null||S===void 0?void 0:S.payload;E&&((R=y.rtcpFb)===null||R===void 0||R.push({payload:E,type:"nack"}))}})},b.prototype.parse=function(){var y=(0,d.parse)(this.rawSdp);return this.patchMsid(y)},b.prototype.getMids=function(y){return y!=null&&y.length?y.reduce(function(g,S){return m(m([],g,!0),[String(S.mid)],!1)},[]):[]},b.prototype.patchMsid=function(y){return y.media.forEach(function(g){var S,R;g.type==="application"||g.msid||(g.msid=(R=(S=g.ssrcs)===null||S===void 0?void 0:S.find(function(E){return E.attribute==="msid"}))===null||R===void 0?void 0:R.value)}),y},b}();v.SdpUtil=u,v.generateFakeMediaSdpAnswer=function(b){if(!b.mids.length||!b.medias.length||b.mids.length!==b.medias.length)return"";var y=`v=0
o=- 1710852399 2 IN IP4 127.0.0.1
s=-
t=0 0
a=group:BUNDLE`,g=`
a=end-of-candidates`;b.mids.forEach(function(R){y+=" ".concat(R)});var S=function(){for(var R="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",E="",I=0;I<24;I++)E+=R.charAt(Math.floor(62*Math.random()));return E}();return b.medias.forEach(function(R,E){if(R.type==="video"){var I=(1e4*Math.random()).toFixed(0),C=R.msid||"rts video";y+=`
m=video 9 UDP/TLS/RTP/SAVPF 106 107
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:ZmFrZV90b2tlbg==
a=ice-pwd:`.concat(S,`
a=ice-options:ice-lite
a=fingerprint:SHA-256 C3:E2:CD:1F:B8:E4:DA:77:D1:D2:36:F3:72:EA:83:CA:7A:F2:3B:26:07:C6:E0:3D:96:44:57:59:14:DE:F0:A4
a=setup:passive
a=sendonly
a=mid:`).concat(b.mids[E],`
a=rtcp-mux
a=rtpmap:106 H264/90000
a=fmtp:106 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f;sps-pps-idr-in-keyframe=1
a=rtcp-fb:106 goog-remb
a=rtcp-fb:106 transport-cc
a=rtcp-fb:106 ccm fir
a=rtcp-fb:106 nack
a=rtcp-fb:106 nack pli
a=rtpmap:107 rtx/90000
a=fmtp:107 apt=106
a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay`);var A=`
a=ssrc:`.concat(I,` cname:defaultcname
a=ssrc:`).concat(I," msid:").concat(C,`
a=ssrc:`).concat(I,` mslabel:rts
a=ssrc:`).concat(I," label:video");b.direction==="sub"&&(y+=A),y+=g}else R.type==="audio"&&(I=(1e4*Math.random()).toFixed(0),C=R.msid||"rts audio",y+=`
m=audio 9 UDP/TLS/RTP/SAVPF 111
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:ZmFrZV90b2tlbg==
a=ice-pwd:`.concat(S,`
a=ice-options:ice-lite
a=fingerprint:SHA-256 C3:E2:CD:1F:B8:E4:DA:77:D1:D2:36:F3:72:EA:83:CA:7A:F2:3B:26:07:C6:E0:3D:96:44:57:59:14:DE:F0:A4
a=setup:passive
a=sendonly
a=mid:`).concat(b.mids[E],`
a=rtcp-mux
a=rtpmap:111 opus/48000/2
a=fmtp:111 minptime=10;stereo=1;useinbandfec=1
a=rtcp-fb:111 transport-cc
a=rtcp-fb:111 nack
a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time`),A=`
a=ssrc:`.concat(I,` cname:defaultcname
a=ssrc:`).concat(I," msid:").concat(C,`
a=ssrc:`).concat(I,` mslabel:rts
a=ssrc:`).concat(I," label:audio"),b.direction==="sub"&&(y+=A),y+=g)}),y}},237:(f,v,p)=>{Object.defineProperty(v,"__esModule",{value:!0}),v.UrlData=void 0;var _=p(887),m=function(){function d(u){var b=(0,_.parseUrlSubParams)(u.url);this.data={url:u.url,subAudio:b.subAudio,subVideo:b.subVideo},typeof u.subAudio=="boolean"&&(this.data.subAudio=u.subAudio),typeof u.subVideo=="boolean"&&(this.data.subVideo=u.subVideo)}return Object.defineProperty(d.prototype,"subVideo",{get:function(){return this.data.subVideo},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"subAudio",{get:function(){return this.data.subAudio},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"url",{get:function(){return(0,_.pruneSubUrl)(this.data.url)},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"originalUrl",{get:function(){return this.data.url},enumerable:!1,configurable:!0}),d}();v.UrlData=m},123:function(f,v,p){var _,m=this&&this.__extends||(_=function(R,E){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(I,C){I.__proto__=C}||function(I,C){for(var A in C)Object.prototype.hasOwnProperty.call(C,A)&&(I[A]=C[A])},_(R,E)},function(R,E){if(typeof E!="function"&&E!==null)throw new TypeError("Class extends value "+String(E)+" is not a constructor or null");function I(){this.constructor=R}_(R,E),R.prototype=E===null?Object.create(E):(I.prototype=E.prototype,new I)}),d=this&&this.__spreadArray||function(R,E,I){if(I||arguments.length===2)for(var C,A=0,w=E.length;A<w;A++)!C&&A in E||(C||(C=Array.prototype.slice.call(E,0,A)),C[A]=E[A]);return R.concat(C||Array.prototype.slice.call(E))},u=this&&this.__importDefault||function(R){return R&&R.__esModule?R:{default:R}};Object.defineProperty(v,"__esModule",{value:!0});var b=u(p(885)),y=p(973),g=[y.EDatachannelSignalResCode.NGX_RTC_STREAM_NO_FOUND],S=function(R){function E(I,C){var A=R.call(this)||this;return A.latestHeartbeatMsgId=-1,A.streamManager=I,A.datachannelManager=C,A}return m(E,R),E.prototype.process=function(I){var C=this,A=this.parseFormat(I);if(A){if(A.type===y.EMessageType.HEBT&&A.msg_id<this.latestHeartbeatMsgId)return console.warn("丢弃过时心跳",A.msg_id,"latest:",this.latestHeartbeatMsgId),void this.emit("hebtDropped",A);var w=this.checkRecode(A),N=w.valid,M=w.error,D=w.reason;if(!N)return A.recode===3?void this.emit("datachannelNotEnabled"):void(M&&this.emit("pcReconnect",{recode:A.recode,reMsg:D}));this.emit("hebtReceived",A),this.checkStreams(A).forEach(function(L){var P={resCode:L.resCode,resMsg:L.resMsg,url:L.url,msids:L.msids,streams:L.streams,type:L.type,latestUrl:L.latestUrl};L.isReconnectable?C.emit("streamReconnect",P):C.emit("streamError",P)})}},E.prototype.setLatestHeartbeatMsgId=function(I){this.latestHeartbeatMsgId=I},E.prototype.dispose=function(){this.removeAllListeners()},E.prototype.parseFormat=function(I){try{return JSON.parse(I)}catch{console.log("Heartbeat parse failed."," Response Data: ",I)}},E.prototype.checkRecode=function(I){var C={valid:!1,error:!1,reason:""};return I.type!==y.EMessageType.HEBT?(C.reason="not heartbeat signal, ignore",C):I.recode!==0?(C.reason=I.msg,C.error=!0,C):(C.valid=!0,C)},E.prototype.checkStreams=function(I){var C=this,A=[];return I.streams&&I.streams.length&&d(d([],this.streamManager.getAllStreamListWithMsids(),!0),this.datachannelManager.getAllList(),!0).forEach(function(w){var N,M=-1;if(I.streams.find(function(x,T){if(x.url===w.url)return M=T,!0})&&M!==-1){var D=I.streams[M];if(D.method===y.EMessageType.HEBT&&D.res_code===200){D.traceid&&C.emit("traceIdUpdate",{url:D.url,traceId:D.traceid});var L=[];w.msids.forEach(function(x){D.msid.find(function(T){return T.name===x.name})||L.push(x)});var P=(N=w.streams)===null||N===void 0?void 0:N.filter(function(x){return!!L.find(function(T){return T.streamId===x.id})});L.length&&A.push({url:w.url,msids:L,streams:P,isReconnectable:!0,resMsg:"RTS heartbeat msid mismatch",resCode:404,type:w.type,latestUrl:w.latestUrl})}else A.push({url:w.url,msids:w.msids,streams:w.streams,isReconnectable:C.isReconnectableErrorCode(D.res_code),resMsg:D.res_msg,resCode:D.res_code,type:w.type,latestUrl:w.latestUrl})}}),A},E.prototype.isReconnectableErrorCode=function(I){return g.includes(I)},E}(b.default);v.default=S},619:function(f,v,p){var _=this&&this.__assign||function(){return _=Object.assign||function(I){for(var C,A=1,w=arguments.length;A<w;A++)for(var N in C=arguments[A])Object.prototype.hasOwnProperty.call(C,N)&&(I[N]=C[N]);return I},_.apply(this,arguments)},m=this&&this.__awaiter||function(I,C,A,w){return new(A||(A=Promise))(function(N,M){function D(x){try{P(w.next(x))}catch(T){M(T)}}function L(x){try{P(w.throw(x))}catch(T){M(T)}}function P(x){var T;x.done?N(x.value):(T=x.value,T instanceof A?T:new A(function(O){O(T)})).then(D,L)}P((w=w.apply(I,C||[])).next())})},d=this&&this.__generator||function(I,C){var A,w,N,M,D={label:0,sent:function(){if(1&N[0])throw N[1];return N[1]},trys:[],ops:[]};return M={next:L(0),throw:L(1),return:L(2)},typeof Symbol=="function"&&(M[Symbol.iterator]=function(){return this}),M;function L(P){return function(x){return function(T){if(A)throw new TypeError("Generator is already executing.");for(;M&&(M=0,T[0]&&(D=0)),D;)try{if(A=1,w&&(N=2&T[0]?w.return:T[0]?w.throw||((N=w.return)&&N.call(w),0):w.next)&&!(N=N.call(w,T[1])).done)return N;switch(w=0,N&&(T=[2&T[0],N.value]),T[0]){case 0:case 1:N=T;break;case 4:return D.label++,{value:T[1],done:!1};case 5:D.label++,w=T[1],T=[0];continue;case 7:T=D.ops.pop(),D.trys.pop();continue;default:if(!((N=(N=D.trys).length>0&&N[N.length-1])||T[0]!==6&&T[0]!==2)){D=0;continue}if(T[0]===3&&(!N||T[1]>N[0]&&T[1]<N[3])){D.label=T[1];break}if(T[0]===6&&D.label<N[1]){D.label=N[1],N=T;break}if(N&&D.label<N[2]){D.label=N[2],D.ops.push(T);break}N[2]&&D.ops.pop(),D.trys.pop();continue}T=C.call(I,D)}catch(O){T=[6,O],w=0}finally{A=N=0}if(5&T[0])throw T[1];return{value:T[0]?T[1]:void 0,done:!0}}([P,x])}}},u=this&&this.__spreadArray||function(I,C,A){if(A||arguments.length===2)for(var w,N=0,M=C.length;N<M;N++)!w&&N in C||(w||(w=Array.prototype.slice.call(C,0,N)),w[N]=C[N]);return I.concat(w||Array.prototype.slice.call(C))};Object.defineProperty(v,"__esModule",{value:!0}),v.Signal=v.ESignalMethod=v.ESignalType=void 0;var b,y,g,S=p(651),R=p(887);(function(I){I.Sub="sub",I.Pub="pub",I.Hebt="hebt"})(b=v.ESignalType||(v.ESignalType={})),function(I){I.Add="add",I.Active="active",I.Stop="stop",I.Delete="delete",I.Hebt="hebt"}(y=v.ESignalMethod||(v.ESignalMethod={})),function(I){I.Audio="audio",I.Video="video",I.Data="data"}(g||(g={}));var E=function(){function I(C){this.latestMsgId=0,this.latestSubAddMsgId=0,this.pc=C.pc,this.datachannel=new S.DataChannelCore({pc:this.pc,onDatachannelEvent:C.onDatachannelEvent,delayOpen:C.delayOpen,initOptions:C.initOptions})}return I.prototype.getDatachannelCore=function(){return this.datachannel},I.prototype.subscribeAdd=function(C,A,w){var N;return m(this,void 0,void 0,function(){var M,D,L,P;return d(this,function(x){switch(x.label){case 0:return M=_(_({},this.baseParams({type:b.Sub,method:y.Add})),{streams:C.map(function(T,O){var k=T.urlData,H=[];return k.subAudio&&!w.isMsidSubPubDone(k.url,{aMsid:T.aMsid[0]})&&H.push({type:g.Audio,name:T.aMsid[0]}),k.subVideo&&!w.isMsidSubPubDone(k.url,{vMsid:T.vMsid[0]})&&H.push({type:g.Video,name:T.vMsid[0]}),{method:y.Add,url:k.url,msid:H,sdp:A[O],ttl:300}})}),[4,(N=this.datachannel)===null||N===void 0?void 0:N.sendData(M)];case 1:D=x.sent();try{L=C[0].urlData.url.split("?")[0].split("/").pop(),P="".concat(L,"_").concat(D.msg_id),D.streams[0].sdp=D.streams[0].sdp.replace(/msid:\S+/g,"msid:".concat(P)).replace(/mslabel:\S+/g,"mslabel:".concat(P))}catch{}return[2,D]}})})},I.prototype.subscribeActive=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){switch(N.label){case 0:return w=_(_({},this.baseParams({type:b.Sub,method:y.Active})),{streams:C.map(function(M){var D=M.urlData;return{method:y.Active,url:D.url}})}),[4,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)];case 1:return N.sent(),[2]}})})},I.prototype.subscribeDelete=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){switch(N.label){case 0:return w=_(_({},this.baseParams()),{streams:C.map(function(M){var D=M.url,L=M.aMsid,P=M.vMsid,x=[];return L!=null&&L.length&&(x=u(u([],x,!0),L.map(function(T){return{name:T}}),!0)),P!=null&&P.length&&(x=u(u([],x,!0),P.map(function(T){return{name:T}}),!0)),{method:y.Delete,url:(0,R.pruneSubUrl)(D),msid:x}})}),[4,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)];case 1:return[2,N.sent()]}})})},I.prototype.subscribeStop=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){switch(N.label){case 0:return w=_(_({},this.baseParams()),{streams:C.map(function(M){var D=M.urlData;return{method:y.Stop,url:D.url}})}),[4,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)];case 1:return[2,N.sent()]}})})},I.prototype.subscribeAddDatachannel=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){switch(N.label){case 0:return w=_(_({},this.baseParams({type:b.Sub,method:y.Add})),{streams:C.map(function(M){var D=M.url,L=M.msid;return{method:y.Add,url:D,msid:[{type:g.Data,name:L}]}})}),[4,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)];case 1:return[2,N.sent()]}})})},I.prototype.subscribeActiveDatachannel=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){switch(N.label){case 0:return w=_(_({},this.baseParams({type:b.Sub,method:y.Active})),{streams:C.map(function(M){var D=M.url,L=M.datachannelId,P=M.msid;return{method:y.Active,url:D,msid:[{type:g.Data,name:P,channel:L}]}})}),[4,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)];case 1:return[2,N.sent()]}})})},I.prototype.subscribeDeleteDatachannel=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){switch(N.label){case 0:return w=_(_({},this.baseParams()),{streams:C.map(function(M){var D=M.url,L=M.msid;return{method:y.Delete,url:D,msid:[{name:L}]}})}),[4,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)];case 1:return[2,N.sent()]}})})},I.prototype.subscribeStopDatachannel=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){switch(N.label){case 0:return w=_(_({},this.baseParams()),{streams:C.map(function(M){var D=M.url;return{method:y.Stop,url:D}})}),[4,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)];case 1:return[2,N.sent()]}})})},I.prototype.publishAdd=function(C,A,w,N){var M;return m(this,void 0,void 0,function(){var D;return d(this,function(L){return D=_(_({},this.baseParams({type:b.Pub})),{streams:C.map(function(P,x){var T=w[x],O=N[x],k=[];return T.length&&k.push({type:"video",name:T[0].trim()}),O.length&&k.push({type:"audio",name:O[0].trim()}),{method:y.Add,url:P,msid:k,sdp:A[x]}})}),[2,(M=this.datachannel)===null||M===void 0?void 0:M.sendData(D)]})})},I.prototype.publishDelete=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){return w=_(_({},this.baseParams({type:b.Pub})),{streams:C.map(function(M){var D=M.url,L=M.aMsid,P=M.vMsid,x=[];return L!=null&&L.length&&(x=u(u([],x,!0),L.map(function(T){return{name:T}}),!0)),P!=null&&P.length&&(x=u(u([],x,!0),P.map(function(T){return{name:T}}),!0)),{method:y.Delete,url:(0,R.pruneSubUrl)(D),msid:x}})}),[2,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)]})})},I.prototype.publishStop=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){return w=_(_({},this.baseParams({type:b.Pub})),{streams:C.map(function(M){return{method:y.Stop,url:M}})}),[2,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)]})})},I.prototype.publishAddDatachannel=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){switch(N.label){case 0:return w=_(_({},this.baseParams({type:b.Pub,method:y.Add})),{streams:C.map(function(M){var D=M.url,L=M.datachannelId,P=M.msid;return{method:y.Add,url:D,msid:[{type:g.Data,name:P,channel:L}]}})}),[4,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)];case 1:return[2,N.sent()]}})})},I.prototype.publishDeleteDatachannel=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){switch(N.label){case 0:return w=_(_({},this.baseParams({type:b.Pub})),{streams:C.map(function(M){var D=M.url,L=M.msid;return{method:y.Delete,url:D,msid:[{name:L}]}})}),[4,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)];case 1:return[2,N.sent()]}})})},I.prototype.publishStopDatachannel=function(C){var A;return m(this,void 0,void 0,function(){var w;return d(this,function(N){switch(N.label){case 0:return w=_(_({},this.baseParams({type:b.Pub})),{streams:C.map(function(M){var D=M.url;return{method:y.Stop,url:D}})}),[4,(A=this.datachannel)===null||A===void 0?void 0:A.sendData(w)];case 1:return[2,N.sent()]}})})},I.prototype.sendHeartbeat=function(C){C&&!C.map&&(C=void 0);var A=_(_({},this.baseParams({type:b.Hebt})),{streams:C==null?void 0:C.map(function(w){var N=w.url;return{method:y.Hebt,url:N}})});if(C||delete A.streams,this.datachannel.sendAsync(A))return A},I.prototype.sendFalseHeartbeat=function(C){var A=_(_({},this.baseParams({type:b.Hebt})),{streams:C==null?void 0:C.map(function(w){return{method:"fake",url:w.url}})});if(C||delete A.streams,this.datachannel.sendAsync(A))return A},I.prototype.dispose=function(){this.datachannel.dispose()},I.prototype.baseParams=function(C){C===void 0&&(C={type:b.Sub});var A=0;return C.type===b.Sub&&C.method===y.Add?(A=++this.latestMsgId,this.latestSubAddMsgId=this.latestMsgId):A=C.type===b.Sub&&C.method===y.Active?this.latestSubAddMsgId:++this.latestMsgId,{msg_id:A,version:2,type:C.type}},I}();v.Signal=E},125:function(f,v,p){var _,m=this&&this.__extends||(_=function(R,E){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(I,C){I.__proto__=C}||function(I,C){for(var A in C)Object.prototype.hasOwnProperty.call(C,A)&&(I[A]=C[A])},_(R,E)},function(R,E){if(typeof E!="function"&&E!==null)throw new TypeError("Class extends value "+String(E)+" is not a constructor or null");function I(){this.constructor=R}_(R,E),R.prototype=E===null?Object.create(E):(I.prototype=E.prototype,new I)}),d=this&&this.__importDefault||function(R){return R&&R.__esModule?R:{default:R}};Object.defineProperty(v,"__esModule",{value:!0}),v.NotifyProcessor=void 0;var u,b=p(973),y=d(p(885)),g=p(390);(function(R){R[R.NGX_RTC_H5_DELIVERY_INTERNAL_EXCEPTION=1]="NGX_RTC_H5_DELIVERY_INTERNAL_EXCEPTION",R[R.NGX_RTC_H5_ACCESS_IP_MIGRATION=2]="NGX_RTC_H5_ACCESS_IP_MIGRATION",R[R.NGX_RTC_H5_ACCESS_SUB_STREAMINFO=3]="NGX_RTC_H5_ACCESS_SUB_STREAMINFO"})(u||(u={}));var S=function(R){function E(){var I=R.call(this)||this;return I.logger=new g.Logger({displayName:"NotifyProcessor",switchName:"RTS_NOTIFY_DEBUG"}),I}return m(E,R),E.prototype.processIpMigration=function(I){var C,A,w=this.parseFormat(I);if(w&&this.checkRelated(w)){this.logger.log("【processIpMigration】parsedData",w),this.emit("message",{message:w});var N=this.parseIP(w.notify_msg);!((C=N.pull)===null||C===void 0)&&C.length||!((A=N.push)===null||A===void 0)&&A.length?(console.warn("【processIpMigration】需要重连",N),this.emit("pcReconnect",{ips:N})):this.logger.log("【processIpMigration】No valid ip found: ",w.notify_msg)}},E.prototype.processSubStreamInfo=function(I){var C=this.parseFormat(I);if(this.logger.log("【processSubStreamInfo】parsedData",C),C&&this.checkRelated(C,u.NGX_RTC_H5_ACCESS_SUB_STREAMINFO))return C},E.prototype.processInternalException=function(I){var C=this.parseFormat(I);if(C&&this.checkRelated(C,u.NGX_RTC_H5_DELIVERY_INTERNAL_EXCEPTION)){this.emit("message",{message:C}),this.logger.log("【processInternalException】parsedData",C);var A=Number(C.res_code);A&&![200,204,205,207,221,403,404,405,429,504,616,409,601].includes(A)?(console.warn("【processInternalException】需要重连",A),this.emit("pcReconnect",{})):this.logger.log("【processInternalException】Error code should not retry ",A)}},E.prototype.dispose=function(){this.removeAllListeners()},E.prototype.parseFormat=function(I){try{return JSON.parse(I)}catch{console.warn("Notify parse failed."," Response Data: ",I)}},E.prototype.checkRelated=function(I,C){return C===void 0&&(C=u.NGX_RTC_H5_ACCESS_IP_MIGRATION),I.type===b.EMessageType.NOTI&&I.notify_type===C},E.prototype.parseIP=function(I){I===void 0&&(I=""),this.logger.log("Paring IP string: ".concat(I));var C=I.split(";"),A=/^(?:\d{1,3}\.){3}\d{1,3}$/,w=/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,N=/^(push|pull)_ips:(.*)$/,M={};return C.forEach(function(D){var L=N.exec(D);if(L){var P=L[1],x=L[2].split(",").filter(function(T){return A.test(T)||w.test(T)});M[P]=x}}),this.logger.log("Parsed IP:",M),M},E}(y.default);v.NotifyProcessor=S},132:function(f,v,p){var _=this&&this.__awaiter||function(g,S,R,E){return new(R||(R=Promise))(function(I,C){function A(M){try{N(E.next(M))}catch(D){C(D)}}function w(M){try{N(E.throw(M))}catch(D){C(D)}}function N(M){var D;M.done?I(M.value):(D=M.value,D instanceof R?D:new R(function(L){L(D)})).then(A,w)}N((E=E.apply(g,S||[])).next())})},m=this&&this.__generator||function(g,S){var R,E,I,C,A={label:0,sent:function(){if(1&I[0])throw I[1];return I[1]},trys:[],ops:[]};return C={next:w(0),throw:w(1),return:w(2)},typeof Symbol=="function"&&(C[Symbol.iterator]=function(){return this}),C;function w(N){return function(M){return function(D){if(R)throw new TypeError("Generator is already executing.");for(;C&&(C=0,D[0]&&(A=0)),A;)try{if(R=1,E&&(I=2&D[0]?E.return:D[0]?E.throw||((I=E.return)&&I.call(E),0):E.next)&&!(I=I.call(E,D[1])).done)return I;switch(E=0,I&&(D=[2&D[0],I.value]),D[0]){case 0:case 1:I=D;break;case 4:return A.label++,{value:D[1],done:!1};case 5:A.label++,E=D[1],D=[0];continue;case 7:D=A.ops.pop(),A.trys.pop();continue;default:if(!((I=(I=A.trys).length>0&&I[I.length-1])||D[0]!==6&&D[0]!==2)){A=0;continue}if(D[0]===3&&(!I||D[1]>I[0]&&D[1]<I[3])){A.label=D[1];break}if(D[0]===6&&A.label<I[1]){A.label=I[1],I=D;break}if(I&&A.label<I[2]){A.label=I[2],A.ops.push(D);break}I[2]&&A.ops.pop(),A.trys.pop();continue}D=S.call(g,A)}catch(L){D=[6,L],E=0}finally{R=I=0}if(5&D[0])throw D[1];return{value:D[0]?D[1]:void 0,done:!0}}([N,M])}}},d=this&&this.__spreadArray||function(g,S,R){if(R||arguments.length===2)for(var E,I=0,C=S.length;I<C;I++)!E&&I in S||(E||(E=Array.prototype.slice.call(S,0,I)),E[I]=S[I]);return g.concat(E||Array.prototype.slice.call(S))},u=this&&this.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(v,"__esModule",{value:!0}),v.PeerConnectionRollbackController=void 0;var b=u(p(775)),y=function(){function g(S){this.fakeSdpParams={direction:"sub",mids:[],medias:[]},this.pcCore=S}return g.prototype.setFakeSdpMids=function(S){this.fakeSdpParams.mids=S},g.prototype.setFakeSdpMedias=function(S,R){this.fakeSdpParams.medias=S,this.fakeSdpParams.direction=R},g.prototype.saveStreamManager=function(S){var R;this.streamManager=S,(R=this.streamManager)===null||R===void 0||R.backup()},g.prototype.saveDatachannelManager=function(S){var R;this.datachannelManager=S,(R=this.datachannelManager)===null||R===void 0||R.backup()},g.prototype.rollback=function(S){return _(this,void 0,void 0,function(){var R;return m(this,function(E){switch(E.label){case 0:if(S!=null&&S.trackListnerRollback&&(this.pcCore.removeTrackListener(),this.log("Sub Track Listener Removed")),(S==null?void 0:S.streamManagerRollback)&&this.streamManager){this.streamManager.restore();try{this.log("Stream Manager Restored",JSON.parse((0,b.default)(this.streamManager)))}catch{}}if(S!=null&&S.datachannelManagerRollback&&this.datachannelManager){this.datachannelManager.restore();try{this.log("Datachannel Manager Restored",JSON.parse((0,b.default)(this.datachannelManager)))}catch{}}if(S!=null&&S.pcTransceiversRollback&&(this.fakeSdpParams.medias.forEach(function(I){var C;(C=I.trans)===null||C===void 0||C.receiver.track.stop()}),this.log("Sub Track(s) Stopped",this.fakeSdpParams.medias)),!(S!=null&&S.runSimulateSignal))return[3,4];this.log("SDP Simulating...",this.fakeSdpParams),E.label=1;case 1:return E.trys.push([1,3,,4]),[4,this.pcCore.simulateOfferAnswer(this.fakeSdpParams)];case 2:return E.sent(),this.log("SDP Simulation Done"),[3,4];case 3:return R=E.sent(),this.log("SDP Simulation Failed",R),[3,4];case 4:return[2]}})})},g.prototype.log=function(){for(var S=[],R=0;R<arguments.length;R++)S[R]=arguments[R];window.RTS_DATACHANNEL_DEBUG&&console.log.apply(console,d(["[PC-Core-Rollback]"],S,!1))},g}();v.PeerConnectionRollbackController=y},748:function(f,v,p){var _=this&&this.__assign||function(){return _=Object.assign||function(b){for(var y,g=1,S=arguments.length;g<S;g++)for(var R in y=arguments[g])Object.prototype.hasOwnProperty.call(y,R)&&(b[R]=y[R]);return b},_.apply(this,arguments)},m=this&&this.__spreadArray||function(b,y,g){if(g||arguments.length===2)for(var S,R=0,E=y.length;R<E;R++)!S&&R in y||(S||(S=Array.prototype.slice.call(y,0,R)),S[R]=y[R]);return b.concat(S||Array.prototype.slice.call(y))};Object.defineProperty(v,"__esModule",{value:!0}),v.DatachannelManager=void 0;var d=p(887),u=function(){function b(y){this.datachannelMap=new Map,this.datachannelMapBackup=new Map}return b.prototype.backup=function(){var y=this;this.datachannelMapBackup=new Map,this.datachannelMap.forEach(function(g,S){y.datachannelMapBackup.set(S,_(_({},g),{msids:m([],g.msids,!0),streams:m([],g.streams,!0)}))})},b.prototype.restore=function(){var y=this;this.datachannelMap=new Map,this.datachannelMapBackup.forEach(function(g,S){y.datachannelMap.set(S,g)})},b.prototype.update=function(y){var g=this.datachannelMap.get(y.url);g?y.msids.forEach(function(S){g.msids.find(function(R){if(R.id===S.id&&R.name===S.name)return!0})?console.log("RTS [DATACHANNEL MANAGER]: duplicate msid for datachannel",y):g.msids.push(S)}):this.datachannelMap.set(y.url,y)},b.prototype.remove=function(y){this.datachannelMap.delete(y.url)},b.prototype.has=function(y){return this.datachannelMap.has((0,d.pruneSubUrl)(y,!0))},b.prototype.get=function(y){return this.datachannelMap.get((0,d.pruneSubUrl)(y,!0))},b.prototype.getByMsid=function(y){var g;if(y.url){var S=this.datachannelMap.get((0,d.pruneSubUrl)(y.url,!0));if(S)return y.msid?(g=S.msids.find(function(R){return R.name===y.msid}))===null||g===void 0?void 0:g.datachannel:S.msids[0].datachannel}else console.warn("[getByMsid] config.url is required.")},b.prototype.getAllList=function(){var y=[];return this.datachannelMap.forEach(function(g){y.push(_(_({},g),{latestUrl:g.latestUrl||g.originUrl}))}),y},b.prototype.getSize=function(){return this.datachannelMap.size},b.prototype.getUrlByIndex=function(y){var g=0,S=void 0;return this.datachannelMap.forEach(function(R){g===y&&(S={url:R.originUrl}),g++}),S},b.prototype.updateLatestUrl=function(y){var g=this.get(y);return!!g&&(g.latestUrl=y,!0)},b.prototype.dispose=function(){this.datachannelMap.clear(),this.datachannelMapBackup.clear()},b}();v.DatachannelManager=u},628:function(f,v,p){var _=this&&this.__assign||function(){return _=Object.assign||function(y){for(var g,S=1,R=arguments.length;S<R;S++)for(var E in g=arguments[S])Object.prototype.hasOwnProperty.call(g,E)&&(y[E]=g[E]);return y},_.apply(this,arguments)},m=this&&this.__spreadArray||function(y,g,S){if(S||arguments.length===2)for(var R,E=0,I=g.length;E<I;E++)!R&&E in g||(R||(R=Array.prototype.slice.call(g,0,E)),R[E]=g[E]);return y.concat(R||Array.prototype.slice.call(g))};Object.defineProperty(v,"__esModule",{value:!0}),v.StreamManager=v.EStreamType=void 0;var d,u=p(887);(function(y){y.Subscribe="sub",y.Publish="pub"})(d=v.EStreamType||(v.EStreamType={}));var b=function(){function y(g){this.streamMap={},this.streamMapBackup={}}return y.prototype.backup=function(){var g=this,S={};Object.keys(this.streamMap).forEach(function(R){var E=g.streamMap[R];S[R]=_(_({},g.streamMap[R]),{videoInfoList:m([],E.videoInfoList,!0),audioInfoList:m([],E.audioInfoList,!0),streamList:m([],E.streamList,!0)})}),this.streamMapBackup=S},y.prototype.restore=function(){this.streamMap=_({},this.streamMapBackup)},y.prototype.init=function(g,S){S===void 0&&(S=d.Subscribe);var R=(0,u.pruneSubUrl)(g);g=(0,u.pruneSubUrl)(g,!0),this.has(g)||(this.streamMap[g]={type:S,videoInfoList:[],audioInfoList:[],streamList:[],originUrl:R})},y.prototype.remove=function(g){delete this.streamMap[(0,u.pruneSubUrl)(g,!0)]},y.prototype.update=function(g,S){var R=this.get(g);if(!R)throw new Error("No url found");if(S.aMsid){var E=R.audioInfoList.find(function(C){return C.msid===S.aMsid})||this.createMediaItem(S.aMsid,"audio");S.aTransceiver&&(E.transceiver=S.aTransceiver),S.stream&&(E.streamId=S.stream.id),this.updateMediaInfoList(E,R.audioInfoList)}if(S.vMsid){var I=R.videoInfoList.find(function(C){return C.msid===S.vMsid})||this.createMediaItem(S.vMsid,"video");S.vTransceiver&&(I.transceiver=S.vTransceiver),S.cumuDelay&&(I.cumuDelay=S.cumuDelay),S.stream&&(I.streamId=S.stream.id),this.updateMediaInfoList(I,R.videoInfoList)}S.stream&&(R.streamList.some(function(C){return C.id===S.stream.id})||(R.streamList=m(m([],R.streamList,!0),[S.stream],!1)))},y.prototype.pruneStreamList=function(g){var S=this.get(g);S&&(S.streamList=S.streamList.filter(function(R){var E;return((E=R.mediaStream)===null||E===void 0?void 0:E.getTracks().length)>0}))},y.prototype.updateSdpInfo=function(g,S){var R,E=this.get(g);if(!E)throw new Error("No url found");if(S.aMsid?R=E.audioInfoList.find(function(I){return I.msid===S.aMsid}):S.vMsid&&(R=E.videoInfoList.find(function(I){return I.msid===S.vMsid})),!R)throw new Error("No target media found");R.ssrc=S.ssrc,R.codec=S.codec,R.pt=S.pt,R.from=S.from},y.prototype.get=function(g){return this.streamMap[(0,u.pruneSubUrl)(g,!0)]},y.prototype.has=function(g){return!!this.get(g)},y.prototype.getSize=function(){return this.getSubOrPubDoneMediaMapSize()},y.prototype.getSubOrPubDoneMediaMapSize=function(){var g=this,S=0;return Object.keys(this.streamMap).forEach(function(R){var E=g.streamMap[R],I=!1;E.audioInfoList.forEach(function(C){I=I||E.type===d.Publish&&C.pubDone||E.type===d.Subscribe&&C.subDone}),E.videoInfoList.forEach(function(C){I=I||E.type===d.Publish&&C.pubDone||E.type===d.Subscribe&&C.subDone}),I&&S++}),S},y.prototype.removeMsid=function(g,S){g=(0,u.pruneSubUrl)(g,!0);var R=this.get(g);R&&(S.vMsid&&(R.videoInfoList=R.videoInfoList.filter(function(E){return E.msid!==S.vMsid})),S.aMsid&&(R.audioInfoList=R.audioInfoList.filter(function(E){return E.msid!==S.aMsid})))},y.prototype.getMids=function(g,S){S===void 0&&(S={filterSubDone:!1}),g=(0,u.pruneSubUrl)(g,!0);var R=this.streamMap[g];return R?m(m([],R.audioInfoList.reduce(function(E,I){return I.transceiver&&(!S.filterSubDone||S.filterSubDone&&!I.subDone)?m(m([],E,!0),[String(I.transceiver.mid)],!1):E},[]),!0),R.videoInfoList.reduce(function(E,I){return I.transceiver&&(!S.filterSubDone||S.filterSubDone&&!I.subDone)?m(m([],E,!0),[String(I.transceiver.mid)],!1):E},[]),!0):[]},y.prototype.getAllTransceivers=function(g){if(!g)return[];g=(0,u.pruneSubUrl)(g,!0);var S=this.get(g);return S?m(m([],S.videoInfoList.map(function(R){return R.transceiver}),!0),S.audioInfoList.map(function(R){return R.transceiver}),!0):[]},y.prototype.getTransceiver=function(g,S){if(S===void 0&&(S={}),g){g=(0,u.pruneSubUrl)(g,!0);var R=S.vMsid,E=S.aMsid,I=this.get(g);if(I){var C;if(R)return(C=I.videoInfoList.find(function(A){return A.msid===R}))==null?void 0:C.transceiver;if(E)return(C=I.audioInfoList.find(function(A){return A.msid===E}))==null?void 0:C.transceiver}}},y.prototype.getStreamByMsid=function(g){var S,R,E=this.get(g.url);if(E){if(g.vMsid){var I=(S=E.videoInfoList.find(function(A){return A.msid===g.vMsid}))===null||S===void 0?void 0:S.streamId;return E.streamList.find(function(A){return A.id===I})}if(g.aMsid){var C=(R=E.audioInfoList.find(function(A){return A.msid===g.aMsid}))===null||R===void 0?void 0:R.streamId;return E.streamList.find(function(A){return A.id===C})}return E.streamList[0]}},y.prototype.hasTransceiver=function(g,S){return S===void 0&&(S={}),!!this.getTransceiver(g,S)},y.prototype.removeTransceiver=function(g,S){g=(0,u.pruneSubUrl)(g,!0);var R,E=this.get(g);E&&(S.vMsid&&(R=E.videoInfoList.find(function(I){return I.msid===S.vMsid}))&&(R.transceiver=void 0),S.aMsid&&(R=E.audioInfoList.find(function(I){return I.msid===S.aMsid}))&&(R.transceiver=void 0))},y.prototype.markAlreadySubPub=function(g,S){S===void 0&&(S={}),g=(0,u.pruneSubUrl)(g,!0);var R,E=this.streamMap[g];E&&(S.vMsid&&(R=E.videoInfoList.find(function(I){return I.msid===S.vMsid}))&&(R[S.isPub?"pubDone":"subDone"]=!S.reset),S.aMsid&&(R=E.audioInfoList.find(function(I){return I.msid===S.aMsid}))&&(R[S.isPub?"pubDone":"subDone"]=!S.reset))},y.prototype.isMsidSubPubDone=function(g,S){S===void 0&&(S={}),g=(0,u.pruneSubUrl)(g,!0);var R=this.streamMap[g];if(!R)return!1;if(S.vMsid){var E=R.videoInfoList.find(function(I){return I.msid===S.vMsid});return S.isPub?E==null?void 0:E.pubDone:E==null?void 0:E.subDone}return S.aMsid?(E=R.audioInfoList.find(function(I){return I.msid===S.aMsid}),S.isPub?E==null?void 0:E.pubDone:E==null?void 0:E.subDone):void 0},y.prototype.getAllMediaInfoList=function(g,S){var R=this.get(g);return R?m(m([],R.audioInfoList.map(function(E){var I,C,A,w,N=E.type,M=E.msid,D=E.ssrc,L=E.pt,P=E.codec,x=E.from,T=E.transceiver,O={type:N,msid:M,ssrc:D,pt:L,codec:P,from:x,trackId:R.type===d.Subscribe?(C=(I=T==null?void 0:T.receiver)===null||I===void 0?void 0:I.track)===null||C===void 0?void 0:C.id:(w=(A=T==null?void 0:T.sender)===null||A===void 0?void 0:A.track)===null||w===void 0?void 0:w.id};return S?_(_({},O),{transceiver:T}):O}),!0),R.videoInfoList.map(function(E){var I,C,A,w,N=E.type,M=E.msid,D=E.ssrc,L=E.pt,P=E.codec,x=E.from,T=E.transceiver,O={type:N,msid:M,ssrc:D,pt:L,codec:P,from:x,trackId:R.type===d.Subscribe?(C=(I=T==null?void 0:T.receiver)===null||I===void 0?void 0:I.track)===null||C===void 0?void 0:C.id:(w=(A=T==null?void 0:T.sender)===null||A===void 0?void 0:A.track)===null||w===void 0?void 0:w.id};return S?_(_({},O),{transceiver:T}):O}),!0):[]},y.prototype.getOriginUrl=function(g){var S=(0,u.pruneSubUrl)(g,!0),R=this.get(S);return R?R.originUrl:g},y.prototype.getAllTrackPairList=function(g){var S,R,E,I,C=[];for(var A in this.streamMap){var w=this.streamMap[A];if(w.type===g)for(var N=Math.max(w.audioInfoList.length,w.videoInfoList.length),M=0;M<N;M++){var D={url:A,originUrl:w.originUrl};M<w.audioInfoList.length&&(D.aTransceiver=g===d.Subscribe?(S=w.audioInfoList[M].transceiver)===null||S===void 0?void 0:S.receiver:(R=w.audioInfoList[M].transceiver)===null||R===void 0?void 0:R.sender,D.aMsid=w.audioInfoList[M].msid),M<w.videoInfoList.length&&(D.vTransceiver=g===d.Subscribe?(E=w.videoInfoList[M].transceiver)===null||E===void 0?void 0:E.receiver:(I=w.videoInfoList[M].transceiver)===null||I===void 0?void 0:I.sender,D.vMsid=w.videoInfoList[M].msid,D.cumuDelay=w.videoInfoList[M].cumuDelay),C.push(D)}}return C},y.prototype.getAllStreamListWithMsids=function(){var g,S=[];for(var R in this.streamMap){for(var E=this.streamMap[R],I=Math.max(E.audioInfoList.length,E.videoInfoList.length,E.streamList.length),C={url:R,msids:[],type:E.type,latestUrl:E.latestUrl||E.originUrl,streams:[]},A=0;A<I;A++){if(A<E.audioInfoList.length&&E.audioInfoList[A].msid){var w=E.audioInfoList[A];w.msid&&(E.type===d.Publish&&w.pubDone||E.type===d.Subscribe&&w.subDone)&&C.msids.push({name:w.msid||"",type:w.type||"audio",streamId:w.streamId})}if(A<E.videoInfoList.length&&E.videoInfoList[A].msid){var N=E.videoInfoList[A];N.msid&&(E.type===d.Publish&&N.pubDone||E.type===d.Subscribe&&N.subDone)&&C.msids.push({name:N.msid||"",type:N.type||"video",streamId:N.streamId})}A<E.streamList.length&&E.streamList[A]&&((g=C.streams)===null||g===void 0||g.push(E.streamList[A]))}C.msids.length&&S.push(C)}return S},y.prototype.getSender=function(g,S,R){var E,I,C=void 0,A=this.getAllMediaInfoList(g,!0);return R?A.forEach(function(w){var N,M,D,L=(M=(N=w.transceiver)===null||N===void 0?void 0:N.sender)===null||M===void 0?void 0:M.track;(L==null?void 0:L.kind)===S&&w.msid===R&&(C=(D=w.transceiver)===null||D===void 0?void 0:D.sender)}):C=(I=(E=A==null?void 0:A.find(function(w){var N,M,D;return((D=(M=(N=w.transceiver)===null||N===void 0?void 0:N.sender)===null||M===void 0?void 0:M.track)===null||D===void 0?void 0:D.kind)===S}))===null||E===void 0?void 0:E.transceiver)===null||I===void 0?void 0:I.sender,C},y.prototype.getReceiver=function(g,S,R){var E,I,C=void 0,A=this.getAllMediaInfoList(g,!0);return R?A.forEach(function(w){var N,M,D,L=(M=(N=w.transceiver)===null||N===void 0?void 0:N.receiver)===null||M===void 0?void 0:M.track;(L==null?void 0:L.kind)===S&&w.msid===R&&(C=(D=w.transceiver)===null||D===void 0?void 0:D.receiver)}):C=(I=(E=A==null?void 0:A.find(function(w){var N,M,D;return((D=(M=(N=w.transceiver)===null||N===void 0?void 0:N.receiver)===null||M===void 0?void 0:M.track)===null||D===void 0?void 0:D.kind)===S}))===null||E===void 0?void 0:E.transceiver)===null||I===void 0?void 0:I.receiver,C},y.prototype.dispose=function(){this.streamMap={},this.streamMapBackup={}},y.prototype.updateMediaInfoList=function(g,S){var R=S.findIndex(function(E){return E.msid===g.msid});R!==-1?S.splice(R,1,g):S.push(g)},y.prototype.findMediaItemByMsid=function(g,S){return S.find(function(R){return R.msid===g})},y.prototype.createMediaItem=function(g,S){return{msid:g,ssrc:void 0,transceiver:void 0,subDone:!1,pubDone:!1,type:S,streamId:void 0}},y.prototype.getPubOrSubDoneMediaUrlByIndex=function(g){var S=0,R=function(A){var w=E.streamMap[A],N=!1;if(w.audioInfoList.forEach(function(M){N=N||w.type===d.Publish&&M.pubDone||w.type===d.Subscribe&&M.subDone}),w.videoInfoList.forEach(function(M){N=N||w.type===d.Publish&&M.pubDone||w.type===d.Subscribe&&M.subDone}),N){if(S===g)return{value:A};S++}},E=this;for(var I in this.streamMap){var C=R(I);if(typeof C=="object")return C.value}},y.prototype.updateLatestUrl=function(g){var S=this.get(g);return!!S&&(S.latestUrl=g,!0)},y}();v.StreamManager=b}},c={};function h(f){var v=c[f];if(v!==void 0)return v.exports;var p=c[f]={exports:{}};return o[f].call(p.exports,p,p.exports,h),p.exports}var l={};return(()=>{var f=l;Object.defineProperty(f,"__esModule",{value:!0}),f.DataChannelCore=f.EDatachannelStatus=f.PeerConnectionCore=void 0;var v=h(776);Object.defineProperty(f,"PeerConnectionCore",{enumerable:!0,get:function(){return v.PeerConnectionCore}}),Object.defineProperty(f,"EDatachannelStatus",{enumerable:!0,get:function(){return v.EDatachannelStatus}});var p=h(651);Object.defineProperty(f,"DataChannelCore",{enumerable:!0,get:function(){return p.DataChannelCore}})})(),l})(),a.exports=s()},2505:(a,s,o)=>{a.exports=o(8015)},5592:(a,s,o)=>{var c=o(9516),h=o(7522),l=o(3948),f=o(9106),v=o(9615),p=o(2012),_=o(4202),m=o(7763);a.exports=function(d){return new Promise(function(u,b){var y=d.data,g=d.headers,S=d.responseType;c.isFormData(y)&&delete g["Content-Type"];var R=new XMLHttpRequest;if(d.auth){var E=d.auth.username||"",I=d.auth.password?unescape(encodeURIComponent(d.auth.password)):"";g.Authorization="Basic "+btoa(E+":"+I)}var C=v(d.baseURL,d.url);function A(){if(R){var N="getAllResponseHeaders"in R?p(R.getAllResponseHeaders()):null,M={data:S&&S!=="text"&&S!=="json"?R.response:R.responseText,status:R.status,statusText:R.statusText,headers:N,config:d,request:R};h(u,b,M),R=null}}if(R.open(d.method.toUpperCase(),f(C,d.params,d.paramsSerializer),!0),R.timeout=d.timeout,"onloadend"in R?R.onloadend=A:R.onreadystatechange=function(){R&&R.readyState===4&&(R.status!==0||R.responseURL&&R.responseURL.indexOf("file:")===0)&&setTimeout(A)},R.onabort=function(){R&&(b(m("Request aborted",d,"ECONNABORTED",R)),R=null)},R.onerror=function(){b(m("Network Error",d,null,R)),R=null},R.ontimeout=function(){var N="timeout of "+d.timeout+"ms exceeded";d.timeoutErrorMessage&&(N=d.timeoutErrorMessage),b(m(N,d,d.transitional&&d.transitional.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",R)),R=null},c.isStandardBrowserEnv()){var w=(d.withCredentials||_(C))&&d.xsrfCookieName?l.read(d.xsrfCookieName):void 0;w&&(g[d.xsrfHeaderName]=w)}"setRequestHeader"in R&&c.forEach(g,function(N,M){y===void 0&&M.toLowerCase()==="content-type"?delete g[M]:R.setRequestHeader(M,N)}),c.isUndefined(d.withCredentials)||(R.withCredentials=!!d.withCredentials),S&&S!=="json"&&(R.responseType=d.responseType),typeof d.onDownloadProgress=="function"&&R.addEventListener("progress",d.onDownloadProgress),typeof d.onUploadProgress=="function"&&R.upload&&R.upload.addEventListener("progress",d.onUploadProgress),d.cancelToken&&d.cancelToken.promise.then(function(N){R&&(R.abort(),b(N),R=null)}),y||(y=null),R.send(y)})}},8015:(a,s,o)=>{var c=o(9516),h=o(9012),l=o(5155),f=o(5343);function v(_){var m=new l(_),d=h(l.prototype.request,m);return c.extend(d,l.prototype,m),c.extend(d,m),d}var p=v(o(6987));p.Axios=l,p.create=function(_){return v(f(p.defaults,_))},p.Cancel=o(1928),p.CancelToken=o(3191),p.isCancel=o(3864),p.all=function(_){return Promise.all(_)},p.spread=o(7980),p.isAxiosError=o(5019),a.exports=p,a.exports.default=p},1928:a=>{function s(o){this.message=o}s.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},s.prototype.__CANCEL__=!0,a.exports=s},3191:(a,s,o)=>{var c=o(1928);function h(l){if(typeof l!="function")throw new TypeError("executor must be a function.");var f;this.promise=new Promise(function(p){f=p});var v=this;l(function(p){v.reason||(v.reason=new c(p),f(v.reason))})}h.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},h.source=function(){var l;return{token:new h(function(f){l=f}),cancel:l}},a.exports=h},3864:a=>{a.exports=function(s){return!(!s||!s.__CANCEL__)}},5155:(a,s,o)=>{var c=o(9516),h=o(9106),l=o(3471),f=o(4490),v=o(5343),p=o(4841),_=p.validators;function m(d){this.defaults=d,this.interceptors={request:new l,response:new l}}m.prototype.request=function(d){typeof d=="string"?(d=arguments[1]||{}).url=arguments[0]:d=d||{},(d=v(this.defaults,d)).method?d.method=d.method.toLowerCase():this.defaults.method?d.method=this.defaults.method.toLowerCase():d.method="get";var u=d.transitional;u!==void 0&&p.assertOptions(u,{silentJSONParsing:_.transitional(_.boolean,"1.0.0"),forcedJSONParsing:_.transitional(_.boolean,"1.0.0"),clarifyTimeoutError:_.transitional(_.boolean,"1.0.0")},!1);var b=[],y=!0;this.interceptors.request.forEach(function(A){typeof A.runWhen=="function"&&A.runWhen(d)===!1||(y=y&&A.synchronous,b.unshift(A.fulfilled,A.rejected))});var g,S=[];if(this.interceptors.response.forEach(function(A){S.push(A.fulfilled,A.rejected)}),!y){var R=[f,void 0];for(Array.prototype.unshift.apply(R,b),R=R.concat(S),g=Promise.resolve(d);R.length;)g=g.then(R.shift(),R.shift());return g}for(var E=d;b.length;){var I=b.shift(),C=b.shift();try{E=I(E)}catch(A){C(A);break}}try{g=f(E)}catch(A){return Promise.reject(A)}for(;S.length;)g=g.then(S.shift(),S.shift());return g},m.prototype.getUri=function(d){return d=v(this.defaults,d),h(d.url,d.params,d.paramsSerializer).replace(/^\?/,"")},c.forEach(["delete","get","head","options"],function(d){m.prototype[d]=function(u,b){return this.request(v(b||{},{method:d,url:u,data:(b||{}).data}))}}),c.forEach(["post","put","patch"],function(d){m.prototype[d]=function(u,b,y){return this.request(v(y||{},{method:d,url:u,data:b}))}}),a.exports=m},3471:(a,s,o)=>{var c=o(9516);function h(){this.handlers=[]}h.prototype.use=function(l,f,v){return this.handlers.push({fulfilled:l,rejected:f,synchronous:!!v&&v.synchronous,runWhen:v?v.runWhen:null}),this.handlers.length-1},h.prototype.eject=function(l){this.handlers[l]&&(this.handlers[l]=null)},h.prototype.forEach=function(l){c.forEach(this.handlers,function(f){f!==null&&l(f)})},a.exports=h},9615:(a,s,o)=>{var c=o(9137),h=o(4680);a.exports=function(l,f){return l&&!c(f)?h(l,f):f}},7763:(a,s,o)=>{var c=o(5449);a.exports=function(h,l,f,v,p){var _=new Error(h);return c(_,l,f,v,p)}},4490:(a,s,o)=>{var c=o(9516),h=o(2881),l=o(3864),f=o(6987);function v(p){p.cancelToken&&p.cancelToken.throwIfRequested()}a.exports=function(p){return v(p),p.headers=p.headers||{},p.data=h.call(p,p.data,p.headers,p.transformRequest),p.headers=c.merge(p.headers.common||{},p.headers[p.method]||{},p.headers),c.forEach(["delete","get","head","post","put","patch","common"],function(_){delete p.headers[_]}),(p.adapter||f.adapter)(p).then(function(_){return v(p),_.data=h.call(p,_.data,_.headers,p.transformResponse),_},function(_){return l(_)||(v(p),_&&_.response&&(_.response.data=h.call(p,_.response.data,_.response.headers,p.transformResponse))),Promise.reject(_)})}},5449:a=>{a.exports=function(s,o,c,h,l){return s.config=o,c&&(s.code=c),s.request=h,s.response=l,s.isAxiosError=!0,s.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},s}},5343:(a,s,o)=>{var c=o(9516);a.exports=function(h,l){l=l||{};var f={},v=["url","method","data"],p=["headers","auth","proxy","params"],_=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],m=["validateStatus"];function d(g,S){return c.isPlainObject(g)&&c.isPlainObject(S)?c.merge(g,S):c.isPlainObject(S)?c.merge({},S):c.isArray(S)?S.slice():S}function u(g){c.isUndefined(l[g])?c.isUndefined(h[g])||(f[g]=d(void 0,h[g])):f[g]=d(h[g],l[g])}c.forEach(v,function(g){c.isUndefined(l[g])||(f[g]=d(void 0,l[g]))}),c.forEach(p,u),c.forEach(_,function(g){c.isUndefined(l[g])?c.isUndefined(h[g])||(f[g]=d(void 0,h[g])):f[g]=d(void 0,l[g])}),c.forEach(m,function(g){g in l?f[g]=d(h[g],l[g]):g in h&&(f[g]=d(void 0,h[g]))});var b=v.concat(p).concat(_).concat(m),y=Object.keys(h).concat(Object.keys(l)).filter(function(g){return b.indexOf(g)===-1});return c.forEach(y,u),f}},7522:(a,s,o)=>{var c=o(7763);a.exports=function(h,l,f){var v=f.config.validateStatus;f.status&&v&&!v(f.status)?l(c("Request failed with status code "+f.status,f.config,null,f.request,f)):h(f)}},2881:(a,s,o)=>{var c=o(9516),h=o(6987);a.exports=function(l,f,v){var p=this||h;return c.forEach(v,function(_){l=_.call(p,l,f)}),l}},6987:(a,s,o)=>{var c=o(9516),h=o(7018),l=o(5449),f={"Content-Type":"application/x-www-form-urlencoded"};function v(m,d){!c.isUndefined(m)&&c.isUndefined(m["Content-Type"])&&(m["Content-Type"]=d)}var p,_={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:((typeof XMLHttpRequest<"u"||typeof process<"u"&&Object.prototype.toString.call(process)==="[object process]")&&(p=o(5592)),p),transformRequest:[function(m,d){return h(d,"Accept"),h(d,"Content-Type"),c.isFormData(m)||c.isArrayBuffer(m)||c.isBuffer(m)||c.isStream(m)||c.isFile(m)||c.isBlob(m)?m:c.isArrayBufferView(m)?m.buffer:c.isURLSearchParams(m)?(v(d,"application/x-www-form-urlencoded;charset=utf-8"),m.toString()):c.isObject(m)||d&&d["Content-Type"]==="application/json"?(v(d,"application/json"),function(u,b,y){if(c.isString(u))try{return(b||JSON.parse)(u),c.trim(u)}catch(g){if(g.name!=="SyntaxError")throw g}return(y||JSON.stringify)(u)}(m)):m}],transformResponse:[function(m){var d=this.transitional,u=d&&d.silentJSONParsing,b=d&&d.forcedJSONParsing,y=!u&&this.responseType==="json";if(y||b&&c.isString(m)&&m.length)try{return JSON.parse(m)}catch(g){if(y)throw g.name==="SyntaxError"?l(g,this,"E_JSON_PARSE"):g}return m}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(m){return m>=200&&m<300}};_.headers={common:{Accept:"application/json, text/plain, */*"}},c.forEach(["delete","get","head"],function(m){_.headers[m]={}}),c.forEach(["post","put","patch"],function(m){_.headers[m]=c.merge(f)}),a.exports=_},9012:a=>{a.exports=function(s,o){return function(){for(var c=new Array(arguments.length),h=0;h<c.length;h++)c[h]=arguments[h];return s.apply(o,c)}}},9106:(a,s,o)=>{var c=o(9516);function h(l){return encodeURIComponent(l).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}a.exports=function(l,f,v){if(!f)return l;var p;if(v)p=v(f);else if(c.isURLSearchParams(f))p=f.toString();else{var _=[];c.forEach(f,function(d,u){d!=null&&(c.isArray(d)?u+="[]":d=[d],c.forEach(d,function(b){c.isDate(b)?b=b.toISOString():c.isObject(b)&&(b=JSON.stringify(b)),_.push(h(u)+"="+h(b))}))}),p=_.join("&")}if(p){var m=l.indexOf("#");m!==-1&&(l=l.slice(0,m)),l+=(l.indexOf("?")===-1?"?":"&")+p}return l}},4680:a=>{a.exports=function(s,o){return o?s.replace(/\/+$/,"")+"/"+o.replace(/^\/+/,""):s}},3948:(a,s,o)=>{var c=o(9516);a.exports=c.isStandardBrowserEnv()?{write:function(h,l,f,v,p,_){var m=[];m.push(h+"="+encodeURIComponent(l)),c.isNumber(f)&&m.push("expires="+new Date(f).toGMTString()),c.isString(v)&&m.push("path="+v),c.isString(p)&&m.push("domain="+p),_===!0&&m.push("secure"),document.cookie=m.join("; ")},read:function(h){var l=document.cookie.match(new RegExp("(^|;\\s*)("+h+")=([^;]*)"));return l?decodeURIComponent(l[3]):null},remove:function(h){this.write(h,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}},9137:a=>{a.exports=function(s){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(s)}},5019:a=>{a.exports=function(s){return typeof s=="object"&&s.isAxiosError===!0}},4202:(a,s,o)=>{var c=o(9516);a.exports=c.isStandardBrowserEnv()?function(){var h,l=/(msie|trident)/i.test(navigator.userAgent),f=document.createElement("a");function v(p){var _=p;return l&&(f.setAttribute("href",_),_=f.href),f.setAttribute("href",_),{href:f.href,protocol:f.protocol?f.protocol.replace(/:$/,""):"",host:f.host,search:f.search?f.search.replace(/^\?/,""):"",hash:f.hash?f.hash.replace(/^#/,""):"",hostname:f.hostname,port:f.port,pathname:f.pathname.charAt(0)==="/"?f.pathname:"/"+f.pathname}}return h=v(window.location.href),function(p){var _=c.isString(p)?v(p):p;return _.protocol===h.protocol&&_.host===h.host}}():function(){return!0}},7018:(a,s,o)=>{var c=o(9516);a.exports=function(h,l){c.forEach(h,function(f,v){v!==l&&v.toUpperCase()===l.toUpperCase()&&(h[l]=f,delete h[v])})}},2012:(a,s,o)=>{var c=o(9516),h=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];a.exports=function(l){var f,v,p,_={};return l&&c.forEach(l.split(`
`),function(m){if(p=m.indexOf(":"),f=c.trim(m.substr(0,p)).toLowerCase(),v=c.trim(m.substr(p+1)),f){if(_[f]&&h.indexOf(f)>=0)return;_[f]=f==="set-cookie"?(_[f]?_[f]:[]).concat([v]):_[f]?_[f]+", "+v:v}}),_}},7980:a=>{a.exports=function(s){return function(o){return s.apply(null,o)}}},4841:(a,s,o)=>{var c=o(4198),h={};["object","boolean","number","function","string","symbol"].forEach(function(p,_){h[p]=function(m){return typeof m===p||"a"+(_<1?"n ":" ")+p}});var l={},f=c.version.split(".");function v(p,_){for(var m=_?_.split("."):f,d=p.split("."),u=0;u<3;u++){if(m[u]>d[u])return!0;if(m[u]<d[u])return!1}return!1}h.transitional=function(p,_,m){var d=_&&v(_);function u(b,y){return"[Axios v"+c.version+"] Transitional option '"+b+"'"+y+(m?". "+m:"")}return function(b,y,g){if(p===!1)throw new Error(u(y," has been removed in "+_));return d&&!l[y]&&(l[y]=!0,console.warn(u(y," has been deprecated since v"+_+" and will be removed in the near future"))),!p||p(b,y,g)}},a.exports={isOlderVersion:v,assertOptions:function(p,_,m){if(typeof p!="object")throw new TypeError("options must be an object");for(var d=Object.keys(p),u=d.length;u-- >0;){var b=d[u],y=_[b];if(y){var g=p[b],S=g===void 0||y(g,b,p);if(S!==!0)throw new TypeError("option "+b+" must be "+S)}else if(m!==!0)throw Error("Unknown option "+b)}},validators:h}},9516:(a,s,o)=>{var c=o(9012),h=Object.prototype.toString;function l(d){return h.call(d)==="[object Array]"}function f(d){return d===void 0}function v(d){return d!==null&&typeof d=="object"}function p(d){if(h.call(d)!=="[object Object]")return!1;var u=Object.getPrototypeOf(d);return u===null||u===Object.prototype}function _(d){return h.call(d)==="[object Function]"}function m(d,u){if(d!=null)if(typeof d!="object"&&(d=[d]),l(d))for(var b=0,y=d.length;b<y;b++)u.call(null,d[b],b,d);else for(var g in d)Object.prototype.hasOwnProperty.call(d,g)&&u.call(null,d[g],g,d)}a.exports={isArray:l,isArrayBuffer:function(d){return h.call(d)==="[object ArrayBuffer]"},isBuffer:function(d){return d!==null&&!f(d)&&d.constructor!==null&&!f(d.constructor)&&typeof d.constructor.isBuffer=="function"&&d.constructor.isBuffer(d)},isFormData:function(d){return typeof FormData<"u"&&d instanceof FormData},isArrayBufferView:function(d){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(d):d&&d.buffer&&d.buffer instanceof ArrayBuffer},isString:function(d){return typeof d=="string"},isNumber:function(d){return typeof d=="number"},isObject:v,isPlainObject:p,isUndefined:f,isDate:function(d){return h.call(d)==="[object Date]"},isFile:function(d){return h.call(d)==="[object File]"},isBlob:function(d){return h.call(d)==="[object Blob]"},isFunction:_,isStream:function(d){return v(d)&&_(d.pipe)},isURLSearchParams:function(d){return typeof URLSearchParams<"u"&&d instanceof URLSearchParams},isStandardBrowserEnv:function(){return(typeof navigator>"u"||navigator.product!=="ReactNative"&&navigator.product!=="NativeScript"&&navigator.product!=="NS")&&typeof window<"u"&&typeof document<"u"},forEach:m,merge:function d(){var u={};function b(S,R){p(u[R])&&p(S)?u[R]=d(u[R],S):p(S)?u[R]=d({},S):l(S)?u[R]=S.slice():u[R]=S}for(var y=0,g=arguments.length;y<g;y++)m(arguments[y],b);return u},extend:function(d,u,b){return m(u,function(y,g){d[g]=b&&typeof y=="function"?c(y,b):y}),d},trim:function(d){return d.trim?d.trim():d.replace(/^\s+|\s+$/g,"")},stripBOM:function(d){return d.charCodeAt(0)===65279&&(d=d.slice(1)),d}}},3412:a=>{/*! media-device - ver 1.4.2 created:2025/11/26 14:19:30 */a.exports=(()=>{var s={304:(c,h,l)=>{Object.defineProperty(h,"__esModule",{value:!0}),h.BrowserDeviceManager=void 0;var f=l(101),v=l(853),p=l(62),_=l(913),m=l(331),d=l(1),u=l(935),b=l(603),y=function(){function g(){this.systemUtil=new f.SystemUtil,this.deviceManager=this.createDeviceManager()}return g.prototype.getCameraList=function(){return this.deviceManager.getCameraList()},g.prototype.getMicList=function(){return this.deviceManager.getMicList()},g.prototype.getSpeakerList=function(){return this.deviceManager.getSpeakerList()},g.prototype.getAudioTrack=function(S){return this.deviceManager.getAudioTrack(S)},g.prototype.getVideoTrack=function(S){return this.deviceManager.getVideoTrack(S)},g.prototype.getAudioVideoTracks=function(S){return this.deviceManager.getAudioVideoTracks(S)},g.prototype.getScreenTrack=function(S){return this.deviceManager.getScreenTrack(S)},g.prototype.getAudioStream=function(S){return this.deviceManager.getAudioStream(S)},g.prototype.getVideoStream=function(S){return this.deviceManager.getVideoStream(S)},g.prototype.getScreenStream=function(S){return this.deviceManager.getScreenStream(S)},g.prototype.checkSupportScreenShare=function(){return this.deviceManager.checkSupportScreenShare()},g.prototype.createDeviceManager=function(){return this.systemUtil.isWindows?new u.WindowsDeviceManager:this.systemUtil.isAndroid?new v.AndroidDeviceManager:this.systemUtil.isIos?new _.IosDeviceManager:this.systemUtil.isMacOS?new d.MacDeviceManager:this.systemUtil.isLinux?new m.LinuxDeviceManager:new p.BaseDeviceManager},g.isDeviceManagerError=b.DeviceError.isDeviceManagerError,g}();h.BrowserDeviceManager=y},603:(c,h,l)=>{Object.defineProperty(h,"__esModule",{value:!0}),h.DeviceError=h.DeviceErrorDescription=h.DeviceErrorCode=void 0;var f=l(610);(function(p){p[p.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",p[p.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",p[p.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10002]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",p[p.ERROR_DEVICE_NOTFOUND=10020]="ERROR_DEVICE_NOTFOUND",p[p.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10003]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",p[p.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10004]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",p[p.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",p[p.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10005]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",p[p.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",p[p.ERROR_DEVICE_NOTREADABLE=10022]="ERROR_DEVICE_NOTREADABLE",p[p.ERROR_DEIVCE_CONSTRAINEDERROR=10007]="ERROR_DEIVCE_CONSTRAINEDERROR",p[p.ERROR_SCREENSHARE_UNKNOWNERRO=10010]="ERROR_SCREENSHARE_UNKNOWNERRO",p[p.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",p[p.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",p[p.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",p[p.ERROR_SCREENSHARE_INVALIDACCESS=10014]="ERROR_SCREENSHARE_INVALIDACCESS",p[p.ERROR_SCREENSHARE_NOTSUPPORT=10018]="ERROR_SCREENSHARE_NOTSUPPORT",p[p.ERROR_DEVICE_NOTSUPPORT=10019]="ERROR_DEVICE_NOTSUPPORT"})(h.DeviceErrorCode||(h.DeviceErrorCode={})),function(p){p.ERRORMESSAGE_DEVICENOTFOUND="Requested device not found",p.ERRORMESSAGE_DEVICENOTALLOWED="Permission denied",p.ERRORMESSAGE_MACCHROME_DEVICENOTREADABLE="Permission denied by system",p.ERRORMESSAGE_MACSAFARI_DEVICENOTALLOWED="The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.",p.ERRORMESSAGE_MOBILEDEVICE_NOTALLOWED="video device not allowed",p.ERRORMESSAGE_AUDIODEVICENOTREADABLE="Could not start audio source",p.ERRORMESSAGE_VIDEODEVICENOTREADABLE="Could not start video source",p.ERRORNAME_DEVICENOTFOUND="NotFoundError",p.ERRORNAME_DEVICENOTALLOWED="NotAllowedError",p.ERRORNAME_DEVICENOTREADABLE="NotReadableError",p.ERRORNAME_DEVICEOVERCONSTRAINED="OverconstrainedError",p.ERRORNAME_INVALID_ACCESS="InvalidAccessError"}(h.DeviceErrorDescription||(h.DeviceErrorDescription={}));var v=function(){function p(_,m){this.linkUtil=new f.LinkUtil,this.code=_,this.reason=m,this.relatedLink=this.linkUtil.getRelatedLink(_)}return p.isDeviceManagerError=function(_){return!!(_&&typeof _=="object"&&"code"in _&&"reason"in _)},p}();h.DeviceError=v},873:(c,h)=>{Object.defineProperty(h,"__esModule",{value:!0}),h.DeviceType=h.MobileCameraType=void 0,function(l){l[l.USER=0]="USER",l[l.ENV=1]="ENV"}(h.MobileCameraType||(h.MobileCameraType={})),function(l){l.Camera="videoinput",l.Mic="audioinput",l.Mixed="audiovideoinput",l.Screen="screen",l.Speaker="audiooutput"}(h.DeviceType||(h.DeviceType={}))},853:function(c,h,l){var f,v=this&&this.__extends||(f=function(_,m){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,u){d.__proto__=u}||function(d,u){for(var b in u)Object.prototype.hasOwnProperty.call(u,b)&&(d[b]=u[b])})(_,m)},function(_,m){function d(){this.constructor=_}f(_,m),_.prototype=m===null?Object.create(m):(d.prototype=m.prototype,new d)});Object.defineProperty(h,"__esModule",{value:!0}),h.AndroidDeviceManager=void 0;var p=function(_){function m(){return _.call(this)||this}return v(m,_),m}(l(583).MobileDeviceManager);h.AndroidDeviceManager=p},62:(c,h,l)=>{Object.defineProperty(h,"__esModule",{value:!0}),h.BaseDeviceManager=void 0;var f=l(603),v=l(873),p=function(){function _(){}return _.prototype.checkSupportScreenShare=function(){return!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia&&navigator.mediaDevices.getDisplayMedia)},_.prototype.getCameraList=function(){var m=this;return new Promise(function(d,u){m.checkSupport()?m.getDeviceRight(v.DeviceType.Camera).then(function(){m.getDeviceList(v.DeviceType.Camera).then(function(b){d(b)}).catch(function(b){u(m.parseError(v.DeviceType.Camera,b))})}).catch(function(b){u(m.parseError(v.DeviceType.Camera,b))}):u(new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},_.prototype.getMicList=function(){var m=this;return new Promise(function(d,u){m.checkSupport()?m.getDeviceRight(v.DeviceType.Mic).then(function(){m.getDeviceList(v.DeviceType.Mic).then(function(b){d(b)}).catch(function(b){u(m.parseError(v.DeviceType.Mic,b))})}).catch(function(b){u(m.parseError(v.DeviceType.Mic,b))}):u(new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},_.prototype.getSpeakerList=function(){var m=this;return new Promise(function(d,u){m.checkSupport()?m.getDeviceRight(v.DeviceType.Speaker).then(function(){m.getDeviceList(v.DeviceType.Speaker).then(function(b){d(b)}).catch(function(b){u(m.parseError(v.DeviceType.Speaker,b))})}).catch(function(b){u(m.parseError(v.DeviceType.Speaker,b))}):u(new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},_.prototype.getAudioTrack=function(m){return this.getAudioStream(m).then(function(d){return d.getAudioTracks()[0]})},_.prototype.getAudioStream=function(m){var d=this;return new Promise(function(u,b){if(d.checkSupport()){var y=d.createAudioConstraints(m);navigator.mediaDevices.getUserMedia(y).then(function(g){u(g)}).catch(function(g){b(d.parseError(v.DeviceType.Mic,g))})}else b(new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},_.prototype.getVideoTrack=function(m){return this.getVideoStream(m).then(function(d){return d.getVideoTracks()[0]})},_.prototype.getVideoStream=function(m){var d=this;return new Promise(function(u,b){if(d.checkSupport()){var y=d.createVideoConstraints(m);navigator.mediaDevices.getUserMedia(y).then(function(g){u(g)}).catch(function(g){b(d.parseError(v.DeviceType.Camera,g))})}else b(new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},_.prototype.getAudioVideoTracks=function(m){return this.getMixedStream(m).then(function(d){return d.getTracks()})},_.prototype.getMixedStream=function(m){var d=this;return new Promise(function(u,b){if(d.checkSupport()){var y=d.createMixedConstraints(m);navigator.mediaDevices.getUserMedia(y).then(function(g){u(g)}).catch(function(g){b(d.parseError(v.DeviceType.Mixed,g))})}else b(new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},_.prototype.getScreenTrack=function(m){return this.getScreenStream(m).then(function(d){return d.getTracks()})},_.prototype.getScreenStream=function(m){var d=this;return new Promise(function(u,b){d.checkSupportScreenShare()?navigator.mediaDevices.getDisplayMedia(m).then(function(y){u(y)}).catch(function(y){b(d.parseError(v.DeviceType.Screen,y))}):b(new f.DeviceError(f.DeviceErrorCode.ERROR_SCREENSHARE_NOTSUPPORT,"browser not support screenshare"))})},_.prototype.checkSupport=function(){return!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices&&navigator.mediaDevices.getUserMedia)},_.prototype.getDeviceList=function(m){return new Promise(function(d,u){navigator.mediaDevices.enumerateDevices().then(function(b){var y=[];b.forEach(function(g){g.kind===m&&y.push(g)}),d(y)}).catch(function(b){u(b)})})},_.prototype.getDeviceRight=function(m){return new Promise(function(d,u){var b;v.DeviceType.Camera===m?b={video:!0}:v.DeviceType.Mic!==m&&v.DeviceType.Speaker!==m||(b={audio:!0}),navigator.mediaDevices.getUserMedia(b).then(function(y){y.getTracks().forEach(function(g){g.stop()}),d(void 0)}).catch(function(y){d(void 0)})})},_.prototype.parseError=function(m,d){var u=null;return v.DeviceType.Mic===m?u=this.parseAudioError(d):v.DeviceType.Camera===m?u=this.parseVideoError(d):v.DeviceType.Mixed===m?u=this.parseMixedError(d):v.DeviceType.Screen===m&&(u=this.parseScreenError(d)),u===null?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_UNKNOWNERROR,""):u},_.prototype.parseAudioError=function(m){return m.message===f.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTFOUND||m.name===f.DeviceErrorDescription.ERRORNAME_DEVICENOTFOUND?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTFOUND,"audio device not found"):m.message===f.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTALLOWED||m.message===f.DeviceErrorDescription.ERRORMESSAGE_MACSAFARI_DEVICENOTALLOWED?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED,"audio device not allowed"):m.message===f.DeviceErrorDescription.ERRORMESSAGE_MACCHROME_DEVICENOTREADABLE||m.message===f.DeviceErrorDescription.ERRORMESSAGE_AUDIODEVICENOTREADABLE||m.message===f.DeviceErrorDescription.ERRORNAME_DEVICENOTREADABLE?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE,"audio device not readable"):null},_.prototype.parseVideoError=function(m){return m.message===f.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTFOUND||m.name===f.DeviceErrorDescription.ERRORNAME_DEVICENOTFOUND?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTFOUND,"video device not found"):m.message===f.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTALLOWED||m.message===f.DeviceErrorDescription.ERRORMESSAGE_MOBILEDEVICE_NOTALLOWED||m.message===f.DeviceErrorDescription.ERRORMESSAGE_MACSAFARI_DEVICENOTALLOWED?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED,"video device not allowed"):m.message===f.DeviceErrorDescription.ERRORMESSAGE_MACCHROME_DEVICENOTREADABLE||m.message===f.DeviceErrorDescription.ERRORMESSAGE_VIDEODEVICENOTREADABLE||m.name===f.DeviceErrorDescription.ERRORNAME_DEVICENOTREADABLE?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE,"video device not readable"):null},_.prototype.parseMixedError=function(m){return m.message===f.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTFOUND||m.name===f.DeviceErrorDescription.ERRORNAME_DEVICENOTFOUND?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_NOTFOUND,"audio or video device not found"):m.message===f.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTALLOWED||m.message===f.DeviceErrorDescription.ERRORMESSAGE_MACSAFARI_DEVICENOTALLOWED?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_NOTALLOWED,"audio or video device not allowed"):m.message===f.DeviceErrorDescription.ERRORMESSAGE_MOBILEDEVICE_NOTALLOWED?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED,"video device not allowed"):m.message===f.DeviceErrorDescription.ERRORMESSAGE_MACCHROME_DEVICENOTREADABLE||m.name===f.DeviceErrorDescription.ERRORNAME_DEVICENOTREADABLE?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_NOTREADABLE,"audio or video device not readable"):m.message===f.DeviceErrorDescription.ERRORMESSAGE_AUDIODEVICENOTREADABLE?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE,"audio device not readable"):m.message===f.DeviceErrorDescription.ERRORMESSAGE_VIDEODEVICENOTREADABLE?new f.DeviceError(f.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE,"video device not readable"):null},_.prototype.parseScreenError=function(m){return m.name===f.DeviceErrorDescription.ERRORNAME_DEVICENOTALLOWED?m.message===f.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTALLOWED?new f.DeviceError(f.DeviceErrorCode.ERROR_SCREENSHARE_NOTALLOWED,m.message):new f.DeviceError(f.DeviceErrorCode.ERROR_SCREENSHARE_NOPERMISSION,m.message):m.name===f.DeviceErrorDescription.ERRORNAME_INVALID_ACCESS?new f.DeviceError(f.DeviceErrorCode.ERROR_SCREENSHARE_INVALIDACCESS,m.message):null},_.prototype.createVideoConstraints=function(m){typeof m.deviceId=="string"&&(m.deviceId={exact:m.deviceId});var d={video:m};return Object.keys(m).length===0&&(d={video:!0}),d},_.prototype.createAudioConstraints=function(m){typeof m.deviceId=="string"&&(m.deviceId={exact:m.deviceId});var d={audio:m};return Object.keys(m).length===0&&(d={audio:!0}),d},_.prototype.createMixedConstraints=function(m){if(console.log("createMixedConstraints"),m.video&&typeof m.video=="object"){var d=m.video;typeof d.deviceId=="string"&&(d.deviceId={exact:d.deviceId})}if(m.audio&&typeof m.audio=="object"){var u=m.audio;typeof u.deviceId=="string"&&(u.deviceId={exact:u.deviceId})}return m},_}();h.BaseDeviceManager=p},913:function(c,h,l){var f,v=this&&this.__extends||(f=function(_,m){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,u){d.__proto__=u}||function(d,u){for(var b in u)Object.prototype.hasOwnProperty.call(u,b)&&(d[b]=u[b])})(_,m)},function(_,m){function d(){this.constructor=_}f(_,m),_.prototype=m===null?Object.create(m):(d.prototype=m.prototype,new d)});Object.defineProperty(h,"__esModule",{value:!0}),h.IosDeviceManager=void 0;var p=function(_){function m(){return _.call(this)||this}return v(m,_),m}(l(583).MobileDeviceManager);h.IosDeviceManager=p},331:function(c,h,l){var f,v=this&&this.__extends||(f=function(_,m){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,u){d.__proto__=u}||function(d,u){for(var b in u)Object.prototype.hasOwnProperty.call(u,b)&&(d[b]=u[b])})(_,m)},function(_,m){function d(){this.constructor=_}f(_,m),_.prototype=m===null?Object.create(m):(d.prototype=m.prototype,new d)});Object.defineProperty(h,"__esModule",{value:!0}),h.LinuxDeviceManager=void 0;var p=function(_){function m(){return _.call(this)||this}return v(m,_),m}(l(62).BaseDeviceManager);h.LinuxDeviceManager=p},1:function(c,h,l){var f,v=this&&this.__extends||(f=function(_,m){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,u){d.__proto__=u}||function(d,u){for(var b in u)Object.prototype.hasOwnProperty.call(u,b)&&(d[b]=u[b])})(_,m)},function(_,m){function d(){this.constructor=_}f(_,m),_.prototype=m===null?Object.create(m):(d.prototype=m.prototype,new d)});Object.defineProperty(h,"__esModule",{value:!0}),h.MacDeviceManager=void 0;var p=function(_){function m(){return _.call(this)||this}return v(m,_),m}(l(62).BaseDeviceManager);h.MacDeviceManager=p},583:function(c,h,l){var f,v=this&&this.__extends||(f=function(m,d){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,b){u.__proto__=b}||function(u,b){for(var y in b)Object.prototype.hasOwnProperty.call(b,y)&&(u[y]=b[y])})(m,d)},function(m,d){function u(){this.constructor=m}f(m,d),m.prototype=d===null?Object.create(d):(u.prototype=d.prototype,new u)});Object.defineProperty(h,"__esModule",{value:!0}),h.MobileDeviceManager=void 0;var p=l(603),_=function(m){function d(){return m.call(this)||this}return v(d,m),d.prototype.checkSupportScreenShare=function(){return!1},d.prototype.getScreenTrack=function(u){return new Promise(function(b,y){y(new p.DeviceError(p.DeviceErrorCode.ERROR_SCREENSHARE_NOTSUPPORT,"mobile not support screenshare"))})},d.prototype.getScreenStream=function(u){return new Promise(function(b,y){y(new p.DeviceError(p.DeviceErrorCode.ERROR_SCREENSHARE_NOTSUPPORT,"mobile not support screenshare"))})},d}(l(62).BaseDeviceManager);h.MobileDeviceManager=_},935:function(c,h,l){var f,v=this&&this.__extends||(f=function(_,m){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,u){d.__proto__=u}||function(d,u){for(var b in u)Object.prototype.hasOwnProperty.call(u,b)&&(d[b]=u[b])})(_,m)},function(_,m){function d(){this.constructor=_}f(_,m),_.prototype=m===null?Object.create(m):(d.prototype=m.prototype,new d)});Object.defineProperty(h,"__esModule",{value:!0}),h.WindowsDeviceManager=void 0;var p=function(_){function m(){return _.call(this)||this}return v(m,_),m}(l(62).BaseDeviceManager);h.WindowsDeviceManager=p},607:function(c,h,l){var f=this&&this.__createBinding||(Object.create?function(_,m,d,u){u===void 0&&(u=d),Object.defineProperty(_,u,{enumerable:!0,get:function(){return m[d]}})}:function(_,m,d,u){u===void 0&&(u=d),_[u]=m[d]}),v=this&&this.__exportStar||function(_,m){for(var d in _)d==="default"||Object.prototype.hasOwnProperty.call(m,d)||f(m,_,d)};Object.defineProperty(h,"__esModule",{value:!0}),h.BrowserDeviceManager=void 0;var p=l(304);Object.defineProperty(h,"BrowserDeviceManager",{enumerable:!0,get:function(){return p.BrowserDeviceManager}}),v(l(873),h),window&&(window.BrowserDeviceManager=p.BrowserDeviceManager)},610:(c,h,l)=>{Object.defineProperty(h,"__esModule",{value:!0}),h.LinkUtil=void 0;var f,v=l(603),p=l(261),_=l(54);(function(y){y[y.Windows=0]="Windows",y[y.MacOS=1]="MacOS",y[y.Other=2]="Other"})(f||(f={}));var m="ms-settings:",d="x-apple.systempreferences:com.apple.preference.security?",u={SYS_MIC:[m+"privacy-microphone",d+"Privacy_Microphone"],SYS_CAMERA:[m+"privacy-webcam",d+"Privacy_Camera"],SYS_SCREENSHARE:["",d+"Privacy_ScreenCapture"]},b=function(){function y(){p||console.error("SystemUtil is not found"),this.systemType=this.getSystemType()}return y.prototype.getRelatedLink=function(g){var S="",R=this.systemType;switch(g){case v.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTFOUND:case v.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE:S=u.SYS_MIC[R];break;case v.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTFOUND:case v.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE:S=u.SYS_CAMERA[R];break;case v.DeviceErrorCode.ERROR_SCREENSHARE_UNKNOWNERRO:case v.DeviceErrorCode.ERROR_SCREENSHARE_NOPERMISSION:S=u.SYS_SCREENSHARE[R];break;case v.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED:case v.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED:case v.DeviceErrorCode.ERROR_DEVICE_NOTALLOWED:_.isChrome?S=this.getChromeResetLink():_.isEdge&&(S=this.getEdgeResetLink());break;default:S=""}return S},y.prototype.getSystemType=function(){return p.isWindows?f.Windows:p.isMacOS?f.MacOS:f.Other},y.prototype.getChromeResetLink=function(){return"chrome://settings/content/siteDetails?site="+encodeURIComponent(window.location.origin)},y.prototype.getEdgeResetLink=function(){return"edge://settings/content/siteDetails?site="+encodeURIComponent(window.location.origin)},y}();h.LinkUtil=b},101:(c,h)=>{var l;Object.defineProperty(h,"__esModule",{value:!0}),h.SystemUtil=void 0,function(v){v[v.Unknown=0]="Unknown",v[v.MacOS=1]="MacOS",v[v.Windows=2]="Windows",v[v.Android=3]="Android",v[v.Iphone=4]="Iphone",v[v.Ipad=5]="Ipad",v[v.Linux=6]="Linux"}(l||(l={}));var f=function(){function v(){this.systemType=l.Unknown,this.getSystemInfo()}return Object.defineProperty(v.prototype,"isIos",{get:function(){return this.systemType===l.Ipad||this.systemType===l.Iphone},enumerable:!1,configurable:!0}),Object.defineProperty(v.prototype,"isAndroid",{get:function(){return this.systemType===l.Android},enumerable:!1,configurable:!0}),Object.defineProperty(v.prototype,"isMacOS",{get:function(){return this.systemType===l.MacOS},enumerable:!1,configurable:!0}),Object.defineProperty(v.prototype,"isWindows",{get:function(){return this.systemType===l.Windows},enumerable:!1,configurable:!0}),Object.defineProperty(v.prototype,"isLinux",{get:function(){return this.systemType===l.Linux},enumerable:!1,configurable:!0}),v.prototype.getSystemInfo=function(){if(navigator&&navigator.userAgent){var p=navigator.userAgent.toLocaleLowerCase();p.indexOf("ipad")>-1?this.systemType=l.Ipad:p.indexOf("iphone")>-1?this.systemType=l.Iphone:p.indexOf("android")>-1?this.systemType=l.Android:p.indexOf("win")>-1?this.systemType=l.Windows:p.indexOf("mac")>-1?this.systemType=l.MacOS:p.indexOf("linux")>-1?this.systemType=l.Linux:p.indexOf("")>-1&&(this.systemType=l.Unknown)}},v}();h.SystemUtil=f},54:c=>{c.exports=window.BrowserUtil},261:c=>{c.exports=window.SystemUtil}},o={};return function c(h){if(o[h])return o[h].exports;var l=o[h]={exports:{}};return s[h].call(l.exports,l,l.exports,c),l.exports}(607)})()},6677:(a,s,o)=>{var c=o(7963);function h(_,m,d,u,b){var y=c.writeRtpDescription(_.kind,m);if(y+=c.writeIceParameters(_.iceGatherer.getLocalParameters()),y+=c.writeDtlsParameters(_.dtlsTransport.getLocalParameters(),d==="offer"?"actpass":b||"active"),y+="a=mid:"+_.mid+`\r
`,_.rtpSender&&_.rtpReceiver?y+=`a=sendrecv\r
`:_.rtpSender?y+=`a=sendonly\r
`:_.rtpReceiver?y+=`a=recvonly\r
`:y+=`a=inactive\r
`,_.rtpSender){var g=_.rtpSender._initialTrackId||_.rtpSender.track.id;_.rtpSender._initialTrackId=g;var S="msid:"+(u?u.id:"-")+" "+g+`\r
`;y+="a="+S,y+="a=ssrc:"+_.sendEncodingParameters[0].ssrc+" "+S,_.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+_.sendEncodingParameters[0].rtx.ssrc+" "+S,y+="a=ssrc-group:FID "+_.sendEncodingParameters[0].ssrc+" "+_.sendEncodingParameters[0].rtx.ssrc+`\r
`)}return y+="a=ssrc:"+_.sendEncodingParameters[0].ssrc+" cname:"+c.localCName+`\r
`,_.rtpSender&&_.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+_.sendEncodingParameters[0].rtx.ssrc+" cname:"+c.localCName+`\r
`),y}function l(_,m){var d={codecs:[],headerExtensions:[],fecMechanisms:[]},u=function(y,g){y=parseInt(y,10);for(var S=0;S<g.length;S++)if(g[S].payloadType===y||g[S].preferredPayloadType===y)return g[S]},b=function(y,g,S,R){var E=u(y.parameters.apt,S),I=u(g.parameters.apt,R);return E&&I&&E.name.toLowerCase()===I.name.toLowerCase()};return _.codecs.forEach(function(y){for(var g=0;g<m.codecs.length;g++){var S=m.codecs[g];if(y.name.toLowerCase()===S.name.toLowerCase()&&y.clockRate===S.clockRate){if(y.name.toLowerCase()==="rtx"&&y.parameters&&S.parameters.apt&&!b(y,S,_.codecs,m.codecs))continue;(S=JSON.parse(JSON.stringify(S))).numChannels=Math.min(y.numChannels,S.numChannels),d.codecs.push(S),S.rtcpFeedback=S.rtcpFeedback.filter(function(R){for(var E=0;E<y.rtcpFeedback.length;E++)if(y.rtcpFeedback[E].type===R.type&&y.rtcpFeedback[E].parameter===R.parameter)return!0;return!1});break}}}),_.headerExtensions.forEach(function(y){for(var g=0;g<m.headerExtensions.length;g++){var S=m.headerExtensions[g];if(y.uri===S.uri){d.headerExtensions.push(S);break}}}),d}function f(_,m,d){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[m][_].indexOf(d)!==-1}function v(_,m){var d=_.getRemoteCandidates().find(function(u){return m.foundation===u.foundation&&m.ip===u.ip&&m.port===u.port&&m.priority===u.priority&&m.protocol===u.protocol&&m.type===u.type});return d||_.addRemoteCandidate(m),!d}function p(_,m){var d=new Error(m);return d.name=_,d.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[_],d}a.exports=function(_,m){function d(g,S){S.addTrack(g),S.dispatchEvent(new _.MediaStreamTrackEvent("addtrack",{track:g}))}function u(g,S,R,E){var I=new Event("track");I.track=S,I.receiver=R,I.transceiver={receiver:R},I.streams=E,_.setTimeout(function(){g._dispatchEvent("track",I)})}var b=function(g){var S=this,R=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(I){S[I]=R[I].bind(R)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",g=JSON.parse(JSON.stringify(g||{})),this.usingBundle=g.bundlePolicy==="max-bundle",g.rtcpMuxPolicy==="negotiate")throw p("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(g.rtcpMuxPolicy||(g.rtcpMuxPolicy="require"),g.iceTransportPolicy){case"all":case"relay":break;default:g.iceTransportPolicy="all"}switch(g.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:g.bundlePolicy="balanced"}if(g.iceServers=function(I,C){var A=!1;return(I=JSON.parse(JSON.stringify(I))).filter(function(w){if(w&&(w.urls||w.url)){var N=w.urls||w.url;w.url&&!w.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var M=typeof N=="string";return M&&(N=[N]),N=N.filter(function(D){return D.indexOf("turn:")!==0||D.indexOf("transport=udp")===-1||D.indexOf("turn:[")!==-1||A?D.indexOf("stun:")===0&&C>=14393&&D.indexOf("?transport=udp")===-1:(A=!0,!0)}),delete w.url,w.urls=M?N[0]:N,!!N.length}})}(g.iceServers||[],m),this._iceGatherers=[],g.iceCandidatePoolSize)for(var E=g.iceCandidatePoolSize;E>0;E--)this._iceGatherers.push(new _.RTCIceGatherer({iceServers:g.iceServers,gatherPolicy:g.iceTransportPolicy}));else g.iceCandidatePoolSize=0;this._config=g,this.transceivers=[],this._sdpSessionId=c.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(b.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(b.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),b.prototype.onicecandidate=null,b.prototype.onaddstream=null,b.prototype.ontrack=null,b.prototype.onremovestream=null,b.prototype.onsignalingstatechange=null,b.prototype.oniceconnectionstatechange=null,b.prototype.onconnectionstatechange=null,b.prototype.onicegatheringstatechange=null,b.prototype.onnegotiationneeded=null,b.prototype.ondatachannel=null,b.prototype._dispatchEvent=function(g,S){this._isClosed||(this.dispatchEvent(S),typeof this["on"+g]=="function"&&this["on"+g](S))},b.prototype._emitGatheringStateChange=function(){var g=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",g)},b.prototype.getConfiguration=function(){return this._config},b.prototype.getLocalStreams=function(){return this.localStreams},b.prototype.getRemoteStreams=function(){return this.remoteStreams},b.prototype._createTransceiver=function(g,S){var R=this.transceivers.length>0,E={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:g,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&R)E.iceTransport=this.transceivers[0].iceTransport,E.dtlsTransport=this.transceivers[0].dtlsTransport;else{var I=this._createIceAndDtlsTransports();E.iceTransport=I.iceTransport,E.dtlsTransport=I.dtlsTransport}return S||this.transceivers.push(E),E},b.prototype.addTrack=function(g,S){if(this._isClosed)throw p("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var R;if(this.transceivers.find(function(I){return I.track===g}))throw p("InvalidAccessError","Track already exists.");for(var E=0;E<this.transceivers.length;E++)this.transceivers[E].track||this.transceivers[E].kind!==g.kind||(R=this.transceivers[E]);return R||(R=this._createTransceiver(g.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(S)===-1&&this.localStreams.push(S),R.track=g,R.stream=S,R.rtpSender=new _.RTCRtpSender(g,R.dtlsTransport),R.rtpSender},b.prototype.addStream=function(g){var S=this;if(m>=15025)g.getTracks().forEach(function(E){S.addTrack(E,g)});else{var R=g.clone();g.getTracks().forEach(function(E,I){var C=R.getTracks()[I];E.addEventListener("enabled",function(A){C.enabled=A.enabled})}),R.getTracks().forEach(function(E){S.addTrack(E,R)})}},b.prototype.removeTrack=function(g){if(this._isClosed)throw p("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(g instanceof _.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var S=this.transceivers.find(function(E){return E.rtpSender===g});if(!S)throw p("InvalidAccessError","Sender was not created by this connection.");var R=S.stream;S.rtpSender.stop(),S.rtpSender=null,S.track=null,S.stream=null,this.transceivers.map(function(E){return E.stream}).indexOf(R)===-1&&this.localStreams.indexOf(R)>-1&&this.localStreams.splice(this.localStreams.indexOf(R),1),this._maybeFireNegotiationNeeded()},b.prototype.removeStream=function(g){var S=this;g.getTracks().forEach(function(R){var E=S.getSenders().find(function(I){return I.track===R});E&&S.removeTrack(E)})},b.prototype.getSenders=function(){return this.transceivers.filter(function(g){return!!g.rtpSender}).map(function(g){return g.rtpSender})},b.prototype.getReceivers=function(){return this.transceivers.filter(function(g){return!!g.rtpReceiver}).map(function(g){return g.rtpReceiver})},b.prototype._createIceGatherer=function(g,S){var R=this;if(S&&g>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var E=new _.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(E,"state",{value:"new",writable:!0}),this.transceivers[g].bufferedCandidateEvents=[],this.transceivers[g].bufferCandidates=function(I){var C=!I.candidate||Object.keys(I.candidate).length===0;E.state=C?"completed":"gathering",R.transceivers[g].bufferedCandidateEvents!==null&&R.transceivers[g].bufferedCandidateEvents.push(I)},E.addEventListener("localcandidate",this.transceivers[g].bufferCandidates),E},b.prototype._gather=function(g,S){var R=this,E=this.transceivers[S].iceGatherer;if(!E.onlocalcandidate){var I=this.transceivers[S].bufferedCandidateEvents;this.transceivers[S].bufferedCandidateEvents=null,E.removeEventListener("localcandidate",this.transceivers[S].bufferCandidates),E.onlocalcandidate=function(C){if(!(R.usingBundle&&S>0)){var A=new Event("icecandidate");A.candidate={sdpMid:g,sdpMLineIndex:S};var w=C.candidate,N=!w||Object.keys(w).length===0;if(N)E.state!=="new"&&E.state!=="gathering"||(E.state="completed");else{E.state==="new"&&(E.state="gathering"),w.component=1,w.ufrag=E.getLocalParameters().usernameFragment;var M=c.writeCandidate(w);A.candidate=Object.assign(A.candidate,c.parseCandidate(M)),A.candidate.candidate=M,A.candidate.toJSON=function(){return{candidate:A.candidate.candidate,sdpMid:A.candidate.sdpMid,sdpMLineIndex:A.candidate.sdpMLineIndex,usernameFragment:A.candidate.usernameFragment}}}var D=c.getMediaSections(R._localDescription.sdp);D[A.candidate.sdpMLineIndex]+=N?`a=end-of-candidates\r
`:"a="+A.candidate.candidate+`\r
`,R._localDescription.sdp=c.getDescription(R._localDescription.sdp)+D.join("");var L=R.transceivers.every(function(P){return P.iceGatherer&&P.iceGatherer.state==="completed"});R.iceGatheringState!=="gathering"&&(R.iceGatheringState="gathering",R._emitGatheringStateChange()),N||R._dispatchEvent("icecandidate",A),L&&(R._dispatchEvent("icecandidate",new Event("icecandidate")),R.iceGatheringState="complete",R._emitGatheringStateChange())}},_.setTimeout(function(){I.forEach(function(C){E.onlocalcandidate(C)})},0)}},b.prototype._createIceAndDtlsTransports=function(){var g=this,S=new _.RTCIceTransport(null);S.onicestatechange=function(){g._updateIceConnectionState(),g._updateConnectionState()};var R=new _.RTCDtlsTransport(S);return R.ondtlsstatechange=function(){g._updateConnectionState()},R.onerror=function(){Object.defineProperty(R,"state",{value:"failed",writable:!0}),g._updateConnectionState()},{iceTransport:S,dtlsTransport:R}},b.prototype._disposeIceAndDtlsTransports=function(g){var S=this.transceivers[g].iceGatherer;S&&(delete S.onlocalcandidate,delete this.transceivers[g].iceGatherer);var R=this.transceivers[g].iceTransport;R&&(delete R.onicestatechange,delete this.transceivers[g].iceTransport);var E=this.transceivers[g].dtlsTransport;E&&(delete E.ondtlsstatechange,delete E.onerror,delete this.transceivers[g].dtlsTransport)},b.prototype._transceive=function(g,S,R){var E=l(g.localCapabilities,g.remoteCapabilities);S&&g.rtpSender&&(E.encodings=g.sendEncodingParameters,E.rtcp={cname:c.localCName,compound:g.rtcpParameters.compound},g.recvEncodingParameters.length&&(E.rtcp.ssrc=g.recvEncodingParameters[0].ssrc),g.rtpSender.send(E)),R&&g.rtpReceiver&&E.codecs.length>0&&(g.kind==="video"&&g.recvEncodingParameters&&m<15019&&g.recvEncodingParameters.forEach(function(I){delete I.rtx}),g.recvEncodingParameters.length?E.encodings=g.recvEncodingParameters:E.encodings=[{}],E.rtcp={compound:g.rtcpParameters.compound},g.rtcpParameters.cname&&(E.rtcp.cname=g.rtcpParameters.cname),g.sendEncodingParameters.length&&(E.rtcp.ssrc=g.sendEncodingParameters[0].ssrc),g.rtpReceiver.receive(E))},b.prototype.setLocalDescription=function(g){var S,R,E=this;if(["offer","answer"].indexOf(g.type)===-1)return Promise.reject(p("TypeError",'Unsupported type "'+g.type+'"'));if(!f("setLocalDescription",g.type,E.signalingState)||E._isClosed)return Promise.reject(p("InvalidStateError","Can not set local "+g.type+" in state "+E.signalingState));if(g.type==="offer")S=c.splitSections(g.sdp),R=S.shift(),S.forEach(function(C,A){var w=c.parseRtpParameters(C);E.transceivers[A].localCapabilities=w}),E.transceivers.forEach(function(C,A){E._gather(C.mid,A)});else if(g.type==="answer"){S=c.splitSections(E._remoteDescription.sdp),R=S.shift();var I=c.matchPrefix(R,"a=ice-lite").length>0;S.forEach(function(C,A){var w=E.transceivers[A],N=w.iceGatherer,M=w.iceTransport,D=w.dtlsTransport,L=w.localCapabilities,P=w.remoteCapabilities;if(!(c.isRejected(C)&&c.matchPrefix(C,"a=bundle-only").length===0)&&!w.rejected){var x=c.getIceParameters(C,R),T=c.getDtlsParameters(C,R);I&&(T.role="server"),E.usingBundle&&A!==0||(E._gather(w.mid,A),M.state==="new"&&M.start(N,x,I?"controlling":"controlled"),D.state==="new"&&D.start(T));var O=l(L,P);E._transceive(w,O.codecs.length>0,!1)}})}return E._localDescription={type:g.type,sdp:g.sdp},g.type==="offer"?E._updateSignalingState("have-local-offer"):E._updateSignalingState("stable"),Promise.resolve()},b.prototype.setRemoteDescription=function(g){var S=this;if(["offer","answer"].indexOf(g.type)===-1)return Promise.reject(p("TypeError",'Unsupported type "'+g.type+'"'));if(!f("setRemoteDescription",g.type,S.signalingState)||S._isClosed)return Promise.reject(p("InvalidStateError","Can not set remote "+g.type+" in state "+S.signalingState));var R={};S.remoteStreams.forEach(function(M){R[M.id]=M});var E=[],I=c.splitSections(g.sdp),C=I.shift(),A=c.matchPrefix(C,"a=ice-lite").length>0,w=c.matchPrefix(C,"a=group:BUNDLE ").length>0;S.usingBundle=w;var N=c.matchPrefix(C,"a=ice-options:")[0];return S.canTrickleIceCandidates=!!N&&N.substr(14).split(" ").indexOf("trickle")>=0,I.forEach(function(M,D){var L=c.splitLines(M),P=c.getKind(M),x=c.isRejected(M)&&c.matchPrefix(M,"a=bundle-only").length===0,T=L[0].substr(2).split(" ")[2],O=c.getDirection(M,C),k=c.parseMsid(M),H=c.getMid(M)||c.generateIdentifier();if(x||P==="application"&&(T==="DTLS/SCTP"||T==="UDP/DTLS/SCTP"))S.transceivers[D]={mid:H,kind:P,protocol:T,rejected:!0};else{var U,ee,W,$,B,F,G,q,X;!x&&S.transceivers[D]&&S.transceivers[D].rejected&&(S.transceivers[D]=S._createTransceiver(P,!0));var J,se,ce=c.parseRtpParameters(M);x||(J=c.getIceParameters(M,C),(se=c.getDtlsParameters(M,C)).role="client"),G=c.parseRtpEncodingParameters(M);var Y=c.parseRtcpParameters(M),fe=c.matchPrefix(M,"a=end-of-candidates",C).length>0,he=c.matchPrefix(M,"a=candidate:").map(function(Te){return c.parseCandidate(Te)}).filter(function(Te){return Te.component===1});if((g.type==="offer"||g.type==="answer")&&!x&&w&&D>0&&S.transceivers[D]&&(S._disposeIceAndDtlsTransports(D),S.transceivers[D].iceGatherer=S.transceivers[0].iceGatherer,S.transceivers[D].iceTransport=S.transceivers[0].iceTransport,S.transceivers[D].dtlsTransport=S.transceivers[0].dtlsTransport,S.transceivers[D].rtpSender&&S.transceivers[D].rtpSender.setTransport(S.transceivers[0].dtlsTransport),S.transceivers[D].rtpReceiver&&S.transceivers[D].rtpReceiver.setTransport(S.transceivers[0].dtlsTransport)),g.type!=="offer"||x)g.type==="answer"&&!x&&(ee=(U=S.transceivers[D]).iceGatherer,W=U.iceTransport,$=U.dtlsTransport,B=U.rtpReceiver,F=U.sendEncodingParameters,q=U.localCapabilities,S.transceivers[D].recvEncodingParameters=G,S.transceivers[D].remoteCapabilities=ce,S.transceivers[D].rtcpParameters=Y,he.length&&W.state==="new"&&(!A&&!fe||w&&D!==0?he.forEach(function(Te){v(U.iceTransport,Te)}):W.setRemoteCandidates(he)),w&&D!==0||(W.state==="new"&&W.start(ee,J,"controlling"),$.state==="new"&&$.start(se)),!l(U.localCapabilities,U.remoteCapabilities).codecs.filter(function(Te){return Te.name.toLowerCase()==="rtx"}).length&&U.sendEncodingParameters[0].rtx&&delete U.sendEncodingParameters[0].rtx,S._transceive(U,O==="sendrecv"||O==="recvonly",O==="sendrecv"||O==="sendonly"),!B||O!=="sendrecv"&&O!=="sendonly"?delete U.rtpReceiver:(X=B.track,k?(R[k.stream]||(R[k.stream]=new _.MediaStream),d(X,R[k.stream]),E.push([X,B,R[k.stream]])):(R.default||(R.default=new _.MediaStream),d(X,R.default),E.push([X,B,R.default]))));else{(U=S.transceivers[D]||S._createTransceiver(P)).mid=H,U.iceGatherer||(U.iceGatherer=S._createIceGatherer(D,w)),he.length&&U.iceTransport.state==="new"&&(!fe||w&&D!==0?he.forEach(function(Te){v(U.iceTransport,Te)}):U.iceTransport.setRemoteCandidates(he)),q=_.RTCRtpReceiver.getCapabilities(P),m<15019&&(q.codecs=q.codecs.filter(function(Te){return Te.name!=="rtx"})),F=U.sendEncodingParameters||[{ssrc:1001*(2*D+2)}];var pe,ue=!1;O==="sendrecv"||O==="sendonly"?(ue=!U.rtpReceiver,B=U.rtpReceiver||new _.RTCRtpReceiver(U.dtlsTransport,P),ue&&(X=B.track,k&&k.stream==="-"||(k?(R[k.stream]||(R[k.stream]=new _.MediaStream,Object.defineProperty(R[k.stream],"id",{get:function(){return k.stream}})),Object.defineProperty(X,"id",{get:function(){return k.track}}),pe=R[k.stream]):(R.default||(R.default=new _.MediaStream),pe=R.default)),pe&&(d(X,pe),U.associatedRemoteMediaStreams.push(pe)),E.push([X,B,pe]))):U.rtpReceiver&&U.rtpReceiver.track&&(U.associatedRemoteMediaStreams.forEach(function(Te){var be=Te.getTracks().find(function(Z){return Z.id===U.rtpReceiver.track.id});be&&function(Z,K){K.removeTrack(Z),K.dispatchEvent(new _.MediaStreamTrackEvent("removetrack",{track:Z}))}(be,Te)}),U.associatedRemoteMediaStreams=[]),U.localCapabilities=q,U.remoteCapabilities=ce,U.rtpReceiver=B,U.rtcpParameters=Y,U.sendEncodingParameters=F,U.recvEncodingParameters=G,S._transceive(S.transceivers[D],!1,ue)}}}),S._dtlsRole===void 0&&(S._dtlsRole=g.type==="offer"?"active":"passive"),S._remoteDescription={type:g.type,sdp:g.sdp},g.type==="offer"?S._updateSignalingState("have-remote-offer"):S._updateSignalingState("stable"),Object.keys(R).forEach(function(M){var D=R[M];if(D.getTracks().length){if(S.remoteStreams.indexOf(D)===-1){S.remoteStreams.push(D);var L=new Event("addstream");L.stream=D,_.setTimeout(function(){S._dispatchEvent("addstream",L)})}E.forEach(function(P){var x=P[0],T=P[1];D.id===P[2].id&&u(S,x,T,[D])})}}),E.forEach(function(M){M[2]||u(S,M[0],M[1],[])}),_.setTimeout(function(){S&&S.transceivers&&S.transceivers.forEach(function(M){M.iceTransport&&M.iceTransport.state==="new"&&M.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),M.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},b.prototype.close=function(){this.transceivers.forEach(function(g){g.iceTransport&&g.iceTransport.stop(),g.dtlsTransport&&g.dtlsTransport.stop(),g.rtpSender&&g.rtpSender.stop(),g.rtpReceiver&&g.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},b.prototype._updateSignalingState=function(g){this.signalingState=g;var S=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",S)},b.prototype._maybeFireNegotiationNeeded=function(){var g=this;this.signalingState==="stable"&&this.needNegotiation!==!0&&(this.needNegotiation=!0,_.setTimeout(function(){if(g.needNegotiation){g.needNegotiation=!1;var S=new Event("negotiationneeded");g._dispatchEvent("negotiationneeded",S)}},0))},b.prototype._updateIceConnectionState=function(){var g,S={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(E){E.iceTransport&&!E.rejected&&S[E.iceTransport.state]++}),g="new",S.failed>0?g="failed":S.checking>0?g="checking":S.disconnected>0?g="disconnected":S.new>0?g="new":S.connected>0?g="connected":S.completed>0&&(g="completed"),g!==this.iceConnectionState){this.iceConnectionState=g;var R=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",R)}},b.prototype._updateConnectionState=function(){var g,S={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(E){E.iceTransport&&E.dtlsTransport&&!E.rejected&&(S[E.iceTransport.state]++,S[E.dtlsTransport.state]++)}),S.connected+=S.completed,g="new",S.failed>0?g="failed":S.connecting>0?g="connecting":S.disconnected>0?g="disconnected":S.new>0?g="new":S.connected>0&&(g="connected"),g!==this.connectionState){this.connectionState=g;var R=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",R)}},b.prototype.createOffer=function(){var g=this;if(g._isClosed)return Promise.reject(p("InvalidStateError","Can not call createOffer after close"));var S=g.transceivers.filter(function(A){return A.kind==="audio"}).length,R=g.transceivers.filter(function(A){return A.kind==="video"}).length,E=arguments[0];if(E){if(E.mandatory||E.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");E.offerToReceiveAudio!==void 0&&(S=E.offerToReceiveAudio===!0?1:E.offerToReceiveAudio===!1?0:E.offerToReceiveAudio),E.offerToReceiveVideo!==void 0&&(R=E.offerToReceiveVideo===!0?1:E.offerToReceiveVideo===!1?0:E.offerToReceiveVideo)}for(g.transceivers.forEach(function(A){A.kind==="audio"?--S<0&&(A.wantReceive=!1):A.kind==="video"&&--R<0&&(A.wantReceive=!1)});S>0||R>0;)S>0&&(g._createTransceiver("audio"),S--),R>0&&(g._createTransceiver("video"),R--);var I=c.writeSessionBoilerplate(g._sdpSessionId,g._sdpSessionVersion++);g.transceivers.forEach(function(A,w){var N=A.track,M=A.kind,D=A.mid||c.generateIdentifier();A.mid=D,A.iceGatherer||(A.iceGatherer=g._createIceGatherer(w,g.usingBundle));var L=_.RTCRtpSender.getCapabilities(M);m<15019&&(L.codecs=L.codecs.filter(function(x){return x.name!=="rtx"})),L.codecs.forEach(function(x){x.name==="H264"&&x.parameters["level-asymmetry-allowed"]===void 0&&(x.parameters["level-asymmetry-allowed"]="1"),A.remoteCapabilities&&A.remoteCapabilities.codecs&&A.remoteCapabilities.codecs.forEach(function(T){x.name.toLowerCase()===T.name.toLowerCase()&&x.clockRate===T.clockRate&&(x.preferredPayloadType=T.payloadType)})}),L.headerExtensions.forEach(function(x){(A.remoteCapabilities&&A.remoteCapabilities.headerExtensions||[]).forEach(function(T){x.uri===T.uri&&(x.id=T.id)})});var P=A.sendEncodingParameters||[{ssrc:1001*(2*w+1)}];N&&m>=15019&&M==="video"&&!P[0].rtx&&(P[0].rtx={ssrc:P[0].ssrc+1}),A.wantReceive&&(A.rtpReceiver=new _.RTCRtpReceiver(A.dtlsTransport,M)),A.localCapabilities=L,A.sendEncodingParameters=P}),g._config.bundlePolicy!=="max-compat"&&(I+="a=group:BUNDLE "+g.transceivers.map(function(A){return A.mid}).join(" ")+`\r
`),I+=`a=ice-options:trickle\r
`,g.transceivers.forEach(function(A,w){I+=h(A,A.localCapabilities,"offer",A.stream,g._dtlsRole),I+=`a=rtcp-rsize\r
`,!A.iceGatherer||g.iceGatheringState==="new"||w!==0&&g.usingBundle||(A.iceGatherer.getLocalCandidates().forEach(function(N){N.component=1,I+="a="+c.writeCandidate(N)+`\r
`}),A.iceGatherer.state==="completed"&&(I+=`a=end-of-candidates\r
`))});var C=new _.RTCSessionDescription({type:"offer",sdp:I});return Promise.resolve(C)},b.prototype.createAnswer=function(){var g=this;if(g._isClosed)return Promise.reject(p("InvalidStateError","Can not call createAnswer after close"));if(g.signalingState!=="have-remote-offer"&&g.signalingState!=="have-local-pranswer")return Promise.reject(p("InvalidStateError","Can not call createAnswer in signalingState "+g.signalingState));var S=c.writeSessionBoilerplate(g._sdpSessionId,g._sdpSessionVersion++);g.usingBundle&&(S+="a=group:BUNDLE "+g.transceivers.map(function(I){return I.mid}).join(" ")+`\r
`),S+=`a=ice-options:trickle\r
`;var R=c.getMediaSections(g._remoteDescription.sdp).length;g.transceivers.forEach(function(I,C){if(!(C+1>R)){if(I.rejected)return I.kind==="application"?I.protocol==="DTLS/SCTP"?S+=`m=application 0 DTLS/SCTP 5000\r
`:S+="m=application 0 "+I.protocol+` webrtc-datachannel\r
`:I.kind==="audio"?S+=`m=audio 0 UDP/TLS/RTP/SAVPF 0\r
a=rtpmap:0 PCMU/8000\r
`:I.kind==="video"&&(S+=`m=video 0 UDP/TLS/RTP/SAVPF 120\r
a=rtpmap:120 VP8/90000\r
`),void(S+=`c=IN IP4 0.0.0.0\r
a=inactive\r
a=mid:`+I.mid+`\r
`);var A;I.stream&&(I.kind==="audio"?A=I.stream.getAudioTracks()[0]:I.kind==="video"&&(A=I.stream.getVideoTracks()[0]),A&&m>=15019&&I.kind==="video"&&!I.sendEncodingParameters[0].rtx&&(I.sendEncodingParameters[0].rtx={ssrc:I.sendEncodingParameters[0].ssrc+1}));var w=l(I.localCapabilities,I.remoteCapabilities);!w.codecs.filter(function(N){return N.name.toLowerCase()==="rtx"}).length&&I.sendEncodingParameters[0].rtx&&delete I.sendEncodingParameters[0].rtx,S+=h(I,w,"answer",I.stream,g._dtlsRole),I.rtcpParameters&&I.rtcpParameters.reducedSize&&(S+=`a=rtcp-rsize\r
`)}});var E=new _.RTCSessionDescription({type:"answer",sdp:S});return Promise.resolve(E)},b.prototype.addIceCandidate=function(g){var S,R=this;return g&&g.sdpMLineIndex===void 0&&!g.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(E,I){if(!R._remoteDescription)return I(p("InvalidStateError","Can not add ICE candidate without a remote description"));if(g&&g.candidate!==""){var C=g.sdpMLineIndex;if(g.sdpMid){for(var A=0;A<R.transceivers.length;A++)if(R.transceivers[A].mid===g.sdpMid){C=A;break}}var w=R.transceivers[C];if(!w)return I(p("OperationError","Can not add ICE candidate"));if(w.rejected)return E();var N=Object.keys(g.candidate).length>0?c.parseCandidate(g.candidate):{};if(N.protocol==="tcp"&&(N.port===0||N.port===9)||N.component&&N.component!==1)return E();if((C===0||C>0&&w.iceTransport!==R.transceivers[0].iceTransport)&&!v(w.iceTransport,N))return I(p("OperationError","Can not add ICE candidate"));var M=g.candidate.trim();M.indexOf("a=")===0&&(M=M.substr(2)),(S=c.getMediaSections(R._remoteDescription.sdp))[C]+="a="+(N.type?M:"end-of-candidates")+`\r
`,R._remoteDescription.sdp=c.getDescription(R._remoteDescription.sdp)+S.join("")}else for(var D=0;D<R.transceivers.length&&(R.transceivers[D].rejected||(R.transceivers[D].iceTransport.addRemoteCandidate({}),(S=c.getMediaSections(R._remoteDescription.sdp))[D]+=`a=end-of-candidates\r
`,R._remoteDescription.sdp=c.getDescription(R._remoteDescription.sdp)+S.join(""),!R.usingBundle));D++);E()})},b.prototype.getStats=function(g){if(g&&g instanceof _.MediaStreamTrack){var S=null;if(this.transceivers.forEach(function(E){E.rtpSender&&E.rtpSender.track===g?S=E.rtpSender:E.rtpReceiver&&E.rtpReceiver.track===g&&(S=E.rtpReceiver)}),!S)throw p("InvalidAccessError","Invalid selector.");return S.getStats()}var R=[];return this.transceivers.forEach(function(E){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(I){E[I]&&R.push(E[I].getStats())})}),Promise.all(R).then(function(E){var I=new Map;return E.forEach(function(C){C.forEach(function(A){I.set(A.id,A)})}),I})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(g){var S=_[g];if(S&&S.prototype&&S.prototype.getStats){var R=S.prototype.getStats;S.prototype.getStats=function(){return R.apply(this).then(function(E){var I=new Map;return Object.keys(E).forEach(function(C){var A;E[C].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(A=E[C]).type]||A.type,I.set(C,E[C])}),I})}}});var y=["createOffer","createAnswer"];return y.forEach(function(g){var S=b.prototype[g];b.prototype[g]=function(){var R=arguments;return typeof R[0]=="function"||typeof R[1]=="function"?S.apply(this,[arguments[2]]).then(function(E){typeof R[0]=="function"&&R[0].apply(null,[E])},function(E){typeof R[1]=="function"&&R[1].apply(null,[E])}):S.apply(this,arguments)}}),(y=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(g){var S=b.prototype[g];b.prototype[g]=function(){var R=arguments;return typeof R[1]=="function"||typeof R[2]=="function"?S.apply(this,arguments).then(function(){typeof R[1]=="function"&&R[1].apply(null)},function(E){typeof R[2]=="function"&&R[2].apply(null,[E])}):S.apply(this,arguments)}}),["getStats"].forEach(function(g){var S=b.prototype[g];b.prototype[g]=function(){var R=arguments;return typeof R[1]=="function"?S.apply(this,arguments).then(function(){typeof R[1]=="function"&&R[1].apply(null)}):S.apply(this,arguments)}}),b}},1401:a=>{var s=Object.prototype.hasOwnProperty;function o(h){return"[Throws: "+(h?h.message:"?")+"]"}function c(h){var l=[];return function f(v){if(v===null||typeof v!="object")return v;if(l.indexOf(v)!==-1)return"[Circular]";if(l.push(v),typeof v.toJSON=="function")try{var p=f(v.toJSON());return l.pop(),p}catch(d){return o(d)}if(Array.isArray(v)){var _=v.map(f);return l.pop(),_}var m=Object.keys(v).reduce(function(d,u){return d[u]=f(function(b,y){if(s.call(b,y))try{return b[y]}catch(g){return o(g)}return b[y]}(v,u)),d},{});return l.pop(),m}(h)}a.exports=function(h,l,f){return JSON.stringify(c(h),l,f)},a.exports.ensureProperties=c},7963:a=>{var s={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};s.localCName=s.generateIdentifier(),s.splitLines=function(o){return o.trim().split(`
`).map(function(c){return c.trim()})},s.splitSections=function(o){return o.split(`
m=`).map(function(c,h){return(h>0?"m="+c:c).trim()+`\r
`})},s.getDescription=function(o){var c=s.splitSections(o);return c&&c[0]},s.getMediaSections=function(o){var c=s.splitSections(o);return c.shift(),c},s.matchPrefix=function(o,c){return s.splitLines(o).filter(function(h){return h.indexOf(c)===0})},s.parseCandidate=function(o){for(var c,h={foundation:(c=o.indexOf("a=candidate:")===0?o.substring(12).split(" "):o.substring(10).split(" "))[0],component:parseInt(c[1],10),protocol:c[2].toLowerCase(),priority:parseInt(c[3],10),ip:c[4],address:c[4],port:parseInt(c[5],10),type:c[7]},l=8;l<c.length;l+=2)switch(c[l]){case"raddr":h.relatedAddress=c[l+1];break;case"rport":h.relatedPort=parseInt(c[l+1],10);break;case"tcptype":h.tcpType=c[l+1];break;case"ufrag":h.ufrag=c[l+1],h.usernameFragment=c[l+1];break;default:h[c[l]]=c[l+1]}return h},s.writeCandidate=function(o){var c=[];c.push(o.foundation),c.push(o.component),c.push(o.protocol.toUpperCase()),c.push(o.priority),c.push(o.address||o.ip),c.push(o.port);var h=o.type;return c.push("typ"),c.push(h),h!=="host"&&o.relatedAddress&&o.relatedPort&&(c.push("raddr"),c.push(o.relatedAddress),c.push("rport"),c.push(o.relatedPort)),o.tcpType&&o.protocol.toLowerCase()==="tcp"&&(c.push("tcptype"),c.push(o.tcpType)),(o.usernameFragment||o.ufrag)&&(c.push("ufrag"),c.push(o.usernameFragment||o.ufrag)),"candidate:"+c.join(" ")},s.parseIceOptions=function(o){return o.substr(14).split(" ")},s.parseRtpMap=function(o){var c=o.substr(9).split(" "),h={payloadType:parseInt(c.shift(),10)};return c=c[0].split("/"),h.name=c[0],h.clockRate=parseInt(c[1],10),h.channels=c.length===3?parseInt(c[2],10):1,h.numChannels=h.channels,h},s.writeRtpMap=function(o){var c=o.payloadType;o.preferredPayloadType!==void 0&&(c=o.preferredPayloadType);var h=o.channels||o.numChannels||1;return"a=rtpmap:"+c+" "+o.name+"/"+o.clockRate+(h!==1?"/"+h:"")+`\r
`},s.parseExtmap=function(o){var c=o.substr(9).split(" ");return{id:parseInt(c[0],10),direction:c[0].indexOf("/")>0?c[0].split("/")[1]:"sendrecv",uri:c[1]}},s.writeExtmap=function(o){return"a=extmap:"+(o.id||o.preferredId)+(o.direction&&o.direction!=="sendrecv"?"/"+o.direction:"")+" "+o.uri+`\r
`},s.parseFmtp=function(o){for(var c,h={},l=o.substr(o.indexOf(" ")+1).split(";"),f=0;f<l.length;f++)h[(c=l[f].trim().split("="))[0].trim()]=c[1];return h},s.writeFmtp=function(o){var c="",h=o.payloadType;if(o.preferredPayloadType!==void 0&&(h=o.preferredPayloadType),o.parameters&&Object.keys(o.parameters).length){var l=[];Object.keys(o.parameters).forEach(function(f){o.parameters[f]?l.push(f+"="+o.parameters[f]):l.push(f)}),c+="a=fmtp:"+h+" "+l.join(";")+`\r
`}return c},s.parseRtcpFb=function(o){var c=o.substr(o.indexOf(" ")+1).split(" ");return{type:c.shift(),parameter:c.join(" ")}},s.writeRtcpFb=function(o){var c="",h=o.payloadType;return o.preferredPayloadType!==void 0&&(h=o.preferredPayloadType),o.rtcpFeedback&&o.rtcpFeedback.length&&o.rtcpFeedback.forEach(function(l){c+="a=rtcp-fb:"+h+" "+l.type+(l.parameter&&l.parameter.length?" "+l.parameter:"")+`\r
`}),c},s.parseSsrcMedia=function(o){var c=o.indexOf(" "),h={ssrc:parseInt(o.substr(7,c-7),10)},l=o.indexOf(":",c);return l>-1?(h.attribute=o.substr(c+1,l-c-1),h.value=o.substr(l+1)):h.attribute=o.substr(c+1),h},s.parseSsrcGroup=function(o){var c=o.substr(13).split(" ");return{semantics:c.shift(),ssrcs:c.map(function(h){return parseInt(h,10)})}},s.getMid=function(o){var c=s.matchPrefix(o,"a=mid:")[0];if(c)return c.substr(6)},s.parseFingerprint=function(o){var c=o.substr(14).split(" ");return{algorithm:c[0].toLowerCase(),value:c[1]}},s.getDtlsParameters=function(o,c){return{role:"auto",fingerprints:s.matchPrefix(o+c,"a=fingerprint:").map(s.parseFingerprint)}},s.writeDtlsParameters=function(o,c){var h="a=setup:"+c+`\r
`;return o.fingerprints.forEach(function(l){h+="a=fingerprint:"+l.algorithm+" "+l.value+`\r
`}),h},s.parseCryptoLine=function(o){var c=o.substr(9).split(" ");return{tag:parseInt(c[0],10),cryptoSuite:c[1],keyParams:c[2],sessionParams:c.slice(3)}},s.writeCryptoLine=function(o){return"a=crypto:"+o.tag+" "+o.cryptoSuite+" "+(typeof o.keyParams=="object"?s.writeCryptoKeyParams(o.keyParams):o.keyParams)+(o.sessionParams?" "+o.sessionParams.join(" "):"")+`\r
`},s.parseCryptoKeyParams=function(o){if(o.indexOf("inline:")!==0)return null;var c=o.substr(7).split("|");return{keyMethod:"inline",keySalt:c[0],lifeTime:c[1],mkiValue:c[2]?c[2].split(":")[0]:void 0,mkiLength:c[2]?c[2].split(":")[1]:void 0}},s.writeCryptoKeyParams=function(o){return o.keyMethod+":"+o.keySalt+(o.lifeTime?"|"+o.lifeTime:"")+(o.mkiValue&&o.mkiLength?"|"+o.mkiValue+":"+o.mkiLength:"")},s.getCryptoParameters=function(o,c){return s.matchPrefix(o+c,"a=crypto:").map(s.parseCryptoLine)},s.getIceParameters=function(o,c){var h=s.matchPrefix(o+c,"a=ice-ufrag:")[0],l=s.matchPrefix(o+c,"a=ice-pwd:")[0];return h&&l?{usernameFragment:h.substr(12),password:l.substr(10)}:null},s.writeIceParameters=function(o){return"a=ice-ufrag:"+o.usernameFragment+`\r
a=ice-pwd:`+o.password+`\r
`},s.parseRtpParameters=function(o){for(var c={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},h=s.splitLines(o)[0].split(" "),l=3;l<h.length;l++){var f=h[l],v=s.matchPrefix(o,"a=rtpmap:"+f+" ")[0];if(v){var p=s.parseRtpMap(v),_=s.matchPrefix(o,"a=fmtp:"+f+" ");switch(p.parameters=_.length?s.parseFmtp(_[0]):{},p.rtcpFeedback=s.matchPrefix(o,"a=rtcp-fb:"+f+" ").map(s.parseRtcpFb),c.codecs.push(p),p.name.toUpperCase()){case"RED":case"ULPFEC":c.fecMechanisms.push(p.name.toUpperCase())}}}return s.matchPrefix(o,"a=extmap:").forEach(function(m){c.headerExtensions.push(s.parseExtmap(m))}),c},s.writeRtpDescription=function(o,c){var h="";h+="m="+o+" ",h+=c.codecs.length>0?"9":"0",h+=" UDP/TLS/RTP/SAVPF ",h+=c.codecs.map(function(f){return f.preferredPayloadType!==void 0?f.preferredPayloadType:f.payloadType}).join(" ")+`\r
`,h+=`c=IN IP4 0.0.0.0\r
`,h+=`a=rtcp:9 IN IP4 0.0.0.0\r
`,c.codecs.forEach(function(f){h+=s.writeRtpMap(f),h+=s.writeFmtp(f),h+=s.writeRtcpFb(f)});var l=0;return c.codecs.forEach(function(f){f.maxptime>l&&(l=f.maxptime)}),l>0&&(h+="a=maxptime:"+l+`\r
`),h+=`a=rtcp-mux\r
`,c.headerExtensions&&c.headerExtensions.forEach(function(f){h+=s.writeExtmap(f)}),h},s.parseRtpEncodingParameters=function(o){var c,h=[],l=s.parseRtpParameters(o),f=l.fecMechanisms.indexOf("RED")!==-1,v=l.fecMechanisms.indexOf("ULPFEC")!==-1,p=s.matchPrefix(o,"a=ssrc:").map(function(u){return s.parseSsrcMedia(u)}).filter(function(u){return u.attribute==="cname"}),_=p.length>0&&p[0].ssrc,m=s.matchPrefix(o,"a=ssrc-group:FID").map(function(u){return u.substr(17).split(" ").map(function(b){return parseInt(b,10)})});m.length>0&&m[0].length>1&&m[0][0]===_&&(c=m[0][1]),l.codecs.forEach(function(u){if(u.name.toUpperCase()==="RTX"&&u.parameters.apt){var b={ssrc:_,codecPayloadType:parseInt(u.parameters.apt,10)};_&&c&&(b.rtx={ssrc:c}),h.push(b),f&&((b=JSON.parse(JSON.stringify(b))).fec={ssrc:_,mechanism:v?"red+ulpfec":"red"},h.push(b))}}),h.length===0&&_&&h.push({ssrc:_});var d=s.matchPrefix(o,"b=");return d.length&&(d=d[0].indexOf("b=TIAS:")===0?parseInt(d[0].substr(7),10):d[0].indexOf("b=AS:")===0?1e3*parseInt(d[0].substr(5),10)*.95-16e3:void 0,h.forEach(function(u){u.maxBitrate=d})),h},s.parseRtcpParameters=function(o){var c={},h=s.matchPrefix(o,"a=ssrc:").map(function(v){return s.parseSsrcMedia(v)}).filter(function(v){return v.attribute==="cname"})[0];h&&(c.cname=h.value,c.ssrc=h.ssrc);var l=s.matchPrefix(o,"a=rtcp-rsize");c.reducedSize=l.length>0,c.compound=l.length===0;var f=s.matchPrefix(o,"a=rtcp-mux");return c.mux=f.length>0,c},s.parseMsid=function(o){var c,h=s.matchPrefix(o,"a=msid:");if(h.length===1)return{stream:(c=h[0].substr(7).split(" "))[0],track:c[1]};var l=s.matchPrefix(o,"a=ssrc:").map(function(f){return s.parseSsrcMedia(f)}).filter(function(f){return f.attribute==="msid"});return l.length>0?{stream:(c=l[0].value.split(" "))[0],track:c[1]}:void 0},s.parseSctpDescription=function(o){var c,h=s.parseMLine(o),l=s.matchPrefix(o,"a=max-message-size:");l.length>0&&(c=parseInt(l[0].substr(19),10)),isNaN(c)&&(c=65536);var f=s.matchPrefix(o,"a=sctp-port:");if(f.length>0)return{port:parseInt(f[0].substr(12),10),protocol:h.fmt,maxMessageSize:c};if(s.matchPrefix(o,"a=sctpmap:").length>0){var v=s.matchPrefix(o,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(v[0],10),protocol:v[1],maxMessageSize:c}}},s.writeSctpDescription=function(o,c){var h=[];return h=o.protocol!=="DTLS/SCTP"?["m="+o.kind+" 9 "+o.protocol+" "+c.protocol+`\r
`,`c=IN IP4 0.0.0.0\r
`,"a=sctp-port:"+c.port+`\r
`]:["m="+o.kind+" 9 "+o.protocol+" "+c.port+`\r
`,`c=IN IP4 0.0.0.0\r
`,"a=sctpmap:"+c.port+" "+c.protocol+` 65535\r
`],c.maxMessageSize!==void 0&&h.push("a=max-message-size:"+c.maxMessageSize+`\r
`),h.join("")},s.generateSessionId=function(){return Math.random().toString().substr(2,21)},s.writeSessionBoilerplate=function(o,c,h){var l=c!==void 0?c:2;return`v=0\r
o=`+(h||"thisisadapterortc")+" "+(o||s.generateSessionId())+" "+l+` IN IP4 127.0.0.1\r
s=-\r
t=0 0\r
`},s.writeMediaSection=function(o,c,h,l){var f=s.writeRtpDescription(o.kind,c);if(f+=s.writeIceParameters(o.iceGatherer.getLocalParameters()),f+=s.writeDtlsParameters(o.dtlsTransport.getLocalParameters(),h==="offer"?"actpass":"active"),f+="a=mid:"+o.mid+`\r
`,o.direction?f+="a="+o.direction+`\r
`:o.rtpSender&&o.rtpReceiver?f+=`a=sendrecv\r
`:o.rtpSender?f+=`a=sendonly\r
`:o.rtpReceiver?f+=`a=recvonly\r
`:f+=`a=inactive\r
`,o.rtpSender){var v="msid:"+l.id+" "+o.rtpSender.track.id+`\r
`;f+="a="+v,f+="a=ssrc:"+o.sendEncodingParameters[0].ssrc+" "+v,o.sendEncodingParameters[0].rtx&&(f+="a=ssrc:"+o.sendEncodingParameters[0].rtx.ssrc+" "+v,f+="a=ssrc-group:FID "+o.sendEncodingParameters[0].ssrc+" "+o.sendEncodingParameters[0].rtx.ssrc+`\r
`)}return f+="a=ssrc:"+o.sendEncodingParameters[0].ssrc+" cname:"+s.localCName+`\r
`,o.rtpSender&&o.sendEncodingParameters[0].rtx&&(f+="a=ssrc:"+o.sendEncodingParameters[0].rtx.ssrc+" cname:"+s.localCName+`\r
`),f},s.getDirection=function(o,c){for(var h=s.splitLines(o),l=0;l<h.length;l++)switch(h[l]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return h[l].substr(2)}return c?s.getDirection(c):"sendrecv"},s.getKind=function(o){return s.splitLines(o)[0].split(" ")[0].substr(2)},s.isRejected=function(o){return o.split(" ",2)[1]==="0"},s.parseMLine=function(o){var c=s.splitLines(o)[0].substr(2).split(" ");return{kind:c[0],port:parseInt(c[1],10),protocol:c[2],fmt:c.slice(3).join(" ")}},s.parseOLine=function(o){var c=s.matchPrefix(o,"o=")[0].substr(2).split(" ");return{username:c[0],sessionId:c[1],sessionVersion:parseInt(c[2],10),netType:c[3],addressType:c[4],address:c[5]}},s.isValidSDP=function(o){if(typeof o!="string"||o.length===0)return!1;for(var c=s.splitLines(o),h=0;h<c.length;h++)if(c[h].length<2||c[h].charAt(1)!=="=")return!1;return!0},a.exports=s},4845:function(a,s,o){var c=this&&this.__assign||function(){return c=Object.assign||function(S){for(var R,E=1,I=arguments.length;E<I;E++)for(var C in R=arguments[E])Object.prototype.hasOwnProperty.call(R,C)&&(S[C]=R[C]);return S},c.apply(this,arguments)},h=this&&this.__importDefault||function(S){return S&&S.__esModule?S:{default:S}};Object.defineProperty(s,"__esModule",{value:!0}),s.AliRTS=void 0;var l=o(2550),f=o(9428),v=o(3412),p=o(7668),_=o(233),m=h(o(2818)),d=o(5259),u=o(7989),b=o(6420),y=o(1698),g=function(){function S(){}return S.createClient=function(R){var E=R||{};return E.customReporter||(E.customReporter=S.customReporter),E.trackLog===void 0&&(E.trackLog=S.trackLog),y.configProvider.setContext(c(c({},E),{env:S.ENV})),new p.RtsClient(E)},S.getMicList=function(){var R=this;return new Promise(function(E,I){R.deviceManager.getMicList().then(function(C){E(C)}).catch(function(C){I(C)})})},S.getCameraList=function(){var R=this;return new Promise(function(E,I){R.deviceManager.getCameraList().then(function(C){E(C)}).catch(function(C){I(C)})})},S.getSpeakerList=function(){var R=this;return new Promise(function(E,I){R.deviceManager.getSpeakerList().then(function(C){E(C)}).catch(function(C){I(C)})})},S.createStream=function(R){return new Promise(function(E,I){var C=new l.LocalStream,A=new m.default({customReporter:S.customReporter,trackLog:S.trackLog,env:S.ENV});C.init(R).then(function(){E(C),A.reportStreamCreated(R,{videoTrack:!!C.videoTrack,audioTrack:!!C.audioTrack,screenAudio:!!C.screenAudioTrack,surface:C.screenSurfaceType})}).catch(function(w){var N=c(c({},w),{relatedLink:w.extraInfo});delete N.extraInfo,I(N),A.reportErrorInfo(f.ErrorCode.ERROR_INIT_LOCAL_FAIL,w.message,w.traceId,{config:R,originErr:w})})})},S.deviceManager=new v.BrowserDeviceManager,S.BrowserUtil=_.BrowserUtil,S.SystenUtil=_.SystemUtil,S.SupportUtil=u.SupportUtil,S.Clock=b.Clock,S.VideoProfileMap=d.VideoProfileMap,S.ScreenProfileMap=d.ScreenProfileMap,S.AudioProfileMap=d.AudioProfileMap,S.ErrorCode=f.ErrorCode,S.customReporter=function(){},S.trackLog=!0,S}();s.AliRTS=g},7028:(a,s)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.default={version:"2.14.6",protocol_version:2,sdk_version:"0.0.1"}},9428:function(a,s){var o,c,h=this&&this.__spreadArray||function(l,f,v){if(v||arguments.length===2)for(var p,_=0,m=f.length;_<m;_++)!p&&_ in f||(p||(p=Array.prototype.slice.call(f,0,_)),p[_]=f[_]);return l.concat(p||Array.prototype.slice.call(f))};Object.defineProperty(s,"__esModule",{value:!0}),s.PC_RECONNECT_ERROR_LIST=s.PUB_RECONNECT_ERROR_LIST=s.RECONNECT_ERROR_EXCLUDE_LIST=s.SUB_RECONNECT_ERROR_LIST=s.DeviceErrorCode=s.ErrorCode=void 0,function(l){l[l.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",l[l.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",l[l.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10002]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",l[l.ERROR_DEVICE_NOTFOUND=10020]="ERROR_DEVICE_NOTFOUND",l[l.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10003]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",l[l.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10004]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",l[l.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",l[l.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10005]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",l[l.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",l[l.ERROR_DEVICE_NOTREADABLE=10022]="ERROR_DEVICE_NOTREADABLE",l[l.ERROR_DEIVCE_CONSTRAINEDERROR=10007]="ERROR_DEIVCE_CONSTRAINEDERROR",l[l.ERROR_SCREENSHARE_UNKNOWNERRO=10010]="ERROR_SCREENSHARE_UNKNOWNERRO",l[l.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",l[l.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",l[l.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",l[l.ERROR_SCREENSHARE_INVALIDACCESS=10014]="ERROR_SCREENSHARE_INVALIDACCESS",l[l.ERROR_SCREENSHARE_NOTSUPPORT=10018]="ERROR_SCREENSHARE_NOTSUPPORT",l[l.ERROR_DEVICE_NOTSUPPORT=10019]="ERROR_DEVICE_NOTSUPPORT",l[l.ERROR_SIGNAL_ERROR=10101]="ERROR_SIGNAL_ERROR",l[l.ERROR_PLAY_FAILED=10102]="ERROR_PLAY_FAILED",l[l.ERROR_NOTSUPPORT_WEBRTC=10110]="ERROR_NOTSUPPORT_WEBRTC",l[l.ERROR_BROWSER_NOTSUPPORT=10111]="ERROR_BROWSER_NOTSUPPORT",l[l.ERROR_BROWSER_VERSIONLOW=10112]="ERROR_BROWSER_VERSIONLOW",l[l.ERROR_NOTSUPPORT_H264=10113]="ERROR_NOTSUPPORT_H264",l[l.ERROR_CREATEOFFER=10114]="ERROR_CREATEOFFER",l[l.ERROR_NO_DATACHANNEL=10115]="ERROR_NO_DATACHANNEL",l[l.ERROR_INIT_LOCAL_FAIL=10116]="ERROR_INIT_LOCAL_FAIL",l[l.ERROR_HEMLELEMENT_NOTMATCH=10125]="ERROR_HEMLELEMENT_NOTMATCH",l[l.ERROR_AUTOPLAY_ERROR=10201]="ERROR_AUTOPLAY_ERROR",l[l.ERROR_PLAY_URL=10202]="ERROR_PLAY_URL",l[l.ERROR_SUBSCRIBE_NOTHING=10203]="ERROR_SUBSCRIBE_NOTHING",l[l.ERROR_HTMLELEMENT_ERROR=10204]="ERROR_HTMLELEMENT_ERROR",l[l.ERROR_HTTPREQUEST_ERROR=10205]="ERROR_HTTPREQUEST_ERROR",l[l.ERROR_ANSWER_ERROR=10206]="ERROR_ANSWER_ERROR",l[l.ERROR_INBOUND_TIMEOUT=10207]="ERROR_INBOUND_TIMEOUT",l[l.ERROR_STREAM_ENDED=10208]="ERROR_STREAM_ENDED",l[l.ERROR_PC_DISCONNECTED=10209]="ERROR_PC_DISCONNECTED",l[l.ERROR_TRANSPORT_CLOSED=10210]="ERROR_TRANSPORT_CLOSED",l[l.ERROR_SIGNAL_URL=10211]="ERROR_SIGNAL_URL",l[l.ERROR_IP_MIGRATE=10212]="ERROR_IP_MIGRATE",l[l.ERROR_PUBLISH_URL=10300]="ERROR_PUBLISH_URL",l[l.ERROR_PUBLISH_NOAUDIO=10301]="ERROR_PUBLISH_NOAUDIO",l[l.ERROR_PUBLISH_NOSTREAM=10302]="ERROR_PUBLISH_NOSTREAM",l[l.ERROR_DATACHANNEL_PARAM=10500]="ERROR_DATACHANNEL_PARAM",l[l.ERROR_DATACHANNEL_OPEN=10501]="ERROR_DATACHANNEL_OPEN",l[l.ERROR_DATACHANNEL_CLOSE=10502]="ERROR_DATACHANNEL_CLOSE",l[l.ERROR_MEDIASTREAMTRACK_TYPE_ERROR=11e3]="ERROR_MEDIASTREAMTRACK_TYPE_ERROR",l[l.ERROR_MEDIASTREAMTRACK_KIND_ERROR=11001]="ERROR_MEDIASTREAMTRACK_KIND_ERROR",l[l.ERROR_MEDIASTREAMTRACK_AUDIO_NONE=11002]="ERROR_MEDIASTREAMTRACK_AUDIO_NONE",l[l.ERROR_CUSTOMSTREAM_NONE=11003]="ERROR_CUSTOMSTREAM_NONE",l[l.ERROR_CUSTOMSTREAM_INVALID=11004]="ERROR_CUSTOMSTREAM_INVALID",l[l.ERROR_CUSTOMSTREAM_TRACK_NONE=11005]="ERROR_CUSTOMSTREAM_TRACK_NONE",l[l.ERROR_PREERCONNECTION_UNKNOWN=12e3]="ERROR_PREERCONNECTION_UNKNOWN",l[l.ERROR_SUBADD_NO_RESULT=13e3]="ERROR_SUBADD_NO_RESULT",l[l.ERROR_PUBADD_NO_RESULT=13001]="ERROR_PUBADD_NO_RESULT",l[l.ERROR_SINGLE_PC_STREAM_ERROR=13100]="ERROR_SINGLE_PC_STREAM_ERROR",l[l.ERROR_SINGLE_PC_STREAM_RECONNECT_FAILED=13101]="ERROR_SINGLE_PC_STREAM_RECONNECT_FAILED",l[l.ERROR_SINGLE_PC_FULL_RECONNECT=13102]="ERROR_SINGLE_PC_FULL_RECONNECT",l[l.ERROR_SINGLE_PC_FULL_RECONNECT_FAILED=13103]="ERROR_SINGLE_PC_FULL_RECONNECT_FAILED"}(o||(s.ErrorCode=o={})),function(l){l[l.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",l[l.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",l[l.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10002]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",l[l.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10003]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",l[l.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10004]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",l[l.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10005]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",l[l.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",l[l.ERROR_SCREENSHARE_NOTSUPPORT=10010]="ERROR_SCREENSHARE_NOTSUPPORT",l[l.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",l[l.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",l[l.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",l[l.ERROR_SCREENSHARE_SAFARI_INVALIDACCESS=10014]="ERROR_SCREENSHARE_SAFARI_INVALIDACCESS",l[l.ERROR_SCREENSHARE_UNKNOWNERRO=10019]="ERROR_SCREENSHARE_UNKNOWNERRO",l[l.ERROR_DEVICE_NOTSUPPORT=2e4]="ERROR_DEVICE_NOTSUPPORT"}(c||(s.DeviceErrorCode=c={})),s.SUB_RECONNECT_ERROR_LIST=[o.ERROR_INBOUND_TIMEOUT,o.ERROR_STREAM_ENDED,o.ERROR_PC_DISCONNECTED],s.RECONNECT_ERROR_EXCLUDE_LIST=[o.ERROR_AUTOPLAY_ERROR,o.ERROR_PLAY_URL,o.ERROR_SUBSCRIBE_NOTHING,o.ERROR_HTMLELEMENT_ERROR,o.ERROR_HEMLELEMENT_NOTMATCH,o.ERROR_PUBLISH_URL,o.ERROR_PUBLISH_NOAUDIO,o.ERROR_PUBLISH_NOSTREAM],s.PUB_RECONNECT_ERROR_LIST=[o.ERROR_PC_DISCONNECTED,o.ERROR_TRANSPORT_CLOSED],s.PC_RECONNECT_ERROR_LIST=h(h(h([],s.SUB_RECONNECT_ERROR_LIST,!0),s.PUB_RECONNECT_ERROR_LIST,!0),[o.ERROR_HTTPREQUEST_ERROR,o.ERROR_PC_DISCONNECTED,o.ERROR_IP_MIGRATE,o.ERROR_DATACHANNEL_CLOSE],!1)},5044:(a,s,o)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.RtsError=void 0;var c=o(9428),h=function(){function l(f,v,p,_){this.errorCode=f,this.errorCodeName=c.ErrorCode[f],this.message=v,this.traceId=p,_&&(this.extraInfo=_)}return l.prototype.renameCode=function(f){this.errorCode=f,this.errorCodeName=c.ErrorCode[f]},l}();s.RtsError=h},6091:(a,s)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.PlayEvent=s.PlayType=void 0,s.PlayType={PLAY_CANPLAY:"canplay",PLAY_WAITING:"waiting",PLAY_PLAYING:"playing",PLAY_MEDIA:"media",PLAY_ENDED:"ended",PLAY_TIMEOUT:"timeout"};var o=function(c){this.event=c};s.PlayEvent=o},5917:(a,s)=>{var o,c,h,l;Object.defineProperty(s,"__esModule",{value:!0}),s.DEFAULT_RETRY_DATACHANNEL_TIMEOUT=s.DEFAULT_HEARTBEAT_TIMEOUT_CHECK_INTERVAL=s.DEFAULT_HEARTBEAT_TIMEOUT_COUNT=s.DEFAULT_RETRY_PUBLISH_INTERVAL=s.DEFAULT_RETRY_SUBSCRIBE_INTERVAL=s.DEFAULT_RETRY_PUBLISH_LIMIT=s.DEFAULT_RETRY_SUBSCRIBE_LIMIT=s.EWorkerAction=s.EWorkerSource=s.EConnectStatus=s.TrackType=void 0,function(f){f.AUDIO="audio",f.VIDEO="video"}(o||(s.TrackType=o={})),function(f){f[f.CONNECT_STATUS_DISCONNECTED=0]="CONNECT_STATUS_DISCONNECTED",f[f.CONNECT_STATUS_CONNECTING=1]="CONNECT_STATUS_CONNECTING",f[f.CONNECT_STATUS_CONNECTED=2]="CONNECT_STATUS_CONNECTED",f[f.CONNECT_STATUS_RECONNECTING=3]="CONNECT_STATUS_RECONNECTING"}(c||(s.EConnectStatus=c={})),function(f){f.Sender="sender",f.Receiver="receiver"}(h||(s.EWorkerSource=h={})),function(f){f.Setup="setup",f.InserSEI="insertSEI",f.UpdatePubStats="updatePubStats",f.UpdateSubStats="updateSubStats",f.SwitchCumuDelay="switchCumuDelay"}(l||(s.EWorkerAction=l={})),s.DEFAULT_RETRY_SUBSCRIBE_LIMIT=5,s.DEFAULT_RETRY_PUBLISH_LIMIT=5,s.DEFAULT_RETRY_SUBSCRIBE_INTERVAL=2e3,s.DEFAULT_RETRY_PUBLISH_INTERVAL=2e3,s.DEFAULT_HEARTBEAT_TIMEOUT_COUNT=8,s.DEFAULT_HEARTBEAT_TIMEOUT_CHECK_INTERVAL=1e3,s.DEFAULT_RETRY_DATACHANNEL_TIMEOUT=8e3},6600:function(a,s,o){var c,h=this&&this.__extends||(c=function(D,L){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(P,x){P.__proto__=x}||function(P,x){for(var T in x)Object.prototype.hasOwnProperty.call(x,T)&&(P[T]=x[T])},c(D,L)},function(D,L){if(typeof L!="function"&&L!==null)throw new TypeError("Class extends value "+String(L)+" is not a constructor or null");function P(){this.constructor=D}c(D,L),D.prototype=L===null?Object.create(L):(P.prototype=L.prototype,new P)}),l=this&&this.__assign||function(){return l=Object.assign||function(D){for(var L,P=1,x=arguments.length;P<x;P++)for(var T in L=arguments[P])Object.prototype.hasOwnProperty.call(L,T)&&(D[T]=L[T]);return D},l.apply(this,arguments)},f=this&&this.__awaiter||function(D,L,P,x){return new(P||(P=Promise))(function(T,O){function k(ee){try{U(x.next(ee))}catch(W){O(W)}}function H(ee){try{U(x.throw(ee))}catch(W){O(W)}}function U(ee){var W;ee.done?T(ee.value):(W=ee.value,W instanceof P?W:new P(function($){$(W)})).then(k,H)}U((x=x.apply(D,L||[])).next())})},v=this&&this.__generator||function(D,L){var P,x,T,O,k={label:0,sent:function(){if(1&T[0])throw T[1];return T[1]},trys:[],ops:[]};return O={next:H(0),throw:H(1),return:H(2)},typeof Symbol=="function"&&(O[Symbol.iterator]=function(){return this}),O;function H(U){return function(ee){return function(W){if(P)throw new TypeError("Generator is already executing.");for(;O&&(O=0,W[0]&&(k=0)),k;)try{if(P=1,x&&(T=2&W[0]?x.return:W[0]?x.throw||((T=x.return)&&T.call(x),0):x.next)&&!(T=T.call(x,W[1])).done)return T;switch(x=0,T&&(W=[2&W[0],T.value]),W[0]){case 0:case 1:T=W;break;case 4:return k.label++,{value:W[1],done:!1};case 5:k.label++,x=W[1],W=[0];continue;case 7:W=k.ops.pop(),k.trys.pop();continue;default:if(T=k.trys,!((T=T.length>0&&T[T.length-1])||W[0]!==6&&W[0]!==2)){k=0;continue}if(W[0]===3&&(!T||W[1]>T[0]&&W[1]<T[3])){k.label=W[1];break}if(W[0]===6&&k.label<T[1]){k.label=T[1],T=W;break}if(T&&k.label<T[2]){k.label=T[2],k.ops.push(W);break}T[2]&&k.ops.pop(),k.trys.pop();continue}W=L.call(D,k)}catch($){W=[6,$],x=0}finally{P=T=0}if(5&W[0])throw W[1];return{value:W[0]?W[1]:void 0,done:!0}}([U,ee])}}},p=this&&this.__importDefault||function(D){return D&&D.__esModule?D:{default:D}};Object.defineProperty(s,"__esModule",{value:!0}),s.CommonController=void 0;var _=o(771),m=o(5917),d=p(o(102)),u=o(9594),b=o(2718),y=o(1698),g=o(5044),S=o(9428),R=o(6091),E=o(5788),I=o(280),C=p(o(1401)),A=o(5649),w=function(D){function L(P){var x=D.call(this)||this;return x.datachannelPool=new N,x.receiverCodecPreferences={},x.senderCodecPreferences={},x.canAutoAssignDcId=!0,x.reporter=P,x.signalChannel=new E.SignalChannel({reporter:P}),x.proxySignalChannelEvents(),x}return h(L,D),L.prototype.dispose=function(){var P;this.removeAllListeners(),this.signalChannel.dispose(),this.datachannelPool.dispose(),this.waitForOpenPms=void 0,this.receiverCodecPreferences={},this.senderCodecPreferences={},this.canAutoAssignDcId=!0,this.config=void 0,!((P=this.peerconnection)===null||P===void 0)&&P.isConnected&&this.peerconnection.reset()},L.prototype.setConfig=function(P){this.config=P},L.prototype.setPeerconnection=function(P){var x=this;P!==this.peerconnection&&(this.peerconnection&&this.peerconnection.removeAllListeners(),this.peerconnection=P,this.signalChannel.isOpen||(this.waitForOpenPms=new Promise(function(T,O){x.peerconnection.on("datachannelStatusChange",function(k){var H;x.emit("datachannelStatusChange",k),k.status===I.EDatachannelStatus.DATACHANNEL_STATUS_OPEN&&(x.signalChannel.setPeerConnection(P),x.canAutoAssignDcId=typeof((H=x.signalChannel.datachannelCore)===null||H===void 0?void 0:H.id)=="number",T())})})),this.peerconnection.on("cumuDelayNotSupported",function(){var T;x.emit("cumuDelayNotSupported"),(T=x.reporter)===null||T===void 0||T.reportCumuDelayNotSupported()}),this.peerconnection.on("innerSubscribeDeleteTracks",function(T){x.handleWorkerSubDelete(T)}),this.peerconnection.on("encodedFrame",function(T){var O;x.emit("encodedFrame",T),T.kind==="video"&&(0,u.parseSei)((O=T.frame)===null||O===void 0?void 0:O.data).forEach(function(k){var H;if(k.payloadType===A.CUMU_DELAY_SEI_PAYLOAD_TYPE){var U={pub:{},sub:{},grtn:{},AIPub:{},AISub:{},AIAgent:{},AIGrtn:{},other:{}},ee=new A.CumuDelaySeiPayloadParser(k.data);U.pub=ee.pub||{},U.sub=T.subStats||{},U.grtn=ee.grtn||{},U.AIPub=ee.AIPub||{},U.AISub=ee.AISub||{},U.AIAgent=ee.AIAgent||{},U.AIGrtn=ee.AIGrtn||{},U.other=ee.other||{},Object.keys(U.pub).forEach(function($){var B=U.pub[$];delete U.pub[$],U.pub[(0,b.lowercaseFirstLetter)($)]=B}),Object.keys(U.sub).forEach(function($){var B=U.sub[$];delete U.sub[$],U.sub[(0,b.lowercaseFirstLetter)($)]=B}),Object.keys(U.AIPub).forEach(function($){var B=U.AIPub[$];delete U.AIPub[$],U.AIPub[(0,b.lowercaseFirstLetter)($)]=B}),Object.keys(U.AISub).forEach(function($){var B=U.AISub[$];delete U.AISub[$],U.AISub[(0,b.lowercaseFirstLetter)($)]=B}),Object.keys(U.AIAgent).forEach(function($){var B=U.AIAgent[$];delete U.AIAgent[$],U.AIAgent[(0,b.underlineToCamelCase)($.toLowerCase())]=B}),Object.keys(U.AIGrtn).forEach(function($){var B=U.AIGrtn[$];delete U.AIGrtn[$],U.AIGrtn[(0,b.underlineToCamelCase)($.toLowerCase())]=B}),Object.keys(U.grtn).forEach(function($){var B=U.grtn[$];delete U.grtn[$],U.grtn[(0,b.underlineToCamelCase)($.toLowerCase())]=B});var W=void 0;try{W=(0,C.default)(U)}catch($){console.warn($,U)}W&&(k.data=new TextEncoder().encode(W),(H=x.reporter)===null||H===void 0||H.updateCumuDelayInfo({json:W}))}x.emit("receivedSEI",{url:T.url,vMsid:T.vMsid,sei:k})})}),this.peerconnection.on("message",function(T){var O;(O=x.reporter)===null||O===void 0||O.reportNotifyMessage(T)}),this.peerconnection.on("signalSent",function(T){x.emit("signalSent",T)}),this.peerconnection.on("signalReceived",function(T){x.emit("signalReceived",T)}),this.peerconnection.on("hebtSent",function(T){x.emit("hebtSent",T)}),this.peerconnection.on("hebtReceived",function(T){x.emit("hebtReceived",T)}),this.peerconnection.on("streamError",function(T){x.emit("onError",new g.RtsError(S.ErrorCode.ERROR_SINGLE_PC_STREAM_ERROR,T.resMsg,"",l({},T)))}),this.peerconnection.on("streamReconnect",function(T){x.emit("reconnect",{type:T.type,reason:new g.RtsError(S.ErrorCode.ERROR_SINGLE_PC_STREAM_ERROR,T.resMsg,"",l({},T)),retryTimes:1,extraInfo:l({},T)}),x.singleStreamReconnect(T).then(function(){x.emit("reconnectFinish",{type:T.type,latestUrl:T.latestUrl,msids:T.msids})}).catch(function(O){x.emit("onError",new g.RtsError(S.ErrorCode.ERROR_SINGLE_PC_STREAM_RECONNECT_FAILED,"single stream reconnect failed","",{originError:O}))})}),this.peerconnection.on("traceIdUpdate",function(T){x.emit("traceId",T)}),this.peerconnection.on("pcReconnect",function(T){x.emit("reconnect",{type:"pc",reason:new g.RtsError(S.ErrorCode.ERROR_SINGLE_PC_FULL_RECONNECT,T.reMsg,"",l({},T)),retryTimes:1,extraInfo:l({},T)})}),(this.receiverCodecPreferences.video||this.receiverCodecPreferences.audio)&&this.peerconnection.setReceiverCodecPreferences(this.receiverCodecPreferences),(this.senderCodecPreferences.video||this.senderCodecPreferences.audio)&&this.peerconnection.setSenderCodecPreferences(this.senderCodecPreferences))},Object.defineProperty(L.prototype,"peerCore",{get:function(){var P;return(P=this.peerconnection)===null||P===void 0?void 0:P.getPeerCore()},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"streamManager",{get:function(){var P;return(P=this.peerCore)===null||P===void 0?void 0:P.getStreamManager()},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"datachannelManager",{get:function(){var P;return(P=this.peerCore)===null||P===void 0?void 0:P.getDatachannelManager()},enumerable:!1,configurable:!0}),L.prototype.subscribeAdd=function(P,x){return f(this,void 0,void 0,function(){var T,O,k,H,U,ee,W,$,B=this;return v(this,function(F){switch(F.label){case 0:if(P.forEach(function(G){var q;(q=B.reporter)===null||q===void 0||q.reportSubscribeStart(G.url,"",G.vMsid,G.aMsid,!0)}),!this.peerconnection)throw this.makeRtsError("subscribeAdd");this.peerconnection.isReused=!0,T=new Date().getTime(),F.label=1;case 1:return F.trys.push([1,3,,4]),[4,this.peerconnection.subAdd(P,x)];case 2:if(!(O=F.sent()).streamList)throw new g.RtsError(S.ErrorCode.ERROR_SUBADD_NO_RESULT,"subAdd streamList not found","",{api:"subscribeAdd",configList:P,response:O});return[3,4];case 3:throw k=F.sent(),H=k,($=this.reporter)===null||$===void 0||$.reportErrorInfo(H.errorCode,H.message,H.traceId,H.extraInfo),H;case 4:return U=O.deleteRspTime-T,ee=O.subAddRspTime-O.deleteRspTime,W=O.activeRspTime-O.subAddRspTime,O.streamList.forEach(function(G,q){var X,J,se,ce;(X=B.reporter)===null||X===void 0||X.reportSubscribeOk({vurl:G.url||void 0,isSubAdd:!0});var Y,fe=P[q]||{},he=fe.targetStream,pe=fe.vMsid,ue=fe.aMsid,Te=G.stream;if(he)return he.mergeStream(Te),(J=B.streamManager)===null||J===void 0||J.update(G.url,{stream:he,vMsid:pe==null?void 0:pe[0],aMsid:ue==null?void 0:ue[0]}),void(G.stream=he);var be=(se=B.streamManager)===null||se===void 0?void 0:se.getStreamByMsid({url:G.url,vMsid:pe==null?void 0:pe[0],aMsid:ue==null?void 0:ue[0]});if(be)be.mergeStream(Te),Y=be;else{(Y=new _.RemoteStream).updateMediaStream(Te),(ce=B.streamManager)===null||ce===void 0||ce.update(G.url,{stream:Y,vMsid:pe==null?void 0:pe[0],aMsid:ue==null?void 0:ue[0]}),Y.on("onCanPlay",function(){var K,re,de=new Date().getTime();(K=B.reporter)===null||K===void 0||K.reportFirstFrameTime(G.url,G.traceId,-1,-1,de-T,0,-1,{},U,ee,W,pe,ue,!0),(re=B.peerconnection)===null||re===void 0||re.playStart()});var Z=new R.PlayEvent(R.PlayType.PLAY_CANPLAY);Z.data={url:G.url,vMsid:(pe==null?void 0:pe[0])||"vMsid unknown",aMsid:(ue==null?void 0:ue[0])||"aMsid unknown"},B.emit("onPlayEvent",Z)}G.stream=Y}),[2,O.streamList]}})})},L.prototype.subscribeActive=function(P){return f(this,void 0,void 0,function(){var x;return v(this,function(T){if(!this.peerconnection)throw this.makeRtsError("subscribeActive");return[2,(x=this.peerconnection)===null||x===void 0?void 0:x.subActive(P)]})})},L.prototype.subscribeStop=function(P){return f(this,void 0,void 0,function(){var x,T,O,k,H;return v(this,function(U){switch(U.label){case 0:if(!this.peerconnection)throw this.makeRtsError("subscribeStop");U.label=1;case 1:return U.trys.push([1,3,,4]),[4,this.peerconnection.subStop(P)];case 2:return x=U.sent(),this.peerconnection.getSubMonitor().updateTranceiversController(),T=this.peerconnection.getWorkerManager(),P.forEach(function(ee){T.removeByUrl({url:ee.url,source:m.EWorkerSource.Receiver})}),[3,4];case 3:throw O=U.sent(),k=O,(H=this.reporter)===null||H===void 0||H.reportErrorInfo(k.errorCode,k.message,k.traceId,k.extraInfo),O;case 4:return[2,x]}})})},L.prototype.subscribeDeleteTracks=function(P){return f(this,void 0,void 0,function(){var x,T,O,k;return v(this,function(H){switch(H.label){case 0:if(!this.peerconnection)throw this.makeRtsError("subscribeDeleteTracks");H.label=1;case 1:return H.trys.push([1,3,,4]),[4,this.peerconnection.subDeleteTracks(P)];case 2:if(!(x=H.sent()))throw this.makeRtsError("subscribeDeleteTracks");return this.peerconnection.getSubMonitor().updateTranceiversController(),this.handleWorkerSubDelete(P),[3,4];case 3:throw T=H.sent(),O=T,(k=this.reporter)===null||k===void 0||k.reportErrorInfo(O.errorCode,O.message,O.traceId,O.extraInfo),T;case 4:return[2,x]}})})},L.prototype.handleWorkerSubDelete=function(P){if(this.peerconnection){var x=this.peerconnection.getWorkerManager();P.forEach(function(T){var O,k;!((O=T.vMsid)===null||O===void 0)&&O.length&&x.removeByMsid({url:T.url,source:m.EWorkerSource.Receiver,kind:"video",msid:T.vMsid[0]}),!((k=T.aMsid)===null||k===void 0)&&k.length&&x.removeByMsid({url:T.url,source:m.EWorkerSource.Receiver,kind:"audio",msid:T.aMsid[0]})})}},L.prototype.publishAdd=function(P){return f(this,void 0,void 0,function(){var x,T,O,k,H,U,ee,W,$,B,F,G,q=this;return v(this,function(X){switch(X.label){case 0:if(P.forEach(function(J){var se;(se=q.reporter)===null||se===void 0||se.reportStartPublish(J.url,"",!0)}),x=new Date().getTime(),!this.peerconnection)throw this.makeRtsError("publishAdd");X.label=1;case 1:return X.trys.push([1,3,,4]),[4,($=this.peerconnection)===null||$===void 0?void 0:$.pubAdd(P)];case 2:if(!(T=X.sent()))throw new g.RtsError(S.ErrorCode.ERROR_PUBADD_NO_RESULT,"pubAdd streamList not found","",{api:"publishAdd",publishInfoList:P});return[3,4];case 3:throw O=X.sent(),k=O,(B=this.reporter)===null||B===void 0||B.reportErrorInfo(k.errorCode,k.message,k.traceId,k.extraInfo),k;case 4:return this.peerconnection.isReused=!0,H=new Date().getTime(),U=H-x,T.forEach(function(J){var se;(se=q.reporter)===null||se===void 0||se.reportPublishOk(J.url||"","",-1,-1,-1,J.traceId||"",U,!0)}),(ee=(F=this.peerconnection)===null||F===void 0?void 0:F.getPc())&&(P.forEach(function(J){q.peerconnection&&J.stream.setEncodeParam(ee)}),this.peerCore&&((G=this.peerconnection)===null||G===void 0||G.getPubMonitor().startHeartbeat(ee,this.peerCore)),W=new Set,P.forEach(function(J){J.stream.audioTrack&&W.add(J.stream.audioTrack.id),J.stream.videoTrack&&W.add(J.stream.videoTrack.id)}),ee.getSenders().forEach(function(J){var se;J.track&&W.has(J.track.id)&&((se=q.peerconnection)===null||se===void 0||se.handleEncodedInsertableStreams({sender:J}))})),[2,T]}})})},L.prototype.publishDeleteTracks=function(P){return f(this,void 0,void 0,function(){var x,T,O,k,H;return v(this,function(U){switch(U.label){case 0:if(!this.peerconnection)throw this.makeRtsError("publishDeleteTracks");U.label=1;case 1:return U.trys.push([1,3,,4]),[4,this.peerconnection.pubDeleteTracks(P)];case 2:if(!(x=U.sent()))throw this.makeRtsError("publishDeleteTracks");return this.peerconnection.getPubMonitor().updateSenders(),T=this.peerconnection.getWorkerManager(),P.forEach(function(ee){var W,$;!((W=ee.vMsid)===null||W===void 0)&&W.length&&T.removeByMsid({url:ee.url,source:m.EWorkerSource.Sender,kind:"video",msid:ee.vMsid[0]}),!(($=ee.aMsid)===null||$===void 0)&&$.length&&T.removeByMsid({url:ee.url,source:m.EWorkerSource.Sender,kind:"audio",msid:ee.aMsid[0]})}),[3,4];case 3:throw O=U.sent(),k=O,(H=this.reporter)===null||H===void 0||H.reportErrorInfo(k.errorCode,k.message,k.traceId,k.extraInfo),O;case 4:return[2,x]}})})},L.prototype.publishReplaceTracks=function(P){return f(this,void 0,void 0,function(){var x,T,O,k;return v(this,function(H){switch(H.label){case 0:if(!this.peerconnection)throw this.makeRtsError("publishReplaceTracks");H.label=1;case 1:return H.trys.push([1,3,,4]),[4,this.peerconnection.pubReplaceTracks(P)];case 2:if(!(x=H.sent()))throw this.makeRtsError("publishReplaceTracks");return this.peerconnection.getPubMonitor().updateSenders(),[3,4];case 3:throw T=H.sent(),O=T,(k=this.reporter)===null||k===void 0||k.reportErrorInfo(O.errorCode,O.message,O.traceId,O.extraInfo),T;case 4:return[2,x]}})})},L.prototype.publishStop=function(P){return f(this,void 0,void 0,function(){var x,T,O,k,H,U=this;return v(this,function(ee){switch(ee.label){case 0:if(P.forEach(function(W){var $;($=U.reporter)===null||$===void 0||$.reportStopPublish(W.url,!0)}),!this.peerconnection)throw this.makeRtsError("publishStop");ee.label=1;case 1:return ee.trys.push([1,3,,4]),[4,this.peerconnection.pubStop(P)];case 2:return x=ee.sent(),this.peerconnection.getPubMonitor().updateSenders(),T=this.peerconnection.getWorkerManager(),P.forEach(function(W){T.removeByUrl({url:W.url,source:m.EWorkerSource.Sender})}),[3,4];case 3:throw O=ee.sent(),k=O,(H=this.reporter)===null||H===void 0||H.reportErrorInfo(k.errorCode,k.message,k.traceId,k.extraInfo),O;case 4:return[2,x]}})})},L.prototype.handleAddDatachannel=function(P){return f(this,void 0,void 0,function(){var x,T,O,k,H,U,ee,W,$,B,F,G,q=this;return v(this,function(X){switch(X.label){case 0:if(!P.url||!P.signalUrl||!P.msid)throw T=new g.RtsError(S.ErrorCode.ERROR_DATACHANNEL_PARAM,"url, signalUrl, msid is required by subscribe(publish)AddDatachannel",""),(ee=this.reporter)===null||ee===void 0||ee.reportErrorInfo(T.errorCode,T.message,T.traceId,T.extraInfo),T;return x=P.type==="sub",this.waitForOpenPms?[4,this.waitForOpenPms]:[3,2];case 1:X.sent(),this.waitForOpenPms=void 0,X.label=2;case 2:if(this.signalChannel.isOpen)return[3,4];if(console.warn("Creating a new signal channel"),!P.signalUrl)throw T=new g.RtsError(S.ErrorCode.ERROR_SIGNAL_URL,"signal url is required",""),(W=this.reporter)===null||W===void 0||W.reportErrorInfo(T.errorCode,T.message,T.traceId,T.extraInfo),T;return[4,this.initSignalChannel(P)];case 3:X.sent(),this.setPeerconnection(this.signalChannel.getPeerConnection()),this.canAutoAssignDcId=typeof(($=this.signalChannel.datachannelCore)===null||$===void 0?void 0:$.id)=="number",X.label=4;case 4:if(O=performance.now(),k={url:P.url,label:P.label,surl:P.signalUrl,msid:P.msid},x?(B=this.reporter)===null||B===void 0||B.reportDatachannelSubAdd(k):(F=this.reporter)===null||F===void 0||F.reportDatachannelPubAdd(k),!(H=(G=this.peerconnection)===null||G===void 0?void 0:G.getPc()))throw new Error("No avaliable peerconnection");return(U=this.datachannelPool.getIdleItem())?U.reuse():(U=new I.DataChannelCore({pc:H,label:P.label,datachannelList:this.datachannelPool.list,assignId:!this.canAutoAssignDcId,delayOpen:y.configProvider.getContext().datachannelDelayOpen,initOptions:P.initOptions}),this.datachannelPool.update(U)),[2,new Promise(function(J,se){return f(q,void 0,void 0,function(){var ce,Y,fe,he,pe,ue,Te,be,Z,K,re,de,ye,Ee,Ve,De,Ue=this;return v(this,function(Ye){switch(Ye.label){case 0:ce="",Y=!1,fe=!1,U.on("statusChange",function(Ie){var Oe;(Oe=Ue.reporter)===null||Oe===void 0||Oe.reportDatachannelStatusChange({state:I.EDatachannelStatus[Ie],url:P.url,label:U.label,id:U.id,msid:P.msid}),Ie===I.EDatachannelStatus.DATACHANNEL_STATUS_OPEN&&(Y=!0,fe&&J({datachannel:U,traceId:ce}))}),U.on("dispose",function(){var Ie;(Ie=Ue.reporter)===null||Ie===void 0||Ie.reportDatachannelDispose({url:P.url,label:U.label,id:U.id,msid:P.msid})}),Ye.label=1;case 1:return Ye.trys.push([1,6,,7]),he=[{url:P.url,msid:P.msid,datachannelId:U.id,label:P.label,datachannel:U}],x?[4,(K=this.peerCore)===null||K===void 0?void 0:K.subscribeAddDatachannel(he)]:[3,3];case 2:return ue=Ye.sent(),[3,5];case 3:return[4,(re=this.peerCore)===null||re===void 0?void 0:re.publishAddDatachannel(he)];case 4:ue=Ye.sent(),Ye.label=5;case 5:return ce=(ye=(de=(pe=ue)==null?void 0:pe.streams)===null||de===void 0?void 0:de[0])===null||ye===void 0?void 0:ye.traceid,[3,7];case 6:return Te=Ye.sent(),be=Te,(Ee=this.reporter)===null||Ee===void 0||Ee.reportErrorInfo(be.errorCode,be.message||"datachannel ".concat(x?"sub":"pub"," add error"),be.traceId,be.extraInfo),[2,se(Te)];case 7:return Z={url:P.url,drct:Math.floor(performance.now()-O),tcid:ce,label:U.label,id:U.id,msid:P.msid},x?(Ve=this.reporter)===null||Ve===void 0||Ve.reportDatachannelSubAddOk(Z):(De=this.reporter)===null||De===void 0||De.reportDatachannelPubAddOk(Z),fe=!0,Y&&J({datachannel:U,traceId:ce}),[2]}})})})]}})})},L.prototype.handleDeleteDatachannel=function(P){return f(this,void 0,void 0,function(){var x,T,O,k,H,U,ee,W,$,B,F,G;return v(this,function(q){switch(q.label){case 0:if(!P.url||!P.datachannel)throw x=new g.RtsError(S.ErrorCode.ERROR_DATACHANNEL_PARAM,"url, datachannel is required by subscribe(publish)DeleteDatachannel",""),(H=this.reporter)===null||H===void 0||H.reportErrorInfo(x.errorCode,x.message,x.traceId,x.extraInfo),x;if(!this.signalChannel.isOpen)throw x=new g.RtsError(S.ErrorCode.ERROR_NO_DATACHANNEL,"Signal channel is closed",""),(U=this.reporter)===null||U===void 0||U.reportErrorInfo(x.errorCode,x.message,x.traceId,x.extraInfo),x;T=P.type==="sub",O=[{url:P.url,msid:P.msid}],k={url:P.url,msid:P.msid,label:P.datachannel.label,id:P.datachannel.id},T?(ee=this.reporter)===null||ee===void 0||ee.reportDatachannelSubDelete(k):(W=this.reporter)===null||W===void 0||W.reportDatachannelPubDelete(k),q.label=1;case 1:return q.trys.push([1,6,,7]),T?[4,($=this.peerCore)===null||$===void 0?void 0:$.subscribeDeleteDatachannel(O)]:[3,3];case 2:return q.sent(),[3,5];case 3:return[4,(B=this.peerCore)===null||B===void 0?void 0:B.publishDeleteDatachannel(O)];case 4:q.sent(),q.label=5;case 5:return[3,7];case 6:throw q.sent();case 7:return T?(F=this.reporter)===null||F===void 0||F.reportDatachannelSubDeleteOk(k):(G=this.reporter)===null||G===void 0||G.reportDatachannelPubDeleteOk(k),P.datachannel.dispose(),[2]}})})},L.prototype.handleStopDatachannel=function(P){return f(this,void 0,void 0,function(){var x,T,O,k,H,U,ee,W,$,B,F,G;return v(this,function(q){switch(q.label){case 0:if(!P.url||!P.datachannel)throw x=new g.RtsError(S.ErrorCode.ERROR_DATACHANNEL_PARAM,"url, datachannel is required by subscribe(publish)StopDatachannel",""),(H=this.reporter)===null||H===void 0||H.reportErrorInfo(x.errorCode,x.message,x.traceId,x.extraInfo),x;if(!this.signalChannel.isOpen)throw x=new g.RtsError(S.ErrorCode.ERROR_NO_DATACHANNEL,"Signal channel is closed",""),(U=this.reporter)===null||U===void 0||U.reportErrorInfo(x.errorCode,x.message,x.traceId,x.extraInfo),x;T=P.type==="sub",O=[{url:P.url}],k={url:P.url,label:P.datachannel.label,id:P.datachannel.id},T?(ee=this.reporter)===null||ee===void 0||ee.reportDatachannelSubStop(k):(W=this.reporter)===null||W===void 0||W.reportDatachannelPubStop(k),q.label=1;case 1:return q.trys.push([1,6,,7]),T?[4,($=this.peerCore)===null||$===void 0?void 0:$.subscribeStopDatachannel(O)]:[3,3];case 2:return q.sent(),[3,5];case 3:return[4,(B=this.peerCore)===null||B===void 0?void 0:B.publishStopDatachannel(O)];case 4:q.sent(),q.label=5;case 5:return[3,7];case 6:throw q.sent();case 7:return T?(F=this.reporter)===null||F===void 0||F.reportDatachannelSubStopOk(k):(G=this.reporter)===null||G===void 0||G.reportDatachannelPubStopOk(k),P.datachannel.dispose(),[2]}})})},L.prototype.subscribeAddDatachannel=function(P){return f(this,void 0,void 0,function(){return v(this,function(x){return[2,this.handleAddDatachannel(l(l({},P),{type:"sub"}))]})})},L.prototype.publishAddDatachannel=function(P){return f(this,void 0,void 0,function(){return v(this,function(x){return[2,this.handleAddDatachannel(l(l({},P),{type:"pub"}))]})})},L.prototype.subscribeDeleteDatachannel=function(P){return f(this,void 0,void 0,function(){return v(this,function(x){return[2,this.handleDeleteDatachannel(l(l({},P),{type:"sub"}))]})})},L.prototype.publishDeleteDatachannel=function(P){return f(this,void 0,void 0,function(){return v(this,function(x){return[2,this.handleDeleteDatachannel(l(l({},P),{type:"pub"}))]})})},L.prototype.subscribeStopDatachannel=function(P){return f(this,void 0,void 0,function(){return v(this,function(x){return[2,this.handleStopDatachannel(l(l({},P),{type:"sub"}))]})})},L.prototype.publishStopDatachannel=function(P){return f(this,void 0,void 0,function(){return v(this,function(x){return[2,this.handleStopDatachannel(l(l({},P),{type:"pub"}))]})})},L.prototype.getSubscribeVideoStats=function(P,x){return this.getSubscribeMediaStats(P,"video",x)},L.prototype.getSubscribeAudioStats=function(P,x){return this.getSubscribeMediaStats(P,"audio",x)},L.prototype.getPublishVideoStats=function(P,x){return this.getPublishMediaStats(P,"video",x)},L.prototype.getPublishAudioStats=function(P,x){return this.getPublishMediaStats(P,"audio",x)},L.prototype.sendSEI=function(P){var x,T;if(!((x=this.peerconnection)===null||x===void 0)&&x.isReused)return(T=this.peerconnection)===null||T===void 0?void 0:T.sendSEI(P)},L.prototype.setReceiverCodecPreferences=function(P){this.receiverCodecPreferences=l({},P)},L.prototype.setSenderCodecPreferences=function(P){this.senderCodecPreferences=l({},P)},L.prototype.getSubscribeMediaStats=function(P,x,T){var O=this;return new Promise(function(k){return f(O,void 0,void 0,function(){var H,U,ee,W,$;return v(this,function(B){switch(B.label){case 0:return this.streamManager?(H=void 0,U=this.streamManager.getAllMediaInfoList(P,!0),T?U.forEach(function(F){var G,q,X,J=(q=(G=F.transceiver)===null||G===void 0?void 0:G.receiver)===null||q===void 0?void 0:q.track;(J==null?void 0:J.kind)===x&&F.msid===T&&(H=(X=F.transceiver)===null||X===void 0?void 0:X.receiver)}):H=($=(W=U==null?void 0:U.find(function(F){var G,q,X;return((X=(q=(G=F.transceiver)===null||G===void 0?void 0:G.receiver)===null||q===void 0?void 0:q.track)===null||X===void 0?void 0:X.kind)===x}))===null||W===void 0?void 0:W.transceiver)===null||$===void 0?void 0:$.receiver,H?(ee=!1,[4,H.getStats()]):[2,k({})]):[2,k({})];case 1:return B.sent().forEach(function(F){F.type==="inbound-rtp"&&(ee=!0,k(F))}),ee||k({}),[2]}})})})},L.prototype.getPublishMediaStats=function(P,x,T){var O=this;return new Promise(function(k){return f(O,void 0,void 0,function(){var H,U,ee,W,$;return v(this,function(B){switch(B.label){case 0:return this.streamManager?(H=void 0,U=this.streamManager.getAllMediaInfoList(P,!0),T?U.forEach(function(F){var G,q,X,J=(q=(G=F.transceiver)===null||G===void 0?void 0:G.sender)===null||q===void 0?void 0:q.track;(J==null?void 0:J.kind)===x&&F.msid===T&&(H=(X=F.transceiver)===null||X===void 0?void 0:X.sender)}):H=($=(W=U==null?void 0:U.find(function(F){var G,q,X;return((X=(q=(G=F.transceiver)===null||G===void 0?void 0:G.sender)===null||q===void 0?void 0:q.track)===null||X===void 0?void 0:X.kind)===x}))===null||W===void 0?void 0:W.transceiver)===null||$===void 0?void 0:$.sender,H?(ee=!1,[4,H.getStats()]):[2,k({})]):[2,k({})];case 1:return B.sent().forEach(function(F){F.type==="outbound-rtp"&&k(F)}),ee||k({}),[2]}})})})},L.prototype.proxySignalChannelEvents=function(){var P=this;this.signalChannel.on("connectStatusChange",function(x){P.emit("connectStatusChange",x)}),this.signalChannel.on("onError",function(x){P.emit("onError",x)})},L.prototype.initSignalChannel=function(P){return this.signalChannel.createDatachannel(P)},L.prototype.makeRtsError=function(P){var x,T=new g.RtsError(S.ErrorCode.ERROR_NO_DATACHANNEL,"No avaliable datachannel, you should subscribe/publish first.","",{api:P});return(x=this.reporter)===null||x===void 0||x.reportErrorInfo(T.errorCode,T.message,T.traceId,T.extraInfo),T},L.prototype.singleStreamReconnect=function(P){var x=this;return new Promise(function(T,O){var k,H,U=P.type,ee=void 0,W=void 0;switch(U){case"sub":(k=P.streams)===null||k===void 0||k.forEach(function(B){var F=[],G=[],q=!0,X=!0;P.msids.forEach(function(J){J.streamId===B.id&&(J.type==="video"?G.push(J.name):J.type==="audio"&&F.push(J.name))}),F.length||(q=!1),G.length||(X=!1),x.subscribeAddWithRetry({url:P.latestUrl,subAudio:q,subVideo:X,vMsid:G,aMsid:F,targetStream:B}).then(T).catch(O)});break;case"pub":(H=P.streams)===null||H===void 0||H.forEach(function(B){var F=[],G=[];P.msids.forEach(function(q){q.streamId===B.id&&(q.type==="video"?G.push(q.name):q.type==="audio"&&F.push(q.name))}),x.publishAddWithRetry([{url:P.latestUrl,vMsid:G,aMsid:F,stream:B}]).then(T).catch(O)});break;case"pub-data":if(P.msids.forEach(function(B){ee=B.name,W=B.label}),ee&&W){var $=P.latestUrl;x.publishAddDatachannelWithRetry({url:$,signalUrl:$,msid:ee,label:W}).then(T).catch(O)}break;case"sub-data":P.msids.forEach(function(B){ee=B.name,W=B.label}),ee&&W&&($=P.latestUrl,x.subscribeAddDatachannelWithRetry({url:$,signalUrl:$,msid:ee,label:W}).then(T).catch(O));break;default:console.warn("RTS PC STREAM RECONNECT: Unknown signal")}})},L.prototype.updateAuth=function(P){var x,T,O=(x=this.streamManager)===null||x===void 0?void 0:x.updateLatestUrl(P),k=(T=this.datachannelManager)===null||T===void 0?void 0:T.updateLatestUrl(P);return O||k},L.prototype.subscribeAddWithRetry=function(P,x){var T=this;return x===void 0&&(x=0),new Promise(function(O,k){T.subscribeAdd([P],!0).then(function(){O()}).catch(function(H){return f(T,void 0,void 0,function(){var U,ee;return v(this,function(W){switch(W.label){case 0:return x<(((U=this.config)===null||U===void 0?void 0:U.retryTimes)||0)?[4,M(((ee=this.config)===null||ee===void 0?void 0:ee.retryInterval)||0)]:[3,2];case 1:return W.sent(),[2,this.subscribeAddWithRetry(P,x+1).then(O).catch(k)];case 2:k(H),W.label=3;case 3:return[2]}})})})})},L.prototype.publishAddWithRetry=function(P,x){var T=this;return x===void 0&&(x=0),new Promise(function(O,k){T.publishAdd(P).then(function(){O()}).catch(function(H){return f(T,void 0,void 0,function(){var U,ee;return v(this,function(W){switch(W.label){case 0:return x<(((U=this.config)===null||U===void 0?void 0:U.retryTimes)||0)?[4,M(((ee=this.config)===null||ee===void 0?void 0:ee.retryInterval)||0)]:[3,2];case 1:return W.sent(),[2,this.publishAddWithRetry(P,x+1).then(O).catch(k)];case 2:k(H),W.label=3;case 3:return[2]}})})})})},L.prototype.subscribeAddDatachannelWithRetry=function(P,x){var T=this;return x===void 0&&(x=0),new Promise(function(O,k){T.subscribeAddDatachannel(P).then(function(){O()}).catch(function(H){return f(T,void 0,void 0,function(){var U,ee;return v(this,function(W){switch(W.label){case 0:return x<(((U=this.config)===null||U===void 0?void 0:U.retryTimes)||0)?[4,M(((ee=this.config)===null||ee===void 0?void 0:ee.retryInterval)||0)]:[3,2];case 1:return W.sent(),[2,this.subscribeAddDatachannelWithRetry(P,x+1).then(O).catch(k)];case 2:k(H),W.label=3;case 3:return[2]}})})})})},L.prototype.publishAddDatachannelWithRetry=function(P,x){var T=this;return x===void 0&&(x=0),new Promise(function(O,k){T.publishAddDatachannel(P).then(function(){O()}).catch(function(H){return f(T,void 0,void 0,function(){var U,ee;return v(this,function(W){switch(W.label){case 0:return x<(((U=this.config)===null||U===void 0?void 0:U.retryTimes)||0)?[4,M(((ee=this.config)===null||ee===void 0?void 0:ee.retryInterval)||0)]:[3,2];case 1:return W.sent(),[2,this.publishAddDatachannelWithRetry(P,x+1).then(O).catch(k)];case 2:k(H),W.label=3;case 3:return[2]}})})})})},L}(d.default);s.CommonController=w;var N=function(){function D(){this._list=[]}return Object.defineProperty(D.prototype,"list",{get:function(){return this._list},enumerable:!1,configurable:!0}),D.prototype.update=function(L){var P=this._list.findIndex(function(x){return x.id===L.id});P!==-1?this._list.splice(P,1,L):this._list.push(L)},D.prototype.getIdleItem=function(){return this._list.find(function(L){return L.isIdle})},D.prototype.dispose=function(){this._list=[]},D}();function M(D){return D===void 0&&(D=1e3),new Promise(function(L){setTimeout(L,D)})}},9796:function(a,s,o){var c,h=this&&this.__extends||(c=function(C,A){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,N){w.__proto__=N}||function(w,N){for(var M in N)Object.prototype.hasOwnProperty.call(N,M)&&(w[M]=N[M])},c(C,A)},function(C,A){if(typeof A!="function"&&A!==null)throw new TypeError("Class extends value "+String(A)+" is not a constructor or null");function w(){this.constructor=C}c(C,A),C.prototype=A===null?Object.create(A):(w.prototype=A.prototype,new w)}),l=this&&this.__assign||function(){return l=Object.assign||function(C){for(var A,w=1,N=arguments.length;w<N;w++)for(var M in A=arguments[w])Object.prototype.hasOwnProperty.call(A,M)&&(C[M]=A[M]);return C},l.apply(this,arguments)},f=this&&this.__awaiter||function(C,A,w,N){return new(w||(w=Promise))(function(M,D){function L(T){try{x(N.next(T))}catch(O){D(O)}}function P(T){try{x(N.throw(T))}catch(O){D(O)}}function x(T){var O;T.done?M(T.value):(O=T.value,O instanceof w?O:new w(function(k){k(O)})).then(L,P)}x((N=N.apply(C,A||[])).next())})},v=this&&this.__generator||function(C,A){var w,N,M,D,L={label:0,sent:function(){if(1&M[0])throw M[1];return M[1]},trys:[],ops:[]};return D={next:P(0),throw:P(1),return:P(2)},typeof Symbol=="function"&&(D[Symbol.iterator]=function(){return this}),D;function P(x){return function(T){return function(O){if(w)throw new TypeError("Generator is already executing.");for(;D&&(D=0,O[0]&&(L=0)),L;)try{if(w=1,N&&(M=2&O[0]?N.return:O[0]?N.throw||((M=N.return)&&M.call(N),0):N.next)&&!(M=M.call(N,O[1])).done)return M;switch(N=0,M&&(O=[2&O[0],M.value]),O[0]){case 0:case 1:M=O;break;case 4:return L.label++,{value:O[1],done:!1};case 5:L.label++,N=O[1],O=[0];continue;case 7:O=L.ops.pop(),L.trys.pop();continue;default:if(M=L.trys,!((M=M.length>0&&M[M.length-1])||O[0]!==6&&O[0]!==2)){L=0;continue}if(O[0]===3&&(!M||O[1]>M[0]&&O[1]<M[3])){L.label=O[1];break}if(O[0]===6&&L.label<M[1]){L.label=M[1],M=O;break}if(M&&L.label<M[2]){L.label=M[2],L.ops.push(O);break}M[2]&&L.ops.pop(),L.trys.pop();continue}O=A.call(C,L)}catch(k){O=[6,k],N=0}finally{w=M=0}if(5&O[0])throw O[1];return{value:O[0]?O[1]:void 0,done:!0}}([x,T])}}},p=this&&this.__importDefault||function(C){return C&&C.__esModule?C:{default:C}};Object.defineProperty(s,"__esModule",{value:!0}),s.Publisher=void 0;var _=o(5917),m=o(4865),d=p(o(7028)),u=o(9428),b=o(5044),y=o(7989),g=p(o(102)),S=p(o(8219)),R=o(2718),E=p(o(1401)),I=function(C){function A(w){var N=C.call(this)||this;return N.publishStartTimeStamp=0,N.pubReconnectTimes=0,N.isConnecting=!1,N.cancelReconnect=!1,N.reconnectTimerHandle=null,N.publishCallId=0,N.reportMonitorTimes=0,N.reportSubFlag=!1,N.reporter=w,N.peerconnection=new m.RtsPeerconnection,N.peerconnection.on("connectStatusChange",function(M){if(M.status!==_.EConnectStatus.CONNECT_STATUS_DISCONNECTED&&M.status!==_.EConnectStatus.CONNECT_STATUS_RECONNECTING||!N.hasRetries())N.emit("connectStatusChange",M);else{var D=M.status===_.EConnectStatus.CONNECT_STATUS_RECONNECTING;N.emit("onError",new b.RtsError(u.ErrorCode.ERROR_PC_DISCONNECTED,"PC disconnected","",{fromSystemEvent:D}))}}),N.peerconnection.on("onMonitorEvent",function(M){var D,L=M.eventList;(D=N.peerconnection)===null||D===void 0||D.updateStatsForSEI(L,M.type),M.type==="pub"?(N.reportMonitorTimes++,N.reportMonitorTimes%4==0&&(L.forEach(function(P){N.reporter.reportPushStats(P)}),N.reportSubFlag=!0,N.reportMonitorTimes=0)):M.type==="sub"&&N.reportSubFlag&&(N.handleSubMonitorEvent(L),N.reportSubFlag=!1)}),N.peerconnection.on("onTransportStateEvent",function(M){var D;N.peerconnection.isReused||((D=N.peerconnection.getPc())===null||D===void 0?void 0:D.connectionState)!=="closed"&&M.state==="closed"&&N.hasRetries()&&N.emit("onError",new b.RtsError(u.ErrorCode.ERROR_TRANSPORT_CLOSED,"Transport has been closed. ".concat(M.kind,"|").concat(M.type,"|").concat(M.url),"",{protocol:M.protocol}))}),N.peerconnection.on("pcReconnect",function(M){var D,L;M.ips?(D="Migrate with ips: ".concat((0,E.default)(M.ips)),L=u.ErrorCode.ERROR_IP_MIGRATE):(D="PC disconnected",L=u.ErrorCode.ERROR_PC_DISCONNECTED),N.emit("onError",new b.RtsError(L,D,"",{pcErrorInfo:M}))}),N.signalingUrl="",N.publishUrl="",N.publishConfig={},N}return h(A,C),A.prototype.publish=function(w,N,M,D){var L=this;return new Promise(function(P,x){if(L.unpublish(),M!=null&&M.cumuDelay&&(M.encodedInsertableStreams=!0),L.localStream=N,L.publishUrl=w,L.publishConfig=M||{},L.checkPublishUrl())if(N)if(N.audioTrack===null)x(new b.RtsError(u.ErrorCode.ERROR_PUBLISH_NOAUDIO,"publish need audiotrack",""));else{var T=M==null?void 0:M.signalUrl;L.signalingUrl=T||L.signalingUrl,L.publishStartTimeStamp=new Date().getTime(),N.setReporter(L.reporter),L.peerconnection.createOffer(N.hasAudio,N.hasVideo||N.hasScreen,N,l(l({},M),{publishUrl:w})).then(function(O){var k=O.desp,H=O.publishTrackInfoList;L.publishTrackInfoList=H;var U=new Date().getTime();L.reporter.reportStartPublish(L.publishUrl,L.signalingUrl),L.excuteSignal(k).then(function(ee){var W=new Date().getTime();L.peerconnection.recvAnswer(ee.data,{answerSdpHook:M==null?void 0:M.answerSdpHook,tcpOnly:M==null?void 0:M.tcpOnly}).then(function(){L.reporter.reportPublishOk(L.publishUrl,L.signalingUrl,U-L.publishStartTimeStamp,W-U,new Date().getTime()-W,ee.data.trace_id),P(ee.data.trace_id),L.pubReconnectTimes=0,L.peerconnection.pushStart()}).catch(function($){$.traceid=ee.data?ee.data.trace_id:"";var B=new b.RtsError($.errorCode||u.ErrorCode.ERROR_ANSWER_ERROR,$.message||"set answer error",$.traceid,{sdp:$.sdp});x(B)})}).catch(function(ee){var W=new b.RtsError(ee.errorCode||u.ErrorCode.ERROR_HTTPREQUEST_ERROR,ee.message||"","",{response:ee.response,sdp:ee.sdp});x(W)})}).catch(function(O){var k=new b.RtsError(O.errorCode||u.ErrorCode.ERROR_CREATEOFFER,O.message||"","");x(k)})}else x(new b.RtsError(u.ErrorCode.ERROR_PUBLISH_NOSTREAM,"publish stream not found",""));else x(new b.RtsError(u.ErrorCode.ERROR_PUBLISH_URL,"url need artc://",""))})},A.prototype.unpublish=function(){this.peerconnection.reset(),this.reporter.reportStopPublish(),this.signalingUrl="",this.publishUrl="",this.publishTrackInfoList=null},A.prototype.dispose=function(){this.removeAllListeners(),this.unpublish()},A.prototype.getTrackInfoList=function(){return this.publishTrackInfoList||[]},A.prototype.getPeerConnection=function(){return this.peerconnection},A.prototype.replaceTrack=function(w,N){return this.peerconnection.replaceTrack(this.publishUrl,w,N)},A.prototype.excuteSignal=function(w){var N,M=this,D={type:w.type,sdp:w.sdp};return this.isSingleMsid()&&(D.sdp=D.sdp.replace(/msid\:-? /g,"msid:")),!((N=this.publishConfig)===null||N===void 0)&&N.cumuDelay&&(D.sdp=D.sdp.replace(/(m=video[^\n]*\n)/,`$1a=cumudelay
`)),new Promise(function(L,P){S.default.post(M.signalingUrl,{version:d.default.protocol_version,sdk_version:d.default.sdk_version,mode:"rtc",push_stream:M.publishUrl,jsep:D}).then(function(x){var T,O,k,H;if(x&&x.status===200){L(x);try{!((T=M.publishConfig)===null||T===void 0)&&T.cumuDelay&&!(!((k=(O=x.data)===null||O===void 0?void 0:O.jsep)===null||k===void 0)&&k.sdp.includes("a=cumudelay"))&&(console.warn("Not found cumudelay in server sdp"),(H=M.reporter)===null||H===void 0||H.reportCumuDelayAnswerNotFound())}catch{}}else P({message:x?"response status:"+x.status:"response is null",sdp:D.sdp})}).catch(function(x){return f(M,void 0,void 0,function(){var T,O;return v(this,function(k){switch(k.label){case 0:if(![400,500].includes((O=x.response)===null||O===void 0?void 0:O.status))return[3,4];x.sdp=w.sdp,k.label=1;case 1:return k.trys.push([1,3,,4]),[4,new y.SupportUtil().isSupport({isReceiveVideo:!0})];case 2:return k.sent(),[3,4];case 3:return T=k.sent(),x.errorCode=T==null?void 0:T.errorCode,x.message=T==null?void 0:T.message,this.pubReconnectTimes=1/0,[3,4];case 4:return P(x),[2]}})})})})},A.prototype.checkPublishUrl=function(){if(!this.publishUrl||this.publishUrl.indexOf("artc://")!==0)return!1;var w=window.location.protocol,N=(["http:","https:"].indexOf(w)>-1?w:"https:")+"//";return this.signalingUrl=this.publishUrl.replace("artc://",N),!0},A.prototype.isSingleMsid=function(){if(!this.publishConfig)return!1;var w=this.publishConfig,N=w.vMsid,M=w.aMsid;return!(!N||!N[0]||N[0].indexOf(" ")!==-1)||!(!M||!M[0]||M[0].indexOf(" ")!==-1)},A.prototype.retryPublish=function(w,N){return f(this,void 0,void 0,function(){var M,D,L,P,x,T,O;return v(this,function(k){switch(k.label){case 0:if(w.extraInfo=l(l({},w.extraInfo),{retryTimes:this.pubReconnectTimes}),!this.hasRetries())return[2,!1];if(typeof(M=this.publishConfig).beforeRetry!="function")return[3,4];k.label=1;case 1:return k.trys.push([1,3,,4]),[4,M.beforeRetry({url:this.publishUrl,stream:this.localStream,vMsid:M.vMsid,aMsid:M.aMsid,useTcp:N})];case 2:return(D=k.sent())?(L=D.url,P=D.stream,x=D.vMsid,T=D.aMsid,P||(console.error("Stream is not returned by beforeRetry function."),this.pubReconnectTimes=1/0),this.reporter.reportReconnectParams("pub",L,x,T,D.useTcp,P==null?void 0:P.id),this.publishUrl=L,this.localStream=P,this.publishConfig.vMsid=x,this.publishConfig.aMsid=T,typeof D.useTcp=="boolean"&&(N=D.useTcp),console.log(`Retry with: 
[URL] `.concat(L,`
[STREAM] `).concat(P==null?void 0:P.id,`
[VMSID]`).concat(x," [AMSID]").concat(T,`
[PROTOCOL] `).concat(N?"TCP":"UDP"))):(this.reporter.reportReconnectParams("pub"),this.pubReconnectTimes=1/0),[3,4];case 3:return O=k.sent(),console.error("Error in beforeRetry",O),[3,4];case 4:return this.hasRetries()&&this.localStream?(this.emit("connectStatusChange",{status:_.EConnectStatus.CONNECT_STATUS_RECONNECTING}),this.incrementReconnectTimes(),w.extraInfo.retryTimes=this.pubReconnectTimes,w.extraInfo.tcpOnly=!!N,this.publishWithReconnect(this.publishUrl,this.localStream,l(l({},this.publishConfig),{tcpOnly:!!N})).catch(function(H){}),[2,!0]):(w.extraInfo.retryTimes=this.pubReconnectTimes,[2,!1])}})})},A.prototype.publishWithReconnect=function(w,N,M,D,L){var P=this,x=++this.publishCallId;return new Promise(function(T,O){T=D||T,O=L||O,P.isConnecting=!0,P.publish(w,N,M,x).then(function(k){P.isConnecting=!1,T(k)}).catch(function(k){var H;if(x===P.publishCallId){if(P.peerconnection.reset(),!P.isConnecting)return O(k);if(!u.RECONNECT_ERROR_EXCLUDE_LIST.includes(k.errorCode)&&P.hasRetries(!0)){var U=((H=P.publishConfig)===null||H===void 0?void 0:H.retryInterval)||_.DEFAULT_RETRY_PUBLISH_INTERVAL;P.reconnectTimerHandle=setTimeout(function(){k.extraInfo=l(l({},k.extraInfo),{retryTimes:P.pubReconnectTimes}),P.emit("reconnect",k),P.publishWithReconnect(w,N,M,T,O)},U)}else O(k),k.extraInfo=l(l({},k.extraInfo),{retryTimes:P.pubReconnectTimes}),P.isConnecting=!1,P.cancelReconnect=!0,P.emit("onError",k)}})})},A.prototype.sendSEI=function(w){var N;(N=this.peerconnection)===null||N===void 0||N.sendSEI(w)},A.prototype.hasRetries=function(w){var N,M,D=_.DEFAULT_RETRY_PUBLISH_LIMIT;typeof((N=this.publishConfig)===null||N===void 0?void 0:N.retryTimes)=="number"&&(D=Math.floor((M=this.publishConfig)===null||M===void 0?void 0:M.retryTimes));var L=this.pubReconnectTimes<D;return w&&L&&this.incrementReconnectTimes(),L},A.prototype.resetRepublishStatus=function(){this.pubReconnectTimes=0,this.isConnecting=!1,this.reporter.updateTid(),this.reconnectTimerHandle!==null&&(clearTimeout(this.reconnectTimerHandle),this.reconnectTimerHandle=null)},A.prototype.handleSubMonitorEvent=function(w){var N=this;w.forEach(function(M){var D={ct:0,tt:4e3,url:M.url},L=M.video,P=M.audio;if(L){var x=L.transportStats,T=L.inboundRtpStats,O=L.inboundRtpStatsPerSec,k=L.localCandidate,H=L.remoteCandidate;D=l(l({},D),{rtt:(x==null?void 0:x.rtt)!==-1?1e3*((x==null?void 0:x.rtt)||0):-1,cand_re_prot:H.protocol,cand_lo_prot:k.protocol,cand_re_addr:"".concat(H.ip||H.address,":").concat(H.port),cand_lo_addr:"".concat(k.ip||k.address,":").concat(k.port),w:T==null?void 0:T.frameWidth,h:T==null?void 0:T.frameHeight,vbps:Math.floor(8*O.bytesReceivedPerSecond),fps:T==null?void 0:T.framesPerSecond,dfps:Math.floor(O==null?void 0:O.framesDecodedPerSecond),vjb:Math.floor((0,R.getJitterBufferDelayAvg)(T==null?void 0:T.jitterBufferDelay,T==null?void 0:T.jitterBufferEmittedCount)),vMsid:M.vMsid})}P&&(x=P.transportStats,T=P.inboundRtpStats,O=P.inboundRtpStatsPerSec,k=P.localCandidate,H=P.remoteCandidate,D=l(l({},D),{rtt:(x==null?void 0:x.rtt)!==-1?1e3*((x==null?void 0:x.rtt)||0):-1,cand_re_prot:H.protocol,cand_lo_prot:k.protocol,cand_re_addr:"".concat(H.ip||H.address,":").concat(H.port),cand_lo_addr:"".concat(k.ip||k.address,":").concat(k.port),abps:Math.floor(8*O.bytesReceivedPerSecond),ajb:Math.floor((0,R.getJitterBufferDelayAvg)(T==null?void 0:T.jitterBufferDelay,T.jitterBufferEmittedCount)),aMsid:M.aMsid})),N.reporter.reportPullStats(D)})},A.prototype.incrementReconnectTimes=function(){this.pubReconnectTimes++},A.prototype.getPublishConfig=function(){return this.publishConfig},A}(g.default);s.Publisher=I},5788:function(a,s,o){var c,h=this&&this.__extends||(c=function(S,R){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(E,I){E.__proto__=I}||function(E,I){for(var C in I)Object.prototype.hasOwnProperty.call(I,C)&&(E[C]=I[C])},c(S,R)},function(S,R){if(typeof R!="function"&&R!==null)throw new TypeError("Class extends value "+String(R)+" is not a constructor or null");function E(){this.constructor=S}c(S,R),S.prototype=R===null?Object.create(R):(E.prototype=R.prototype,new E)}),l=this&&this.__awaiter||function(S,R,E,I){return new(E||(E=Promise))(function(C,A){function w(D){try{M(I.next(D))}catch(L){A(L)}}function N(D){try{M(I.throw(D))}catch(L){A(L)}}function M(D){var L;D.done?C(D.value):(L=D.value,L instanceof E?L:new E(function(P){P(L)})).then(w,N)}M((I=I.apply(S,R||[])).next())})},f=this&&this.__generator||function(S,R){var E,I,C,A,w={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return A={next:N(0),throw:N(1),return:N(2)},typeof Symbol=="function"&&(A[Symbol.iterator]=function(){return this}),A;function N(M){return function(D){return function(L){if(E)throw new TypeError("Generator is already executing.");for(;A&&(A=0,L[0]&&(w=0)),w;)try{if(E=1,I&&(C=2&L[0]?I.return:L[0]?I.throw||((C=I.return)&&C.call(I),0):I.next)&&!(C=C.call(I,L[1])).done)return C;switch(I=0,C&&(L=[2&L[0],C.value]),L[0]){case 0:case 1:C=L;break;case 4:return w.label++,{value:L[1],done:!1};case 5:w.label++,I=L[1],L=[0];continue;case 7:L=w.ops.pop(),w.trys.pop();continue;default:if(C=w.trys,!((C=C.length>0&&C[C.length-1])||L[0]!==6&&L[0]!==2)){w=0;continue}if(L[0]===3&&(!C||L[1]>C[0]&&L[1]<C[3])){w.label=L[1];break}if(L[0]===6&&w.label<C[1]){w.label=C[1],C=L;break}if(C&&w.label<C[2]){w.label=C[2],w.ops.push(L);break}C[2]&&w.ops.pop(),w.trys.pop();continue}L=R.call(S,w)}catch(P){L=[6,P],I=0}finally{E=C=0}if(5&L[0])throw L[1];return{value:L[0]?L[1]:void 0,done:!0}}([M,D])}}},v=this&&this.__importDefault||function(S){return S&&S.__esModule?S:{default:S}};Object.defineProperty(s,"__esModule",{value:!0}),s.SignalChannel=void 0;var p=v(o(7028)),_=o(4865),m=v(o(102)),d=v(o(8219)),u=o(9428),b=o(5044),y=o(280),g=function(S){function R(E){var I=S.call(this)||this;return I.reporter=E.reporter,I}return h(R,S),Object.defineProperty(R.prototype,"isOpen",{get:function(){return this.readyState==="open"},enumerable:!1,configurable:!0}),Object.defineProperty(R.prototype,"readyState",{get:function(){var E,I;return((E=this.peerconnection)===null||E===void 0?void 0:E.isConnected)&&((I=this.datachannelCore)===null||I===void 0?void 0:I.readyState)},enumerable:!1,configurable:!0}),Object.defineProperty(R.prototype,"datachannelCore",{get:function(){var E,I,C;return(C=(I=(E=this.peerconnection)===null||E===void 0?void 0:E.getPeerCore())===null||I===void 0?void 0:I.getSignal())===null||C===void 0?void 0:C.getDatachannelCore()},enumerable:!1,configurable:!0}),R.prototype.getPeerConnection=function(){return this.peerconnection},R.prototype.setPeerConnection=function(E){this.peerconnection=E},R.prototype.createDatachannel=function(E){return l(this,void 0,void 0,function(){var I,C,A,w,N,M,D,L,P,x,T,O;return f(this,function(k){switch(k.label){case 0:if(I=E.signalUrl,!this.checkUrl(I))throw new b.RtsError(u.ErrorCode.ERROR_DATACHANNEL_PARAM,"url need artc://","");this.closeDatachannel(),this.createPC(),this.reporter.updateUrl(I),this.reporter.reportDatachannelHttpConnect(I),C=performance.now(),k.label=1;case 1:return k.trys.push([1,3,,4]),[4,(x=this.peerconnection)===null||x===void 0?void 0:x.createOffer(!1,!1,void 0,E)];case 2:return A=k.sent(),[3,4];case 3:return w=k.sent(),this.throwRtsError(new b.RtsError(w.errorCode||u.ErrorCode.ERROR_CREATEOFFER,w.message||"","")),[3,4];case 4:M="",k.label=5;case 5:return k.trys.push([5,7,,8]),[4,this.excuteSignal(A.desp)];case 6:return N=k.sent(),M=((T=N==null?void 0:N.data)===null||T===void 0?void 0:T.trace_id)||"",this.reporter.reportDatachannelHttpConnectOk({url:I,hrct:Math.floor(performance.now()-C),tcid:M}),[3,8];case 7:return D=k.sent(),this.throwRtsError(new b.RtsError(D.errorCode||u.ErrorCode.ERROR_HTTPREQUEST_ERROR,D.message||"",M)),[3,8];case 8:return k.trys.push([8,10,,11]),[4,(O=this.peerconnection)===null||O===void 0?void 0:O.recvAnswer(N==null?void 0:N.data,{answerSdpHook:E.answerSdpHook})];case 9:return k.sent(),[3,11];case 10:return L=k.sent(),this.throwRtsError(new b.RtsError(L.errorCode||u.ErrorCode.ERROR_ANSWER_ERROR,L.message||"set answer error",M)),[3,11];case 11:return k.trys.push([11,13,,14]),[4,this.waitForOpen()];case 12:return k.sent(),[3,14];case 13:return P=k.sent(),this.throwRtsError(new b.RtsError(u.ErrorCode.ERROR_DATACHANNEL_OPEN,"datachannel open failed: ".concat(P),M)),[3,14];case 14:return[2,M]}})})},R.prototype.waitForOpen=function(){var E,I=this;return new Promise(function(C,A){var w;E=window.setTimeout(function(){var M;(M=I.peerconnection)===null||M===void 0||M.off("datachannelStatusChange",N),E=void 0,A("timeout")},5e3);var N=function(M){E&&(clearTimeout(E),E=void 0),M.status===y.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?C(!0):A("status is ".concat(M.status))};(w=I.peerconnection)===null||w===void 0||w.once("datachannelStatusChange",N)})},R.prototype.excuteSignal=function(E){return l(this,void 0,void 0,function(){var I;return f(this,function(C){switch(C.label){case 0:return[4,d.default.post(this.signalUrl,{version:p.default.protocol_version,sdk_version:p.default.sdk_version,mode:"live",jsep:E})];case 1:if(((I=C.sent())==null?void 0:I.status)!==200)throw new b.RtsError(u.ErrorCode.ERROR_SIGNAL_ERROR,I?"response status:"+I.status:"response is null","");return[2,I]}})})},R.prototype.closeDatachannel=function(){var E;(E=this.peerconnection)===null||E===void 0||E.reset()},R.prototype.dispose=function(){this.removeAllListeners()},R.prototype.checkUrl=function(E){var I="artc://";if(E&&E.indexOf(I)===0){var C=window.location.protocol,A=(["http:","https:"].indexOf(C)>-1?C:"https:")+"//";return this.signalUrl=E.replace(I,A),!0}},R.prototype.throwRtsError=function(E){throw this.emit("onError",E),E},R.prototype.createPC=function(){var E=this;this.peerconnection=new _.RtsPeerconnection,this.peerconnection.on("connectStatusChange",function(I){E.emit("connectStatusChange",I)})},R}(m.default);s.SignalChannel=g},2550:function(a,s,o){var c,h=this&&this.__extends||(c=function(C,A){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,N){w.__proto__=N}||function(w,N){for(var M in N)Object.prototype.hasOwnProperty.call(N,M)&&(w[M]=N[M])},c(C,A)},function(C,A){if(typeof A!="function"&&A!==null)throw new TypeError("Class extends value "+String(A)+" is not a constructor or null");function w(){this.constructor=C}c(C,A),C.prototype=A===null?Object.create(A):(w.prototype=A.prototype,new w)}),l=this&&this.__assign||function(){return l=Object.assign||function(C){for(var A,w=1,N=arguments.length;w<N;w++)for(var M in A=arguments[w])Object.prototype.hasOwnProperty.call(A,M)&&(C[M]=A[M]);return C},l.apply(this,arguments)},f=this&&this.__awaiter||function(C,A,w,N){return new(w||(w=Promise))(function(M,D){function L(T){try{x(N.next(T))}catch(O){D(O)}}function P(T){try{x(N.throw(T))}catch(O){D(O)}}function x(T){var O;T.done?M(T.value):(O=T.value,O instanceof w?O:new w(function(k){k(O)})).then(L,P)}x((N=N.apply(C,A||[])).next())})},v=this&&this.__generator||function(C,A){var w,N,M,D,L={label:0,sent:function(){if(1&M[0])throw M[1];return M[1]},trys:[],ops:[]};return D={next:P(0),throw:P(1),return:P(2)},typeof Symbol=="function"&&(D[Symbol.iterator]=function(){return this}),D;function P(x){return function(T){return function(O){if(w)throw new TypeError("Generator is already executing.");for(;D&&(D=0,O[0]&&(L=0)),L;)try{if(w=1,N&&(M=2&O[0]?N.return:O[0]?N.throw||((M=N.return)&&M.call(N),0):N.next)&&!(M=M.call(N,O[1])).done)return M;switch(N=0,M&&(O=[2&O[0],M.value]),O[0]){case 0:case 1:M=O;break;case 4:return L.label++,{value:O[1],done:!1};case 5:L.label++,N=O[1],O=[0];continue;case 7:O=L.ops.pop(),L.trys.pop();continue;default:if(M=L.trys,!((M=M.length>0&&M[M.length-1])||O[0]!==6&&O[0]!==2)){L=0;continue}if(O[0]===3&&(!M||O[1]>M[0]&&O[1]<M[3])){L.label=O[1];break}if(O[0]===6&&L.label<M[1]){L.label=M[1],M=O;break}if(M&&L.label<M[2]){L.label=M[2],L.ops.push(O);break}M[2]&&L.ops.pop(),L.trys.pop();continue}O=A.call(C,L)}catch(k){O=[6,k],N=0}finally{w=M=0}if(5&O[0])throw O[1];return{value:O[0]?O[1]:void 0,done:!0}}([x,T])}}},p=this&&this.__rest||function(C,A){var w={};for(var N in C)Object.prototype.hasOwnProperty.call(C,N)&&A.indexOf(N)<0&&(w[N]=C[N]);if(C!=null&&typeof Object.getOwnPropertySymbols=="function"){var M=0;for(N=Object.getOwnPropertySymbols(C);M<N.length;M++)A.indexOf(N[M])<0&&Object.prototype.propertyIsEnumerable.call(C,N[M])&&(w[N[M]]=C[N[M]])}return w},_=this&&this.__importDefault||function(C){return C&&C.__esModule?C:{default:C}};Object.defineProperty(s,"__esModule",{value:!0}),s.LocalStream=void 0;var m=o(5805),d=o(3412),u=o(5044),b=o(9428),y=o(5259),g=o(233),S=_(o(335)),R=o(6295),E=o(2718),I=function(C){function A(){var w=C.call(this)||this;return w.screenSurfaceType="",w.VideoProfileMap=new Map(y.VideoProfileMap),w.ScreenProfileMap=new Map(y.ScreenProfileMap),w.AudioProfileMap=new Map(y.AudioProfileMap),w.deviceManager=new d.BrowserDeviceManager,w.mediastream=new MediaStream,w.hasVideo=!1,w.hasScreen=!1,w.videoProfile="360p_1",w.screenProfile="720p_1",w.audioProfile="standard",w.isCustomStream=!1,w.handleVideoTrackEnded=w.handleVideoTrackEnded.bind(w),w.handleAudioTrackEnded=w.handleAudioTrackEnded.bind(w),w}return h(A,C),Object.defineProperty(A.prototype,"mediaStream",{get:function(){return this.mediastream},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"audioTrack",{get:function(){return this.audiotrack},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"videoTrack",{get:function(){return this.videotrack},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"hasAudio",{get:function(){return!!this.audioTrack},enumerable:!1,configurable:!0}),A.prototype.getVideoProfile=function(){if(this.hasVideo)return this.videoProfile},A.prototype.getScreenProfile=function(){if(this.hasScreen)return this.screenProfile},A.prototype.getAudioProfile=function(){if(this.hasAudio)return this.audioProfile},A.prototype.init=function(w){return w.custom?this.createCustomStream(w.mediaStream):this.initWithRetry(w)},A.prototype.initWithRetry=function(w,N,M){var D=this;return new Promise(function(L,P){L=N||L,P=M||P;var x=[];w.audio&&w.video?x.push(D.initMicCamera(w)):(x.push(D.initMicAudio(w)),x.push(D.initCameraVideo(w))),w.video||x.push(D.initScreenVideoAudio(w)),Promise.all(x).then(function(){D.tryMixMicAndScreenAudio(w),D.initTracks(w),w.skipProfile?L():D.tryToSetProfile(w).then(function(){L()}).catch(function(T){console.log(T),D.resetLocalStream(),D.initWithRetry(l(l({},w),{skipProfile:!0}),L,P)})}).catch(function(T){D.stopAllTracks(),P(T)})})},A.prototype.initMicAudio=function(w){var N=this;return new Promise(function(M,D){if(!w||!w.audio)return M();var L=typeof w.audio=="boolean"?{}:w.audio;N.deviceManager.getAudioTrack(L).then(function(P){N.micAudioTrack=P,N.audiotrack=P,M()}).catch(function(P){D(new u.RtsError(P.code,P.reason,"",P.relatedLink))})})},A.prototype.initCameraVideo=function(w){var N=this;return new Promise(function(M,D){if(!w||!w.video)return M();var L=typeof w.video=="boolean"?{}:w.video;N.deviceManager.getVideoTrack(L).then(function(P){N.videotrack=P,N.hasVideo=!0,M()}).catch(function(P){D(new u.RtsError(P.code,P.reason,"",P.relatedLink))})})},A.prototype.initMicCamera=function(w){var N=this;return new Promise(function(M,D){var L={video:w.video,audio:w.audio};N.deviceManager.getAudioVideoTracks(L).then(function(P){N.videotrack=P.find(function(x){return x.kind==="video"}),N.hasVideo=!!N.videotrack,N.audiotrack=N.micAudioTrack=P.find(function(x){return x.kind==="audio"}),M()}).catch(function(P){D(new u.RtsError(P.code,P.reason,"",P.relatedLink))})})},A.prototype.initScreenVideoAudio=function(w){var N=this;return new Promise(function(M,D){if(!w||!w.screen)return M();var L=!0,P=!1,x={};if(typeof w.screen!="boolean"){var T=w.screen,O=T.video,k=T.audio;x=p(T,["video","audio"]),L=typeof O!="object"||O,typeof k!="boolean"&&typeof k!="object"||(P=k)}g.SystemUtil.isMacOS&&g.BrowserUtil.isSafari&&["16.1","16.2","16.3"].indexOf(g.BrowserUtil.browserVersion)>-1&&typeof L=="object"&&(typeof L.width=="number"&&(L.width={max:L.width}),typeof L.height=="number"&&(L.height={max:L.height})),N.deviceManager.getScreenStream(l({video:L,audio:P},x)).then(function(H){N.videotrack=H.getVideoTracks()[0],N.videotrack&&N.videotrack.getSettings&&(N.screenSurfaceType=N.videotrack.getSettings().displaySurface),N.hasScreen=!0;var U=H.getAudioTracks()[0];U&&(N.screenAudioTrack=U),M()}).catch(function(H){D(new u.RtsError(H.code,H.reason,"",H.relatedLink))})})},A.prototype.tryMixMicAndScreenAudio=function(w){w.audio&&this.micAudioTrack&&this.hasScreenAudioConfig(w)&&this.screenAudioTrack?(this.audioMixer||(this.audioMixer=new S.default({useGainNode:!1,trackList:[]})),this.audioMixer.updateTrackList([this.screenAudioTrack,this.micAudioTrack]),this.audiotrack=this.audioMixer.getMixedAudioTrack()):w.audio&&this.micAudioTrack?this.audiotrack=this.micAudioTrack:this.hasScreenAudioConfig(w)&&this.screenAudioTrack&&(this.audiotrack=this.screenAudioTrack)},A.prototype.initTracks=function(w){this.hasAudioTrackReady(w)&&this.audiotrack&&this.mediastream.addTrack(this.audiotrack),this.hasVideoTrackReady(w)&&this.videotrack&&this.mediastream.addTrack(this.videotrack),this.addTrackListener()},A.prototype.tryToSetProfile=function(w){var N=this;return new Promise(function(M,D){return f(N,void 0,void 0,function(){var L;return v(this,function(P){switch(P.label){case 0:return P.trys.push([0,4,,5]),w.video?[4,this.setVideoProfile(this.videoProfile)]:[3,2];case 1:return P.sent(),[3,3];case 2:w.screen&&this.setScreenProfile(this.screenProfile).catch(function(x){console.log(x)}),P.label=3;case 3:return M(),[3,5];case 4:return L=P.sent(),D(new u.RtsError(b.ErrorCode.ERROR_DEIVCE_CONSTRAINEDERROR,"apply constraint failed","",{originErr:L,config:w})),[3,5];case 5:return[2]}})})})},A.prototype.stopAllTracks=function(){this.screenAudioTrack&&(this.screenAudioTrack.stop(),this.screenAudioTrack=void 0),this.micAudioTrack&&(this.micAudioTrack.stop(),this.micAudioTrack=void 0),this.audioTrack&&(this.audioTrack.stop(),this.audiotrack=void 0),this.videoTrack&&(this.videoTrack.stop(),this.videotrack=void 0)},A.prototype.resetLocalStream=function(){this.deviceManager=new d.BrowserDeviceManager,this.mediastream=new MediaStream,this.hasVideo=!1,this.hasScreen=!1,this.videoProfile="360p_1",this.screenProfile="720p_1",this.isCustomStream=!1,this.stopAllTracks(),this.audioMixer=void 0,this.screenSurfaceType=""},A.prototype.setEncodeParam=function(w,N){var M=this;this.pc=w;var D=!1,L=!1;N?N==="video"?D=!0:N==="audio"&&(L=!0):D=L=!0,w.getSenders().forEach(function(P){var x=P.track;!x||x.kind!=="video"&&x.kind!=="audio"||(x.kind==="video"&&D&&M.setVideoEncodeParams(P),x.kind==="audio"&&L&&M.setAudioEncodeParams(P))})},A.prototype.setVideoEncodeParams=function(w){var N,M,D;if(((N=w.track)===null||N===void 0?void 0:N.id)===((M=this.videoTrack)===null||M===void 0?void 0:M.id)&&(this.hasVideo?D=this.VideoProfileMap.get(this.videoProfile):this.hasScreen&&(D=this.ScreenProfileMap.get(this.screenProfile)),D&&w.setParameters&&w.getParameters)){var L=w.getParameters();L.degradationPreference="maintain-resolution",L.encodings.forEach(function(P){D!=null&&D.maxBitrate&&(P.maxBitrate=1024*D.maxBitrate),D!=null&&D.frameRate&&(P.maxFramerate=D.frameRate)}),w.setParameters(L)}},A.prototype.setAudioEncodeParams=function(w){var N,M;if(((N=w.track)===null||N===void 0?void 0:N.id)===((M=this.audioTrack)===null||M===void 0?void 0:M.id)){var D=this.AudioProfileMap.get(this.audioProfile);if(D&&w.setParameters&&w.getParameters){var L=w.getParameters();L.encodings.forEach(function(P){D.maxBitrate&&(P.maxBitrate=1024*D.maxBitrate)}),w.setParameters(L)}}},A.prototype.play=function(w,N){var M,D=this;if((M=this.reporter)===null||M===void 0||M.reportPlay(w?w.nodeName:String(w)),w&&(this.element=w,this.mediastream)){if(this.element.srcObject=this.mediastream,(g.SystemUtil.isIos&&g.SystemUtil.systemVersion.indexOf("15.1")===0&&(g.BrowserUtil.isSafari||g.BrowserUtil.isChrome||g.BrowserUtil.isMicroMessenger)||(N==null?void 0:N.canvasStream))&&this.hasVideo){if(this.canvasRenderer)return;this.canvasRenderer=new R.CanvasRenderer({video:this.element});var L=this;this.element.addEventListener("loadeddata",function P(){if(L.element&&(L.element.removeEventListener("loadeddata",P),L.canvasRenderer)){L.canvasRenderer.start();var x=L.canvasRenderer.mediaStream;x&&(L.mediastream=x,L.videotrack=x.getVideoTracks()[0])}}),this.element.addEventListener("resize",function(){var P;if(D){var x=D.element;x&&((P=D.canvasRenderer)===null||P===void 0||P.resize(x.videoWidth,x.videoHeight))}})}if(N&&N.autoplay===!1)return;this.element.play()}},A.prototype.setVideoProfile=function(w){var N=this;return new Promise(function(M,D){return f(N,void 0,void 0,function(){var L,P,x;return v(this,function(T){switch(T.label){case 0:if((x=this.reporter)===null||x===void 0||x.reportVideoProfile(w),!(L=this.VideoProfileMap.get(w)))return[3,5];if(this.isCustomStream||!this.hasVideo||!this.videotrack||!this.videotrack.applyConstraints)return[3,4];T.label=1;case 1:return T.trys.push([1,3,,4]),[4,this.videotrack.applyConstraints(L)];case 2:return T.sent(),[3,4];case 3:return P=T.sent(),[2,D(P)];case 4:return this.videoProfile=w,this.pc&&this.setEncodeParam(this.pc,"video"),M(this.videoProfile),[3,6];case 5:D("Profile not found"),T.label=6;case 6:return[2]}})})})},A.prototype.setScreenProfile=function(w){var N=this;return new Promise(function(M,D){return f(N,void 0,void 0,function(){var L,P,x;return v(this,function(T){switch(T.label){case 0:if((x=this.reporter)===null||x===void 0||x.reportScreenProfile(w),!(L=this.ScreenProfileMap.get(w)))return[3,5];if(!(this.hasScreen&&this.videotrack&&this.videotrack.applyConstraints))return[3,4];T.label=1;case 1:return T.trys.push([1,3,,4]),[4,this.videotrack.applyConstraints(L)];case 2:return T.sent(),[3,4];case 3:return P=T.sent(),[2,D(P)];case 4:return this.screenProfile=w,this.pc&&this.setEncodeParam(this.pc,"video"),M(this.screenProfile),[3,6];case 5:D("Profile not found"),T.label=6;case 6:return[2]}})})})},A.prototype.setAudioProfile=function(w){var N=this;return new Promise(function(M,D){return f(N,void 0,void 0,function(){var L,P,x;return v(this,function(T){switch(T.label){case 0:if((x=this.reporter)===null||x===void 0||x.reportAudioProfile(w),!(L=this.AudioProfileMap.get(w)))return[3,5];if(this.isCustomStream||!this.hasAudio||!this.audioTrack||!this.audioTrack.applyConstraints)return[3,4];T.label=1;case 1:return T.trys.push([1,3,,4]),[4,this.audioTrack.applyConstraints(L)];case 2:return T.sent(),[3,4];case 3:return P=T.sent(),[2,D(P)];case 4:return this.audioProfile=w,this.pc&&this.setEncodeParam(this.pc,"audio"),M(this.audioProfile),[3,6];case 5:D("Profile not found"),T.label=6;case 6:return[2]}})})})},A.prototype.enableAudio=function(){var w;return(w=this.reporter)===null||w===void 0||w.reportEnableAudio(),!!this.audiotrack&&(this.audiotrack.enabled=!0,!0)},A.prototype.disableAudio=function(){var w;return(w=this.reporter)===null||w===void 0||w.reportDisableAudio(),!!this.audiotrack&&(this.audiotrack.enabled=!1,!0)},A.prototype.enableVideo=function(){var w;return(w=this.reporter)===null||w===void 0||w.reportEnableVideo(),!!this.videotrack&&(this.videotrack.enabled=!0,!0)},A.prototype.disableVideo=function(){var w;return(w=this.reporter)===null||w===void 0||w.reportDisableVideo(),!!this.videotrack&&(this.videotrack.enabled=!1,!0)},A.prototype.stop=function(){var w;C.prototype.stop.call(this),this.hasVideo=!1,this.hasScreen=!1,this.isCustomStream=!1,this.canvasRenderer&&(this.canvasRenderer.stop(),this.canvasRenderer=void 0),this.audiotrack&&(this.audiotrack.stop(),this.audiotrack=void 0),this.videotrack&&(this.videotrack.stop(),this.videotrack=void 0),this.micAudioTrack&&(this.micAudioTrack.stop(),this.micAudioTrack=void 0),this.screenAudioTrack&&(this.screenAudioTrack.stop(),this.screenAudioTrack=void 0),(w=this.reporter)===null||w===void 0||w.reportStop(0)},A.prototype.mergeStream=function(w){var N=w.videoTrack,M=w.audioTrack;N&&(this.videoTrack&&(this.videoTrack.removeEventListener("ended",this.handleVideoTrackEnded),this.mediaStream.removeTrack(this.videoTrack)),this.mediaStream.addTrack(N),this.videotrack=N,this.listenVideoEnded(),this.hasVideo=w.hasVideo,this.hasScreen=w.hasScreen,this.isCustomStream=w.isCustomStream,this.hasVideo&&(this.videoProfile=w.videoProfile),this.hasScreen&&(this.screenProfile=w.screenProfile)),M&&(this.audioTrack&&(this.audioTrack.removeEventListener("ended",this.handleAudioTrackEnded),this.mediaStream.removeTrack(this.audioTrack)),this.mediaStream.addTrack(M),this.audiotrack=M,this.listenAudioEnded())},A.prototype.deleteTracks=function(w){w.audio&&this.audioTrack&&(this.mediaStream.removeTrack(this.audioTrack),this.audiotrack=void 0),w.video&&this.videoTrack&&(this.mediaStream.removeTrack(this.videoTrack),this.videotrack=void 0,this.hasScreen=!1,this.hasVideo=!1)},A.prototype.createCustomStream=function(w){var N=this;return new Promise(function(M,D){if(!w)return D(new u.RtsError(b.ErrorCode.ERROR_CUSTOMSTREAM_NONE,"MediaStream is required.",""));if(!(w instanceof MediaStream))return D(new u.RtsError(b.ErrorCode.ERROR_CUSTOMSTREAM_INVALID,"MediaStream is invalid.",""));if(w.getTracks().length===0)return D(new u.RtsError(b.ErrorCode.ERROR_CUSTOMSTREAM_TRACK_NONE,"MediaStream has no track.",""));var L=(0,E.getVideoTrack)(w),P=(0,E.getAudioTrack)(w);L&&(N.hasVideo=!0,N.videotrack=L,N.mediastream.addTrack(L)),P&&(N.audiotrack=P,N.mediastream.addTrack(P)),N.isCustomStream=!0,N.setVideoProfile(N.videoProfile),N.addTrackListener(),M()})},A.prototype.releaseMediaStream=function(){var w=this;this.mediastream.getTracks().forEach(function(N){N.stop(),w.mediastream.removeTrack(N)})},A.prototype.hasVideoTrackReady=function(w){return!(!w.video&&!w.screen||!this.videotrack)||!w.video&&!w.screen},A.prototype.hasScreenAudioConfig=function(w){return typeof w.screen=="object"&&w.screen.audio},A.prototype.hasAudioTrackReady=function(w){return!(w.audio&&(!this.hasMicAudioAndReady(w)&&!this.hasScreenAudioAndReady(w)||!this.audiotrack))},A.prototype.hasMicAudioAndReady=function(w){return w.audio&&this.micAudioTrack},A.prototype.hasScreenAudioAndReady=function(w){return this.hasScreenAudioConfig(w)&&this.screenAudioTrack},A.prototype.addTrackListener=function(){this.listenVideoEnded(),this.listenAudioEnded()},A.prototype.listenVideoEnded=function(){var w=this;this.videotrack&&this.videotrack.addEventListener("ended",this.handleVideoTrackEnded),this.micAudioTrack&&this.micAudioTrack.addEventListener("ended",function(){var N;w.emit("micAudioTrackEnded"),w.screenAudioTrack&&w.screenAudioTrack.readyState==="ended"&&((N=w.audioMixer)===null||N===void 0||N.destroy(),w.emit("audioTrackEnded"))}),this.screenAudioTrack&&this.screenAudioTrack.addEventListener("ended",function(){var N;w.emit("screenAudioTrackEnded"),w.micAudioTrack&&w.micAudioTrack.readyState==="ended"&&((N=w.audioMixer)===null||N===void 0||N.destroy(),w.emit("audioTrackEnded"))})},A.prototype.listenAudioEnded=function(){this.audiotrack&&this.audiotrack.addEventListener("ended",this.handleAudioTrackEnded)},A.prototype.handleVideoTrackEnded=function(){this.hasScreen=!1,this.hasVideo=!1,this.emit("videoTrackEnded")},A.prototype.handleAudioTrackEnded=function(){this.emit("audioTrackEnded")},A}(m.Stream);s.LocalStream=I},771:function(a,s,o){var c,h=this&&this.__extends||(c=function(m,d){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,b){u.__proto__=b}||function(u,b){for(var y in b)Object.prototype.hasOwnProperty.call(b,y)&&(u[y]=b[y])},c(m,d)},function(m,d){if(typeof d!="function"&&d!==null)throw new TypeError("Class extends value "+String(d)+" is not a constructor or null");function u(){this.constructor=m}c(m,d),m.prototype=d===null?Object.create(d):(u.prototype=d.prototype,new u)});Object.defineProperty(s,"__esModule",{value:!0}),s.RemoteStream=void 0;var l=o(5805),f=o(233),v=o(5044),p=o(9428),_=function(m){function d(){var u=m.call(this)||this;return u.recvCanPlay=!1,u.autoplay=!0,u.onCanPlay=u.onCanPlay.bind(u),u}return h(d,m),Object.defineProperty(d.prototype,"muted",{get:function(){return!!this.element&&this.element.muted},set:function(u){this.element&&(this.element.muted=u)},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"audioTrack",{get:function(){var u;return(u=this.mediastream)===null||u===void 0?void 0:u.getAudioTracks()[0]},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"videoTrack",{get:function(){var u;return(u=this.mediastream)===null||u===void 0?void 0:u.getVideoTracks()[0]},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"hasVideo",{get:function(){return!!this.videoTrack},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"hasAudio",{get:function(){return!!this.audioTrack},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"mediaStream",{get:function(){return this.mediastream},enumerable:!1,configurable:!0}),d.prototype.updateMediaStream=function(u){var b=this.mediastream||new MediaStream;u.getTracks().forEach(function(y){return b.addTrack(y)}),this.mediastream=b,this.element&&this.play(this.element)},d.prototype.getMediaStream=function(){return this.mediastream},d.prototype.mergeStream=function(u){if(this.mediaStream){var b=u.getVideoTracks()[0],y=u.getAudioTracks()[0];b&&(this.videoTrack&&this.mediaStream.removeTrack(this.videoTrack),this.mediaStream.addTrack(b),this.videotrack=b),y&&(this.audioTrack&&this.mediaStream.removeTrack(this.audioTrack),this.mediaStream.addTrack(y),this.audiotrack=y)}},d.prototype.play=function(u,b){if(this.autoplay=!!(!b||b.autoplay),u){if(!(u instanceof HTMLMediaElement))throw new v.RtsError(p.ErrorCode.ERROR_HTMLELEMENT_ERROR,"Param is not a HTMLMediaElement","",{element:u});this.recvCanPlay=!1,this.emit("mediaElementBinded"),this.element=u,this.element.addEventListener("canplay",this.onCanPlay);var y=this.mediaStream;this.element.addEventListener("playing",function g(){u.removeEventListener("playing",g),f.SystemUtil.isIos&&parseInt(f.SystemUtil.systemVersion)<=13&&!u.muted&&(y!=null&&y.getAudioTracks().length)&&(u.pause(),u.play())}),this.element.nodeName==="VIDEO"&&(this.element.setAttribute("playsinline",""),f.BrowserUtil.isMicroMessenger&&(this.element.setAttribute("x5-video-player-type","h5-page"),this.element.setAttribute("x5-playsinline",""),f.SystemUtil.isAndroid||f.SystemUtil.isIos&&this.element.setAttribute("x-webkit-airplay","allow"))),this.autoplay&&f.BrowserUtil.isSafari&&this.element.setAttribute("autoplay",""),this.mediastream&&this.bindMediaStream(this.mediastream)}else this.release()},d.prototype.disableVideo=function(){var u=this.getMediaStream();u&&u.getVideoTracks().forEach(function(b){b.enabled&&(b.enabled=!1)})},d.prototype.enableVideo=function(){var u=this.getMediaStream();u&&u.getVideoTracks().forEach(function(b){b.enabled||(b.enabled=!0)})},d.prototype.disableAudio=function(){var u=this.getMediaStream();u&&u.getAudioTracks().forEach(function(b){b.enabled&&(b.enabled=!1)})},d.prototype.enableAudio=function(){var u=this.getMediaStream();u&&u.getAudioTracks().forEach(function(b){b.enabled||(b.enabled=!0)})},d.prototype.stop=function(){m.prototype.stop.call(this),this.release()},d.prototype.onCanPlay=function(){var u=this;if(!this.recvCanPlay&&(this.emit("onCanPlay"),this.recvCanPlay=!0,this.autoplay))if(this.element)if(f.BrowserUtil.isMicroMessenger){var b=window.top!==window.self,y=window.WeixinJSBridge||window.top.WeixinJSBridge;y?y.invoke("getNetworkType",{},function(){u.tryToPlay()}):(b?window.top.document:document).addEventListener("WeixinJSBridgeReady",function(){y.invoke("getNetworkType",{},function(){u.tryToPlay()})})}else this.tryToPlay();else this.tryToPlay()},d.prototype.release=function(){this.element&&(this.element.pause(),this.element.srcObject=null,this.element.load(),this.element.removeEventListener("canplay",this.onCanPlay)),this.recvCanPlay=!1,this.mediastream=void 0},d.prototype.bindMediaStream=function(u){this.element&&(this.element.nodeName==="AUDIO"&&u.getVideoTracks()[0]&&u.removeTrack(u.getVideoTracks()[0]),this.element.srcObject=u),this.mediastream=u},d.prototype.tryToPlay=function(){var u=this;if(this.element){var b=this.element.play();b!==void 0&&b.then(function(){}).catch(function(y){console.log("playPromise err",y),u.element&&u.element.srcObject&&u.emit("onAutoPlayError")})}},d}(l.Stream);s.RemoteStream=_},5805:function(a,s,o){var c,h=this&&this.__extends||(c=function(p,_){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(m,d){m.__proto__=d}||function(m,d){for(var u in d)Object.prototype.hasOwnProperty.call(d,u)&&(m[u]=d[u])},c(p,_)},function(p,_){if(typeof _!="function"&&_!==null)throw new TypeError("Class extends value "+String(_)+" is not a constructor or null");function m(){this.constructor=p}c(p,_),p.prototype=_===null?Object.create(_):(m.prototype=_.prototype,new m)}),l=this&&this.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(s,"__esModule",{value:!0}),s.Stream=void 0;var f=o(233),v=function(p){function _(){var m=p.call(this)||this;return m.traceid="",m.id=f.Guid.create(32),m}return h(_,p),Object.defineProperty(_.prototype,"traceId",{get:function(){return this.traceid},set:function(m){this.traceid=m},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"mediaElement",{get:function(){return this.element},enumerable:!1,configurable:!0}),_.prototype.setReporter=function(m){this.reporter=m},_.prototype.play=function(m){},_.prototype.stop=function(){this.traceid="",this.reporter=void 0},_}(l(o(102)).default);s.Stream=v},5676:function(a,s,o){var c,h=this&&this.__extends||(c=function(D,L){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(P,x){P.__proto__=x}||function(P,x){for(var T in x)Object.prototype.hasOwnProperty.call(x,T)&&(P[T]=x[T])},c(D,L)},function(D,L){if(typeof L!="function"&&L!==null)throw new TypeError("Class extends value "+String(L)+" is not a constructor or null");function P(){this.constructor=D}c(D,L),D.prototype=L===null?Object.create(L):(P.prototype=L.prototype,new P)}),l=this&&this.__assign||function(){return l=Object.assign||function(D){for(var L,P=1,x=arguments.length;P<x;P++)for(var T in L=arguments[P])Object.prototype.hasOwnProperty.call(L,T)&&(D[T]=L[T]);return D},l.apply(this,arguments)},f=this&&this.__awaiter||function(D,L,P,x){return new(P||(P=Promise))(function(T,O){function k(ee){try{U(x.next(ee))}catch(W){O(W)}}function H(ee){try{U(x.throw(ee))}catch(W){O(W)}}function U(ee){var W;ee.done?T(ee.value):(W=ee.value,W instanceof P?W:new P(function($){$(W)})).then(k,H)}U((x=x.apply(D,L||[])).next())})},v=this&&this.__generator||function(D,L){var P,x,T,O,k={label:0,sent:function(){if(1&T[0])throw T[1];return T[1]},trys:[],ops:[]};return O={next:H(0),throw:H(1),return:H(2)},typeof Symbol=="function"&&(O[Symbol.iterator]=function(){return this}),O;function H(U){return function(ee){return function(W){if(P)throw new TypeError("Generator is already executing.");for(;O&&(O=0,W[0]&&(k=0)),k;)try{if(P=1,x&&(T=2&W[0]?x.return:W[0]?x.throw||((T=x.return)&&T.call(x),0):x.next)&&!(T=T.call(x,W[1])).done)return T;switch(x=0,T&&(W=[2&W[0],T.value]),W[0]){case 0:case 1:T=W;break;case 4:return k.label++,{value:W[1],done:!1};case 5:k.label++,x=W[1],W=[0];continue;case 7:W=k.ops.pop(),k.trys.pop();continue;default:if(T=k.trys,!((T=T.length>0&&T[T.length-1])||W[0]!==6&&W[0]!==2)){k=0;continue}if(W[0]===3&&(!T||W[1]>T[0]&&W[1]<T[3])){k.label=W[1];break}if(W[0]===6&&k.label<T[1]){k.label=T[1],T=W;break}if(T&&k.label<T[2]){k.label=T[2],k.ops.push(W);break}T[2]&&k.ops.pop(),k.trys.pop();continue}W=L.call(D,k)}catch($){W=[6,$],x=0}finally{P=T=0}if(5&W[0])throw W[1];return{value:W[0]?W[1]:void 0,done:!0}}([U,ee])}}},p=this&&this.__importDefault||function(D){return D&&D.__esModule?D:{default:D}};Object.defineProperty(s,"__esModule",{value:!0}),s.Subscriber=void 0;var _,m=o(4865),d=o(5917),u=o(9428),b=p(o(8219)),y=p(o(102)),g=o(5044),S=o(7989),R=o(492),E=p(o(2818)),I=p(o(7028)),C=o(6091),A=o(771),w=o(2718),N=p(o(1401));(function(D){D[D.Init=0]="Init",D[D.Requesting=1]="Requesting",D[D.Playing=2]="Playing",D[D.Waiting=3]="Waiting"})(_||(_={}));var M=function(D){function L(P,x){var T=D.call(this)||this;return T.monitorStatsHistory=[],T.playTimeIndex=0,T.playCatonIndex=0,T.reportPubFlag=!1,T.state=_.Init,T.subscribeAudio=!0,T.subscribeVideo=!0,T.signalingUrl="",T.pullStreamUrl="",T.noParsePullStreamUrl="",T.subReconnectTimes=0,T.isConnecting=!1,T.cancelReconnect=!1,T.reconnectTimerHandle=null,T.subscribeCallId=0,T.reporter=P,T.playTimer=0,T.config=x||{playTimeOut:5e3},T.remoteStream=new A.RemoteStream,T.remoteStream.on("onAutoPlayError",function(){T.emit("onError",new g.RtsError(u.ErrorCode.ERROR_AUTOPLAY_ERROR,"auto play failed",""))}),T.remoteStream.on("onCanPlay",function(){return f(T,void 0,void 0,function(){var O,k,H,U,ee,W,$,B,F,G,q;return v(this,function(X){switch(X.label){case 0:return O=new Date().getTime(),[4,this.peerconnection.sample()];case 1:return X.sent(),k=-1,H=[],U=-1,this.monitorStatsHistory&&this.monitorStatsHistory.length&&(ee=this.monitorStatsHistory[this.monitorStatsHistory.length-1],this.monitorStatsHistory.forEach(function(J){var se=J.rtt;se&&se>0&&H.push(se)}),k=Number((H.reduce(function(J,se){return J+se},0)/H.length).toFixed(3)),U=ee.packetsLost,this.monitorStatsHistory=null),this.stopPlayTimer(),this.peerconnection.playStart(),this.subReconnectTimes=0,W=this._cnend||O,this.reporter.reportFirstFrameTime(this.noParsePullStreamUrl,this.remoteStream.traceId,this._cpend-this._cpstart,this._hrend-this._cpend,O-this._cpstart,0,W-this._hrend,{rttAvg:k,packetsLost:U},-1,-1,-1,(B=this.subscribeConfig)===null||B===void 0?void 0:B.vMsid,(F=this.subscribeConfig)===null||F===void 0?void 0:F.aMsid),($=new C.PlayEvent(C.PlayType.PLAY_CANPLAY)).data={url:this.noParsePullStreamUrl,vMsid:(G=this.subscribeConfig)===null||G===void 0?void 0:G.vMsid,aMsid:(q=this.subscribeConfig)===null||q===void 0?void 0:q.aMsid},this.emit("onPlayEvent",$),[2]}})})}),T.peerconnection=new m.RtsPeerconnection,T.peerconnection.on("onConnected",function(){T._cnend=new Date().getTime()}),T.peerconnection.on("streamEnded",function(O){var k=new C.PlayEvent(C.PlayType.PLAY_ENDED);k.data=l({},O),T.emit("onPlayEvent",k),T.emit("onError",new g.RtsError(u.ErrorCode.ERROR_STREAM_ENDED,"Stream Receiver Transport is Closed",T.remoteStream.traceId))}),T.peerconnection.on("onTrackEvent",function(O){O.streams&&O.streams.length&&(T.remoteStream.updateMediaStream(O.streams[0]),T.onTrackFunction&&T.onTrackFunction())}),T.peerconnection.on("connectStatusChange",function(O){if(O.status!==d.EConnectStatus.CONNECT_STATUS_DISCONNECTED&&O.status!==d.EConnectStatus.CONNECT_STATUS_RECONNECTING||!T.hasRetries())T.emit("connectStatusChange",O);else{var k=O.status===d.EConnectStatus.CONNECT_STATUS_RECONNECTING;T.emit("onError",new g.RtsError(u.ErrorCode.ERROR_PC_DISCONNECTED,"PC disconnected",T.remoteStream.traceId,{fromSystemEvent:k}))}}),T.peerconnection.on("pcReconnect",function(O){var k,H;O.ips?(k="Migrate with ips: ".concat((0,N.default)(O.ips)),H=u.ErrorCode.ERROR_IP_MIGRATE):(k="PC disconnected",H=u.ErrorCode.ERROR_PC_DISCONNECTED),T.emit("onError",new g.RtsError(H,k,"",{pcErrorInfo:O}))}),T.mediaObserver=new R.MediaObserver({handler:function(O,k,H){var U,ee=new C.PlayEvent(C.PlayType.PLAY_TIMEOUT),W={url:O};k&&(W.vMsid=k),H&&(W.aMsid=H),ee.data=W,T.emit("onPlayEvent",ee);var $=new g.RtsError(u.ErrorCode.ERROR_INBOUND_TIMEOUT,"Media data timeout after ".concat((U=T.mediaObserver)===null||U===void 0?void 0:U.actTimeout," ms."),T.remoteStream.traceId);T.emit("onError",$)}}),T.peerconnection.on("onMonitorEvent",function(O){var k,H=O.eventList;if((k=T.peerconnection)===null||k===void 0||k.updateStatsForSEI(H,O.type),O.type!=="pub"){if(H.length){for(var U=void 0,ee=0;ee<H.length;ee++)if(H[ee].url===(0,w.pruneSubUrl)(T.noParsePullStreamUrl,!0)){U=H[ee];break}if(U){T.lastMeidaEventData=U;var W=U.video,$=U.audio;W&&T.monitorStatsHistory?T.monitorStatsHistory.push({rtt:W.transportStats.rtt,packetsLost:W.inboundRtpStats.packetsLost}):$&&T.monitorStatsHistory&&T.monitorStatsHistory.push({rtt:$.transportStats.rtt,packetsLost:$.inboundRtpStats.packetsLost}),_.Requesting===T.state?U.video?U.video.inboundRtpStatsPerSec.framesDecodedPerSecond>1&&(T.state=_.Playing):U.audio&&U.audio.inboundRtpStatsPerSec.bytesReceivedPerSecond>0&&(T.state=_.Playing):T.state!==_.Playing&&T.state!==_.Waiting||(++T.playTimeIndex,U.video&&(U.video.inboundRtpStatsPerSec.framesDecodedPerSecond<=1?(++T.playCatonIndex,_.Waiting!==T.state&&(T.state=_.Waiting,T.emit("onPlayEvent",new C.PlayEvent(C.PlayType.PLAY_WAITING)))):_.Waiting===T.state&&(T.state=_.Playing,T.emit("onPlayEvent",new C.PlayEvent(C.PlayType.PLAY_PLAYING)))),E.default.HEARTHEAT_INTERVAL===T.playTimeIndex&&(T.reportPubFlag=!0,H.forEach(function(F){T.doReportPullStats(F)}),T.playTimeIndex=0,T.playCatonIndex=0))}var B=new C.PlayEvent(C.PlayType.PLAY_MEDIA);B.data=[],H.forEach(function(F){var G={};G.url=F.url;var q=T.calcStreamPullStats(F);if(F.audio&&(G.audio={bytesReceivedPerSecond:F.audio.inboundRtpStatsPerSec.bytesReceivedPerSecond,rtt:F.audio.transportStats.rtt,lossRate:q.aloss,jitterBufferDelayAvg:F.audio.inboundRtpStatsPerSec.jitterBufferDelayAvg},G.aMsid=F.aMsid),F.video){var X=F.video,J=X.inboundRtpStats,se=X.inboundRtpStatsPerSec,ce=X.transportStats;G.video={bytesReceivedPerSecond:se.bytesReceivedPerSecond,fps:J.framesPerSecond||se.framesDecodedPerSecond,framesDecodedPerSecond:se.framesDecodedPerSecond,rtt:ce.rtt,width:J.frameWidth,height:J.frameHeight,lossRate:q.vloss,jitterBufferDelayAvg:se.jitterBufferDelayAvg},G.vMsid=F.vMsid}G.networkQuality=q.net_qual||0,B.data.push(G)}),B.data&&B.data.length&&(B.data.forEach(function(F){var G;(G=T.mediaObserver)===null||G===void 0||G.check({audio:F.audio,video:F.video},F.url,F.vMsid,F.aMsid)}),B.data.length===1&&(B.data[0].audio||B.data[0].video)&&(B.data=l({},B.data[0])),T.emit("onPlayEvent",B))}}else T.reportPubFlag&&(T.reportPubFlag=!1)}),T.playTimer=0,T._cpstart=0,T._cpend=0,T._hrend=0,T._cnend=0,T.subscribeConfig={},T}return h(L,D),L.prototype.getPeerConnection=function(){return this.peerconnection},L.prototype.subscribe=function(P,x,T,O){var k=this;return new Promise(function(H,U){return f(k,void 0,void 0,function(){var ee,W,$=this;return v(this,function(B){switch(B.label){case 0:return this.monitorStatsHistory=[],this.unsubscribe(),x!=null&&x.cumuDelay&&(x.encodedInsertableStreams=!0),this.subscribeConfig=x||{},this.state=_.Requesting,this.noParsePullStreamUrl=P,this.parseUrl(P),(W=this.mediaObserver)===null||W===void 0||W.updateConfig({timeout:x==null?void 0:x.mediaTimeout}),ee=x==null?void 0:x.signalUrl,this.signalingUrl=ee||this.signalingUrl,this.checkPullUrl()?[3,1]:(U(new g.RtsError(u.ErrorCode.ERROR_PLAY_URL,"url need artc://","")),[3,8]);case 1:return this.subscribeAudio||this.subscribeVideo?[3,2]:(U(new g.RtsError(u.ErrorCode.ERROR_SUBSCRIBE_NOTHING,"subscribe nothing","")),[3,8]);case 2:if(this._cpstart=new Date().getTime(),!this.subscribeVideo||(x==null?void 0:x.isH264Checked))return[3,7];B.label=3;case 3:return B.trys.push([3,5,,6]),[4,new S.SupportUtil().loadH264(3)];case 4:return B.sent(),[3,6];case 5:return B.sent(),[3,6];case 6:B.label=7;case 7:this.peerconnection.createOffer(this.subscribeAudio,this.subscribeVideo,void 0,{offerSdpHook:x==null?void 0:x.offerSdpHook,answerSdpHook:x==null?void 0:x.answerSdpHook,encodedInsertableStreams:x==null?void 0:x.encodedInsertableStreams,disableStereo:x==null?void 0:x.disableStereo,disableHeartbeat:x==null?void 0:x.disableHeartbeat,cumuDelay:x==null?void 0:x.cumuDelay,heartbeat:x==null?void 0:x.heartbeat}).then(function(F){var G=F.desp;$._cpend=new Date().getTime(),$.reporter.reportSubscribeStart($.noParsePullStreamUrl,$.signalingUrl,x==null?void 0:x.vMsid,x==null?void 0:x.aMsid),$.excuteSignal(G,{innerTcpOnly:!!(T!=null&&T.innerTcpOnly)}).then(function(q){var X;$.remoteStream.traceId=q,H($.remoteStream);try{(X=$.peerconnection.getPeerCore())===null||X===void 0||X.patchSubscribeStreamManagerRecord($.noParsePullStreamUrl,l(l({},$.subscribeConfig),{stream:$.remoteStream}))}catch(J){console.log(J)}$.peerconnection.getSubMonitor().updateTranceiversController()}).catch(function(q){$._hrend=new Date().getTime();var X=new g.RtsError(q.errorCode?q.errorCode:u.ErrorCode.ERROR_HTTPREQUEST_ERROR,q.message,q?q.traceid:"",{response:q.response,sdp:q.sdp});U(X)})}).catch(function(F){$._cpend=new Date().getTime();var G=new g.RtsError(u.ErrorCode.ERROR_CREATEOFFER,F.message,"");U(G)}),B.label=8;case 8:return[2]}})})})},L.prototype.unsubscribe=function(){var P;this.lastMeidaEventData&&this.doReportPullStats(this.lastMeidaEventData),this.stopPlayTimer(),this.peerconnection.reset(),this.remoteStream.stop(),this.subscribeVideo=!0,this.subscribeAudio=!0,this.state=_.Init,this.signalingUrl="",this.pullStreamUrl="",this.noParsePullStreamUrl="",this.onTrackFunction=void 0,this.playTimer=0,this._cpstart=0,this._cpend=0,this._hrend=0,this._cnend=0,this.monitorStatsHistory=[],(P=this.mediaObserver)===null||P===void 0||P.reset()},L.prototype.dispose=function(){this.removeAllListeners(),this.unsubscribe()},L.prototype.startLiveStream=function(P,x,T){var O=this;return console.error("此API可能存在稳定性问题,并将在未来的版本移除。请使用subscribe替代,详细用法请参考官方文档。"),new Promise(function(k,H){O.unsubscribe(),O.state=_.Requesting,O.noParsePullStreamUrl=P,O.parseUrl(P);var U=T==null?void 0:T.signalUrl;O.signalingUrl=U||O.signalingUrl,O.pullStreamUrl===""?H(new g.RtsError(u.ErrorCode.ERROR_PLAY_URL,"url need artc://","")):O.subscribeAudio||O.subscribeVideo?!x||x.nodeName!=="AUDIO"&&x.nodeName!=="VIDEO"?H(new g.RtsError(u.ErrorCode.ERROR_HTMLELEMENT_ERROR,"need htmlaudioelement or htmlvideoelement","")):(O.subscribeAudio&&O.subscribeVideo?x.nodeName!=="VIDEO"&&O.emit("onError",new g.RtsError(u.ErrorCode.ERROR_HEMLELEMENT_NOTMATCH,"need htmlvideoelement","")):O.subscribeAudio?x.nodeName!=="AUDIO"&&O.emit("onError",new g.RtsError(u.ErrorCode.ERROR_HEMLELEMENT_NOTMATCH,"need htmlaudioelement","")):x.nodeName!=="VIDEO"&&O.emit("onError",new g.RtsError(u.ErrorCode.ERROR_HEMLELEMENT_NOTMATCH,"need htmlvieoelement","")),O._cpstart=new Date().getTime(),O.reporter.updateTid(),O.peerconnection.createOffer(O.subscribeAudio,O.subscribeVideo).then(function(ee){var W=ee.desp;O._cpend=new Date().getTime(),O.excuteSignal(W).then(function($){O.remoteStream.traceId=$,O._hrend=new Date().getTime(),O.remoteStream.play(x),k($)}).catch(function($){O._hrend=new Date().getTime(),O.reporter.reportFirstFrameTime(O.noParsePullStreamUrl,$?$.traceid:"",O._cpend-O._cpstart,O._hrend-O._cpend,-1,-1,O._cnend-O._hrend),H(new g.RtsError($.errorCode?$.errorCode:u.ErrorCode.ERROR_HTTPREQUEST_ERROR,$.message,""))})}).catch(function(ee){O._cpend=new Date().getTime(),O.reporter.reportFirstFrameTime(O.noParsePullStreamUrl,ee?ee.traceid:"",O._cpend-O._cpstart,-1,-1,-1,O._cnend-O._hrend),H(new g.RtsError(u.ErrorCode.ERROR_CREATEOFFER,ee.message,""))})):H(new g.RtsError(u.ErrorCode.ERROR_SUBSCRIBE_NOTHING,"subscribe nothing",""))})},L.prototype.stopLiveStream=function(){this.unsubscribe()},L.prototype.muteLiveStream=function(P){return this.remoteStream.muted=P,!0},L.prototype.excuteSignal=function(P,x){var T=this,O={type:P.type,sdp:P.sdp};return new Promise(function(k,H){var U,ee,W,$,B,F={url:T.pullStreamUrl,amsid:((U=T.subscribeConfig)===null||U===void 0?void 0:U.aMsid)||["rts audio"],vmsid:((ee=T.subscribeConfig)===null||ee===void 0?void 0:ee.vMsid)||["rts video"]};T.subscribeAudio||delete F.amsid,T.subscribeVideo||delete F.vmsid,!((W=T.subscribeConfig)===null||W===void 0)&&W.cumuDelay&&(O.sdp=O.sdp.replace(/(m=video[^\n]*\n)/,`$1a=cumudelay
`)),b.default.post(T.signalingUrl,{version:(($=T.subscribeConfig)===null||$===void 0?void 0:$.signalVersion)||I.default.protocol_version,sdk_version:I.default.sdk_version,mode:((B=T.subscribeConfig)===null||B===void 0?void 0:B.signalMode)||"live",pull_streams:[F],jsep:O}).then(function(G){var q,X,J,se,ce,Y,fe,he,pe,ue,Te;if(G&&G.status===200){T._hrend=new Date().getTime();try{!((q=T.subscribeConfig)===null||q===void 0)&&q.cumuDelay&&!(!((J=(X=G.data)===null||X===void 0?void 0:X.jsep)===null||J===void 0)&&J.sdp.includes("a=cumudelay"))&&(console.warn("Not found cumudelay in server sdp"),(se=T.reporter)===null||se===void 0||se.reportCumuDelayAnswerNotFound())}catch{}var be=(ce=G.data)===null||ce===void 0?void 0:ce.trace_id;T.reporter.reportSubscribeOk({vurl:T.noParsePullStreamUrl,surl:T.signalingUrl,traceId:be,hrct:T._hrend-T._cpend,rslt:(Y=G.data)===null||Y===void 0?void 0:Y.code});var Z=typeof((fe=T.subscribeConfig)===null||fe===void 0?void 0:fe.tcpOnly)=="boolean"?T.subscribeConfig.tcpOnly:x==null?void 0:x.innerTcpOnly;if(!((pe=(he=G.data)===null||he===void 0?void 0:he.jsep)===null||pe===void 0)&&pe.sdp){var K=T.signalingUrl.split("?")[0].split("/").pop();G.data.jsep.sdp=G.data.jsep.sdp.replace(/msid:\S+/g,"msid:".concat(K)).replace(/mslabel:\S+/g,"mslabel:".concat(K))}T.peerconnection.recvAnswer(G.data,{answerSdpHook:(ue=T.subscribeConfig)===null||ue===void 0?void 0:ue.answerSdpHook,tcpOnly:Z}).then(function(){k(be)}).catch(function(re){re.traceid=G.data?G.data.trace_id:"",H({errorCode:u.ErrorCode.ERROR_ANSWER_ERROR,message:re.message?re.message:"set answer error",traceid:re.traceid,sdp:re.sdp})})}else H({message:G?"response status:"+G.status:"response is null",traceid:(Te=G==null?void 0:G.data)===null||Te===void 0?void 0:Te.trace_id,sdp:P.sdp})}).catch(function(G){return f(T,void 0,void 0,function(){var q,X;return v(this,function(J){switch(J.label){case 0:if(![400,500].includes((X=G.response)===null||X===void 0?void 0:X.status))return[3,4];G.sdp=P.sdp,J.label=1;case 1:return J.trys.push([1,3,,4]),[4,new S.SupportUtil().isSupport({isReceiveVideo:!0})];case 2:return J.sent(),[3,4];case 3:return q=J.sent(),G.errorCode=q==null?void 0:q.errorCode,G.message=q==null?void 0:q.message,this.subReconnectTimes=1/0,[3,4];case 4:return H(G),[2]}})})})})},L.prototype.checkPullUrl=function(){return!!this.noParsePullStreamUrl&&this.noParsePullStreamUrl.indexOf("artc://")===0},L.prototype.parseUrl=function(P){if(P===void 0&&(P=""),(P==null?void 0:P.indexOf("artc://"))===0){P.indexOf("@subaudio=no")>-1&&(this.subscribeAudio=!1,P=P.replace("@subaudio=no","")),P.indexOf("@subvideo=no")>-1&&(this.subscribeVideo=!1,P=P.replace("@subvideo=no","")),this.pullStreamUrl=P;var x=window.location.protocol,T=(["http:","https:"].indexOf(x)>-1?x:"https:")+"//";this.signalingUrl=this.pullStreamUrl.replace("artc://",T)}},L.prototype.stopPlayTimer=function(){this.playTimer&&clearTimeout(this.playTimer),this.playTimer=0},L.prototype.calcStreamPullStats=function(P){var x={},T=P.video,O=P.audio;if(T){var k=T.transportStats,H=T.inboundRtpStats,U=T.inboundRtpStatsPerSec,ee=T.localCandidate,W=T.remoteCandidate;x=l(l({},x),{rtt:(k==null?void 0:k.rtt)!==-1?1e3*((k==null?void 0:k.rtt)||0):-1,cand_re_prot:W.protocol,cand_lo_prot:ee.protocol,cand_re_addr:"".concat(W.ip||W.address,":").concat(W.port),cand_lo_addr:"".concat(ee.ip||ee.address,":").concat(ee.port),w:H==null?void 0:H.frameWidth,h:H==null?void 0:H.frameHeight,vbps:Math.floor(8*U.bytesReceivedPerSecond),fps:H==null?void 0:H.framesPerSecond,dfps:Math.floor(U==null?void 0:U.framesDecodedPerSecond),vjb:Math.floor((0,w.getJitterBufferDelayAvg)(H==null?void 0:H.jitterBufferDelay,H==null?void 0:H.jitterBufferEmittedCount)),vMsid:P.vMsid,vloss:U.packetsLostRate})}return O&&(k=O.transportStats,H=O.inboundRtpStats,U=O.inboundRtpStatsPerSec,ee=O.localCandidate,W=O.remoteCandidate,x=l(l({},x),{rtt:(k==null?void 0:k.rtt)!==-1?1e3*((k==null?void 0:k.rtt)||0):-1,cand_re_prot:W.protocol,cand_lo_prot:ee.protocol,cand_re_addr:"".concat(W.ip||W.address,":").concat(W.port),cand_lo_addr:"".concat(ee.ip||ee.address,":").concat(ee.port),abps:Math.floor(8*U.bytesReceivedPerSecond),ajb:Math.floor((0,w.getJitterBufferDelayAvg)(H==null?void 0:H.jitterBufferDelay,H.jitterBufferEmittedCount)),aMsid:P.aMsid,aloss:U.packetsLostRate})),x=l(l({},x),{net_qual:(0,w.evaluateNetworkCondition)(x.rtt,x.aloss,x.vloss,x.ajb,x.vjb)})},L.prototype.doReportPullStats=function(P){var x=this.calcStreamPullStats(P),T={ct:1e3*this.playCatonIndex,tt:1e3*this.playTimeIndex,url:P.url};T.tt&&(T=l(l({},T),x),this.reporter.reportPullStats(T),this.lastMeidaEventData=void 0)},L.prototype.retrySubscribe=function(P,x){return f(this,void 0,void 0,function(){var T,O,k,H,U,ee,W;return v(this,function($){switch($.label){case 0:if(P.extraInfo=l(l({},P.extraInfo),{retryTimes:this.subReconnectTimes}),!this.hasRetries())return[2,!1];if(typeof((T=this.subscribeConfig)==null?void 0:T.beforeRetry)!="function")return[3,4];$.label=1;case 1:return $.trys.push([1,3,,4]),[4,T.beforeRetry({url:this.noParsePullStreamUrl,vMsid:T.vMsid,aMsid:T.aMsid,useTcp:x==null?void 0:x.innerTcpOnly})];case 2:return(O=$.sent())?(k=O.url,H=O.vMsid,U=O.aMsid,ee=O.useTcp,this.reporter.reportReconnectParams("sub",k,H,U,ee),this.noParsePullStreamUrl=k,this.subscribeConfig.vMsid=H,this.subscribeConfig.aMsid=U,typeof ee=="boolean"&&(x=l(l({},x),{innerTcpOnly:ee})),console.log(`retry with: 
[URL] `.concat(k,`
[VMSID]`).concat(H," [AMSID]").concat(U,`
[PROTOCOL] `).concat(ee?"TCP":"UDP"))):(this.reporter.reportReconnectParams("sub"),this.subReconnectTimes=1/0),[3,4];case 3:return W=$.sent(),console.error("Error in beforeRetry",W),[3,4];case 4:return this.hasRetries()?(this.emit("connectStatusChange",{status:d.EConnectStatus.CONNECT_STATUS_RECONNECTING}),this.incrementReconnectTimes(),P.extraInfo.retryTimes=this.subReconnectTimes,P.extraInfo.tcpOnly=x==null?void 0:x.innerTcpOnly,this.subscribeWithReconnect(this.noParsePullStreamUrl,l({innerTcpOnly:x==null?void 0:x.innerTcpOnly},this.subscribeConfig)).catch(function(B){}),[2,!0]):(P.extraInfo.retryTimes=this.subReconnectTimes,[2,!1])}})})},L.prototype.subscribeWithReconnect=function(P,x,T,O){var k=this,H=++this.subscribeCallId;return new Promise(function(U,ee){U=T||U,ee=O||ee,k.isConnecting=!0;var W=(x||{}).innerTcpOnly;x==null||delete x.innerTcpOnly,k.subscribe(P,x,{innerTcpOnly:W},H).then(function($){k.isConnecting=!1,U($)}).catch(function($){var B;if(H===k.subscribeCallId){if(k.peerconnection.reset(),!k.isConnecting)return ee($);if(!u.RECONNECT_ERROR_EXCLUDE_LIST.includes($.errorCode)&&k.hasRetries(!0)){var F=((B=k.subscribeConfig)===null||B===void 0?void 0:B.retryInterval)||d.DEFAULT_RETRY_SUBSCRIBE_INTERVAL;k.reconnectTimerHandle=setTimeout(function(){$.extraInfo=l(l({},$.extraInfo),{retryTimes:k.subReconnectTimes}),k.emit("reconnect",$),k.subscribeWithReconnect(P,x,U,ee)},F)}else ee($),$.extraInfo=l(l({},$.extraInfo),{retryTimes:k.subReconnectTimes}),k.isConnecting=!1,k.cancelReconnect=!0,k.emit("onError",$)}})})},L.prototype.hasRetries=function(P){var x,T,O=d.DEFAULT_RETRY_SUBSCRIBE_LIMIT;typeof((x=this.subscribeConfig)===null||x===void 0?void 0:x.retryTimes)=="number"&&(O=Math.floor((T=this.subscribeConfig)===null||T===void 0?void 0:T.retryTimes));var k=this.subReconnectTimes<O;return P&&k&&this.incrementReconnectTimes(),k},L.prototype.resetResubscribeStatus=function(){this.subReconnectTimes=0,this.isConnecting=!1,this.reporter.updateTid(),this.reconnectTimerHandle!==null&&(clearTimeout(this.reconnectTimerHandle),this.reconnectTimerHandle=null)},L.prototype.handlePubMonitorEvent=function(P){var x=this;P.forEach(function(T){x.reporter.reportPushStats(T)})},L.prototype.incrementReconnectTimes=function(){this.subReconnectTimes++},L.prototype.getSubscribeConfig=function(){return this.subscribeConfig},L}(y.default);s.Subscriber=M},6901:function(a,s,o){var c,h=this&&this.__extends||(c=function(v,p){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(_,m){_.__proto__=m}||function(_,m){for(var d in m)Object.prototype.hasOwnProperty.call(m,d)&&(_[d]=m[d])},c(v,p)},function(v,p){if(typeof p!="function"&&p!==null)throw new TypeError("Class extends value "+String(p)+" is not a constructor or null");function _(){this.constructor=v}c(v,p),v.prototype=p===null?Object.create(p):(_.prototype=p.prototype,new _)});Object.defineProperty(s,"__esModule",{value:!0}),s.AudioReceiverMonitorData=void 0;var l=o(1353),f=function(v){function p(){return v.call(this,l.ReceiverMonitorType.AUDIO)||this}return h(p,v),p}(l.ReceiverMonitorData);s.AudioReceiverMonitorData=f},1353:function(a,s,o){var c,h=this&&this.__extends||(c=function(u,b){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,g){y.__proto__=g}||function(y,g){for(var S in g)Object.prototype.hasOwnProperty.call(g,S)&&(y[S]=g[S])},c(u,b)},function(u,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");function y(){this.constructor=u}c(u,b),u.prototype=b===null?Object.create(b):(y.prototype=b.prototype,new y)}),l=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(s,"__esModule",{value:!0}),s.ReceiverMonitorData=s.ReceiverMonitorType=void 0;var f,v=o(233),p=l(o(102)),_=o(2688),m=o(2718);(function(u){u.AUDIO="audio",u.VIDEO="video"})(f||(s.ReceiverMonitorType=f={}));var d=function(u){function b(y){var g=u.call(this)||this;return g.streamEnded=!1,g.currentTimeGap=0,g.lastTimeStamp=0,g.transportStats={},g.remoteCandidate={},g.localCandidate={},g.inboundRtpStreamStats={},g.inboundRtpStreamStatsDiff={},g.receiver=null,g.pc=null,g.canplay=!1,g.type=y,g}return h(b,u),Object.defineProperty(b.prototype,"rtpReceiver",{set:function(y){this.receiver=y},enumerable:!1,configurable:!0}),Object.defineProperty(b.prototype,"RTCPeerconnection",{set:function(y){this.pc=y},enumerable:!1,configurable:!0}),Object.defineProperty(b.prototype,"isExist",{get:function(){return this.receiver!=null},enumerable:!1,configurable:!0}),Object.defineProperty(b.prototype,"isPlaying",{get:function(){return this.canplay},enumerable:!1,configurable:!0}),Object.defineProperty(b.prototype,"isStreamEnded",{get:function(){return this.streamEnded},enumerable:!1,configurable:!0}),Object.defineProperty(b.prototype,"monitorData",{get:function(){var y=this.inboundRtpStreamStatsDiff||{},g=(this.inboundRtpStreamStats,this.currentTimeGap),S=0;return y.nackCount!==void 0&&y.packetsReceived!==void 0&&(S=Math.round(y.nackCount/(y.packetsReceived+y.nackCount)*1e3)/1e3),{inboundRtpStats:this.inboundRtpStreamStats,inboundRtpStatsPerSec:{bytesReceivedPerSecond:y.bytesReceived/g||0,framesDecodedPerSecond:y.framesDecoded/g||0,packetsLostRate:S>0?S:0,decodeTimeAvg:y.totalDecodeTime&&y.framesDecoded?1e3*(y.totalDecodeTime/y.framesDecoded||0):0,jitterBufferDelayAvg:y.jitterBufferDelay&&y.jitterBufferEmittedCount?(0,m.getJitterBufferDelayAvg)(y.jitterBufferDelay,y.jitterBufferEmittedCount):0,totalProcessingDelayAvg:y.totalProcessingDelay&&y.framesDecoded?y.totalProcessingDelay/y.framesDecoded*1e3:0,totalAssemblyTimeAvg:y.totalAssemblyTime&&y.framesAssembledFromMultiplePackets?y.totalAssemblyTime/y.framesAssembledFromMultiplePackets*1e3:0},transportStats:this.transportStats,remoteCandidate:this.remoteCandidate,localCandidate:this.localCandidate}},enumerable:!1,configurable:!0}),b.prototype.getInfo=function(){var y=this;if(this.receiver&&this.receiver.transport&&this.receiver.transport.state==="closed"&&this.canplay&&(this.streamEnded=!0,this.emit("streamEnded"),this.canplay=!1),this.receiver&&"getStats"in this.receiver||this.pc&&"getStats"in this.pc)return new Promise(function(g,S){var R=null,E=!1;y.receiver&&"getStats"in y.receiver?R=y.receiver.getStats():y.pc&&"getStats"in y.pc&&(R=y.pc.getStats(),E=!0),R==null||R.then(function(I){I.forEach(function(C){var A,w;if(C)switch(C.type){case _.RTCStatsType.CandidatePair:y.onCandidatePair(C);break;case _.RTCStatsType.InboundRtp:v.SystemUtil.isIos&&E?!((A=C.id)===null||A===void 0)&&A.toLowerCase().includes(y.type)&&y.onInBoundRtp(C):v.BrowserUtil.isFirefox?C.kind===y.type&&y.onInBoundRtp(C):y.onInBoundRtp(C);break;case _.RTCStatsType.RemoteCandidate:y.onRemoteCandidate(C);break;case _.RTCStatsType.LocalCandidate:y.onLocalCandidate(C);break;case _.RTCStatsType.Track:if(y.type!==f.VIDEO)break;v.SystemUtil.isIos&&E?(!((w=C.id)===null||w===void 0)&&w.toLowerCase().includes(y.type)||C.trackIdentifier.toLowerCase()===y.type)&&y.onTrack(C):y.onTrack(C)}}),g("")}).catch(function(I){S(I)})})},b.prototype.dispose=function(){this.reset()},b.prototype.onCandidatePair=function(y){(y.state==="succeeded"||y.bytesReceived)&&(this.transportStats={timestamp:Math.floor(y.timestamp),rtt:y.currentRoundTripTime||-1,bytesReceived:y.bytesReceived,bytesSent:y.bytesSent})},b.prototype.onInBoundRtp=function(y){this.currentTimeGap=(y.timestamp-this.lastTimeStamp)/1e3,this.lastTimeStamp=y.timestamp,this.inboundRtpStreamStatsDiff=this.calcDiff(y,this.inboundRtpStreamStats,["bytesReceived","framesDecoded","packetsReceived","nackCount","totalDecodeTime","jitterBufferDelay","jitterBufferEmittedCount","totalProcessingDelay","totalAssemblyTime","framesAssembledFromMultiplePackets"]),this.inboundRtpStreamStats=y,!this.canplay&&Number(y.bytesReceived)>0&&(this.canplay=!0,this.emit("canPlay"))},b.prototype.calcDiff=function(y,g,S){var R={};return S.forEach(function(E){R[E]=Number(y[E]||0)-Number(g[E]||0)}),R},b.prototype.onRemoteCandidate=function(y){this.remoteCandidate=y||{}},b.prototype.onLocalCandidate=function(y){this.localCandidate=y||{}},b.prototype.onTrack=function(y){y.frameWidth&&(this.inboundRtpStreamStats.frameWidth=y.frameWidth,this.inboundRtpStreamStats.frameHeight=y.frameHeight)},b.prototype.reset=function(){this.currentTimeGap=0,this.lastTimeStamp=0,this.transportStats={},this.remoteCandidate={},this.localCandidate={},this.inboundRtpStreamStats={},this.inboundRtpStreamStatsDiff={},this.receiver=null,this.canplay=!1,this.streamEnded=!1},b}(p.default);s.ReceiverMonitorData=d},5250:function(a,s,o){var c,h=this&&this.__extends||(c=function(v,p){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(_,m){_.__proto__=m}||function(_,m){for(var d in m)Object.prototype.hasOwnProperty.call(m,d)&&(_[d]=m[d])},c(v,p)},function(v,p){if(typeof p!="function"&&p!==null)throw new TypeError("Class extends value "+String(p)+" is not a constructor or null");function _(){this.constructor=v}c(v,p),v.prototype=p===null?Object.create(p):(_.prototype=p.prototype,new _)});Object.defineProperty(s,"__esModule",{value:!0}),s.VideoReceiverMonitorData=void 0;var l=o(1353),f=function(v){function p(){return v.call(this,l.ReceiverMonitorType.VIDEO)||this}return h(p,v),p}(l.ReceiverMonitorData);s.VideoReceiverMonitorData=f},2688:(a,s)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.RTCStatsType=void 0;var o=function(){function c(){}return c.CandidatePair="candidate-pair",c.Certificate="certificate",c.Codec="codec",c.Csrc="csrc",c.DataCahnnel="data-channel",c.InboundRtp="inbound-rtp",c.LocalCandidate="local-candidate",c.OutboundRtp="outbound-rtp",c.PeerConnection="peer-connection",c.Receiver="receiver",c.RemoteCandidate="remote-candidate",c.RemoteInboundRtp="remote-inbound-rtp",c.RemoteOutboundRtp="remote-outbound-rtp",c.Sender="sender",c.Stream="stream",c.Track="track",c.Transport="transport",c.MediaSource="media-source",c}();s.RTCStatsType=o},5657:(a,s,o)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.SenderMonitorData=void 0;var c=o(2688),h=function(){function l(){this._audiosender=null,this._videosender=null,this.timeStamp=0,this.curTimeStamp=0,this.audioBytesSent=0,this.curAudioBytesSent=0,this.videoBytesSent=0,this.curVideoBytesSent=0,this.audioRetransmittedBytesSent=0,this.curAudioRetransmittedBytesSent=0,this.videoRetransmiitedBytesSent=0,this.curVideoRetransmiitedBytesSent=0,this.framesSent=0,this.curFramesSent=0,this.framesEncoded=0,this.curFramesEncoded=0,this.totalEncodeTime=0,this.curTotalEncodeTime=0,this.totalPacketSendDelay=0,this.curTotalPacketSendDelay=0,this.packetsSent=0,this.curPacketsSent=0,this.rtt=0,this.localProtocol="",this.remoteProtocol="",this.localTransportAddr="",this.remoteTransportAddr="",this.frameHeight=0,this.frameWidth=0,this.efps=0,this.sfps=0,this.timeGap=0,this.abps=0,this.vbps=0,this.rt_abps=0,this.rt_vbps=0,this.encodeTimeAvg=0,this.packetSendDelayAvg=0,this.stashedData={}}return Object.defineProperty(l.prototype,"videoSender",{set:function(f){this._videosender=f},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"audioSender",{set:function(f){this._audiosender=f},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"monitorData",{get:function(){return this.doCalc(),{tt:parseFloat(this.timeGap.toFixed(0)),rtt:this.rtt,cand_re_prot:this.remoteProtocol,cand_lo_prot:this.localProtocol,cand_re_addr:this.remoteTransportAddr,cand_lo_addr:this.localTransportAddr,w:this.frameWidth,h:this.frameHeight,efps:parseFloat(this.efps.toFixed(0)),fps:parseFloat(this.sfps.toFixed(0)),abps:parseFloat(this.abps.toFixed(0)),vbps:parseFloat(this.vbps.toFixed(0)),rt_abps:parseFloat(this.rt_abps.toFixed(0)),rt_vbps:parseFloat(this.rt_vbps.toFixed(0)),v_encode_time_avg:parseFloat(this.encodeTimeAvg.toFixed(2)),v_packet_send_delay_avg:parseFloat(this.packetSendDelayAvg.toFixed(2))}},enumerable:!1,configurable:!0}),l.prototype.doCalc=function(){this.timeStamp!==0&&(this.timeGap=this.curTimeStamp-this.timeStamp,this.timeGap>0&&(this.efps=1e3*(this.curFramesEncoded-this.framesEncoded)/this.timeGap,this.sfps=1e3*(this.curFramesSent-this.framesSent)/this.timeGap,this.abps=1e3*(this.curAudioBytesSent-this.audioBytesSent)/this.timeGap,this.vbps=1e3*(this.curVideoBytesSent-this.videoBytesSent)/this.timeGap,this.rt_abps=1e3*(this.curAudioRetransmittedBytesSent-this.audioRetransmittedBytesSent)/this.timeGap,this.rt_vbps=1e3*(this.curVideoRetransmiitedBytesSent-this.videoRetransmiitedBytesSent)/this.timeGap,this.encodeTimeAvg=(this.curTotalEncodeTime-this.totalEncodeTime)/(this.curFramesEncoded-this.framesEncoded)*1e3,this.packetSendDelayAvg=(this.curTotalPacketSendDelay-this.totalPacketSendDelay)/(this.curPacketsSent-this.packetsSent)*1e3)),this.timeStamp=this.curTimeStamp,this.audioBytesSent=this.curAudioBytesSent,this.videoBytesSent=this.curVideoBytesSent,this.audioRetransmittedBytesSent=this.curAudioRetransmittedBytesSent,this.videoRetransmiitedBytesSent=this.curVideoRetransmiitedBytesSent,this.framesSent=this.curFramesSent,this.framesEncoded=this.curFramesEncoded,this.totalEncodeTime=this.curTotalEncodeTime,this.packetsSent=this.curPacketsSent,this.totalPacketSendDelay=this.curTotalPacketSendDelay},l.prototype.getInfo=function(){var f=this,v=new Promise(function(_,m){f._videosender&&f._videosender.getStats?f._videosender.getStats().then(function(d){d.forEach(function(u){if(u)switch(u.type){case c.RTCStatsType.CandidatePair:f.onCandidatePair(u);break;case c.RTCStatsType.OutboundRtp:f.onOutBoundRtp(u,"video");break;case c.RTCStatsType.RemoteCandidate:f.onRemoteCandidate(u);break;case c.RTCStatsType.LocalCandidate:f.onLocalCandidate(u)}}),_()}).catch(function(d){m(d)}):m("no video sender")}),p=new Promise(function(_,m){f._audiosender&&f._audiosender.getStats?f._audiosender.getStats().then(function(d){d.forEach(function(u){if(u)switch(u.type){case c.RTCStatsType.CandidatePair:f.onCandidatePair(u);break;case c.RTCStatsType.OutboundRtp:f.onOutBoundRtp(u,"audio");break;case c.RTCStatsType.RemoteCandidate:f.onRemoteCandidate(u);break;case c.RTCStatsType.LocalCandidate:f.onLocalCandidate(u)}}),_()}).catch(function(d){m(d)}):m("no audio sender")});return Promise.all([v,p])},l.prototype.onCandidatePair=function(f){this.curTimeStamp=f.timestamp,this.rtt=f.currentRoundTripTime},l.prototype.onOutBoundRtp=function(f,v){this.curTimeStamp=f.timestamp,v==="video"?(this.curVideoBytesSent=f.bytesSent,this.curVideoRetransmiitedBytesSent=f.retransmittedBytesSent,this.curFramesEncoded=f.framesEncoded,this.curFramesSent=f.framesSent,this.frameWidth=f.frameWidth,this.frameHeight=f.frameHeight,this.curTotalEncodeTime=f.totalEncodeTime,this.curTotalPacketSendDelay=f.totalPacketSendDelay,this.curPacketsSent=f.packetsSent):v==="audio"&&(this.curAudioBytesSent=f.bytesSent,this.curAudioRetransmittedBytesSent=f.retransmittedBytesSent)},l.prototype.onRemoteCandidate=function(f){this.curTimeStamp=f.timestamp,this.remoteProtocol=f.protocol,this.remoteTransportAddr=(f.ip||f.address)+(f.port?":"+f.port.toFixed(0):"")},l.prototype.onLocalCandidate=function(f){this.curTimeStamp=f.timestamp,this.localProtocol=f.protocol,this.localTransportAddr=(f.ip||f.address)+(f.port?":"+f.port.toFixed(0):"")},l}();s.SenderMonitorData=h},9752:function(a,s,o){var c,h=this&&this.__extends||(c=function(d,u){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,y){b.__proto__=y}||function(b,y){for(var g in y)Object.prototype.hasOwnProperty.call(y,g)&&(b[g]=y[g])},c(d,u)},function(d,u){if(typeof u!="function"&&u!==null)throw new TypeError("Class extends value "+String(u)+" is not a constructor or null");function b(){this.constructor=d}c(d,u),d.prototype=u===null?Object.create(u):(b.prototype=u.prototype,new b)}),l=this&&this.__assign||function(){return l=Object.assign||function(d){for(var u,b=1,y=arguments.length;b<y;b++)for(var g in u=arguments[b])Object.prototype.hasOwnProperty.call(u,g)&&(d[g]=u[g]);return d},l.apply(this,arguments)},f=this&&this.__spreadArray||function(d,u,b){if(b||arguments.length===2)for(var y,g=0,S=u.length;g<S;g++)!y&&g in u||(y||(y=Array.prototype.slice.call(u,0,g)),y[g]=u[g]);return d.concat(y||Array.prototype.slice.call(u))},v=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(s,"__esModule",{value:!0}),s.PubMonitor=void 0;var p=v(o(102)),_=o(5657),m=function(d){function u(){var b=d.call(this)||this;return b.heartbeatHandle=null,b.pc=null,b.pcCore=null,b.senderMonitorDataList=[],b}return h(u,d),u.prototype.startHeartbeat=function(b,y,g){var S=this;this.pc=b,this.pcCore=y,this.updateSenders(),this.stopHeartbeat(),this.heartbeatHandle=setInterval(function(){S.emitHeartBeat()},g||1e3)},u.prototype.stopHeartbeat=function(){this.heartbeatHandle!==null&&clearInterval(this.heartbeatHandle),this.heartbeatHandle=null},u.prototype.addTrackPair=function(b,y,g,S,R){var E=this;if(b){var I=new _.SenderMonitorData;if(y){I.videoSender=y;var C=y.transport;C&&(C.onstatechange=function(){var w,N,M,D;E.emit("onTransportStateEvent",{url:b,type:"pub",kind:"video",state:C.state,protocol:(D=(M=(N=(w=C.iceTransport)===null||w===void 0?void 0:w.getSelectedCandidatePair)===null||N===void 0?void 0:N.call(w))===null||M===void 0?void 0:M.local)===null||D===void 0?void 0:D.protocol})})}if(g){I.audioSender=g;var A=g.transport;A&&(A.onstatechange=function(){var w,N,M,D;E.emit("onTransportStateEvent",{url:b,type:"pub",kind:"audio",state:A.state,protocol:(D=(M=(N=(w=A.iceTransport)===null||w===void 0?void 0:w.getSelectedCandidatePair)===null||N===void 0?void 0:N.call(w))===null||M===void 0?void 0:M.local)===null||D===void 0?void 0:D.protocol})})}this.senderMonitorDataList.push({url:b,vMsid:S,aMsid:R,senderData:I})}},u.prototype.updateSenders=function(){var b,y=this,g=(b=this.pcCore)===null||b===void 0?void 0:b.getStreamManager().getAllTrackPairList("pub");this.senderMonitorDataList=[],g==null||g.forEach(function(S){y.addTrackPair(S.url,S.vTransceiver,S.aTransceiver,S.vMsid,S.aMsid)})},u.prototype.emitHeartBeat=function(){var b=this;Promise.all(this.senderMonitorDataList.reduce(function(y,g){return f(f([],y,!0),[g.senderData.getInfo()],!1)},[])).then(function(){}).catch(function(y){}).finally(function(){var y=b.senderMonitorDataList.map(function(g){return l(l({},g.senderData.monitorData),{url:g.url,vMsid:g.vMsid,aMsid:g.aMsid})});b.emit("onMonitorEvent",{eventList:y,type:"pub"})})},u}(p.default);s.PubMonitor=m},4699:function(a,s,o){var c,h=this&&this.__extends||(c=function(y,g){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(S,R){S.__proto__=R}||function(S,R){for(var E in R)Object.prototype.hasOwnProperty.call(R,E)&&(S[E]=R[E])},c(y,g)},function(y,g){if(typeof g!="function"&&g!==null)throw new TypeError("Class extends value "+String(g)+" is not a constructor or null");function S(){this.constructor=y}c(y,g),y.prototype=g===null?Object.create(g):(S.prototype=g.prototype,new S)}),l=this&&this.__awaiter||function(y,g,S,R){return new(S||(S=Promise))(function(E,I){function C(N){try{w(R.next(N))}catch(M){I(M)}}function A(N){try{w(R.throw(N))}catch(M){I(M)}}function w(N){var M;N.done?E(N.value):(M=N.value,M instanceof S?M:new S(function(D){D(M)})).then(C,A)}w((R=R.apply(y,g||[])).next())})},f=this&&this.__generator||function(y,g){var S,R,E,I,C={label:0,sent:function(){if(1&E[0])throw E[1];return E[1]},trys:[],ops:[]};return I={next:A(0),throw:A(1),return:A(2)},typeof Symbol=="function"&&(I[Symbol.iterator]=function(){return this}),I;function A(w){return function(N){return function(M){if(S)throw new TypeError("Generator is already executing.");for(;I&&(I=0,M[0]&&(C=0)),C;)try{if(S=1,R&&(E=2&M[0]?R.return:M[0]?R.throw||((E=R.return)&&E.call(R),0):R.next)&&!(E=E.call(R,M[1])).done)return E;switch(R=0,E&&(M=[2&M[0],E.value]),M[0]){case 0:case 1:E=M;break;case 4:return C.label++,{value:M[1],done:!1};case 5:C.label++,R=M[1],M=[0];continue;case 7:M=C.ops.pop(),C.trys.pop();continue;default:if(E=C.trys,!((E=E.length>0&&E[E.length-1])||M[0]!==6&&M[0]!==2)){C=0;continue}if(M[0]===3&&(!E||M[1]>E[0]&&M[1]<E[3])){C.label=M[1];break}if(M[0]===6&&C.label<E[1]){C.label=E[1],E=M;break}if(E&&C.label<E[2]){C.label=E[2],C.ops.push(M);break}E[2]&&C.ops.pop(),C.trys.pop();continue}M=g.call(y,C)}catch(D){M=[6,D],R=0}finally{S=E=0}if(5&M[0])throw M[1];return{value:M[0]?M[1]:void 0,done:!0}}([w,N])}}},v=this&&this.__spreadArray||function(y,g,S){if(S||arguments.length===2)for(var R,E=0,I=g.length;E<I;E++)!R&&E in g||(R||(R=Array.prototype.slice.call(g,0,E)),R[E]=g[E]);return y.concat(R||Array.prototype.slice.call(g))},p=this&&this.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(s,"__esModule",{value:!0}),s.SubMonitor=void 0;var _=o(6901),m=o(5250),d=p(o(102)),u=function(){function y(){this.trackPairDataList=[]}return y.prototype.reset=function(){this.trackPairDataList=[]},y.prototype.addTrackPair=function(g,S,R,E,I,C){var A=new _.AudioReceiverMonitorData,w=new m.VideoReceiverMonitorData;E&&(w.rtpReceiver=E),I&&(A.rtpReceiver=I),C&&(w.RTCPeerconnection=C,A.RTCPeerconnection=C),this.trackPairDataList.push({url:g,vMsid:S,aMsid:R,audioReceiverMonitorData:A,videoReceiverMonitorData:w})},y}(),b=function(y){function g(){var S=y.call(this)||this;return S.canplay=!1,S.pc=null,S.pcCore=null,S.monitorTimerId=null,S.audioReceiverMonitorData=new _.AudioReceiverMonitorData,S.videoReceiverMonitorData=new m.VideoReceiverMonitorData,S.receiverMonitorController=new u,S}return h(g,y),g.prototype.start=function(S,R){this.pc=S,this.pcCore=R,this.updateTranceiversController(),this.startMonitorTimer(200)},g.prototype.updateTranceiversController=function(){var S=this;if(this.pc&&this.pcCore){var R=this.pcCore.getStreamManager().getAllTrackPairList("sub");this.receiverMonitorController.reset(),R.forEach(function(E){E.url&&S.receiverMonitorController.addTrackPair(E.url,E.vMsid,E.aMsid,E.vTransceiver,E.aTransceiver,S.pc)}),this.receiverMonitorController.trackPairDataList.forEach(function(E){S.initEvent(E)})}},g.prototype.resetTimer=function(S){this.updateTranceiversController(),this.stopMonitorTimer(),this.startMonitorTimer(S)},g.prototype.stop=function(){this.canplay=!1,this.stopMonitorTimer(),this.audioReceiverMonitorData.dispose(),this.videoReceiverMonitorData.dispose()},g.prototype.startMonitorTimer=function(S){var R=this;this.monitorTimerId||(this.monitorTimerId=window.setInterval(function(){R.onMonitorTimer()},S))},g.prototype.stopMonitorTimer=function(){this.monitorTimerId&&clearInterval(this.monitorTimerId),this.monitorTimerId=null},g.prototype.onMonitorTimer=function(){return l(this,void 0,void 0,function(){var S;return f(this,function(R){switch(R.label){case 0:return[4,this.updateMonitorData()];case 1:return R.sent(),S=[],this.receiverMonitorController.trackPairDataList.forEach(function(E){var I,C;if(E.url){var A={url:E.url};E.audioReceiverMonitorData.isExist&&(A.audio=(I=E.audioReceiverMonitorData)===null||I===void 0?void 0:I.monitorData,A.aMsid=E.aMsid),E.videoReceiverMonitorData.isExist&&(A.video=(C=E.videoReceiverMonitorData)===null||C===void 0?void 0:C.monitorData,A.vMsid=E.vMsid),S.push(A)}}),this.emit("onMonitorEvent",{eventList:S,type:"sub"}),[2]}})})},g.prototype.initEvent=function(S){var R=this,E={url:S.url||"url unknown",vMsid:S.vMsid||"vMsid unknown",aMsid:S.aMsid||"aMsid unknown"};S.audioReceiverMonitorData.isExist&&(S.audioReceiverMonitorData.on("streamEnded",function(){S.videoReceiverMonitorData&&!S.videoReceiverMonitorData.isStreamEnded||(R.emit("streamEnded",E),R.stopMonitorTimer())}),S.audioReceiverMonitorData.on("canPlay",function(){R.emitCanPlay()})),S.videoReceiverMonitorData.isExist&&(S.videoReceiverMonitorData.on("streamEnded",function(){S.audioReceiverMonitorData&&!S.audioReceiverMonitorData.isStreamEnded||(R.emit("streamEnded",E),R.stopMonitorTimer())}),S.videoReceiverMonitorData.on("canPlay",function(){R.emitCanPlay()}))},g.prototype.updateMonitorData=function(){return Promise.all(this.receiverMonitorController.trackPairDataList.reduce(function(S,R){var E,I;return v(v([],S,!0),[(E=R.audioReceiverMonitorData)===null||E===void 0?void 0:E.getInfo(),(I=R.videoReceiverMonitorData)===null||I===void 0?void 0:I.getInfo()],!1)},[]))},g.prototype.emitCanPlay=function(){this.canplay||(this.canplay=!0,this.emit("canPlay"))},g.prototype.copyMonitorData=function(){var S,R;!((R=(S=this.receiverMonitorController)===null||S===void 0?void 0:S.trackPairDataList)===null||R===void 0)&&R.length&&(this.audioReceiverMonitorData=this.receiverMonitorController.trackPairDataList[0].audioReceiverMonitorData,this.videoReceiverMonitorData=this.receiverMonitorController.trackPairDataList[0].videoReceiverMonitorData)},g.prototype.getTransportStats=function(){return l(this,void 0,void 0,function(){var S;return f(this,function(R){switch(R.label){case 0:return[4,this.updateMonitorData()];case 1:return R.sent(),this.copyMonitorData(),S={},this.videoReceiverMonitorData.isExist?S=this.videoReceiverMonitorData.monitorData.transportStats:this.audioReceiverMonitorData.isExist&&(S=this.audioReceiverMonitorData.monitorData.transportStats),[2,S]}})})},g.prototype.getRemoteVideoStats=function(){return l(this,void 0,void 0,function(){var S,R;return f(this,function(E){switch(E.label){case 0:return[4,this.updateMonitorData()];case 1:return E.sent(),this.copyMonitorData(),S={},this.videoReceiverMonitorData.isExist&&(R=this.videoReceiverMonitorData.monitorData.inboundRtpStats,S={timestamp:Math.floor(R.timestamp||0),framesDecodedPerSecond:R.framesPerSecond,framesDecoded:R.framesDecoded,frameWidth:R.frameWidth,frameHeight:R.frameHeight,bytesReceived:R.bytesReceived,jitter:R.jitter,jitterBufferDelayAvg:Number(R.jitterBufferDelay)/Number(R.jitterBufferEmittedCount),packetsLost:R.packetsLost,packetsReceived:R.packetsReceived}),[2,S]}})})},g.prototype.getRemoteAudioStats=function(){return l(this,void 0,void 0,function(){var S,R;return f(this,function(E){switch(E.label){case 0:return[4,this.updateMonitorData()];case 1:return E.sent(),this.copyMonitorData(),S={},this.audioReceiverMonitorData.isExist&&(R=this.audioReceiverMonitorData.monitorData.inboundRtpStats,S={timestamp:Math.floor(R.timestamp||0),bytesReceived:R.bytesReceived,jitter:R.jitter,jitterBufferDelayAvg:Number(R.jitterBufferDelay)/Number(R.jitterBufferEmittedCount),packetsLost:R.packetsLost,packetsReceived:R.packetsReceived}),[2,S]}})})},g}(d.default);s.SubMonitor=b},5259:(a,s)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.AudioProfileMap=s.VideoProfileMap=s.ScreenProfileMap=void 0,s.ScreenProfileMap=new Map,s.ScreenProfileMap.set("480p_1",{width:640,height:480,frameRate:5,maxBitrate:300}),s.ScreenProfileMap.set("480p_2",{width:640,height:480,frameRate:30,maxBitrate:1e3}),s.ScreenProfileMap.set("720p_1",{width:1280,height:720,frameRate:5,maxBitrate:800}),s.ScreenProfileMap.set("720p_2",{width:1280,height:720,frameRate:30,maxBitrate:2e3}),s.ScreenProfileMap.set("1080p_1",{width:1920,height:1080,frameRate:5,maxBitrate:1e3}),s.ScreenProfileMap.set("1080p_2",{width:1920,height:1080,frameRate:30,maxBitrate:3e3}),s.VideoProfileMap=new Map,s.VideoProfileMap.set("120p_1",{width:160,height:120,frameRate:15,maxBitrate:65}),s.VideoProfileMap.set("120p_3",{width:120,height:120,frameRate:15,maxBitrate:50}),s.VideoProfileMap.set("180p_1",{width:320,height:180,frameRate:15,maxBitrate:140}),s.VideoProfileMap.set("180p_3",{width:180,height:180,frameRate:15,maxBitrate:100}),s.VideoProfileMap.set("180p_4",{width:240,height:180,frameRate:15,maxBitrate:120}),s.VideoProfileMap.set("240p_1",{width:320,height:240,frameRate:15,maxBitrate:200}),s.VideoProfileMap.set("240p_3",{width:240,height:240,frameRate:15,maxBitrate:140}),s.VideoProfileMap.set("240p_4",{width:424,height:240,frameRate:15,maxBitrate:220}),s.VideoProfileMap.set("360p_1",{width:640,height:360,frameRate:15,maxBitrate:400}),s.VideoProfileMap.set("360p_3",{width:360,height:360,frameRate:15,maxBitrate:260}),s.VideoProfileMap.set("360p_4",{width:640,height:360,frameRate:30,maxBitrate:600}),s.VideoProfileMap.set("360p_6",{width:360,height:360,frameRate:30,maxBitrate:400}),s.VideoProfileMap.set("360p_7",{width:480,height:360,frameRate:15,maxBitrate:320}),s.VideoProfileMap.set("360p_8",{width:480,height:360,frameRate:30,maxBitrate:490}),s.VideoProfileMap.set("360p_9",{width:640,height:360,frameRate:15,maxBitrate:800}),s.VideoProfileMap.set("360p_10",{width:640,height:360,frameRate:24,maxBitrate:800}),s.VideoProfileMap.set("360p_11",{width:640,height:360,frameRate:24,maxBitrate:1e3}),s.VideoProfileMap.set("480p_1",{width:640,height:480,frameRate:15,maxBitrate:500}),s.VideoProfileMap.set("480p_2",{width:640,height:480,frameRate:30,maxBitrate:1e3}),s.VideoProfileMap.set("480p_3",{width:480,height:480,frameRate:15,maxBitrate:400}),s.VideoProfileMap.set("480p_4",{width:640,height:480,frameRate:30,maxBitrate:750}),s.VideoProfileMap.set("480p_6",{width:480,height:480,frameRate:30,maxBitrate:600}),s.VideoProfileMap.set("480p_8",{width:848,height:480,frameRate:15,maxBitrate:610}),s.VideoProfileMap.set("480p_9",{width:848,height:480,frameRate:30,maxBitrate:930}),s.VideoProfileMap.set("480p_10",{width:640,height:480,frameRate:10,maxBitrate:400}),s.VideoProfileMap.set("720p_1",{width:1280,height:720,frameRate:15,maxBitrate:1130}),s.VideoProfileMap.set("720p_2",{width:1280,height:720,frameRate:30,maxBitrate:2e3}),s.VideoProfileMap.set("720p_3",{width:1280,height:720,frameRate:30,maxBitrate:1710}),s.VideoProfileMap.set("720p_5",{width:960,height:720,frameRate:15,maxBitrate:910}),s.VideoProfileMap.set("720p_6",{width:960,height:720,frameRate:30,maxBitrate:1380}),s.VideoProfileMap.set("1080p_1",{width:1920,height:1080,frameRate:15,maxBitrate:2080}),s.VideoProfileMap.set("1080p_2",{width:1920,height:1080,frameRate:30,maxBitrate:3e3}),s.VideoProfileMap.set("1080p_3",{width:1920,height:1080,frameRate:30,maxBitrate:3150}),s.VideoProfileMap.set("1080p_5",{width:1920,height:1080,frameRate:60,maxBitrate:4780}),s.VideoProfileMap.set("1440p_1",{width:2560,height:1440,frameRate:30,maxBitrate:4850}),s.VideoProfileMap.set("1440p_2",{width:2560,height:1440,frameRate:60,maxBitrate:7350}),s.VideoProfileMap.set("4K_1",{width:3840,height:2160,frameRate:30,maxBitrate:8910}),s.VideoProfileMap.set("4K_3",{width:3840,height:2160,frameRate:60,maxBitrate:13500}),s.AudioProfileMap=new Map,s.AudioProfileMap.set("standard",{sampleRate:48e3,channelCount:1,maxBitrate:64}),s.AudioProfileMap.set("high",{sampleRate:48e3,channelCount:1,maxBitrate:128}),s.AudioProfileMap.set("standard-stereo",{sampleRate:48e3,channelCount:2,maxBitrate:80}),s.AudioProfileMap.set("high-stereo",{sampleRate:48e3,channelCount:2,maxBitrate:192})},5553:(a,s)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.Datachannel=void 0;var o=function(){function c(h){this.pc=h,this.messageId=1,this.dataChannel=this.pc.createDataChannel("GRTNDataChannel"),this.dataChannel.onopen=function(l){},this.dataChannel.onmessage=function(l){l.data},this.dataChannel.onclose=function(l){},this.dataChannel.onerror=function(l){}}return c.prototype.addTrack=function(h,l){return new Promise(function(f,v){})},c.prototype.removeTrack=function(h,l){return new Promise(function(f,v){})},c.prototype.createPublishPacket=function(){var h={type:"pub",version:1,msg_id:this.messageId,streams:[]};return++this.messageId,h},c}();s.Datachannel=o},2470:function(a,s,o){var c,h=this&&this.__extends||(c=function(g,S){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(R,E){R.__proto__=E}||function(R,E){for(var I in E)Object.prototype.hasOwnProperty.call(E,I)&&(R[I]=E[I])},c(g,S)},function(g,S){if(typeof S!="function"&&S!==null)throw new TypeError("Class extends value "+String(S)+" is not a constructor or null");function R(){this.constructor=g}c(g,S),g.prototype=S===null?Object.create(S):(R.prototype=S.prototype,new R)}),l=this&&this.__assign||function(){return l=Object.assign||function(g){for(var S,R=1,E=arguments.length;R<E;R++)for(var I in S=arguments[R])Object.prototype.hasOwnProperty.call(S,I)&&(g[I]=S[I]);return g},l.apply(this,arguments)},f=this&&this.__awaiter||function(g,S,R,E){return new(R||(R=Promise))(function(I,C){function A(M){try{N(E.next(M))}catch(D){C(D)}}function w(M){try{N(E.throw(M))}catch(D){C(D)}}function N(M){var D;M.done?I(M.value):(D=M.value,D instanceof R?D:new R(function(L){L(D)})).then(A,w)}N((E=E.apply(g,S||[])).next())})},v=this&&this.__generator||function(g,S){var R,E,I,C,A={label:0,sent:function(){if(1&I[0])throw I[1];return I[1]},trys:[],ops:[]};return C={next:w(0),throw:w(1),return:w(2)},typeof Symbol=="function"&&(C[Symbol.iterator]=function(){return this}),C;function w(N){return function(M){return function(D){if(R)throw new TypeError("Generator is already executing.");for(;C&&(C=0,D[0]&&(A=0)),A;)try{if(R=1,E&&(I=2&D[0]?E.return:D[0]?E.throw||((I=E.return)&&I.call(E),0):E.next)&&!(I=I.call(E,D[1])).done)return I;switch(E=0,I&&(D=[2&D[0],I.value]),D[0]){case 0:case 1:I=D;break;case 4:return A.label++,{value:D[1],done:!1};case 5:A.label++,E=D[1],D=[0];continue;case 7:D=A.ops.pop(),A.trys.pop();continue;default:if(I=A.trys,!((I=I.length>0&&I[I.length-1])||D[0]!==6&&D[0]!==2)){A=0;continue}if(D[0]===3&&(!I||D[1]>I[0]&&D[1]<I[3])){A.label=D[1];break}if(D[0]===6&&A.label<I[1]){A.label=I[1],I=D;break}if(I&&A.label<I[2]){A.label=I[2],A.ops.push(D);break}I[2]&&A.ops.pop(),A.trys.pop();continue}D=S.call(g,A)}catch(L){D=[6,L],E=0}finally{R=I=0}if(5&D[0])throw D[1];return{value:D[0]?D[1]:void 0,done:!0}}([N,M])}}},p=this&&this.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(s,"__esModule",{value:!0}),s.PcRestorer=void 0;var _=p(o(102)),m=o(5917),d=o(280),u=o(9428),b=o(5044),y=function(g){function S(R){var E=g.call(this)||this;return E.continueRetryRestore=!0,E.restoring=!1,E.maxRestoreDuration=0,E.subscriber=R.subscriber,E.publisher=R.publisher,E.commonController=R.commonController,E}return h(S,g),S.prototype.isReconnecting=function(){return this.restoring},S.prototype.isRestoreRetryComplete=function(){return!this.continueRetryRestore},S.prototype.restore=function(R,E){var I=this;if(E===void 0&&(E=0),this.maxRestoreDuration===0){var C=(this.subscriber.getSubscribeConfig().retryInterval||m.DEFAULT_RETRY_SUBSCRIBE_INTERVAL)*(this.subscriber.getSubscribeConfig().retryTimes||m.DEFAULT_RETRY_SUBSCRIBE_LIMIT),A=(this.publisher.getPublishConfig().retryInterval||m.DEFAULT_RETRY_PUBLISH_INTERVAL)*(this.publisher.getPublishConfig().retryTimes||m.DEFAULT_RETRY_PUBLISH_LIMIT);this.maxRestoreDuration=Math.max(C,A)}return E>=this.maxRestoreDuration?Promise.reject(new b.RtsError(u.ErrorCode.ERROR_SINGLE_PC_FULL_RECONNECT_FAILED,"PC restore failed after ".concat(E,"/").concat(this.maxRestoreDuration),"")):(console.log("PC begin restore, ".concat(E,"ms/").concat(this.maxRestoreDuration,"ms")),new Promise(function(w,N){return f(I,void 0,void 0,function(){var M,D,L,P;return v(this,function(x){switch(x.label){case 0:this.continueRetryRestore=!0,this.restoring=!0,M=Date.now(),x.label=1;case 1:return x.trys.push([1,3,,4]),[4,this.performRestore(R)];case 2:return D=x.sent(),this.restoring=!1,w(D),[3,4];case 3:return L=x.sent(),this.restoring=!1,console.log("PC restore's datachannel failed, continueRetryRestore=".concat(this.continueRetryRestore,", error="),L),this.continueRetryRestore?(P=Date.now()-M,this.restore(R,E+P).then(w).catch(N)):N(L),[3,4];case 4:return[2]}})})}))},S.prototype.performRestore=function(R){return f(this,void 0,void 0,function(){var E,I,C,A,w,N,M,D,L,P,x=this;return v(this,function(T){switch(T.label){case 0:if(!(E=this.restructureStreams())||!E.length)return[2,{traceId:void 0,latestUrl:void 0}];switch(this.subscriber.unsubscribe(),this.publisher.unpublish(),I=Promise.reject().catch(function(){}),C=E[0],A=C.url,R&&(A=this.makeIpQuery(A,R,C.type)),C.type){case"sub":this.commonController.setPeerconnection(this.subscriber.getPeerConnection()),this.subscriber.incrementReconnectTimes(),I=this.subscriber.subscribeWithReconnect(A,l(l({},this.subscriber.getSubscribeConfig()),{vMsid:C.vMsid,aMsid:C.aMsid}));break;case"pub":C.targetStream&&(this.commonController.setPeerconnection(this.publisher.getPeerConnection()),this.publisher.incrementReconnectTimes(),I=this.publisher.publishWithReconnect(A,C.targetStream,l(l({},this.publisher.getPublishConfig()),{vMsid:C.vMsid,aMsid:C.aMsid})));break;case"sub-data":C.msid&&C.label&&(I=this.commonController.subscribeAddDatachannel({signalUrl:A,url:A,label:C.label,msid:C.msid}));break;case"pub-data":C.msid&&C.label&&(I=this.commonController.publishAddDatachannel({signalUrl:C.url,url:C.url,label:C.label,msid:C.msid}));break;default:console.log("RTS [PC RESTORER] unknown http reconnect type",C.type)}T.label=1;case 1:return T.trys.push([1,3,,4]),[4,I];case 2:return N=T.sent(),w=typeof N=="string"?N:N==null?void 0:N.traceId,[3,4];case 3:throw M=T.sent(),(C.type==="sub"&&this.subscriber.cancelReconnect||C.type==="pub"&&this.publisher.cancelReconnect)&&(this.continueRetryRestore=!1),M;case 4:return T.trys.push([4,6,,7]),[4,this.waitForDatachannelOpen()];case 5:return T.sent(),[3,7];case 6:throw T.sent();case 7:for(D=[],L=1;L<E.length;L++)if(P=E[L])switch(P.type){case"sub":D.push(this.commonController.subscribeAdd([{url:P.url,vMsid:P.vMsid,aMsid:P.aMsid,targetStream:P.targetStream,subAudio:!(!P.aMsid||!P.aMsid.length),subVideo:!(!P.vMsid||!P.vMsid.length)}],!0).catch(function(O){throw x.makeSingleStreamReconnectError(O)}));break;case"pub":D.push(this.commonController.publishAdd([{url:P.url,stream:P.targetStream,vMsid:P.vMsid,aMsid:P.aMsid}]).catch(function(O){throw x.makeSingleStreamReconnectError(O)}));break;case"sub-data":P.label&&P.msid&&D.push(this.commonController.subscribeAddDatachannel({signalUrl:P.url,url:P.url,label:P.label,msid:P.msid}).catch(function(O){throw x.makeSingleStreamReconnectError(O)}));break;case"pub-data":P.label&&P.msid&&D.push(this.commonController.publishAddDatachannel({signalUrl:P.url,url:P.url,label:P.label,msid:P.msid}).catch(function(O){throw x.makeSingleStreamReconnectError(O)}));break;default:console.log("RTS [PC RESTORER] unknown pc reconnect type")}return[2,Promise.allSettled(D).then(function(O){var k,H,U=O.find(function(ee){return ee.status==="fulfilled"});return{traceId:w=((H=(k=U==null?void 0:U.value)===null||k===void 0?void 0:k[0])===null||H===void 0?void 0:H.traceId)||w,latestUrl:A}})]}})})},S.prototype.waitForDatachannelOpen=function(){var R=this;return new Promise(function(E,I){clearTimeout(R.dcOpenTimer),R.dcOpenTimer=setTimeout(function(){var A=new b.RtsError(u.ErrorCode.ERROR_DATACHANNEL_OPEN,"reconnect pc datachannel open timeout after ".concat(m.DEFAULT_RETRY_DATACHANNEL_TIMEOUT,"ms"),"");I(A)},m.DEFAULT_RETRY_DATACHANNEL_TIMEOUT);var C=function(A){A.status===d.EDatachannelStatus.DATACHANNEL_STATUS_OPEN&&(clearTimeout(R.dcOpenTimer),R.commonController.off("datachannelStatusChange",C),E())};R.commonController.on("datachannelStatusChange",C)})},S.prototype.restructureStreams=function(){var R,E,I=(R=this.commonController.peerCore)===null||R===void 0?void 0:R.getStreamManager(),C=(E=this.commonController.peerCore)===null||E===void 0?void 0:E.getDatachannelManager(),A=I==null?void 0:I.getAllStreamListWithMsids(),w=C==null?void 0:C.getAllList(),N=[];return A==null||A.forEach(function(M){var D;(D=M.streams)===null||D===void 0||D.forEach(function(L){var P=[],x=[],T=M.type,O=M.latestUrl,k=L;M.msids.forEach(function(H){H.streamId===L.id&&(H.type==="video"?x.push(H.name):H.type==="audio"&&P.push(H.name))}),N.push({aMsid:P,vMsid:x,type:T,url:O,targetStream:k})})}),w==null||w.forEach(function(M){M.msids.forEach(function(D){if(D.name&&D.label){var L=D.name,P=D.label,x=M.type,T=M.latestUrl;N.push({msid:L,type:x,label:P,url:T})}})}),N},S.prototype.dispose=function(){this.removeAllListeners(),clearTimeout(this.dcOpenTimer)},S.prototype.makeSingleStreamReconnectError=function(R){return new b.RtsError(u.ErrorCode.ERROR_SINGLE_PC_STREAM_RECONNECT_FAILED,"single stream reconnect failed","",{originError:R})},S.prototype.makeIpQuery=function(R,E,I){var C,A,w,N="ali_prefer_media_server",M="ip_migration",D=R,L="";if(I.indexOf("sub")===0&&(!((A=E.pull)===null||A===void 0)&&A.length)?L=E.pull[0]:I.indexOf("pub")===0&&(!((w=E.push)===null||w===void 0)&&w.length)&&(L=E.push[0]),L){var P=R.split("?"),x=P[0],T=P[1],O=void 0;T?((O=new URLSearchParams(T)).has(N)?O.set(N,L):O.append(N,L),!O.has(M)&&O.append(M,"on")):O=new URLSearchParams(((C={})[N]=L,C[M]="on",C)),D="".concat(x,"?").concat(O.toString())}return D},S}(_.default);s.PcRestorer=y},4865:function(a,s,o){var c,h=this&&this.__extends||(c=function(P,x){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(T,O){T.__proto__=O}||function(T,O){for(var k in O)Object.prototype.hasOwnProperty.call(O,k)&&(T[k]=O[k])},c(P,x)},function(P,x){if(typeof x!="function"&&x!==null)throw new TypeError("Class extends value "+String(x)+" is not a constructor or null");function T(){this.constructor=P}c(P,x),P.prototype=x===null?Object.create(x):(T.prototype=x.prototype,new T)}),l=this&&this.__assign||function(){return l=Object.assign||function(P){for(var x,T=1,O=arguments.length;T<O;T++)for(var k in x=arguments[T])Object.prototype.hasOwnProperty.call(x,k)&&(P[k]=x[k]);return P},l.apply(this,arguments)},f=this&&this.__awaiter||function(P,x,T,O){return new(T||(T=Promise))(function(k,H){function U($){try{W(O.next($))}catch(B){H(B)}}function ee($){try{W(O.throw($))}catch(B){H(B)}}function W($){var B;$.done?k($.value):(B=$.value,B instanceof T?B:new T(function(F){F(B)})).then(U,ee)}W((O=O.apply(P,x||[])).next())})},v=this&&this.__generator||function(P,x){var T,O,k,H,U={label:0,sent:function(){if(1&k[0])throw k[1];return k[1]},trys:[],ops:[]};return H={next:ee(0),throw:ee(1),return:ee(2)},typeof Symbol=="function"&&(H[Symbol.iterator]=function(){return this}),H;function ee(W){return function($){return function(B){if(T)throw new TypeError("Generator is already executing.");for(;H&&(H=0,B[0]&&(U=0)),U;)try{if(T=1,O&&(k=2&B[0]?O.return:B[0]?O.throw||((k=O.return)&&k.call(O),0):O.next)&&!(k=k.call(O,B[1])).done)return k;switch(O=0,k&&(B=[2&B[0],k.value]),B[0]){case 0:case 1:k=B;break;case 4:return U.label++,{value:B[1],done:!1};case 5:U.label++,O=B[1],B=[0];continue;case 7:B=U.ops.pop(),U.trys.pop();continue;default:if(k=U.trys,!((k=k.length>0&&k[k.length-1])||B[0]!==6&&B[0]!==2)){U=0;continue}if(B[0]===3&&(!k||B[1]>k[0]&&B[1]<k[3])){U.label=B[1];break}if(B[0]===6&&U.label<k[1]){U.label=k[1],k=B;break}if(k&&U.label<k[2]){U.label=k[2],U.ops.push(B);break}k[2]&&U.ops.pop(),U.trys.pop();continue}B=x.call(P,U)}catch(F){B=[6,F],O=0}finally{T=k=0}if(5&B[0])throw B[1];return{value:B[0]?B[1]:void 0,done:!0}}([W,$])}}},p=this&&this.__importDefault||function(P){return P&&P.__esModule?P:{default:P}};Object.defineProperty(s,"__esModule",{value:!0}),s.RtsPeerconnection=void 0;var _,m=o(280),d=o(233),u=o(4315),b=o(2718),y=p(o(102)),g=o(1698),S=o(5917),R=o(4699),E=o(9752),I=o(5553),C=o(9428),A=o(5044),w=p(o(6834));(function(P){P.Subscribe="sub",P.Publish="pub"})(_||(_={}));var N=window.RTCRtpReceiver&&"createEncodedStreams"in RTCRtpReceiver.prototype,M=window.RTCRtpReceiver&&"transform"in RTCRtpReceiver.prototype&&"RTCRtpScriptTransform"in window,D=function(P){function x(){var T=P.call(this)||this;return T.connectingEventSent=!1,T.reused=!1,T.transformWorkerList=new L,T.receiverCodecPreferences={},T.senderCodecPreferences={},T.heartbeatTimeoutHandler=null,T.noHeartbeatCount=0,T.lastVideoBytesReceived=0,T.lastAudioBytesReceived=0,T.enablePullStreamAliveDetect=!0,T.subMonitor=new R.SubMonitor,T.subMonitor.on("onMonitorEvent",function(O){T.emit("onMonitorEvent",O)}),T.subMonitor.on("streamEnded",function(){T.emit("streamEnded")}),T.subMonitor.on("canPlay",function(){}),T.pubMonitor=new E.PubMonitor,T.pubMonitor.on("onMonitorEvent",function(O){T.emit("onMonitorEvent",O)}),T.pubMonitor.on("onTransportStateEvent",function(O){T.emit("onTransportStateEvent",O)}),T}return h(x,P),Object.defineProperty(x.prototype,"isConnected",{get:function(){var T;return((T=this.pc)===null||T===void 0?void 0:T.connectionState)==="connected"},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"isReused",{get:function(){return this.reused},set:function(T){this.reused=!!T},enumerable:!1,configurable:!0}),x.prototype.getWorkerManager=function(){return this.transformWorkerList},x.prototype.getPc=function(){return this.pc},x.prototype.getPeerCore=function(){return this.peerCore},x.prototype.getSubMonitor=function(){return this.subMonitor},x.prototype.getPubMonitor=function(){return this.pubMonitor},x.prototype.playStart=function(){this.subMonitor.resetTimer(1e3)},x.prototype.pushStart=function(){this.pc&&this.peerCore&&this.pubMonitor.startHeartbeat(this.pc,this.peerCore)},x.prototype.sample=function(){return f(this,void 0,void 0,function(){return v(this,function(T){switch(T.label){case 0:return[4,this.subMonitor.onMonitorTimer()];case 1:return T.sent(),[2]}})})},x.prototype.subAdd=function(T,O){var k;return(k=this.peerCore)===null||k===void 0?void 0:k.subscribeAdd(T,O)},x.prototype.subActive=function(T){var O;return(O=this.peerCore)===null||O===void 0?void 0:O.subscribeActive(T)},x.prototype.subStop=function(T){var O;return(O=this.peerCore)===null||O===void 0?void 0:O.subscribeStop(T)},x.prototype.subDeleteTracks=function(T){var O;return(O=this.peerCore)===null||O===void 0?void 0:O.subscribeDeleteTracks(T)},x.prototype.pubAdd=function(T){var O;return(O=this.peerCore)===null||O===void 0?void 0:O.publishAdd(T)},x.prototype.pubDeleteTracks=function(T){var O;return(O=this.peerCore)===null||O===void 0?void 0:O.publishDeleteTracks(T)},x.prototype.pubReplaceTracks=function(T){var O;return(O=this.peerCore)===null||O===void 0?void 0:O.publishReplaceTracks(T)},x.prototype.pubStop=function(T){var O;return(O=this.peerCore)===null||O===void 0?void 0:O.publishStop(T)},x.prototype.createOffer=function(T,O,k,H){var U=this;return H===void 0&&(H={publishUrl:""}),new Promise(function(ee,W){var $;($=U.cancelable)===null||$===void 0||$.cancel();var B={googCpuOveruseDetection:!1,sdpSemantics:"unified-plan",encodedInsertableStreams:H.encodedInsertableStreams,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"};if(d.BrowserUtil.isChrome&&Number(d.BrowserUtil.browserMainVersion)<=55&&(B.iceServers=[]),U.pc=new RTCPeerConnection(B),U.encodedInsertableStreams=H.encodedInsertableStreams,U.peerCore=new m.PeerConnectionCore({pc:U.pc,onDatachannelEvent:function(X){var J,se,ce,Y,fe;U.emit("datachannelStatusChange",{status:X}),H.disableHeartbeat||(U.enablePullStreamAliveDetect=(se=(J=H.heartbeat)===null||J===void 0?void 0:J.enablePullStreamAliveDetect)===null||se===void 0||se,X===m.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?((0,b.hebtLog)("DATACHANNEL OPEN"," heartbeat send scheduler started"),(ce=U.peerCore)===null||ce===void 0||ce.startSignalHeartbeatTimer((Y=H==null?void 0:H.heartbeat)===null||Y===void 0?void 0:Y.interval)):X===m.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&((0,b.hebtLog)("DATACHANNEL CLOSE"," heartbeats from now on will fail"),(fe=U.peerCore)===null||fe===void 0||fe.stopSignalHeartbeatTimer()))},onInnerSubscribeDelete:function(X){U.emit("innerSubscribeDeleteTracks",X)},offerSdpHook:H.offerSdpHook,answerSdpHook:H.answerSdpHook,delayOpen:g.configProvider.getContext().datachannelDelayOpen,signalDatachannelInitOptions:g.configProvider.getContext().signalDatachannelInitOptions}),U.registerPeerCoreListeners(H),U.peerCore.setReceiverCodecPreferences(U.receiverCodecPreferences),U.peerCore.setSenderCodecPreferences(U.senderCodecPreferences),U.pc.onconnectionstatechange=function(){var X=(U.pc||{}).connectionState;switch(U.connectingEventSent||(U.connectingEventSent=!0,U.emit("connectStatusChange",{status:S.EConnectStatus.CONNECT_STATUS_CONNECTING})),X!=="connecting"&&U.clearStatusTimer(),X){case"connected":U.emit("onConnected"),U.emit("connectStatusChange",{status:S.EConnectStatus.CONNECT_STATUS_CONNECTED});break;case"disconnected":U.emit("connectStatusChange",{status:S.EConnectStatus.CONNECT_STATUS_RECONNECTING});break;case"failed":case"closed":U.handleClosed()}},U.clearStatusTimer(),U.statusTimer=window.setTimeout(function(){U.handleClosed()},x.CONNECT_TIMEOUT),k){U.localStream=k,U.sdpUtil=new u.SdpUtil(U.localStream);var F=U.addStream();if(F!==0)return U.pc=void 0,void W(new A.RtsError(F,F===C.ErrorCode.ERROR_MEDIASTREAMTRACK_AUDIO_NONE?"need audio track":"",""))}else U.sdpUtil=new u.SdpUtil;var G={};k||(G=U.handleSubTransceiver(T,O).added?{}:{offerToReceiveAudio:T,offerToReceiveVideo:O});var q=U.pc.createOffer(G);U.cancelable=(0,b.makeCancelable)(q),U.cancelable.promise.then(function(X){var J,se,ce,Y,fe,he,pe;if(U.cancelable=void 0,U.sdpUtil){if(U.sdpUtil.init(String(X.sdp)),U.sdpUtil.addNack(),U.sdpUtil.addSps(),H.disableStereo||U.sdpUtil.addStereo(),H.cumuDelay&&(U.sdpUtil.setSingleNaluPackMode()||U.emit("cumuDelayNotSupported")),k&&U.sdpUtil.modifyTrackName({vMsid:H.vMsid&&H.vMsid[0],aMsid:H.aMsid&&H.aMsid[0]}),U.pc){if(X.sdp=U.sdpUtil.sdp,k&&k.sdpHook&&typeof k.sdpHook=="function")try{X.sdp=k.sdpHook(X.sdp)}catch(be){console.log("Error in sdp hook",be)}(J=U.peerCore)===null||J===void 0||J.setPrevOfferSdp(X.sdp||"");var ue=[];if(k)try{(se=U.peerCore)===null||se===void 0||se.patchPublishStreamManagerRecord(H.publishUrl||"",l(l({},H),{stream:k,cumuDelay:H.cumuDelay}));var Te=(ce=U.peerCore)===null||ce===void 0?void 0:ce.parseSdp(X.sdp||"");ue=(Y=U.peerCore)===null||Y===void 0?void 0:Y.updateTrackInfoList({url:H.publishUrl||"",stream:k,vMsid:(fe=U.peerCore)===null||fe===void 0?void 0:fe.unifyMsid(H.vMsid,"video"),aMsid:(he=U.peerCore)===null||he===void 0?void 0:he.unifyMsid(H.aMsid,"audio"),sdpMediaList:(pe=Te==null?void 0:Te.detail)===null||pe===void 0?void 0:pe.media})}catch(be){console.log(be)}if(H.offerSdpHook&&typeof H.offerSdpHook=="function")try{X.sdp=H.offerSdpHook(X.sdp||"")}catch(be){console.log("Error in offerSdpHook",be)}U.pc.setLocalDescription(X).then(function(){U.pc?ee({desp:U.pc.localDescription,publishTrackInfoList:ue}):W(new A.RtsError(C.ErrorCode.ERROR_CREATEOFFER,"no pc",""))}).catch(function(be){W(new A.RtsError(C.ErrorCode.ERROR_CREATEOFFER,"setLocalDescription error "+be.message,""))})}}else W(new A.RtsError(C.ErrorCode.ERROR_CREATEOFFER,"no sdp",""))}).catch(function(X){X.isCanceled||W(new A.RtsError(C.ErrorCode.ERROR_CREATEOFFER,X.message?X.message:"create offer error",""))})})},x.prototype.recvAnswer=function(T,O){var k,H,U=this;return O===void 0&&(O={}),(k=this.peerCore)===null||k===void 0||k.setPrevAnswerSdp((H=T==null?void 0:T.jsep)===null||H===void 0?void 0:H.sdp),new Promise(function(ee,W){var $,B,F,G,q,X;if(U.pc){if(U.pc.ontrack=function(se){U.pc&&U.peerCore&&U.subMonitor.start(U.pc,U.peerCore),setTimeout(function(){U.handleEncodedInsertableStreams({receiver:se.receiver})}),U.isReused||U.emit("onTrackEvent",se)},U.pc.signalingState==="closed")return void W({message:"PeerConnection signalingState is closed"});if(!(($=T.jsep)===null||$===void 0)&&$.sdp){var J=new u.SdpUtil;J.init(String((B=T.jsep)===null||B===void 0?void 0:B.sdp)),U.localStream&&(U.localStream.audioTrack&&!U.localStream.videoTrack&&(J.removeTwccRtcpFb(),(F=U.peerCore)===null||F===void 0||F.setRemoveTwcc(!0)),J.setDirection()),O.tcpOnly&&J.hasTcpCandidate&&J.removeUdpCandidate(),T.jsep.sdp=J.sdp,(G=U.peerCore)===null||G===void 0||G.setPrevAnswerSdp((q=T==null?void 0:T.jsep)===null||q===void 0?void 0:q.sdp)}if(!((X=T.jsep)===null||X===void 0)&&X.sdp&&O.answerSdpHook&&typeof O.answerSdpHook=="function")try{T.jsep.sdp=O.answerSdpHook(T.jsep.sdp)}catch(se){console.log("Error in answerSdpHook",se)}U.pc.setRemoteDescription(new RTCSessionDescription(T.jsep)).then(function(se){var ce;U.pc&&U.localStream&&(U.localStream.setEncodeParam(U.pc),(ce=U.pc)===null||ce===void 0||ce.getSenders().forEach(function(Y){U.handleEncodedInsertableStreams({sender:Y})})),ee(se)}).catch(function(se){se.sdp=T.jsep.sdp,W(se)})}else W({message:"no PeerConnection"})})},x.prototype.setReceiverCodecPreferences=function(T){var O;this.receiverCodecPreferences=l({},T),(O=this.peerCore)===null||O===void 0||O.setReceiverCodecPreferences(this.receiverCodecPreferences)},x.prototype.setSenderCodecPreferences=function(T){var O;this.senderCodecPreferences=l({},T),(O=this.peerCore)===null||O===void 0||O.setSenderCodecPreferences(this.senderCodecPreferences)},x.prototype.removeTrack=function(T,O){var k=this;return new Promise(function(H,U){k.pc&&k.dataChannel&&k.dataChannel.removeTrack(T,O).then(function(){}).catch(function(ee){U(ee)})})},x.prototype.replaceTrack=function(T,O,k){var H=this;return new Promise(function(U,ee){k||H.pc&&H.dataChannel&&H.dataChannel.removeTrack(T,O).then(function(){}).catch(function(W){ee(W)})})},x.prototype.sendSEI=function(T){var O;if(!T.data)throw new Error("No data to send, please check your params.");if(!(T.data instanceof ArrayBuffer))throw new Error("data should be ArrayBuffer, please check your params.");if(!T.url)throw new Error("url is required, please check your params.");if(!T.vMsid)throw new Error("vMsid is required, please check your params.");if(N||M){var k=this.transformWorkerList.findByMsid({url:T.url,kind:S.TrackType.VIDEO,source:S.EWorkerSource.Sender,msid:T.vMsid});if(!k)throw new Error("No published stream found, please check your url: "+T.url);(O=k==null?void 0:k.worker)===null||O===void 0||O.postMessage({operation:S.EWorkerAction.InserSEI,payloadType:T.payloadType,repeatCount:T.repeatCount,keyframeOnly:T.keyframeOnly,sei:T.data})}},x.prototype.updateStatsForSEI=function(T,O){var k=this,H=O==="pub";this.encodedInsertableStreams&&(N||M)&&T.forEach(function(U){var ee,W=k.transformWorkerList.findByMsid({url:U.url,kind:S.TrackType.VIDEO,source:H?S.EWorkerSource.Sender:S.EWorkerSource.Receiver,msid:U.vMsid});W&&((ee=W==null?void 0:W.worker)===null||ee===void 0||ee.postMessage({operation:H?S.EWorkerAction.UpdatePubStats:S.EWorkerAction.UpdateSubStats,stats:U}))})},x.prototype.reset=function(){this.cancelable&&(this.cancelable.cancel(),this.cancelable=void 0),this.peerCore&&(this.peerCore.dispose(),this.peerCore=void 0),this.pc&&(this.pc.onconnectionstatechange=function(){},this.pc.ontrack=function(){},this.pc.close(),this.pc=void 0,this.clearStatusTimer()),this.sdpUtil&&(this.sdpUtil.dispose(),this.sdpUtil=void 0),this.localStream&&(this.localStream=void 0),this.transformWorkerList.dispose(),this.subMonitor.stop(),this.pubMonitor.stopHeartbeat(),this.isReused=!1,this.encodedInsertableStreams=void 0,this.stopHeartbeatTimeoutChecker()},x.prototype.addStream=function(){if(this.localStream){if(this.pc){if(this.localStream.audioTrack){var T=this.pc.addTransceiver(this.localStream.audioTrack,{direction:"sendonly",streams:[this.localStream.mediaStream]});if(this.senderCodecPreferences.audio)try{T.setCodecPreferences(this.senderCodecPreferences.audio)}catch(k){console.warn("setCodecPreferences error",k)}}if(this.localStream.videoTrack){var O=this.pc.addTransceiver(this.localStream.videoTrack,{direction:"sendonly",streams:[this.localStream.mediaStream]});if(this.senderCodecPreferences.video)try{O.setCodecPreferences(this.senderCodecPreferences.video)}catch(k){console.warn("setCodecPreferences error",k)}}return 0}return C.ErrorCode.ERROR_PREERCONNECTION_UNKNOWN}return C.ErrorCode.ERROR_MEDIASTREAMTRACK_AUDIO_NONE},x.prototype.handleEncodedInsertableStreams=function(T){var O,k,H=this;if(this.encodedInsertableStreams){var U=T.receiver,ee=T.sender,W=U?S.EWorkerSource.Receiver:S.EWorkerSource.Sender,$=U||ee,B=$.track;if(!B)return console.warn("no track in senderReceiver!");var F=B.kind,G=(k=(O=this.peerCore)===null||O===void 0?void 0:O.getStreamManager())===null||k===void 0?void 0:k.getAllTrackPairList(W===S.EWorkerSource.Receiver?_.Subscribe:_.Publish),q=G==null?void 0:G.find(function(he){var pe,ue;return((ue=(pe=he[F===S.TrackType.VIDEO?"vTransceiver":"aTransceiver"])===null||pe===void 0?void 0:pe.track)===null||ue===void 0?void 0:ue.id)===B.id});if(!q)return console.warn("no existing stream info found");var X=new w.default;if(this.transformWorkerList.removeByMsid({url:q.url||"",kind:F,source:W,msid:(F===S.TrackType.VIDEO?q.vMsid:q.aMsid)||""}),!this.transformWorkerList.add({worker:X,kind:F,source:W,info:q,receiver:U,sender:ee}))return console.log("worker existing, skip.",F);var J=S.EWorkerAction.Setup,se=performance.timeOrigin;if(N){var ce=$.createEncodedStreams(),Y=ce.readable,fe=ce.writable;X.postMessage({source:W,readable:Y,writable:fe,operation:J},[Y,fe])}else M&&($.transform=new RTCRtpScriptTransform(X,{source:W,operation:J,windowTimeOrigin:se}));q.cumuDelay&&F==="video"&&(X.postMessage({operation:S.EWorkerAction.SwitchCumuDelay,enable:!0,windowTimeOrigin:se}),N||M||this.emit("cumuDelayNotSupported")),X.onmessage=function(he){var pe=he.data,ue=pe.type,Te=pe.data,be=pe.frameInfo;ue==="encodedFrame"&&H.emit("encodedFrame",{kind:F,url:q.originUrl,vMsid:F==="video"?q==null?void 0:q.vMsid:void 0,aMsid:F==="audio"?q==null?void 0:q.aMsid:void 0,frame:l({data:Te},be),subStats:he.data.subStats})}}},x.prototype.handleSubTransceiver=function(T,O){var k,H,U,ee=!1;if(!((k=this.pc)===null||k===void 0)&&k.addTransceiver){if(T&&(H=this.pc.addTransceiver("audio",{direction:"recvonly"}),this.receiverCodecPreferences.audio))try{H.setCodecPreferences(this.receiverCodecPreferences.audio)}catch(W){console.warn("setCodecPreferences error",W)}if(O&&(U=this.pc.addTransceiver("video",{direction:"recvonly"}),this.receiverCodecPreferences.video))try{U.setCodecPreferences(this.receiverCodecPreferences.video)}catch(W){console.warn("setCodecPreferences error",W)}ee=!0}return{added:ee,aTransceiver:H,vTransceiver:U}},x.prototype.initDataChannel=function(){!this.dataChannel&&this.pc&&(this.dataChannel=new I.Datachannel(this.pc))},x.prototype.handleClosed=function(){this.subMonitor.stop(),this.emit("connectStatusChange",{status:S.EConnectStatus.CONNECT_STATUS_DISCONNECTED}),this.emit("onEnd")},x.prototype.clearStatusTimer=function(){this.statusTimer&&clearTimeout(this.statusTimer),this.statusTimer=void 0},x.prototype.registerPeerCoreListeners=function(T){var O,k=this;this.peerCore?(T.disableHeartbeat||((0,b.hebtLog)("heartbeat [timeout checker] started"),this.startHeartbeatTimeoutChecker((O=T==null?void 0:T.heartbeat)===null||O===void 0?void 0:O.timeout)),this.peerCore.on("message",function(H){k.emit("message",H)}),this.peerCore.on("signalSent",function(H){k.emit("signalSent",H)}),this.peerCore.on("signalReceived",function(H){k.emit("signalReceived",H)}),this.peerCore.on("hebtDropped",function(H){(0,b.hebtLog)("EVENT: HEBT DROPPED",H),k.noHeartbeatCount=0,k.emit("hebtDropped",H)}),this.peerCore.on("hebtSent",function(H){(0,b.hebtLog)("EVENT: HEBT SENT",H),k.emit("hebtSent",H)}),this.peerCore.on("hebtReceived",function(H){(0,b.hebtLog)("EVENT: HEBT RECV",H),k.noHeartbeatCount=0,k.emit("hebtReceived",H)}),this.peerCore.on("streamError",function(H){(0,b.hebtLog)("EVENT: 单路流错误",H),k.emit("streamError",H)}),this.peerCore.on("streamReconnect",function(H){(0,b.hebtLog)("EVENT: 单路流重连",H),k.emit("streamReconnect",H)}),this.peerCore.on("traceIdUpdate",function(H){k.emit("traceIdUpdate",H)}),this.peerCore.on("pcReconnect",function(H){(0,b.hebtLog)("EVENT: PC重连",H),k.emit("pcReconnect",H)}),this.peerCore.on("datachannelNotEnabled",function(){var H;(0,b.hebtLog)("EVENT: 数据通道未开启"),k.stopHeartbeatTimeoutChecker(),(H=k.peerCore)===null||H===void 0||H.stopSignalHeartbeatTimer()})):(0,b.hebtLog)("PeerCore listeners registration failed.")},x.prototype.startHeartbeatTimeoutChecker=function(T){var O=this;this.stopHeartbeatTimeoutChecker();var k=S.DEFAULT_HEARTBEAT_TIMEOUT_COUNT;T&&(k=T/S.DEFAULT_HEARTBEAT_TIMEOUT_CHECK_INTERVAL),this.heartbeatTimeoutHandler=setInterval(function(){var H;O.noHeartbeatCount++,O.enablePullStreamAliveDetect&&((H=O.getPc())===null||H===void 0||H.getStats().then(function(U){U&&U.forEach(function(ee){ee.type==="inbound-rtp"&&(ee.kind==="video"?(O.lastVideoBytesReceived&&ee.bytesReceived>O.lastVideoBytesReceived&&(O.noHeartbeatCount=0),O.lastVideoBytesReceived=ee.bytesReceived):ee.kind==="audio"&&(O.lastAudioBytesReceived&&ee.bytesReceived>O.lastAudioBytesReceived&&(O.noHeartbeatCount=0),O.lastAudioBytesReceived=ee.bytesReceived))})}).catch(function(U){console.log("getStats failed,",U,", ignore it.")})),O.noHeartbeatCount>=k&&((0,b.hebtLog)("EVENT: 心跳超时, PC重连"),O.stopHeartbeatTimeoutChecker(),O.emit("pcReconnect",{recode:"",reMsg:"heartbeat timeout"}))},S.DEFAULT_HEARTBEAT_TIMEOUT_CHECK_INTERVAL)},x.prototype.stopHeartbeatTimeoutChecker=function(){this.heartbeatTimeoutHandler!==null&&clearInterval(this.heartbeatTimeoutHandler),this.heartbeatTimeoutHandler=null,this.noHeartbeatCount=0},x.CONNECT_TIMEOUT=1e4,x}(y.default);s.RtsPeerconnection=D;var L=function(){function P(){this.workerList=[]}return P.prototype.add=function(x){return!this.findByMsid({url:x.info.url,source:x.source,kind:x.kind,msid:x.kind===S.TrackType.VIDEO?x.info.vMsid:x.info.aMsid})&&(this.workerList.push(x),!0)},P.prototype.removeByUrl=function(x){var T=this;this.workerList.filter(function(O){return O.info.url.split("?")[0]===x.url.split("?")[0]&&O.source===x.source}).forEach(function(O){O.worker.terminate(),T.workerList=T.workerList.filter(function(k){return k!==O})})},P.prototype.removeByMsid=function(x){var T=this.findByMsid(x);T&&(T.worker.terminate(),this.workerList=this.workerList.filter(function(O){return O!==T}))},P.prototype.findByUrl=function(x,T){return this.workerList.find(function(O){return O.info.url.split("?")[0]===x.split("?")[0]&&O.kind===T})},P.prototype.findByMsid=function(x){var T=x.url,O=x.kind,k=x.source,H=x.msid,U=O===S.TrackType.VIDEO?"vMsid":"aMsid";return this.workerList.find(function(ee){return ee.info.url.split("?")[0]===T.split("?")[0]&&ee.source===k&&ee.kind===O&&ee.info[U]===H})},P.prototype.dispose=function(){this.workerList.forEach(function(x){x.worker.terminate()}),this.workerList=[]},P}()},2825:(a,s)=>{Object.defineProperty(s,"__esModule",{value:!0})},8156:function(a,s,o){var c=this&&this.__createBinding||(Object.create?function(p,_,m,d){d===void 0&&(d=m);var u=Object.getOwnPropertyDescriptor(_,m);u&&!("get"in u?!_.__esModule:u.writable||u.configurable)||(u={enumerable:!0,get:function(){return _[m]}}),Object.defineProperty(p,d,u)}:function(p,_,m,d){d===void 0&&(d=m),p[d]=_[m]}),h=this&&this.__exportStar||function(p,_){for(var m in p)m==="default"||Object.prototype.hasOwnProperty.call(_,m)||c(_,p,m)};Object.defineProperty(s,"__esModule",{value:!0}),s.EDatachannelStatus=s.EConnectStatus=s.AliRTS=void 0,o(9543);var l=o(4845);Object.defineProperty(s,"AliRTS",{enumerable:!0,get:function(){return l.AliRTS}}),window&&(window.AliRTS=l.AliRTS);var f=o(5917);Object.defineProperty(s,"EConnectStatus",{enumerable:!0,get:function(){return f.EConnectStatus}});var v=o(280);Object.defineProperty(s,"EDatachannelStatus",{enumerable:!0,get:function(){return v.EDatachannelStatus}}),h(o(2825),s)},2672:(a,s)=>{var o;Object.defineProperty(s,"__esModule",{value:!0}),s.EN=void 0,function(c){c.MESSAGE_NOTSUPPORT_WEBRTC="not support webrtc",c.MESSAGE_BROWSER_NOTSUPPORT="browser not support",c.MESSAGE_BROWSER_VERSIONLOW="browser version too low",c.MESSAGE_NOTSUPPORT_H264="not support h264",c.MESSAGE_CREATEOFFER="create offer error"}(o||(s.EN=o={}))},2818:function(a,s,o){var c=this&&this.__assign||function(){return c=Object.assign||function(u){for(var b,y=1,g=arguments.length;y<g;y++)for(var S in b=arguments[y])Object.prototype.hasOwnProperty.call(b,S)&&(u[S]=b[S]);return u},c.apply(this,arguments)},h=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(s,"__esModule",{value:!0});var l,f=o(233),v=h(o(7028)),p=o(9428),_=h(o(2632)),m=h(o(1401));(function(u){u[u.UA=101]="UA",u[u.SUB_STATS=107]="SUB_STATS",u[u.PUB_STATS=108]="PUB_STATS",u[u.CONNECT_STATE_CHANGE=109]="CONNECT_STATE_CHANGE",u[u.START_PLAY=120]="START_PLAY",u[u.STOP_PLAY=121]="STOP_PLAY",u[u.SUBSCRIBE_START=125]="SUBSCRIBE_START",u[u.SUBSCRIBE_OK=126]="SUBSCRIBE_OK",u[u.FIRST_FRAME_TIME=137]="FIRST_FRAME_TIME",u[u.DC_HTTP_CONNECT=140]="DC_HTTP_CONNECT",u[u.DC_HTTP_CONNECT_OK=141]="DC_HTTP_CONNECT_OK",u[u.DC_SUB_ADD=142]="DC_SUB_ADD",u[u.DC_SUB_ADD_OK=143]="DC_SUB_ADD_OK",u[u.DC_CONNECT_STATE_CHANGE=144]="DC_CONNECT_STATE_CHANGE",u[u.DC_SUB_STOP=145]="DC_SUB_STOP",u[u.DC_SUB_STOP_OK=146]="DC_SUB_STOP_OK",u[u.DC_DISPOSE=147]="DC_DISPOSE",u[u.DC_SUB_DELETE=148]="DC_SUB_DELETE",u[u.DC_SUB_DELETE_OK=149]="DC_SUB_DELETE_OK",u[u.ERROR_INFO=150]="ERROR_INFO",u[u.DC_PUB_ADD=152]="DC_PUB_ADD",u[u.DC_PUB_ADD_OK=153]="DC_PUB_ADD_OK",u[u.DC_PUB_STOP=155]="DC_PUB_STOP",u[u.DC_PUB_STOP_OK=156]="DC_PUB_STOP_OK",u[u.DC_PUB_DELETE=157]="DC_PUB_DELETE",u[u.DC_PUB_DELETE_OK=158]="DC_PUB_DELETE_OK",u[u.RECONNECT=160]="RECONNECT",u[u.RECONNECT_PARAMS=161]="RECONNECT_PARAMS",u[u.RECONNECT_FINISH=162]="RECONNECT_FINISH",u[u.NOTIFY_MESSAGE=170]="NOTIFY_MESSAGE",u[u.CUMU_DELAY_NOT_SUPPORTED=180]="CUMU_DELAY_NOT_SUPPORTED",u[u.CUMU_DELAY_ANSWER_NOT_FOUND=181]="CUMU_DELAY_ANSWER_NOT_FOUND",u[u.CREATE_CLIENT=200]="CREATE_CLIENT",u[u.LOCALSTREAM_INITED=201]="LOCALSTREAM_INITED",u[u.START_PUBLISH=220]="START_PUBLISH",u[u.STOP_PUBLISH=221]="STOP_PUBLISH",u[u.PUBLISH_OK=222]="PUBLISH_OK",u[u.SET_VIDEOPROFILE=230]="SET_VIDEOPROFILE",u[u.SET_SCREENPROFILE=231]="SET_SCREENPROFILE",u[u.SET_AUDIOPROFILE=238]="SET_AUDIOPROFILE",u[u.ENABLE_AUDIO=232]="ENABLE_AUDIO",u[u.DISABLE_AUDIO=233]="DISABLE_AUDIO",u[u.ENABLE_VIDEO=234]="ENABLE_VIDEO",u[u.DISABLE_VIDEO=235]="DISABLE_VIDEO",u[u.STOP=236]="STOP",u[u.PLAY=237]="PLAY"})(l||(l={}));var d=function(){function u(b){this.customReporter=b==null?void 0:b.customReporter,this.ct=b&&b.customTag?b.customTag:"",this.enableLog=!b||b.trackLog!=0,this._initParam();var y="cn-hangzhou.log.aliyuncs.com",g="videocloud",S="live-client-log";(b==null?void 0:b.env)==="SEA"&&(y="ap-southeast-1.log.aliyuncs.com",g="videocloud-sgp",S="live-client-log"),this.slsTracker=new _.default({host:y,project:g,logstore:S,time:10,count:10})}return u.prototype.dispose=function(){this.ct="",this.enableLog=!0,this.slsTracker=null,this.cumuDelayInfo=void 0,this.customReporter=void 0},u.prototype.updateTid=function(){this.param?this.param.tid=f.Guid.create(32):this._initParam()},u.prototype.updateUrl=function(b){this.param&&(this.param.pu=b)},u.prototype.reportUA=function(b){this.reporter({msgid:l.UA,args:(0,m.default)({ua:b})})},u.prototype.reportPullStats=function(b){var y,g=c(c({},b),{cumu:""});if(this.cumuDelayInfo)try{y=JSON.parse(this.cumuDelayInfo)}catch{}y&&(this.cumuDelayInfo=void 0,g.cumu=y),this.reporter({msgid:l.SUB_STATS,args:(0,m.default)(c({},g))})},u.prototype.reportPushStats=function(b){this.reporter({msgid:l.PUB_STATS,args:(0,m.default)(c({},b))})},u.prototype.reportStartPlay=function(b){this.reporter({msgid:l.START_PLAY,args:(0,m.default)({vurl:b})})},u.prototype.reportStopPlay=function(){this.reporter({msgid:l.STOP_PLAY})},u.prototype.reportSubscribeStart=function(b,y,g,S,R){this.reporter({msgid:l.SUBSCRIBE_START,args:(0,m.default)({vurl:b,surl:y,vMsid:g?g.join(", "):"",aMsid:S?S.join(", "):"",isSubAdd:!!R})})},u.prototype.reportSubscribeOk=function(b){b===void 0&&(b={}),this.reporter({msgid:l.SUBSCRIBE_OK,args:(0,m.default)({vurl:b.vurl||"",surl:b.surl||"",hrct:b.hrct,tcid:b.traceId,rslt:b.rslt,isSubAdd:!!b.isSubAdd})})},u.prototype.reportFirstFrameTime=function(b,y,g,S,R,E,I,C,A,w,N,M,D,L){this.reporter({msgid:l.FIRST_FRAME_TIME,args:(0,m.default)({vurl:b,cpct:g,hrct:S,tcid:y,ffct:R,rslt:E,cnct:I,stats:C,delct:A,addct:w,actct:N,vMsid:M?M.join(", "):"",aMsid:D?D.join(", "):"",isSubAdd:!!L})})},u.prototype.reportErrorInfo=function(b,y,g,S){b!==p.ErrorCode.ERROR_AUTOPLAY_ERROR&&this.reporter({msgid:l.ERROR_INFO,args:(0,m.default)({errorCode:b,message:y,tcid:g,extraInfo:S})})},u.prototype.reportReconnect=function(b,y,g,S,R){this.reporter({msgid:l.RECONNECT,args:(0,m.default)({errorCode:b,message:y,tcid:g,retryTimes:S,useTcp:R})})},u.prototype.reportReconnectParams=function(b,y,g,S,R,E){this.reporter({msgid:l.RECONNECT_PARAMS,args:(0,m.default)({type:b,url:y,vMsid:(g||[]).join(","),aMsid:(S||[]).join(","),useTcp:R,streamId:E})})},u.prototype.reportReconnectFinish=function(b){b===void 0&&(b={}),this.reporter({msgid:l.RECONNECT_FINISH,args:(0,m.default)(c({},b))})},u.prototype.reportCreateClient=function(){this.reporter({msgid:l.CREATE_CLIENT})},u.prototype.reportStartPublish=function(b,y,g){this.reporter({msgid:l.START_PUBLISH,args:(0,m.default)({purl:b,surl:y,isPubAdd:!!g})})},u.prototype.reportPublishOk=function(b,y,g,S,R,E,I,C){this.reporter({msgid:l.PUBLISH_OK,args:(0,m.default)({purl:b,surl:y,coct:g,hrct:S,act:R,tcid:E,totalct:I||g+S+R,isPubAdd:!!C})})},u.prototype.reportStopPublish=function(b,y){this.reporter({msgid:l.STOP_PUBLISH,args:(0,m.default)({url:b,isPubStop:!!y})})},u.prototype.reportVideoProfile=function(b){this.reporter({msgid:l.SET_VIDEOPROFILE,args:(0,m.default)({vp:b})})},u.prototype.reportScreenProfile=function(b){this.reporter({msgid:l.SET_SCREENPROFILE,args:(0,m.default)({sp:b})})},u.prototype.reportAudioProfile=function(b){this.reporter({msgid:l.SET_AUDIOPROFILE,args:(0,m.default)({vp:b})})},u.prototype.reportEnableAudio=function(){this.reporter({msgid:l.ENABLE_AUDIO})},u.prototype.reportDisableAudio=function(){this.reporter({msgid:l.DISABLE_AUDIO})},u.prototype.reportEnableVideo=function(){this.reporter({msgid:l.ENABLE_VIDEO})},u.prototype.reportDisableVideo=function(){this.reporter({msgid:l.DISABLE_VIDEO})},u.prototype.reportStop=function(b){this.reporter({msgid:l.STOP,args:(0,m.default)({tp:b})})},u.prototype.reportPlay=function(b){this.reporter({msgid:l.PLAY,args:(0,m.default)({tp:b})})},u.prototype.reportStreamCreated=function(b,y){this.reporter({msgid:l.LOCALSTREAM_INITED,args:(0,m.default)({userConfig:b,localStreamInfo:y})})},u.prototype.reportConnectionChange=function(b,y){this.reporter({msgid:l.CONNECT_STATE_CHANGE,args:(0,m.default)({connectionState:b,direction:y})})},u.prototype.reportDatachannelHttpConnect=function(b){this.reporter({msgid:l.DC_HTTP_CONNECT,args:(0,m.default)({url:b})})},u.prototype.reportDatachannelHttpConnectOk=function(b){this.reporter({msgid:l.DC_HTTP_CONNECT_OK,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelSubAdd=function(b){this.reporter({msgid:l.DC_SUB_ADD,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelPubAdd=function(b){this.reporter({msgid:l.DC_PUB_ADD,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelSubAddOk=function(b){this.reporter({msgid:l.DC_SUB_ADD_OK,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelPubAddOk=function(b){this.reporter({msgid:l.DC_PUB_ADD_OK,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelStatusChange=function(b){this.reporter({msgid:l.DC_CONNECT_STATE_CHANGE,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelSubDelete=function(b){this.reporter({msgid:l.DC_SUB_DELETE,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelPubDelete=function(b){this.reporter({msgid:l.DC_PUB_DELETE,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelSubDeleteOk=function(b){this.reporter({msgid:l.DC_SUB_DELETE_OK,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelPubDeleteOk=function(b){this.reporter({msgid:l.DC_PUB_DELETE_OK,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelSubStop=function(b){this.reporter({msgid:l.DC_SUB_STOP,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelPubStop=function(b){this.reporter({msgid:l.DC_PUB_STOP,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelSubStopOk=function(b){this.reporter({msgid:l.DC_SUB_STOP_OK,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelPubStopOk=function(b){this.reporter({msgid:l.DC_PUB_STOP_OK,args:(0,m.default)(c({},b))})},u.prototype.reportDatachannelDispose=function(b){this.reporter({msgid:l.DC_DISPOSE,args:(0,m.default)(c({},b))})},u.prototype.reportNotifyMessage=function(b){this.reporter({msgid:l.NOTIFY_MESSAGE,args:(0,m.default)(c({},b))})},u.prototype.reportCumuDelayNotSupported=function(){this.reporter({msgid:l.CUMU_DELAY_NOT_SUPPORTED})},u.prototype.reportCumuDelayAnswerNotFound=function(){this.reporter({msgid:l.CUMU_DELAY_ANSWER_NOT_FOUND})},u.prototype.updateCumuDelayInfo=function(b){this.cumuDelayInfo=b.json},u.prototype._initParam=function(){this.param||(this.param={APIVersion:"0.6.0",os:f.SystemUtil.platform,osv:f.SystemUtil.systemVersion,bt:f.BrowserUtil.browserName,bv:f.BrowserUtil.browserVersion,host:window.location.origin,page:window.location.href,uid:f.LocalStorage.uuid,tid:f.Guid.create(32),ver:v.default.version,ct:this.ct,dt:"",lv:"1.0.0",ua:navigator&&navigator.userAgent||"",pu:""})},u.prototype.reporter=function(b){var y,g=c(c(c(c({},this.param||{}),{tm:new Date().getTime()}),b||{}),{msgname:l[b.msgid]});if(this.customReporter&&typeof this.customReporter=="function")try{this.customReporter(g)}catch(S){console.error("[Error in customReporter] ",S)}this.enableLog&&((y=this.slsTracker)===null||y===void 0||y.send(g))},u.prototype.data2String=function(b){var y="";for(var g in b)b.hasOwnProperty(g)&&(y.length&&(y+="&"),y+=g+"="+b[g]);return y},u.HEARTHEAT_INTERVAL=4,u}();s.default=d},7668:function(a,s,o){var c,h=this&&this.__extends||(c=function(M,D){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(L,P){L.__proto__=P}||function(L,P){for(var x in P)Object.prototype.hasOwnProperty.call(P,x)&&(L[x]=P[x])},c(M,D)},function(M,D){if(typeof D!="function"&&D!==null)throw new TypeError("Class extends value "+String(D)+" is not a constructor or null");function L(){this.constructor=M}c(M,D),M.prototype=D===null?Object.create(D):(L.prototype=D.prototype,new L)}),l=this&&this.__assign||function(){return l=Object.assign||function(M){for(var D,L=1,P=arguments.length;L<P;L++)for(var x in D=arguments[L])Object.prototype.hasOwnProperty.call(D,x)&&(M[x]=D[x]);return M},l.apply(this,arguments)},f=this&&this.__awaiter||function(M,D,L,P){return new(L||(L=Promise))(function(x,T){function O(U){try{H(P.next(U))}catch(ee){T(ee)}}function k(U){try{H(P.throw(U))}catch(ee){T(ee)}}function H(U){var ee;U.done?x(U.value):(ee=U.value,ee instanceof L?ee:new L(function(W){W(ee)})).then(O,k)}H((P=P.apply(M,D||[])).next())})},v=this&&this.__generator||function(M,D){var L,P,x,T,O={label:0,sent:function(){if(1&x[0])throw x[1];return x[1]},trys:[],ops:[]};return T={next:k(0),throw:k(1),return:k(2)},typeof Symbol=="function"&&(T[Symbol.iterator]=function(){return this}),T;function k(H){return function(U){return function(ee){if(L)throw new TypeError("Generator is already executing.");for(;T&&(T=0,ee[0]&&(O=0)),O;)try{if(L=1,P&&(x=2&ee[0]?P.return:ee[0]?P.throw||((x=P.return)&&x.call(P),0):P.next)&&!(x=x.call(P,ee[1])).done)return x;switch(P=0,x&&(ee=[2&ee[0],x.value]),ee[0]){case 0:case 1:x=ee;break;case 4:return O.label++,{value:ee[1],done:!1};case 5:O.label++,P=ee[1],ee=[0];continue;case 7:ee=O.ops.pop(),O.trys.pop();continue;default:if(x=O.trys,!((x=x.length>0&&x[x.length-1])||ee[0]!==6&&ee[0]!==2)){O=0;continue}if(ee[0]===3&&(!x||ee[1]>x[0]&&ee[1]<x[3])){O.label=ee[1];break}if(ee[0]===6&&O.label<x[1]){O.label=x[1],x=ee;break}if(x&&O.label<x[2]){O.label=x[2],O.ops.push(ee);break}x[2]&&O.ops.pop(),O.trys.pop();continue}ee=D.call(M,O)}catch(W){ee=[6,W],P=0}finally{L=x=0}if(5&ee[0])throw ee[1];return{value:ee[0]?ee[1]:void 0,done:!0}}([H,U])}}},p=this&&this.__rest||function(M,D){var L={};for(var P in M)Object.prototype.hasOwnProperty.call(M,P)&&D.indexOf(P)<0&&(L[P]=M[P]);if(M!=null&&typeof Object.getOwnPropertySymbols=="function"){var x=0;for(P=Object.getOwnPropertySymbols(M);x<P.length;x++)D.indexOf(P[x])<0&&Object.prototype.propertyIsEnumerable.call(M,P[x])&&(L[P[x]]=M[P[x]])}return L},_=this&&this.__importDefault||function(M){return M&&M.__esModule?M:{default:M}};Object.defineProperty(s,"__esModule",{value:!0}),s.RtsClient=void 0;var m=_(o(102)),d=o(5917),u=o(5676),b=o(9796),y=o(6600),g=_(o(2818)),S=_(o(7028)),R=o(7989),E=o(1698),I=o(280),C=o(9428),A=o(5044),w=o(2470),N=function(M){function D(L){var P,x=M.call(this)||this;return x.pullH264Checked=!1,x.lastProtocol="udp",x.usePcReconnect=!1,x.isOnErrorState=!1,x.reporter=new g.default(l(l({},L),{env:E.configProvider.getContext().env})),x.subscriber=new u.Subscriber(x.reporter,L?L.playConfig:void 0),x.publisher=new b.Publisher(x.reporter),x.commonController=new y.CommonController(x.reporter),x.pcRestorer=new w.PcRestorer({subscriber:x.subscriber,publisher:x.publisher,commonController:x.commonController}),x.usePcReconnect=!!(!((P=L==null?void 0:L.singlePcConfig)===null||P===void 0)&&P.usePcReconnect),x.subscriber.on("onError",function(T){return f(x,void 0,void 0,function(){var O,k,H,U,ee,W,$,B,F,G,q,X,J=this;return v(this,function(se){switch(se.label){case 0:return console.log("internal subscriber.on('onError'), err:",T," this.usePcReconnect=",this.usePcReconnect,"this.isOnErrorState=",this.isOnErrorState),this.isOnErrorState?[2]:(O=(U=T.extraInfo)===null||U===void 0?void 0:U.response,this.reporter.reportErrorInfo(T.errorCode,T.message,T.traceId,{sdp:(ee=T.extraInfo)===null||ee===void 0?void 0:ee.sdp,response:{status:O==null?void 0:O.status,data:O==null?void 0:O.data},pcErrorInfo:(W=T.extraInfo)===null||W===void 0?void 0:W.pcErrorInfo}),this.usePcReconnect?[3,5]:C.SUB_RECONNECT_ERROR_LIST.includes(T.errorCode)?this.subscriber.isConnecting?[3,2]:(k=this.lastProtocol==="udp",this.lastProtocol=k?"tcp":"udp",console.log("retrying with",this.lastProtocol),[4,this.subscriber.retrySubscribe(T,{innerTcpOnly:k})]):[3,3]);case 1:se.sent()?(this.reporter.reportReconnect(T.errorCode,T.message,T.traceId,($=T.extraInfo)===null||$===void 0?void 0:$.retryTimes,k),this.emit("reconnect",this.makeReconnectEvent("sub",T))):this.emit("onError",T),se.label=2;case 2:return[3,4];case 3:this.emit("onError",T),se.label=4;case 4:return[3,6];case 5:C.PC_RECONNECT_ERROR_LIST.includes(T.errorCode)?(this.subscriber.getSubscribeConfig().disableHeartbeat||!(!((B=T.extraInfo)===null||B===void 0)&&B.fromSystemEvent)&&T.errorCode!==C.ErrorCode.ERROR_INBOUND_TIMEOUT)&&(this.pcRestorer.isReconnecting()?this.pcRestorer.isRestoreRetryComplete()&&(this.isOnErrorState=!0,H=new A.RtsError(C.ErrorCode.ERROR_SINGLE_PC_FULL_RECONNECT_FAILED,"PC restore failed",""),this.emit("onError",H),this.reporter.reportErrorInfo(H.errorCode,H.message)):(T.extraInfo=l(l({},T.extraInfo),{retryTimes:1}),this.reporter.reportReconnect(T.errorCode,T.message,T.traceId,(F=T.extraInfo)===null||F===void 0?void 0:F.retryTimes),this.emit("reconnect",this.makeReconnectEvent("sub",T)),this.emit("connectStatusChange",{status:d.EConnectStatus.CONNECT_STATUS_RECONNECTING}),(X=(q=this.pcRestorer.restore((G=T.extraInfo.pcErrorInfo)===null||G===void 0?void 0:G.ips))===null||q===void 0?void 0:q.then(function(ce){J.reporter.reportReconnectFinish({level:"pc"}),J.emit("reconnectFinish",{type:"all",traceId:ce.traceId,latestUrl:ce.latestUrl})}))===null||X===void 0||X.catch(function(ce){J.isOnErrorState=!0,J.emit("onError",ce),J.reporter.reportErrorInfo(ce.errorCode,ce.message)}))):console.log("not expected errorCode, errorCode: ",T.errorCode),se.label=6;case 6:return[2]}})})}),x.subscriber.on("reconnect",function(T){var O;x.reporter.reportReconnect(T.errorCode,T.message,T.traceId,(O=T.extraInfo)===null||O===void 0?void 0:O.retryTimes),x.emit("reconnect",x.makeReconnectEvent("sub",T))}),x.subscriber.on("onPlayEvent",function(T){x.emit("onPlayEvent",T)}),x.subscriber.on("connectStatusChange",function(T){x.isOnErrorState||x.emit("connectStatusChange",T),x.reporter.reportConnectionChange(d.EConnectStatus[T.status],"sub")}),x.publisher.on("connectStatusChange",function(T){x.emit("connectStatusChange",T),x.reporter.reportConnectionChange(d.EConnectStatus[T.status],"pub")}),x.publisher.on("onError",function(T){return f(x,void 0,void 0,function(){var O,k,H,U,ee,W,$,B,F,G,q,X=this;return v(this,function(J){switch(J.label){case 0:return O=(H=T.extraInfo)===null||H===void 0?void 0:H.response,this.reporter.reportErrorInfo(T.errorCode,T.message,T.traceId,{sdp:(U=T.extraInfo)===null||U===void 0?void 0:U.sdp,response:{status:O==null?void 0:O.status,data:O==null?void 0:O.data},pcErrorInfo:(ee=T.extraInfo)===null||ee===void 0?void 0:ee.pcErrorInfo}),this.usePcReconnect?[3,5]:C.PUB_RECONNECT_ERROR_LIST.includes(T.errorCode)?this.publisher.isConnecting?[3,2]:(k=T.errorCode===C.ErrorCode.ERROR_TRANSPORT_CLOSED&&((W=T.extraInfo)===null||W===void 0?void 0:W.protocol)!=="tcp",console.log("Retrying with ",k?"TCP":"UDP"),[4,this.publisher.retryPublish(T,k)]):[3,3];case 1:J.sent()?(this.reporter.reportReconnect(T.errorCode,T.message,T.traceId,($=T.extraInfo)===null||$===void 0?void 0:$.retryTimes,k),this.emit("reconnect",this.makeReconnectEvent("pub",T))):this.emit("onError",T),J.label=2;case 2:return[3,4];case 3:this.emit("onError",T),J.label=4;case 4:return[3,6];case 5:[C.ErrorCode.ERROR_PC_DISCONNECTED,C.ErrorCode.ERROR_IP_MIGRATE].includes(T.errorCode)&&(this.pcRestorer.isReconnecting()||(T.extraInfo=l(l({},T.extraInfo),{retryTimes:1}),this.reporter.reportReconnect(T.errorCode,T.message,T.traceId,(B=T.extraInfo)===null||B===void 0?void 0:B.retryTimes),this.emit("reconnect",this.makeReconnectEvent("pub",T)),this.emit("connectStatusChange",{status:d.EConnectStatus.CONNECT_STATUS_RECONNECTING}),(q=(G=this.pcRestorer.restore((F=T.extraInfo.pcErrorInfo)===null||F===void 0?void 0:F.ips))===null||G===void 0?void 0:G.then(function(se){X.reporter.reportReconnectFinish({level:"pc"}),X.emit("reconnectFinish",{type:"all",traceId:se.traceId,latestUrl:se.latestUrl})}))===null||q===void 0||q.catch(function(se){X.emit("onError",se),X.reporter.reportErrorInfo(se.errorCode,se.message)}))),J.label=6;case 6:return[2]}})})}),x.publisher.on("reconnect",function(T){var O;x.reporter.reportReconnect(T.errorCode,T.message,T.traceId,(O=T.extraInfo)===null||O===void 0?void 0:O.retryTimes),x.emit("reconnect",x.makeReconnectEvent("pub",T))}),x.commonController.on("connectStatusChange",function(T){x.emit("connectStatusChange",T),x.reporter.reportConnectionChange(d.EConnectStatus[T.status],"signalChannel")}),x.commonController.on("onError",function(T){x.reporter.reportErrorInfo(T.errorCode,T.message,T.traceId),x.emit("onError",T)}),x.commonController.on("datachannelStatusChange",function(T){x.emit("datachannelStatusChange",T),T.status===I.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&x.subscriber.emit("onError",new A.RtsError(C.ErrorCode.ERROR_DATACHANNEL_CLOSE,"DataChannel closed","")),x.reporter.reportDatachannelStatusChange({state:I.EDatachannelStatus[T.status],url:"",label:"SIGNAL",id:-1,msid:""})}),x.commonController.on("encodedFrame",function(T){x.emit("encodedFrame",T)}),x.commonController.on("receivedSEI",function(T){x.emit("receivedSEI",T)}),x.commonController.on("onPlayEvent",function(T){x.emit("onPlayEvent",T)}),x.commonController.on("reconnect",function(T){T.type!=="pc"&&x.emit("reconnect",T)}),x.commonController.on("reconnectFinish",function(T){x.reporter.reportReconnectFinish(T),x.emit("reconnectFinish",T)}),x.commonController.on("traceId",function(T){x.emit("traceId",T)}),x.commonController.on("signalSent",function(T){x.emit("signalSent",T)}),x.commonController.on("signalReceived",function(T){x.emit("signalReceived",T)}),x.commonController.on("hebtSent",function(T){x.emit("hebtSent",T)}),x.commonController.on("hebtReceived",function(T){x.emit("hebtReceived",T)}),x.commonController.on("cumuDelayNotSupported",function(){x.emit("cumuDelayNotSupported")}),x.reporter.reportCreateClient(),x}return h(D,M),D.prototype.getVersion=function(){return S.default.version},D.prototype.isSupport=function(L){var P=new R.SupportUtil;return this.pullH264Checked=!0,P.isSupport(L)},D.prototype.checkPublishSupport=function(){return new R.SupportUtil().checkPublishSupport()},D.prototype.checkEncodedTransformSupport=function(){return new R.SupportUtil().checkEncodedTransformSupport()},D.prototype.subscribe=function(L,P){return this.isOnErrorState=!1,this.reporter.updateUrl(L),this.commonController.setConfig(P),this.commonController.setPeerconnection(this.subscriber.getPeerConnection()),this.subscriber.resetResubscribeStatus(),this.subscriber.subscribeWithReconnect(L,l(l({},P),{isH264Checked:this.pullH264Checked}))},D.prototype.subscribeAdd=function(L){return this.commonController.subscribeAdd(L)},D.prototype.subscribeActive=function(L){return this.commonController.subscribeActive(L)},D.prototype.subscribeDeleteTracks=function(L){return this.commonController.subscribeDeleteTracks(L)},D.prototype.subscribeStop=function(L){return this.commonController.subscribeStop(L)},D.prototype.publishAdd=function(L){return this.commonController.publishAdd(L)},D.prototype.publishDeleteTracks=function(L){return this.commonController.publishDeleteTracks(L)},D.prototype.publishReplaceTracks=function(L){return this.commonController.publishReplaceTracks(L)},D.prototype.publishStop=function(L){return this.commonController.publishStop(L)},D.prototype.subscribeAddDatachannel=function(L){return this.commonController.subscribeAddDatachannel(L)},D.prototype.subscribeDeleteDatachannel=function(L){return this.commonController.subscribeDeleteDatachannel(L)},D.prototype.publishDeleteDatachannel=function(L){return this.commonController.publishDeleteDatachannel(L)},D.prototype.subscribeStopDatachannel=function(L){return this.commonController.subscribeStopDatachannel(L)},D.prototype.publishAddDatachannel=function(L){return this.commonController.publishAddDatachannel(L)},D.prototype.publishStopDatachannel=function(L){return this.commonController.publishStopDatachannel(L)},D.prototype.unsubscribe=function(){this.isOnErrorState=!1,this.subscriber.resetResubscribeStatus(),this.subscriber.unsubscribe()},D.prototype.startLiveStream=function(L,P,x){return this.reporter.reportStartPlay(L),this.subscriber.startLiveStream(L,P,x)},D.prototype.stopLiveStream=function(){this.reporter.reportStopPlay(),this.subscriber.stopLiveStream()},D.prototype.muteLiveStream=function(L){this.subscriber.muteLiveStream(L)},D.prototype.publish=function(L,P,x){return f(this,void 0,void 0,function(){return v(this,function(T){return this.isOnErrorState=!1,this.reporter.updateUrl(L),this.commonController.setConfig(x),this.commonController.setPeerconnection(this.publisher.getPeerConnection()),this.publisher.resetRepublishStatus(),[2,this.publisher.publishWithReconnect(L,P,x)]})})},D.prototype.unpublish=function(){return this.isOnErrorState=!1,this.publisher.resetRepublishStatus(),this.publisher.unpublish()},D.prototype.sendSEI=function(L){this.publisher.sendSEI(L),this.commonController.sendSEI(L)},D.prototype.getPublishTrackInfoList=function(){return this.publisher.getTrackInfoList()},D.prototype.getTransportStats=function(){return this.subscriber.getPeerConnection().getSubMonitor().getTransportStats()},D.prototype.getRemoteVideoStats=function(){return this.subscriber.getPeerConnection().getSubMonitor().getRemoteVideoStats()},D.prototype.getRemoteAudioStats=function(){return this.subscriber.getPeerConnection().getSubMonitor().getRemoteAudioStats()},D.prototype.getSubscribeVideoStats=function(L,P){return this.commonController.getSubscribeVideoStats(L,P)},D.prototype.getSubscribeAudioStats=function(L,P){return this.commonController.getSubscribeAudioStats(L,P)},D.prototype.getPublishVideoStats=function(L,P){return this.commonController.getPublishVideoStats(L,P)},D.prototype.getPublishAudioStats=function(L,P){return this.commonController.getPublishAudioStats(L,P)},D.prototype.setReceiverCodecPreferences=function(L){return this.commonController.setReceiverCodecPreferences(L)},D.prototype.setSenderCodecPreferences=function(L){return this.commonController.setSenderCodecPreferences(L)},D.prototype.makeReconnectEvent=function(L,P){var x=P||{},T=x.extraInfo,O=p(x,["extraInfo"]),k=T||{},H=k.retryTimes,U=p(k,["retryTimes"]),ee=L;return{type:this.usePcReconnect?"pc":ee,reason:O,retryTimes:H,extraInfo:U}},D.prototype.heartbeat=function(L){var P;(P=this.commonController.peerCore)===null||P===void 0||P.sendOnceHeartbeat(L)},D.prototype.setAutoHeartbeat=function(L){var P;(P=this.commonController.peerCore)===null||P===void 0||P.startSignalHeartbeatTimer(L)},D.prototype.clearAutoHeartbeat=function(){var L;(L=this.commonController.peerCore)===null||L===void 0||L.stopSignalHeartbeatTimer()},D.prototype.sendFalseHeartbeat=function(L){var P;(P=this.commonController.peerCore)===null||P===void 0||P.sendFalseHeartbeat(L)},D.prototype.updateAuth=function(L){return this.commonController.updateAuth(L)},D.prototype.dispose=function(){this.isOnErrorState=!1,this.removeAllListeners(),this.reporter.dispose(),this.subscriber.dispose(),this.publisher.dispose(),this.commonController.dispose(),this.pcRestorer.dispose()},D}(m.default);s.RtsClient=N},335:(a,s)=>{Object.defineProperty(s,"__esModule",{value:!0});var o=function(){function c(h){this.useGainNode=!0,this.audioContext=new AudioContext,this.audioDestination=this.audioContext.createMediaStreamDestination(),this.audioSource=[],this.gainNode=null,this.audioTrack=null,this.audioTrackArr=h.trackList||[],this.useGainNode=typeof h.useGainNode!="boolean"||h.useGainNode,this.useGainNode&&(this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.gainNode.gain.value=0),this.getMixedAudioTrack()}return c.prototype.destroy=function(){var h;(h=this.getMixedAudioTrack())===null||h===void 0||h.stop(),this.disconnectSourceNode(),this.audioContext.close(),this.audioTrackArr=[]},c.prototype.updateTrackList=function(h){h.length&&(this.disconnectSourceNode(),this.audioTrackArr=h,this.connectNode())},c.prototype.getMixedAudioTrack=function(){return this.audioTrack||(this.connectNode(),this.audioTrack=this.audioDestination.stream.getAudioTracks()[0]),this.audioTrack},c.prototype.connectNode=function(){var h=this;this.audioTrackArr.forEach(function(l){var f=new MediaStream;f.addTrack(l);var v=h.audioContext.createMediaStreamSource(f);h.gainNode&&v.connect(h.gainNode),h.audioSource.push(v)}),this.audioSource.forEach(function(l){l.connect(h.audioDestination)})},c.prototype.disconnectSourceNode=function(){var h=this;this.audioSource.forEach(function(l){h.gainNode&&l.disconnect(h.gainNode),l.disconnect(h.audioDestination)}),this.audioSource=[]},c}();s.default=o},1893:(a,s)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.TwoDRenderer=void 0;var o=function(){function c(h){this.video=h.video,this.canvas=h.canvas,this.ctx=this.canvas.getContext("2d")}return c.prototype.render=function(){var h,l,f=this.video,v=this.canvas;f&&v&&((h=this.ctx)===null||h===void 0||h.clearRect(0,0,v.width,v.height),(l=this.ctx)===null||l===void 0||l.drawImage(f,0,0,1*f.videoWidth,1*f.videoHeight),this.requestId=requestAnimationFrame(this.render.bind(this)))},c.prototype.stop=function(){this.requestId&&cancelAnimationFrame(this.requestId)},c}();s.TwoDRenderer=o},6295:(a,s,o)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.CanvasRenderer=void 0;var c=o(1893),h=function(){function l(f){this.video=f.video,this.canvas=this.initCanvas(),this.activeRenderer=this.initRenderer()}return Object.defineProperty(l.prototype,"mediaStream",{get:function(){var f;return this.ms||(this.ms=((f=this.canvas)===null||f===void 0?void 0:f.captureStream())||void 0),this.ms},enumerable:!1,configurable:!0}),l.prototype.start=function(){this.render()},l.prototype.stop=function(){this.activeRenderer.stop()},l.prototype.initCanvas=function(){var f=document.createElement("canvas"),v=this.video;return f.width=1*v.videoWidth,f.height=1*v.videoHeight,f},l.prototype.initRenderer=function(){return new c.TwoDRenderer({video:this.video,canvas:this.canvas})},l.prototype.render=function(){this.activeRenderer.render()},l.prototype.resize=function(f,v){this.canvas&&(this.canvas.width=f,this.canvas.height=v)},l}();s.CanvasRenderer=h},6420:function(a,s,o){var c=this&&this.__awaiter||function(p,_,m,d){return new(m||(m=Promise))(function(u,b){function y(R){try{S(d.next(R))}catch(E){b(E)}}function g(R){try{S(d.throw(R))}catch(E){b(E)}}function S(R){var E;R.done?u(R.value):(E=R.value,E instanceof m?E:new m(function(I){I(E)})).then(y,g)}S((d=d.apply(p,_||[])).next())})},h=this&&this.__generator||function(p,_){var m,d,u,b,y={label:0,sent:function(){if(1&u[0])throw u[1];return u[1]},trys:[],ops:[]};return b={next:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(b[Symbol.iterator]=function(){return this}),b;function g(S){return function(R){return function(E){if(m)throw new TypeError("Generator is already executing.");for(;b&&(b=0,E[0]&&(y=0)),y;)try{if(m=1,d&&(u=2&E[0]?d.return:E[0]?d.throw||((u=d.return)&&u.call(d),0):d.next)&&!(u=u.call(d,E[1])).done)return u;switch(d=0,u&&(E=[2&E[0],u.value]),E[0]){case 0:case 1:u=E;break;case 4:return y.label++,{value:E[1],done:!1};case 5:y.label++,d=E[1],E=[0];continue;case 7:E=y.ops.pop(),y.trys.pop();continue;default:if(u=y.trys,!((u=u.length>0&&u[u.length-1])||E[0]!==6&&E[0]!==2)){y=0;continue}if(E[0]===3&&(!u||E[1]>u[0]&&E[1]<u[3])){y.label=E[1];break}if(E[0]===6&&y.label<u[1]){y.label=u[1],u=E;break}if(u&&y.label<u[2]){y.label=u[2],y.ops.push(E);break}u[2]&&y.ops.pop(),y.trys.pop();continue}E=_.call(p,y)}catch(I){E=[6,I],d=0}finally{m=u=0}if(5&E[0])throw E[1];return{value:E[0]?E[1]:void 0,done:!0}}([S,R])}}},l=this&&this.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(s,"__esModule",{value:!0}),s.Clock=void 0;var f=l(o(2505)),v=function(){function p(){this.request=f.default.create({timeout:6e4}),this.offset=0,this.nextAttemptMs=p.DEFAULT_ATTEMPT_INTERVAL,this.attemptCount=0,this.random=Math.random(),this.startSyncClock()}return p.prototype.now=function(){if(this.offset&&!Number.isNaN(this.offset)){var _=Date.now()+this.offset;return Math.round(_)}return Date.now()},p.prototype.syncClock=function(){return c(this,void 0,void 0,function(){var _,m,d,u,b;return h(this,function(y){switch(y.label){case 0:return _=!1,m=Date.now(),[4,this.fetchServerTime()];case 1:return d=y.sent(),u=Date.now(),d?(b=new Date(d).getTime(),Number.isNaN(b)||(this.offset=this.calculateOffset(m+this.fixRequestStartTime(),u,b),_=!0)):console.warn("Failed to fetch server time, should try again"),[2,_]}})})},p.prototype.startSyncClock=function(){return c(this,void 0,void 0,function(){var _,m=this;return h(this,function(d){switch(d.label){case 0:return[4,this.syncClock()];case 1:return _=d.sent(),this.nextAttemptMs=_?p.DEFAULT_ATTEMPT_INTERVAL:p.DEFAULT_ATTEMPT_RETRY_INTERVAL,this.stopSyncClock(),this.attemptTimer=setTimeout(function(){m.startSyncClock()},this.nextAttemptMs),[2]}})})},p.prototype.stopSyncClock=function(){this.attemptTimer&&clearTimeout(this.attemptTimer),this.attemptTimer=void 0},p.prototype.fetchServerTime=function(){return c(this,void 0,void 0,function(){var _,m,d;return h(this,function(u){switch(u.label){case 0:this.attemptCount++,u.label=1;case 1:return u.trys.push([1,3,,4]),[4,this.request.get(this.attachCount(p.DEFAULT_TIME_SOURCE))];case 2:return _=(d=u.sent())===null||d===void 0?void 0:d.data,[3,4];case 3:return m=u.sent(),console.log("GetServerTime error",m),[3,4];case 4:return[2,_]}})})},p.prototype.calculateOffset=function(_,m,d){return d-(m-(m-_)/2)},p.prototype.fixRequestStartTime=function(){var _=0,m=performance.getEntriesByName(this.attachCount(p.DEFAULT_TIME_SOURCE),"resource");if(m!=null&&m.length)if(m.length>1)console.warn("multiple resource entries found");else try{var d=m[0];_=d.requestStart-d.startTime,d.domainLookupEnd,d.domainLookupStart,d.secureConnectionStart,d.connectStart,d.requestStart,d.secureConnectionStart}catch(u){console.log(u)}else console.warn("no resource entry found"),window.RTS_DISABLE_CLEAR_RESOURCE_TIMINGS||performance.clearResourceTimings();return Math.max(0,_||0)},p.prototype.attachCount=function(_){return"".concat(_,"&count=").concat(this.random,"_").concat(this.attemptCount)},p.DEFAULT_TIME_SOURCE="https://time.akamai.com/?iso&ms",p.DEFAULT_ATTEMPT_INTERVAL=3e4,p.DEFAULT_ATTEMPT_RETRY_INTERVAL=5e3,p}();s.Clock=v},1698:function(a,s){var o=this&&this.__assign||function(){return o=Object.assign||function(h){for(var l,f=1,v=arguments.length;f<v;f++)for(var p in l=arguments[f])Object.prototype.hasOwnProperty.call(l,p)&&(h[p]=l[p]);return h},o.apply(this,arguments)};Object.defineProperty(s,"__esModule",{value:!0}),s.configProvider=void 0;var c=function(){function h(){this.context={},this.subscribers=new Set}return h.prototype.setContext=function(l){this.context=o(o({},this.context),l),this.notifySubscribers()},h.prototype.getContext=function(){return this.context},h.prototype.subscribe=function(l){var f=this;return this.subscribers.add(l),function(){return f.subscribers.delete(l)}},h.prototype.notifySubscribers=function(){var l=this;this.subscribers.forEach(function(f){return f(l.context)})},h}();s.configProvider=new c},5649:function(a,s,o){var c,h,l=this&&this.__assign||function(){return l=Object.assign||function(M){for(var D,L=1,P=arguments.length;L<P;L++)for(var x in D=arguments[L])Object.prototype.hasOwnProperty.call(D,x)&&(M[x]=D[x]);return M},l.apply(this,arguments)},f=this&&this.__importDefault||function(M){return M&&M.__esModule?M:{default:M}};Object.defineProperty(s,"__esModule",{value:!0}),s.CumuDelaySeiPayloadParser=s.CumuDelaySeiPayload=s.ECumuDelayGrtnKey=s.ECumuDelayPubSdkKey=s.ECumuDelayAVCommonKey=s.ECumuDelayVideoKey=s.ECumuDelayGrtnExportKey=s.ECumuDelaySubKey=s.CUMU_DELAY_UUID=s.CUMU_DELAY_SEI_PAYLOAD_TYPE=void 0;var v,p,_,m,d=f(o(7028));s.CUMU_DELAY_SEI_PAYLOAD_TYPE=99,s.CUMU_DELAY_UUID=[32,36,16,9,16,23,7,1,150,117,25,212,25,129,3,7],function(M){M.SophonAudioDual="sophon_audio_dual",M.SophonVideoCamera="sophon_video_camera",M.SophonVideoCameraSmall="sophon_video_camera_small",M.SophonVideoCameraSuper="sophon_video_camera_super",M.SophonVideoScreenShare="sophon_video_screen_share",M.SophonAudio="sophon_audio",M.SophonVideoCameraLarge="sophon_video_camera_large",M.RtsAudio="rts audio",M.RtsVideo="rts video"}(v||(v={})),function(M){M[M.Web=0]="Web",M[M.iOS=1]="iOS",M[M.Android=2]="Android"}(p||(p={})),function(M){M.VTotalCost="VTotalCost",M.VAssemblyCost="VAssemblyCost",M.VJitterBufferDelay="VJitterBufferDelay",M.VDecPlugCost="VDecPlugCost",M.DownRTTHalf="DownRTTHalf"}(_||(s.ECumuDelaySubKey=_={})),function(M){M.TOTAL_COST="TOTAL_COST",M.ENTER_GRTN_TIMESTAMP="ENTER_GRTN_TIMESTAMP",M.LEAVE_GRTN_TIMESTAMP="LEAVE_GRTN_TIMESTAMP"}(m||(s.ECumuDelayGrtnExportKey=m={}));var u,b,y,g,S,R,E,I=((c={})[v.SophonAudioDual]=4,c[v.SophonVideoCamera]=5,c[v.SophonVideoCameraSmall]=6,c[v.SophonVideoCameraSuper]=7,c[v.SophonVideoScreenShare]=8,c[v.SophonAudio]=9,c[v.SophonVideoCameraLarge]=10,c[v.RtsAudio]=11,c[v.RtsVideo]=12,c);(h={})[I[v.SophonAudioDual]]=v.SophonAudioDual,h[I[v.SophonVideoCamera]]=v.SophonVideoCamera,h[I[v.SophonVideoCameraSmall]]=v.SophonVideoCameraSmall,h[I[v.SophonVideoCameraSuper]]=v.SophonVideoCameraSuper,h[I[v.SophonVideoScreenShare]]=v.SophonVideoScreenShare,h[I[v.SophonAudio]]=v.SophonAudio,h[I[v.SophonVideoCameraLarge]]=v.SophonVideoCameraLarge,h[I[v.RtsAudio]]=v.RtsAudio,h[I[v.RtsVideo]]=v.RtsVideo,function(M){M[M.VTotalCost=4]="VTotalCost",M[M.CapDeviceCost=5]="CapDeviceCost",M[M.PushExtCost=6]="PushExtCost",M[M.CapPlugCost=7]="CapPlugCost",M[M.PrepThrCost=8]="PrepThrCost",M[M.PrepPlugCost=9]="PrepPlugCost",M[M.DispThrCost=10]="DispThrCost",M[M.DispPlugCost=11]="DispPlugCost",M[M.VEncThrCost=12]="VEncThrCost",M[M.VEncPlugCost=13]="VEncPlugCost"}(u||(s.ECumuDelayVideoKey=u={})),function(M){M[M.ATotalCost=24]="ATotalCost",M[M.ASourceCCost=25]="ASourceCCost",M[M.AMixerCost=26]="AMixerCost",M[M.AEncodeCCost=27]="AEncodeCCost",M[M.AAIClientQuestionTimestampHEAD=28]="AAIClientQuestionTimestampHEAD",M[M.AAIClientQuestionTimestampTAIL=29]="AAIClientQuestionTimestampTAIL",M[M.AAIClientAnswerTimestampHEAD=30]="AAIClientAnswerTimestampHEAD",M[M.AAIClientAnswerTimestampTAIL=31]="AAIClientAnswerTimestampTAIL",M[M.AAIClientScentenceId=32]="AAIClientScentenceId",M[M.AAIClientSourceCost=33]="AAIClientSourceCost",M[M.AAIClientMixerCost=34]="AAIClientMixerCost",M[M.AAIClientEncoderCost=35]="AAIClientEncoderCost",M[M.AAILinuxReceiveCost=36]="AAILinuxReceiveCost",M[M.AAILinuxNeteqCost=37]="AAILinuxNeteqCost",M[M.AAILinuxRemoteSourceCost=38]="AAILinuxRemoteSourceCost",M[M.AAILinuxPlayMixerCost=39]="AAILinuxPlayMixerCost",M[M.AAILinuxPlayCost=40]="AAILinuxPlayCost",M[M.AAIClientQuestionUidDigestHEAD=41]="AAIClientQuestionUidDigestHEAD",M[M.AAIClientQuestionUidDigestTAIL=42]="AAIClientQuestionUidDigestTAIL",M[M.AIClinetSmartDenoise=43]="AIClinetSmartDenoise"}(b||(b={})),function(M){M[M.NetsdkThrCost=44]="NetsdkThrCost",M[M.QosThrCost=45]="QosThrCost",M[M.PacerCost=46]="PacerCost",M[M.UpRTTHalf=47]="UpRTTHalf",M[M.AIClientNetsdkThrCost=48]="AIClientNetsdkThrCost",M[M.AIClientQosThrCost=49]="AIClientQosThrCost",M[M.AIClientPacerCost=50]="AIClientPacerCost",M[M.AIClientUpRTTHalf=51]="AIClientUpRTTHalf"}(y||(s.ECumuDelayAVCommonKey=y={})),function(M){M[M.AIAsrCost=64]="AIAsrCost",M[M.AILlmCost=65]="AILlmCost",M[M.AITtsCost=66]="AITtsCost",M[M.AIMuteCost=67]="AIMuteCost",M[M.AIAgentTotalCost=68]="AIAgentTotalCost",M[M.AIAgentExtraAvatarCost=69]="AIAgentExtraAvatarCost"}(g||(g={})),function(M){M[M.PubSdkType=100]="PubSdkType",M[M.PubSdkVersion=101]="PubSdkVersion"}(S||(s.ECumuDelayPubSdkKey=S={})),function(M){M[M.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_INTERNAL_RTT_HALF=121]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_INTERNAL_RTT_HALF",M[M.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_BEF_PACER=122]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_BEF_PACER",M[M.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_PACER_COST=123]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_PACER_COST",M[M.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_DOWN_RTT_HALF=124]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_DOWN_RTT_HALF"}(R||(s.ECumuDelayGrtnKey=R={})),function(M){M[M.AIGRTNInternalRTTHalf=104]="AIGRTNInternalRTTHalf",M[M.AIGRTNBeforePacer=105]="AIGRTNBeforePacer",M[M.AIGRTNPacerCost=106]="AIGRTNPacerCost",M[M.AIGRTNDownRTTHalf=107]="AIGRTNDownRTTHalf"}(E||(E={}));var C=function(M){M.msid=v.SophonAudio;var D=I[M.msid];D||console.warn("No mapped msid for cumuDelay",M.msid);var L=new ArrayBuffer(M.sendTs?8:4);if(M.sendTs){var P=Math.floor(performance.now()+performance.timeOrigin-M.windowTimeOrigin);P>=Math.pow(2,32)-1&&(P=0);var x=new DataView(L);x.setUint8(0,8),x.setUint8(1,0),x.setUint8(2,D),x.setUint8(3,5),x.setUint32(4,P)}else new Uint8Array(L).set([0,0,D,1]);M.kv[S.PubSdkType]=p.Web,M.kv[S.PubSdkVersion]=Number(d.default.version.split(".").join("").split("-")[0]);var T=Object.keys(M.kv).length;T>256&&console.warn("Too much kv");var O,k,H,U,ee=1+3*T+1,W=new ArrayBuffer(ee),$=new DataView(W);$.setInt8(0,T),Object.keys(M.kv).forEach(function(B,F){B in l(l(l({},u),y),S)||console.warn("Unknown CumuDelay key: ".concat(B));var G=M.kv[B],q=1+3*F;$.setUint8(q,parseInt(B)),$.setUint16(q+1,G)}),$.setUint8(ee-1,128),this.buffer=(O=L,k=W,H=new ArrayBuffer(O.byteLength+k.byteLength),(U=new Uint8Array(H)).set(new Uint8Array(O),0),U.set(new Uint8Array(k),O.byteLength),H)};s.CumuDelaySeiPayload=C;var A=function(M){var D;this.pub={},this.grtn={},this.AIPub={},this.AISub={},this.AIAgent={},this.AIGrtn={},this.other={};var L,P,x=new N(M),T=(x.readBits(3),x.readBits()),O=x.readBits(),k=x.readBits(),H=x.readBits(),U=x.readBits();if(x.readBits(8),x.readBits(8),x.readBits(8),T===1&&x.readBits(16),O===1){var ee=x.readBits(32);this.pub.timestamp=ee,this.pub.timestampRecv=Math.floor(performance.now())}k===1&&x.readBits(16),H===1&&(L=x.readBits(32)),U===1&&(P=x.readBits(32)),L&&P&&(this.grtn=((D={})[m.TOTAL_COST]=P-L,D[m.ENTER_GRTN_TIMESTAMP]=L,D[m.LEAVE_GRTN_TIMESTAMP]=P,D));for(var W=x.readBits(8),$=0;$<W;$++){var B=x.readBits(8),F=x.readBits(16);if(w(B,[u.VTotalCost,u.VEncPlugCost])||w(B,[b.ATotalCost,b.AEncodeCCost])||w(B,[y.NetsdkThrCost,y.UpRTTHalf])||w(B,[S.PubSdkType,S.PubSdkVersion])){var G=u[B]||b[B]||y[B]||S[B];this.pub[G]=F}else if(w(B,[b.AAIClientQuestionTimestampHEAD,b.AAIClientEncoderCost])||w(B,[y.AIClientNetsdkThrCost,y.AIClientUpRTTHalf]))G=b[B]||y[B],this.AIPub[G]=F;else if(w(B,[b.AAILinuxReceiveCost,b.AIClinetSmartDenoise]))G=b[B],this.AISub[G]=F;else if(w(B,[g.AIAsrCost,g.AIAgentExtraAvatarCost]))G=g[B],this.AIAgent[G]=F;else if(w(B,[E.AIGRTNInternalRTTHalf,E.AIGRTNDownRTTHalf])){G=E[B];for(var q=0,X="".concat(G,"_").concat(q);this.AIGrtn.hasOwnProperty(X);)X="".concat(G,"_").concat(q++);this.AIGrtn[X]=F}else if(w(B,[R.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_INTERNAL_RTT_HALF,R.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_DOWN_RTT_HALF])){for(G=R[B],q=0,X="".concat(G,"_").concat(q);this.grtn.hasOwnProperty(X);)X="".concat(G,"_").concat(q++);this.grtn[X]=F}else this.other[B]=F}};function w(M,D){return M>=D[0]&&M<=D[1]}s.CumuDelaySeiPayloadParser=A;var N=function(){function M(D){this.byteOffset=0,this.bitOffset=0;var L=new Uint8Array(D);this.buffer=L}return M.prototype.readBits=function(D){D===void 0&&(D=1);for(var L=0,P=0;P<D;){if(this.byteOffset>=this.buffer.byteLength)throw new Error("readBits out of range");var x=8-this.bitOffset,T=Math.min(x,D-P);L=L<<T|this.getBitsFromByte(this.buffer,this.byteOffset,this.bitOffset,this.bitOffset+T-1),this.bitOffset+=T,P+=T,this.bitOffset===8&&(this.byteOffset++,this.bitOffset=0)}return D===32&&(L>>>=0),L},M.prototype.hasNext=function(){return this.byteOffset<this.buffer.byteLength},M.prototype.getBitsFromByte=function(D,L,P,x){if(L<0||L>=D.byteLength||P<0||x>7||P>x)throw new Error("Invalid parameters");return D[L]>>7-x&(1<<x-P+1)-1},M}()},102:(a,s)=>{Object.defineProperty(s,"__esModule",{value:!0});var o=function(){function c(){this._eventMap={}}return c.prototype.listeners=function(h){return this._eventMap[h]||[]},c.prototype.emit=function(h){for(var l=this,f=[],v=1;v<arguments.length;v++)f[v-1]=arguments[v];var p=this._eventMap[h];return!!Array.isArray(p)&&(p.forEach(function(_){return _.apply(l,f)}),!0)},c.prototype.off=function(h,l){var f=this._eventMap[h];return Array.isArray(f)&&(this._eventMap[h]=f.filter(function(v){return v!==l})),this},c.prototype.removeAllListeners=function(h){return h===void 0?this._eventMap={}:this._eventMap[h]&&(this._eventMap[h]=[]),this},c.prototype.on=function(h,l){return this._eventMap[h]?this._eventMap[h].push(l):this._eventMap[h]=[l],this},c.prototype.once=function(h,l){var f=this,v=function(){for(var p=[],_=0;_<arguments.length;_++)p[_]=arguments[_];f.off(h,v),l.apply(f,p)};return this.on(h,v),this},c}();s.default=o},492:(a,s)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.MediaObserver=void 0;var o=function(){function c(h){this.timeout=h.timeout||c.DEFAULT_TIMEOUT,this.handler=h.handler||function(){},this.watchTimer=null}return Object.defineProperty(c.prototype,"actTimeout",{get:function(){return this.timeout},enumerable:!1,configurable:!0}),c.prototype.check=function(h,l,f,v){var p=this;this.hasNoData(h)?this.watchTimer||(this.watchTimer=window.setTimeout(function(){p.handler(l,f,v)},this.timeout)):this.watchTimer&&(clearTimeout(this.watchTimer),this.watchTimer=null)},c.prototype.hasNoData=function(h){return!h||(h.video?!(Number(h.video.bytesReceivedPerSecond)>0):!h.audio||!(Number(h.audio.bytesReceivedPerSecond)>0))},c.prototype.updateConfig=function(h){this.timeout=h.timeout||this.timeout,this.handler=h.handler||this.handler},c.prototype.reset=function(){this.watchTimer&&(clearTimeout(this.watchTimer),this.watchTimer=null)},c.prototype.dispose=function(){this.timeout=c.DEFAULT_TIMEOUT,this.handler=function(){},this.watchTimer&&(clearTimeout(this.watchTimer),this.watchTimer=null)},c.DEFAULT_TIMEOUT=6e3,c}();s.MediaObserver=o},9594:(a,s,o)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.readUUID=s.discardEPB=s.insertEPB=s.SODBtoRBSP=s.convertPayloadSize=s.NALU=s.SEI=s.parseSei=s.insertSei=void 0;var c=o(5649);s.insertSei=function(v,p,_,m){_===void 0&&(_=5);for(var d=v.data,u=new DataView(d),b=0;;){if(u.getUint32(b)===1){u.getUint8(b+4);var y=new h(p,_,m).buffer,g=new l(y).buffer,S=new ArrayBuffer(g.byteLength+d.byteLength),R=new Uint8Array(S),E=new Uint8Array(g);R.set(E);var I=new Uint8Array(d);R.set(I,g.byteLength),v.data=S,b+=1;break}if((b+=1)+4>=u.byteLength)break}},s.parseSei=function(v){for(var p=[],_=new DataView(v),m=0;;){var d=m,u=_.getUint32(d);if(d+=4,u===1){if((31&_.getUint8(d++))===6){for(var b=_.getUint8(d++),y=f(b)?16:0,g=0;_.getUint8(d)==255;)d++,g+=255;if((g+=_.getUint8(d++))>0&&_.byteLength>d+g){var S=new Uint8Array(_.buffer),R="";if(f(b)){var E=S.slice(d,d+y);R=(0,s.readUUID)((0,s.discardEPB)(E))}var I=S.slice(d+y,d+g);d+=g,p.push({payloadType:b,uuid:R,data:I.buffer})}}m=d}else m+=1;if(m+4>=_.byteLength)break}return p};var h=function(v,p,_){p===void 0&&(p=5);var m=f(p)?16:0,d=v.byteLength+m,u=(0,s.convertPayloadSize)(d),b=u.buffer.byteLength,y=new ArrayBuffer(1+b+m+v.byteLength),g=new Uint8Array(y),S=0;if(g[S++]=p,g.set(u,S),S+=u.byteLength,f(p)){_=(_||"00000000-0000-0000-0000-000000000000").replace(/-/g,"");for(var R=0;R<16;R++)g[S+R]=parseInt(_.substr(2*R,2),16);S+=16}var E=new Uint8Array(v);g.set(E,S);var I=(0,s.SODBtoRBSP)(g);this.buffer=I.buffer};s.SEI=h;var l=function(v){var p=new Uint8Array([0,0,0,1]),_=new Uint8Array([6]),m=new ArrayBuffer(p.byteLength+_.byteLength+v.byteLength),d=new Uint8Array(m);d.set(p),d.set(_,p.byteLength),d.set(new Uint8Array(v),p.byteLength+_.byteLength),this.buffer=m};s.NALU=l,s.convertPayloadSize=function(v){if(v<=0)throw new Error("payloadSize must be a positive integer.");for(var p=Math.ceil(v/255),_=new ArrayBuffer(p),m=new DataView(_),d=0;d<p-1;d++)m.setUint8(d,255);return m.setUint8(p-1,v%255&255),new Uint8Array(_)},s.SODBtoRBSP=function(v){for(var p=new Uint8Array(v),_="",m=0;m<p.length;m++)_+=p[m].toString(2).padStart(8,"0");for(_+="1";_.length%8!=0;)_+="0";var d=_.length/8,u=new Uint8Array(d);for(m=0;m<d;m++)u[m]=parseInt(_.slice(8*m,8*m+8),2);return(0,s.insertEPB)(u)},s.insertEPB=function(v){for(var p=[],_=0,m=0;m<v.length;m++)p.push(v[m]),v[m]===0?++_===2&&m<v.length-1&&v[m+1]<=3&&(p.push(3),_=0):_=0;return new Uint8Array(p)},s.discardEPB=function(v){for(var p=v.byteLength,_=[],m=1;m<p-2;)v[m]===0&&v[m+1]===0&&v[m+2]===3?(_.push(m+2),m+=2):m++;if(_.length===0)return v;var d=p-_.length,u=new Uint8Array(d),b=0;for(m=0;m<d;b++,m++)b===_[0]&&(b++,_.shift()),u[m]=v[b];return u},s.readUUID=function(v){if(v.length!==16)throw new Error("UUID must be 16 bytes long.");var p=v.reduce(function(_,m){return _+m.toString(16).padStart(2,"0")},"");return"".concat(p.slice(0,8),"-").concat(p.slice(8,12),"-").concat(p.slice(12,16),"-").concat(p.slice(16,20),"-").concat(p.slice(20))};var f=function(v){return v===5||v===c.CUMU_DELAY_SEI_PAYLOAD_TYPE}},8219:function(a,s,o){var c=this&&this.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(s,"__esModule",{value:!0});var h=c(o(2505));s.default=h.default.create({baseURL:"",timeout:5e3,headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}})},4315:function(a,s,o){var c=this&&this.__spreadArray||function(v,p,_){if(_||arguments.length===2)for(var m,d=0,u=p.length;d<u;d++)!m&&d in p||(m||(m=Array.prototype.slice.call(p,0,d)),m[d]=p[d]);return v.concat(m||Array.prototype.slice.call(p))};Object.defineProperty(s,"__esModule",{value:!0}),s.SdpUtil=void 0;var h=o(233),l=function(){this.stramId="",this.audioTrackId="",this.videoTrackId="",this.screenTrackId="",this.customTrackId=""},f=function(){function v(p){this.sdpLines=new Array,this.localStream=p,this.publishStreamInfo=new l}return Object.defineProperty(v.prototype,"sdp",{get:function(){return this.sdpLines.join(`\r
`)},enumerable:!1,configurable:!0}),Object.defineProperty(v.prototype,"videoTrackId",{get:function(){return this.publishStreamInfo.videoTrackId},enumerable:!1,configurable:!0}),Object.defineProperty(v.prototype,"screenTrackId",{get:function(){return this.publishStreamInfo.videoTrackId},enumerable:!1,configurable:!0}),Object.defineProperty(v.prototype,"videoName",{get:function(){return"rts video"},enumerable:!1,configurable:!0}),Object.defineProperty(v.prototype,"screenName",{get:function(){return"rts screen"},enumerable:!1,configurable:!0}),Object.defineProperty(v.prototype,"hasTcpCandidate",{get:function(){return this.sdpLines.some(function(p){return p.indexOf("tcptype")!==-1})},enumerable:!1,configurable:!0}),v.prototype.init=function(p){this.sdpLines=p.split(`\r
`)},v.prototype.addNack=function(){for(var p=0;p<this.sdpLines.length;++p)if(this.sdpLines[p].indexOf("opus")!=-1&&this.sdpLines[p+1].indexOf("rtcp-fb")!=-1){var _=this.sdpLines[p+1].split(" ");_.length==2&&(this.sdpLines[p+2].indexOf("rtcp-fb")!=-1?this.sdpLines.splice(p+3,0,_[0]+" nack"):this.sdpLines.splice(p+2,0,_[0]+" nack"))}},v.prototype.parseCustomMsid=function(p){var _={stream:"",track:""};if(!p)return _;var m=p.trim().split(" ");return m.length==2?(_.stream=m[0],_.track=m[1]):_.track=m[0],_},v.prototype.modifyTrackName=function(p){p===void 0&&(p={});var _=p.vMsid,m=p.aMsid,d=_?this.parseCustomMsid(_):{stream:"rts",track:"video"},u=m?this.parseCustomMsid(m):{stream:"rts",track:"audio"},b="";if(this.localStream){this.publishStreamInfo.stramId=this.localStream.mediaStream.id,this.localStream.audioTrack&&(this.publishStreamInfo.audioTrackId=this.localStream.audioTrack.id,b=u.stream||"-"),this.localStream.videoTrack&&(this.publishStreamInfo.videoTrackId=this.localStream.videoTrack.id,b=d.stream||"-");for(var y=!1,g=!1,S=0;S<this.sdpLines.length;++S){var R=this.sdpLines[S],E=R.indexOf(this.publishStreamInfo.stramId);this.publishStreamInfo.stramId&&E!=-1&&(this.sdpLines[S]=this.sdpLines[S].replace(this.publishStreamInfo.stramId,b),h.BrowserUtil.isFirefox&&(y?this.sdpLines[S]=this.sdpLines[S].substring(0,E+b.length+1)+u.track:g&&(this.sdpLines[S]=this.sdpLines[S].substring(0,E+b.length+1)+d.track))),this.publishStreamInfo.audioTrackId&&R.indexOf(this.publishStreamInfo.audioTrackId)!=-1?this.sdpLines[S]=this.sdpLines[S].replace(this.publishStreamInfo.audioTrackId,u.track):this.publishStreamInfo.videoTrackId&&R.indexOf(this.publishStreamInfo.videoTrackId)!=-1&&(this.sdpLines[S]=this.sdpLines[S].replace(this.publishStreamInfo.videoTrackId,d.track)),R.indexOf("m=audio")!=-1?(y=!0,g=!1):R.indexOf("m=video")!=-1&&(g=!0,y=!1),R.indexOf("a=ssrc")!=-1&&(E=R.indexOf("cname:"))!==-1&&(y?this.sdpLines[S]=R.substr(0,E+6)+u.track:g&&(this.sdpLines[S]=R.substr(0,E+6)+d.track))}}},v.prototype.getPublishVideoSdp=function(){for(var p=-1,_=-1,m=!1,d=0;d<this.sdpLines.length;++d){if(m&&this.sdpLines[d].indexOf("m=application")>-1){_=d-1;break}if(this.sdpLines[d].indexOf("m=video")>-1){if(m){_=d-1;break}p=d}this.sdpLines[d].indexOf("rts video")>-1&&(m=!0)}return m?(_===-1&&(_=this.sdpLines.length-1),this.sdpLines.splice(p,_-p).join(`\r
`)):""},v.prototype.removeVideoTrack=function(p){for(var _="rts "+p,m=-1,d=-1,u=!1,b=0;b<this.sdpLines.length;++b){if(u&&this.sdpLines[b].indexOf("m=application")>-1){d=b-1;break}if(this.sdpLines[b].indexOf("m=video")>-1){if(u){d=b-1;break}m=b}this.sdpLines[b].indexOf(_)>-1&&(u=!0)}return!!u&&(d===-1&&(d=this.sdpLines.length-1),this.sdpLines.splice(m,d-m),!0)},v.prototype.ios15PushHack=function(){var p=!1,_=-1;if(this.sdpLines.forEach(function(u,b){u.includes("m=video")&&(p=!0),p&&_===-1&&u.includes("a=")&&(_=b)}),_!==-1){var m=this.getExtmapIds(),d=Math.max.apply(Math,m)+1;this.sdpLines.splice(_,0,"a=extmap:".concat(d," urn:3gpp:video-orientation"))}},v.prototype.addSps=function(){this.sdpLines=this.sdpLines.map(function(p){return p.includes("a=fmtp:")&&p.includes("level-asymmetry-allowed")?p+=";sps-pps-idr-in-keyframe=1":p})},v.prototype.removeTwccRtcpFb=function(){this.sdpLines=this.sdpLines.filter(function(p){return!p.includes("http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01")})},v.prototype.removeUdpCandidate=function(){this.sdpLines=this.sdpLines.filter(function(p){return!p.includes("a=candidate:")||!p.includes("UDP")})},v.prototype.setDirection=function(p){p===void 0&&(p={direction:"recvonly"});var _=["sendonly","recvonly","sendrecv"].filter(function(u){return u!==p.direction}),m=!1,d=!1;this.sdpLines=this.sdpLines.map(function(u,b){if(u.includes("m=video"))m=!0,d=!1;else if(u.includes("m=audio"))d=!0,m=!1;else if(u.includes("m=application"))m=!1,d=!1;else if(m||d){var y;if(_.some(function(g){if(u.includes(g))return y=g,!0})&&y)return u.replace(y,p.direction)}return u})},v.prototype.removeSDES=function(){var p=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"];this.sdpLines=this.sdpLines.filter(function(_){return!p.some(function(m){return _.includes(m)})})},v.prototype.addStereo=function(){var p=this;this.getPayloadType("opus").map(this.getFmtpIndex.bind(this)).filter(function(_){return _!==void 0}).forEach(function(_){p.sdpLines[_].indexOf("stereo=1")>-1||(p.sdpLines[_]=p.sdpLines[_]+";stereo=1")})},v.prototype.setSingleNaluPackMode__legacy=function(){this.sdpLines=this.sdpLines.filter(function(p){return!p.includes("a=fmtp:")||!p.includes("packetization-mode=1")})},v.prototype.setSingleNaluPackMode=function(){var p=this,_=[],m=[],d=!1;if(this.sdpLines.forEach(function(R){if(R.includes("packetization-mode=0")&&(d=!0),R.includes("packetization-mode=1")){var E=p.parseFmtpValue(R);_.push(E||"NULL")}_.length&&new RegExp("apt=(".concat(_.join("|"),")")).test(R)&&(E=p.parseFmtpValue(R),m.push(E||"NULL"))}),!d)return!1;var u=c(c([],_,!0),m,!0).join("|"),b=new RegExp("(rtpmap|rtcp-fb|fmtp):.*?(".concat(u,")"));this.sdpLines=this.sdpLines.filter(function(R){return!b.test(R)});for(var y=0;y<this.sdpLines.length;y++){var g=this.sdpLines[y];if(g.includes("m=video")){var S=new RegExp("( ".concat(c(c([],_,!0),m,!0).join("| "),")"),"g");this.sdpLines[y]=g.replace(S,"");break}}return!0},v.prototype.dispose=function(){this.localStream&&(this.localStream=void 0),this.sdpLines=new Array,this.publishStreamInfo=new l},v.prototype.getExtmapIds=function(){return this.sdpLines.reduce(function(p,_){if(_.includes("a=extmap")){var m=Number(_.replace("a=extmap:","").split(" ")[0]);return c(c([],p,!0),[m],!1)}return p},[]).filter(function(p){return p})},v.prototype.getPayloadType=function(p){for(var _=[],m=new RegExp("a\\=rtpmap\\:(\\d+) ".concat(p,".*"),"i"),d=0;d<this.sdpLines.length;d++){var u=this.sdpLines[d],b=m.exec(u);b!=null&&b.length&&_.push(b[1])}return _},v.prototype.getFmtpIndex=function(p){for(var _=new RegExp("a\\=fmtp\\:".concat(p," .*"),"i"),m=0;m<this.sdpLines.length;m++){var d=this.sdpLines[m];if(_.test(d))return m}},v.prototype.parseFmtpValue=function(p){var _=p.match(/a=fmtp:(\d+)/);return _?_[1]:null},v}();s.SdpUtil=f},7989:function(a,s,o){var c=this&&this.__awaiter||function(d,u,b,y){return new(b||(b=Promise))(function(g,S){function R(C){try{I(y.next(C))}catch(A){S(A)}}function E(C){try{I(y.throw(C))}catch(A){S(A)}}function I(C){var A;C.done?g(C.value):(A=C.value,A instanceof b?A:new b(function(w){w(A)})).then(R,E)}I((y=y.apply(d,u||[])).next())})},h=this&&this.__generator||function(d,u){var b,y,g,S,R={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return S={next:E(0),throw:E(1),return:E(2)},typeof Symbol=="function"&&(S[Symbol.iterator]=function(){return this}),S;function E(I){return function(C){return function(A){if(b)throw new TypeError("Generator is already executing.");for(;S&&(S=0,A[0]&&(R=0)),R;)try{if(b=1,y&&(g=2&A[0]?y.return:A[0]?y.throw||((g=y.return)&&g.call(y),0):y.next)&&!(g=g.call(y,A[1])).done)return g;switch(y=0,g&&(A=[2&A[0],g.value]),A[0]){case 0:case 1:g=A;break;case 4:return R.label++,{value:A[1],done:!1};case 5:R.label++,y=A[1],A=[0];continue;case 7:A=R.ops.pop(),R.trys.pop();continue;default:if(g=R.trys,!((g=g.length>0&&g[g.length-1])||A[0]!==6&&A[0]!==2)){R=0;continue}if(A[0]===3&&(!g||A[1]>g[0]&&A[1]<g[3])){R.label=A[1];break}if(A[0]===6&&R.label<g[1]){R.label=g[1],g=A;break}if(g&&R.label<g[2]){R.label=g[2],R.ops.push(A);break}g[2]&&R.ops.pop(),R.trys.pop();continue}A=u.call(d,R)}catch(w){A=[6,w],y=0}finally{b=g=0}if(5&A[0])throw A[1];return{value:A[0]?A[1]:void 0,done:!0}}([I,C])}}};Object.defineProperty(s,"__esModule",{value:!0}),s.SupportUtil=void 0;var l=o(233),f=o(3412),v=o(9428),p=o(2672),_=function(){this.errorCode=0,this.message=""},m=function(){function d(){this.deviceManager=new f.BrowserDeviceManager}return d.prototype.isSupport=function(u){var b=this;return new Promise(function(y,g){return c(b,void 0,void 0,function(){var S,R,E,I;return h(this,function(C){switch(C.label){case 0:return S=new _,this.checkWebRtcSupport()?u.onlyCheckUA?this.checkBrowser(S)?[3,3]:[2,g(S)]:[3,1]:(S.errorCode=v.ErrorCode.ERROR_NOTSUPPORT_WEBRTC,S.message=p.EN.MESSAGE_NOTSUPPORT_WEBRTC,[2,g(S)]);case 1:return[4,this.checkWebrtcAbilities()];case 2:if(R=C.sent(),E=R[0],R[1],R[2],I=R[3],!E)return S.errorCode=v.ErrorCode.ERROR_NOTSUPPORT_WEBRTC,S.message=p.EN.MESSAGE_NOTSUPPORT_WEBRTC,[2,g(S)];if(I)return S.errorCode=v.ErrorCode.ERROR_BROWSER_NOTSUPPORT,S.message=p.EN.MESSAGE_BROWSER_NOTSUPPORT,[2,g(S)];C.label=3;case 3:return u.isReceiveVideo?this.checkH264Decode(S).then(function(){y(S)}).catch(function(){g(S)}):y(S),[2]}})})})},d.prototype.checkEncodedTransformSupport=function(){var u=window.RTCRtpReceiver&&"createEncodedStreams"in RTCRtpReceiver.prototype,b=window.RTCRtpReceiver&&"transform"in RTCRtpReceiver.prototype&&"RTCRtpScriptTransform"in window;return u||b},d.prototype.checkWebrtcAbilities=function(u){return c(this,void 0,void 0,function(){var b,y,g,S,R,E,I,C,A;return h(this,function(w){switch(w.label){case 0:b=window.RTCPeerConnection,y=!1,g=!1,S=null,R=!1,w.label=1;case 1:return w.trys.push([1,4,,5]),b?(E=new b,g="createDataChannel"in E,u&&(I=this.createBlankStream()).getTracks().forEach(function(N){E==null||E.addTrack(N,I)}),[4,E.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,iceRestart:!0})]):[3,3];case 2:C=w.sent(),A=(C||{}).sdp,S=u?!!(A&&A.indexOf("a=sendrecv")>-1):null,E.close(),E=void 0,y=!0,w.label=3;case 3:return[3,5];case 4:return w.sent(),y=!1,g=!1,S=!1,[3,5];case 5:return R=this.checkBlackList(),[2,[y,g,S,R]]}})})},d.prototype.checkPublishSupport=function(){return c(this,void 0,void 0,function(){var u,b,y,g,S,R,E,I;return h(this,function(C){switch(C.label){case 0:return u={isWebRTCSupported:!1,isH264EncodeSupported:!1,isMediaDevicesSupported:!1,isScreenCaptureSupported:!1,isAudioMixSupported:!1,cameraList:[],micList:[],speakerList:[]},this.checkWebRtcSupport()?[3,1]:(u.isWebRTCSupported=!1,u.isH264EncodeSupported=!1,[3,5]);case 1:return[4,this.checkWebrtcAbilities(!0)];case 2:return b=C.sent(),y=b[0],b[1],g=b[2],u.isWebRTCSupported=!(!y||!g),u.isWebRTCSupported?[3,3]:(u.isH264EncodeSupported=!1,[3,5]);case 3:return S=u,[4,this.checkH264Encode()];case 4:S.isH264EncodeSupported=C.sent(),C.label=5;case 5:if(u.isMediaDevicesSupported=this.checkMediaDevices(),u.isScreenCaptureSupported=this.checkScreenCapture(),u.isAudioMixSupported=this.checkAudioMix(),!u.isMediaDevicesSupported)return[3,11];C.label=6;case 6:return C.trys.push([6,10,,11]),R=u,[4,this.deviceManager.getCameraList()];case 7:return R.cameraList=C.sent().filter(function(A){return A.deviceId}),E=u,[4,this.deviceManager.getMicList()];case 8:return E.micList=C.sent().filter(function(A){return A.deviceId}),I=u,[4,this.deviceManager.getSpeakerList()];case 9:return I.speakerList=C.sent().filter(function(A){return A.deviceId}),[3,11];case 10:return C.sent(),[3,11];case 11:return[2,u]}})})},d.prototype.checkWebRtcSupport=function(){return!!window.RTCPeerConnection},d.prototype.checkMediaDevices=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)},d.prototype.checkScreenCapture=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},d.prototype.checkAudioMix=function(){if(!window.AudioContext)return!1;var u=new AudioContext;return!!u.createMediaStreamDestination&&!!u.createMediaStreamSource},d.prototype.checkBlackList=function(){var u=!1;if(l.BrowserUtil.isOppoBrowser&&l.SystemUtil.isAndroid){var b=(this.getUa().toLowerCase().match(/heytapbrowser\/([\d.]+)/)||[])[1]||"";u=!this.compareVersion(b,"40.7.39.1")}else(l.BrowserUtil.isUCBrowser||l.BrowserUtil.isQuarkBrowser)&&l.SystemUtil.isIos?u=!0:l.BrowserUtil.isWebView&&l.SystemUtil.isAndroid&&(u=!(l.BrowserUtil.browserMainVersion>=79));return u},d.prototype.checkBrowser=function(u){if(l.SystemUtil.isIos){if(l.BrowserUtil.isUCBrowser||l.BrowserUtil.isQuarkBrowser)return u.errorCode=v.ErrorCode.ERROR_BROWSER_NOTSUPPORT,u.message=p.EN.MESSAGE_BROWSER_NOTSUPPORT,!1;if(l.BrowserUtil.isSafari||l.BrowserUtil.isQQBrowser)return l.BrowserUtil.browserMainVersion>=11||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isEdge||l.BrowserUtil.isChrome)return l.BrowserUtil.browserMainVersion>=79||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isMicroMessenger)return!!this.compareVersion(l.SystemUtil.systemVersion,"12.1.4")||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isDingTalk)return!!l.SystemUtil.compareVersion("11.2.5")||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isWebView)return!!this.compareVersion(l.SystemUtil.systemVersion,"14.3")||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1)}else if(l.SystemUtil.isAndroid){if(this.checkPrivateUcWebview())return!0;if(l.BrowserUtil.isChrome||l.BrowserUtil.isQQBrowser||l.BrowserUtil.isHuaweiBrowser||l.BrowserUtil.isSamsungBrowser)return l.BrowserUtil.browserMainVersion>=63||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isEdge)return l.BrowserUtil.browserMainVersion>=79||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isMicroMessenger)return!!this.compareVersion(this.getChromeCoreVersion(),"63")||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isDingTalk)return!!this.compareVersion(this.getChromeCoreVersion(),"69")||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isOppoBrowser){var b=(this.getUa().toLowerCase().match(/heytapbrowser\/([\d.]+)/)||[])[1]||"";return!!this.compareVersion(b,"40.7.39.1")||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1)}if(l.BrowserUtil.isX5Core)return!0;if(l.BrowserUtil.isWebView)return l.BrowserUtil.browserMainVersion>=79||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1)}else if(l.SystemUtil.isMacOS){if(l.BrowserUtil.isElectron)return!0;if(l.BrowserUtil.isSafari)return l.BrowserUtil.browserMainVersion>=11||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isChrome)return l.BrowserUtil.browserMainVersion>=63||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isEdge)return l.BrowserUtil.browserMainVersion>=79||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isFirefox)return l.BrowserUtil.browserMainVersion>=62||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isOpera)return l.BrowserUtil.browserMainVersion>=15||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1)}else if(l.SystemUtil.isWindows){if(l.BrowserUtil.isElectron||l.BrowserUtil.isMicroMessenger)return!0;if(l.BrowserUtil.isChrome||l.BrowserUtil.isQQBrowser)return l.BrowserUtil.browserMainVersion>=63||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isEdge)return l.BrowserUtil.browserMainVersion>=79||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isFirefox)return l.BrowserUtil.browserMainVersion>=62||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isOpera)return l.BrowserUtil.browserMainVersion>=15||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1)}else if(l.SystemUtil.isLinux){if(l.BrowserUtil.isChrome)return l.BrowserUtil.browserMainVersion>=63||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isEdge)return l.BrowserUtil.browserMainVersion>=79||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1);if(l.BrowserUtil.isFirefox)return l.BrowserUtil.browserMainVersion>=62||(u.errorCode=v.ErrorCode.ERROR_BROWSER_VERSIONLOW,u.message=p.EN.MESSAGE_BROWSER_VERSIONLOW,!1)}return u.errorCode===0&&(u.errorCode=v.ErrorCode.ERROR_BROWSER_NOTSUPPORT,u.message=p.EN.MESSAGE_BROWSER_NOTSUPPORT),!1},d.prototype.checkH264Decode=function(u){var b=this;return new Promise(function(y,g){return c(b,void 0,void 0,function(){var S;return h(this,function(R){switch(R.label){case 0:return[4,this.tryFindH264FromSdp(u)];case 1:if(S=R.sent())return y(!0),[2];R.label=2;case 2:return R.trys.push([2,4,,5]),[4,this.loadH264(3)];case 3:return S=R.sent(),[3,5];case 4:return R.sent(),[3,5];case 5:return S?y(!0):(u&&u.errorCode===0&&(u.errorCode=v.ErrorCode.ERROR_NOTSUPPORT_H264,u.message=p.EN.MESSAGE_NOTSUPPORT_H264),g(!1)),[2]}})})})},d.prototype.checkSDPSupportH264=function(u){return u.indexOf("H264")>0||u.indexOf("h264")>0||u.indexOf("H.264")>0||u.indexOf("h.264")>0},d.prototype.checkPrivateUcWebview=function(){return this.getUa().indexOf("UniqueCode")>0},d.prototype.getUa=function(){return navigator&&navigator.userAgent||""},d.prototype.getChromeCoreVersion=function(){return(this.getUa().toLowerCase().match(/chrome\/([\d.]+)/)||[])[1]||""},d.prototype.compareVersion=function(u,b){u===void 0&&(u=""),b===void 0&&(b="");for(var y=(u||"").split("."),g=(b||"").split("."),S=0,R=0,E=0;E<y.length&&E<g.length;++E){if((S=isNaN(parseInt(y[E],10))?0:parseInt(y[E],10))<(R=isNaN(parseInt(g[E],10))?0:parseInt(g[E],10)))return!1;if(S>R)return!0}return!0},d.prototype.tryFindH264FromSdp=function(u){return c(this,void 0,void 0,function(){var b,y,g;return h(this,function(S){switch(S.label){case 0:if(b=!1,!RTCPeerConnection)return[2,b];y=new RTCPeerConnection,g=void 0,S.label=1;case 1:return S.trys.push([1,3,,4]),[4,y.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!0})];case 2:return(g=S.sent())&&g.sdp&&(b=this.checkSDPSupportH264(g.sdp)),[3,4];case 3:return S.sent(),b=!1,u&&(u.errorCode=v.ErrorCode.ERROR_CREATEOFFER,u.message=p.EN.MESSAGE_CREATEOFFER),[3,4];case 4:return y.close(),y=void 0,[2,b]}})})},d.prototype.loadH264=function(u){var b=this;return new Promise(function(y,g){return c(b,void 0,void 0,function(){var S,R,E,I,C=this;return h(this,function(A){if(!l.SystemUtil.isAndroid||!l.BrowserUtil.isChrome&&!l.BrowserUtil.isWebView)return y(!1),[2];for(S=0,R=[],E=0;S<u;)I=setTimeout(function(){return c(C,void 0,void 0,function(){return h(this,function(w){switch(w.label){case 0:return E++,[4,this.tryFindH264FromSdp()];case 1:return w.sent()?(R.forEach(function(N){clearTimeout(N)}),R=[],y(!0),[2]):(E===u&&y(!1),[2])}})})},1e3*S),R.push(I),S++;return[2]})})})},d.prototype.checkH264Encode=function(){return c(this,void 0,void 0,function(){var u,b;return h(this,function(y){switch(y.label){case 0:return[4,this.loadH264(3)];case 1:y.sent(),(u=new RTCPeerConnection).addTransceiver("video",{direction:"sendonly"}),y.label=2;case 2:return y.trys.push([2,4,,5]),[4,u.createOffer()];case 3:return b=y.sent(),[2,this.checkSDPSupportH264(b.sdp||"")];case 4:return y.sent(),[2,!1];case 5:return[2]}})})},d.prototype.createBlankStream=function(){var u,b,y,g=(u=new AudioContext,b=u.createOscillator(),y=b.connect(u.createMediaStreamDestination()),b.start(),Object.assign(y.stream.getAudioTracks()[0],{enabled:!1}));g.stop();var S=function(R){var E,I={},C=I.width,A=C===void 0?160:C,w=I.height,N=w===void 0?90:w,M=document.createElement("canvas");M.width=A,M.height=N,(E=M.getContext("2d"))===null||E===void 0||E.fillRect(0,0,A,N);var D=M.captureStream();return Object.assign(D.getVideoTracks()[0],{enabled:!1})}();return S.stop(),new MediaStream([g,S])},d}();s.SupportUtil=m},2718:function(a,s){var o=this&&this.__spreadArray||function(c,h,l){if(l||arguments.length===2)for(var f,v=0,p=h.length;v<p;v++)!f&&v in h||(f||(f=Array.prototype.slice.call(h,0,v)),f[v]=h[v]);return c.concat(f||Array.prototype.slice.call(h))};Object.defineProperty(s,"__esModule",{value:!0}),s.hebtLog=s.createUUID=s.evaluateNetworkCondition=s.makeCancelable=s.hasVideoTrack=s.hasAudioTrack=s.getVideoTrack=s.getAudioTrack=s.pruneSubUrl=s.getJitterBufferDelayAvg=void 0,s.lowercaseFirstLetter=function(c){return c.replace(/([A-Za-z])/,function(h){return h.toLowerCase()})},s.underlineToCamelCase=function(c){return c.replace(/_([a-z])/g,function(h,l){return l.toUpperCase()})},s.getJitterBufferDelayAvg=function(c,h){return c&&h?Number(c)/Number(h)*1e3:-1},s.pruneSubUrl=function(c,h){var l=c||"";return l=l.replace("@subaudio=no","").replace("@subvideo=no",""),h&&(l=l.split("?")[0]),l},s.getAudioTrack=function(c){return c.getAudioTracks()[0]},s.getVideoTrack=function(c){return c.getVideoTracks()[0]},s.hasAudioTrack=function(c){return c.getAudioTracks().length>0},s.hasVideoTrack=function(c){return c.getVideoTracks().length>0},s.makeCancelable=function(c){var h=!1;return{promise:new Promise(function(l,f){c.then(function(v){return h?f({isCanceled:!0}):l(v)}),c.catch(function(v){return f(h?{isCanceled:!0}:v)})}),cancel:function(){h=!0}}},s.evaluateNetworkCondition=function(c,h,l,f,v){var p=0;if(!navigator.onLine)return p=6;var _=[{loss:0,rtt:0,jbd:1},{loss:0,rtt:1,jbd:0},{loss:0,rtt:.5,jbd:.5},{loss:1,rtt:0,jbd:0},{loss:.8,rtt:0,jbd:.2},{loss:.8,rtt:.2,jbd:0},{loss:.6,rtt:.2,jbd:.2}],m=-1,d=-1,u=-1;if(typeof h=="number"&&h>=0||typeof l=="number"&&l>=0){m=0;var b=!1,y=!1;typeof h=="number"&&h>=0&&(m+=h,b=!0),typeof l=="number"&&l>=0&&(m+=l,y=!0),b&&!y&&(m*=2),y&&!b&&(m*=1.8)}typeof c=="number"&&c>=0&&(u=c),(typeof f=="number"&&f>=0||typeof v=="number"&&v>=0)&&(d=0,typeof f=="number"&&f>=0&&(d+=f),typeof v=="number"&&v>=0&&(d+=v));var g;if((g=4*(m!==-1?1:0)+2*(u!==-1?1:0)+(d!==-1?1:0))>0){var S=1.2*m*_[g-1].loss+u/1500*_[g-1].rtt+d/3e3*_[g-1].jbd;p=S<=.1?1:S<=.23?2:S<=.36?3:S<=.49?4:5}else p=0;return p},s.createUUID=function(c,h){var l,f="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),v=[];if(h=h||f.length,c)for(l=0;l<c;l++)v[l]=f[0|Math.random()*h];else{var p=void 0;for(v[8]=v[13]=v[18]=v[23]="-",v[14]="4",l=0;l<36;l++)v[l]||(p=0|16*Math.random(),v[l]=f[l==19?3&p|8:p])}return v.join("")},s.hebtLog=function(){for(var c=[],h=0;h<arguments.length;h++)c[h]=arguments[h];window.RTS_HEBT_DEBUG&&console.log.apply(console,o(["[rts hebt]"],c,!1))}},233:a=>{/*! useragent-util - ver 1.3.1 created:9/4/2024, 4:31:28 PM */a.exports=(()=>{var s={622:(l,f,v)=>{Object.defineProperty(f,"__esModule",{value:!0}),f.BrowserUtil=f.BrowserType=void 0;var p,_=v(101);(function(d){d.IE="IE",d.Chrome="Chrome",d.Safari="Safari",d.Firefox="Firefox",d.Opera="Opera",d.Edge="Edge",d.MicroMessenger="MicroMessenger",d.X5Core="X5Core",d.Quark="Quark",d.QQ="QQ",d.QQBrowser="QQBrowser",d.DingTalk="DingTalk",d.Electron="Electron",d.Sogou="Sogou",d.Vivo="VivoBrowser",d.Oppo="OppoBrowser",d.UC="UCBrowser",d.MI="MiBrowser",d.Lenovo="SLBrowser",d.Maxthon="Maxthon",d.Liebao="Liebao",d.Huawei="Huawei",d.Meizu="MZBrowser",d.Finger="FingerBrowser",d.Samsung="SamsungBrowser",d.WebVeiw="WebVeiw",d.Unknown="unknown"})(p=f.BrowserType||(f.BrowserType={}));var m=function(){function d(){}return Object.defineProperty(d,"isBrowser",{get:function(){return typeof document<"u"},enumerable:!1,configurable:!0}),Object.defineProperty(d,"domain",{get:function(){return window.location.protocol+window.location.host},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isHttps",{get:function(){return this.isBrowser&&document.location&&(document.location.protocol=="https:"||document.location.host.indexOf("127.0.0.1:")===0||document.location.host.indexOf("localhost:")===0)},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isSupportScreenShare",{get:function(){return!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isChrome",{get:function(){return d._getBrowserInfo(),p.Chrome===d._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isSafari",{get:function(){return d._getBrowserInfo(),p.Safari===d._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isIE",{get:function(){return d._getBrowserInfo(),p.IE===d._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isFirefox",{get:function(){return d._getBrowserInfo(),p.Firefox===d._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isEdge",{get:function(){return d._getBrowserInfo(),p.Edge===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isSogou",{get:function(){return d._getBrowserInfo(),p.Sogou===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isVivoBroswer",{get:function(){return d._getBrowserInfo(),p.Vivo===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isOppoBrowser",{get:function(){return d._getBrowserInfo(),p.Oppo===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isMiBrowser",{get:function(){return d._getBrowserInfo(),p.MI===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isLenovoBrowser",{get:function(){return d._getBrowserInfo(),p.Lenovo===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isMaxthonBrowser",{get:function(){return d._getBrowserInfo(),p.Maxthon===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isLiebaoBrowser",{get:function(){return d._getBrowserInfo(),p.Liebao===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isHuaweiBrowser",{get:function(){return d._getBrowserInfo(),p.Huawei===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isMZBrowser",{get:function(){return d._getBrowserInfo(),p.Meizu===d._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isSamsungBrowser",{get:function(){return d._getBrowserInfo(),p.Samsung===d._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isOpera",{get:function(){return d._getBrowserInfo(),p.Opera===d._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isMicroMessenger",{get:function(){return d._getBrowserInfo(),d._browserName===p.MicroMessenger},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isQQ",{get:function(){return d._getBrowserInfo(),p.QQ===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isQQBrowser",{get:function(){return d._getBrowserInfo(),p.QQBrowser===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isX5Core",{get:function(){return d._getBrowserInfo(),d._browserName===p.X5Core},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isUCBrowser",{get:function(){return d._getBrowserInfo(),d._browserName===p.UC},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isQuarkBrowser",{get:function(){return d._getBrowserInfo(),d._browserName===p.Quark},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isFingerBrowser",{get:function(){return d._getBrowserInfo(),d._browserName===p.Finger},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isChromeCore",{get:function(){return d._getBrowserInfo(),d._core==="Chrome"},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isWebView",{get:function(){return d._getBrowserInfo(),d._browserName===p.WebVeiw},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isDingTalk",{get:function(){return d._getBrowserInfo(),d._browserName===p.DingTalk},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isUnknown",{get:function(){return d._getBrowserInfo(),p.Unknown===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"browserName",{get:function(){return d._getBrowserInfo(),d._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"browserVersion",{get:function(){return d._getBrowserInfo(),d._browserVersion},enumerable:!1,configurable:!0}),Object.defineProperty(d,"browserMainVersion",{get:function(){return d._getBrowserInfo(),d._browserVersion?parseInt(d._browserVersion.split(".")[0],10):0},enumerable:!1,configurable:!0}),Object.defineProperty(d,"browserCoreVersion",{get:function(){return navigator.userAgent.toLowerCase(),_.SystemUtil.isIos||_.SystemUtil.isMacOS,d.browserMainVersion},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isElectron",{get:function(){return d._getBrowserInfo(),p.Electron===d.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"userAgent",{get:function(){var u=navigator.userAgent.toLowerCase(),b=u.indexOf("gecko");if(b>-1){b=u.indexOf(" ",b);var y=(u=u.substring(b+1,u.length)).split(" ");u="";for(var g=0;g<y.length;++g){var S=y[g].split("/");S&&S.length&&(u+=S[0]+" ")}}return u},enumerable:!1,configurable:!0}),d.compareVersion=function(u){if(d._getBrowserInfo(),d._browserVersion){for(var b=d._browserVersion.split("."),y=u.split("."),g=0,S=0,R=0;R<b.length&&R<y.length;++R){if((g=isNaN(parseInt(b[R],10))?0:parseInt(b[R],10))<(S=isNaN(parseInt(y[R],10))?0:parseInt(y[R],10)))return!1;if(g>S)return!0}return!0}return!0},d._getBrowserInfo=function(){if(!d._browserName||!d._browserVersion)if(navigator&&navigator.userAgent){var u=navigator.userAgent.toLowerCase(),b=void 0;(b=u.match(/edg[e|a]?\/([\d.]+)/))||(b=u.match(/edgios\/([\d.]+)/))?d._updateBrowserInfo(p.Edge,u,b[1]):(b=u.match(/rv:([\d.]+)\) like gecko/))||(b=u.match(/msie ([\d.]+)/))?d._updateBrowserInfo(p.IE,u,b[1]):(b=u.match(/vivobrowser\/([\d.]+)/))?d._updateBrowserInfo(p.Vivo,u,b[1]):(b=u.match(/miuibrowser\/([\d.]+)/))?d._updateBrowserInfo(p.MI,u,b[1]):(b=u.match(/samsungbrowser\/([\d.]+)/))?d._updateBrowserInfo(p.Samsung,u,b[1]):(b=u.match(/heytapbrowser\/([\d.]+)/))?d._updateBrowserInfo(p.Oppo,u,b[1]):(b=u.match(/mzbrowser\/([\d.]+)/))?d._updateBrowserInfo(p.Meizu,u,b[1]):(b=u.match(/ucbrowser\/([\d.]+)/))?d._updateBrowserInfo(p.UC,u,b[1]):(b=u.match(/quark\/([\d.]+)/))?d._updateBrowserInfo(p.Quark,u,b[1]):(b=u.match(/slbrowser\/([\d.]+)/))?d._updateBrowserInfo(p.Lenovo,u,b[1]):(b=u.match(/lbbrowser\/([\d.]+)/))?d._updateBrowserInfo(p.Liebao,u,b[1]):(b=u.match(/fingerbrowser\/([\d.]+)/))?d._updateBrowserInfo(p.Finger,u,b[1]):(b=u.match(/huaweibrowser\/([\d.]+)/))?d._updateBrowserInfo(p.Huawei,u,b[1]):(b=u.match(/maxthon\/([\d.]+)/))?d._updateBrowserInfo(p.Maxthon,u,b[1]):(b=u.match(/firefox\/([\d.]+)/))?d._updateBrowserInfo(p.Firefox,u,b[1]):(b=u.match(/electron\/([\d.]+)/))?d._updateBrowserInfo(p.Electron,u,b[1]):(b=u.match(/chrome\/([\d.]+)/))&&this._isChrome(u)||(b=u.match(/crios\/([\d.]+)/))&&this._isChrome(u)?d._updateBrowserInfo(p.Chrome,u,b[1]):(b=u.match(/metasr\s([\d.]+)/))||(b=u.match(/sogoumobilebrowser\/([\d.]+)/))?d._updateBrowserInfo(p.Sogou,u,b[1]):(b=u.match(/opr.([\d.]+)/))?d._updateBrowserInfo(p.Opera,u,b[1]):(b=u.match(/micromessenger.([\d.]+)/))?d._updateBrowserInfo(p.MicroMessenger,u,b[1]):(b=u.match(/qq\/([\d.]+)/))?d._updateBrowserInfo(p.QQ,u,b[1]):(b=u.match(/m?qqbrowser\/([\d.]+)/))||(b=u.match(/qqbrowserlite\/([\d.]+)/))?d._updateBrowserInfo(p.QQBrowser,u,b[1]):(b=u.match(/dingtalk.([\d.]+)/))?d._updateBrowserInfo(p.DingTalk,u,b[1]):(b=u.match(/tbs\/([\d.]+)/))?d._updateBrowserInfo(p.X5Core,u,b[1]):(b=u.match(/version\/([\d.]+).*safari/))&&this._isSafari(u)&&d._updateBrowserInfo(p.Safari,u,b[1]),d._browserName===p.Unknown&&d._isWebview(u)&&d._updateBrowserInfo(p.WebVeiw,u,"")}else d._browserName=p.Unknown,d._browserVersion="0.0"},d._isChrome=function(u){var b=u.split(/\(|\)/);if(d._core="Chrome",b.length===5){var y=b[4].trim().split(" ");if(y.length===2){if(y[0].indexOf("chrome")>-1&&y[1].indexOf("safari")>-1)return!0}else if(y.length===3){if(y[1].indexOf("mobile")>-1&&y[2].indexOf("safari")>-1&&(y[0].indexOf("chrome")>-1||y[0].indexOf("crios")>-1))return!0}else if(u.indexOf("qianniu")>-1)return!0}return!1},d._isSafari=function(u){var b=u.split(/\(|\)/);if(b.length===5){var y=b[4].trim().split(" ");if(y.length===2){if(y[0].indexOf("version")>-1&&y[1].indexOf("safari")>-1)return!0}else if(y.length===3&&y[0].indexOf("version")>-1&&y[1].indexOf("mobile")>-1&&y[2].indexOf("safari")>-1)return!0}return!1},d._isWebview=function(u){if(u){var b=new RegExp("("+["WebView","(iPhone|iPod|iPad)(?!.*Safari)","Android.*(wv|.0.0.0)","Linux; U; Android"].join("|")+")","ig"),y=new RegExp("("+["VivoBrowser","MZBrowser","MiuiBrowser"].join("|")+")","ig");return!!u.match(b)&&!u.match(y)}},d._updateBrowserInfo=function(u,b,y){d._browserName=u;var g=null;switch(u){case p.QQBrowser:_.SystemUtil.isIos||_.SystemUtil.isMacOS?(g=b.match(/version\/([\d.]+).*safari/),d._browserVersion=g?g[1]:"0.0"):(g=b.match(/chrome\/([\d.]+)/),d._browserVersion=g?g[1]:"0.0");break;case p.Vivo:case p.Oppo:case p.Meizu:case p.Huawei:case p.Sogou:case p.Samsung:g=b.match(/chrome\/([\d.]+)/),d._browserVersion=g?g[1]:"0.0";break;case p.WebVeiw:_.SystemUtil.isAndroid?(g=b.match(/chrome\/([\d.]+)/),d._browserVersion=g?g[1]:"0.0"):_.SystemUtil.isIos&&(d._browserVersion=_.SystemUtil.systemVersion);break;default:d._browserVersion=y}},d._browserName=p.Unknown,d._browserVersion="",d._core="",d}();f.BrowserUtil=m},864:(l,f)=>{Object.defineProperty(f,"__esModule",{value:!0}),f.Guid=void 0;var v=function(){function p(){}return p.create=function(_,m){m===void 0&&(m=16);var d,u,b="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),y=[];if(m=m||b.length,_)for(d=0;d<_;d++)y[d]=b[0|Math.random()*m];else for(y[8]=y[13]=y[18]=y[23]="-",y[14]="4",d=0;d<36;d++)y[d]||(u=0|16*Math.random(),y[d]=b[d==19?3&u|8:u]);return y.join("")},p}();f.Guid=v},442:(l,f,v)=>{Object.defineProperty(f,"__esModule",{value:!0}),f.LocalStorage=void 0;var p=v(864),_=function(){function m(){}return Object.defineProperty(m,"uuid",{get:function(){var d="alirtc_uuid",u=m.get(d);return u||(u=p.Guid.create(32),m.set(d,u)),u},enumerable:!1,configurable:!0}),m.get=function(d){var u="";return window&&window.localStorage&&(u=window.localStorage.getItem(d)||""),u},m.set=function(d,u){d&&window&&window.localStorage&&window.localStorage.setItem(d,u)},m}();f.LocalStorage=_},72:(l,f)=>{Object.defineProperty(f,"__esModule",{value:!0}),f.ApiRequest=void 0;var v=function(){function p(){}return p.postBody=function(_,m,d){_=p._getUrl(_,m);var u,b={};return b.headers||(b.headers={}),b.headers.Accept="application/json",b.headers["Content-Type"]="application/json",new Promise(function(y,g){p.requestBody("POST",_,d).then(function(S){return u=S,S.ok?S.json():S.text()}).then(function(S){u.ok?S.code?(S=p._intercept(S),g(S)):y(S.data):g(p._httpErrorMessage(u,S))}).catch(function(S){S=p._httpErrorMessage(S),g(S)})})},p.get=function(_,m,d){var u;return d===void 0&&(d={}),_=p._getUrl(_,m),d.headers||(d.headers={}),d.headers["Content-Type"]="application/json",new Promise(function(b,y){p.request("GET",_,d).then(function(g){return u=g,g.ok?g.json():g.text()}).then(function(g){u.ok?g.code?(g=p._intercept(g),y(g)):b(g.data):y(p._httpErrorMessage(u,g))}).catch(function(g){g=p._httpErrorMessage(g),y(g)})})},p.post=function(_,m,d,u){var b;return u===void 0&&(u={}),_=p._getUrl(_,m),u.headers||(u.headers={}),u.body=d,u.headers.Accept="application/json",u.headers["Content-Type"]="application/json",new Promise(function(y,g){p.request("POST",_,u).then(function(S){return b=S,S.ok?S.json():S.text()}).then(function(S){b.ok?S.code?(S=p._intercept(S),g(S)):y(S.data):g(p._httpErrorMessage(b,S))}).catch(function(S){S=p._httpErrorMessage(S),g(S)})})},p.request=function(_,m,d){_===void 0&&(_="GET");var u=new Headers(d.headers),b=new Request(m,{method:_,headers:u});return fetch(b)},p.requestBody=function(_,m,d){return _===void 0&&(_="GET"),fetch(m,{method:_,body:d,headers:new Headers({"Content-Type":"application/json"})})},p.ajaxPost=function(_,m,d,u){return u===void 0&&(u={}),_=p._getUrl(_,m),u.headers||(u.headers={}),u.headers.Accept="application/json",u.headers["Content-Type"]="application/json",p.ajax("POST",_,d,u)},p.ajax=function(_,m,d,u){_===void 0&&(_="GET"),u===void 0&&(u={});var b=new XMLHttpRequest;return new Promise(function(y,g){b.onreadystatechange=function(){if(b.readyState===4)if(b.status===200){var R=JSON.parse(b.responseText);R.code?(R=p._intercept(R),g(R)):y(R)}else g({message:b.responseText||"请求失败:"+m})},b.open(_,m,!0);try{if(u.withCredentials&&(b.withCredentials=!0),u.headers)for(var S in u.headers)b.setRequestHeader(S,u.headers[S])}catch(R){return void g(R)}try{b.send(d)}catch(R){g(R)}})},p._getUrl=function(_,m){var d=[];if(m)for(var u in m)d.push(u+"="+m[u]);var b=d.join("&");return(_.indexOf("?")!=-1?_:_+"?")+b},p._httpErrorMessage=function(_,m){return _.message||(_.message="HTTP "+_.status+"("+_.statusText+") : "+m),_},p._intercept=function(_){var m=_.data;return _.code&&((m=m||{}).data=_.data,m.code=_.code,m.description=_.description,m.message="0x"+Number(_.code).toString(16)+", "+_.description,m.tid&&(m.message+=", tid="+m.tid)),m},p}();f.ApiRequest=v},101:(l,f)=>{var v,p;Object.defineProperty(f,"__esModule",{value:!0}),f.SystemUtil=f.WindowsType=f.SystemType=void 0,function(m){m.Unknown="Unknown",m.MacOS="Mac",m.Windows="Windows",m.Android="Android",m.Iphone="iphone",m.Ipad="ipad",m.iOS="iOS",m.Linux="Linux",m.ChromeOS="ChromeOS"}(v=f.SystemType||(f.SystemType={})),function(m){m.Windows10="Windows 10",m.Windows7="Windows 7",m.WindowsVista="Windows vista",m.WindowsXP="Windows xp"}(p=f.WindowsType||(f.WindowsType={}));var _=function(){function m(){}return Object.defineProperty(m,"isMacOS",{get:function(){return v.MacOS===m.systemName},enumerable:!1,configurable:!0}),Object.defineProperty(m,"isWindows",{get:function(){return m.systemName.indexOf(v.Windows)>-1},enumerable:!1,configurable:!0}),Object.defineProperty(m,"isIos",{get:function(){return v.Iphone===m.systemName||v.Ipad===m.systemName},enumerable:!1,configurable:!0}),Object.defineProperty(m,"isAndroid",{get:function(){return v.Android===m.systemName},enumerable:!1,configurable:!0}),Object.defineProperty(m,"isLinux",{get:function(){return v.Linux===m.systemName||v.Linux===m._platform},enumerable:!1,configurable:!0}),Object.defineProperty(m,"systemName",{get:function(){return m._getSystemInfo(),m._systemName},enumerable:!1,configurable:!0}),Object.defineProperty(m,"systemVersion",{get:function(){return m._getSystemInfo(),m._systemVersion},enumerable:!1,configurable:!0}),Object.defineProperty(m,"platform",{get:function(){return m._getSystemInfo(),m._platform},enumerable:!1,configurable:!0}),Object.defineProperty(m,"isUnknown",{get:function(){return!m.platform||m.platform===v.Unknown},enumerable:!1,configurable:!0}),m.compareVersion=function(d){if(m._getSystemInfo(),m._systemVersion){for(var u=m._systemVersion.split("."),b=d.split("."),y=0,g=0,S=0;S<u.length&&S<b.length;++S){if((y=isNaN(parseInt(u[S],10))?0:parseInt(u[S],10))<(g=isNaN(parseInt(b[S],10))?0:parseInt(b[S],10)))return!1;if(y>g)return!0}return!0}return!0},m._getSystemInfo=function(){if(!m._systemName||!m._systemVersion||!m._platform)if(navigator&&navigator.userAgent){var d=navigator.userAgent.toLowerCase();d.indexOf("ipad")>-1?(m._systemName=v.Ipad,m._platform=v.iOS,m._systemVersion=m._getIosSystemVersion(d)):d.indexOf("iphone")>-1?(m._systemName=v.Iphone,m._platform=v.iOS,m._systemVersion=m._getIosSystemVersion(d)):d.indexOf("android")>-1?(m._platform=v.Android,m._systemName=v.Android,m._systemVersion=m._getAndroidSystemVersion(d)):d.indexOf("win")>-1?d.indexOf("windwos nt 10")>-1||d.indexOf("windows 10")?(m._systemName=p.Windows10,m._platform=v.Windows,m._systemVersion="10"):d.indexOf("windows nt 6.1")>-1||d.indexOf("windows 7")>-1?(m._systemName=p.Windows7,m._platform=v.Windows,m._systemVersion="7"):d.indexOf("windows nt 6.0")>-1||d.indexOf("windows vista")>-1?(m._systemName=p.WindowsVista,m._platform=v.Windows,m._systemVersion="vista"):d.indexOf("widows nt 5.1")>-1||d.indexOf("windows xp")>-1?(m._systemName=p.WindowsXP,m._platform=v.Windows,m._systemVersion="xp"):(m._platform=v.Windows,m._systemName=v.Windows,m._systemVersion="0.0"):d.indexOf("mac")>-1?navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0?(m._systemName=v.Ipad,m._platform=v.iOS,m._systemVersion=m._getIosSystemVersion(d)):(m._platform=v.MacOS,m._systemName=v.MacOS,m._systemVersion=m._getMacSystemVersion(d)):d.indexOf("linux")>-1?(m._platform=v.Linux,m._systemName=v.Linux,m._systemVersion="0.0"):d.indexOf("cros")>-1?(m._platform=v.Linux,m._systemName=v.ChromeOS,m._systemVersion="0.0"):(m._systemName=v.Unknown,m._platform=v.Windows,m._systemVersion="0.0")}else m._systemName=v.Unknown,m._platform=v.Unknown,m._systemVersion="0.0"},m._getIosSystemVersion=function(d){return(d.match(/OS [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".")},m._getMacSystemVersion=function(d){return(d.match(/OS X [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".")},m._getAndroidSystemVersion=function(d){return d.substr(d.indexOf("android")+8,d.indexOf(";",d.indexOf("android"))-d.indexOf("android")-8)},m._systemName="",m._systemVersion="",m._platform=v.Unknown,m}();f.SystemUtil=_}},o={};function c(l){if(o[l])return o[l].exports;var f=o[l]={exports:{}};return s[l](f,f.exports,c),f.exports}var h={};return(()=>{var l=h;Object.defineProperty(l,"__esModule",{value:!0}),l.ApiRequest=l.LocalStorage=l.Guid=l.BrowserUtil=l.SystemUtil=void 0;var f=c(101);Object.defineProperty(l,"SystemUtil",{enumerable:!0,get:function(){return f.SystemUtil}});var v=c(622);Object.defineProperty(l,"BrowserUtil",{enumerable:!0,get:function(){return v.BrowserUtil}});var p=c(864);Object.defineProperty(l,"Guid",{enumerable:!0,get:function(){return p.Guid}});var _=c(442);Object.defineProperty(l,"LocalStorage",{enumerable:!0,get:function(){return _.LocalStorage}});var m=c(72);Object.defineProperty(l,"ApiRequest",{enumerable:!0,get:function(){return m.ApiRequest}}),window&&(window.SystemUtil=f.SystemUtil,window.BrowserUtil=v.BrowserUtil,window.Guid=p.Guid,window.LocalStorage=_.LocalStorage,window.ApiRequest=m.ApiRequest)})(),h})()},9543:(a,s,o)=>{o.r(s),o.d(s,{default:()=>tt});var c={};o.r(c),o.d(c,{fixNegotiationNeeded:()=>k,shimAddTrackRemoveTrack:()=>T,shimAddTrackRemoveTrackWithNative:()=>x,shimGetDisplayMedia:()=>w,shimGetSendersWithDtmf:()=>D,shimGetStats:()=>L,shimGetUserMedia:()=>A,shimMediaStream:()=>N,shimOnTrack:()=>M,shimPeerConnection:()=>O,shimSenderReceiverGetStats:()=>P});var h={};o.r(h),o.d(h,{shimGetDisplayMedia:()=>W,shimGetUserMedia:()=>ee,shimPeerConnection:()=>$,shimReplaceTrack:()=>B});var l={};o.r(l),o.d(l,{shimAddTransceiver:()=>fe,shimCreateAnswer:()=>ue,shimCreateOffer:()=>pe,shimGetDisplayMedia:()=>G,shimGetParameters:()=>he,shimGetUserMedia:()=>F,shimOnTrack:()=>q,shimPeerConnection:()=>X,shimRTCDataChannel:()=>Y,shimReceiverGetStats:()=>se,shimRemoveStream:()=>ce,shimSenderGetStats:()=>J});var f={};o.r(f),o.d(f,{shimAudioContext:()=>Ve,shimCallbacksAPI:()=>Z,shimConstraints:()=>re,shimCreateOfferLegacy:()=>Ee,shimGetUserMedia:()=>K,shimLocalStreamsAPI:()=>Te,shimRTCIceServerUrls:()=>de,shimRemoteStreamsAPI:()=>be,shimTrackEventTransceiver:()=>ye});var v={};o.r(v),o.d(v,{removeExtmapAllowMixed:()=>Ke,shimAddIceCandidateNullOrEmpty:()=>Fe,shimConnectionState:()=>$e,shimMaxMessageSize:()=>Ie,shimRTCIceCandidate:()=>Ye,shimSendThrowTypeError:()=>Oe});let p=!0,_=!0;function m(z,j,te){const Q=z.match(j);return Q&&Q.length>=te&&parseInt(Q[te],10)}function d(z,j,te){if(!z.RTCPeerConnection)return;const Q=z.RTCPeerConnection.prototype,ne=Q.addEventListener;Q.addEventListener=function(oe,Se){if(oe!==j)return ne.apply(this,arguments);const _e=xe=>{const Pe=te(xe);Pe&&(Se.handleEvent?Se.handleEvent(Pe):Se(Pe))};return this._eventMap=this._eventMap||{},this._eventMap[j]||(this._eventMap[j]=new Map),this._eventMap[j].set(Se,_e),ne.apply(this,[oe,_e])};const ae=Q.removeEventListener;Q.removeEventListener=function(oe,Se){if(oe!==j||!this._eventMap||!this._eventMap[j])return ae.apply(this,arguments);if(!this._eventMap[j].has(Se))return ae.apply(this,arguments);const _e=this._eventMap[j].get(Se);return this._eventMap[j].delete(Se),this._eventMap[j].size===0&&delete this._eventMap[j],Object.keys(this._eventMap).length===0&&delete this._eventMap,ae.apply(this,[oe,_e])},Object.defineProperty(Q,"on"+j,{get(){return this["_on"+j]},set(oe){this["_on"+j]&&(this.removeEventListener(j,this["_on"+j]),delete this["_on"+j]),oe&&this.addEventListener(j,this["_on"+j]=oe)},enumerable:!0,configurable:!0})}function u(z){return typeof z!="boolean"?new Error("Argument type: "+typeof z+". Please use a boolean."):(p=z,z?"adapter.js logging disabled":"adapter.js logging enabled")}function b(z){return typeof z!="boolean"?new Error("Argument type: "+typeof z+". Please use a boolean."):(_=!z,"adapter.js deprecation warnings "+(z?"disabled":"enabled"))}function y(){if(typeof window=="object"){if(p)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function g(z,j){_&&console.warn(z+" is deprecated, please use "+j+" instead.")}function S(z){return Object.prototype.toString.call(z)==="[object Object]"}function R(z){return S(z)?Object.keys(z).reduce(function(j,te){const Q=S(z[te]),ne=Q?R(z[te]):z[te],ae=Q&&!Object.keys(ne).length;return ne===void 0||ae?j:Object.assign(j,{[te]:ne})},{}):z}function E(z,j,te){j&&!te.has(j.id)&&(te.set(j.id,j),Object.keys(j).forEach(Q=>{Q.endsWith("Id")?E(z,z.get(j[Q]),te):Q.endsWith("Ids")&&j[Q].forEach(ne=>{E(z,z.get(ne),te)})}))}function I(z,j,te){const Q=te?"outbound-rtp":"inbound-rtp",ne=new Map;if(j===null)return ne;const ae=[];return z.forEach(oe=>{oe.type==="track"&&oe.trackIdentifier===j.id&&ae.push(oe)}),ae.forEach(oe=>{z.forEach(Se=>{Se.type===Q&&Se.trackId===oe.id&&E(z,Se,ne)})}),ne}const C=y;function A(z,j){const te=z&&z.navigator;if(!te.mediaDevices)return;const Q=function(oe){if(typeof oe!="object"||oe.mandatory||oe.optional)return oe;const Se={};return Object.keys(oe).forEach(_e=>{if(_e==="require"||_e==="advanced"||_e==="mediaSource")return;const xe=typeof oe[_e]=="object"?oe[_e]:{ideal:oe[_e]};xe.exact!==void 0&&typeof xe.exact=="number"&&(xe.min=xe.max=xe.exact);const Pe=function(He,it){return He?He+it.charAt(0).toUpperCase()+it.slice(1):it==="deviceId"?"sourceId":it};if(xe.ideal!==void 0){Se.optional=Se.optional||[];let He={};typeof xe.ideal=="number"?(He[Pe("min",_e)]=xe.ideal,Se.optional.push(He),He={},He[Pe("max",_e)]=xe.ideal,Se.optional.push(He)):(He[Pe("",_e)]=xe.ideal,Se.optional.push(He))}xe.exact!==void 0&&typeof xe.exact!="number"?(Se.mandatory=Se.mandatory||{},Se.mandatory[Pe("",_e)]=xe.exact):["min","max"].forEach(He=>{xe[He]!==void 0&&(Se.mandatory=Se.mandatory||{},Se.mandatory[Pe(He,_e)]=xe[He])})}),oe.advanced&&(Se.optional=(Se.optional||[]).concat(oe.advanced)),Se},ne=function(oe,Se){if(j.version>=61)return Se(oe);if((oe=JSON.parse(JSON.stringify(oe)))&&typeof oe.audio=="object"){const _e=function(xe,Pe,He){Pe in xe&&!(He in xe)&&(xe[He]=xe[Pe],delete xe[Pe])};_e((oe=JSON.parse(JSON.stringify(oe))).audio,"autoGainControl","googAutoGainControl"),_e(oe.audio,"noiseSuppression","googNoiseSuppression"),oe.audio=Q(oe.audio)}if(oe&&typeof oe.video=="object"){let _e=oe.video.facingMode;_e=_e&&(typeof _e=="object"?_e:{ideal:_e});const xe=j.version<66;if(_e&&(_e.exact==="user"||_e.exact==="environment"||_e.ideal==="user"||_e.ideal==="environment")&&(!te.mediaDevices.getSupportedConstraints||!te.mediaDevices.getSupportedConstraints().facingMode||xe)){let Pe;if(delete oe.video.facingMode,_e.exact==="environment"||_e.ideal==="environment"?Pe=["back","rear"]:_e.exact!=="user"&&_e.ideal!=="user"||(Pe=["front"]),Pe)return te.mediaDevices.enumerateDevices().then(He=>{let it=(He=He.filter(pi=>pi.kind==="videoinput")).find(pi=>Pe.some(Js=>pi.label.toLowerCase().includes(Js)));return!it&&He.length&&Pe.includes("back")&&(it=He[He.length-1]),it&&(oe.video.deviceId=_e.exact?{exact:it.deviceId}:{ideal:it.deviceId}),oe.video=Q(oe.video),C("chrome: "+JSON.stringify(oe)),Se(oe)})}oe.video=Q(oe.video)}return C("chrome: "+JSON.stringify(oe)),Se(oe)},ae=function(oe){return j.version>=64?oe:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[oe.name]||oe.name,message:oe.message,constraint:oe.constraint||oe.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(te.getUserMedia=(function(oe,Se,_e){ne(oe,xe=>{te.webkitGetUserMedia(xe,Se,Pe=>{_e&&_e(ae(Pe))})})}).bind(te),te.mediaDevices.getUserMedia){const oe=te.mediaDevices.getUserMedia.bind(te.mediaDevices);te.mediaDevices.getUserMedia=function(Se){return ne(Se,_e=>oe(_e).then(xe=>{if(_e.audio&&!xe.getAudioTracks().length||_e.video&&!xe.getVideoTracks().length)throw xe.getTracks().forEach(Pe=>{Pe.stop()}),new DOMException("","NotFoundError");return xe},xe=>Promise.reject(ae(xe))))}}}function w(z,j){z.navigator.mediaDevices&&"getDisplayMedia"in z.navigator.mediaDevices||z.navigator.mediaDevices&&(typeof j=="function"?z.navigator.mediaDevices.getDisplayMedia=function(te){return j(te).then(Q=>{const ne=te.video&&te.video.width,ae=te.video&&te.video.height,oe=te.video&&te.video.frameRate;return te.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:Q,maxFrameRate:oe||3}},ne&&(te.video.mandatory.maxWidth=ne),ae&&(te.video.mandatory.maxHeight=ae),z.navigator.mediaDevices.getUserMedia(te)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}function N(z){z.MediaStream=z.MediaStream||z.webkitMediaStream}function M(z){if(typeof z=="object"&&z.RTCPeerConnection&&!("ontrack"in z.RTCPeerConnection.prototype)){Object.defineProperty(z.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(te){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=te)},enumerable:!0,configurable:!0});const j=z.RTCPeerConnection.prototype.setRemoteDescription;z.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=te=>{te.stream.addEventListener("addtrack",Q=>{let ne;ne=z.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(oe=>oe.track&&oe.track.id===Q.track.id):{track:Q.track};const ae=new Event("track");ae.track=Q.track,ae.receiver=ne,ae.transceiver={receiver:ne},ae.streams=[te.stream],this.dispatchEvent(ae)}),te.stream.getTracks().forEach(Q=>{let ne;ne=z.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(oe=>oe.track&&oe.track.id===Q.id):{track:Q};const ae=new Event("track");ae.track=Q,ae.receiver=ne,ae.transceiver={receiver:ne},ae.streams=[te.stream],this.dispatchEvent(ae)})},this.addEventListener("addstream",this._ontrackpoly)),j.apply(this,arguments)}}else d(z,"track",j=>(j.transceiver||Object.defineProperty(j,"transceiver",{value:{receiver:j.receiver}}),j))}function D(z){if(typeof z=="object"&&z.RTCPeerConnection&&!("getSenders"in z.RTCPeerConnection.prototype)&&"createDTMFSender"in z.RTCPeerConnection.prototype){const j=function(ne,ae){return{track:ae,get dtmf(){return this._dtmf===void 0&&(ae.kind==="audio"?this._dtmf=ne.createDTMFSender(ae):this._dtmf=null),this._dtmf},_pc:ne}};if(!z.RTCPeerConnection.prototype.getSenders){z.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const ne=z.RTCPeerConnection.prototype.addTrack;z.RTCPeerConnection.prototype.addTrack=function(oe,Se){let _e=ne.apply(this,arguments);return _e||(_e=j(this,oe),this._senders.push(_e)),_e};const ae=z.RTCPeerConnection.prototype.removeTrack;z.RTCPeerConnection.prototype.removeTrack=function(oe){ae.apply(this,arguments);const Se=this._senders.indexOf(oe);Se!==-1&&this._senders.splice(Se,1)}}const te=z.RTCPeerConnection.prototype.addStream;z.RTCPeerConnection.prototype.addStream=function(ne){this._senders=this._senders||[],te.apply(this,[ne]),ne.getTracks().forEach(ae=>{this._senders.push(j(this,ae))})};const Q=z.RTCPeerConnection.prototype.removeStream;z.RTCPeerConnection.prototype.removeStream=function(ne){this._senders=this._senders||[],Q.apply(this,[ne]),ne.getTracks().forEach(ae=>{const oe=this._senders.find(Se=>Se.track===ae);oe&&this._senders.splice(this._senders.indexOf(oe),1)})}}else if(typeof z=="object"&&z.RTCPeerConnection&&"getSenders"in z.RTCPeerConnection.prototype&&"createDTMFSender"in z.RTCPeerConnection.prototype&&z.RTCRtpSender&&!("dtmf"in z.RTCRtpSender.prototype)){const j=z.RTCPeerConnection.prototype.getSenders;z.RTCPeerConnection.prototype.getSenders=function(){const te=j.apply(this,[]);return te.forEach(Q=>Q._pc=this),te},Object.defineProperty(z.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function L(z){if(!z.RTCPeerConnection)return;const j=z.RTCPeerConnection.prototype.getStats;z.RTCPeerConnection.prototype.getStats=function(){const[te,Q,ne]=arguments;if(arguments.length>0&&typeof te=="function")return j.apply(this,arguments);if(j.length===0&&(arguments.length===0||typeof te!="function"))return j.apply(this,[]);const ae=function(Se){const _e={};return Se.result().forEach(xe=>{const Pe={id:xe.id,timestamp:xe.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[xe.type]||xe.type};xe.names().forEach(He=>{Pe[He]=xe.stat(He)}),_e[Pe.id]=Pe}),_e},oe=function(Se){return new Map(Object.keys(Se).map(_e=>[_e,Se[_e]]))};if(arguments.length>=2){const Se=function(_e){Q(oe(ae(_e)))};return j.apply(this,[Se,te])}return new Promise((Se,_e)=>{j.apply(this,[function(xe){Se(oe(ae(xe)))},_e])}).then(Q,ne)}}function P(z){if(!(typeof z=="object"&&z.RTCPeerConnection&&z.RTCRtpSender&&z.RTCRtpReceiver))return;if(!("getStats"in z.RTCRtpSender.prototype)){const te=z.RTCPeerConnection.prototype.getSenders;te&&(z.RTCPeerConnection.prototype.getSenders=function(){const ne=te.apply(this,[]);return ne.forEach(ae=>ae._pc=this),ne});const Q=z.RTCPeerConnection.prototype.addTrack;Q&&(z.RTCPeerConnection.prototype.addTrack=function(){const ne=Q.apply(this,arguments);return ne._pc=this,ne}),z.RTCRtpSender.prototype.getStats=function(){const ne=this;return this._pc.getStats().then(ae=>I(ae,ne.track,!0))}}if(!("getStats"in z.RTCRtpReceiver.prototype)){const te=z.RTCPeerConnection.prototype.getReceivers;te&&(z.RTCPeerConnection.prototype.getReceivers=function(){const Q=te.apply(this,[]);return Q.forEach(ne=>ne._pc=this),Q}),d(z,"track",Q=>(Q.receiver._pc=Q.srcElement,Q)),z.RTCRtpReceiver.prototype.getStats=function(){const Q=this;return this._pc.getStats().then(ne=>I(ne,Q.track,!1))}}if(!("getStats"in z.RTCRtpSender.prototype)||!("getStats"in z.RTCRtpReceiver.prototype))return;const j=z.RTCPeerConnection.prototype.getStats;z.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof z.MediaStreamTrack){const te=arguments[0];let Q,ne,ae;return this.getSenders().forEach(oe=>{oe.track===te&&(Q?ae=!0:Q=oe)}),this.getReceivers().forEach(oe=>(oe.track===te&&(ne?ae=!0:ne=oe),oe.track===te)),ae||Q&&ne?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):Q?Q.getStats():ne?ne.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return j.apply(this,arguments)}}function x(z){z.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(ae=>this._shimmedLocalStreams[ae][0])};const j=z.RTCPeerConnection.prototype.addTrack;z.RTCPeerConnection.prototype.addTrack=function(ae,oe){if(!oe)return j.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const Se=j.apply(this,arguments);return this._shimmedLocalStreams[oe.id]?this._shimmedLocalStreams[oe.id].indexOf(Se)===-1&&this._shimmedLocalStreams[oe.id].push(Se):this._shimmedLocalStreams[oe.id]=[oe,Se],Se};const te=z.RTCPeerConnection.prototype.addStream;z.RTCPeerConnection.prototype.addStream=function(ae){this._shimmedLocalStreams=this._shimmedLocalStreams||{},ae.getTracks().forEach(_e=>{if(this.getSenders().find(xe=>xe.track===_e))throw new DOMException("Track already exists.","InvalidAccessError")});const oe=this.getSenders();te.apply(this,arguments);const Se=this.getSenders().filter(_e=>oe.indexOf(_e)===-1);this._shimmedLocalStreams[ae.id]=[ae].concat(Se)};const Q=z.RTCPeerConnection.prototype.removeStream;z.RTCPeerConnection.prototype.removeStream=function(ae){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[ae.id],Q.apply(this,arguments)};const ne=z.RTCPeerConnection.prototype.removeTrack;z.RTCPeerConnection.prototype.removeTrack=function(ae){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},ae&&Object.keys(this._shimmedLocalStreams).forEach(oe=>{const Se=this._shimmedLocalStreams[oe].indexOf(ae);Se!==-1&&this._shimmedLocalStreams[oe].splice(Se,1),this._shimmedLocalStreams[oe].length===1&&delete this._shimmedLocalStreams[oe]}),ne.apply(this,arguments)}}function T(z,j){if(!z.RTCPeerConnection)return;if(z.RTCPeerConnection.prototype.addTrack&&j.version>=65)return x(z);const te=z.RTCPeerConnection.prototype.getLocalStreams;z.RTCPeerConnection.prototype.getLocalStreams=function(){const _e=te.apply(this);return this._reverseStreams=this._reverseStreams||{},_e.map(xe=>this._reverseStreams[xe.id])};const Q=z.RTCPeerConnection.prototype.addStream;z.RTCPeerConnection.prototype.addStream=function(_e){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},_e.getTracks().forEach(xe=>{if(this.getSenders().find(Pe=>Pe.track===xe))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[_e.id]){const xe=new z.MediaStream(_e.getTracks());this._streams[_e.id]=xe,this._reverseStreams[xe.id]=_e,_e=xe}Q.apply(this,[_e])};const ne=z.RTCPeerConnection.prototype.removeStream;function ae(_e,xe){let Pe=xe.sdp;return Object.keys(_e._reverseStreams||[]).forEach(He=>{const it=_e._reverseStreams[He],pi=_e._streams[it.id];Pe=Pe.replace(new RegExp(pi.id,"g"),it.id)}),new RTCSessionDescription({type:xe.type,sdp:Pe})}z.RTCPeerConnection.prototype.removeStream=function(_e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},ne.apply(this,[this._streams[_e.id]||_e]),delete this._reverseStreams[this._streams[_e.id]?this._streams[_e.id].id:_e.id],delete this._streams[_e.id]},z.RTCPeerConnection.prototype.addTrack=function(_e,xe){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const Pe=[].slice.call(arguments,1);if(Pe.length!==1||!Pe[0].getTracks().find(it=>it===_e))throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(it=>it.track===_e))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const He=this._streams[xe.id];if(He)He.addTrack(_e),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const it=new z.MediaStream([_e]);this._streams[xe.id]=it,this._reverseStreams[it.id]=xe,this.addStream(it)}return this.getSenders().find(it=>it.track===_e)},["createOffer","createAnswer"].forEach(function(_e){const xe=z.RTCPeerConnection.prototype[_e],Pe={[_e](){const He=arguments;return arguments.length&&typeof arguments[0]=="function"?xe.apply(this,[it=>{const pi=ae(this,it);He[0].apply(null,[pi])},it=>{He[1]&&He[1].apply(null,it)},arguments[2]]):xe.apply(this,arguments).then(it=>ae(this,it))}};z.RTCPeerConnection.prototype[_e]=Pe[_e]});const oe=z.RTCPeerConnection.prototype.setLocalDescription;z.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(_e,xe){let Pe=xe.sdp;return Object.keys(_e._reverseStreams||[]).forEach(He=>{const it=_e._reverseStreams[He],pi=_e._streams[it.id];Pe=Pe.replace(new RegExp(it.id,"g"),pi.id)}),new RTCSessionDescription({type:xe.type,sdp:Pe})}(this,arguments[0]),oe.apply(this,arguments)):oe.apply(this,arguments)};const Se=Object.getOwnPropertyDescriptor(z.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(z.RTCPeerConnection.prototype,"localDescription",{get(){const _e=Se.get.apply(this);return _e.type===""?_e:ae(this,_e)}}),z.RTCPeerConnection.prototype.removeTrack=function(_e){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!_e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(_e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let xe;this._streams=this._streams||{},Object.keys(this._streams).forEach(Pe=>{this._streams[Pe].getTracks().find(He=>_e.track===He)&&(xe=this._streams[Pe])}),xe&&(xe.getTracks().length===1?this.removeStream(this._reverseStreams[xe.id]):xe.removeTrack(_e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function O(z,j){!z.RTCPeerConnection&&z.webkitRTCPeerConnection&&(z.RTCPeerConnection=z.webkitRTCPeerConnection),z.RTCPeerConnection&&j.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(te){const Q=z.RTCPeerConnection.prototype[te],ne={[te](){return arguments[0]=new(te==="addIceCandidate"?z.RTCIceCandidate:z.RTCSessionDescription)(arguments[0]),Q.apply(this,arguments)}};z.RTCPeerConnection.prototype[te]=ne[te]})}function k(z,j){d(z,"negotiationneeded",te=>{const Q=te.target;if(!(j.version<72||Q.getConfiguration&&Q.getConfiguration().sdpSemantics==="plan-b")||Q.signalingState==="stable")return te})}var H=o(6677),U=o.n(H);function ee(z){const j=z&&z.navigator,te=j.mediaDevices.getUserMedia.bind(j.mediaDevices);j.mediaDevices.getUserMedia=function(Q){return te(Q).catch(ne=>Promise.reject(function(ae){return{name:{PermissionDeniedError:"NotAllowedError"}[ae.name]||ae.name,message:ae.message,constraint:ae.constraint,toString(){return this.name}}}(ne)))}}function W(z){"getDisplayMedia"in z.navigator&&z.navigator.mediaDevices&&(z.navigator.mediaDevices&&"getDisplayMedia"in z.navigator.mediaDevices||(z.navigator.mediaDevices.getDisplayMedia=z.navigator.getDisplayMedia.bind(z.navigator)))}function $(z,j){if(z.RTCIceGatherer&&(z.RTCIceCandidate||(z.RTCIceCandidate=function(Q){return Q}),z.RTCSessionDescription||(z.RTCSessionDescription=function(Q){return Q}),j.version<15025)){const Q=Object.getOwnPropertyDescriptor(z.MediaStreamTrack.prototype,"enabled");Object.defineProperty(z.MediaStreamTrack.prototype,"enabled",{set(ne){Q.set.call(this,ne);const ae=new Event("enabled");ae.enabled=ne,this.dispatchEvent(ae)}})}z.RTCRtpSender&&!("dtmf"in z.RTCRtpSender.prototype)&&Object.defineProperty(z.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new z.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),z.RTCDtmfSender&&!z.RTCDTMFSender&&(z.RTCDTMFSender=z.RTCDtmfSender);const te=U()(z,j.version);z.RTCPeerConnection=function(Q){return Q&&Q.iceServers&&(Q.iceServers=function(ne){let ae=!1;return(ne=JSON.parse(JSON.stringify(ne))).filter(oe=>{if(oe&&(oe.urls||oe.url)){let Se=oe.urls||oe.url;oe.url&&!oe.urls&&g("RTCIceServer.url","RTCIceServer.urls");const _e=typeof Se=="string";return _e&&(Se=[Se]),Se=Se.filter(xe=>{if(xe.indexOf("stun:")===0)return!1;const Pe=xe.startsWith("turn")&&!xe.startsWith("turn:[")&&xe.includes("transport=udp");return Pe&&!ae?(ae=!0,!0):Pe&&!ae}),delete oe.url,oe.urls=_e?Se[0]:Se,!!Se.length}})}(Q.iceServers,j.version),y("ICE servers after filtering:",Q.iceServers)),new te(Q)},z.RTCPeerConnection.prototype=te.prototype}function B(z){z.RTCRtpSender&&!("replaceTrack"in z.RTCRtpSender.prototype)&&(z.RTCRtpSender.prototype.replaceTrack=z.RTCRtpSender.prototype.setTrack)}function F(z,j){const te=z&&z.navigator,Q=z&&z.MediaStreamTrack;if(te.getUserMedia=function(ne,ae,oe){g("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),te.mediaDevices.getUserMedia(ne).then(ae,oe)},!(j.version>55&&"autoGainControl"in te.mediaDevices.getSupportedConstraints())){const ne=function(oe,Se,_e){Se in oe&&!(_e in oe)&&(oe[_e]=oe[Se],delete oe[Se])},ae=te.mediaDevices.getUserMedia.bind(te.mediaDevices);if(te.mediaDevices.getUserMedia=function(oe){return typeof oe=="object"&&typeof oe.audio=="object"&&(oe=JSON.parse(JSON.stringify(oe)),ne(oe.audio,"autoGainControl","mozAutoGainControl"),ne(oe.audio,"noiseSuppression","mozNoiseSuppression")),ae(oe)},Q&&Q.prototype.getSettings){const oe=Q.prototype.getSettings;Q.prototype.getSettings=function(){const Se=oe.apply(this,arguments);return ne(Se,"mozAutoGainControl","autoGainControl"),ne(Se,"mozNoiseSuppression","noiseSuppression"),Se}}if(Q&&Q.prototype.applyConstraints){const oe=Q.prototype.applyConstraints;Q.prototype.applyConstraints=function(Se){return this.kind==="audio"&&typeof Se=="object"&&(Se=JSON.parse(JSON.stringify(Se)),ne(Se,"autoGainControl","mozAutoGainControl"),ne(Se,"noiseSuppression","mozNoiseSuppression")),oe.apply(this,[Se])}}}}function G(z,j){z.navigator.mediaDevices&&"getDisplayMedia"in z.navigator.mediaDevices||z.navigator.mediaDevices&&(z.navigator.mediaDevices.getDisplayMedia=function(te){if(!te||!te.video){const Q=new DOMException("getDisplayMedia without video constraints is undefined");return Q.name="NotFoundError",Q.code=8,Promise.reject(Q)}return te.video===!0?te.video={mediaSource:j}:te.video.mediaSource=j,z.navigator.mediaDevices.getUserMedia(te)})}function q(z){typeof z=="object"&&z.RTCTrackEvent&&"receiver"in z.RTCTrackEvent.prototype&&!("transceiver"in z.RTCTrackEvent.prototype)&&Object.defineProperty(z.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function X(z,j){if(typeof z!="object"||!z.RTCPeerConnection&&!z.mozRTCPeerConnection)return;!z.RTCPeerConnection&&z.mozRTCPeerConnection&&(z.RTCPeerConnection=z.mozRTCPeerConnection),j.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(ne){const ae=z.RTCPeerConnection.prototype[ne],oe={[ne](){return arguments[0]=new(ne==="addIceCandidate"?z.RTCIceCandidate:z.RTCSessionDescription)(arguments[0]),ae.apply(this,arguments)}};z.RTCPeerConnection.prototype[ne]=oe[ne]});const te={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},Q=z.RTCPeerConnection.prototype.getStats;z.RTCPeerConnection.prototype.getStats=function(){const[ne,ae,oe]=arguments;return Q.apply(this,[ne||null]).then(Se=>{if(j.version<53&&!ae)try{Se.forEach(_e=>{_e.type=te[_e.type]||_e.type})}catch(_e){if(_e.name!=="TypeError")throw _e;Se.forEach((xe,Pe)=>{Se.set(Pe,Object.assign({},xe,{type:te[xe.type]||xe.type}))})}return Se}).then(ae,oe)}}function J(z){if(typeof z!="object"||!z.RTCPeerConnection||!z.RTCRtpSender||z.RTCRtpSender&&"getStats"in z.RTCRtpSender.prototype)return;const j=z.RTCPeerConnection.prototype.getSenders;j&&(z.RTCPeerConnection.prototype.getSenders=function(){const Q=j.apply(this,[]);return Q.forEach(ne=>ne._pc=this),Q});const te=z.RTCPeerConnection.prototype.addTrack;te&&(z.RTCPeerConnection.prototype.addTrack=function(){const Q=te.apply(this,arguments);return Q._pc=this,Q}),z.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function se(z){if(typeof z!="object"||!z.RTCPeerConnection||!z.RTCRtpSender||z.RTCRtpSender&&"getStats"in z.RTCRtpReceiver.prototype)return;const j=z.RTCPeerConnection.prototype.getReceivers;j&&(z.RTCPeerConnection.prototype.getReceivers=function(){const te=j.apply(this,[]);return te.forEach(Q=>Q._pc=this),te}),d(z,"track",te=>(te.receiver._pc=te.srcElement,te)),z.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ce(z){z.RTCPeerConnection&&!("removeStream"in z.RTCPeerConnection.prototype)&&(z.RTCPeerConnection.prototype.removeStream=function(j){g("removeStream","removeTrack"),this.getSenders().forEach(te=>{te.track&&j.getTracks().includes(te.track)&&this.removeTrack(te)})})}function Y(z){z.DataChannel&&!z.RTCDataChannel&&(z.RTCDataChannel=z.DataChannel)}function fe(z){if(typeof z!="object"||!z.RTCPeerConnection)return;const j=z.RTCPeerConnection.prototype.addTransceiver;j&&(z.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const te=arguments[1],Q=te&&"sendEncodings"in te;Q&&te.sendEncodings.forEach(ae=>{if("rid"in ae&&!/^[a-z0-9]{0,16}$/i.test(ae.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in ae&&!(parseFloat(ae.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in ae&&!(parseFloat(ae.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const ne=j.apply(this,arguments);if(Q){const{sender:ae}=ne,oe=ae.getParameters();(!("encodings"in oe)||oe.encodings.length===1&&Object.keys(oe.encodings[0]).length===0)&&(oe.encodings=te.sendEncodings,ae.sendEncodings=te.sendEncodings,this.setParametersPromises.push(ae.setParameters(oe).then(()=>{delete ae.sendEncodings}).catch(()=>{delete ae.sendEncodings})))}return ne})}function he(z){if(typeof z!="object"||!z.RTCRtpSender)return;const j=z.RTCRtpSender.prototype.getParameters;j&&(z.RTCRtpSender.prototype.getParameters=function(){const te=j.apply(this,arguments);return"encodings"in te||(te.encodings=[].concat(this.sendEncodings||[{}])),te})}function pe(z){if(typeof z!="object"||!z.RTCPeerConnection)return;const j=z.RTCPeerConnection.prototype.createOffer;z.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>j.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):j.apply(this,arguments)}}function ue(z){if(typeof z!="object"||!z.RTCPeerConnection)return;const j=z.RTCPeerConnection.prototype.createAnswer;z.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>j.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):j.apply(this,arguments)}}function Te(z){if(typeof z=="object"&&z.RTCPeerConnection){if("getLocalStreams"in z.RTCPeerConnection.prototype||(z.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in z.RTCPeerConnection.prototype)){const j=z.RTCPeerConnection.prototype.addTrack;z.RTCPeerConnection.prototype.addStream=function(te){this._localStreams||(this._localStreams=[]),this._localStreams.includes(te)||this._localStreams.push(te),te.getAudioTracks().forEach(Q=>j.call(this,Q,te)),te.getVideoTracks().forEach(Q=>j.call(this,Q,te))},z.RTCPeerConnection.prototype.addTrack=function(te,...Q){return Q&&Q.forEach(ne=>{this._localStreams?this._localStreams.includes(ne)||this._localStreams.push(ne):this._localStreams=[ne]}),j.apply(this,arguments)}}"removeStream"in z.RTCPeerConnection.prototype||(z.RTCPeerConnection.prototype.removeStream=function(j){this._localStreams||(this._localStreams=[]);const te=this._localStreams.indexOf(j);if(te===-1)return;this._localStreams.splice(te,1);const Q=j.getTracks();this.getSenders().forEach(ne=>{Q.includes(ne.track)&&this.removeTrack(ne)})})}}function be(z){if(typeof z=="object"&&z.RTCPeerConnection&&("getRemoteStreams"in z.RTCPeerConnection.prototype||(z.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in z.RTCPeerConnection.prototype))){Object.defineProperty(z.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(te){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=te),this.addEventListener("track",this._onaddstreampoly=Q=>{Q.streams.forEach(ne=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(ne))return;this._remoteStreams.push(ne);const ae=new Event("addstream");ae.stream=ne,this.dispatchEvent(ae)})})}});const j=z.RTCPeerConnection.prototype.setRemoteDescription;z.RTCPeerConnection.prototype.setRemoteDescription=function(){const te=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(Q){Q.streams.forEach(ne=>{if(te._remoteStreams||(te._remoteStreams=[]),te._remoteStreams.indexOf(ne)>=0)return;te._remoteStreams.push(ne);const ae=new Event("addstream");ae.stream=ne,te.dispatchEvent(ae)})}),j.apply(te,arguments)}}}function Z(z){if(typeof z!="object"||!z.RTCPeerConnection)return;const j=z.RTCPeerConnection.prototype,te=j.createOffer,Q=j.createAnswer,ne=j.setLocalDescription,ae=j.setRemoteDescription,oe=j.addIceCandidate;j.createOffer=function(_e,xe){const Pe=arguments.length>=2?arguments[2]:arguments[0],He=te.apply(this,[Pe]);return xe?(He.then(_e,xe),Promise.resolve()):He},j.createAnswer=function(_e,xe){const Pe=arguments.length>=2?arguments[2]:arguments[0],He=Q.apply(this,[Pe]);return xe?(He.then(_e,xe),Promise.resolve()):He};let Se=function(_e,xe,Pe){const He=ne.apply(this,[_e]);return Pe?(He.then(xe,Pe),Promise.resolve()):He};j.setLocalDescription=Se,Se=function(_e,xe,Pe){const He=ae.apply(this,[_e]);return Pe?(He.then(xe,Pe),Promise.resolve()):He},j.setRemoteDescription=Se,Se=function(_e,xe,Pe){const He=oe.apply(this,[_e]);return Pe?(He.then(xe,Pe),Promise.resolve()):He},j.addIceCandidate=Se}function K(z){const j=z&&z.navigator;if(j.mediaDevices&&j.mediaDevices.getUserMedia){const te=j.mediaDevices,Q=te.getUserMedia.bind(te);j.mediaDevices.getUserMedia=ne=>Q(re(ne))}!j.getUserMedia&&j.mediaDevices&&j.mediaDevices.getUserMedia&&(j.getUserMedia=(function(te,Q,ne){j.mediaDevices.getUserMedia(te).then(Q,ne)}).bind(j))}function re(z){return z&&z.video!==void 0?Object.assign({},z,{video:R(z.video)}):z}function de(z){if(!z.RTCPeerConnection)return;const j=z.RTCPeerConnection;z.RTCPeerConnection=function(te,Q){if(te&&te.iceServers){const ne=[];for(let ae=0;ae<te.iceServers.length;ae++){let oe=te.iceServers[ae];!oe.hasOwnProperty("urls")&&oe.hasOwnProperty("url")?(g("RTCIceServer.url","RTCIceServer.urls"),oe=JSON.parse(JSON.stringify(oe)),oe.urls=oe.url,delete oe.url,ne.push(oe)):ne.push(te.iceServers[ae])}te.iceServers=ne}return new j(te,Q)},z.RTCPeerConnection.prototype=j.prototype,"generateCertificate"in j&&Object.defineProperty(z.RTCPeerConnection,"generateCertificate",{get:()=>j.generateCertificate})}function ye(z){typeof z=="object"&&z.RTCTrackEvent&&"receiver"in z.RTCTrackEvent.prototype&&!("transceiver"in z.RTCTrackEvent.prototype)&&Object.defineProperty(z.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ee(z){const j=z.RTCPeerConnection.prototype.createOffer;z.RTCPeerConnection.prototype.createOffer=function(te){if(te){te.offerToReceiveAudio!==void 0&&(te.offerToReceiveAudio=!!te.offerToReceiveAudio);const Q=this.getTransceivers().find(ae=>ae.receiver.track.kind==="audio");te.offerToReceiveAudio===!1&&Q?Q.direction==="sendrecv"?Q.setDirection?Q.setDirection("sendonly"):Q.direction="sendonly":Q.direction==="recvonly"&&(Q.setDirection?Q.setDirection("inactive"):Q.direction="inactive"):te.offerToReceiveAudio!==!0||Q||this.addTransceiver("audio"),te.offerToReceiveVideo!==void 0&&(te.offerToReceiveVideo=!!te.offerToReceiveVideo);const ne=this.getTransceivers().find(ae=>ae.receiver.track.kind==="video");te.offerToReceiveVideo===!1&&ne?ne.direction==="sendrecv"?ne.setDirection?ne.setDirection("sendonly"):ne.direction="sendonly":ne.direction==="recvonly"&&(ne.setDirection?ne.setDirection("inactive"):ne.direction="inactive"):te.offerToReceiveVideo!==!0||ne||this.addTransceiver("video")}return j.apply(this,arguments)}}function Ve(z){typeof z!="object"||z.AudioContext||(z.AudioContext=z.webkitAudioContext)}var De=o(7963),Ue=o.n(De);function Ye(z){if(!z.RTCIceCandidate||z.RTCIceCandidate&&"foundation"in z.RTCIceCandidate.prototype)return;const j=z.RTCIceCandidate;z.RTCIceCandidate=function(te){if(typeof te=="object"&&te.candidate&&te.candidate.indexOf("a=")===0&&((te=JSON.parse(JSON.stringify(te))).candidate=te.candidate.substr(2)),te.candidate&&te.candidate.length){const Q=new j(te),ne=Ue().parseCandidate(te.candidate),ae=Object.assign(Q,ne);return ae.toJSON=function(){return{candidate:ae.candidate,sdpMid:ae.sdpMid,sdpMLineIndex:ae.sdpMLineIndex,usernameFragment:ae.usernameFragment}},ae}return new j(te)},z.RTCIceCandidate.prototype=j.prototype,d(z,"icecandidate",te=>(te.candidate&&Object.defineProperty(te,"candidate",{value:new z.RTCIceCandidate(te.candidate),writable:"false"}),te))}function Ie(z,j){if(!z.RTCPeerConnection)return;"sctp"in z.RTCPeerConnection.prototype||Object.defineProperty(z.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});const te=z.RTCPeerConnection.prototype.setRemoteDescription;z.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,j.browser==="chrome"&&j.version>=76){const{sdpSemantics:Q}=this.getConfiguration();Q==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(Q){if(!Q||!Q.sdp)return!1;const ne=Ue().splitSections(Q.sdp);return ne.shift(),ne.some(ae=>{const oe=Ue().parseMLine(ae);return oe&&oe.kind==="application"&&oe.protocol.indexOf("SCTP")!==-1})}(arguments[0])){const Q=function(_e){const xe=_e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(xe===null||xe.length<2)return-1;const Pe=parseInt(xe[1],10);return Pe!=Pe?-1:Pe}(arguments[0]),ne=function(_e){let xe=65536;return j.browser==="firefox"&&(xe=j.version<57?_e===-1?16384:2147483637:j.version<60?j.version===57?65535:65536:2147483637),xe}(Q),ae=function(_e,xe){let Pe=65536;j.browser==="firefox"&&j.version===57&&(Pe=65535);const He=Ue().matchPrefix(_e.sdp,"a=max-message-size:");return He.length>0?Pe=parseInt(He[0].substr(19),10):j.browser==="firefox"&&xe!==-1&&(Pe=2147483637),Pe}(arguments[0],Q);let oe;oe=ne===0&&ae===0?Number.POSITIVE_INFINITY:ne===0||ae===0?Math.max(ne,ae):Math.min(ne,ae);const Se={};Object.defineProperty(Se,"maxMessageSize",{get:()=>oe}),this._sctp=Se}return te.apply(this,arguments)}}function Oe(z){if(!z.RTCPeerConnection||!("createDataChannel"in z.RTCPeerConnection.prototype))return;function j(Q,ne){const ae=Q.send;Q.send=function(){const oe=arguments[0],Se=oe.length||oe.size||oe.byteLength;if(Q.readyState==="open"&&ne.sctp&&Se>ne.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+ne.sctp.maxMessageSize+" bytes)");return ae.apply(Q,arguments)}}const te=z.RTCPeerConnection.prototype.createDataChannel;z.RTCPeerConnection.prototype.createDataChannel=function(){const Q=te.apply(this,arguments);return j(Q,this),Q},d(z,"datachannel",Q=>(j(Q.channel,Q.target),Q))}function $e(z){if(!z.RTCPeerConnection||"connectionState"in z.RTCPeerConnection.prototype)return;const j=z.RTCPeerConnection.prototype;Object.defineProperty(j,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(j,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(te){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),te&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=te)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(te=>{const Q=j[te];j[te]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=ne=>{const ae=ne.target;if(ae._lastConnectionState!==ae.connectionState){ae._lastConnectionState=ae.connectionState;const oe=new Event("connectionstatechange",ne);ae.dispatchEvent(oe)}return ne},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),Q.apply(this,arguments)}})}function Ke(z,j){if(!z.RTCPeerConnection||j.browser==="chrome"&&j.version>=71||j.browser==="safari"&&j.version>=605)return;const te=z.RTCPeerConnection.prototype.setRemoteDescription;z.RTCPeerConnection.prototype.setRemoteDescription=function(Q){if(Q&&Q.sdp&&Q.sdp.indexOf(`
a=extmap-allow-mixed`)!==-1){const ne=Q.sdp.split(`
`).filter(ae=>ae.trim()!=="a=extmap-allow-mixed").join(`
`);z.RTCSessionDescription&&Q instanceof z.RTCSessionDescription?arguments[0]=new z.RTCSessionDescription({type:Q.type,sdp:ne}):Q.sdp=ne}return te.apply(this,arguments)}}function Fe(z,j){if(!z.RTCPeerConnection||!z.RTCPeerConnection.prototype)return;const te=z.RTCPeerConnection.prototype.addIceCandidate;te&&te.length!==0&&(z.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(j.browser==="chrome"&&j.version<78||j.browser==="firefox"&&j.version<68||j.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():te.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}const st=function({window:z}={},j={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const te=y,Q=function(ae){const oe={browser:null,version:null};if(ae===void 0||!ae.navigator)return oe.browser="Not a browser.",oe;const{navigator:Se}=ae;if(Se.mozGetUserMedia)oe.browser="firefox",oe.version=m(Se.userAgent,/Firefox\/(\d+)\./,1);else if(Se.webkitGetUserMedia||ae.isSecureContext===!1&&ae.webkitRTCPeerConnection&&!ae.RTCIceGatherer)oe.browser="chrome",oe.version=m(Se.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(Se.mediaDevices&&Se.userAgent.match(/Edge\/(\d+).(\d+)$/))oe.browser="edge",oe.version=m(Se.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!ae.RTCPeerConnection||!Se.userAgent.match(/AppleWebKit\/(\d+)\./))return oe.browser="Not a supported browser.",oe;oe.browser="safari",oe.version=m(Se.userAgent,/AppleWebKit\/(\d+)\./,1),oe.supportsUnifiedPlan=ae.RTCRtpTransceiver&&"currentDirection"in ae.RTCRtpTransceiver.prototype}return oe}(z),ne={browserDetails:Q,commonShim:v,extractVersion:m,disableLog:u,disableWarnings:b};switch(Q.browser){case"chrome":if(!c||!O||!j.shimChrome)return te("Chrome shim is not included in this adapter release."),ne;if(Q.version===null)return te("Chrome shim can not determine version, not shimming."),ne;te("adapter.js shimming chrome."),ne.browserShim=c,Fe(z,Q),A(z,Q),N(z),O(z,Q),M(z),T(z,Q),D(z),L(z),P(z),k(z,Q),Ye(z),$e(z),Ie(z,Q),Oe(z),Ke(z,Q);break;case"firefox":if(!l||!X||!j.shimFirefox)return te("Firefox shim is not included in this adapter release."),ne;te("adapter.js shimming firefox."),ne.browserShim=l,Fe(z,Q),F(z,Q),X(z,Q),q(z),ce(z),J(z),se(z),Y(z),fe(z),he(z),pe(z),ue(z),Ye(z),$e(z),Ie(z,Q),Oe(z);break;case"edge":if(!h||!$||!j.shimEdge)return te("MS edge shim is not included in this adapter release."),ne;te("adapter.js shimming edge."),ne.browserShim=h,ee(z),W(z),$(z,Q),B(z),Ie(z,Q),Oe(z);break;case"safari":if(!f||!j.shimSafari)return te("Safari shim is not included in this adapter release."),ne;te("adapter.js shimming safari."),ne.browserShim=f,Fe(z,Q),de(z),Ee(z),Z(z),Te(z),be(z),ye(z),K(z),Ve(z),Ye(z),Ie(z,Q),Oe(z),Ke(z,Q);break;default:te("Unsupported browser!")}return ne}({window:typeof window>"u"?void 0:window}),tt=st},6834:(a,s,o)=>{o.r(s),o.d(s,{default:()=>l});var c=o(5512),h=o.n(c);function l(){return h()('/*! aliyun rts sdk - ver2.14.6 created:2026/3/25 20:14:32 */(()=>{"use strict";var e={28:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});t.default={version:"2.14.6",protocol_version:2,sdk_version:"0.0.1"}},917:(e,t)=>{var r,o,n,i;Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_RETRY_DATACHANNEL_TIMEOUT=t.DEFAULT_HEARTBEAT_TIMEOUT_CHECK_INTERVAL=t.DEFAULT_HEARTBEAT_TIMEOUT_COUNT=t.DEFAULT_RETRY_PUBLISH_INTERVAL=t.DEFAULT_RETRY_SUBSCRIBE_INTERVAL=t.DEFAULT_RETRY_PUBLISH_LIMIT=t.DEFAULT_RETRY_SUBSCRIBE_LIMIT=t.EWorkerAction=t.EWorkerSource=t.EConnectStatus=t.TrackType=void 0,function(e){e.AUDIO="audio",e.VIDEO="video"}(r||(t.TrackType=r={})),function(e){e[e.CONNECT_STATUS_DISCONNECTED=0]="CONNECT_STATUS_DISCONNECTED",e[e.CONNECT_STATUS_CONNECTING=1]="CONNECT_STATUS_CONNECTING",e[e.CONNECT_STATUS_CONNECTED=2]="CONNECT_STATUS_CONNECTED",e[e.CONNECT_STATUS_RECONNECTING=3]="CONNECT_STATUS_RECONNECTING"}(o||(t.EConnectStatus=o={})),function(e){e.Sender="sender",e.Receiver="receiver"}(n||(t.EWorkerSource=n={})),function(e){e.Setup="setup",e.InserSEI="insertSEI",e.UpdatePubStats="updatePubStats",e.UpdateSubStats="updateSubStats",e.SwitchCumuDelay="switchCumuDelay"}(i||(t.EWorkerAction=i={})),t.DEFAULT_RETRY_SUBSCRIBE_LIMIT=5,t.DEFAULT_RETRY_PUBLISH_LIMIT=5,t.DEFAULT_RETRY_SUBSCRIBE_INTERVAL=2e3,t.DEFAULT_RETRY_PUBLISH_INTERVAL=2e3,t.DEFAULT_HEARTBEAT_TIMEOUT_COUNT=8,t.DEFAULT_HEARTBEAT_TIMEOUT_CHECK_INTERVAL=1e3,t.DEFAULT_RETRY_DATACHANNEL_TIMEOUT=8e3},649:function(e,t,r){var o,n,i=this&&this.__assign||function(){return i=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},i.apply(this,arguments)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CumuDelaySeiPayloadParser=t.CumuDelaySeiPayload=t.ECumuDelayGrtnKey=t.ECumuDelayPubSdkKey=t.ECumuDelayAVCommonKey=t.ECumuDelayVideoKey=t.ECumuDelayGrtnExportKey=t.ECumuDelaySubKey=t.CUMU_DELAY_UUID=t.CUMU_DELAY_SEI_PAYLOAD_TYPE=void 0;var s,u,l,A,C=a(r(28));t.CUMU_DELAY_SEI_PAYLOAD_TYPE=99,t.CUMU_DELAY_UUID=[32,36,16,9,16,23,7,1,150,117,25,212,25,129,3,7],function(e){e.SophonAudioDual="sophon_audio_dual",e.SophonVideoCamera="sophon_video_camera",e.SophonVideoCameraSmall="sophon_video_camera_small",e.SophonVideoCameraSuper="sophon_video_camera_super",e.SophonVideoScreenShare="sophon_video_screen_share",e.SophonAudio="sophon_audio",e.SophonVideoCameraLarge="sophon_video_camera_large",e.RtsAudio="rts audio",e.RtsVideo="rts video"}(s||(s={})),function(e){e[e.Web=0]="Web",e[e.iOS=1]="iOS",e[e.Android=2]="Android"}(u||(u={})),function(e){e.VTotalCost="VTotalCost",e.VAssemblyCost="VAssemblyCost",e.VJitterBufferDelay="VJitterBufferDelay",e.VDecPlugCost="VDecPlugCost",e.DownRTTHalf="DownRTTHalf"}(l||(t.ECumuDelaySubKey=l={})),function(e){e.TOTAL_COST="TOTAL_COST",e.ENTER_GRTN_TIMESTAMP="ENTER_GRTN_TIMESTAMP",e.LEAVE_GRTN_TIMESTAMP="LEAVE_GRTN_TIMESTAMP"}(A||(t.ECumuDelayGrtnExportKey=A={}));var T,c,f,d,E,_,y,S=((o={})[s.SophonAudioDual]=4,o[s.SophonVideoCamera]=5,o[s.SophonVideoCameraSmall]=6,o[s.SophonVideoCameraSuper]=7,o[s.SophonVideoScreenShare]=8,o[s.SophonAudio]=9,o[s.SophonVideoCameraLarge]=10,o[s.RtsAudio]=11,o[s.RtsVideo]=12,o);(n={})[S[s.SophonAudioDual]]=s.SophonAudioDual,n[S[s.SophonVideoCamera]]=s.SophonVideoCamera,n[S[s.SophonVideoCameraSmall]]=s.SophonVideoCameraSmall,n[S[s.SophonVideoCameraSuper]]=s.SophonVideoCameraSuper,n[S[s.SophonVideoScreenShare]]=s.SophonVideoScreenShare,n[S[s.SophonAudio]]=s.SophonAudio,n[S[s.SophonVideoCameraLarge]]=s.SophonVideoCameraLarge,n[S[s.RtsAudio]]=s.RtsAudio,n[S[s.RtsVideo]]=s.RtsVideo;!function(e){e[e.VTotalCost=4]="VTotalCost",e[e.CapDeviceCost=5]="CapDeviceCost",e[e.PushExtCost=6]="PushExtCost",e[e.CapPlugCost=7]="CapPlugCost",e[e.PrepThrCost=8]="PrepThrCost",e[e.PrepPlugCost=9]="PrepPlugCost",e[e.DispThrCost=10]="DispThrCost",e[e.DispPlugCost=11]="DispPlugCost",e[e.VEncThrCost=12]="VEncThrCost",e[e.VEncPlugCost=13]="VEncPlugCost"}(T||(t.ECumuDelayVideoKey=T={})),function(e){e[e.ATotalCost=24]="ATotalCost",e[e.ASourceCCost=25]="ASourceCCost",e[e.AMixerCost=26]="AMixerCost",e[e.AEncodeCCost=27]="AEncodeCCost",e[e.AAIClientQuestionTimestampHEAD=28]="AAIClientQuestionTimestampHEAD",e[e.AAIClientQuestionTimestampTAIL=29]="AAIClientQuestionTimestampTAIL",e[e.AAIClientAnswerTimestampHEAD=30]="AAIClientAnswerTimestampHEAD",e[e.AAIClientAnswerTimestampTAIL=31]="AAIClientAnswerTimestampTAIL",e[e.AAIClientScentenceId=32]="AAIClientScentenceId",e[e.AAIClientSourceCost=33]="AAIClientSourceCost",e[e.AAIClientMixerCost=34]="AAIClientMixerCost",e[e.AAIClientEncoderCost=35]="AAIClientEncoderCost",e[e.AAILinuxReceiveCost=36]="AAILinuxReceiveCost",e[e.AAILinuxNeteqCost=37]="AAILinuxNeteqCost",e[e.AAILinuxRemoteSourceCost=38]="AAILinuxRemoteSourceCost",e[e.AAILinuxPlayMixerCost=39]="AAILinuxPlayMixerCost",e[e.AAILinuxPlayCost=40]="AAILinuxPlayCost",e[e.AAIClientQuestionUidDigestHEAD=41]="AAIClientQuestionUidDigestHEAD",e[e.AAIClientQuestionUidDigestTAIL=42]="AAIClientQuestionUidDigestTAIL",e[e.AIClinetSmartDenoise=43]="AIClinetSmartDenoise"}(c||(c={})),function(e){e[e.NetsdkThrCost=44]="NetsdkThrCost",e[e.QosThrCost=45]="QosThrCost",e[e.PacerCost=46]="PacerCost",e[e.UpRTTHalf=47]="UpRTTHalf",e[e.AIClientNetsdkThrCost=48]="AIClientNetsdkThrCost",e[e.AIClientQosThrCost=49]="AIClientQosThrCost",e[e.AIClientPacerCost=50]="AIClientPacerCost",e[e.AIClientUpRTTHalf=51]="AIClientUpRTTHalf"}(f||(t.ECumuDelayAVCommonKey=f={})),function(e){e[e.AIAsrCost=64]="AIAsrCost",e[e.AILlmCost=65]="AILlmCost",e[e.AITtsCost=66]="AITtsCost",e[e.AIMuteCost=67]="AIMuteCost",e[e.AIAgentTotalCost=68]="AIAgentTotalCost",e[e.AIAgentExtraAvatarCost=69]="AIAgentExtraAvatarCost"}(d||(d={})),function(e){e[e.PubSdkType=100]="PubSdkType",e[e.PubSdkVersion=101]="PubSdkVersion"}(E||(t.ECumuDelayPubSdkKey=E={})),function(e){e[e.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_INTERNAL_RTT_HALF=121]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_INTERNAL_RTT_HALF",e[e.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_BEF_PACER=122]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_BEF_PACER",e[e.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_PACER_COST=123]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_PACER_COST",e[e.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_DOWN_RTT_HALF=124]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_DOWN_RTT_HALF"}(_||(t.ECumuDelayGrtnKey=_={})),function(e){e[e.AIGRTNInternalRTTHalf=104]="AIGRTNInternalRTTHalf",e[e.AIGRTNBeforePacer=105]="AIGRTNBeforePacer",e[e.AIGRTNPacerCost=106]="AIGRTNPacerCost",e[e.AIGRTNDownRTTHalf=107]="AIGRTNDownRTTHalf"}(y||(y={}));var p=function(e){e.msid=s.SophonAudio;var t=S[e.msid];t||console.warn("No mapped msid for cumuDelay",e.msid);var r=new ArrayBuffer(e.sendTs?8:4);if(e.sendTs){var o=Math.floor(performance.now()+performance.timeOrigin-e.windowTimeOrigin);o>=Math.pow(2,32)-1&&(o=0);var n=new DataView(r);n.setUint8(0,8),n.setUint8(1,0),n.setUint8(2,t),n.setUint8(3,5),n.setUint32(4,o)}else new Uint8Array(r).set([0,0,t,1]);e.kv[E.PubSdkType]=u.Web,e.kv[E.PubSdkVersion]=Number(C.default.version.split(".").join("").split("-")[0]);var a=Object.keys(e.kv).length;a>256&&console.warn("Too much kv");var l,A,c,d,_=1+3*a+1,y=new ArrayBuffer(_),p=new DataView(y);p.setInt8(0,a),Object.keys(e.kv).forEach((function(t,r){t in i(i(i({},T),f),E)||console.warn("Unknown CumuDelay key: ".concat(t));var o=e.kv[t],n=1+3*r;p.setUint8(n,parseInt(t)),p.setUint16(n+1,o)})),p.setUint8(_-1,128),this.buffer=(l=r,A=y,c=new ArrayBuffer(l.byteLength+A.byteLength),(d=new Uint8Array(c)).set(new Uint8Array(l),0),d.set(new Uint8Array(A),l.byteLength),c)};t.CumuDelaySeiPayload=p;var h=function(e){var t;this.pub={},this.grtn={},this.AIPub={},this.AISub={},this.AIAgent={},this.AIGrtn={},this.other={};var r,o,n=new v(e),i=(n.readBits(3),n.readBits()),a=n.readBits(),s=n.readBits(),u=n.readBits(),l=n.readBits();n.readBits(8),n.readBits(8),n.readBits(8),1===i&&n.readBits(16);if(1===a){var C=n.readBits(32);this.pub.timestamp=C,this.pub.timestampRecv=Math.floor(performance.now())}1===s&&n.readBits(16);1===u&&(r=n.readBits(32)),1===l&&(o=n.readBits(32)),r&&o&&(this.grtn=((t={})[A.TOTAL_COST]=o-r,t[A.ENTER_GRTN_TIMESTAMP]=r,t[A.LEAVE_GRTN_TIMESTAMP]=o,t));for(var S=n.readBits(8),p=0;p<S;p++){var h=n.readBits(8),m=n.readBits(16);if(I(h,[T.VTotalCost,T.VEncPlugCost])||I(h,[c.ATotalCost,c.AEncodeCCost])||I(h,[f.NetsdkThrCost,f.UpRTTHalf])||I(h,[E.PubSdkType,E.PubSdkVersion])){var b=T[h]||c[h]||f[h]||E[h];this.pub[b]=m}else if(I(h,[c.AAIClientQuestionTimestampHEAD,c.AAIClientEncoderCost])||I(h,[f.AIClientNetsdkThrCost,f.AIClientUpRTTHalf]))b=c[h]||f[h],this.AIPub[b]=m;else if(I(h,[c.AAILinuxReceiveCost,c.AIClinetSmartDenoise]))b=c[h],this.AISub[b]=m;else if(I(h,[d.AIAsrCost,d.AIAgentExtraAvatarCost]))b=d[h],this.AIAgent[b]=m;else if(I(h,[y.AIGRTNInternalRTTHalf,y.AIGRTNDownRTTHalf])){b=y[h];for(var U=0,D="".concat(b,"_").concat(U);this.AIGrtn.hasOwnProperty(D);)D="".concat(b,"_").concat(U++);this.AIGrtn[D]=m}else if(I(h,[_.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_INTERNAL_RTT_HALF,_.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_DOWN_RTT_HALF])){for(b=_[h],U=0,D="".concat(b,"_").concat(U);this.grtn.hasOwnProperty(D);)D="".concat(b,"_").concat(U++);this.grtn[D]=m}else this.other[h]=m}};function I(e,t){return e>=t[0]&&e<=t[1]}t.CumuDelaySeiPayloadParser=h;var v=function(){function e(e){this.byteOffset=0,this.bitOffset=0;var t=new Uint8Array(e);this.buffer=t}return e.prototype.readBits=function(e){void 0===e&&(e=1);for(var t=0,r=0;r<e;){if(this.byteOffset>=this.buffer.byteLength)throw new Error("readBits out of range");var o=8-this.bitOffset,n=Math.min(o,e-r);t=t<<n|this.getBitsFromByte(this.buffer,this.byteOffset,this.bitOffset,this.bitOffset+n-1),this.bitOffset+=n,r+=n,8===this.bitOffset&&(this.byteOffset++,this.bitOffset=0)}return 32===e&&(t>>>=0),t},e.prototype.hasNext=function(){return this.byteOffset<this.buffer.byteLength},e.prototype.getBitsFromByte=function(e,t,r,o){if(t<0||t>=e.byteLength||r<0||o>7||r>o)throw new Error("Invalid parameters");return e[t]>>7-o&(1<<o-r+1)-1},e}()},594:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readUUID=t.discardEPB=t.insertEPB=t.SODBtoRBSP=t.convertPayloadSize=t.NALU=t.SEI=t.parseSei=t.insertSei=void 0;var o=r(649);t.insertSei=function(e,t,r,o){void 0===r&&(r=5);for(var a=e.data,s=new DataView(a),u=0;;){if(1===s.getUint32(u)){s.getUint8(u+4);var l=new n(t,r,o).buffer,A=new i(l).buffer,C=new ArrayBuffer(A.byteLength+a.byteLength),T=new Uint8Array(C),c=new Uint8Array(A);T.set(c);var f=new Uint8Array(a);T.set(f,A.byteLength),e.data=C,u+=1;break}if((u+=1)+4>=s.byteLength)break}};t.parseSei=function(e){for(var r=[],o=new DataView(e),n=0;;){var i=n,s=o.getUint32(i);if(i+=4,1===s){if(6===(31&o.getUint8(i++))){for(var u=o.getUint8(i++),l=a(u)?16:0,A=0;255==o.getUint8(i);)i++,A+=255;if((A+=o.getUint8(i++))>0&&o.byteLength>i+A){var C=new Uint8Array(o.buffer),T="";if(a(u)){var c=C.slice(i,i+l);T=(0,t.readUUID)((0,t.discardEPB)(c))}var f=C.slice(i+l,i+A);i+=A,r.push({payloadType:u,uuid:T,data:f.buffer})}}n=i}else n+=1;if(n+4>=o.byteLength)break}return r};var n=function(e,r,o){void 0===r&&(r=5);var n=a(r)?16:0,i=e.byteLength+n,s=(0,t.convertPayloadSize)(i),u=s.buffer.byteLength,l=new ArrayBuffer(1+u+n+e.byteLength),A=new Uint8Array(l),C=0;if(A[C++]=r,A.set(s,C),C+=s.byteLength,a(r)){o=(o||"00000000-0000-0000-0000-000000000000").replace(/-/g,"");for(var T=0;T<16;T++)A[C+T]=parseInt(o.substr(2*T,2),16);C+=16}var c=new Uint8Array(e);A.set(c,C);var f=(0,t.SODBtoRBSP)(A);this.buffer=f.buffer};t.SEI=n;var i=function(e){var t=new Uint8Array([0,0,0,1]),r=new Uint8Array([6]),o=new ArrayBuffer(t.byteLength+r.byteLength+e.byteLength),n=new Uint8Array(o);n.set(t),n.set(r,t.byteLength),n.set(new Uint8Array(e),t.byteLength+r.byteLength),this.buffer=o};t.NALU=i;t.convertPayloadSize=function(e){if(e<=0)throw new Error("payloadSize must be a positive integer.");for(var t=Math.ceil(e/255),r=new ArrayBuffer(t),o=new DataView(r),n=0;n<t-1;n++)o.setUint8(n,255);return o.setUint8(t-1,e%255&255),new Uint8Array(r)};t.SODBtoRBSP=function(e){for(var r=new Uint8Array(e),o="",n=0;n<r.length;n++)o+=r[n].toString(2).padStart(8,"0");for(o+="1";o.length%8!=0;)o+="0";var i=o.length/8,a=new Uint8Array(i);for(n=0;n<i;n++)a[n]=parseInt(o.slice(8*n,8*n+8),2);return(0,t.insertEPB)(a)};t.insertEPB=function(e){for(var t=[],r=0,o=0;o<e.length;o++)t.push(e[o]),0===e[o]?2===++r&&o<e.length-1&&e[o+1]<=3&&(t.push(3),r=0):r=0;return new Uint8Array(t)};t.discardEPB=function(e){for(var t=e.byteLength,r=[],o=1;o<t-2;)0===e[o]&&0===e[o+1]&&3===e[o+2]?(r.push(o+2),o+=2):o++;if(0===r.length)return e;var n=t-r.length,i=new Uint8Array(n),a=0;for(o=0;o<n;a++,o++)a===r[0]&&(a++,r.shift()),i[o]=e[a];return i};t.readUUID=function(e){if(16!==e.length)throw new Error("UUID must be 16 bytes long.");var t=e.reduce((function(e,t){return e+t.toString(16).padStart(2,"0")}),"");return"".concat(t.slice(0,8),"-").concat(t.slice(8,12),"-").concat(t.slice(12,16),"-").concat(t.slice(16,20),"-").concat(t.slice(20))};var a=function(e){return 5===e||e===o.CUMU_DELAY_SEI_PAYLOAD_TYPE}},718:function(e,t){var r=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,i=t.length;n<i;n++)!o&&n in t||(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.hebtLog=t.createUUID=t.evaluateNetworkCondition=t.makeCancelable=t.hasVideoTrack=t.hasAudioTrack=t.getVideoTrack=t.getAudioTrack=t.pruneSubUrl=t.getJitterBufferDelayAvg=void 0,t.lowercaseFirstLetter=function(e){return e.replace(/([A-Za-z])/,(function(e){return e.toLowerCase()}))},t.underlineToCamelCase=function(e){return e.replace(/_([a-z])/g,(function(e,t){return t.toUpperCase()}))};t.getJitterBufferDelayAvg=function(e,t){return e&&t?Number(e)/Number(t)*1e3:-1};t.pruneSubUrl=function(e,t){var r=e||"";return r=r.replace("@subaudio=no","").replace("@subvideo=no",""),t&&(r=r.split("?")[0]),r};t.getAudioTrack=function(e){return e.getAudioTracks()[0]};t.getVideoTrack=function(e){return e.getVideoTracks()[0]};t.hasAudioTrack=function(e){return e.getAudioTracks().length>0};t.hasVideoTrack=function(e){return e.getVideoTracks().length>0};t.makeCancelable=function(e){var t=!1;return{promise:new Promise((function(r,o){e.then((function(e){return t?o({isCanceled:!0}):r(e)})),e.catch((function(e){return o(t?{isCanceled:!0}:e)}))})),cancel:function(){t=!0}}};t.evaluateNetworkCondition=function(e,t,r,o,n){var i=0;if(!navigator.onLine)return i=6;var a=[{loss:0,rtt:0,jbd:1},{loss:0,rtt:1,jbd:0},{loss:0,rtt:.5,jbd:.5},{loss:1,rtt:0,jbd:0},{loss:.8,rtt:0,jbd:.2},{loss:.8,rtt:.2,jbd:0},{loss:.6,rtt:.2,jbd:.2}],s=-1,u=-1,l=-1;if("number"==typeof t&&t>=0||"number"==typeof r&&r>=0){s=0;var A=!1,C=!1;"number"==typeof t&&t>=0&&(s+=t,A=!0),"number"==typeof r&&r>=0&&(s+=r,C=!0),A&&!C&&(s*=2),C&&!A&&(s*=1.8)}if("number"==typeof e&&e>=0&&(l=e),"number"==typeof o&&o>=0||"number"==typeof n&&n>=0){u=0;"number"==typeof o&&o>=0&&(u+=o),"number"==typeof n&&n>=0&&(u+=n)}var T;if((T=4*(-1!==s?1:0)+2*(-1!==l?1:0)+(-1!==u?1:0))>0){var c=1.2*s*a[T-1].loss+l/1500*a[T-1].rtt+u/3e3*a[T-1].jbd;i=c<=.1?1:c<=.23?2:c<=.36?3:c<=.49?4:5}else i=0;return i};t.createUUID=function(e,t){var r,o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),n=[];if(t=t||o.length,e)for(r=0;r<e;r++)n[r]=o[0|Math.random()*t];else{var i=void 0;for(n[8]=n[13]=n[18]=n[23]="-",n[14]="4",r=0;r<36;r++)n[r]||(i=0|16*Math.random(),n[r]=o[19==r?3&i|8:i])}return n.join("")};t.hebtLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];window.RTS_HEBT_DEBUG&&console.log.apply(console,r(["[rts hebt]"],e,!1))}}},t={};function r(o){var n=t[o];if(void 0!==n)return n.exports;var i=t[o]={exports:{}};return e[o].call(i.exports,i,i.exports,r),i.exports}var o,n,i,a,s,u,l,A,C,T,c,f;a=r(594),s=r(718),u=r(649),l=r(917),A=self,C=!1,T=0,c=function(e,t,r,s){if(e===l.EWorkerSource.Sender){var A=new TransformStream({transform:function(e,t){var r=e;if(e.type){if(o)try{(!o.keyframeOnly||o.keyframeOnly&&"key"===e.type)&&((0,a.insertSei)(e,o.sei,o.payloadType,o.uuid),void 0===o.repeatCount?o=null:-1!==o.repeatCount&&(o.repeatCount--,o.repeatCount<0&&(o=null)))}catch(t){e=r,console.log("error in inserting user SEI",t)}else if(C)try{if("key"===e.type&&n){var i={};n.v_encode_time_avg&&(i[u.ECumuDelayVideoKey.VEncPlugCost]=Math.ceil(n.v_encode_time_avg)),n.v_packet_send_delay_avg&&(i[u.ECumuDelayAVCommonKey.PacerCost]=Math.ceil(n.v_packet_send_delay_avg)),n.rtt&&(i[u.ECumuDelayAVCommonKey.UpRTTHalf]=Math.ceil(n.rtt/2*1e3)),i[u.ECumuDelayVideoKey.VTotalCost]=Math.ceil((i[u.ECumuDelayVideoKey.VEncPlugCost]||0)+(i[u.ECumuDelayAVCommonKey.PacerCost]||0)),(0,a.insertSei)(e,new u.CumuDelaySeiPayload({msid:n.vMsid||"",kv:i,sendTs:!0,windowTimeOrigin:T}).buffer,u.CUMU_DELAY_SEI_PAYLOAD_TYPE,(0,a.readUUID)(new Uint8Array(u.CUMU_DELAY_UUID)))}}catch(t){e=r,console.log("error in inserting cumuDelay SEI",t)}r=null,s&&s(e)}t.enqueue(e)}});t.pipeThrough(A).pipeTo(r)}else e===l.EWorkerSource.Receiver&&(A=new TransformStream({transform:function(e,t){var r,o,n,a,l,A,C,T,c,f,d,E=e;if(e.type){try{if(i){var _=((r={})[u.ECumuDelaySubKey.DownRTTHalf]=Math.ceil(((null===(n=null===(o=i.video)||void 0===o?void 0:o.transportStats)||void 0===n?void 0:n.rtt)||0)/2*1e3),r[u.ECumuDelaySubKey.VAssemblyCost]=Math.ceil((null===(l=null===(a=i.video)||void 0===a?void 0:a.inboundRtpStatsPerSec)||void 0===l?void 0:l.totalAssemblyTimeAvg)||0),r[u.ECumuDelaySubKey.VJitterBufferDelay]=Math.ceil((null===(C=null===(A=i.video)||void 0===A?void 0:A.inboundRtpStatsPerSec)||void 0===C?void 0:C.jitterBufferDelayAvg)||0),r[u.ECumuDelaySubKey.VDecPlugCost]=Math.ceil((null===(c=null===(T=i.video)||void 0===T?void 0:T.inboundRtpStatsPerSec)||void 0===c?void 0:c.decodeTimeAvg)||0),r[u.ECumuDelaySubKey.VTotalCost]=Math.ceil((null===(d=null===(f=i.video)||void 0===f?void 0:f.inboundRtpStatsPerSec)||void 0===d?void 0:d.totalProcessingDelayAvg)||0),r);_[u.ECumuDelaySubKey.VTotalCost]||(_[u.ECumuDelaySubKey.VTotalCost]=Math.ceil((_[u.ECumuDelaySubKey.VAssemblyCost]||0)+(_[u.ECumuDelaySubKey.VJitterBufferDelay]||0)+(_[u.ECumuDelaySubKey.VDecPlugCost]||0))),e.subStats=_}}catch(t){console.log("error in parsing SEI",t),e=E}E=null,s&&s(e)}delete e.subStats,t.enqueue(e)}}),t.pipeThrough(A).pipeTo(r))},f=function(e){var t=e.data.slice(0);A.postMessage({type:"encodedFrame",data:t,frameInfo:{type:e.type,timestamp:e.timestamp},subStats:e.subStats},[t]),t=null},A.RTCTransformEvent&&(A.onrtctransform=function(e){var t=e.transformer,r=t.options.source,o=t.readable,n=t.writable;c(r,o,n,(function(e){r===l.EWorkerSource.Receiver&&f(e)}))}),onmessage=function(e){switch(e.data.operation){case l.EWorkerAction.Setup:t=e.data,r=t.source,a=t.readable,u=t.writable,c(r,a,u,(function(e){r===l.EWorkerSource.Receiver&&f(e)}));break;case l.EWorkerAction.InserSEI:!function(e){(o=e)&&(o.uuid=(0,s.createUUID)().toLowerCase(),o.repeatCount=o.repeatCount||0)}(e.data);break;case l.EWorkerAction.UpdatePubStats:!function(e){n=e.stats}(e.data);break;case l.EWorkerAction.UpdateSubStats:!function(e){i=e.stats}(e.data);break;case l.EWorkerAction.SwitchCumuDelay:!function(e){C=e.enable,T=e.windowTimeOrigin}(e.data)}var t,r,a,u}})();',"Worker",void 0,void 0)}},5512:a=>{a.exports=function(s,o,c,h){var l=self||window;try{try{var f;try{f=new l.Blob([s])}catch{(f=new(l.BlobBuilder||l.WebKitBlobBuilder||l.MozBlobBuilder||l.MSBlobBuilder)).append(s),f=f.getBlob()}var v=l.URL||l.webkitURL,p=v.createObjectURL(f),_=new l[o](p,c);return v.revokeObjectURL(p),_}catch{return new l[o]("data:application/javascript,".concat(encodeURIComponent(s)),c)}}catch{if(!h)throw Error("Inline worker is not supported");return new l[o](h,c)}}},2632:(a,s,o)=>{o.r(s),o.d(s,{default:()=>m});function c(d,u,b){Object.defineProperty(d,u,{writable:!0,enumerable:!0,configurable:!0,value:b})}Array(32);var h,l,f;class v{constructor(u){var b,y;this.timer=null,this.time=10,this.count=10,this.arr=[],this.time=(b=u.time)!=null?b:10,this.count=(y=u.count)!=null?y:10,u.host.startsWith("http://")||u.host.startsWith("https://")?this.url=u.host+"/logstores/"+u.logstore+"/track":this.url="https://"+u.project+"."+u.host+"/logstores/"+u.logstore+"/track",this.opt=u,u.installUnloadHook&&typeof u.installUnloadHook=="function"&&u.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(u=this.arr){const b={__logs__:u};return this.opt.tags&&(b.__tags__=this.opt.tags),this.opt.topic&&(b.__topic__=this.opt.topic),this.opt.source&&(b.__source__=this.opt.source),JSON.stringify(b)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const u=this.assemblePayload();this.opt.sendPayload(this.url,u)}}transString(u){let b={};for(let y in u)typeof u[y]=="object"?b[y]=JSON.stringify(u[y]):b[y]=String(u[y]);return b}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const u=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){u.sendImmediateInner()},1e3*this.time)}}send(u){const b=this.transString(u);this.arr.push(b),this.sendInner()}sendImmediate(u){const b=this.transString(u);this.arr.push(b),this.sendImmediateInner()}sendBatchLogs(u){const b=u.map(y=>this.transString(y));this.arr.push(...b),this.sendInner()}sendBatchLogsImmediate(u){const b=u.map(y=>this.transString(y));this.arr.push(...b),this.sendImmediateInner()}}function p(d,u){const b=new window.XMLHttpRequest;b.open("POST",`${d}?APIVersion=0.6.0`,!0),b.send(u)}function _(d,u){try{if(u.length>=32768)return void p(d,u);(function(b,y){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${b}?APIVersion=0.6.0`,y)})(d,u)||p(d,u)}catch(b){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
`+b),console.error("Failed log data:",d))}}class m extends v{constructor(u){super(Object.assign({},u,{installUnloadHook:b=>{window.addEventListener("beforeunload",()=>{b()})},sendPayload:(b,y)=>{_(b,y)}}))}}h=window,l="SLS_Tracker",f=m,c(h,l,f)},4198:a=>{a.exports=JSON.parse('{"name":"axios","version":"0.21.4","description":"Promise based HTTP client for the browser and node.js","main":"index.js","scripts":{"test":"grunt test","start":"node ./sandbox/server.js","build":"NODE_ENV=production grunt build","preversion":"npm test","version":"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json","postversion":"git push && git push --tags","examples":"node ./examples/server.js","coveralls":"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js","fix":"eslint --fix lib/**/*.js"},"repository":{"type":"git","url":"https://github.com/axios/axios.git"},"keywords":["xhr","http","ajax","promise","node"],"author":"Matt Zabriskie","license":"MIT","bugs":{"url":"https://github.com/axios/axios/issues"},"homepage":"https://axios-http.com","devDependencies":{"coveralls":"^3.0.0","es6-promise":"^4.2.4","grunt":"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1","karma":"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2","minimist":"^1.2.0","mocha":"^8.2.1","sinon":"^4.5.0","terser-webpack-plugin":"^4.2.3","typescript":"^4.0.5","url-search-params":"^0.10.0","webpack":"^4.44.2","webpack-dev-server":"^3.11.0"},"browser":{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},"jsdelivr":"dist/axios.min.js","unpkg":"dist/axios.min.js","typings":"./index.d.ts","dependencies":{"follow-redirects":"^1.14.0"},"bundlesize":[{"path":"./dist/axios.min.js","threshold":"5kB"}]}')}},n={};function r(a){var s=n[a];if(s!==void 0)return s.exports;var o=n[a]={exports:{}};return t[a].call(o.exports,o,o.exports,r),o.exports}return r.n=a=>{var s=a&&a.__esModule?()=>a.default:()=>a;return r.d(s,{a:s}),s},r.d=(a,s)=>{for(var o in s)r.o(s,o)&&!r.o(a,o)&&Object.defineProperty(a,o,{enumerable:!0,get:s[o]})},r.o=(a,s)=>Object.prototype.hasOwnProperty.call(a,s),r.r=a=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(a,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(a,"__esModule",{value:!0})},r(8156)})())})(Ll);var St=Ll.exports,Ol={exports:{}};(function(i){var e=Object.prototype.hasOwnProperty,t="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(t=!1));function r(c,h,l){this.fn=c,this.context=h,this.once=l||!1}function a(c,h,l,f,v){if(typeof l!="function")throw new TypeError("The listener must be a function");var p=new r(l,f||c,v),_=t?t+h:h;return c._events[_]?c._events[_].fn?c._events[_]=[c._events[_],p]:c._events[_].push(p):(c._events[_]=p,c._eventsCount++),c}function s(c,h){--c._eventsCount===0?c._events=new n:delete c._events[h]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var h=[],l,f;if(this._eventsCount===0)return h;for(f in l=this._events)e.call(l,f)&&h.push(t?f.slice(1):f);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(l)):h},o.prototype.listeners=function(h){var l=t?t+h:h,f=this._events[l];if(!f)return[];if(f.fn)return[f.fn];for(var v=0,p=f.length,_=new Array(p);v<p;v++)_[v]=f[v].fn;return _},o.prototype.listenerCount=function(h){var l=t?t+h:h,f=this._events[l];return f?f.fn?1:f.length:0},o.prototype.emit=function(h,l,f,v,p,_){var m=t?t+h:h;if(!this._events[m])return!1;var d=this._events[m],u=arguments.length,b,y;if(d.fn){switch(d.once&&this.removeListener(h,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,l),!0;case 3:return d.fn.call(d.context,l,f),!0;case 4:return d.fn.call(d.context,l,f,v),!0;case 5:return d.fn.call(d.context,l,f,v,p),!0;case 6:return d.fn.call(d.context,l,f,v,p,_),!0}for(y=1,b=new Array(u-1);y<u;y++)b[y-1]=arguments[y];d.fn.apply(d.context,b)}else{var g=d.length,S;for(y=0;y<g;y++)switch(d[y].once&&this.removeListener(h,d[y].fn,void 0,!0),u){case 1:d[y].fn.call(d[y].context);break;case 2:d[y].fn.call(d[y].context,l);break;case 3:d[y].fn.call(d[y].context,l,f);break;case 4:d[y].fn.call(d[y].context,l,f,v);break;default:if(!b)for(S=1,b=new Array(u-1);S<u;S++)b[S-1]=arguments[S];d[y].fn.apply(d[y].context,b)}}return!0},o.prototype.on=function(h,l,f){return a(this,h,l,f,!1)},o.prototype.once=function(h,l,f){return a(this,h,l,f,!0)},o.prototype.removeListener=function(h,l,f,v){var p=t?t+h:h;if(!this._events[p])return this;if(!l)return s(this,p),this;var _=this._events[p];if(_.fn)_.fn===l&&(!v||_.once)&&(!f||_.context===f)&&s(this,p);else{for(var m=0,d=[],u=_.length;m<u;m++)(_[m].fn!==l||v&&!_[m].once||f&&_[m].context!==f)&&d.push(_[m]);d.length?this._events[p]=d.length===1?d[0]:d:s(this,p)}return this},o.prototype.removeAllListeners=function(h){var l;return h?(l=t?t+h:h,this._events[l]&&s(this,l)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,i.exports=o})(Ol);var Sf=Ol.exports;const Kt=Un(Sf);var bf=Object.defineProperty,yf=Object.defineProperties,Ef=Object.getOwnPropertyDescriptors,Xo=Object.getOwnPropertySymbols,Rf=Object.getPrototypeOf,Nl=Object.prototype.hasOwnProperty,kl=Object.prototype.propertyIsEnumerable,Tf=Reflect.get,ia=(i,e,t)=>e in i?bf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ze=(i,e)=>{for(var t in e||(e={}))Nl.call(e,t)&&ia(i,t,e[t]);if(Xo)for(var t of Xo(e))kl.call(e,t)&&ia(i,t,e[t]);return i},Ki=(i,e)=>yf(i,Ef(e)),Bn=(i,e)=>{var t={};for(var n in i)Nl.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&Xo)for(var n of Xo(i))e.indexOf(n)<0&&kl.call(i,n)&&(t[n]=i[n]);return t},V=(i,e,t)=>(ia(i,typeof e!="symbol"?e+"":e,t),t),Ul=(i,e,t)=>Tf(Rf(i),t,e),le=(i,e,t)=>new Promise((n,r)=>{var a=c=>{try{o(t.next(c))}catch(h){r(h)}},s=c=>{try{o(t.throw(c))}catch(h){r(h)}},o=c=>c.done?n(c.value):Promise.resolve(c.value).then(a,s);o((t=t.apply(i,e)).next())}),Bl=(i=>(i.EnableNonOnePcDefaultJoinMode="h5_enable_non_one_pc_default_join_mode",i))(Bl||{}),Vn=(i=>(i.prod="rs.rtn.aliyuncs.com",i.pre="prs.rtn.aliyuncs.com",i))(Vn||{}),qi=(i=>(i.pre="pre",i.prod="prod",i))(qi||{}),ki=(i=>(i.AliRtcSdkCommunication="communication",i.AliRtcSdkInteractiveLive="interactive_live",i.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",i))(ki||{}),un=(i=>(i.AliRtcSdkInteractive="interactive",i.AliRtcSdkLive="live",i))(un||{}),_n=(i=>(i[i.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",i[i.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",i[i.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",i[i.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",i[i.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",i[i.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",i[i.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",i))(_n||{}),Bt=(i=>(i[i.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",i[i.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",i[i.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",i[i.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",i[i.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",i[i.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",i[i.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",i[i.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",i[i.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",i[i.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",i[i.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",i[i.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",i[i.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",i[i.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",i))(Bt||{}),at=(i=>(i[i.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",i[i.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",i[i.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",i[i.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",i[i.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",i[i.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",i))(at||{}),Sn=(i=>(i[i.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",i[i.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",i[i.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",i[i.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",i[i.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",i[i.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",i[i.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",i[i.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",i[i.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",i[i.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",i[i.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",i[i.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",i[i.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",i))(Sn||{}),na=(i=>(i[i.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",i[i.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",i[i.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",i))(na||{}),xr=(i=>(i[i.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",i[i.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",i[i.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",i))(xr||{}),ft=(i=>(i[i.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",i[i.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",i[i.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",i[i.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",i))(ft||{}),nt=(i=>(i[i.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",i[i.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",i[i.AliRtcStatePublishing=2]="AliRtcStatePublishing",i[i.AliRtcStatePublished=3]="AliRtcStatePublished",i[i.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",i))(nt||{}),ut=(i=>(i[i.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",i[i.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",i[i.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",i[i.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",i[i.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",i))(ut||{}),ti=(i=>(i[i.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",i[i.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",i[i.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",i))(ti||{}),mo=(i=>(i[i.CAMERA_INVALID=-1]="CAMERA_INVALID",i[i.CAMERA_REAR=0]="CAMERA_REAR",i[i.CAMERA_FRONT=1]="CAMERA_FRONT",i))(mo||{}),Ui=(i=>(i[i.AliRtcNetworkExcellent=0]="AliRtcNetworkExcellent",i[i.AliRtcNetworkGood=1]="AliRtcNetworkGood",i[i.AliRtcNetworkPoor=2]="AliRtcNetworkPoor",i[i.AliRtcNetworkBad=3]="AliRtcNetworkBad",i[i.AliRtcNetworkVeryBad=4]="AliRtcNetworkVeryBad",i[i.AliRtcNetworkDisconnected=5]="AliRtcNetworkDisconnected",i[i.AliRtcNetworkUnknown=6]="AliRtcNetworkUnknown",i))(Ui||{}),Nt=(i=>(i.PullStreamStats="remoteStat",i.RtsSubscribeExceeds="rtsSubscribeExceeds",i.UserJoined="userJoined",i.UserLeft="userLeft",i.Bye="bye",i.MuteAudio="muteAudio",i.UnmuteAudio="unmuteAudio",i.MuteVideo="muteVideo",i.UnmuteVideo="unmuteVideo",i.MuteScreen="muteScreen",i.UnmuteScreen="unmuteScreen",i.Error="error",i))(Nt||{}),ai=(i=>(i.Local="local-device-status-change",i.Remote="remote-device-status-change",i))(ai||{}),Me=(i=>(i.Audio="sophon_audio",i.VideoLarge="sophon_video_camera_large",i.VideoSmall="sophon_video_camera_small",i.Screen="sophon_video_screen_share",i.Data="sophon_data",i))(Me||{}),ra=(i=>(i.Audio="rts audio",i.VideoLarge="rts video",i))(ra||{}),Fn=(i=>(i.Add="add",i.Delete="delete",i.Replace="replace",i.Stop="stop",i.UnPublish="unpublish",i))(Fn||{}),go=(i=>(i[i.Camera=0]="Camera",i[i.Screen=1]="Screen",i[i.Image=2]="Image",i))(go||{}),$o=(i=>(i[i.Microphone=0]="Microphone",i[i.Screen=1]="Screen",i[i.Mixed=2]="Mixed",i))($o||{}),Ct=(i=>(i.InRoom="inRoom",i.Join="join",i.Publish="publish",i.User="user",i.Resume="resume",i.Retry="retry",i.Reconnect="reconnect",i))(Ct||{}),dn=(i=>(i[i.MANUAL=0]="MANUAL",i[i.JOIN_CHANNEL=1]="JOIN_CHANNEL",i[i.ROLE_CHANGE=2]="ROLE_CHANGE",i[i.RECONNECT=3]="RECONNECT",i))(dn||{}),Ne=(i=>(i[i.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",i[i.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",i[i.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",i[i.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",i[i.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",i[i.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",i[i.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",i[i.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",i[i.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",i[i.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",i[i.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",i[i.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",i[i.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",i[i.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",i[i.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",i[i.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",i[i.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",i[i.ERR_SPEAKER_NOT_AVAILABLE=17040400]="ERR_SPEAKER_NOT_AVAILABLE",i[i.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",i[i.ERR_CAMERA_AUTH_FAIL=17039621]="ERR_CAMERA_AUTH_FAIL",i[i.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",i[i.ERR_CAMERA_NOT_AVAILABLE=17039623]="ERR_CAMERA_NOT_AVAILABLE",i[i.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",i[i.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",i[i.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",i[i.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",i[i.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",i[i.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",i[i.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",i[i.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",i[i.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",i[i.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",i[i.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",i[i.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",i[i.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",i[i.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",i[i.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",i[i.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED",i[i.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED",i[i.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STREAM_FAILED",i[i.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",i[i.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",i[i.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",i[i.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",i[i.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED",i[i.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED",i[i.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED",i[i.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",i[i.ERR_SDK_SUBSCRIBE_DATA_FAILED=16844117]="ERR_SDK_SUBSCRIBE_DATA_FAILED",i[i.ERR_SDK_SUBSCRIBE_DATA_ERROR=16844118]="ERR_SDK_SUBSCRIBE_DATA_ERROR",i[i.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",i[i.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",i[i.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",i[i.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",i[i.ERR_INNER=-1]="ERR_INNER",i[i.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",i[i.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",i[i.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",i[i.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",i[i.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",i[i.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",i[i.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",i[i.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",i[i.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",i[i.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",i[i.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",i[i.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",i[i.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",i[i.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",i[i.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",i[i.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",i))(Ne||{});class Le extends Error{constructor(e,t,n){super(t),V(this,"_code"),V(this,"_extra"),this._code=e,this._extra=n}static fromRtsError(e){return e instanceof Le?e:new Le((e==null?void 0:e.errorCode)||-1,(e==null?void 0:e.message)||(e==null?void 0:e.errorCodeName)||"rts error",e)}static fromError(e,t=-1,n=""){return new Le(t,(e==null?void 0:e.message)||(e==null?void 0:e.reason)||n||"error",e)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}function Vl(i){var e;if(((e=i==null?void 0:i.nodeName)==null?void 0:e.toLowerCase())==="video")return i.setAttribute("playsinline",""),i;if(typeof i=="string"){let t=document.getElementById(i);if(t){if(t.nodeName.toLocaleLowerCase()==="video")return t.setAttribute("playsinline",""),t;throw new Le(Ne.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}throw new Le(Ne.ERR_INVALID_ARGUMENTS,"element not founded")}throw new Le(Ne.ERR_INVALID_ARGUMENTS,"element id should be string")}function oa(i){var e;const t=[];if(Array.isArray(i))i.forEach(n=>{try{t.push(Vl(n))}catch{}});else if(typeof i=="string"||((e=i==null?void 0:i.nodeName)==null?void 0:e.toLowerCase())==="video")try{t.push(Vl(i))}catch{}return t}function Hn(i){return new Promise(e=>setTimeout(e,i))}function Fl(i,e,t=1e3,n=r=>!0){return le(this,null,function*(){let r=0;for(;r<e;)try{return yield i(r)}catch(a){if(r++,r>=e||!n(a))throw a||void 0;yield new Promise(s=>setTimeout(s,t))}})}function sa(i,e){let t=e;return typeof window.__ali_prefer_media_server=="string"&&window.__ali_prefer_media_server!==""&&(t=window.__ali_prefer_media_server),t?`${i}&ali_prefer_media_server=${t}`:i}function rr(i,e){var t;try{const{archCfgs:n}=i;if(!n||!Array.isArray(n))return;const r=n.find(a=>a.arch==="grtn");return r?(t=r.user_specified)==null?void 0:t[e]:void 0}catch{return}}function Ir(i,e){try{const{config:t}=i;return t?t==null?void 0:t[e]:void 0}catch{return}}function Af(i){const e=i.replace(/(a=rtpmap:(\d+).*\r\n)/g,`$1a=rtcp-fb:$2 rrtr\r
`);return e.includes(`a=rtcp-rsize\r
`)?e:e.replace(/(m=(video|audio).*\r\n)/g,`$1a=rtcp-rsize\r
`)}function Hl(i,e){return i>50||e>500?Ui.AliRtcNetworkVeryBad:i>30||e>350?Ui.AliRtcNetworkBad:i>20||e>200?Ui.AliRtcNetworkPoor:i>10||e>100?Ui.AliRtcNetworkGood:i>=0||e>=0?Ui.AliRtcNetworkExcellent:Ui.AliRtcNetworkUnknown}function Gl(i){return!!i&&[Me.VideoLarge,Me.VideoSmall,Me.Screen].includes(i)}function zl(i){return i===Me.Audio}for(var aa,ii=[],ca=0;ca<256;++ca)ii.push((ca+256).toString(16).slice(1));var Cf=new Uint8Array(16);function wf(){if(!aa&&!(aa=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return aa(Cf)}const Wl={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Ai(i,e,t){if(Wl.randomUUID&&!e&&!i)return Wl.randomUUID();var n=(i=i||{}).random||(i.rng||wf)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,function(r,a=0){return(ii[r[a+0]]+ii[r[a+1]]+ii[r[a+2]]+ii[r[a+3]]+"-"+ii[r[a+4]]+ii[r[a+5]]+"-"+ii[r[a+6]]+ii[r[a+7]]+"-"+ii[r[a+8]]+ii[r[a+9]]+"-"+ii[r[a+10]]+ii[r[a+11]]+ii[r[a+12]]+ii[r[a+13]]+ii[r[a+14]]+ii[r[a+15]]).toLowerCase()}(n)}const vo="7.2.4";class kt{static getVersionNumber(){let e=vo.split("."),t="";return e.forEach(n=>{n.length===1?t+="0"+n:t+=n}),parseInt(t)}static queryingParam(e){let t=[];if(e)for(let n in e)t.push(n+"="+e[n]);return t.join("&")}static getQueryParams(e){const t=window.location.search.substring(1).split("&");for(let n=0;n<t.length;n++){const r=t[n].split("=");if(decodeURIComponent(r[0])===e)return decodeURIComponent(r[1])}}static createCallid(e=""){const t=Ai();return e&&t&&t.length>e.length?`${e}${t.substring(e.length)}`:t}static checkSubOptionsValid(e){if(e){const{audio:t,video:n,screen:r}=e;if(t===!1&&n===!1&&r===!1)return!1}return!0}static isNetworkAvailable(){return le(this,null,function*(){const e=Vn.prod,{onLine:t}=navigator;if(!t)return!1;try{return yield fetch(`https://${e}/roomserver/v1/ws/version`),!0}catch{return!1}})}static toString(e){let t;if(e instanceof Error)t=e.message;else if(typeof e=="string")t=e;else try{t=JSON.stringify(e)}catch{t="undefined"}return t}static paramArrayToString(e){let t="";for(let n=0;n<e.length;n++)t!==""&&(t+=" "),t+=kt.toString(e[n]);return t}static removeQueryString(e){if(!e)return e;let t=e.indexOf("?");return t>0?e.substring(0,t):e}}function Mf(i,e,t){Object.defineProperty(i,e,{writable:!0,enumerable:!0,configurable:!0,value:t})}function jl(i,e,t,n){Mf(i,e,t)}Array(32);var Ko=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function xf(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}function If(i){if(i.__esModule)return i;var e=i.default;if(typeof e=="function"){var t=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(i).forEach(function(n){var r=Object.getOwnPropertyDescriptor(i,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return i[n]}})}),t}var Xl={exports:{}},$l={exports:{}};const Pf=If(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var Kl;function gt(){return Kl||(Kl=1,$l.exports=function(){var i=i||function(e,t){var n;if(typeof window<"u"&&window.crypto&&(n=window.crypto),typeof self<"u"&&self.crypto&&(n=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(n=globalThis.crypto),!n&&typeof window<"u"&&window.msCrypto&&(n=window.msCrypto),!n&&Ko!==void 0&&Ko.crypto&&(n=Ko.crypto),!n)try{n=Pf}catch{}var r=function(){if(n){if(typeof n.getRandomValues=="function")try{return n.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof n.randomBytes=="function")try{return n.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},a=Object.create||function(){function d(){}return function(u){var b;return d.prototype=u,b=new d,d.prototype=null,b}}(),s={},o=s.lib={},c=o.Base={extend:function(d){var u=a(this);return d&&u.mixIn(d),u.hasOwnProperty("init")&&this.init!==u.init||(u.init=function(){u.$super.init.apply(this,arguments)}),u.init.prototype=u,u.$super=this,u},create:function(){var d=this.extend();return d.init.apply(d,arguments),d},init:function(){},mixIn:function(d){for(var u in d)d.hasOwnProperty(u)&&(this[u]=d[u]);d.hasOwnProperty("toString")&&(this.toString=d.toString)},clone:function(){return this.init.prototype.extend(this)}},h=o.WordArray=c.extend({init:function(d,u){d=this.words=d||[],this.sigBytes=u!=t?u:4*d.length},toString:function(d){return(d||f).stringify(this)},concat:function(d){var u=this.words,b=d.words,y=this.sigBytes,g=d.sigBytes;if(this.clamp(),y%4)for(var S=0;S<g;S++){var R=b[S>>>2]>>>24-S%4*8&255;u[y+S>>>2]|=R<<24-(y+S)%4*8}else for(var E=0;E<g;E+=4)u[y+E>>>2]=b[E>>>2];return this.sigBytes+=g,this},clamp:function(){var d=this.words,u=this.sigBytes;d[u>>>2]&=4294967295<<32-u%4*8,d.length=e.ceil(u/4)},clone:function(){var d=c.clone.call(this);return d.words=this.words.slice(0),d},random:function(d){for(var u=[],b=0;b<d;b+=4)u.push(r());return new h.init(u,d)}}),l=s.enc={},f=l.Hex={stringify:function(d){for(var u=d.words,b=d.sigBytes,y=[],g=0;g<b;g++){var S=u[g>>>2]>>>24-g%4*8&255;y.push((S>>>4).toString(16)),y.push((15&S).toString(16))}return y.join("")},parse:function(d){for(var u=d.length,b=[],y=0;y<u;y+=2)b[y>>>3]|=parseInt(d.substr(y,2),16)<<24-y%8*4;return new h.init(b,u/2)}},v=l.Latin1={stringify:function(d){for(var u=d.words,b=d.sigBytes,y=[],g=0;g<b;g++){var S=u[g>>>2]>>>24-g%4*8&255;y.push(String.fromCharCode(S))}return y.join("")},parse:function(d){for(var u=d.length,b=[],y=0;y<u;y++)b[y>>>2]|=(255&d.charCodeAt(y))<<24-y%4*8;return new h.init(b,u)}},p=l.Utf8={stringify:function(d){try{return decodeURIComponent(escape(v.stringify(d)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(d){return v.parse(unescape(encodeURIComponent(d)))}},_=o.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new h.init,this._nDataBytes=0},_append:function(d){typeof d=="string"&&(d=p.parse(d)),this._data.concat(d),this._nDataBytes+=d.sigBytes},_process:function(d){var u,b=this._data,y=b.words,g=b.sigBytes,S=this.blockSize,R=g/(4*S),E=(R=d?e.ceil(R):e.max((0|R)-this._minBufferSize,0))*S,I=e.min(4*E,g);if(E){for(var C=0;C<E;C+=S)this._doProcessBlock(y,C);u=y.splice(0,E),b.sigBytes-=I}return new h.init(u,I)},clone:function(){var d=c.clone.call(this);return d._data=this._data.clone(),d},_minBufferSize:0});o.Hasher=_.extend({cfg:c.extend(),init:function(d){this.cfg=this.cfg.extend(d),this.reset()},reset:function(){_.reset.call(this),this._doReset()},update:function(d){return this._append(d),this._process(),this},finalize:function(d){return d&&this._append(d),this._doFinalize()},blockSize:16,_createHelper:function(d){return function(u,b){return new d.init(b).finalize(u)}},_createHmacHelper:function(d){return function(u,b){return new m.HMAC.init(d,b).finalize(u)}}});var m=s.algo={};return s}(Math);return i}()),$l.exports}var ql,Yl={exports:{}};function qo(){return ql||(ql=1,Yl.exports=function(i){return n=(t=i).lib,r=n.Base,a=n.WordArray,(s=t.x64={}).Word=r.extend({init:function(o,c){this.high=o,this.low=c}}),s.WordArray=r.extend({init:function(o,c){o=this.words=o||[],this.sigBytes=c!=e?c:8*o.length},toX32:function(){for(var o=this.words,c=o.length,h=[],l=0;l<c;l++){var f=o[l];h.push(f.high),h.push(f.low)}return a.create(h,this.sigBytes)},clone:function(){for(var o=r.clone.call(this),c=o.words=this.words.slice(0),h=c.length,l=0;l<h;l++)c[l]=c[l].clone();return o}}),i;var e,t,n,r,a,s}(gt())),Yl.exports}var Jl,Ql={exports:{}};function Df(){return Jl||(Jl=1,Ql.exports=function(i){return function(){if(typeof ArrayBuffer=="function"){var e=i.lib.WordArray,t=e.init,n=e.init=function(r){if(r instanceof ArrayBuffer&&(r=new Uint8Array(r)),(r instanceof Int8Array||typeof Uint8ClampedArray<"u"&&r instanceof Uint8ClampedArray||r instanceof Int16Array||r instanceof Uint16Array||r instanceof Int32Array||r instanceof Uint32Array||r instanceof Float32Array||r instanceof Float64Array)&&(r=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),r instanceof Uint8Array){for(var a=r.byteLength,s=[],o=0;o<a;o++)s[o>>>2]|=r[o]<<24-o%4*8;t.call(this,s,a)}else t.apply(this,arguments)};n.prototype=e}}(),i.lib.WordArray}(gt())),Ql.exports}var Zl,eu={exports:{}};function Lf(){return Zl||(Zl=1,eu.exports=function(i){return function(){var e=i,t=e.lib.WordArray,n=e.enc;function r(a){return a<<8&4278255360|a>>>8&16711935}n.Utf16=n.Utf16BE={stringify:function(a){for(var s=a.words,o=a.sigBytes,c=[],h=0;h<o;h+=2){var l=s[h>>>2]>>>16-h%4*8&65535;c.push(String.fromCharCode(l))}return c.join("")},parse:function(a){for(var s=a.length,o=[],c=0;c<s;c++)o[c>>>1]|=a.charCodeAt(c)<<16-c%2*16;return t.create(o,2*s)}},n.Utf16LE={stringify:function(a){for(var s=a.words,o=a.sigBytes,c=[],h=0;h<o;h+=2){var l=r(s[h>>>2]>>>16-h%4*8&65535);c.push(String.fromCharCode(l))}return c.join("")},parse:function(a){for(var s=a.length,o=[],c=0;c<s;c++)o[c>>>1]|=r(a.charCodeAt(c)<<16-c%2*16);return t.create(o,2*s)}}}(),i.enc.Utf16}(gt())),eu.exports}var tu,iu={exports:{}};function or(){return tu||(tu=1,iu.exports=function(i){return function(){var e=i,t=e.lib.WordArray;function n(r,a,s){for(var o=[],c=0,h=0;h<a;h++)if(h%4){var l=s[r.charCodeAt(h-1)]<<h%4*2|s[r.charCodeAt(h)]>>>6-h%4*2;o[c>>>2]|=l<<24-c%4*8,c++}return t.create(o,c)}e.enc.Base64={stringify:function(r){var a=r.words,s=r.sigBytes,o=this._map;r.clamp();for(var c=[],h=0;h<s;h+=3)for(var l=(a[h>>>2]>>>24-h%4*8&255)<<16|(a[h+1>>>2]>>>24-(h+1)%4*8&255)<<8|a[h+2>>>2]>>>24-(h+2)%4*8&255,f=0;f<4&&h+.75*f<s;f++)c.push(o.charAt(l>>>6*(3-f)&63));var v=o.charAt(64);if(v)for(;c.length%4;)c.push(v);return c.join("")},parse:function(r){var a=r.length,s=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var c=0;c<s.length;c++)o[s.charCodeAt(c)]=c}var h=s.charAt(64);if(h){var l=r.indexOf(h);l!==-1&&(a=l)}return n(r,a,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),i.enc.Base64}(gt())),iu.exports}var nu,ru={exports:{}};function Of(){return nu||(nu=1,ru.exports=function(i){return function(){var e=i,t=e.lib.WordArray;function n(r,a,s){for(var o=[],c=0,h=0;h<a;h++)if(h%4){var l=s[r.charCodeAt(h-1)]<<h%4*2|s[r.charCodeAt(h)]>>>6-h%4*2;o[c>>>2]|=l<<24-c%4*8,c++}return t.create(o,c)}e.enc.Base64url={stringify:function(r,a){a===void 0&&(a=!0);var s=r.words,o=r.sigBytes,c=a?this._safe_map:this._map;r.clamp();for(var h=[],l=0;l<o;l+=3)for(var f=(s[l>>>2]>>>24-l%4*8&255)<<16|(s[l+1>>>2]>>>24-(l+1)%4*8&255)<<8|s[l+2>>>2]>>>24-(l+2)%4*8&255,v=0;v<4&&l+.75*v<o;v++)h.push(c.charAt(f>>>6*(3-v)&63));var p=c.charAt(64);if(p)for(;h.length%4;)h.push(p);return h.join("")},parse:function(r,a){a===void 0&&(a=!0);var s=r.length,o=a?this._safe_map:this._map,c=this._reverseMap;if(!c){c=this._reverseMap=[];for(var h=0;h<o.length;h++)c[o.charCodeAt(h)]=h}var l=o.charAt(64);if(l){var f=r.indexOf(l);f!==-1&&(s=f)}return n(r,s,c)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"}}(),i.enc.Base64url}(gt())),ru.exports}var ou,su={exports:{}};function sr(){return ou||(ou=1,su.exports=function(i){return function(e){var t=i,n=t.lib,r=n.WordArray,a=n.Hasher,s=t.algo,o=[];(function(){for(var p=0;p<64;p++)o[p]=4294967296*e.abs(e.sin(p+1))|0})();var c=s.MD5=a.extend({_doReset:function(){this._hash=new r.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(p,_){for(var m=0;m<16;m++){var d=_+m,u=p[d];p[d]=16711935&(u<<8|u>>>24)|4278255360&(u<<24|u>>>8)}var b=this._hash.words,y=p[_+0],g=p[_+1],S=p[_+2],R=p[_+3],E=p[_+4],I=p[_+5],C=p[_+6],A=p[_+7],w=p[_+8],N=p[_+9],M=p[_+10],D=p[_+11],L=p[_+12],P=p[_+13],x=p[_+14],T=p[_+15],O=b[0],k=b[1],H=b[2],U=b[3];O=h(O,k,H,U,y,7,o[0]),U=h(U,O,k,H,g,12,o[1]),H=h(H,U,O,k,S,17,o[2]),k=h(k,H,U,O,R,22,o[3]),O=h(O,k,H,U,E,7,o[4]),U=h(U,O,k,H,I,12,o[5]),H=h(H,U,O,k,C,17,o[6]),k=h(k,H,U,O,A,22,o[7]),O=h(O,k,H,U,w,7,o[8]),U=h(U,O,k,H,N,12,o[9]),H=h(H,U,O,k,M,17,o[10]),k=h(k,H,U,O,D,22,o[11]),O=h(O,k,H,U,L,7,o[12]),U=h(U,O,k,H,P,12,o[13]),H=h(H,U,O,k,x,17,o[14]),O=l(O,k=h(k,H,U,O,T,22,o[15]),H,U,g,5,o[16]),U=l(U,O,k,H,C,9,o[17]),H=l(H,U,O,k,D,14,o[18]),k=l(k,H,U,O,y,20,o[19]),O=l(O,k,H,U,I,5,o[20]),U=l(U,O,k,H,M,9,o[21]),H=l(H,U,O,k,T,14,o[22]),k=l(k,H,U,O,E,20,o[23]),O=l(O,k,H,U,N,5,o[24]),U=l(U,O,k,H,x,9,o[25]),H=l(H,U,O,k,R,14,o[26]),k=l(k,H,U,O,w,20,o[27]),O=l(O,k,H,U,P,5,o[28]),U=l(U,O,k,H,S,9,o[29]),H=l(H,U,O,k,A,14,o[30]),O=f(O,k=l(k,H,U,O,L,20,o[31]),H,U,I,4,o[32]),U=f(U,O,k,H,w,11,o[33]),H=f(H,U,O,k,D,16,o[34]),k=f(k,H,U,O,x,23,o[35]),O=f(O,k,H,U,g,4,o[36]),U=f(U,O,k,H,E,11,o[37]),H=f(H,U,O,k,A,16,o[38]),k=f(k,H,U,O,M,23,o[39]),O=f(O,k,H,U,P,4,o[40]),U=f(U,O,k,H,y,11,o[41]),H=f(H,U,O,k,R,16,o[42]),k=f(k,H,U,O,C,23,o[43]),O=f(O,k,H,U,N,4,o[44]),U=f(U,O,k,H,L,11,o[45]),H=f(H,U,O,k,T,16,o[46]),O=v(O,k=f(k,H,U,O,S,23,o[47]),H,U,y,6,o[48]),U=v(U,O,k,H,A,10,o[49]),H=v(H,U,O,k,x,15,o[50]),k=v(k,H,U,O,I,21,o[51]),O=v(O,k,H,U,L,6,o[52]),U=v(U,O,k,H,R,10,o[53]),H=v(H,U,O,k,M,15,o[54]),k=v(k,H,U,O,g,21,o[55]),O=v(O,k,H,U,w,6,o[56]),U=v(U,O,k,H,T,10,o[57]),H=v(H,U,O,k,C,15,o[58]),k=v(k,H,U,O,P,21,o[59]),O=v(O,k,H,U,E,6,o[60]),U=v(U,O,k,H,D,10,o[61]),H=v(H,U,O,k,S,15,o[62]),k=v(k,H,U,O,N,21,o[63]),b[0]=b[0]+O|0,b[1]=b[1]+k|0,b[2]=b[2]+H|0,b[3]=b[3]+U|0},_doFinalize:function(){var p=this._data,_=p.words,m=8*this._nDataBytes,d=8*p.sigBytes;_[d>>>5]|=128<<24-d%32;var u=e.floor(m/4294967296),b=m;_[15+(d+64>>>9<<4)]=16711935&(u<<8|u>>>24)|4278255360&(u<<24|u>>>8),_[14+(d+64>>>9<<4)]=16711935&(b<<8|b>>>24)|4278255360&(b<<24|b>>>8),p.sigBytes=4*(_.length+1),this._process();for(var y=this._hash,g=y.words,S=0;S<4;S++){var R=g[S];g[S]=16711935&(R<<8|R>>>24)|4278255360&(R<<24|R>>>8)}return y},clone:function(){var p=a.clone.call(this);return p._hash=this._hash.clone(),p}});function h(p,_,m,d,u,b,y){var g=p+(_&m|~_&d)+u+y;return(g<<b|g>>>32-b)+_}function l(p,_,m,d,u,b,y){var g=p+(_&d|m&~d)+u+y;return(g<<b|g>>>32-b)+_}function f(p,_,m,d,u,b,y){var g=p+(_^m^d)+u+y;return(g<<b|g>>>32-b)+_}function v(p,_,m,d,u,b,y){var g=p+(m^(_|~d))+u+y;return(g<<b|g>>>32-b)+_}t.MD5=a._createHelper(c),t.HmacMD5=a._createHmacHelper(c)}(Math),i.MD5}(gt())),su.exports}var au,cu={exports:{}};function lu(){return au||(au=1,cu.exports=function(i){return t=(e=i).lib,n=t.WordArray,r=t.Hasher,a=e.algo,s=[],o=a.SHA1=r.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(c,h){for(var l=this._hash.words,f=l[0],v=l[1],p=l[2],_=l[3],m=l[4],d=0;d<80;d++){if(d<16)s[d]=0|c[h+d];else{var u=s[d-3]^s[d-8]^s[d-14]^s[d-16];s[d]=u<<1|u>>>31}var b=(f<<5|f>>>27)+m+s[d];b+=d<20?1518500249+(v&p|~v&_):d<40?1859775393+(v^p^_):d<60?(v&p|v&_|p&_)-1894007588:(v^p^_)-899497514,m=_,_=p,p=v<<30|v>>>2,v=f,f=b}l[0]=l[0]+f|0,l[1]=l[1]+v|0,l[2]=l[2]+p|0,l[3]=l[3]+_|0,l[4]=l[4]+m|0},_doFinalize:function(){var c=this._data,h=c.words,l=8*this._nDataBytes,f=8*c.sigBytes;return h[f>>>5]|=128<<24-f%32,h[14+(f+64>>>9<<4)]=Math.floor(l/4294967296),h[15+(f+64>>>9<<4)]=l,c.sigBytes=4*h.length,this._process(),this._hash},clone:function(){var c=r.clone.call(this);return c._hash=this._hash.clone(),c}}),e.SHA1=r._createHelper(o),e.HmacSHA1=r._createHmacHelper(o),i.SHA1;var e,t,n,r,a,s,o}(gt())),cu.exports}var uu,du={exports:{}};function la(){return uu||(uu=1,du.exports=function(i){return function(e){var t=i,n=t.lib,r=n.WordArray,a=n.Hasher,s=t.algo,o=[],c=[];(function(){function f(m){for(var d=e.sqrt(m),u=2;u<=d;u++)if(!(m%u))return!1;return!0}function v(m){return 4294967296*(m-(0|m))|0}for(var p=2,_=0;_<64;)f(p)&&(_<8&&(o[_]=v(e.pow(p,.5))),c[_]=v(e.pow(p,1/3)),_++),p++})();var h=[],l=s.SHA256=a.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(f,v){for(var p=this._hash.words,_=p[0],m=p[1],d=p[2],u=p[3],b=p[4],y=p[5],g=p[6],S=p[7],R=0;R<64;R++){if(R<16)h[R]=0|f[v+R];else{var E=h[R-15],I=(E<<25|E>>>7)^(E<<14|E>>>18)^E>>>3,C=h[R-2],A=(C<<15|C>>>17)^(C<<13|C>>>19)^C>>>10;h[R]=I+h[R-7]+A+h[R-16]}var w=_&m^_&d^m&d,N=(_<<30|_>>>2)^(_<<19|_>>>13)^(_<<10|_>>>22),M=S+((b<<26|b>>>6)^(b<<21|b>>>11)^(b<<7|b>>>25))+(b&y^~b&g)+c[R]+h[R];S=g,g=y,y=b,b=u+M|0,u=d,d=m,m=_,_=M+(N+w)|0}p[0]=p[0]+_|0,p[1]=p[1]+m|0,p[2]=p[2]+d|0,p[3]=p[3]+u|0,p[4]=p[4]+b|0,p[5]=p[5]+y|0,p[6]=p[6]+g|0,p[7]=p[7]+S|0},_doFinalize:function(){var f=this._data,v=f.words,p=8*this._nDataBytes,_=8*f.sigBytes;return v[_>>>5]|=128<<24-_%32,v[14+(_+64>>>9<<4)]=e.floor(p/4294967296),v[15+(_+64>>>9<<4)]=p,f.sigBytes=4*v.length,this._process(),this._hash},clone:function(){var f=a.clone.call(this);return f._hash=this._hash.clone(),f}});t.SHA256=a._createHelper(l),t.HmacSHA256=a._createHmacHelper(l)}(Math),i.SHA256}(gt())),du.exports}var hu,pu,fu={exports:{}};function mu(){return pu||(pu=1,fu.exports=function(i){return function(){var e=i,t=e.lib.Hasher,n=e.x64,r=n.Word,a=n.WordArray,s=e.algo;function o(){return r.create.apply(r,arguments)}var c=[o(1116352408,3609767458),o(1899447441,602891725),o(3049323471,3964484399),o(3921009573,2173295548),o(961987163,4081628472),o(1508970993,3053834265),o(2453635748,2937671579),o(2870763221,3664609560),o(3624381080,2734883394),o(310598401,1164996542),o(607225278,1323610764),o(1426881987,3590304994),o(1925078388,4068182383),o(2162078206,991336113),o(2614888103,633803317),o(3248222580,3479774868),o(3835390401,2666613458),o(4022224774,944711139),o(264347078,2341262773),o(604807628,2007800933),o(770255983,1495990901),o(1249150122,1856431235),o(1555081692,3175218132),o(1996064986,2198950837),o(2554220882,3999719339),o(2821834349,766784016),o(2952996808,2566594879),o(3210313671,3203337956),o(3336571891,1034457026),o(3584528711,2466948901),o(113926993,3758326383),o(338241895,168717936),o(666307205,1188179964),o(773529912,1546045734),o(1294757372,1522805485),o(1396182291,2643833823),o(1695183700,2343527390),o(1986661051,1014477480),o(2177026350,1206759142),o(2456956037,344077627),o(2730485921,1290863460),o(2820302411,3158454273),o(3259730800,3505952657),o(3345764771,106217008),o(3516065817,3606008344),o(3600352804,1432725776),o(4094571909,1467031594),o(275423344,851169720),o(430227734,3100823752),o(506948616,1363258195),o(659060556,3750685593),o(883997877,3785050280),o(958139571,3318307427),o(1322822218,3812723403),o(1537002063,2003034995),o(1747873779,3602036899),o(1955562222,1575990012),o(2024104815,1125592928),o(2227730452,2716904306),o(2361852424,442776044),o(2428436474,593698344),o(2756734187,3733110249),o(3204031479,2999351573),o(3329325298,3815920427),o(3391569614,3928383900),o(3515267271,566280711),o(3940187606,3454069534),o(4118630271,4000239992),o(116418474,1914138554),o(174292421,2731055270),o(289380356,3203993006),o(460393269,320620315),o(685471733,587496836),o(852142971,1086792851),o(1017036298,365543100),o(1126000580,2618297676),o(1288033470,3409855158),o(1501505948,4234509866),o(1607167915,987167468),o(1816402316,1246189591)],h=[];(function(){for(var f=0;f<80;f++)h[f]=o()})();var l=s.SHA512=t.extend({_doReset:function(){this._hash=new a.init([new r.init(1779033703,4089235720),new r.init(3144134277,2227873595),new r.init(1013904242,4271175723),new r.init(2773480762,1595750129),new r.init(1359893119,2917565137),new r.init(2600822924,725511199),new r.init(528734635,4215389547),new r.init(1541459225,327033209)])},_doProcessBlock:function(f,v){for(var p=this._hash.words,_=p[0],m=p[1],d=p[2],u=p[3],b=p[4],y=p[5],g=p[6],S=p[7],R=_.high,E=_.low,I=m.high,C=m.low,A=d.high,w=d.low,N=u.high,M=u.low,D=b.high,L=b.low,P=y.high,x=y.low,T=g.high,O=g.low,k=S.high,H=S.low,U=R,ee=E,W=I,$=C,B=A,F=w,G=N,q=M,X=D,J=L,se=P,ce=x,Y=T,fe=O,he=k,pe=H,ue=0;ue<80;ue++){var Te,be,Z=h[ue];if(ue<16)be=Z.high=0|f[v+2*ue],Te=Z.low=0|f[v+2*ue+1];else{var K=h[ue-15],re=K.high,de=K.low,ye=(re>>>1|de<<31)^(re>>>8|de<<24)^re>>>7,Ee=(de>>>1|re<<31)^(de>>>8|re<<24)^(de>>>7|re<<25),Ve=h[ue-2],De=Ve.high,Ue=Ve.low,Ye=(De>>>19|Ue<<13)^(De<<3|Ue>>>29)^De>>>6,Ie=(Ue>>>19|De<<13)^(Ue<<3|De>>>29)^(Ue>>>6|De<<26),Oe=h[ue-7],$e=Oe.high,Ke=Oe.low,Fe=h[ue-16],st=Fe.high,tt=Fe.low;be=(be=(be=ye+$e+((Te=Ee+Ke)>>>0<Ee>>>0?1:0))+Ye+((Te+=Ie)>>>0<Ie>>>0?1:0))+st+((Te+=tt)>>>0<tt>>>0?1:0),Z.high=be,Z.low=Te}var z,j=X&se^~X&Y,te=J&ce^~J&fe,Q=U&W^U&B^W&B,ne=ee&$^ee&F^$&F,ae=(U>>>28|ee<<4)^(U<<30|ee>>>2)^(U<<25|ee>>>7),oe=(ee>>>28|U<<4)^(ee<<30|U>>>2)^(ee<<25|U>>>7),Se=(X>>>14|J<<18)^(X>>>18|J<<14)^(X<<23|J>>>9),_e=(J>>>14|X<<18)^(J>>>18|X<<14)^(J<<23|X>>>9),xe=c[ue],Pe=xe.high,He=xe.low,it=he+Se+((z=pe+_e)>>>0<pe>>>0?1:0),pi=oe+ne;he=Y,pe=fe,Y=se,fe=ce,se=X,ce=J,X=G+(it=(it=(it=it+j+((z+=te)>>>0<te>>>0?1:0))+Pe+((z+=He)>>>0<He>>>0?1:0))+be+((z+=Te)>>>0<Te>>>0?1:0))+((J=q+z|0)>>>0<q>>>0?1:0)|0,G=B,q=F,B=W,F=$,W=U,$=ee,U=it+(ae+Q+(pi>>>0<oe>>>0?1:0))+((ee=z+pi|0)>>>0<z>>>0?1:0)|0}E=_.low=E+ee,_.high=R+U+(E>>>0<ee>>>0?1:0),C=m.low=C+$,m.high=I+W+(C>>>0<$>>>0?1:0),w=d.low=w+F,d.high=A+B+(w>>>0<F>>>0?1:0),M=u.low=M+q,u.high=N+G+(M>>>0<q>>>0?1:0),L=b.low=L+J,b.high=D+X+(L>>>0<J>>>0?1:0),x=y.low=x+ce,y.high=P+se+(x>>>0<ce>>>0?1:0),O=g.low=O+fe,g.high=T+Y+(O>>>0<fe>>>0?1:0),H=S.low=H+pe,S.high=k+he+(H>>>0<pe>>>0?1:0)},_doFinalize:function(){var f=this._data,v=f.words,p=8*this._nDataBytes,_=8*f.sigBytes;return v[_>>>5]|=128<<24-_%32,v[30+(_+128>>>10<<5)]=Math.floor(p/4294967296),v[31+(_+128>>>10<<5)]=p,f.sigBytes=4*v.length,this._process(),this._hash.toX32()},clone:function(){var f=t.clone.call(this);return f._hash=this._hash.clone(),f},blockSize:32});e.SHA512=t._createHelper(l),e.HmacSHA512=t._createHmacHelper(l)}(),i.SHA512}(gt(),qo())),fu.exports}var gu,vu,_u={exports:{}};function Nf(){return vu||(vu=1,_u.exports=function(i){return function(e){var t=i,n=t.lib,r=n.WordArray,a=n.Hasher,s=t.x64.Word,o=t.algo,c=[],h=[],l=[];(function(){for(var p=1,_=0,m=0;m<24;m++){c[p+5*_]=(m+1)*(m+2)/2%64;var d=(2*p+3*_)%5;p=_%5,_=d}for(p=0;p<5;p++)for(_=0;_<5;_++)h[p+5*_]=_+(2*p+3*_)%5*5;for(var u=1,b=0;b<24;b++){for(var y=0,g=0,S=0;S<7;S++){if(1&u){var R=(1<<S)-1;R<32?g^=1<<R:y^=1<<R-32}128&u?u=u<<1^113:u<<=1}l[b]=s.create(y,g)}})();var f=[];(function(){for(var p=0;p<25;p++)f[p]=s.create()})();var v=o.SHA3=a.extend({cfg:a.cfg.extend({outputLength:512}),_doReset:function(){for(var p=this._state=[],_=0;_<25;_++)p[_]=new s.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(p,_){for(var m=this._state,d=this.blockSize/2,u=0;u<d;u++){var b=p[_+2*u],y=p[_+2*u+1];b=16711935&(b<<8|b>>>24)|4278255360&(b<<24|b>>>8),y=16711935&(y<<8|y>>>24)|4278255360&(y<<24|y>>>8),(H=m[u]).high^=y,H.low^=b}for(var g=0;g<24;g++){for(var S=0;S<5;S++){for(var R=0,E=0,I=0;I<5;I++)R^=(H=m[S+5*I]).high,E^=H.low;var C=f[S];C.high=R,C.low=E}for(S=0;S<5;S++){var A=f[(S+4)%5],w=f[(S+1)%5],N=w.high,M=w.low;for(R=A.high^(N<<1|M>>>31),E=A.low^(M<<1|N>>>31),I=0;I<5;I++)(H=m[S+5*I]).high^=R,H.low^=E}for(var D=1;D<25;D++){var L=(H=m[D]).high,P=H.low,x=c[D];x<32?(R=L<<x|P>>>32-x,E=P<<x|L>>>32-x):(R=P<<x-32|L>>>64-x,E=L<<x-32|P>>>64-x);var T=f[h[D]];T.high=R,T.low=E}var O=f[0],k=m[0];for(O.high=k.high,O.low=k.low,S=0;S<5;S++)for(I=0;I<5;I++){var H=m[D=S+5*I],U=f[D],ee=f[(S+1)%5+5*I],W=f[(S+2)%5+5*I];H.high=U.high^~ee.high&W.high,H.low=U.low^~ee.low&W.low}H=m[0];var $=l[g];H.high^=$.high,H.low^=$.low}},_doFinalize:function(){var p=this._data,_=p.words;this._nDataBytes;var m=8*p.sigBytes,d=32*this.blockSize;_[m>>>5]|=1<<24-m%32,_[(e.ceil((m+1)/d)*d>>>5)-1]|=128,p.sigBytes=4*_.length,this._process();for(var u=this._state,b=this.cfg.outputLength/8,y=b/8,g=[],S=0;S<y;S++){var R=u[S],E=R.high,I=R.low;E=16711935&(E<<8|E>>>24)|4278255360&(E<<24|E>>>8),I=16711935&(I<<8|I>>>24)|4278255360&(I<<24|I>>>8),g.push(I),g.push(E)}return new r.init(g,b)},clone:function(){for(var p=a.clone.call(this),_=p._state=this._state.slice(0),m=0;m<25;m++)_[m]=_[m].clone();return p}});t.SHA3=a._createHelper(v),t.HmacSHA3=a._createHmacHelper(v)}(Math),i.SHA3}(gt(),qo())),_u.exports}var Su,bu,yu={exports:{}};function ua(){return bu||(bu=1,yu.exports=function(i){var e,t,n;t=(e=i).lib.Base,n=e.enc.Utf8,e.algo.HMAC=t.extend({init:function(r,a){r=this._hasher=new r.init,typeof a=="string"&&(a=n.parse(a));var s=r.blockSize,o=4*s;a.sigBytes>o&&(a=r.finalize(a)),a.clamp();for(var c=this._oKey=a.clone(),h=this._iKey=a.clone(),l=c.words,f=h.words,v=0;v<s;v++)l[v]^=1549556828,f[v]^=909522486;c.sigBytes=h.sigBytes=o,this.reset()},reset:function(){var r=this._hasher;r.reset(),r.update(this._iKey)},update:function(r){return this._hasher.update(r),this},finalize:function(r){var a=this._hasher,s=a.finalize(r);return a.reset(),a.finalize(this._oKey.clone().concat(s))}})}(gt())),yu.exports}var Eu,Ru,Tu={exports:{}};function Gn(){return Ru||(Ru=1,Tu.exports=function(i){return t=(e=i).lib,n=t.Base,r=t.WordArray,a=e.algo,s=a.MD5,o=a.EvpKDF=n.extend({cfg:n.extend({keySize:4,hasher:s,iterations:1}),init:function(c){this.cfg=this.cfg.extend(c)},compute:function(c,h){for(var l,f=this.cfg,v=f.hasher.create(),p=r.create(),_=p.words,m=f.keySize,d=f.iterations;_.length<m;){l&&v.update(l),l=v.update(c).finalize(h),v.reset();for(var u=1;u<d;u++)l=v.finalize(l),v.reset();p.concat(l)}return p.sigBytes=4*m,p}}),e.EvpKDF=function(c,h,l){return o.create(l).compute(c,h)},i.EvpKDF;var e,t,n,r,a,s,o}(gt(),lu(),ua())),Tu.exports}var Au,Cu={exports:{}};function Zt(){return Au||(Au=1,Cu.exports=function(i){i.lib.Cipher||function(e){var t=i,n=t.lib,r=n.Base,a=n.WordArray,s=n.BufferedBlockAlgorithm,o=t.enc;o.Utf8;var c=o.Base64,h=t.algo.EvpKDF,l=n.Cipher=s.extend({cfg:r.extend(),createEncryptor:function(g,S){return this.create(this._ENC_XFORM_MODE,g,S)},createDecryptor:function(g,S){return this.create(this._DEC_XFORM_MODE,g,S)},init:function(g,S,R){this.cfg=this.cfg.extend(R),this._xformMode=g,this._key=S,this.reset()},reset:function(){s.reset.call(this),this._doReset()},process:function(g){return this._append(g),this._process()},finalize:function(g){return g&&this._append(g),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function g(S){return typeof S=="string"?y:u}return function(S){return{encrypt:function(R,E,I){return g(E).encrypt(S,R,E,I)},decrypt:function(R,E,I){return g(E).decrypt(S,R,E,I)}}}}()});n.StreamCipher=l.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var f=t.mode={},v=n.BlockCipherMode=r.extend({createEncryptor:function(g,S){return this.Encryptor.create(g,S)},createDecryptor:function(g,S){return this.Decryptor.create(g,S)},init:function(g,S){this._cipher=g,this._iv=S}}),p=f.CBC=function(){var g=v.extend();function S(R,E,I){var C,A=this._iv;A?(C=A,this._iv=e):C=this._prevBlock;for(var w=0;w<I;w++)R[E+w]^=C[w]}return g.Encryptor=g.extend({processBlock:function(R,E){var I=this._cipher,C=I.blockSize;S.call(this,R,E,C),I.encryptBlock(R,E),this._prevBlock=R.slice(E,E+C)}}),g.Decryptor=g.extend({processBlock:function(R,E){var I=this._cipher,C=I.blockSize,A=R.slice(E,E+C);I.decryptBlock(R,E),S.call(this,R,E,C),this._prevBlock=A}}),g}(),_=(t.pad={}).Pkcs7={pad:function(g,S){for(var R=4*S,E=R-g.sigBytes%R,I=E<<24|E<<16|E<<8|E,C=[],A=0;A<E;A+=4)C.push(I);var w=a.create(C,E);g.concat(w)},unpad:function(g){var S=255&g.words[g.sigBytes-1>>>2];g.sigBytes-=S}};n.BlockCipher=l.extend({cfg:l.cfg.extend({mode:p,padding:_}),reset:function(){var g;l.reset.call(this);var S=this.cfg,R=S.iv,E=S.mode;this._xformMode==this._ENC_XFORM_MODE?g=E.createEncryptor:(g=E.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==g?this._mode.init(this,R&&R.words):(this._mode=g.call(E,this,R&&R.words),this._mode.__creator=g)},_doProcessBlock:function(g,S){this._mode.processBlock(g,S)},_doFinalize:function(){var g,S=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(S.pad(this._data,this.blockSize),g=this._process(!0)):(g=this._process(!0),S.unpad(g)),g},blockSize:4});var m=n.CipherParams=r.extend({init:function(g){this.mixIn(g)},toString:function(g){return(g||this.formatter).stringify(this)}}),d=(t.format={}).OpenSSL={stringify:function(g){var S=g.ciphertext,R=g.salt;return(R?a.create([1398893684,1701076831]).concat(R).concat(S):S).toString(c)},parse:function(g){var S,R=c.parse(g),E=R.words;return E[0]==1398893684&&E[1]==1701076831&&(S=a.create(E.slice(2,4)),E.splice(0,4),R.sigBytes-=16),m.create({ciphertext:R,salt:S})}},u=n.SerializableCipher=r.extend({cfg:r.extend({format:d}),encrypt:function(g,S,R,E){E=this.cfg.extend(E);var I=g.createEncryptor(R,E),C=I.finalize(S),A=I.cfg;return m.create({ciphertext:C,key:R,iv:A.iv,algorithm:g,mode:A.mode,padding:A.padding,blockSize:g.blockSize,formatter:E.format})},decrypt:function(g,S,R,E){return E=this.cfg.extend(E),S=this._parse(S,E.format),g.createDecryptor(R,E).finalize(S.ciphertext)},_parse:function(g,S){return typeof g=="string"?S.parse(g,this):g}}),b=(t.kdf={}).OpenSSL={execute:function(g,S,R,E,I){if(E||(E=a.random(8)),I)C=h.create({keySize:S+R,hasher:I}).compute(g,E);else var C=h.create({keySize:S+R}).compute(g,E);var A=a.create(C.words.slice(S),4*R);return C.sigBytes=4*S,m.create({key:C,iv:A,salt:E})}},y=n.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:b}),encrypt:function(g,S,R,E){var I=(E=this.cfg.extend(E)).kdf.execute(R,g.keySize,g.ivSize,E.salt,E.hasher);E.iv=I.iv;var C=u.encrypt.call(this,g,S,I.key,E);return C.mixIn(I),C},decrypt:function(g,S,R,E){E=this.cfg.extend(E),S=this._parse(S,E.format);var I=E.kdf.execute(R,g.keySize,g.ivSize,S.salt,E.hasher);return E.iv=I.iv,u.decrypt.call(this,g,S,I.key,E)}})}()}(gt(),Gn())),Cu.exports}var wu,Mu={exports:{}};function kf(){return wu||(wu=1,Mu.exports=function(i){return i.mode.CFB=function(){var e=i.lib.BlockCipherMode.extend();function t(n,r,a,s){var o,c=this._iv;c?(o=c.slice(0),this._iv=void 0):o=this._prevBlock,s.encryptBlock(o,0);for(var h=0;h<a;h++)n[r+h]^=o[h]}return e.Encryptor=e.extend({processBlock:function(n,r){var a=this._cipher,s=a.blockSize;t.call(this,n,r,s,a),this._prevBlock=n.slice(r,r+s)}}),e.Decryptor=e.extend({processBlock:function(n,r){var a=this._cipher,s=a.blockSize,o=n.slice(r,r+s);t.call(this,n,r,s,a),this._prevBlock=o}}),e}(),i.mode.CFB}(gt(),Zt())),Mu.exports}var xu,Iu={exports:{}};function Uf(){return xu||(xu=1,Iu.exports=function(i){return i.mode.CTR=(e=i.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(n,r){var a=this._cipher,s=a.blockSize,o=this._iv,c=this._counter;o&&(c=this._counter=o.slice(0),this._iv=void 0);var h=c.slice(0);a.encryptBlock(h,0),c[s-1]=c[s-1]+1|0;for(var l=0;l<s;l++)n[r+l]^=h[l]}}),e.Decryptor=t,e),i.mode.CTR;var e,t}(gt(),Zt())),Iu.exports}var Pu,Du={exports:{}};function Bf(){return Pu||(Pu=1,Du.exports=function(i){return i.mode.CTRGladman=function(){var e=i.lib.BlockCipherMode.extend();function t(a){if(255&~(a>>24))a+=1<<24;else{var s=a>>16&255,o=a>>8&255,c=255&a;s===255?(s=0,o===255?(o=0,c===255?c=0:++c):++o):++s,a=0,a+=s<<16,a+=o<<8,a+=c}return a}function n(a){return(a[0]=t(a[0]))===0&&(a[1]=t(a[1])),a}var r=e.Encryptor=e.extend({processBlock:function(a,s){var o=this._cipher,c=o.blockSize,h=this._iv,l=this._counter;h&&(l=this._counter=h.slice(0),this._iv=void 0),n(l);var f=l.slice(0);o.encryptBlock(f,0);for(var v=0;v<c;v++)a[s+v]^=f[v]}});return e.Decryptor=r,e}(),i.mode.CTRGladman}(gt(),Zt())),Du.exports}var Lu,Ou={exports:{}};function Vf(){return Lu||(Lu=1,Ou.exports=function(i){return i.mode.OFB=(e=i.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(n,r){var a=this._cipher,s=a.blockSize,o=this._iv,c=this._keystream;o&&(c=this._keystream=o.slice(0),this._iv=void 0),a.encryptBlock(c,0);for(var h=0;h<s;h++)n[r+h]^=c[h]}}),e.Decryptor=t,e),i.mode.OFB;var e,t}(gt(),Zt())),Ou.exports}var Nu,ku,Uu,Bu,Vu,Fu,Hu,Gu,zu,Wu={exports:{}};function Ff(){return zu||(zu=1,Wu.exports=function(i){return function(){var e=i,t=e.lib,n=t.WordArray,r=t.BlockCipher,a=e.algo,s=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],c=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],h=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],l=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],f=a.DES=r.extend({_doReset:function(){for(var m=this._key.words,d=[],u=0;u<56;u++){var b=s[u]-1;d[u]=m[b>>>5]>>>31-b%32&1}for(var y=this._subKeys=[],g=0;g<16;g++){var S=y[g]=[],R=c[g];for(u=0;u<24;u++)S[u/6|0]|=d[(o[u]-1+R)%28]<<31-u%6,S[4+(u/6|0)]|=d[28+(o[u+24]-1+R)%28]<<31-u%6;for(S[0]=S[0]<<1|S[0]>>>31,u=1;u<7;u++)S[u]=S[u]>>>4*(u-1)+3;S[7]=S[7]<<5|S[7]>>>27}var E=this._invSubKeys=[];for(u=0;u<16;u++)E[u]=y[15-u]},encryptBlock:function(m,d){this._doCryptBlock(m,d,this._subKeys)},decryptBlock:function(m,d){this._doCryptBlock(m,d,this._invSubKeys)},_doCryptBlock:function(m,d,u){this._lBlock=m[d],this._rBlock=m[d+1],v.call(this,4,252645135),v.call(this,16,65535),p.call(this,2,858993459),p.call(this,8,16711935),v.call(this,1,1431655765);for(var b=0;b<16;b++){for(var y=u[b],g=this._lBlock,S=this._rBlock,R=0,E=0;E<8;E++)R|=h[E][((S^y[E])&l[E])>>>0];this._lBlock=S,this._rBlock=g^R}var I=this._lBlock;this._lBlock=this._rBlock,this._rBlock=I,v.call(this,1,1431655765),p.call(this,8,16711935),p.call(this,2,858993459),v.call(this,16,65535),v.call(this,4,252645135),m[d]=this._lBlock,m[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function v(m,d){var u=(this._lBlock>>>m^this._rBlock)&d;this._rBlock^=u,this._lBlock^=u<<m}function p(m,d){var u=(this._rBlock>>>m^this._lBlock)&d;this._lBlock^=u,this._rBlock^=u<<m}e.DES=r._createHelper(f);var _=a.TripleDES=r.extend({_doReset:function(){var m=this._key.words;if(m.length!==2&&m.length!==4&&m.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var d=m.slice(0,2),u=m.length<4?m.slice(0,2):m.slice(2,4),b=m.length<6?m.slice(0,2):m.slice(4,6);this._des1=f.createEncryptor(n.create(d)),this._des2=f.createEncryptor(n.create(u)),this._des3=f.createEncryptor(n.create(b))},encryptBlock:function(m,d){this._des1.encryptBlock(m,d),this._des2.decryptBlock(m,d),this._des3.encryptBlock(m,d)},decryptBlock:function(m,d){this._des3.decryptBlock(m,d),this._des2.encryptBlock(m,d),this._des1.decryptBlock(m,d)},keySize:6,ivSize:2,blockSize:2});e.TripleDES=r._createHelper(_)}(),i.TripleDES}(gt(),or(),sr(),Gn(),Zt())),Wu.exports}var ju,Xu,$u,Ku,qu={exports:{}};function Hf(){return Ku||(Ku=1,qu.exports=function(i){return function(){var e=i,t=e.lib.BlockCipher,n=e.algo;const r=16,a=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],s=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var o={pbox:[],sbox:[]};function c(p,_){let m=_>>24&255,d=_>>16&255,u=_>>8&255,b=255&_,y=p.sbox[0][m]+p.sbox[1][d];return y^=p.sbox[2][u],y+=p.sbox[3][b],y}function h(p,_,m){let d,u=_,b=m;for(let y=0;y<r;++y)u^=p.pbox[y],b=c(p,u)^b,d=u,u=b,b=d;return d=u,u=b,b=d,b^=p.pbox[r],u^=p.pbox[r+1],{left:u,right:b}}function l(p,_,m){let d,u=_,b=m;for(let y=r+1;y>1;--y)u^=p.pbox[y],b=c(p,u)^b,d=u,u=b,b=d;return d=u,u=b,b=d,b^=p.pbox[1],u^=p.pbox[0],{left:u,right:b}}function f(p,_,m){for(let g=0;g<4;g++){p.sbox[g]=[];for(let S=0;S<256;S++)p.sbox[g][S]=s[g][S]}let d=0;for(let g=0;g<r+2;g++)p.pbox[g]=a[g]^_[d],d++,d>=m&&(d=0);let u=0,b=0,y=0;for(let g=0;g<r+2;g+=2)y=h(p,u,b),u=y.left,b=y.right,p.pbox[g]=u,p.pbox[g+1]=b;for(let g=0;g<4;g++)for(let S=0;S<256;S+=2)y=h(p,u,b),u=y.left,b=y.right,p.sbox[g][S]=u,p.sbox[g][S+1]=b;return!0}var v=n.Blowfish=t.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var p=this._keyPriorReset=this._key,_=p.words,m=p.sigBytes/4;f(o,_,m)}},encryptBlock:function(p,_){var m=h(o,p[_],p[_+1]);p[_]=m.left,p[_+1]=m.right},decryptBlock:function(p,_){var m=l(o,p[_],p[_+1]);p[_]=m.left,p[_+1]=m.right},blockSize:2,keySize:4,ivSize:2});e.Blowfish=t._createHelper(v)}(),i.Blowfish}(gt(),or(),sr(),Gn(),Zt())),qu.exports}Xl.exports=function(i){return i}(gt(),qo(),Df(),Lf(),or(),Of(),sr(),lu(),la(),hu||(hu=1,function(i){return t=(e=i).lib.WordArray,n=e.algo,r=n.SHA256,a=n.SHA224=r.extend({_doReset:function(){this._hash=new t.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var s=r._doFinalize.call(this);return s.sigBytes-=4,s}}),e.SHA224=r._createHelper(a),e.HmacSHA224=r._createHmacHelper(a),i.SHA224;var e,t,n,r,a}(gt(),la())),mu(),gu||(gu=1,function(i){return t=(e=i).x64,n=t.Word,r=t.WordArray,a=e.algo,s=a.SHA512,o=a.SHA384=s.extend({_doReset:function(){this._hash=new r.init([new n.init(3418070365,3238371032),new n.init(1654270250,914150663),new n.init(2438529370,812702999),new n.init(355462360,4144912697),new n.init(1731405415,4290775857),new n.init(2394180231,1750603025),new n.init(3675008525,1694076839),new n.init(1203062813,3204075428)])},_doFinalize:function(){var c=s._doFinalize.call(this);return c.sigBytes-=16,c}}),e.SHA384=s._createHelper(o),e.HmacSHA384=s._createHmacHelper(o),i.SHA384;var e,t,n,r,a,s,o}(gt(),qo(),mu())),Nf(),Su||(Su=1,function(i){return function(){var e=i,t=e.lib,n=t.WordArray,r=t.Hasher,a=e.algo,s=n.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=n.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),c=n.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),h=n.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),l=n.create([0,1518500249,1859775393,2400959708,2840853838]),f=n.create([1352829926,1548603684,1836072691,2053994217,0]),v=a.RIPEMD160=r.extend({_doReset:function(){this._hash=n.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(y,g){for(var S=0;S<16;S++){var R=g+S,E=y[R];y[R]=16711935&(E<<8|E>>>24)|4278255360&(E<<24|E>>>8)}var I,C,A,w,N,M,D,L,P,x,T,O=this._hash.words,k=l.words,H=f.words,U=s.words,ee=o.words,W=c.words,$=h.words;for(M=I=O[0],D=C=O[1],L=A=O[2],P=w=O[3],x=N=O[4],S=0;S<80;S+=1)T=I+y[g+U[S]]|0,T+=S<16?p(C,A,w)+k[0]:S<32?_(C,A,w)+k[1]:S<48?m(C,A,w)+k[2]:S<64?d(C,A,w)+k[3]:u(C,A,w)+k[4],T=(T=b(T|=0,W[S]))+N|0,I=N,N=w,w=b(A,10),A=C,C=T,T=M+y[g+ee[S]]|0,T+=S<16?u(D,L,P)+H[0]:S<32?d(D,L,P)+H[1]:S<48?m(D,L,P)+H[2]:S<64?_(D,L,P)+H[3]:p(D,L,P)+H[4],T=(T=b(T|=0,$[S]))+x|0,M=x,x=P,P=b(L,10),L=D,D=T;T=O[1]+A+P|0,O[1]=O[2]+w+x|0,O[2]=O[3]+N+M|0,O[3]=O[4]+I+D|0,O[4]=O[0]+C+L|0,O[0]=T},_doFinalize:function(){var y=this._data,g=y.words,S=8*this._nDataBytes,R=8*y.sigBytes;g[R>>>5]|=128<<24-R%32,g[14+(R+64>>>9<<4)]=16711935&(S<<8|S>>>24)|4278255360&(S<<24|S>>>8),y.sigBytes=4*(g.length+1),this._process();for(var E=this._hash,I=E.words,C=0;C<5;C++){var A=I[C];I[C]=16711935&(A<<8|A>>>24)|4278255360&(A<<24|A>>>8)}return E},clone:function(){var y=r.clone.call(this);return y._hash=this._hash.clone(),y}});function p(y,g,S){return y^g^S}function _(y,g,S){return y&g|~y&S}function m(y,g,S){return(y|~g)^S}function d(y,g,S){return y&S|g&~S}function u(y,g,S){return y^(g|~S)}function b(y,g){return y<<g|y>>>32-g}e.RIPEMD160=r._createHelper(v),e.HmacRIPEMD160=r._createHmacHelper(v)}(),i.RIPEMD160}(gt())),ua(),Eu||(Eu=1,function(i){return n=(t=(e=i).lib).Base,r=t.WordArray,s=(a=e.algo).SHA256,o=a.HMAC,c=a.PBKDF2=n.extend({cfg:n.extend({keySize:4,hasher:s,iterations:25e4}),init:function(h){this.cfg=this.cfg.extend(h)},compute:function(h,l){for(var f=this.cfg,v=o.create(f.hasher,h),p=r.create(),_=r.create([1]),m=p.words,d=_.words,u=f.keySize,b=f.iterations;m.length<u;){var y=v.update(l).finalize(_);v.reset();for(var g=y.words,S=g.length,R=y,E=1;E<b;E++){R=v.finalize(R),v.reset();for(var I=R.words,C=0;C<S;C++)g[C]^=I[C]}p.concat(y),d[0]++}return p.sigBytes=4*u,p}}),e.PBKDF2=function(h,l,f){return c.create(f).compute(h,l)},i.PBKDF2;var e,t,n,r,a,s,o,c}(gt(),la(),ua())),Gn(),Zt(),kf(),Uf(),Bf(),Vf(),Nu||(Nu=1,function(i){return i.mode.ECB=((e=i.lib.BlockCipherMode.extend()).Encryptor=e.extend({processBlock:function(t,n){this._cipher.encryptBlock(t,n)}}),e.Decryptor=e.extend({processBlock:function(t,n){this._cipher.decryptBlock(t,n)}}),e),i.mode.ECB;var e}(gt(),Zt())),ku||(ku=1,function(i){return i.pad.AnsiX923={pad:function(e,t){var n=e.sigBytes,r=4*t,a=r-n%r,s=n+a-1;e.clamp(),e.words[s>>>2]|=a<<24-s%4*8,e.sigBytes+=a},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},i.pad.Ansix923}(gt(),Zt())),Uu||(Uu=1,function(i){return i.pad.Iso10126={pad:function(e,t){var n=4*t,r=n-e.sigBytes%n;e.concat(i.lib.WordArray.random(r-1)).concat(i.lib.WordArray.create([r<<24],1))},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},i.pad.Iso10126}(gt(),Zt())),Bu||(Bu=1,function(i){return i.pad.Iso97971={pad:function(e,t){e.concat(i.lib.WordArray.create([2147483648],1)),i.pad.ZeroPadding.pad(e,t)},unpad:function(e){i.pad.ZeroPadding.unpad(e),e.sigBytes--}},i.pad.Iso97971}(gt(),Zt())),Vu||(Vu=1,function(i){return i.pad.ZeroPadding={pad:function(e,t){var n=4*t;e.clamp(),e.sigBytes+=n-(e.sigBytes%n||n)},unpad:function(e){var t=e.words,n=e.sigBytes-1;for(n=e.sigBytes-1;n>=0;n--)if(t[n>>>2]>>>24-n%4*8&255){e.sigBytes=n+1;break}}},i.pad.ZeroPadding}(gt(),Zt())),Fu||(Fu=1,function(i){return i.pad.NoPadding={pad:function(){},unpad:function(){}},i.pad.NoPadding}(gt(),Zt())),Hu||(Hu=1,function(i){return t=(e=i).lib.CipherParams,n=e.enc.Hex,e.format.Hex={stringify:function(r){return r.ciphertext.toString(n)},parse:function(r){var a=n.parse(r);return t.create({ciphertext:a})}},i.format.Hex;var e,t,n}(gt(),Zt())),Gu||(Gu=1,function(i){return function(){var e=i,t=e.lib.BlockCipher,n=e.algo,r=[],a=[],s=[],o=[],c=[],h=[],l=[],f=[],v=[],p=[];(function(){for(var d=[],u=0;u<256;u++)d[u]=u<128?u<<1:u<<1^283;var b=0,y=0;for(u=0;u<256;u++){var g=y^y<<1^y<<2^y<<3^y<<4;g=g>>>8^255&g^99,r[b]=g,a[g]=b;var S=d[b],R=d[S],E=d[R],I=257*d[g]^16843008*g;s[b]=I<<24|I>>>8,o[b]=I<<16|I>>>16,c[b]=I<<8|I>>>24,h[b]=I,I=16843009*E^65537*R^257*S^16843008*b,l[g]=I<<24|I>>>8,f[g]=I<<16|I>>>16,v[g]=I<<8|I>>>24,p[g]=I,b?(b=S^d[d[d[E^S]]],y^=d[d[y]]):b=y=1}})();var _=[0,1,2,4,8,16,32,64,128,27,54],m=n.AES=t.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var d=this._keyPriorReset=this._key,u=d.words,b=d.sigBytes/4,y=4*((this._nRounds=b+6)+1),g=this._keySchedule=[],S=0;S<y;S++)S<b?g[S]=u[S]:(I=g[S-1],S%b?b>6&&S%b==4&&(I=r[I>>>24]<<24|r[I>>>16&255]<<16|r[I>>>8&255]<<8|r[255&I]):(I=r[(I=I<<8|I>>>24)>>>24]<<24|r[I>>>16&255]<<16|r[I>>>8&255]<<8|r[255&I],I^=_[S/b|0]<<24),g[S]=g[S-b]^I);for(var R=this._invKeySchedule=[],E=0;E<y;E++){if(S=y-E,E%4)var I=g[S];else I=g[S-4];R[E]=E<4||S<=4?I:l[r[I>>>24]]^f[r[I>>>16&255]]^v[r[I>>>8&255]]^p[r[255&I]]}}},encryptBlock:function(d,u){this._doCryptBlock(d,u,this._keySchedule,s,o,c,h,r)},decryptBlock:function(d,u){var b=d[u+1];d[u+1]=d[u+3],d[u+3]=b,this._doCryptBlock(d,u,this._invKeySchedule,l,f,v,p,a),b=d[u+1],d[u+1]=d[u+3],d[u+3]=b},_doCryptBlock:function(d,u,b,y,g,S,R,E){for(var I=this._nRounds,C=d[u]^b[0],A=d[u+1]^b[1],w=d[u+2]^b[2],N=d[u+3]^b[3],M=4,D=1;D<I;D++){var L=y[C>>>24]^g[A>>>16&255]^S[w>>>8&255]^R[255&N]^b[M++],P=y[A>>>24]^g[w>>>16&255]^S[N>>>8&255]^R[255&C]^b[M++],x=y[w>>>24]^g[N>>>16&255]^S[C>>>8&255]^R[255&A]^b[M++],T=y[N>>>24]^g[C>>>16&255]^S[A>>>8&255]^R[255&w]^b[M++];C=L,A=P,w=x,N=T}L=(E[C>>>24]<<24|E[A>>>16&255]<<16|E[w>>>8&255]<<8|E[255&N])^b[M++],P=(E[A>>>24]<<24|E[w>>>16&255]<<16|E[N>>>8&255]<<8|E[255&C])^b[M++],x=(E[w>>>24]<<24|E[N>>>16&255]<<16|E[C>>>8&255]<<8|E[255&A])^b[M++],T=(E[N>>>24]<<24|E[C>>>16&255]<<16|E[A>>>8&255]<<8|E[255&w])^b[M++],d[u]=L,d[u+1]=P,d[u+2]=x,d[u+3]=T},keySize:8});e.AES=t._createHelper(m)}(),i.AES}(gt(),or(),sr(),Gn(),Zt())),Ff(),ju||(ju=1,function(i){return function(){var e=i,t=e.lib.StreamCipher,n=e.algo,r=n.RC4=t.extend({_doReset:function(){for(var o=this._key,c=o.words,h=o.sigBytes,l=this._S=[],f=0;f<256;f++)l[f]=f;f=0;for(var v=0;f<256;f++){var p=f%h,_=c[p>>>2]>>>24-p%4*8&255;v=(v+l[f]+_)%256;var m=l[f];l[f]=l[v],l[v]=m}this._i=this._j=0},_doProcessBlock:function(o,c){o[c]^=a.call(this)},keySize:8,ivSize:0});function a(){for(var o=this._S,c=this._i,h=this._j,l=0,f=0;f<4;f++){h=(h+o[c=(c+1)%256])%256;var v=o[c];o[c]=o[h],o[h]=v,l|=o[(o[c]+o[h])%256]<<24-8*f}return this._i=c,this._j=h,l}e.RC4=t._createHelper(r);var s=n.RC4Drop=r.extend({cfg:r.cfg.extend({drop:192}),_doReset:function(){r._doReset.call(this);for(var o=this.cfg.drop;o>0;o--)a.call(this)}});e.RC4Drop=t._createHelper(s)}(),i.RC4}(gt(),or(),sr(),Gn(),Zt())),Xu||(Xu=1,function(i){return function(){var e=i,t=e.lib.StreamCipher,n=e.algo,r=[],a=[],s=[],o=n.Rabbit=t.extend({_doReset:function(){for(var h=this._key.words,l=this.cfg.iv,f=0;f<4;f++)h[f]=16711935&(h[f]<<8|h[f]>>>24)|4278255360&(h[f]<<24|h[f]>>>8);var v=this._X=[h[0],h[3]<<16|h[2]>>>16,h[1],h[0]<<16|h[3]>>>16,h[2],h[1]<<16|h[0]>>>16,h[3],h[2]<<16|h[1]>>>16],p=this._C=[h[2]<<16|h[2]>>>16,4294901760&h[0]|65535&h[1],h[3]<<16|h[3]>>>16,4294901760&h[1]|65535&h[2],h[0]<<16|h[0]>>>16,4294901760&h[2]|65535&h[3],h[1]<<16|h[1]>>>16,4294901760&h[3]|65535&h[0]];for(this._b=0,f=0;f<4;f++)c.call(this);for(f=0;f<8;f++)p[f]^=v[f+4&7];if(l){var _=l.words,m=_[0],d=_[1],u=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),b=16711935&(d<<8|d>>>24)|4278255360&(d<<24|d>>>8),y=u>>>16|4294901760&b,g=b<<16|65535&u;for(p[0]^=u,p[1]^=y,p[2]^=b,p[3]^=g,p[4]^=u,p[5]^=y,p[6]^=b,p[7]^=g,f=0;f<4;f++)c.call(this)}},_doProcessBlock:function(h,l){var f=this._X;c.call(this),r[0]=f[0]^f[5]>>>16^f[3]<<16,r[1]=f[2]^f[7]>>>16^f[5]<<16,r[2]=f[4]^f[1]>>>16^f[7]<<16,r[3]=f[6]^f[3]>>>16^f[1]<<16;for(var v=0;v<4;v++)r[v]=16711935&(r[v]<<8|r[v]>>>24)|4278255360&(r[v]<<24|r[v]>>>8),h[l+v]^=r[v]},blockSize:4,ivSize:2});function c(){for(var h=this._X,l=this._C,f=0;f<8;f++)a[f]=l[f];for(l[0]=l[0]+1295307597+this._b|0,l[1]=l[1]+3545052371+(l[0]>>>0<a[0]>>>0?1:0)|0,l[2]=l[2]+886263092+(l[1]>>>0<a[1]>>>0?1:0)|0,l[3]=l[3]+1295307597+(l[2]>>>0<a[2]>>>0?1:0)|0,l[4]=l[4]+3545052371+(l[3]>>>0<a[3]>>>0?1:0)|0,l[5]=l[5]+886263092+(l[4]>>>0<a[4]>>>0?1:0)|0,l[6]=l[6]+1295307597+(l[5]>>>0<a[5]>>>0?1:0)|0,l[7]=l[7]+3545052371+(l[6]>>>0<a[6]>>>0?1:0)|0,this._b=l[7]>>>0<a[7]>>>0?1:0,f=0;f<8;f++){var v=h[f]+l[f],p=65535&v,_=v>>>16,m=((p*p>>>17)+p*_>>>15)+_*_,d=((4294901760&v)*v|0)+((65535&v)*v|0);s[f]=m^d}h[0]=s[0]+(s[7]<<16|s[7]>>>16)+(s[6]<<16|s[6]>>>16)|0,h[1]=s[1]+(s[0]<<8|s[0]>>>24)+s[7]|0,h[2]=s[2]+(s[1]<<16|s[1]>>>16)+(s[0]<<16|s[0]>>>16)|0,h[3]=s[3]+(s[2]<<8|s[2]>>>24)+s[1]|0,h[4]=s[4]+(s[3]<<16|s[3]>>>16)+(s[2]<<16|s[2]>>>16)|0,h[5]=s[5]+(s[4]<<8|s[4]>>>24)+s[3]|0,h[6]=s[6]+(s[5]<<16|s[5]>>>16)+(s[4]<<16|s[4]>>>16)|0,h[7]=s[7]+(s[6]<<8|s[6]>>>24)+s[5]|0}e.Rabbit=t._createHelper(o)}(),i.Rabbit}(gt(),or(),sr(),Gn(),Zt())),$u||($u=1,function(i){return function(){var e=i,t=e.lib.StreamCipher,n=e.algo,r=[],a=[],s=[],o=n.RabbitLegacy=t.extend({_doReset:function(){var h=this._key.words,l=this.cfg.iv,f=this._X=[h[0],h[3]<<16|h[2]>>>16,h[1],h[0]<<16|h[3]>>>16,h[2],h[1]<<16|h[0]>>>16,h[3],h[2]<<16|h[1]>>>16],v=this._C=[h[2]<<16|h[2]>>>16,4294901760&h[0]|65535&h[1],h[3]<<16|h[3]>>>16,4294901760&h[1]|65535&h[2],h[0]<<16|h[0]>>>16,4294901760&h[2]|65535&h[3],h[1]<<16|h[1]>>>16,4294901760&h[3]|65535&h[0]];this._b=0;for(var p=0;p<4;p++)c.call(this);for(p=0;p<8;p++)v[p]^=f[p+4&7];if(l){var _=l.words,m=_[0],d=_[1],u=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),b=16711935&(d<<8|d>>>24)|4278255360&(d<<24|d>>>8),y=u>>>16|4294901760&b,g=b<<16|65535&u;for(v[0]^=u,v[1]^=y,v[2]^=b,v[3]^=g,v[4]^=u,v[5]^=y,v[6]^=b,v[7]^=g,p=0;p<4;p++)c.call(this)}},_doProcessBlock:function(h,l){var f=this._X;c.call(this),r[0]=f[0]^f[5]>>>16^f[3]<<16,r[1]=f[2]^f[7]>>>16^f[5]<<16,r[2]=f[4]^f[1]>>>16^f[7]<<16,r[3]=f[6]^f[3]>>>16^f[1]<<16;for(var v=0;v<4;v++)r[v]=16711935&(r[v]<<8|r[v]>>>24)|4278255360&(r[v]<<24|r[v]>>>8),h[l+v]^=r[v]},blockSize:4,ivSize:2});function c(){for(var h=this._X,l=this._C,f=0;f<8;f++)a[f]=l[f];for(l[0]=l[0]+1295307597+this._b|0,l[1]=l[1]+3545052371+(l[0]>>>0<a[0]>>>0?1:0)|0,l[2]=l[2]+886263092+(l[1]>>>0<a[1]>>>0?1:0)|0,l[3]=l[3]+1295307597+(l[2]>>>0<a[2]>>>0?1:0)|0,l[4]=l[4]+3545052371+(l[3]>>>0<a[3]>>>0?1:0)|0,l[5]=l[5]+886263092+(l[4]>>>0<a[4]>>>0?1:0)|0,l[6]=l[6]+1295307597+(l[5]>>>0<a[5]>>>0?1:0)|0,l[7]=l[7]+3545052371+(l[6]>>>0<a[6]>>>0?1:0)|0,this._b=l[7]>>>0<a[7]>>>0?1:0,f=0;f<8;f++){var v=h[f]+l[f],p=65535&v,_=v>>>16,m=((p*p>>>17)+p*_>>>15)+_*_,d=((4294901760&v)*v|0)+((65535&v)*v|0);s[f]=m^d}h[0]=s[0]+(s[7]<<16|s[7]>>>16)+(s[6]<<16|s[6]>>>16)|0,h[1]=s[1]+(s[0]<<8|s[0]>>>24)+s[7]|0,h[2]=s[2]+(s[1]<<16|s[1]>>>16)+(s[0]<<16|s[0]>>>16)|0,h[3]=s[3]+(s[2]<<8|s[2]>>>24)+s[1]|0,h[4]=s[4]+(s[3]<<16|s[3]>>>16)+(s[2]<<16|s[2]>>>16)|0,h[5]=s[5]+(s[4]<<8|s[4]>>>24)+s[3]|0,h[6]=s[6]+(s[5]<<16|s[5]>>>16)+(s[4]<<16|s[4]>>>16)|0,h[7]=s[7]+(s[6]<<8|s[6]>>>24)+s[5]|0}e.RabbitLegacy=t._createHelper(o)}(),i.RabbitLegacy}(gt(),or(),sr(),Gn(),Zt())),Hf());const ar=xf(Xl.exports);function Gf(i){return e=this,t=null,n=function*(){const r=new Date;if(i.refreshSTSTokenInterval||(i.refreshSTSTokenInterval=3e5),!i.stsTokenFreshTime||+r-i.stsTokenFreshTime>=i.refreshSTSTokenInterval){i.stsTokenFreshTime=r;try{yield i.refreshSTSToken()}catch(a){typeof console.error=="function"&&console.error(`Some error occured during excuting refreshSTSToken, see:
`+a)}}return null},new Promise((r,a)=>{var s=h=>{try{c(n.next(h))}catch(l){a(l)}},o=h=>{try{c(n.throw(h))}catch(l){a(l)}},c=h=>h.done?r(h.value):Promise.resolve(h.value).then(s,o);c((n=n.apply(e,t)).next())});var e,t,n}function da(i){return{transString:function(e){let t={},n=0,r=!1;for(let a in e)a!=="time"&&a!=="__time__"||typeof e[a]!="number"?typeof e[a]=="object"?t[a]=JSON.stringify(e[a]):t[a]=String(e[a]):(n=e[a],r=!0);return t.__time__=r?n:Math.floor(new Date().getTime()/1e3),t},process:function(e,t){return n=this,r=null,a=function*(){yield Gf(i);let s=e.slice(e.indexOf("/logstores")),o=t.length,c=(h=t,ar.MD5(h).toString().toUpperCase());var h;let l=new Date().toUTCString(),f=new Map,v=new Map([["Content-Type","application/json"],["Content-MD5",c],["x-log-bodyrawsize",o.toString()]]);i.securityToken&&v.set("x-acs-security-token",i.securityToken),function(_,m,d,u,b,y,g,S){var R;let E="";y.set("x-log-apiversion","0.6.0"),y.set("x-log-signaturemethod","hmac-sha1"),E+=_+`
`+g+`
`+((R=y.get("Content-Type"))!=null?R:"")+`
`+S+`
`;const I=(w,N)=>w[0].localeCompare(N[0]),C=w=>w[0].startsWith("x-log-")||w[0].startsWith("x-acs-");try{const w=[...y.entries()].filter(C).sort(I).map(N=>N[0]+":"+N[1]+`
`).join("");E+=w}catch{}E+=m,b.size>0&&(E+="?");try{E+=[...b.entries()].sort(I).map(w=>w[0]+"="+w[1]).join("&")}catch{}const A="LOG "+d+":"+ar.HmacSHA1(E,u).toString(ar.enc.Base64);y.set("Authorization",A),y.set("x-log-date",S)}("POST",s,i.accessKeyId,i.accessKeySecret,f,v,c,l);let p=Object.fromEntries(v);return{data:t,header:p}},new Promise((s,o)=>{var c=f=>{try{l(a.next(f))}catch(v){o(v)}},h=f=>{try{l(a.throw(f))}catch(v){o(v)}},l=f=>f.done?s(f.value):Promise.resolve(f.value).then(c,h);l((a=a.apply(n,r)).next())});var n,r,a}}}typeof window<"u"&&jl(window,"stsPlugin",da);var zf=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,Wf=/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g,jf=/[^-+\dA-Z]/g;function Yo(i,e,t,n){if(arguments.length!==1||typeof i!="string"||/\d/.test(i)||(e=i,i=void 0),(i=i||i===0?i:new Date)instanceof Date||(i=new Date(i)),isNaN(i))throw TypeError("Invalid date");var r=(e=String(Yu[e]||e||Yu.default)).slice(0,4);r!=="UTC:"&&r!=="GMT:"||(e=e.slice(4),t=!0,r==="GMT:"&&(n=!0));var a=function(){return t?"getUTC":"get"},s=function(){return i[a()+"Date"]()},o=function(){return i[a()+"Day"]()},c=function(){return i[a()+"Month"]()},h=function(){return i[a()+"FullYear"]()},l=function(){return i[a()+"Hours"]()},f=function(){return i[a()+"Minutes"]()},v=function(){return i[a()+"Seconds"]()},p=function(){return i[a()+"Milliseconds"]()},_=function(){return t?0:i.getTimezoneOffset()},m=function(){return Xf(i)},d={d:function(){return s()},dd:function(){return Ci(s())},ddd:function(){return gi.dayNames[o()]},DDD:function(){return Ju({y:h(),m:c(),d:s(),_:a(),dayName:gi.dayNames[o()],short:!0})},dddd:function(){return gi.dayNames[o()+7]},DDDD:function(){return Ju({y:h(),m:c(),d:s(),_:a(),dayName:gi.dayNames[o()+7]})},m:function(){return c()+1},mm:function(){return Ci(c()+1)},mmm:function(){return gi.monthNames[c()]},mmmm:function(){return gi.monthNames[c()+12]},yy:function(){return String(h()).slice(2)},yyyy:function(){return Ci(h(),4)},h:function(){return l()%12||12},hh:function(){return Ci(l()%12||12)},H:function(){return l()},HH:function(){return Ci(l())},M:function(){return f()},MM:function(){return Ci(f())},s:function(){return v()},ss:function(){return Ci(v())},l:function(){return Ci(p(),3)},L:function(){return Ci(Math.floor(p()/10))},t:function(){return l()<12?gi.timeNames[0]:gi.timeNames[1]},tt:function(){return l()<12?gi.timeNames[2]:gi.timeNames[3]},T:function(){return l()<12?gi.timeNames[4]:gi.timeNames[5]},TT:function(){return l()<12?gi.timeNames[6]:gi.timeNames[7]},Z:function(){return n?"GMT":t?"UTC":Kf(i)},o:function(){return(_()>0?"-":"+")+Ci(100*Math.floor(Math.abs(_())/60)+Math.abs(_())%60,4)},p:function(){return(_()>0?"-":"+")+Ci(Math.floor(Math.abs(_())/60),2)+":"+Ci(Math.floor(Math.abs(_())%60),2)},S:function(){return["th","st","nd","rd"][s()%10>3?0:(s()%100-s()%10!=10)*s()%10]},W:function(){return m()},WW:function(){return Ci(m())},N:function(){return $f(i)}};return e.replace(zf,function(u){return u in d?d[u]():u.slice(1,u.length-1)})}var Yu={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"},gi={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]},Ci=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return String(i).padStart(e,"0")},Ju=function(i){var e=i.y,t=i.m,n=i.d,r=i._,a=i.dayName,s=i.short,o=s!==void 0&&s,c=new Date,h=new Date;h.setDate(h[r+"Date"]()-1);var l=new Date;return l.setDate(l[r+"Date"]()+1),c[r+"FullYear"]()===e&&c[r+"Month"]()===t&&c[r+"Date"]()===n?o?"Tdy":"Today":h[r+"FullYear"]()===e&&h[r+"Month"]()===t&&h[r+"Date"]()===n?o?"Ysd":"Yesterday":l[r+"FullYear"]()===e&&l[r+"Month"]()===t&&l[r+"Date"]()===n?o?"Tmw":"Tomorrow":a},Xf=function(i){var e=new Date(i.getFullYear(),i.getMonth(),i.getDate());e.setDate(e.getDate()-(e.getDay()+6)%7+3);var t=new Date(e.getFullYear(),0,4);t.setDate(t.getDate()-(t.getDay()+6)%7+3);var n=e.getTimezoneOffset()-t.getTimezoneOffset();e.setHours(e.getHours()-n);var r=(e-t)/6048e5;return 1+Math.floor(r)},$f=function(i){var e=i.getDay();return e===0&&(e=7),e},Kf=function(i){return(String(i).match(Wf)||[""]).pop().replace(jf,"").replace(/GMT\+0000/g,"UTC")};const{BrowserUtil:qf}=St.AliRTS,Yf="EdgeHTML",Qu="Blink",Jf="Trident",Qf="Gecko",Zf="WebKit",Jo=(i,e)=>{const t=e.match(i);return t&&t.length>0&&t[1]||""},em=[{test:[/\sedg\//i,[/edg([ea]|ios)/i]],describe(i){if(/\sedg\//i.test(i))return{name:Qu};const e=Jo(/edge\/(\d+(\.?_?\d+)+)/i,i);return{name:Yf,version:e}}},{test:[/trident/i],describe(i){const e={name:Jf},t=Jo(/trident\/(\d+(\.?_?\d+)+)/i,i);return t&&(e.version=t),e}},{test(i){const e=/gecko/i.test(i),t=/like gecko/i.test(i);return e&&!t},describe(i){const e={name:Qf},t=Jo(/gecko\/(\d+(\.?_?\d+)+)/i,i);return t&&(e.version=t),e}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:Qu})},{test:[/(apple)?webkit/i],describe(i){const e={name:Zf},t=Jo(/webkit\/(\d+(\.?_?\d+)+)/i,i);return t&&(e.version=t),e}}],ha=(i,e)=>i.find(t=>typeof t.test=="function"?t.test(e):Array.isArray(t.test)?t.test.some(n=>typeof n=="string"?e.indexOf(n)>-1:n instanceof RegExp&&n.test(e)):void 0),tm=()=>{try{const i=navigator.userAgent||"",e=ha(em,i);if(e){const t=e.describe(i);return`${t.name}/${t.version||qf.browserVersion}`}}catch{}return navigator.userAgent},im=[{test:["wow64","win64","x64"],describe:()=>"amd64"},{test:["i686","x86"],describe:()=>"x86"},{test:["aarch64","arm64"],describe:()=>"arm64"},{test:["arm"],describe:()=>"arm"}],Zu=()=>{let i="unknown";try{const e=navigator.userAgent||"",t=ha(im,e);if(!t)return i;i=t.describe(e)}catch{}return i},nm=[{test:[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],describe:()=>"Samsung"},{test:[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i,/\((ipad);[-\w\),; ]+apple/i,/(macintosh);/i],describe:()=>"Apple"},{test:[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],describe:()=>"Huawei"},{test:[/(?:honor)([-\w ]+)[;\)]/i],describe:()=>"Honor"},{test:[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],describe:()=>"Xiaomi"},{test:[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],describe:()=>"Oppo"},{test:[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],describe:()=>"Vivo"},{test:[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],describe:()=>"Realme"},{test:[/(pixel c)\b/i,/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],describe:()=>"Google"},{test:[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],describe:()=>"ZTE"},{test:[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],describe:()=>"Meizu"}],rm=()=>{let i="Unknown";try{const e=navigator.userAgent||"",t=ha(nm,e);if(!t)return i;i=t.describe(e)}catch{}return i};class ed{constructor(e){var t,n;this.timer=null,this.time=10,this.count=10,this.arr=[],this.time=(t=e.time)!=null?t:10,this.count=(n=e.count)!=null?n:10,e.host.startsWith("http://")||e.host.startsWith("https://")?this.url=e.host+"/logstores/"+e.logstore+"/track":this.url="https://"+e.project+"."+e.host+"/logstores/"+e.logstore+"/track",this.opt=e,e.installUnloadHook&&typeof e.installUnloadHook=="function"&&e.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(e){const t={__logs__:e};return this.opt.tags&&(t.__tags__=this.opt.tags),this.opt.topic&&(t.__topic__=this.opt.topic),this.opt.source&&(t.__source__=this.opt.source),JSON.stringify(t)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const e=this.assemblePayload(this.arr);this.opt.sendPayload(this.url,e)}}transString(e){let t={};for(let n in e)typeof e[n]=="object"?t[n]=JSON.stringify(e[n]):t[n]=String(e[n]);return t}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const e=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){e.sendImmediateInner()},1e3*this.time)}}send(e){const t=this.transString(e);this.arr.push(t),this.sendInner()}sendImmediate(e){const t=this.transString(e);this.arr.push(t),this.sendImmediateInner()}sendBatchLogs(e){const t=e.map(n=>this.transString(n));this.arr.push(...t),this.sendInner()}sendBatchLogsImmediate(e){const t=e.map(n=>this.transString(n));this.arr.push(...t),this.sendImmediateInner()}overwriteTransString(e){this.transString=e.transString}getOpt(){return this.opt}}function td(i,e){return new Promise((t,n)=>{const r=new window.XMLHttpRequest;r.onload=()=>{r.status>=200&&r.status<300?t():n(new Error(`HTTP ${r.status}: ${r.statusText}`))},r.onerror=()=>{n(new Error("Network error occurred"))},r.ontimeout=()=>{n(new Error("Request timeout"))},r.timeout=1e4,r.open("POST",`${i}?APIVersion=0.6.0`,!0),r.send(e)})}function om(i,e,t=!1){return le(this,null,function*(){try{if(t||e.length>=32768)return void(yield td(i,e));(function(n,r){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${n}?APIVersion=0.6.0`,r)})(i,e)||(yield td(i,e))}catch(n){const r=n instanceof Error?n:new Error(String(n));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
`+r.message),console.error("Failed log data:",i)),r}})}let sm=class extends ed{constructor(i){const e=i,{maxRetries:t=10,retryDelay:n=2e3,backoffMultiplier:r=2,maxRetryDelay:a=3e5,enableLocalStorage:s=!0,maxStorageSize:o=1e3,storageKey:c="artc_reliable_logs",enableNetworkMonitor:h=!0,onNetworkChange:l=()=>{},forceXhrMode:f=!0,debug:v=!1}=e,p=Bn(e,["maxRetries","retryDelay","backoffMultiplier","maxRetryDelay","enableLocalStorage","maxStorageSize","storageKey","enableNetworkMonitor","onNetworkChange","forceXhrMode","debug"]);super(Object.assign({},p,{installUnloadHook:_=>{window.addEventListener("beforeunload",()=>{this.saveFailedLogs(),_()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.saveFailedLogs()})},sendPayload:(_,m)=>le(this,null,function*(){return Promise.resolve()})})),V(this,"reliableConfig"),V(this,"failedLogs",new Map),V(this,"networkStatus","online"),V(this,"retryTimer",null),V(this,"originalSendPayload",null),this.reliableConfig={maxRetries:t,retryDelay:n,backoffMultiplier:r,maxRetryDelay:a,enableLocalStorage:s,maxStorageSize:o,storageKey:c,enableNetworkMonitor:h,onNetworkChange:l,forceXhrMode:f,debug:v},this.originalSendPayload=(_,m)=>le(this,null,function*(){return om(_,m,f)}),this.getOpt().sendPayload=(_,m)=>le(this,null,function*(){return this.reliableSendAsync(_,m)}),this.initNetworkMonitor(),this.loadFailedLogs(),this.startRetryTimer()}reliableSendAsync(i,e){return le(this,null,function*(){const t=this.generateId();try{yield Promise.resolve(this.originalSendPayload(i,e)),this.debug(`Log ${t} sent successfully`)}catch(n){this.debug(`Log ${t} failed, adding to retry queue:`,n),this.addToFailedQueue(t,i,e,n)}})}addToFailedQueue(i,e,t,n){const r={id:i,data:{error:n.message},timestamp:Date.now(),retryCount:0,lastRetryTime:0,url:e,payload:t};this.failedLogs.set(i,r),this.scheduleRetry(r)}scheduleRetry(i){if(i.retryCount>=this.reliableConfig.maxRetries)return this.debug(`Log ${i.id} exceeded max retries, removing from queue`),void this.failedLogs.delete(i.id);const e=Math.min(this.reliableConfig.retryDelay*Math.pow(this.reliableConfig.backoffMultiplier,i.retryCount),this.reliableConfig.maxRetryDelay);this.debug(`Scheduling retry for log ${i.id} in ${e}ms (attempt ${i.retryCount+1}/${this.reliableConfig.maxRetries})`),setTimeout(()=>{this.retryLog(i)},e)}retryLog(i){return le(this,null,function*(){if(this.failedLogs.has(i.id)){i.retryCount++,i.lastRetryTime=Date.now();try{if(this.networkStatus==="offline")return this.debug(`Log ${i.id} retry skipped - network offline`),void this.scheduleRetry(i);yield this.originalSendPayload(i.url,i.payload),this.debug(`Log ${i.id} retry successful`),this.failedLogs.delete(i.id)}catch(e){this.debug(`Log ${i.id} retry failed:`,e),this.scheduleRetry(i)}}})}initNetworkMonitor(){this.reliableConfig.enableNetworkMonitor&&typeof window<"u"&&(this.networkStatus=navigator.onLine?"online":"offline",window.addEventListener("online",()=>{this.handleNetworkChange("online")}),window.addEventListener("offline",()=>{this.handleNetworkChange("offline")}),this.debug(`Network monitor initialized. Current status: ${this.networkStatus}`))}handleNetworkChange(i){const e=this.networkStatus;this.networkStatus=i,this.debug(`Network status changed: ${e} -> ${i}`),this.reliableConfig.onNetworkChange(i==="online"),i==="online"&&e==="offline"&&(this.debug("Network recovered, retrying failed logs"),this.retryAllFailedLogs())}retryAllFailedLogs(){this.failedLogs.size!==0&&(this.debug(`Retrying ${this.failedLogs.size} failed logs after network recovery`),Array.from(this.failedLogs.values()).forEach(i=>{setTimeout(()=>this.retryLog(i),100*Math.random())}))}startRetryTimer(){typeof window<"u"&&(this.retryTimer=window.setInterval(()=>{if(this.failedLogs.size>0&&this.networkStatus==="online"){const i=Date.now();Array.from(this.failedLogs.values()).forEach(e=>{i-e.lastRetryTime>this.reliableConfig.retryDelay&&this.retryLog(e)})}},this.reliableConfig.retryDelay),this.debug(`Retry timer started with interval ${this.reliableConfig.retryDelay}ms`))}loadFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage<"u")try{const i=localStorage.getItem(this.reliableConfig.storageKey);if(i){const e=JSON.parse(i);e.forEach(t=>{this.failedLogs.set(t.id,t)}),this.debug(`Loaded ${e.length} failed logs from storage`),localStorage.removeItem(this.reliableConfig.storageKey),this.networkStatus==="online"&&this.retryAllFailedLogs()}}catch(i){this.debug("Failed to load failed logs from storage:",i)}}saveFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage<"u"&&this.failedLogs.size!==0)try{const i=Array.from(this.failedLogs.values()).slice(-this.reliableConfig.maxStorageSize);localStorage.setItem(this.reliableConfig.storageKey,JSON.stringify(i)),this.debug(`Saved ${i.length} failed logs to storage`)}catch(i){this.debug("Failed to save failed logs to storage:",i)}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}debug(...i){this.reliableConfig.debug&&typeof console<"u"&&console.log("[ReliableWebTracker]",...i)}useStsPlugin(i){this.originalSendPayload=(e,t)=>le(this,null,function*(){return function(n,r,a){return le(this,null,function*(){try{n=n.slice(0,-6);const{data:s,header:o}=yield a.process(n,r);return new Promise((c,h)=>{const l=new window.XMLHttpRequest;l.onload=()=>{l.status>=200&&l.status<300?c():h(new Error(`HTTP ${l.status}: ${l.statusText}`))},l.onerror=()=>{h(new Error("Network error occurred"))},l.ontimeout=()=>{h(new Error("Request timeout"))},l.timeout=1e4,l.open("POST",n,!0);for(let f in o)l.setRequestHeader(f,o[f]);l.send(s)})}catch(s){const o=s instanceof Error?s:new Error(String(s));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
`+o.message),console.error("Failed log data:",n)),o}})}(e,t,i)}),this.getOpt().sendPayload=(e,t)=>le(this,null,function*(){return this.reliableSendAsync(e,t)}),this.overwriteTransString(i)}getStatus(){return{networkStatus:this.networkStatus,failedLogsCount:this.failedLogs.size,isRetryActive:this.retryTimer!==null,config:this.reliableConfig}}retryAll(){this.debug("Manual retry triggered"),this.retryAllFailedLogs()}clearFailedLogs(){const i=this.failedLogs.size;this.failedLogs.clear(),this.debug(`Cleared ${i} failed logs`)}getFailedLogs(){return Array.from(this.failedLogs.values())}destroy(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),this.saveFailedLogs(),this.failedLogs.clear(),this.debug("WebTrackerBrowser destroyed")}};const{BrowserUtil:id,SystenUtil:nd}=St.AliRTS,am=Zu(),Qo=6e5,rd={host:"cn-hangzhou.log.aliyuncs.com",project:"alivc-aio",logstore:"logger",time:10,count:10},od={host:"ap-southeast-1.log.aliyuncs.com",project:"alivc-aio-sgp",logstore:"logger",time:10,count:10};function pa(){return Yo(new Date,"HH:MM:ss.l")}function sd(){return Yo(new Date,"isoDate")}var ad=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.API=2]="API",i[i.WARNING=3]="WARNING",i[i.ERROR=4]="ERROR",i[i.NONE=5]="NONE",i))(ad||{});class cm{constructor(){V(this,"tracker"),V(this,"stsPlugin"),V(this,"stsData"),V(this,"stsExpiration",Date.now()),V(this,"clientId",Ai()),V(this,"bSesid",Ai()),V(this,"logLevel",3),V(this,"appId",""),V(this,"sessionId",""),V(this,"logCache",[]),V(this,"updateTaskTimer"),V(this,"endReported",!0),V(this,"logSequence",0),V(this,"globalEnv","DEFAULT"),V(this,"sendLogBeforeUnload",e=>le(this,null,function*(){if(!this.stsPlugin)return;this.logSequence+=1,e.unshift(this.getLogParams(710203,{log:`[${sd()} ${pa()}] [INF] beforeunload`,stat_log_seq:this.logSequence}));const t=this.globalEnv==="SEA"?od:rd,n=`https://${t.project}.${t.host}/logstores/${t.logstore}`,r={__logs__:e.map(o=>this.stsPlugin.transString(o))},{data:a,header:s}=yield this.stsPlugin.process(n,JSON.stringify(r));fetch(n,{keepalive:!0,method:"POST",headers:s,body:a})})),V(this,"logMethod",(e,t=console.log)=>(...n)=>{let r=pa();this.logLevel<=e&&t(r,...n);let a=kt.paramArrayToString(n);e>0&&this.addLog(a)}),V(this,"d",this.logMethod(0,console.debug)),V(this,"i",this.logMethod(1)),V(this,"w",this.logMethod(3,console.warn)),V(this,"e",this.logMethod(4,(...e)=>{const[t,...n]=e;console.error(t,"<error>",n)})),V(this,"ev",this.logMethod(2)),V(this,"a",this.logMethod(2,(...e)=>{const[t,...n]=e;if(n.length>2){const r=`${n[1]}`;r.startsWith("__g__")&&console.group(`${r.substring(5)}_${n[2]}`)}console.log(t,...n)})),V(this,"ar",this.logMethod(2,(...e)=>{const[t,...n]=e;console.log(t,...n),n.length>2&&`${n[1]}`.startsWith("__g__")&&console.groupEnd()})),V(this,"ae",this.logMethod(2,(...e)=>{const[t,...n]=e;console.error(t,"<error>",...n),n.length>2&&`${n[1]}`.startsWith("__g__")&&console.groupEnd()})),window.addEventListener("beforeunload",()=>{this.reportEnd(!0)})}init(e){e&&(this.globalEnv=e),this.reset(),this.startSTSUpdateTask()}destroy(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer)}reset(){this.bSesid=Ai(),this.endReported=!0,this.logSequence=0,this.appId="",this.sessionId=""}startSTSUpdateTask(){return le(this,null,function*(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer);try{const e=yield this.refreshSTSToken();this.createTracker(e)}catch{}this.updateTaskTimer=setTimeout(()=>{this.startSTSUpdateTask()},Qo)})}refreshSTSToken(){return le(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()+Qo){const e=yield this.requestSTSToken(),t=new Date(e==null?void 0:e.Expiration).getTime()||0,n=Date.now()+Qo;this.stsExpiration=Math.max(t,n),this.stsData=e}return this.stsData})}requestSTSToken(){const e=Date.now(),t=`${this.clientId}|woMMssV6jmyol9fr|${e}`,n={Action:"AssumeSlsRoleV2",AuthInfo:ar.MD5(t).toString(ar.enc.Hex),ClientId:this.clientId,BusinessType:"logger",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${e}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:Yo(e,"isoUtcDateTime")},r=new URLSearchParams(n).toString(),a=`https://${this.globalEnv==="SEA"?"slsrole-intl.alicdn.com":"slsrole.alicdn.com"}/?${r}`;return fetch(a).then(s=>s.json()).then(s=>JSON.parse(window.atob(s.SlsAuthResult)))}createTracker(e){if(!this.tracker){const t={accessKeyId:e.AccessKeyId,accessKeySecret:e.AccessKeySecret,securityToken:e.SecurityToken,refreshSTSTokenInterval:Qo,stsTokenFreshTime:void 0,refreshSTSToken:()=>{this.refreshSTSToken().then(a=>{t.accessKeyId=a.AccessKeyId,t.accessKeySecret=a.AccessKeySecret,t.securityToken=a.SecurityToken}).catch(()=>{})}},n=new sm(this.globalEnv==="SEA"?od:rd),r=da(t);n.useStsPlugin(r),this.stsPlugin=r,this.tracker=n,this.reportStartAndCache()}}changeConfig(e){e.logLevel!==void 0&&e.logLevel>=0&&e.logLevel<=5&&(this.logLevel=e.logLevel)}setSessionID(e,t){e&&t&&(this.appId=e,this.sessionId=t,this.reportStartAndCache())}reportStartAndCache(){if(!this.tracker||!this.sessionId)return;this.endReported=!1;const e={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},t=[this.getLogParams(710201,e),this.getLogParams(710202,e)];this.tracker.sendBatchLogsImmediate(t),this.logCache.forEach(n=>{this.sendLog(n)})}reportEnd(e=!1){if(!this.tracker||!this.sessionId||this.endReported)return void this.reset();const t={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},n=[this.getLogParams(710204,t),this.getLogParams(710205,t)];e?this.sendLogBeforeUnload(n):(this.tracker.sendBatchLogsImmediate(n),this.endReported=!0),this.reset()}getLogParams(e,t){return Ze({appid:`${window.location.host}`,appid_list:this.appId,appver:"",b_sesid:this.bSesid,biz_type:"rtc",cpu_info:am,db:id.browserName,dm:id.browserVersion,install_uuid:this.clientId,logger_v:"0.0.1",os:nd.systemName,osv:nd.systemVersion,p_sesid:this.bSesid,sdk_version:vo,sdkname:"AliRTCSdk",stm:Date.now(),tar_pf:"web",traceid:this.sessionId,event_id:e},t||{})}sendLog(e){if(!this.tracker||!this.sessionId)return;this.logSequence+=1;const t=this.getLogParams(710203,{log:e,stat_log_seq:this.logSequence});this.tracker.send(t)}addLog(e){const t=pa(),n=`[${sd()} ${t}] ${e}`;this.sessionId&&this.tracker?this.sendLog(n):(this.logCache.push(n),this.logCache.length>=200&&this.logCache.shift())}}class Re{static getLogger(){return this.logger||(this.logger=new cm),this.logger}static init(e){this.getLogger().init(e)}static destroy(){this.getLogger().destroy()}static setLogLevel(e){this.getLogger().changeConfig({logLevel:e})}static setSessionID(e,t){this.getLogger().setSessionID(e,t)}static reportEnd(){this.getLogger().reportEnd()}static interface(...e){this.getLogger().a("[API]",...e)}static interfaceResult(e,t,n,...r){n?this.getLogger().ar("[ARE]",e,t,...r):this.getLogger().ae("[ARE]",e,t,...r)}static event(...e){this.getLogger().ev("[EVT]",...e)}static debug(...e){this.getLogger().d("[DBG]",...e)}static info(...e){this.getLogger().i("[INF]",...e)}static warn(...e){this.getLogger().w("[WARN]",...e)}static error(...e){this.getLogger().e("[ERR]",...e)}}V(Re,"logger");const cd=class _f extends Kt{constructor(e){super(),V(this,"roomServerUrl"),V(this,"label"),V(this,"rtsInstance"),V(this,"currentStatus",at.AliRtcConnectionStatusInit),V(this,"latestStreamInfo"),V(this,"preferredL1Ip"),V(this,"usePreferredL1InRetry",!0),V(this,"_remoteStream"),V(this,"remoteStream"),V(this,"_prevDownlinkStat"),V(this,"networkQualityTimer"),this.config=e;const{env:t,appId:n,currentUserId:r,targetChannelId:a,targetUserId:s,token:o,nonce:c,timestamp:h}=e,l=kt.createCallid(),f=new URLSearchParams({appid:n,channelid:a,userid:r,timestamp:h.toString(),token:o,nonce:c??"",tid:l,pubchannelid:a,pubuserid:s}),v=t===qi.pre?Vn.pre:Vn.prod;this.roomServerUrl=`https://${v}/signaling/v1/querypulluri?${f.toString()}`,this.label=`${this.config.currentUserId} => ${this.config.targetChannelId} > ${this.config.targetUserId}`,this.fetchStreamUrlAndPlay()}get logName(){return`${_f.logName}(${this.label})`}updateConnectionStatus(e){this.currentStatus!==e&&(this.currentStatus=e,this.emit("connectionStatusChange",e))}handleError(e,t){var n;Re.error(`[${this.logName}]`,"Error:",e,t),this.emit("error",e,t),this.updateConnectionStatus(at.AliRtcConnectionStatusFailed),(n=this.rtsInstance)==null||n.dispose(),this.rtsInstance=void 0}fetchStreamUrlAndPlay(){return le(this,null,function*(){var e,t,n;this.updateConnectionStatus(at.AliRtcConnectionStatusConnecting);try{const r=yield fetch(this.roomServerUrl);if(!r.ok){const h=yield r.text();return void this.handleError("FETCH_STREAM_URL_FAILED",`Fetch stream url failed, status: ${r.status} ${h}`)}const a=yield r.json();if(Re.debug(`[${this.logName}]`,"Query pull uri response:",a),a.code!==0)return void this.handleError("FETCH_STREAM_URL_FAILED",`Business error, code: ${a.code}`);if(!((t=(e=a==null?void 0:a.data)==null?void 0:e.subscribe)!=null&&t.pullstreamurl)||!((n=a==null?void 0:a.data)!=null&&n.tracks))return void this.handleError("NO_STREAM_AVAILABLE","No stream available");const s=`${a.data.subscribe.pullstreamurl}&curUid=${this.config.currentUserId}&tarCid=${this.config.targetChannelId}&tarUid=${this.config.targetUserId}`,o=a.data.tracks.filter(h=>Gl(h.msid)).map(h=>h.msid),c=a.data.tracks.filter(h=>zl(h.msid)).map(h=>h.msid);if(o.length===0&&c.length===0)return void this.handleError("NO_STREAM_AVAILABLE","No tracks available");Re.info(`[${this.logName}]`,"Fetch stream url success",s,o,c),this.latestStreamInfo={url:s,vMsid:o,aMsid:c},this.preferredL1Ip=a.l1ip,this.rtsInstance=St.AliRTS.createClient(),this.rtsInstance.on("reconnect",h=>{h.retryTimes>=300?this.handleError("SUBSCRIBE_FAILED","reconnect failed"):this.currentStatus!==at.AliRtcConnectionStatusReconnecting&&(Re.warn(`[${this.logName}]`,"reconnecting",h),this.updateConnectionStatus(at.AliRtcConnectionStatusReconnecting))}),this.rtsInstance.on("hebtReceived",h=>{var l,f;h.recode===0&&((f=(l=h.streams)==null?void 0:l[0])==null?void 0:f.res_code)===200&&this.currentStatus===at.AliRtcConnectionStatusReconnecting&&(Re.warn(`[${this.logName}]`,"reconnect success",h),this.updateConnectionStatus(at.AliRtcConnectionStatusConnected))});try{if(this._remoteStream=yield this.subscribeWithPreferredL1Fallback(s,{vMsid:o,aMsid:c,heartbeat:{interval:1e3,timeout:5e3},retryTimes:300,beforeRetry:()=>le(this,null,function*(){var h;Re.info(`[${this.logName}]`,"Trying to fetch new stream url...");const l=yield fetch(this.roomServerUrl);if(l.status!==400){if(l.ok&&l.status===200){const f=yield l.json();if(Re.debug(`[${this.logName}]`,"Query pull uri response:",f),f.code===0&&((h=f.data.subscribe)==null?void 0:h.pullstreamurl)&&f.data.tracks){const v=`${f.data.subscribe.pullstreamurl}&curUid=${this.config.currentUserId}&tarCid=${this.config.targetChannelId}&tarUid=${this.config.targetUserId}`,p=f.data.tracks.filter(m=>Gl(m.msid)).map(m=>m.msid),_=f.data.tracks.filter(m=>zl(m.msid)).map(m=>m.msid);if(p.length>0||_.length>0){const m=this.usePreferredL1InRetry?sa(v,f.l1ip):v;Re.info(`[${this.logName}]`,"Fetch new stream url success",m,p,_,`usePreferredL1InRetry=${this.usePreferredL1InRetry}`),this.latestStreamInfo={url:m,vMsid:p,aMsid:_}}}}return this.latestStreamInfo}{const f=yield l.text();this.handleError("FETCH_STREAM_URL_FAILED",`Fetch new stream url failed, status: ${l.status} ${f}`)}})}),Re.info(`[${this.logName}]`,"Subscribe success",this._remoteStream.traceId),this.remoteStream=this.createRemoteStreamProxy(this._remoteStream),this.updateConnectionStatus(at.AliRtcConnectionStatusConnected),this.startNetworkQualityTimer(),this.config.view){let h;h=typeof this.config.view=="string"?document.getElementById(this.config.view):this.config.view,h instanceof HTMLMediaElement?this._remoteStream.play(h):this.emit("error","INVALID_VIEW_ELEMENT","view is not a media element")}}catch(h){this.handleError("SUBSCRIBE_FAILED",`Subscribe failed: ${h.message}`)}}catch(r){this.handleError("FETCH_STREAM_URL_FAILED",`Fetch stream url failed: ${r.message}`)}})}subscribeWithPreferredL1Fallback(e,t){return le(this,null,function*(){const n=sa(e,this.preferredL1Ip);if(n!==e){const a=window.__ali_prefer_media_server||this.preferredL1Ip;Re.info(`[${this.logName}]`,"Subscribing with preferred media server, ip:",a);const s=new Promise((o,c)=>{setTimeout(()=>c(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const o=yield Promise.race([this.rtsInstance.subscribe(n,t),s]);return this.latestStreamInfo.url=n,this.logCandidateProtocol("subscribe (preferred)"),o}catch(o){if(o.message==="PREFERRED_L1_TIMEOUT"){Re.warn(`[${this.logName}]`,"Preferred media server subscribe timeout, falling back to DNS"),this.usePreferredL1InRetry=!1;const c=yield this.rtsInstance.subscribe(e,t);return this.logCandidateProtocol("subscribe (fallback)"),c}throw o}}const r=yield this.rtsInstance.subscribe(e,t);return this.logCandidateProtocol("subscribe"),r})}logCandidateProtocol(e){return le(this,null,function*(){var t,n,r;try{const a=(r=(n=(t=this.rtsInstance)==null?void 0:t.commonController)==null?void 0:n.peerCore)==null?void 0:r.pc;if(!a)return void Re.debug(`[${this.logName}]`,`${e} - PC not available`);const s=yield a.getStats();let o,c,h,l;s.forEach(f=>{f.type==="candidate-pair"&&f.state==="succeeded"&&f.nominated&&(o=f.localCandidateId,c=f.remoteCandidateId)}),o||c||s.forEach(f=>{f.type!=="candidate-pair"||f.state!=="succeeded"&&f.state!=="in-progress"||o||(o=f.localCandidateId,c=f.remoteCandidateId)}),s.forEach(f=>{f.type==="local-candidate"&&f.id===o&&(h=f.protocol),f.type==="remote-candidate"&&f.id===c&&(l=f.protocol)}),Re.info(`[${this.logName}]`,`${e} - Candidate Protocol: local=${h||"unknown"}, remote=${l||"unknown"}`)}catch(a){Re.warn(`[${this.logName}]`,`${e} - Failed to get candidate protocol:`,a)}})}createRemoteStreamProxy(e){const t=this.logName;return new Proxy(e,{get(n,r,a){const s=Reflect.get(n,r,a);return typeof s=="function"?function(...o){Re.interface(`[${t}]`,`remoteStream.${String(r)} called`,o.length>0?o:"");const c=s.apply(n,o);return c instanceof Promise?c.then(h=>(Re.info(`[${t}]`,`remoteStream.${String(r)} resolved`,h!==void 0?h:""),h),h=>{throw Re.error(`[${t}]`,`remoteStream.${String(r)} rejected`,h),h}):c}:s}})}startNetworkQualityTimer(){this.stopNetworkQualityTimer(),this._prevDownlinkStat=void 0,this.networkQualityTimer=setInterval(()=>le(this,null,function*(){if(this.currentStatus===at.AliRtcConnectionStatusConnected)try{const e=yield this.getNetworkQuality();this.emit("networkQuality",e)}catch(e){Re.warn(`[${this.logName}]`,"Failed to get network quality:",e)}}),2e3)}stopNetworkQualityTimer(){this.networkQualityTimer&&(clearInterval(this.networkQualityTimer),this.networkQualityTimer=void 0)}getNetworkQuality(){return le(this,null,function*(){var e,t,n;const r=(n=(t=(e=this.rtsInstance)==null?void 0:e.commonController)==null?void 0:t.peerCore)==null?void 0:n.pc;if(!r||r.connectionState==="disconnected"||r.connectionState==="failed"||r.connectionState==="closed")return{rtt:0,loss:0,quality:Ui.AliRtcNetworkDisconnected};let a=0,s=0,o=0;const c=r.getReceivers();for(const m of c)(yield m.getStats()).forEach(d=>{d.type==="candidate-pair"&&typeof d.currentRoundTripTime=="number"&&(a=Math.round(1e3*d.currentRoundTripTime)),d.type!=="inbound-rtp"||d.mediaType!=="audio"&&d.mediaType!=="video"||(s+=d.packetsLost||0,o+=d.packetsReceived||0)});if(!this._prevDownlinkStat)return this._prevDownlinkStat={totalPacketsLost:s,totalPacketsReceived:o},{rtt:a,loss:0,quality:Ui.AliRtcNetworkUnknown};const{totalPacketsLost:h,totalPacketsReceived:l}=this._prevDownlinkStat,f=s-h,v=o-l;let p=0;f>0&&v>=0&&(p=Math.round(f/(f+v)*100));const _=Hl(p,a);return this._prevDownlinkStat={totalPacketsLost:s,totalPacketsReceived:o},{rtt:a,loss:p,quality:_}})}dispose(){Re.info(`[${this.logName}]`,"dispose"),this.stopNetworkQualityTimer(),this.updateConnectionStatus(at.AliRtcConnectionStatusDisconnected),this.rtsInstance&&this.rtsInstance.dispose()}};V(cd,"logName","RemoteStreamHandler");let lm=cd;var fa,ma,ga={exports:{}};fa=ga,ma=ga.exports,function(i,e){var t="function",n="undefined",r="object",a="string",s="major",o="model",c="name",h="type",l="vendor",f="version",v="architecture",p="console",_="mobile",m="tablet",d="smarttv",u="wearable",b="embedded",y="Amazon",g="Apple",S="ASUS",R="BlackBerry",E="Browser",I="Chrome",C="Firefox",A="Google",w="Huawei",N="LG",M="Microsoft",D="Motorola",L="Opera",P="Samsung",x="Sharp",T="Sony",O="Xiaomi",k="Zebra",H="Facebook",U="Chromium OS",ee="Mac OS",W=" Browser",$=function(he){for(var pe={},ue=0;ue<he.length;ue++)pe[he[ue].toUpperCase()]=he[ue];return pe},B=function(he,pe){return typeof he===a&&F(pe).indexOf(F(he))!==-1},F=function(he){return he.toLowerCase()},G=function(he,pe){if(typeof he===a)return he=he.replace(/^\s\s*/,""),typeof pe===n?he:he.substring(0,500)},q=function(he,pe){for(var ue,Te,be,Z,K,re,de=0;de<pe.length&&!K;){var ye=pe[de],Ee=pe[de+1];for(ue=Te=0;ue<ye.length&&!K&&ye[ue];)if(K=ye[ue++].exec(he))for(be=0;be<Ee.length;be++)re=K[++Te],typeof(Z=Ee[be])===r&&Z.length>0?Z.length===2?typeof Z[1]==t?this[Z[0]]=Z[1].call(this,re):this[Z[0]]=Z[1]:Z.length===3?typeof Z[1]!==t||Z[1].exec&&Z[1].test?this[Z[0]]=re?re.replace(Z[1],Z[2]):e:this[Z[0]]=re?Z[1].call(this,re,Z[2]):e:Z.length===4&&(this[Z[0]]=re?Z[3].call(this,re.replace(Z[1],Z[2])):e):this[Z]=re||e;de+=2}},X=function(he,pe){for(var ue in pe)if(typeof pe[ue]===r&&pe[ue].length>0){for(var Te=0;Te<pe[ue].length;Te++)if(B(pe[ue][Te],he))return ue==="?"?e:ue}else if(B(pe[ue],he))return ue==="?"?e:ue;return pe.hasOwnProperty("*")?pe["*"]:he},J={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},se={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[f,[c,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[f,[c,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[c,f],[/opios[\/ ]+([\w\.]+)/i],[f,[c,L+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[f,[c,L+" GX"]],[/\bopr\/([\w\.]+)/i],[f,[c,L]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[f,[c,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[f,[c,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[c,f],[/quark(?:pc)?\/([-\w\.]+)/i],[f,[c,"Quark"]],[/\bddg\/([\w\.]+)/i],[f,[c,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[f,[c,"UC"+E]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[f,[c,"WeChat"]],[/konqueror\/([\w\.]+)/i],[f,[c,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[f,[c,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[f,[c,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[f,[c,"Smart Lenovo "+E]],[/(avast|avg)\/([\w\.]+)/i],[[c,/(.+)/,"$1 Secure "+E],f],[/\bfocus\/([\w\.]+)/i],[f,[c,C+" Focus"]],[/\bopt\/([\w\.]+)/i],[f,[c,L+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[f,[c,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[f,[c,"Dolphin"]],[/coast\/([\w\.]+)/i],[f,[c,L+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[f,[c,"MIUI"+W]],[/fxios\/([\w\.-]+)/i],[f,[c,C]],[/\bqihoobrowser\/?([\w\.]*)/i],[f,[c,"360"]],[/\b(qq)\/([\w\.]+)/i],[[c,/(.+)/,"$1Browser"],f],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[c,/(.+)/,"$1"+W],f],[/samsungbrowser\/([\w\.]+)/i],[f,[c,P+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[f,[c,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[c,"Sogou Mobile"],f],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[c,f],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[c],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[f,c],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[c,H],f],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[c,f],[/\bgsa\/([\w\.]+) .*safari\//i],[f,[c,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[f,[c,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[f,[c,I+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[c,I+" WebView"],f],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[f,[c,"Android "+E]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[c,f],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[f,[c,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[f,c],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[c,[f,X,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[c,f],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[c,"Netscape"],f],[/(wolvic|librewolf)\/([\w\.]+)/i],[c,f],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[f,[c,C+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[c,[f,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[c,[f,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[v,"amd64"]],[/(ia32(?=;))/i],[[v,F]],[/((?:i[346]|x)86)[;\)]/i],[[v,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[v,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[v,"armhf"]],[/windows (ce|mobile); ppc;/i],[[v,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[v,/ower/,"",F]],[/(sun4\w)[;\)]/i],[[v,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[v,F]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[o,[l,P],[h,m]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[o,[l,P],[h,_]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[o,[l,g],[h,_]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[o,[l,g],[h,m]],[/(macintosh);/i],[o,[l,g]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[o,[l,x],[h,_]],[/(?:honor)([-\w ]+)[;\)]/i],[o,[l,"Honor"],[h,_]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[o,[l,w],[h,m]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[o,[l,w],[h,_]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[o,/_/g," "],[l,O],[h,_]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[o,/_/g," "],[l,O],[h,m]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[o,[l,"OPPO"],[h,_]],[/\b(opd2\d{3}a?) bui/i],[o,[l,"OPPO"],[h,m]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[o,[l,"Vivo"],[h,_]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[o,[l,"Realme"],[h,_]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[o,[l,D],[h,_]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[o,[l,D],[h,m]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[o,[l,N],[h,m]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[o,[l,N],[h,_]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[o,[l,"Lenovo"],[h,m]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[o,/_/g," "],[l,"Nokia"],[h,_]],[/(pixel c)\b/i],[o,[l,A],[h,m]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[o,[l,A],[h,_]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[o,[l,T],[h,_]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[o,"Xperia Tablet"],[l,T],[h,m]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[o,[l,"OnePlus"],[h,_]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[o,[l,y],[h,m]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[o,/(.+)/g,"Fire Phone $1"],[l,y],[h,_]],[/(playbook);[-\w\),; ]+(rim)/i],[o,l,[h,m]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[o,[l,R],[h,_]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[o,[l,S],[h,m]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[o,[l,S],[h,_]],[/(nexus 9)/i],[o,[l,"HTC"],[h,m]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[l,[o,/_/g," "],[h,_]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[o,[l,"TCL"],[h,m]],[/(itel) ((\w+))/i],[[l,F],o,[h,X,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[o,[l,"Acer"],[h,m]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[o,[l,"Meizu"],[h,_]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[o,[l,"Ulefone"],[h,_]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[o,[l,"Energizer"],[h,_]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[o,[l,"Cat"],[h,_]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[o,[l,"Smartfren"],[h,_]],[/droid.+; (a(?:015|06[35]|142p?))/i],[o,[l,"Nothing"],[h,_]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[l,o,[h,_]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[l,o,[h,m]],[/(surface duo)/i],[o,[l,M],[h,m]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[o,[l,"Fairphone"],[h,_]],[/(u304aa)/i],[o,[l,"AT&T"],[h,_]],[/\bsie-(\w*)/i],[o,[l,"Siemens"],[h,_]],[/\b(rct\w+) b/i],[o,[l,"RCA"],[h,m]],[/\b(venue[\d ]{2,7}) b/i],[o,[l,"Dell"],[h,m]],[/\b(q(?:mv|ta)\w+) b/i],[o,[l,"Verizon"],[h,m]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[o,[l,"Barnes & Noble"],[h,m]],[/\b(tm\d{3}\w+) b/i],[o,[l,"NuVision"],[h,m]],[/\b(k88) b/i],[o,[l,"ZTE"],[h,m]],[/\b(nx\d{3}j) b/i],[o,[l,"ZTE"],[h,_]],[/\b(gen\d{3}) b.+49h/i],[o,[l,"Swiss"],[h,_]],[/\b(zur\d{3}) b/i],[o,[l,"Swiss"],[h,m]],[/\b((zeki)?tb.*\b) b/i],[o,[l,"Zeki"],[h,m]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[l,"Dragon Touch"],o,[h,m]],[/\b(ns-?\w{0,9}) b/i],[o,[l,"Insignia"],[h,m]],[/\b((nxa|next)-?\w{0,9}) b/i],[o,[l,"NextBook"],[h,m]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[l,"Voice"],o,[h,_]],[/\b(lvtel\-)?(v1[12]) b/i],[[l,"LvTel"],o,[h,_]],[/\b(ph-1) /i],[o,[l,"Essential"],[h,_]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[o,[l,"Envizen"],[h,m]],[/\b(trio[-\w\. ]+) b/i],[o,[l,"MachSpeed"],[h,m]],[/\btu_(1491) b/i],[o,[l,"Rotor"],[h,m]],[/(shield[\w ]+) b/i],[o,[l,"Nvidia"],[h,m]],[/(sprint) (\w+)/i],[l,o,[h,_]],[/(kin\.[onetw]{3})/i],[[o,/\./g," "],[l,M],[h,_]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[o,[l,k],[h,m]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[o,[l,k],[h,_]],[/smart-tv.+(samsung)/i],[l,[h,d]],[/hbbtv.+maple;(\d+)/i],[[o,/^/,"SmartTV"],[l,P],[h,d]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[l,N],[h,d]],[/(apple) ?tv/i],[l,[o,g+" TV"],[h,d]],[/crkey/i],[[o,I+"cast"],[l,A],[h,d]],[/droid.+aft(\w+)( bui|\))/i],[o,[l,y],[h,d]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[o,[l,x],[h,d]],[/(bravia[\w ]+)( bui|\))/i],[o,[l,T],[h,d]],[/(mitv-\w{5}) bui/i],[o,[l,O],[h,d]],[/Hbbtv.*(technisat) (.*);/i],[l,o,[h,d]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[l,G],[o,G],[h,d]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,d]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[l,o,[h,p]],[/droid.+; (shield) bui/i],[o,[l,"Nvidia"],[h,p]],[/(playstation [345portablevi]+)/i],[o,[l,T],[h,p]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[o,[l,M],[h,p]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[o,[l,P],[h,u]],[/((pebble))app/i],[l,o,[h,u]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[o,[l,g],[h,u]],[/droid.+; (glass) \d/i],[o,[l,A],[h,u]],[/droid.+; (wt63?0{2,3})\)/i],[o,[l,k],[h,u]],[/droid.+; (glass) \d/i],[o,[l,A],[h,u]],[/(pico) (4|neo3(?: link|pro)?)/i],[l,o,[h,u]],[/; (quest( \d| pro)?)/i],[o,[l,H],[h,u]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[l,[h,b]],[/(aeobc)\b/i],[o,[l,y],[h,b]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[o,[h,_]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[o,[h,m]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,m]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,_]],[/(android[-\w\. ]{0,9});.+buil/i],[o,[l,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[f,[c,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[c,f],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[f,[c,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[c,f],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[f,c]],os:[[/microsoft (windows) (vista|xp)/i],[c,f],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[c,[f,X,J]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[f,X,J],[c,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[f,/_/g,"."],[c,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[c,ee],[f,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[f,c],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[c,f],[/\(bb(10);/i],[f,[c,R]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[f,[c,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[f,[c,C+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[f,[c,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[f,[c,"watchOS"]],[/crkey\/([\d\.]+)/i],[f,[c,I+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[c,U],f],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[c,f],[/(sunos) ?([\w\.\d]*)/i],[[c,"Solaris"],f],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[c,f]]},ce=function(he,pe){if(typeof he===r&&(pe=he,he=e),!(this instanceof ce))return new ce(he,pe).getResult();var ue=typeof i!==n&&i.navigator?i.navigator:e,Te=he||(ue&&ue.userAgent?ue.userAgent:""),be=ue&&ue.userAgentData?ue.userAgentData:e,Z=pe?function(re,de){var ye={};for(var Ee in re)de[Ee]&&de[Ee].length%2==0?ye[Ee]=de[Ee].concat(re[Ee]):ye[Ee]=re[Ee];return ye}(se,pe):se,K=ue&&ue.userAgent==Te;return this.getBrowser=function(){var re,de={};return de[c]=e,de[f]=e,q.call(de,Te,Z.browser),de[s]=typeof(re=de[f])===a?re.replace(/[^\d\.]/g,"").split(".")[0]:e,K&&ue&&ue.brave&&typeof ue.brave.isBrave==t&&(de[c]="Brave"),de},this.getCPU=function(){var re={};return re[v]=e,q.call(re,Te,Z.cpu),re},this.getDevice=function(){var re={};return re[l]=e,re[o]=e,re[h]=e,q.call(re,Te,Z.device),K&&!re[h]&&be&&be.mobile&&(re[h]=_),K&&re[o]=="Macintosh"&&ue&&typeof ue.standalone!==n&&ue.maxTouchPoints&&ue.maxTouchPoints>2&&(re[o]="iPad",re[h]=m),re},this.getEngine=function(){var re={};return re[c]=e,re[f]=e,q.call(re,Te,Z.engine),re},this.getOS=function(){var re={};return re[c]=e,re[f]=e,q.call(re,Te,Z.os),K&&!re[c]&&be&&be.platform&&be.platform!="Unknown"&&(re[c]=be.platform.replace(/chrome os/i,U).replace(/macos/i,ee)),re},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return Te},this.setUA=function(re){return Te=typeof re===a&&re.length>500?G(re,500):re,this},this.setUA(Te),this};ce.VERSION="1.0.40",ce.BROWSER=$([c,f,s]),ce.CPU=$([v]),ce.DEVICE=$([o,l,h,p,_,d,m,u,b]),ce.ENGINE=ce.OS=$([c,f]),fa.exports&&(ma=fa.exports=ce),ma.UAParser=ce;var Y=typeof i!==n&&(i.jQuery||i.Zepto);if(Y&&!Y.ua){var fe=new ce;Y.ua=fe.getResult(),Y.ua.get=function(){return fe.getUA()},Y.ua.set=function(he){fe.setUA(he);var pe=fe.getResult();for(var ue in pe)Y.ua[ue]=pe[ue]}}}(typeof window=="object"?window:Ko);var um=ga.exports,Ht=(i=>(i.KEEPALIVE="keepalive",i.JOINCHANNEL="joinchannel",i.NOTIFYJOIN="notifyjoin",i.NOTIFYSTATUS="notifystatus",i.STATUSREPORT="statusreport",i.LEAVECHANNEL="leavechannel",i.NOTIFYLEAVE="notifyleave",i.NOTIFYPUBLISH="notifypublish",i.BYE="bye",i.RECONNECT="reconnect",i.PUBLISH="publish",i.REFRESHURL="refreshurl",i.UNSUBSCRIBE="unsubscribe",i.ROLEUPDATE="roleupdate",i))(Ht||{});class Zo{constructor(e,t){V(this,"authInfo"),V(this,"userName"),V(this,"seqIndex",0),this.authInfo=e,this.userName=typeof t=="number"?t.toString():t}get roleAuth(){if(this.authInfo.role){const{timestamp:e,nonce:t,token:n,role:r}=this.authInfo;return{timestamp:e,nonce:t,token:n,tokenrole:r}}}static get adaptInfo(){var e,t,n,r;let a=new um.UAParser().getResult();return{os_name:((e=a.os.name)==null?void 0:e.replace(" ",""))+"_"+((t=a.browser.name)==null?void 0:t.replace(" ","")),device_name:((n=a.device.model)==null?void 0:n.replace(" ",""))||"",brand_name:((r=a.device.vendor)==null?void 0:r.replace(" ",""))||"",device_key:window.navigator.userAgent,os_version:a.browser.version||"",sdk_version:"7.2.4",version:"v1"}}refreshAuthInfo(e){this.authInfo=e}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(e){let t=this.createBaseSendPackage("joinchannel");return t.header.displayName=this.userName,t.header.clientversion=kt.getVersionNumber().toString(),t.header.platform="web",this.roleAuth&&(t.data.auth=this.roleAuth),t.data.adapt=Zo.adaptInfo,e&&(t.data=Ze(Ze({},t.data),e)),t}createLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(e){let t=this.createBaseSendPackage("statusreport");return t.header.displayName=this.userName,t.data.status=e,t}createPublishPackage(){let e=this.createBaseSendPackage("publish");return e.data.users=[{}],this.roleAuth&&(e.data.auth=this.roleAuth),e}createRoleUpdatePackage(){let e=this.createBaseSendPackage("roleupdate");return e.header.displayName=this.userName,e}createReconnectPackage(e){let t=this.createBaseSendPackage("reconnect");return t.header.displayName=this.userName,t.header.clientversion=kt.getVersionNumber().toString(),t.header.platform="web",t.data=Ze(Ze({},t.data),e??{}),this.roleAuth&&(t.data.auth=this.roleAuth),t}createRefreshUrlPackage(){let e=this.createBaseSendPackage("refreshurl");return e.header.displayName=this.userName,e}createResponsePackage(e,t){return{version:1,code:200,tid:e,msgtype:t}}createBaseSendPackage(e){var t;return++this.seqIndex,{version:1,msgtype:e,tid:Ai(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(t=this.authInfo.sessionId)!=null?t:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}const ld="ALI_RTC_SDK_ALLOCATE_RESULT",ud=class ea{constructor(e,t,n){V(this,"result",null),V(this,"pms");let r=localStorage.getItem(ld);if(r){const _=JSON.parse(r);_.appId===t.appId&&_.expireTs-3e5>Date.now()?this.result=_.allocatedData:Re.info(`[${ea.logName}]`,"allocate","cached data is invalid")}const{appId:a,channelId:s,sessionId:o,userId:c,timestamp:h,token:l,nonce:f}=t,v=new URLSearchParams({appid:a,channelid:s,session:o,userid:c,timestamp:`${h}`,token:l,nonce:f??"",adapt:"true",clitype:"2"});n&&v.set("joinmode",n);const p=e===qi.pre?Vn.pre:Vn.prod;this.pms=fetch(`https://${p}/gslb/v1/allocate?${v.toString()}`,{method:"POST",body:JSON.stringify(Zo.adaptInfo)}).then(_=>_.json()).then(_=>{if(_.code===0){const m=_.data;this.result=m;const{ice_ufrag:d}=m.h5auth,[u,b]=atob(d).split("_"),y={appId:a,expireTs:1e3*parseInt(b),allocatedData:m};return Re.info(`[${ea.logName}]`,"got allocate result and save",m.h5auth.ice_ufrag),localStorage.setItem(ld,JSON.stringify(y)),m}return null}).catch(_=>(Re.error(`[${ea.logName}]`,"allocate",_),null))}};V(ud,"logName","Allocator");let va=ud;class _a{constructor(e,t){V(this,"originTrack"),V(this,"originVideo"),V(this,"targetWidth"),V(this,"targetHeight"),V(this,"targetFrameRate"),V(this,"targetCanvas"),V(this,"animationFrameId"),V(this,"resultTrack"),this.targetWidth=t.width,this.targetHeight=t.height,this.targetFrameRate=t.frameRate,this.originTrack=e,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(e){this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(e,t,n,r){const a=t/e,s=r/n;let o=n,c=r,h=0,l=0;return s>a?(o=Math.round(c/a),h=Math.round((n-o)/2)):s<a&&(c=Math.round(o*a),l=Math.round((r-c)/2)),{x:h,y:l,width:o,height:c}}}class dm extends _a{constructor(e,t){super(e,t),V(this,"targetCtx"),this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}function dd(i,e,t){const n=i.createShader(e);if(n)return i.shaderSource(n,t),i.compileShader(n),i.getShaderParameter(n,i.COMPILE_STATUS)?n:(console.error(`An error occurred compiling the shaders: ${i.getShaderInfoLog(n)}`),i.deleteShader(n),null);console.error("create shader failed")}class hd extends _a{constructor(e,t){super(e,t),V(this,"targetCtx"),V(this,"targetTexture"),V(this,"locationMap"),this.targetCtx=this.targetCanvas.getContext("webgl2"),this.locationMap={},this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.updateBuffer=this.updateBuffer.bind(this),this.initGL(),this.initStream(e)}static isSupport(){return function(){let e;try{const t=document.createElement("canvas");t.width=1,t.height=1;const n={alpha:!1,depth:!1,stencil:!1,antialias:!1,preferLowPowerToHighPerformance:!0};e=t.getContext("webgl2",n)}catch{return!1}return!!e}()}initGL(){const e=this.targetCtx;if(!e)return;this.targetTexture=function(o){const c=o.createTexture();return o.bindTexture(o.TEXTURE_2D,c),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),c}(e);const t=function(o,c,h){const l=dd(o,o.VERTEX_SHADER,c),f=dd(o,o.FRAGMENT_SHADER,h),v=o.createProgram();if(v&&l&&f)return o.attachShader(v,l),o.attachShader(v,f),o.linkProgram(v),o.getProgramParameter(v,o.LINK_STATUS)?v:(console.error(`Unable to initialize the shader program: ${o.getProgramInfoLog(v)}`),null)}(e,`
attribute vec2 a_position;
attribute vec2 a_texCoord;

uniform vec2 u_resolution;
varying vec2 v_texCoord;

void main() {
  // convert the rectangle from pixels to 0.0 to 1.0
  vec2 zeroToOne = a_position / u_resolution;

  // convert from 0->1 to 0->2
  vec2 zeroToTwo = zeroToOne * 2.0;

  // convert from 0->2 to -1->+1 (clipspace)
  vec2 clipSpace = zeroToTwo - 1.0;

  gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);

  v_texCoord = a_texCoord;
}
`,`
precision mediump float;

varying lowp vec2 v_texCoord;
uniform sampler2D u_texture;

void main() {
  gl_FragColor = texture2D(u_texture, v_texCoord);
}
`);if(!t)return void console.log("[ScalerWebGL] program is null.");e.useProgram(t);const n=e.getAttribLocation(t,"a_position"),r=e.getAttribLocation(t,"a_texCoord"),a=e.getUniformLocation(t,"u_resolution");if(!a)return void console.log("[ScalerWebGL] resolutionLocation is null.");const s=e.getUniformLocation(t,"u_texture");s?(this.locationMap={program:t,positionLocation:n,texCoordLocation:r,resolutionLocation:a,textureLocation:s},this.updateBuffer()):console.log("[ScalerWebGL] textureLocation is null.")}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender),this.originVideo.addEventListener("resize",this.updateBuffer)}startRender(){this.cancelAnimation();const e=()=>{this.targetCtx&&(this.renderTexture(),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e)))};e()}updateBuffer(){const e=this.targetCtx,t=this.locationMap.positionLocation,n=this.locationMap.texCoordLocation,r=this.locationMap.resolutionLocation;if(!e||!this.originVideo.videoWidth||!this.originVideo.videoHeight)return;const a=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight),s=function(c,h,l,f=0,v=0){const p=c.createBuffer();c.bindBuffer(c.ARRAY_BUFFER,p);const _=h+f,m=l+v,d=[f,v,_,v,f,m,f,m,_,v,_,m];return c.bufferData(c.ARRAY_BUFFER,new Float32Array(d),c.STATIC_DRAW),p}(e,a.width,a.height,a.x,a.y);e.enableVertexAttribArray(t),e.bindBuffer(e.ARRAY_BUFFER,s),e.vertexAttribPointer(t,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(n);const o=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,o),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,o),e.vertexAttribPointer(n,2,e.FLOAT,!1,0,0),e.uniform2f(r,this.targetWidth,this.targetHeight)}renderTexture(){const e=this.targetTexture,t=this.targetCtx,n=this.locationMap.textureLocation;e&&t&&(t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.originVideo),t.useProgram(this.locationMap.program),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e),t.uniform1i(n,0),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLES,0,6))}stopRender(){this.cancelAnimation()}updateOptions(e){super.updateOptions(e),this.updateBuffer()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.removeEventListener("resize",this.updateBuffer),this.originVideo.pause(),this.originVideo.srcObject=null}}class pd extends _a{constructor(e,t){super(e,t),V(this,"processor"),V(this,"trackGenerator"),V(this,"worker"),this.processor=new MediaStreamTrackProcessor({track:e}),this.trackGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.startTransform()}static isSupport(){return"MediaStreamTrackProcessor"in window&&"MediaStreamTrackGenerator"in window&&"TransformStream"in window&&"VideoFrame"in window}startTransform(){const e=new Blob([`
var targetOptions={
  width: 320,
  height: 180,
  ratio: 0.5625,
  interval: 66,
};
var timer;
var reader;
var writer;

function updateOptions(data) {
  targetOptions.width=data.width||320;
  targetOptions.height=data.height||180;
  targetOptions.ratio=targetOptions.height/targetOptions.width;
  targetOptions.interval=Math.floor(1000/data.frameRate)||66;
}

function postError(err, defaultMsg) {
  var msg=err ? err.message : '';
  postMessage({ type: 'error', messge: msg || defaultMsg });
}

function startLoop(data) {
  if(timer){
    clearInterval(timer);
  }
  timer=setInterval(() => {
    reader.read().then(function (ret){
      var videoFrame=ret.value;
      if(ret.done || !videoFrame) {
        return;
      }

      var vratio=videoFrame.displayHeight/videoFrame.displayWidth;
      var vw=videoFrame.displayWidth;
      var vh=videoFrame.displayHeight;
      var vx=0;
      var vy=0;
      if(targetOptions.ratio>vratio){
        vw=Math.round(vh/targetOptions.ratio);
        vx=Math.round((videoFrame.displayWidth-vw)/2);
      }else if(targetOptions.ratio<vratio){
        vh=Math.round(vw*targetOptions.ratio);
        vy=Math.round((videoFrame.displayHeight-vh)/2);
      }
      var newFrame=new VideoFrame(videoFrame,{
        displayWidth:targetOptions.width,
        displayHeight:targetOptions.height,
        visibleRect:{
          x:vx,
          y:vy,
          width:vw,
          height:vh,
        },
        timestamp:videoFrame.timestamp,
      });

      writer.write(newFrame).catch(function (err){
        postError(err, 'write error');
      });
      videoFrame.close();
    }).catch(function (err){
      postError(err, 'read error');
    });
  }, targetOptions.interval);
}

onmessage = function(evt) {
  var data=evt.data;
  switch (data.type) {
    case 'startRender':
      updateOptions(data);
      reader=data.readable.getReader();
      writer=data.writable.getWriter();
      startLoop(data);
      break;
    case 'updateOptions':
      updateOptions(data);
      startLoop(data);
      break;
    default:
      break;
  }
}
`],{type:"text/javascript"}),t=(window.URL||window.webkitURL).createObjectURL(e);this.worker=new Worker(t);const{readable:n}=this.processor,{writable:r}=this.trackGenerator;this.worker.postMessage({type:"startRender",readable:n,writable:r,width:this.targetWidth,height:this.targetHeight,frameRate:this.targetFrameRate},[n,r])}updateOptions(e){super.updateOptions(e),this.worker&&this.worker.postMessage(Ze({type:"updateOptions"},e))}dispose(){try{this.processor.readable.cancel(),this.trackGenerator.writable.close()}catch{}}getVideoTrack(){return this.trackGenerator}}class Sa{static isSupport(){return typeof HTMLCanvasElement.prototype.captureStream=="function"}static getInstance(e,t){return pd.isSupport()?new pd(e,t):hd.isSupport()?new hd(e,t):new dm(e,t)}}var fd,md,hm=Object.defineProperty,pm=Object.defineProperties,fm=Object.getOwnPropertyDescriptors,gd=Object.getOwnPropertySymbols,mm=Object.prototype.hasOwnProperty,gm=Object.prototype.propertyIsEnumerable,ba=(i,e,t)=>e in i?hm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ya=(i,e)=>{for(var t in e||(e={}))mm.call(e,t)&&ba(i,t,e[t]);if(gd)for(var t of gd(e))gm.call(e,t)&&ba(i,t,e[t]);return i},cr=(i,e,t)=>(ba(i,typeof e!="symbol"?e+"":e,t),t),Ea={exports:{}},Ra={exports:{}};function ci(){if(md)return fd;md=1,Date.now=Date.now||function(){return new Date().getTime()};var i=Date.now(),e=function(){},t={noop:e,warn:function(){var n=typeof console=="object"?console.warn:e;try{var r={warn:n};r.warn.call(r)}catch{return e}return n}(),key:"__bl",selfErrKey:"ARMS_SDK_ERROR",selfErrPage:"ARMSSDK",win:typeof window=="object"&&window.document?window:void 0,regionMap:{cn:"https://arms-retcode.aliyuncs.com/r.png?",sg:"https://arms-retcode-sg.aliyuncs.com/r.png?",sg_2:"https://retcode-sg-lazada.arms.aliyuncs.com/r.png?",daily:"http://arms-retcode-daily.alibaba.net/r.png?",daily_2:"https://arms-retcode-daily.alibaba.net/r.png?",daily_3:"http://arms-retcode-daily.aliyun.test/r.png?",us:"https://retcode-us-west-1.arms.aliyuncs.com/r.png?",tw:"https://arms-retcode.orientalgame.com.tw/r.png?",tw_sg:"https://arms-retcode-sg.orientalgame.com.tw/r.png?",hz_finance:"https://arms-retcode-hz-finance.aliyuncs.com/r.png?"},defaultImgUrl:"https://arms-retcode.aliyuncs.com/r.png?",createObject:function(n){if(Object.create)return Object.create(n);var r=function(){};return r.prototype=n,new r},each:function(n,r){var a=0,s=n.length;if(this.T(n,"Array"))for(;a<s&&r.call(n[a],n[a],a)!==!1;a++);else for(a in n)if(r.call(n[a],n[a],a)===!1)break;return n},safetyCall:function(n,r,a){if(typeof n!="function")return a;try{return n.apply(this,r)}catch{return a}},T:function(n,r){var a=Object.prototype.toString.call(n).substring(8).replace("]","");return r?a===r:a},duration:function(){var n=Date;try{performance&&this.T(performance.now,"Function")&&(n=performance)}catch{n=Date}var r=n.now();return function(){return Math.round(n.now()-r)}},filterByRule:function(){var n=[].slice.call(arguments),r=n.length;if(r<2)return n[0];var a=n[r-1],s=n[0];if(!s)return"";if(!a)return s;var o=this,c=o.T(a),h=n.slice(0,r-1);return c==="Function"?o.safetyCall(a,h,s):c==="Array"?(this.each(a,function(l){h[0]=s=o.filterByRule.apply(o,[].concat(h,l))}),s):c==="Object"?s.replace(a.rule,a.target||""):s.replace(a,"")},ignoreByRule:function(n,r){if(!n||!r)return!1;if((this.isString(r)||r.source||this.T(r)==="Function")&&(r=[r]),!this.isArray(r))return this.warn("[arms] invalid rules of ignore config, (list of) String/RegExp/Funcitons are available"),!1;for(var a,s=[],o=0,c=r.length;o<c;o++)if(a=r[o],this.isString(a))s.push(a.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1"));else if(a&&a.source)s.push(a.source);else if(a&&this.T(a)==="Function"&&this.safetyCall(a,[n],!1)===!0)return!0;var h=new RegExp(s.join("|"),"i");return!!(s.length&&h.test&&h.test(n))},J:function(n){if(!n||typeof n!="string")return n;var r=null;try{r=JSON.parse(n)}catch{}return r},pick:function(n){return n===1||Math.ceil(Math.random()*n)===1},verifyConfig:function(n){if("sample"in n){var r=n.sample,a=r;r&&/^\d+(\.\d+)?%$/.test(r)&&(a=parseInt(100/parseFloat(r))),0<a&&1>a&&(a=parseInt(1/a)),a>=1&&a<=100?n.sample=a:delete n.sample}return n},on:function(n,r,a,s,o){return n.addEventListener?(o=o||!1,n.addEventListener(r,function c(h){s&&n.removeEventListener(r,c,o),a.call(this,h)},o)):n.attachEvent&&n.attachEvent("on"+r,function c(h){s&&n.detachEvent("on"+r,c),a.call(this,h)}),this},off:function(n,r,a){return a?(n.removeEventListener?n.removeEventListener(r,a):n.detachEvent&&n.detachEvent(r,a),this):this},delay:function(n,r){return r===-1?(n(),null):setTimeout(n,r||0)},ext:function(n){for(var r=1,a=arguments.length;r<a;r++){var s=arguments[r];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(n[o]=s[o])}return n},sub:function(n,r){var a={};return this.each(n,function(s,o){r.indexOf(o)!==-1&&(a[o]=s)}),a},uu:function(){for(var n,r,a=20,s=new Array(a),o=Date.now().toString(36).split("");a-- >0;)r=(n=36*Math.random()|0).toString(36),s[a]=n%3?r:r.toUpperCase();for(var c=0;c<8;c++)s.splice(3*c+2,0,o[c]);return s.join("")},guid:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){var r=16*Math.random()|0;return(n==="x"?r:3&r|8).toString(16)})},seq:function(){return(i++).toString(36)},decode:function(n){try{n=decodeURIComponent(n)}catch{}return n},encode:function(n,r){try{n=r?encodeURIComponent(n).replace(/\(/g,"%28").replace(/\)/g,"%29"):encodeURIComponent(n)}catch{}return n},serialize:function(n){n=n||{};var r=[];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&n[a]!==void 0&&r.push(a+"="+this.encode(n[a],a==="msg"));return r.join("&")},checkAPI:function(n,r){if(!n||typeof n!="string")return!1;var a=/arms-retcode[\w-]*\.aliyuncs/.test(n);return!a&&r&&(a=/(alicdn\.com)|(mmstat\.com)/.test(n)),!a},checkAutoError:function(n){return!(!n||!n.message||/failed[\w\s]+fetch/i.test(n.message))},cutUrlSearch:function(n){return n&&typeof n=="string"?n.replace(/^(https?:)?\/\//,"").replace(/\?.*$/,""):""},removeUrlSearch:function(n){return n&&typeof n=="string"?n.replace(/\?.*$/,""):""},createFakeToString:function(n){return function(){return n+"() { [native code] }"}},checkSameOrigin:function(n,r){if(!r||!n)return!1;var a="//"+r.split("/")[2];return n===r||n.slice(0,r.length+1)===r+"/"||n===a||n.slice(0,a.length+1)===a+"/"||!/^(\/\/|http:|https:).*/.test(n)},getRandIP:function(){for(var n=[],r=0;r<4;r++){var a=Math.floor(256*Math.random());n[r]=(a>15?"":"0")+a.toString(16)}return n.join("").replace(/^0/,"1")},getSortNum:function(n){return n?(n+=1)>=1e3&&n<=9999?n:n<1e3?n+1e3:n%1e4+1e3:1e3},getRandNum:function(n){return n&&typeof n=="string"?n.length<5?this.getNum(5):n.substring(n.length-5):this.getNum(5)},getNum:function(n){for(var r=[],a=0;a<n;a++){var s=Math.floor(16*Math.random());r[a]=s.toString(16)}return r.join("")},getCurDomain:function(){return location&&location.hostname||""},getSrcType:function(n,r){var a=location&&location.host||"";if(!a)return"";var s=new URL(n).host;if(s===a)return"self";for(var o=0;o<r.length;o+=1)if(s.includes(r[o]))return"cdn";return"others"},parseFetchHeaders:function(n){if(!n)return{};var r={};try{if(typeof n.keys=="function")for(var a=n.keys(),s=a.next();!s.done;){var o=s.value;r[o]=n.get(o),s=a.next()}else r=n}catch{r={}}return r},parseXhrHeaders:function(n){if(!n&&typeof n!="string")return{};var r={};try{r=n.split(`\r
`).reduce(function(a,s){var o=s.split(": ");return a[o[0]]=o[1],a},{})}catch{r={}}return r},getQuerys:function(n){if(!n)return"";var r={},a=[],s="",o="";try{var c=[];if(n.indexOf("?")>=0&&(c=n.substring(n.indexOf("?")+1,n.length).split("&")),c.length>0)for(var h in c)s=(a=c[h].split("="))[0],o=a[1],r[s]=o}catch{r={}}return r},getURL:function(n){if(!n)return null;var r={},a=n.length,s=n.indexOf("://");if(s<0)return null;r.protocol=n.substring(0,s+1);var o=n.indexOf("#"),c=n.indexOf("?");o<0&&(o=a),c<0&&(c=o),r.search=n.substring(c,o).substring(0,1e3);var h=n.substring(s+3,c),l=h.indexOf("/");return l<0&&(l=h.length),r.domain=h.substring(0,l).split(":")[0],r.path=h.substring(l,h.length).substring(0,1e3),r},getResType:function(n,r){if(["script","img","other"].indexOf(n)>-1)return n;if(["video"].indexOf(n)>-1)return"media";if(["document","iframe"].indexOf(n)>-1)return"doc";var a=r?this.getURL(r):null,s=a&&a.path?a.path.lastIndexOf("."):-1,o=(s>0?a.path.substr(s+1):"").toLowerCase();if(o){if(["eot","woff","woff2","ttf"].indexOf(o)>-1)return"font";if(o==="css")return"css";if(o==="js")return"script"}return["fetch","xmlhttprequest","beacon"].indexOf(n)>-1?"api":"others"},areInOrder:function(){for(var n=1;n<arguments.length;n+=1)if(arguments[n-1]>arguments[n])return!1;return!0},getFetchSnapshot:function(n,r,a){var s,o;try{var c=(n&&typeof n[0]!="string"?n[0].url:n[0])||"",h=(n&&typeof n[0]!="string"?n[0]:n[1])||{},l=h.method.toUpperCase()==="POST"?h.body:this.getQuerys(c);s={originApi:c,method:h.method||"unknown",params:l,response:r||"",reqHeaders:this.parseFetchHeaders(h.headers||null),resHeaders:this.parseFetchHeaders(a)},o=JSON&&JSON.stringify(s)||"{}"}catch{o="{}"}return o},getXhrSnapshot:function(n,r,a){if(!n||!r||!a)return{};var s,o;try{var c="";a.responseType===""||a.responseType==="text"?c=a.responseText:a.responseType==="document"&&(c=a.responseXML),s={originApi:n,method:r,params:this.getQuerys(n),response:c,reqHeaders:{},resHeaders:this.parseXhrHeaders(typeof a.getAllResponseHeaders=="function"&&a.getAllResponseHeaders()||"")},o=JSON&&JSON.stringify(s)||"{}"}catch{o="{}"}return o},isRobot:function(){var n=["nuhk","googlebot/","googlebot-image","yammybot","openbot","slurp","msnbot","ask jeeves/teoma","ia_archiver","baiduspider","bingbot/","adsbot"];if(!navigator||typeof navigator.userAgent!="string")return!1;try{for(var r=navigator.userAgent.toLowerCase(),a=0;a<n.length;a++){var s=n[a];if(r.lastIndexOf(s)>=0)return!0}}catch{this.warn("[arms] useragent parse error")}return!1},isFunction:function(n){return typeof n=="function"},isPlainObject:function(n){return Object.prototype.toString.call(n)==="[object Object]"},isString:function(n){return Object.prototype.toString.call(n)==="[object String]"},isArray:function(n){return Object.prototype.toString.call(n)==="[object Array]"},joinRegExp:function(n){for(var r,a=[],s=0,o=n.length;s<o;s++)r=n[s],this.isString(r)?a.push(r.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):r&&r.source&&a.push(r.source);return new RegExp(a.join("|"),"i")},reWriteMethod:function(n,r,a){if(n!==null){var s=n[r];n[r]=a(s)}},checkSDKError:function(n,r){return!(!n&&!r)&&(!!new RegExp(this.selfErrKey,"i").test(n)||!!this.ignoreByRule(r,[/retcode.alicdn.com\/retcode\/bl.js/,/g.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/laz-g-cdn.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/local.taobao.com:8880\/build\/bl/]))},sdkError:function(n){return{msg:n,message:this.selfErrKey}},dealParam:function(n,r,a){var s={};try{s=this.isPlainObject(n)?this.ext({key:n.key||"default",val:n.val||n.value||a},n,{begin:Date.now()}):{key:n||"default",val:r||a,begin:Date.now()}}catch(o){this.warn("[retcode] baseLog error: "+o)}return s}};return fd=t}var vd,_d,Sd,bd,Ta={exports:{}},Aa={exports:{}};function vm(){if(Sd)return Aa.exports;Sd=1;var i=ci(),e=function(){if(_d)return vd;_d=1;var a=ci();return vd=function(s,o,c){typeof s=="object"&&(s=a.serialize(s));var h=o+s+(c?"&post_res=":"");window&&window.navigator&&typeof window.navigator.sendBeacon=="function"?window.navigator.sendBeacon(h,c||"&post_res="):a.warn("[arms] navigator.sendBeacon not surported")}}(),t="aokcdqn3ly@e629dabd48a9933",n=function(a,s){var o;if(s.t==="error"&&(o=a.requestQueue[0])&&o.t==="error"&&s.msg===o.msg)return s.times=o.times+1,void(a.requestQueue[0]=s);if(s.t==="behavior"){var c=a.requestQueue&&a.requestQueue.length;if(c>0&&a.requestQueue[c-1].t==="behavior"){var h=s.behavior||[];a.requestQueue[c-1].behavior.concat(h)}else a.requestQueue.push(s)}else a.requestQueue.unshift(s);return a.onReady(function(){a.requestTimmer=i.delay(function(){a.clear()},a.requestQueue[0]&&a.requestQueue[0].t==="error"?3e3:-1)}),!0},r=function(a){return this.ver="1.8.36-beta.12",this._conf=i.ext({},r.dftCon),this.sampleCache={},this.requestQueue=[],this.selfQueue=[],this.sdkFlag=!0,this.hash=i.seq(),this.resetPageview(),this.setConfig(a),this.rip=i.getRandIP(),this.record=999,this["EagleEye-TraceID"]=this.getTraceId()["EagleEye-TraceID"],this._common={},this};return r.dftCon={sample:1,pvSample:1,tag:"",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",region:null,ignore:{ignoreUrls:[],ignoreApis:[],ignoreErrors:[/^Script error\.?$/],ignoreResErrors:[],ignoreResources:[/\/(bl|wl)(.debug)?.js$/]},release:void 0,environment:"prod",beforeReport:null,parseTraceId:null},r.prototype={constructor:r,onReady:function(a){return a()},getPage:function(){var a=this._conf.page;return i.safetyCall(a,[],a+"")},setPage:function(){},setConfig:function(a){a&&typeof a=="object"&&(i.verifyConfig(a),a=this.setImgUrl(a),this._conf=i.ext({},this._conf,a))},setImgUrl:function(a){var s=a.region,o=a.imgUrl;if(s){var c=i.regionMap[s];return a.imgUrl=c||i.defaultImgUrl,a}return o&&(a.imgUrl=o),a},checkImgUrl:function(){return!0},sendRequest:function(){},sendBeacon:function(a,s,o){e(a,s||this.getConfig("imgUrl"),o)},postData:function(){},commonInfo:function(){return{}},setCommonInfo:function(a){a&&typeof a=="object"&&(this._common=i.ext({},this._common,a))},resetPageview:function(){this.pageview=i.uu(),this.sBegin=Date.now()},getUsername:function(){if(this.username)return this.username;var a=this._conf,s=a&&a.setUsername;if(typeof s=="function")try{var o=s();typeof o=="string"&&(o=o.substr(0,40),this.username=o)}catch(c){i.warn("[arms] setUsername fail",c)}return this.username},getTraceId:function(){var a=this.rip,s=Date.now(),o=i.getSortNum(this.record),c=a+s+o+i.getRandNum(this._conf.pid);return this["EagleEye-TraceID"]=c,this.record=o,{"EagleEye-TraceID":c}},getUberTraceId:function(a){var s=this.rip,o=Date.now(),c=i.getSortNum(this.record),h=i.getRandNum(this._conf.pid),l=s+o+c+i.getNum(2)+h,f=l.substring(0,16);return a=a?"1":"0",l[0]==="0"&&(l[0]="1"),l[16]==="0"&&(l[16]="1"),{"uber-trace-id":l+":"+f+":0:"+a,traceId:l}},getB3TraceId:function(a){var s=this.rip,o=Date.now(),c=i.getSortNum(this.record),h=i.getRandNum(this._conf.pid),l=s+o+c+i.getNum(2)+h,f=l.substring(0,16);return a=a?"1":"0",l[0]==="0"&&(l[0]="1"),l[16]==="0"&&(l[16]="1"),{b3:l+"-"+f+"-"+a+"-0","X-B3-TraceId":l,"X-B3-ParentSpanId":"0","X-B3-SpanId":f,"X-B3-Sampled":a}},getPageviewId:function(){return{"EagleEye-SessionID":this.pageview}},getConfig:function(a){return a?this._conf[a]:i.ext({},this._conf)},sampling:function(a){return a===1||(typeof this.sampleCache[a]=="boolean"||(this.sampleCache[a]=i.pick(a)),this.sampleCache[a])},clear:function(a){var s;clearTimeout(this.requestTimmer),this.requestTimmer=null;for(var o=this._conf&&typeof this._conf.sendRequest=="function";s=this.requestQueue.pop();)if(s.t==="res")this.postData(s,"res");else if(s.t==="error")this.postData(s,"err");else if(s.t==="api")this.postData(s,"apiSnapshot");else if(s.t==="behavior")this.postData(s,"behavior");else if(s.t==="health"&&!o&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function")this.sendBeacon(s);else if(s.t==="resource"&&!o&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function"){var c=JSON.stringify({resource:s.resource});delete s.resource,this.sendBeacon(s,null,c)}else s.t==="resource"?this.postData(s,"resource"):this.sendRequest(s);return a&&this.clearSelf(),this},clearSelf:function(){var a;for(clearTimeout(this.Timmer),this.Timmer=null;a=this.selfQueue.pop();)this.postData(a,"err");return this},_lg:function(a,s,o,c){var h=this,l=h._conf,f=h.getPage(),v=l.ignore||{},p=v.ignoreErrors,_=v.ignoreResErrors,m=v.ignoreUrls,d=v.ignoreApis;if(h._isRobot||i.ignoreByRule(f,m)||i.ignoreByRule(i.decode(f),m)||a==="error"&&(i.ignoreByRule(s.msg,p)||i.ignoreByRule(i.decode(s.msg),p))||a==="resourceError"&&(i.ignoreByRule(s.src,_)||i.ignoreByRule(i.decode(s.src),_))||a==="api"&&(i.ignoreByRule(s.api,d)||i.ignoreByRule(i.decode(s.api),d))||!h.checkImgUrl(l.imgUrl)||!s||l.disabled||!l.pid||c===0)return h;var u=s.dl;if(delete s.dl,s=i.ext({t:a,times:1,page:f,tag:l.tag||"",release:l.release||"",environment:l.environment,begin:Date.now(),c1:l.c1,c2:l.c2,c3:l.c3},s,h.commonInfo(),h._common,{pid:l.pid,_v:h.ver,pv_id:h.pageview,username:h.getUsername(),sampling:o||1,dl:u,z:i.seq()}),i.T(l.beforeReport)==="Function")try{if(!(s=l.beforeReport(s)))return h}catch{return h}return c===1?n(h,s):o&&!h.sampling(o)?h:n(h,s)},_self:function(a,s,o){var c=this,h=c._conf;if(a!=="error"||!c.checkImgUrl(h.imgUrl)||!s||h.disabled||!h.pid||o&&!c.sampling(o))return c;s=i.ext({t:a,times:1,page:i.selfErrPage,tag:h.pid,begin:Date.now()},s,{pid:t,_v:c.ver,sampling:o||1,z:i.seq()});var l=c.selfQueue[0];if(l){l.times++;try{l.err&&s.err&&l.err.msg_raw&&s.err.msg_raw&&l.err.msg_raw.split("&").indexOf(s.err.msg_raw)<0&&l.err.msg_raw.length<1e3&&(l.err.msg_raw+="&"+s.err.msg_raw)}catch{}}else c.selfQueue.unshift(s),c.onReady(function(){c.sdkFlag&&(c.sdkFlag=!1,c.Timmer=i.delay(function(){c.clearSelf()},1e4))})},custom:function(a,s){if(!a||typeof a!="object")return this;var o=!1,c={begin:Date.now()};return i.each(a,function(h,l){return!(o=l&&l.length<=20)&&i.warn("[retcode] invalid key: "+l),c["x-"+l]=h,o}),o?this._lg("custom",c,s||1):this}},Aa.exports=r,Aa.exports}var yd,Ca={exports:{}},Ed,wa,Rd,Ma={exports:{}};function _m(){if(Rd)return wa;Rd=1;var i=ci();return wa=function(e,t){var n=[],r=null,a=t&&t.location&&t.location.href,s=void 0,o=null,c=function(f,v,p){if(f!==null){var _=f[v];f[v]=p(_)}},h=function(f){var v,p,_,m,d,u=[];if(!f||typeof f.tagName!="string")return"";if(u.push(f.tagName.toLowerCase()),typeof f.id=="string"&&u.push("#".concat(f.id)),typeof(v=f.className)=="string")for(p=v.split(/\s+/),d=0;d<p.length;d++)u.push(".".concat(p[d]));var b=["type","name","title","alt","data-arms-attr"];for(d=0;d<b.length;d++)_=b[d],typeof(m=f.getAttribute(_))=="string"&&u.push("[".concat(_,'="').concat(m,'"]'));return u.join("")},l=function(f,v){return function(p){if(p&&p!==o){var _;o=p;try{_=p.target}catch{_="<unknown>"}if(_.length!==0){var m={type:"ui.".concat(f),data:{message:function(d){if(!d||d.nodeType!==1)return"";for(var u=d||null,b=[],y=0,g=0,S="";u&&y++<5&&!((S=h(u))==="html"||y>1&&g+3*b.length+S.length>=80);)b.push(S),g+=S.length,u=u.parentNode;return b.reverse().join(" > ")}(_)},timestamp:Date.now()};f==="click"?r&&r.addBehavior(m):f==="keypress"&&(s||r&&r.addBehavior(m),clearTimeout(s),s=setTimeout(function(){s=void 0},100))}}}};i.ext(e.prototype,{addBehavior:function(f){if(this.getConfig("behavior")&&f&&typeof f=="object"){var v={},p=f.data||{};if(f.type)v=p;else{if(typeof p.name!="string"||typeof p.message!="string")return;v.name=p.name.substr(0,20),v.message=p.message.substr(0,200)}v.message&&(v.message=i.encode(v.message));var _={type:f.type||"custom",data:v||{},timestamp:f.timestamp||Date.now(),page:f.page||t&&t.location&&t.location.pathname};return n.push(_),n=n.slice(-100)}},getBehavior:function(){return n||[]},setBehavior:function(f){return f&&(n=f),n},reportBehavior:function(f){var v=this;v.getConfig("behavior")&&(v.sendBhTimer&&(clearTimeout(v.sendBhTimer),v.sendBhTimer=void 0),v.sendBhTimer=setTimeout(function(){n&&n.length>0&&(v.behavior(n),n=[],v.sendBhTimer=void 0,f&&typeof f=="function"&&f())},0))},initBehavior:function(){if(!this.hasInitBehavior&&!r){try{(function(){if(document&&document.referrer&&document.location){var v=document.referrer,p=document.location.href;if(v!==""){var _={type:"navigation",data:{from:v,to:p}};a=p,r&&r.addBehavior(_)}}})(),t&&t.document&&t.document.addEventListener&&(t.document.addEventListener("click",l("click"),!1),t.document.addEventListener("keypress",l("keypress"),!1)),function(){if(function(){var m=t&&t.chrome,d=m&&m.app&&m.app.runtime,u="history"in t&&!!t.history.pushState&&!!t.history.replaceState;return!d&&u}()){var v=function(m,d){var u={type:"navigation",data:{from:m,to:d}};r&&r.addBehavior(u),a=d},p=t.onpopstate;t.onpopstate=function(){for(var m=arguments.length,d=new Array(m),u=0;u<m;u++)d[u]=arguments[u];var b=t.location.href;if(v(a,b),p)return p.apply(this,d)};var _=function(m){return function(){for(var d=arguments.length,u=new Array(d),b=0;b<d;b++)u[b]=arguments[b];var y=u.length>2?u[2]:void 0;return y&&v(a,String(y)),m.apply(this,u)}};c(t.history,"pushState",_),c(t.history,"replaceState",_)}}();var f=this.getConfig("enableConsole");f&&function(v){if(t&&t.console){var p=["debug","info","warn","log","error","assert"];i.isArray(v)&&(p=v);for(var _=0;_<p.length;_++){var m=p[_];m&&i.isString(m)&&t.console[m]&&typeof t.console[m]=="function"&&c(t.console,m,function(d){var u=m;return function(){for(var b=arguments.length,y=new Array(b),g=0;g<b;g++)y[g]=arguments[g];var S={type:"console",data:{level:u,message:y}};if(r&&r.addBehavior(S),u==="error")for(var R=0;R<y.length;R++){var E=y[R];E&&E.message&&E.stack&&r&&r.errorHandler(new ErrorEvent("error",{error:E,message:E.message}))}d&&Function.prototype.apply.call(d,t.console,y)}})}}}(f)}catch(v){i.warn("[arms] error in initBehavior",v)}r=this,this.hasInitBehavior=!0}return this}})},wa}var Td,xa,Ad,Ia,Cd,wd,Md,Pa,xd,Id,Pd,Dd,Ld,Da,Od,Nd,kd,Ud={};function La(){return Td||(Td=1,Ud.TIMING_KEYS=["startTime","fetchStart","domainLookupStart","domainLookupEnd","connectStart","connectEnd","requestStart","responseStart","responseEnd","","domInteractive","","domContentLoadedEventEnd","","loadEventStart","","msFirstPaint","secureConnectionStart","redirectStart","redirectEnd"]),Ud}function Sm(){return Md||(Md=1,wd=function(i,e,t){var n=ci(),r=function(){if(Ad)return xa;Ad=1;var m=ci(),d=La().TIMING_KEYS;return xa=function(){var u=m.win||{},b=u.performance;if(!b||typeof b!="object"||typeof b.getEntriesByType!="function")return null;var y={},g=b.timing||{},S=b.getEntriesByType("resource")||[];if(y.begin=g[d[1]]||Date.now(),typeof u.PerformanceNavigationTiming=="function"){var R=b.getEntriesByType("navigation")[0];R&&(g=R)}return m.each({dom:[10,8],load:[14,1]},function(E,I){var C=g[d[E[1]]],A=g[d[E[0]]];if(C>0&&A>0){var w=Math.round(A-C);w>=0&&w<6e5&&(y[I]=w)}}),y.res=JSON.stringify(S),y},xa}(),a=function(){if(Cd)return Ia;Cd=1;var m=ci(),d=La().TIMING_KEYS;return Ia=function(){var u=m.win||{},b=u.performance;if(!b||typeof b!="object")return null;var y={},g=b.timing||{},S=Date.now(),R=1;if(typeof u.PerformanceNavigationTiming=="function"){var E=b.getEntriesByType("navigation")[0];E&&(g=E,R=2)}m.each({dns:[3,2],tcp:[5,4],ssl:[5,17],ttfb:[7,6],trans:[8,7],dom:[10,8],res:[14,12],firstbyte:[7,2],fpt:[8,1],tti:[10,1],ready:[12,1],load:[14,1]},function(N,M){var D=g[d[N[1]]],L=g[d[N[0]]];if(R===2||D>0&&L>0){var P=Math.round(L-D);P>=0&&P<6e5&&(y[M]=P)}});var I=u.navigator.connection,C=b.navigation||{};y.ct=I?I.effectiveType||I.type:"";var A=I&&(I.downlink||I.downlinkMax||I.bandwidth)||null;if((A=A>999?999:A)&&(y.bandwidth=A),y.navtype=C.type===1?"Reload":"Other",R===1&&g[d[16]]>0&&g[d[1]]>0){var w=g[d[16]]-g[d[1]];w>=0&&w<36e5&&(y.fpt=w)}return R===1&&g[d[1]]>0?y.begin=g[d[1]]:R===2&&y.load>0?y.begin=S-y.load:y.begin=S,y},Ia}(),s=null,o=t.documentElement,c=e.innerWidth||o.clientWidth||t.body.clientWidth,h=e.innerHeight||o.clientHeight||t.body.clientHeight,l=e.navigator.connection,f={sr:screen.width+"x"+screen.height,vp:c+"x"+h,ct:l?l.effectiveType||l.type:""},v={},p=function(m,d,u,b,y){if(d===void 0){var g,S;if(!v[m]){g=new RegExp(m+"=([^;]+)");try{S=g.exec(t.cookie)}catch(E){return n.warn("[retcode] can not get cookie:",E),null}S&&(v[m]=S[1])}return v[m]}var R=m+"="+d;R+="; path=/",u&&(R+="; max-age="+u);try{return t.cookie=R,!!t.cookie}catch(E){return n.warn("[retcode] can not set cookie: ",E),!1}},_=function(m){var d=m._conf.uid||p("_nk_")||p("_bl_uid");return d||(d=n.uu(),p("_bl_uid",d,15552e3))?d:null};return n.ext(i.prototype,{activeErrHandler:function(m){return s&&!m||(s=this),this},errorHandler:function(m){if(!m)return this;var d=m.type;if(d==="error"){var u=m.target||m.srcElement;!u||!u.tagName||m.message||m.filename||m.lineno||m.colno?this.error(m.error||{message:m.message},m):this.resourceErrorHandler(m)}else d==="unhandledrejection"&&n.T(m.reason,"Error")&&n.checkAutoError(m.reason)&&this.error(m.reason);try{this.getConfig("behavior")&&this.reportBehavior&&this.reportBehavior()}catch{}return this},resourceErrorHandler:function(m){var d=this,u=m.target||m.srcElement;try{var b=d.getSrc(u),y=typeof u.tagName=="string"?u.tagName.toLowerCase():"",g=d.getXPath(u,5),S=n.getURL(b),R={src:b&&b.substring(0,1e3),node_name:y,xpath:g,res_type:n.getResType(y,b),res_name:S.path,domain:S.domain};return d._conf.enableResource&&d.fixResourceStatus&&m.timeStamp&&d.fixResourceStatus({src:b,node_name:y,res_type:n.getResType(y,b),timeStamp:m.timeStamp,domain:S.domain}),d._lg("resourceError",R),d}catch(E){return n.warn("[ARMS] resourceErrorHandler error :",E),d}},getSrc:function(m){var d=m.src||m.href;try{if(!d){var u=(typeof m.tagName=="string"?m.tagName.toLowerCase():"")==="object",b=m.getAttribute("classid")&&m.getAttribute("classid").toLowerCase()==="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"||m.getAttribute("type")==="application/x-shockwave-flash";u&&b&&(d=m.getAttribute("data")||m.getAttribute("codebase")),d||(d=m.outerHTML||m.innerHTML)}}catch{d=""}return d},getXPath:function(m,d){var u=m.id?"#"+m.id:"",b=typeof m.className=="string"?"."+m.className.split(" ").join("."):"",y=(typeof m.tagName=="string"?m.tagName.toLowerCase():"")+u+b;return m.parentNode&&m.parentNode.tagName&&d-1!=0?this.getXPath(m.parentNode,d-1)+" > "+y:y},sendPerformance:function(m){var d=this;d.onReady(function(){var u=a();u&&u.load&&u.load>0&&(u.page=d.getPage(!0),m&&(u=n.ext(u,m)),u.autoSend=!0,d.performance(u))})},sendResources:function(m){var d=this;d.onReady(function(){var u=r();u&&u.load&&u.load>0&&(u.load&&u.load<=2e3||u.load&&u.load<=8e3&&Math.random()>.05||(u.page=d.getPage(!0),u.dl=location.href,m&&(u=n.ext(u,m)),d._lg("res",u,d.getConfig("sample"))))})},sendPV:function(){var m=this;m.onReady(function(){var d,u,b=(d=_(m),u=e.devicePixelRatio||1,{uid:d,dt:t.title,dl:location.href,dr:t.referrer,dpr:u.toFixed(2),de:(t.characterSet||t.defaultCharset||"").toLowerCase(),ul:o.lang,begin:Date.now()});b&&b.uid&&m._lg("pv",b,m.getConfig("pvSample"))})},commonInfo:function(){return f.uid=_(this),f.sid=function(m){if(m.session)return m.session;var d;try{if(typeof window=="object"&&typeof sessionStorage=="object"&&typeof sessionStorage.getItem=="function")return typeof(d=sessionStorage.getItem("_bl_sid"))=="string"?(m.session=d,d):(d=n.uu(),m.session=d,typeof sessionStorage.setItem=="function"&&sessionStorage.setItem("_bl_sid",d),d)}catch(u){n.warn("[ARMS] getSid error :",u)}return m.session=d=n.uu(),d}(this),f},handleUnload:function(m){var d=Date.now();if(d-this._lastUnload<200)return this;this._lastUnload=d,this.sendHealth(m),this.speedCache&&(this._lg("speed",this.speedCache),this.speedCache=null,clearTimeout(this.speedTimmer)),this._conf&&this._conf.enableResource&&this.resourceComboReport(),this.clear(!0)},bindHashChange:function(m){var d=this;if(!m^d.hashChangeHandler)return d;m?(d.hackHistoryState(),d.hashChangeHandler=function(u){var b=d._conf.parseHash(location.hash);b&&d.setPage(b,u!==!1)},d.stateChangeHandler=function(u){var b=d._conf.parseHash(u.detail);b&&d.setPage(b)},n.on(e,"hashchange",d.hashChangeHandler),n.on(e,"historystatechange",d.stateChangeHandler),d.hashChangeHandler(!1)):(n.off(e,"hashchange",d.hashChangeHandler),n.off(e,"historystatechange",d.stateChangeHandler),d.hashChangeHandler=null,d.stateChangeHandler=null)},initHandler:function(){var m=this;if(m.hasInitHandler)return m;var d=m._conf;return n.on(e,"beforeunload",function(){m.handleUnload(0)}),m.bindHashChange(d.enableSPA),m.activeErrHandler(!1),m.hasInitHandler=!0,m}}),n.on(e,"error",function(m){s&&s.errorHandler(m)},!1,!0).on(e,"unhandledrejection",function(m){s&&s.errorHandler(m)}),i}),wd}function bm(){if(xd)return Pa;xd=1;var i=ci();return Pa=function(e,t,n){function r(l,f,v){var p=0,_=l.tagName;if(_!=="SCRIPT"&&_!=="STYLE"&&_!=="META"&&_!=="HEAD"){var m=l.children?l.children.length:0;if(m>0)for(var d=l.children,u=m-1;u>=0;u--)p+=r(d[u],f+1,p>0);if(p<=0&&!v&&!(l.getBoundingClientRect&&l.getBoundingClientRect().top<s))return 0;p+=1+.5*f}return p}function a(l){for(var f=1;f<l.length;f++)if(l[f].score<l[f-1].score)return l.splice(f,1),a(l);return l}var s=t.innerHeight||0,o=[],c=null,h=0;i.ext(e.prototype,{initFmpObserver:function(l){var f=this;if(!f._conf||!f._conf.useFmp)return null;if(!t.MutationObserver)return i.warn("[retcode] first meaningful paint can not be retrieved"),f.sendPerformance(),null;i.on(t,"beforeunload",function(){f.endObserving(0,!0)});var v=t.MutationObserver;return(c=new v(function(){(function(p){var _=Date.now()-p,m=n.querySelector("body");if(m){var d=0;d+=r(m,1,!1),o.push({score:d,t:_})}else o.push({score:0,t:_})})(f._startTime)})).observe(document,{childList:!0,subtree:!0}),h=1,f.onReady(function(){f.endObserving(l)}),c},endObserving:function(l,f){var v,p,_,m=this;if(c&&h)if(m.fmpTimmer&&(clearTimeout(m.fmpTimmer),m.fmpTimmer=null),f||(v=m._startTime,p=l,(_=Date.now()-v)>p||_-(o&&o.length&&o[o.length-1].t||0)>1e3)){c.disconnect(),h=0,o=a(o);for(var d=null,u=1;u<o.length;u++)if(o[u].t>=o[u-1].t){var b=o[u].score-o[u-1].score;(!d||d.rate<=b)&&(d={t:o[u].t,rate:b})}d&&d.t>0&&d.t<36e5?m.sendPerformance({fmp:d.t}):m.sendPerformance()}else m.fmpTimmer=i.delay(function(){m.endObserving(l)},500)}})},Pa}function ym(){if(Nd)return Ra.exports;Nd=1;var i=ci(),e=function(){if(bd)return Ta.exports;bd=1;var c=ci(),h=vm(),l=["api","success","time","code","msg","trace","traceId","begin","pv_id","sid","seq","domain","flag","apiSnapshot","tag","c1","c2","c3"],f=function(p){var _=(p.key||"default").split("::");return _.length>1?c.ext(p,{group:_[0],key:_[1]}):c.ext(p,{group:"default_group",key:_[0]})},v=function(p){var _;h.call(this,p);try{_=typeof performance=="object"?performance.timing.fetchStart:Date.now()}catch{_=Date.now()}return this._startTime=_,this};return v.prototype=c.createObject(h.prototype),c.ext(h.dftCon,{startTime:null}),c.ext(v.prototype,{constructor:v,_super:h,sum:function(p,_,m){try{var d=c.dealParam(p,_,1);return this._lg("sum",f(d),m)}catch(u){c.warn("[retcode] can not get parseStatData: "+u)}},avg:function(p,_,m){try{var d=c.dealParam(p,_,0);return this._lg("avg",f(d),m)}catch(u){c.warn("[retcode] can not get parseStatData: "+u)}},percent:function(p,_,m,d){try{return this._lg("percent",f({key:p,subkey:_,val:m||0,begin:Date.now()}),d)}catch(u){c.warn("[retcode] can not get parseStatData: "+u)}},msg:function(p,_){if(p&&!(p.length>180))return this.custom({msg:p},_)},error:function(p,_){if(!p)return c.warn("[retcode] invalid param e: "+p),this;arguments.length===1?(typeof p=="string"&&(p={message:p},_={}),typeof p=="object"&&(_=p=p.error||p)):(typeof p=="string"&&(p={message:p}),typeof _!="object"&&(_={}));var m=p.name||"CustomError",d=p.message||"",u=p.stack||"";_=_||{};var b=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"";if(c.checkSDKError(d,_.filename)){var y=/^Script error\.?$/,g=p.msg||p.message;if(c.ignoreByRule(g,y)||c.ignoreByRule(c.decode(g),y))return this;var S={msg:c.selfErrKey,err:{msg_raw:c.encode(p.msg||p.message)}};return this._self("error",S,1)}for(var R={begin:Date.now(),cate:m,msg:d&&d.substring(0,1e3),stack:u&&u.substring(0,1e3),file:c.removeUrlSearch(_.filename||""),line:_.lineno||"",col:_.colno||"",err:{msg_raw:c.encode(d),stack_raw:c.encode(u)},dl:b},E=["tag","c1","c2","c3"],I=0;I<E.length;I++){var C=E[I];_[C]&&(R[C]=_[C])}var A=(this.getConfig("ignore")||{}).ignoreErrors;return c.ignoreByRule(R.msg,A)||c.ignoreByRule(c.decode(R.msg),A)?this:(this.beforeSend&&this.beforeSend("error",R),this._lg("error",R,1))},behavior:function(p){if(p){var _=typeof p=="object"&&p.behavior?p:{behavior:p};return this.beforeSend&&this.beforeSend("behavior",_),this._lg("behavior",_,1)}},api:function(p,_,m,d,u,b,y,g,S,R,E,I,C,A,w,N){if(!p)return c.warn("[retcode] api is null"),this;if(p=typeof p=="string"?{api:p,success:_,time:m,code:d,msg:u,begin:b,traceId:y,pv_id:g,apiSnapshot:S,domain:R,flag:I,tag:C,c1:A,c2:w,c3:N}:c.sub(p,l),!c.checkAPI(p.api,!0))return this;p.code=p.code||"";var M=p.msg||"";if(M=typeof M=="string"?M.substring(0,1e3):M,p.msg=M,p.success=p.success?1:0,p.time=+p.time,p.begin=p.begin,p.traceId=p.traceId||"",p.pv_id=p.pv_id||"",p.domain=p.domain||"",p.flag=p.flag,p.dl=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"",p.apiSnapshot&&(typeof p.apiSnapshot=="object"&&(p.apiSnapshot=JSON.stringify(p.apiSnapshot)),typeof p.apiSnapshot!="string"&&delete p.apiSnapshot,p.apiSnapshot.length>2e3&&(p.apiSnapshot=p.apiSnapshot.substring(0,2e3))),E&&(p.traceOrigin=E),!p.api||isNaN(p.time))return c.warn("[retcode] invalid time or api"),this;var D=(this.getConfig("ignore")||{}).ignoreApis;return c.ignoreByRule(p.api,D)||c.ignoreByRule(c.decode(p.api),D)||p.time<0?this:(this.beforeSend&&this.beforeSend("api",p),this._lg("api",p,p.success&&this.getConfig("sample"),p.flag))},speed:function(p,_,m){var d=this,u=this.getConfig("startTime")||this._startTime;return/^s(\d|1[0])$/.test(p)?(_=typeof _!="number"?Date.now()-u:_>=u?_-u:_,d.speedCache=d.speedCache||{},d.speedCache[p]=_,d.speedCache.begin=u,clearTimeout(d.speedTimmer),d.speedTimmer=setTimeout(function(){m||(d.speedCache.page=d.getPage(!0)),d._lg("speed",d.speedCache),d.speedCache=null},5e3),d):(c.warn("[retcode] invalid point: "+p),d)},performance:function(p){if(p&&typeof p=="object"&&!this.hasSendPerf){var _={},m={},d=this.getConfig("autoSendPerf");if(p.autoSend&&d)return m=c.ext(this.perfData||{},p),this.hasSendPerf=!0,this._lg("perf",m,this.getConfig("sample"));if(p.autoSend&&!d)return delete p.autoSend,this.perfData?(m=c.ext(this.perfData||{},p),this.hasSendPerf=!0,this._lg("perf",m,this.getConfig("sample"))):void(this.perfData=p);for(var u in p)(/^t([1-9]|1[0])$/.test(u)||u==="ctti"||u==="cfpt")&&(_[u]=p[u]);if(p.autoSend===!0||!d&&(d||this.perfData))return p.autoSend!==!0&&d===!1&&this.perfData?(_=c.ext(this.perfData||{},_),this.hasSendPerf=!0,this._lg("perf",_,this.getConfig("sample"))):void 0;this.perfData=c.ext(this.perfData||{},_)}},resource:function(p,_){if(!p||!c.isPlainObject(p))return c.warn("[arms] invalid param data: "+p),this;var m=Object.keys(p),d=["begin","dom","load","res","dl"],u=!1;for(var b in d)if(m.indexOf(d[b])<0){u=!0;break}if(u)return c.warn("[arms] lack param data: "+p),this;var y={begin:p.begin||Date.now(),dom:p.dom||"",load:p.load||"",res:c.isArray(p.res)?JSON.stringify(p.res):JSON.stringify([]),dl:p.dl||""};return this._lg("res",y,_)},event:function(p,_){if(typeof p=="object"&&p&&p.key){var m={},d=["key","success","time","c1","c2","c3"];for(var u in p)d.indexOf(u)>-1&&(m[u]=p[u]);m.success=p.success===!1?0:1,this._lg("event",m,_)}}}),v._super=h,v._root=h,h.Reporter=v,Ta.exports=v,Ta.exports}(),t=function(){if(yd)return Ca.exports;yd=1;var c=ci(),h=typeof window=="object"?window:{},l=h.__oFetch_||h.fetch;return l=typeof l=="function"?l:void 0,Ca.exports=function(f,v){var p=-1;typeof f=="object"&&(p=f.z,f=c.serialize(f));var _=v+f;if(l)return l(_,{method:"HEAD",mode:"no-cors"}).catch(c.noop);if(h.document&&h.document.createElement){var m="__request_hold_"+p,d=h[m]=new Image;d.onload=d.onerror=function(){h[m]=void 0},d.src=_,d=null}},Ca.exports}(),n=function(){if(Ed)return Ma.exports;Ed=1;var c=ci(),h=typeof window=="object"?window:{},l=h.__oXMLHttpRequest_||h.XMLHttpRequest;return l=typeof l=="function"?l:void 0,Ma.exports=function(f,v){try{var p=new l;p.open("POST",v,!0),p.setRequestHeader("Content-Type","text/plain"),p.send(JSON.stringify(f))}catch(_){c.warn(`[retcode] Failed to log, exception is :
`+_)}},Ma.exports}(),r=i.win,a=r.document,s=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,o=function(c){var h=this;return e.call(h,c),h._initialPage=c.page&&i.safetyCall(c.page,[],c.page+"")||null,h._isRobot=i.isRobot(),h._health={errcount:0,apisucc:0,apifail:0},h.beforeSend=function(l,f){l==="error"?h._health.errcount++:l==="api"&&h._health[f.success?"apisucc":"apifail"]++},c.enableInstanceAutoSend!==!1&&(h.initHandler(),h.initHook(),h.initFmpObserver(1e4),h._conf&&h._conf.behavior&&typeof h.initBehavior=="function"&&h.initBehavior(),h._conf&&h._conf.enableResource&&typeof h.initResource=="function"&&h.initResource()),Object.defineProperty&&r.addEventListener&&Object.defineProperty(h,"pipe",{set:h.sendPipe}),h};return o.prototype=i.createObject(e.prototype),i.ext(e._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],resourceHelper:[],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",cdnHostList:[],resourceTypes:["css","script","img","font"],resourceSlow:2e3,disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(c){return(c?i.cutUrlSearch(c.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(c){if(!c||typeof c!="object")return{};var h=c.code,l=c.msg||c.message||c.subMsg||c.errorMsg||c.ret||c.errorResponse||"";return typeof l=="object"&&(h=h||l.code,l=l.msg||l.message||l.info||l.ret||JSON.stringify(l)),{msg:l,code:h,success:!0}}}),i.ext(o.prototype,{constructor:o,_super:e,onReady:function(c){var h=this;if(h.hasReady)return c();a.readyState==="complete"?(h.hasReady=!0,c()):i.on(r,"load",function(){h.hasReady=!0,c()},!0)},getPage:function(c){var h=this._conf,l=h.page,f=location,v=f.host+f.pathname;return l&&!c?i.safetyCall(l,[],l+""):this._initialPage||i.filterByRule(h.ignoreUrlCase?v.toLowerCase():v,f.href,h.ignoreUrlPath?h.ignoreUrlPath:h.urlHelper)},setPage:function(c,h){var l=this,f=l.prevPage;if(h!==!1){if(!c||c===f)return l;l.prevPage=c,clearTimeout(l.sendPVTimmer),l.handleUnload(1),l.resetPageview(),l.sendPVTimmer=setTimeout(function(){l.sendPV()},10)}else l.prevPage=c;return l._conf.page=c,l},setConfig:function(c,h){if(c&&typeof c=="object"){i.verifyConfig(c),c=this.setImgUrl(c);var l=this._conf;if(this._conf=i.ext({},l,c),!h){var f="disableHook";f in c&&l[f]!==c[f]&&(c[f]?this.removeHook():this.addHook()),(f="enableSPA")in c&&l[f]!==c[f]&&this.bindHashChange(c[f])}}},sendRequest:function(c){t(c,this.getConfig("imgUrl"))},postData:function(c,h){var l={};l[h]=c[h],delete c[h];var f="";typeof c=="object"&&(f=i.serialize(c)),n(l,this.getConfig("imgUrl")+f+"&post_res=")},sendPipe:function(c){var h=this;if(!c||!c.length)return h;try{if(i.T(c[0])==="Array")return i.each(c,function(f){return h.sendPipe(f)});if(i.T(c)!=="Array")return h;var l=c.shift();if(!s.test(l))return h;h[l].apply(h,c)}catch(f){return i.warn("[retcode] error in sendPipe",f),h}},sendHealth:function(){var c=i.ext({},this._health);c.healthy=c.errcount>0?0:1,c.begin=Date.now();var h=c.begin-this.sBegin;c.stay=h,this._lg("health",c,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(c){c=i.ext({pid:this._conf.pid},c);var h=this.__proto__.constructor(c);return c.page&&h.sendPV(),h}}),_m()(o,r),Sm()(o,r,a),bm()(o,r,a),(Pd||(Pd=1,Id=function(c,h){var l=ci(),f=null,v=l.getCurDomain(),p=function(b,y,g,S,R,E,I,C,A,w,N,M,D){var L=l.J(R)||null,P=l.safetyCall(y,[L,S],null);if(!P)return!1;var x=P.code||E,T=!("success"in P)||P.success;b.api(g,T,I,x,P.msg,C,A,w,T?{}:N,v,M,D)},_="fetch",m="__oFetch_",d="__oXMLHttpRequest_",u="XMLHttpRequest";return l.ext(c.prototype,{removeHook:function(b,y){return f&&(y||this===f)?(h[m]&&(h[_]=h[m],delete h[m]),h[d]&&(h[u]=h[d],delete h[d]),f=null,this):this},addHook:function(b){return!b&&f||(f||(function(){if(typeof h[_]=="function"){var y=h[_];h[m]=y,h[_]=function(g,S){var R=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),E=f;if(!E||!E.api||S&&(S.method==="HEAD"||S.mode==="no-cors"))return y.apply(h,R);S||(S={});var I=Date.now(),C=E._conf,A=l.duration(),w=(g&&typeof g!="string"?g.url:g)||"",N=w;w=l.cutUrlSearch(w);var M=(C.ignore||{}).ignoreApis,D=C.parseTraceId;if(!l.checkAPI(w,!0)||l.ignoreByRule(w,M))return y.apply(h,R);w=l.filterByRule(w,N,C.ignoreApiPath?C.ignoreApiPath:C.apiHelper);var L=C.enableLinkTrace,P="",x="",T=E.getConfig("pid"),O=null,k=E.getConfig("sample"),H=E.getConfig("linkType"),U=1;if(k&&!E.sampling(k)&&(U=0),L){var ee="";try{ee=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch{ee=""}var W=l.checkSameOrigin(N,ee);if(E.getConfig("enableApiCors")||W)if(g&&typeof g!="string")try{if(R[0].headers&&typeof R[0].headers.get=="function"&&typeof R[0].headers.append=="function")switch(H){case"arms":var $=R[0].headers.get("EagleEye-TraceID"),B=R[0].headers.get("EagleEye-SessionID"),F=R[0].headers.get("EagleEye-pAppName");$?P=$:(P=E.getTraceId()["EagleEye-TraceID"],R[0].headers.append("EagleEye-TraceID",P)),B?x=B:(x=E.getPageviewId()["EagleEye-SessionID"],R[0].headers.append("EagleEye-SessionID",x)),F||R[0].headers.append("EagleEye-pAppName",T);break;case"b3":var G=R[0].headers.get("X-B3-TraceId");if(G)P=G;else{var q=E.getB3TraceId(U);R[0].headers.append("X-B3-TraceId",q["X-B3-TraceId"]),R[0].headers.append("X-B3-ParentSpanId",q["X-B3-ParentSpanId"]),R[0].headers.append("X-B3-SpanId",q["X-B3-SpanId"]),R[0].headers.append("X-B3-Sampled",q["X-B3-Sampled"]),R[0].headers.append("X-Request-ID",l.guid()),P=q["X-B3-TraceId"]}x=E.pageview;break;default:var X=R[0].headers.get("uber-trace-id");X?P=X.split(":")[0]:(X=E.getUberTraceId(U),R[0].headers.append("uber-trace-id",X["uber-trace-id"]),P=X.traceId),x=E.pageview}}catch(ce){l.warn(`[retcode] fetch failed to set header, exception is :
`+ce)}else switch(S.headers=S.headers?S.headers:{},H){case"arms":S.headers["EagleEye-TraceID"]?P=S.headers["EagleEye-TraceID"]:(P=E.getTraceId()["EagleEye-TraceID"],S.headers["EagleEye-TraceID"]=P),S.headers["EagleEye-SessionID"]?x=S.headers["EagleEye-SessionID"]:(x=E.getPageviewId()["EagleEye-SessionID"],S.headers["EagleEye-SessionID"]=x),S.headers["EagleEye-pAppName"]||(S.headers["EagleEye-pAppName"]=T);break;case"b3":if(S.headers["X-B3-TraceId"])P=S.headers["X-B3-TraceId"];else{var J=E.getB3TraceId(U);S.headers["X-B3-TraceId"]=J["X-B3-TraceId"],S.headers["X-B3-ParentSpanId"]=J["X-B3-ParentSpanId"],S.headers["X-B3-SpanId"]=J["X-B3-SpanId"],S.headers["X-B3-Sampled"]=J["X-B3-Sampled"],S.headers["X-Request-ID"]=l.guid(),P=J["X-B3-TraceId"]}x=E.getPageviewId()["EagleEye-SessionID"];break;default:if(S.headers["uber-trace-id"])P=S.headers["uber-trace-id"].split(":")[0];else{var se=E.getUberTraceId(U);S.headers["uber-trace-id"]=se["uber-trace-id"],P=se.traceId}x=E.getPageviewId()["EagleEye-SessionID"]}}return y.apply(h,R).then(function(ce){if(!E||!E.api)return ce;try{if(!ce||typeof ce.clone!="function")return ce;var Y=ce.clone(),fe=Y.headers;if(fe&&typeof fe.get=="function"){var he=fe.get("content-type");if(he&&!/(text)|(json)/.test(he))return ce;if(!P){var pe=l.parseFetchHeaders(fe);typeof pe=="object"&&pe["eagleeye-traceid"]&&(P=pe["eagleeye-traceid"],O="response")}}var ue=A();return Y.text().then(function(Te){if(!P&&l.isFunction(D)){var be=D(Y,Te);be&&l.isString(be)&&(P=be)}var Z=l.getFetchSnapshot(R,Te,fe);Y.ok?p(E,C.parseResponse,w,N,Te,Y.status||200,ue,I,P,x,Z,O,U):(E.api(w,!1,ue,Y.status||404,Y.statusText,I,P,x,Z,v,O,U),C.enableResource&&f.fixResourceStatus&&f.fixResourceStatus({src:Y.url,res_type:"api"}))}),ce}catch(Te){return l.warn("[ARMS] fetch response error :",Te),ce}}).catch(function(ce){if(!E||!E.api)throw ce;var Y=A();throw E.api(w,!1,Y,ce.name||"Error",ce.message,I,P,x,{},v),C.enableResource&&f.fixResourceStatus&&f.fixResourceStatus({src:N,res_type:"api"}),ce})},h[_].toString=l.createFakeToString(_)}}(),function(){if(typeof h[u]=="function"){var y,g=h[u];h[d]=g;var S=function(R){var E=new g(R),I=f;if(!I||!I.api||!E.addEventListener)return E;var C,A,w,N,M=E.send,D=E.open,L=E.setRequestHeader,P=I._conf,x=(P.ignore||{}).ignoreApis,T=P.parseTraceId,O=I.getConfig("enableLinkTrace"),k="",H="",U="",ee=null,W=I.getConfig("sample"),$=I.getConfig("linkType"),B=1;return W&&!I.sampling(W)&&(B=0),E.open=function(F,G){y=F;var q=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);D.apply(E,q),N=G||"",w=l.cutUrlSearch(N);var X=!l.checkAPI(w,!0)||l.ignoreByRule(w,x);if(w=w?l.filterByRule(w,N,P.ignoreApiPath?P.ignoreApiPath:P.apiHelper):"",!X&&O){var J="";try{J=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch{J=""}var se=l.checkSameOrigin(N,J);if((I.getConfig("enableApiCors")||se)&&L&&typeof L=="function")switch($){case"arms":k=I.getTraceId()["EagleEye-TraceID"],L.apply(E,["EagleEye-TraceID",k]),H=I.getPageviewId()["EagleEye-SessionID"],L.apply(E,["EagleEye-SessionID",H]),U=I.getConfig("pid"),L.apply(E,["EagleEye-pAppName",U]);break;case"b3":var ce=I.getB3TraceId(B);L.apply(E,["X-B3-TraceId",ce["X-B3-TraceId"]]),L.apply(E,["X-B3-ParentSpanId",ce["X-B3-ParentSpanId"]]),L.apply(E,["X-B3-SpanId",ce["X-B3-SpanId"]]),L.apply(E,["X-B3-Sampled",ce["X-B3-Sampled"]]),L.apply(E,["X-Request-ID",l.guid()]),k=ce["X-B3-TraceId"],H=I.getPageviewId()["EagleEye-SessionID"];break;default:var Y=I.getUberTraceId(B);L.apply(E,["uber-trace-id",Y["uber-trace-id"]]),k=Y.traceId,H=I.getPageviewId()["EagleEye-SessionID"]}}},E.send=function(){C=Date.now(),A=l.duration();var F=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);M.apply(E,F)},l.on(E,"readystatechange",function(){if(w&&E.readyState===4){var F=A(),G=l.getXhrSnapshot(N,y,E);if(!k){var q=l.parseXhrHeaders(typeof E.getAllResponseHeaders=="function"&&E.getAllResponseHeaders()||"");typeof q=="object"&&q["eagleeye-traceid"]&&(k=q["eagleeye-traceid"],ee="response")}if(!k&&l.isFunction(T)){var X=T(E);X&&l.isString(X)&&(k=X)}if(E.status>=200&&E.status<=299){var J=E.status||200;if(typeof E.getResponseHeader=="function"){var se=E.getResponseHeader("Content-Type");if(se&&!/(text)|(json)/.test(se))return}E.responseType&&E.responseType!=="text"?I.api(w,!0,F,J,"",C,k,H,{},v,ee,B):p(I,P.parseResponse,w,N,E.responseText,J,F,C,k,H,G,ee,B)}else I.api(w,!1,F,E.status||"FAILED",E.statusText,C,k,H,G,v,ee,B),P.enableResource&&f.fixResourceStatus&&f.fixResourceStatus({src:E.responseURL||N,res_type:"api"})}}),E};S.prototype=g.prototype,l.each(Object.keys(g),function(R){S[R]=g[R]}),h[u]=S,h[u].toString=l.createFakeToString(u)}}()),f=this),this},initHook:function(){return this.hasInitHook||(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0),this}}),c}),Id)(o,r),(Ld||(Ld=1,Dd=function(c,h){var l=ci(),f=h.history||{},v=h.document,p=function(m,d){var u;h.CustomEvent?u=new CustomEvent(m,{detail:d}):((u=v.createEvent("HTMLEvents")).initEvent(m,!1,!0),u.detail=d),h.dispatchEvent(u)},_=function(m){var d=f[m];typeof d=="function"&&(f[m]=function(u,b,y){var g=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),S=location.href,R=d.apply(f,g);if(!y||typeof y!="string"||y===S)return R;try{var E=S.split("#"),I=y.split("#"),C=l.cutUrlSearch(E[0]),A=l.cutUrlSearch(I[0]),w=E[1]&&E[1].replace(/^\/?(.*)/,"$1"),N=I[1]&&I[1].replace(/^\/?(.*)/,"$1");w!==N?p("historystatechange",N):C!==A&&p("historystatechange",A)}catch(M){l.warn("[retcode] error in "+m+": "+M)}return R},f[m].toString=l.createFakeToString(m))};l.ext(c.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState||(_("pushState"),_("replaceState"),this.hasHackedHistoryState=!0),this}})}),Dd)(o,r),function(){if(Od)return Da;Od=1;var c=ci(),h=La().TIMING_KEYS;return Da=function(l,f){function v(m,d,u){if(m instanceof f.PerformanceResourceTiming&&m.initiatorType){var b=c.getResType(m.initiatorType,m.name),y=d.resourceTypes||[],g=(d.ignore||{}).ignoreResources;if(b&&y.includes(b)&&!c.ignoreByRule(m.name,g)&&!c.ignoreByRule(c.decode(m.name),g)){var S=m[h[0]],R=m[h[1]],E=m[h[2]],I=m[h[3]],C=m[h[4]],A=m[h[5]],w=m[h[6]],N=m[h[7]],M=m[h[8]],D=m[h[18]],L=m[h[19]];if(!u.has(m)&&(!c.areInOrder(S,R,E,I,C,A,w,N,M)||S>N))return;if(D<S&&(D=S),L<S&&(L=R),c.areInOrder(S,D,L,R))return{domain:c.getURL(m.name).domain,res_type:b,src_type:c.getSrcType(m.name,d.cdnHostList),success:1,size:Math.round(m.decodedBodySize),duration:Math.round(m.duration),timeStamp:m.responseEnd,timing:m}}}}var p="_resource-"+Date.now(),_="_resource_error-"+Date.now();c.ext(l.prototype,{initResource:function(){var m=this,d=f.performance,u=f.PerformanceObserver;if(m[_]||(m[_]=new WeakMap),!d||!u||typeof d!="object"||typeof d.getEntriesByType!="function")return null;var b=d.getEntriesByType("resource")||[];return setTimeout(function(){m.setResource(b)},10),new u(function(y){setTimeout(function(){m.setResource(y.getEntries())},10)}).observe({entryTypes:["resource"]}),this.onReady(function(){setTimeout(m.resourceComboReport.bind(m),5e3)}),m},setResource:function(m){var d=this._conf,u=this[_];if(c.isArray(m)&&m.length){this[p]||(this[p]={});for(var b=this[p],y=0,g=m.length;y<g;y+=1){var S=m[y];if(c.checkAPI(S.name,!1)){var R=v(S,d,u);if(R){var E=R.res_type+"-"+R.domain;E in b||(b[E]=[]),b[E].push(R)}}}return this}},fixResourceStatus:function(m){var d=f.performance;if(!d||typeof d.getEntriesByName!="function")return null;var u=this[_];if(!m.src||!c.checkAPI(m.src,!1))return this;var b=m.timeStamp||d.now(),y=d.getEntriesByName(m.src,"resource");return c.each(y,function(g){u.has(g)||b-g.responseEnd<100&&u.set(g,{success:0})}),this},resourceComboReport:function(){var m=this[p]||{},d=this._conf.resourceSlow||2e3,u=this[_];this[p]={};var b=Object.keys(m);if(b.length!==0){var y=[];c.each(b,function(E){var I=m[E],C={domain:"",res_type:"",src_type:"",size:0,duration:0,count:0,err_count:0,err_duration:0,slow_count:0,slow_duration:0,timings:[]};c.each(I,function(A){var w=A.timing||{},N=u.get(A.timing),M=N?N.success:1,D=A.duration>d?1:0;C.domain=A.domain,C.res_type=A.res_type,C.src_type=A.src_type,C.count+=1,C.duration+=A.duration,C.size+=A.size,M||(C.err_count+=1,C.err_duration+=A.duration),D&&(C.slow_count+=1,C.slow_duration+=A.duration);try{var L=JSON.parse(JSON.stringify(w));L.success=M,L.resourceSlow=d,L.isSlow=D,C.timings.push(L)}catch{}}),C.count&&(C.size=Math.round(C.size/C.count),C.duration=Math.round(C.duration/C.count)),C.slow_count&&(C.slow_duration=Math.round(C.slow_duration/C.slow_count)),C.err_count&&(C.err_duration=Math.round(C.err_duration/C.err_count)),C.timings.length>20&&(C.timings.sort(function(A,w){return w.duration-A.duration}),C.timings.length=20),C.timings=encodeURIComponent(JSON.stringify(C.timings)),y.push(C)});var g={_combo:1,resource:JSON.stringify(y)},S=f.navigator.connection;g.ct=S?S.effectiveType||S.type:"";var R=S&&(S.downlink||S.downlinkMax||S.bandwidth)||null;(R=R>999?999:R)&&(g.bandwidth=R),this._lg("resource",g,this.getConfig("sample"))}}})},Da}()(o,r),o._super=e,o._root=e._root,e.Browser=o,Ra.exports=o,Ra.exports}var Em={getArmsLogger:function(){return function(){if(kd)return Ea.exports;function i(a,s){var o=e[n]=new t(a);o.sendPipe(s);var c=o._conf;return c.autoSendPv!==!1&&o.sendPV(),c&&c.useFmp||o.sendPerformance(),c&&c.sendResource&&o.sendResources(),e[r]=!0,o}kd=1;var e=window,t=e.BrowserLogger=ym(),n=ci().key,r="__hasInitBlSdk";return t.singleton=function(a,s){return e[r]?e[n]:i(a,s)},t.createExtraInstance=function(a){a&&typeof a=="object"&&a.enableInstanceAutoSend!==!0&&(a.enableInstanceAutoSend=!1);var s=new t(a),o=s._conf;return o.enableInstanceAutoSend&&(o.autoSendPv!==!1&&s.sendPV(),o&&o.useFmp||s.sendPerformance(),o&&o.sendResource&&s.sendResources()),s},typeof window=="object"&&window.navigator&&e[n]&&(t.bl=function(){if(e[r])return e[n];var a={},s=[];return n in e&&(a=e[n].config||{},s=e[n].pipe||[]),i(a,s)}()),Ea.exports=t,Ea.exports}()}};const Bd="https://arms-retcode.aliyuncs.com/r.png?",Vd="https://arms-retcode-sg.aliyuncs.com/r.png?",Fd="https://retcode-us-west-1.arms.aliyuncs.com/r.png?",Hd="e1iftji1w7@7ec1cef2cc88733",Gd="e1iftji1w7@10a06d1ec260adc",zd="e1iftji1w7@10a06d1ec260adc",Oa={cn:{reportUrl:Bd,pid:Hd},"cn-hangzhou":{reportUrl:Bd,pid:Hd},sg:{reportUrl:Vd,pid:Gd},"ap-southeast-1":{reportUrl:Vd,pid:Gd},usw:{reportUrl:Fd,pid:zd},"us-west-1":{reportUrl:Fd,pid:zd}},Rm=i=>!!Object.isExtensible(i)&&(e=>Object.prototype.toString.call(e).slice(8,-1))(i)==="Object";function Wd(i,e){if(typeof i!="string")return e;if(jd(i,e))return i;const t=i.indexOf(`
`);return t<0?`${i}${e}`:`${i.slice(0,t)}${e}${i.slice(t)}`}function jd(i,e){if(typeof i!="string")return!1;const t=i.indexOf(e);if(t<0)return!1;const n=i.indexOf(`
`);return n<0||t<n}function bn(i,e,t){return typeof i=="function"?function(n,r,a){if(Reflect.get(n,"__v_skip")===!0)return n;const s={MediaboxWrapperFunctionApply(o,c,h){let l;try{l=Reflect.apply(o,c,h)}catch(f){throw a(f),f}return bn(l,r,a)},MediaboxWrapperFunctionGet(o,c){const h=Object.getOwnPropertyDescriptor(o,c);return!h||h.writable||h.configurable?bn(o[c],r,a):o[c]},MediaboxWrapperClassConstructor(o,c){let h;try{h=new o(...c)}catch(l){throw a(l),l}return bn(h,r,a)}};return Object.defineProperty(n,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(n,{apply:s.MediaboxWrapperFunctionApply,get:s.MediaboxWrapperFunctionGet,construct:s.MediaboxWrapperClassConstructor})}(i,e+1,t):i instanceof Promise?i.then(n=>bn(n,e+1,t)).catch(n=>(t(n),Promise.reject(n))):Array.isArray(i)?(i.forEach((n,r)=>{i[r]=bn(n,e+1,t)}),i):(n=>n!==null&&typeof n=="object")(i)&&Rm(i)?function(n,r,a){var s;if(Reflect.get(n,"__v_skip")===!0)return n;const o=[],c=typeof Object.getOwnPropertyDescriptors=="function"?Object.getOwnPropertyDescriptors((s=Object.getPrototypeOf(n))!=null?s:{}):{};for(const l of Object.keys(c))c[l].get&&o.push(l);const h={MediaboxWrapperObjectGetter(l,f){if(typeof f=="string"&&o.indexOf(f)>-1){let p;try{p=l[f]}catch(_){throw a(_),_}return bn(p,r,a)}if(r>10)return l[f];const v=Reflect.getOwnPropertyDescriptor(l,f);return!v||v.writable||v.configurable?bn(l[f],r,a):l[f]},MediaboxWrapperObjectSetter:(l,f,v)=>(l[f]=bn(v,r,a),!0)};return Object.defineProperty(n,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(n,{get:h.MediaboxWrapperObjectGetter,set:h.MediaboxWrapperObjectSetter})}(i,e+1,t):i}function Na(i){return typeof i=="string"&&(i.indexOf("g.alicdn.com/apsara-media-")>-1||i.indexOf("g.alicdn.com/thor-server")>-1||i.indexOf("MediaboxWrapper")>-1)}function Xd(i,e){if(Reflect.get(i,"__v_skip")===!0)return i;const t={MediaboxWrapperShallowGet(n,r){const a=n[r];return typeof a=="function"?t.MediaboxWrapperShallowMethod(a,n):a},MediaboxWrapperShallowMethod:(n,r)=>({MediaboxWrapperShallowApply(...a){let s;try{s=n.apply(r,a)}catch(o){throw e(o),o}return s instanceof Promise?s.catch(o=>(e(o),Promise.reject(o))):s}}).MediaboxWrapperShallowApply};return Object.defineProperty(i,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(i,{get:t.MediaboxWrapperShallowGet})}class $d extends Error{constructor(e){super(e),this.name="MQTError"}}let Tm=1;class ka{constructor(e){var t,n;cr(this,"armsLogger"),cr(this,"isReady",!1),cr(this,"isDestroyed",!1),cr(this,"options"),cr(this,"queue",[]),cr(this,"marker"),cr(this,"helper",{MediaboxWrapperQueue:r=>new $d(r),MediaboxWrapperInitiative:r=>new $d(r)}),this.options=((r,a)=>pm(r,fm(a)))(ya({},e),{region:e.deferRegionSet?void 0:(t=e.region)!=null?t:"cn",env:(n=e.env)!=null?n:"prod"}),this.marker=`-${Tm++}-`,this.initArmsLogger()}static get version(){return"0.31.0"}initArmsLogger(e){const{region:t,env:n,disabled:r}=this.options;if(r||this.armsLogger)return;if(e&&!t)throw new Error("region is required");if(!t)return;if(!Oa[t])throw new Error(`region ${t} is not supported`);const a=Em.getArmsLogger();this.armsLogger=a.createExtraInstance({enableInstanceAutoSend:!0,pid:Oa[t].pid,tag:this.options.businessName,release:`${this.options.businessName}_${this.options.version}`,imgUrl:Oa[t].reportUrl,behavior:!0,sample:1,disableHook:!0,environment:n,beforeReport:s=>{var o;if(this.isDestroyed||jd(s.stack,this.marker)||s.t!=="pv"&&s.t!=="error"&&s.t!=="health")return!1;if(s.c1=(o=this.options.cid)!=null?o:window.location.host,s.c2=ka.version,this.options.customData&&(s.c3=new URLSearchParams(this.options.customData).toString()),s.t==="error"){if(function(c){return typeof c=="string"&&(c.indexOf("g.alicdn.com/apsara-media-")>-1||c.indexOf("g.alicdn.com/thor-server")>-1)}(s.file)||Na(s.stack)){let c=s;return this.options.beforeSend&&(c=this.options.beforeSend(s)),this.isReady?c:(c&&this.queue.push(c),!1)}return!1}return s}})}wrap(e){return this.options.disabled||typeof Proxy>"u"?e:bn(e,0,t=>{var n;t instanceof Error&&typeof t.stack=="string"&&Na(t.stack)&&((n=this.armsLogger)==null||n.error(t),t.stack=Wd(t.stack,this.marker))})}shallowWrapClass(e){return this.options.disabled||typeof Proxy>"u"?e:function(t,n){if(Reflect.get(t,"__v_skip")===!0)return t;const r=s=>s instanceof t?Xd(s,n):s,a={MediaboxWrapperStaticGet(s,o){const c=s[o];return typeof c=="function"&&o!=="prototype"?a.MediaboxWrapperStaticMethod(c,s):c},MediaboxWrapperStaticMethod(s,o){const c={MediaboxWrapperStaticApply(h,l,f){let v;try{v=s.apply(o,f)}catch(p){throw n(p),p}return v instanceof Promise?v.then(p=>r(p)).catch(p=>(n(p),Promise.reject(p))):r(v)},MediaboxWrapperStaticConstruct(h,l,f){let v;try{v=Reflect.construct(s,l,f)}catch(p){throw n(p),p}return r(v)}};return new Proxy(s,{apply:c.MediaboxWrapperStaticApply,construct:c.MediaboxWrapperStaticConstruct})},MediaboxWrapperConstruct(s,o,c){let h;try{h=Reflect.construct(s,o,c)}catch(l){throw n(l),l}return Xd(h,n)}};return Object.defineProperty(t,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(t,{get:a.MediaboxWrapperStaticGet,construct:a.MediaboxWrapperConstruct})}(e,t=>{var n;t instanceof Error&&typeof t.stack=="string"&&Na(t.stack)&&((n=this.armsLogger)==null||n.error(t),t.stack=Wd(t.stack,this.marker))})}updateOptions(e){this.options=ya(ya({},this.options),e)}setReady(){this.initArmsLogger(!0),this.isReady=!0,this.queue.length&&this.queue.forEach(e=>{var t;(t=this.armsLogger)==null||t.error(this.helper.MediaboxWrapperQueue(e.msg),{filename:e.file,lineno:e.line,colno:e.col})})}report(e,t){var n;(n=this.armsLogger)==null||n.error(this.helper.MediaboxWrapperInitiative(e),t)}destroy(){this.isDestroyed=!0}}function Pr(){}const Kd=class Wo{static getInstance(){var e;return Wo.instance||(Wo.instance=new AudioContext),(e=Wo.instance.resume())==null||e.then(Pr,Pr).catch(Pr),Wo.instance}};V(Kd,"instance");let _o=Kd;const es=()=>{var i;const e=_o.getInstance();e.state!=="running"&&e.state!=="closed"&&((i=e.resume())==null||i.then(Pr,Pr).catch(Pr)),window.removeEventListener("mousedown",es),window.removeEventListener("touchstart",es)};window.addEventListener("mousedown",es),window.addEventListener("touchstart",es);class Am extends Kt{constructor(){super(),V(this,"audioContext"),V(this,"stream"),V(this,"sourceNode"),V(this,"analyser"),this.audioContext=_o.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const n=this.audioContext.createMediaStreamDestination();this.analyser=function(r,a,s,o,c){let h,l=o,f=0;const v=r.createAnalyser();v.fftSize=256;const p=new Uint8Array(v.frequencyBinCount);a.connect(v),v.connect(s);const _=()=>{h&&window.clearInterval(h)},m=()=>{r.state==="suspended"&&r.resume(),h=window.setInterval(()=>{v.getByteFrequencyData(p);let d=Math.round(p.reduce((u,b)=>u+b)/p.length);d=Math.min(100,d),f=d,c&&c(d)},l)};return m(),{updateInterval:d=>{_(),l=d,m()},getLevel:()=>f,dispose:()=>{_(),a.disconnect(),v.disconnect()}}}(this.audioContext,this.sourceNode,n,t,r=>{this.emit("audioLevel",r)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class qd extends Kt{constructor(e,t,n,r){super(),V(this,"uid"),V(this,"name"),V(this,"rtsManager"),V(this,"callId",""),V(this,"audioLevelMonitor"),V(this,"audioVolumeIndicationInterval",0),this.uid=e,this.name=t,this.rtsManager=n,this.audioVolumeIndicationInterval=r,this.audioLevelMonitor=new Am}get userId(){return this.uid}get displayname(){return this.name}createCallId(e=!1){this.callId&&!e||(this.callId=kt.createCallid())}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class Yd{static getCurrentStatus(e){let t=0;e.micOpen&&(t+=1),e.micInterrupted&&(t+=2),e.cameraOpen&&(t+=4),e.screenShare&&(t+=128),e.audioDisable&&(t+=8),e.videoDisable&&(t+=16),e.screenDisable&&(t+=256);let n=t.toString(16);for(;n.length<16;)n="0"+n;return n}static parseStatus(e){let t=parseInt(e,16);return{micOpen:!!(1&t),micInterrupted:!!(2&t),cameraOpen:!!(4&t),screenShare:!!(128&t),audioDisable:!!(8&t),videoDisable:!!(16&t),screenDisable:!!(256&t),backgroundMode:!!(32&t),accompanyPlaying:!!(64&t)}}}const ge=(i,e)=>(t,n,r)=>{const a=r.value;return r.value=function(...s){var o;const c=`[${this.logName||((o=t.constructor)==null?void 0:o.logName)||""}]`,h=Date.now();let l=[];if(i)try{l=i(s)}catch{}Re.interface(c,n,...l);const f=a.apply(this,s);return Promise.resolve(f).then(v=>v).catch(v=>v).then(v=>{var p;let _="";const m=v instanceof Error,d=m&&((p=t.constructor)==null?void 0:p.logError);if(e||m){if(d)_=v;else if(m)_=v.message||"";else{if(!e)return;if(v===void 0)_="";else try{_=e(v)}catch{}}Re.interfaceResult(c,n,!(m&&d),Date.now()-h+"ms",_)}}),f},r},ke=i=>i,Jd="customVideoProfile",Qd="customScreenProfile",Ua={width:1280,height:720,frameRate:30,maxBitrate:2e3},Zd={width:1920,height:1080,frameRate:30,maxBitrate:2600};var So=(i=>(i[i.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",i[i.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",i[i.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10002]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",i[i.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10003]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",i[i.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10004]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",i[i.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10005]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",i[i.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",i[i.ERROR_SCREENSHARE_NOTSUPPORT=10010]="ERROR_SCREENSHARE_NOTSUPPORT",i[i.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",i[i.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",i[i.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",i[i.ERROR_SCREENSHARE_SAFARI_INVALIDACCESS=10014]="ERROR_SCREENSHARE_SAFARI_INVALIDACCESS",i[i.ERROR_SCREENSHARE_UNKNOWNERRO=10019]="ERROR_SCREENSHARE_UNKNOWNERRO",i[i.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",i[i.ERROR_DEVICE_NOTSUPPORT=2e4]="ERROR_DEVICE_NOTSUPPORT",i))(So||{});const Cm={1e4:Bt.AliEngineLocalDeviceExceptionTypeUnknown,2e4:Bt.AliEngineLocalDeviceExceptionTypeUnknown,10001:Bt.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:Bt.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:Bt.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:Bt.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:Bt.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:Bt.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:Bt.AliEngineLocalDeviceExceptionTypeDisplayException,10011:Bt.AliEngineLocalDeviceExceptionTypeDisplayException,10012:Bt.AliEngineLocalDeviceExceptionTypeDisplayException,10013:Bt.AliEngineLocalDeviceExceptionTypeDisplayException,10014:Bt.AliEngineLocalDeviceExceptionTypeDisplayException,10019:Bt.AliEngineLocalDeviceExceptionTypeDisplayException};var wi=(i=>(i.CREATE_ENGINE="create_engine",i.JOIN="join",i.WANT_INSERT_PUB_TASK="wantInsertPubTask",i.INSERT_PUB_TASK="InsertPubTask",i.HANDLE_PUB_TASK="HandlePubTask",i.RECV_NOTIFY_PUBLISH="RecvNotifyPublish",i.INSERT_SUB_TASK="InsertSubTask",i.HANDLE_SUB_TASK="HandleSubTask",i.FIRST_REMOTE="first_remote",i))(wi||{}),Bi=(i=>(i.START="start",i.SEND_SIG="send_sig",i.RECV_RST="recv_rst",i.END="end",i.RECEIVED="received",i.DECODED="decoded",i.PLAYED="played",i))(Bi||{});const eh=(i,e,t=!1)=>{const n=()=>(i.muted=!0,Promise.race([Hn(500),i._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let r;return t&&i.srcObject===e?r=Promise.resolve():(i.load(),i.srcObject=e,r=i.play(),i._playPromise=r),r}));return new Promise(r=>{if(St.AliRTS.BrowserUtil.isMicroMessenger){const a=window.top!==window.self,s=window.WeixinJSBridge||window.top.WeixinJSBridge;s?s.invoke("getNetworkType",{},()=>{r(n())}):(a?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{s.invoke("getNetworkType",{},()=>{r(n())})}),setTimeout(()=>{r(n())},1e3)}else setTimeout(()=>{r(n())},0)})},hn=i=>{Promise.race([Hn(100),i._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{i.srcObject=null,i._playPromise=void 0})};var th=(i=>(i[i.AliEngineDataMsgNone=0]="AliEngineDataMsgNone",i[i.AliEngineDataMsgMusicProgress=1]="AliEngineDataMsgMusicProgress",i[i.AliEngineDataMsgCustom=2]="AliEngineDataMsgCustom",i))(th||{});class ts{constructor(e,t,n,r=0){V(this,"msgType"),V(this,"msgId"),V(this,"protocolVersion"),V(this,"tlvVersion"),this.msgType=e,this.msgId=t,this.protocolVersion=n,this.tlvVersion=r}build(){const e=new Uint8Array(4);return e.set(Uint8Array.from([this.protocolVersion,this.tlvVersion<<4|15&this.msgType]),0),e.set(Uint16Array.from([this.msgId]),2),e}static parse(e){const t=new DataView(e),n=t.getUint8(0),r=t.getUint8(1)>>4,a=15&t.getUint8(1),s=t.getUint16(2);return new ts(a,s,n,r)}}class is{constructor(e,t,n){if(V(this,"_byteArray"),this._byteArray=new Uint8Array(0),e!==void 0&&t!==void 0&&n!==void 0){const r=new ts(e,t,n).build();this._byteArray=new Uint8Array(r.byteLength+this._byteArray.byteLength),this._byteArray.set(r,0)}}write(e,t){const n=this._byteArray,r=new ArrayBuffer(5),a=new DataView(r);a.setUint8(0,e),a.setUint32(1,t.byteLength);const s=new Uint8Array(n.byteLength+5+t.byteLength);s.set(n,0),s.set(new Uint8Array(r),n.byteLength),s.set(new Uint8Array(t),n.byteLength+5),this._byteArray=s}static parse(e){const t={},n=new DataView(e);let r=0;for(;r<e.byteLength;){const a=n.getUint8(r),s=n.getUint32(r+1);if(!(r+5+s<=e.byteLength))break;{const o=e.slice(r+5,r+5+s);t[a]=o,r+=5+s}}return t}get buffer(){return this._byteArray.buffer}}class bo{constructor(e=0,t=!0,n=1,r=!1,a=0,s=!1,o=!1,c=3){V(this,"_fin",!0),V(this,"_hasExtension",!1),V(this,"_version",0),V(this,"_frameType",1),V(this,"_isEncrypted",!1),V(this,"_isCompressed",!1),V(this,"_signalType",3),V(this,"_payloadLength",0),this._fin=t,this._hasExtension=r,this._version=a,this._frameType=n,this._isEncrypted=s,this._isCompressed=o,this._signalType=c,this._payloadLength=e}get fin(){return this._fin}get hasExtension(){return this._hasExtension}get version(){return this._version}get frameType(){return this._frameType}get isEncrypted(){return this._isEncrypted}get isCompressed(){return this._isCompressed}get signalType(){return this._signalType}get payloadLength(){return this._payloadLength}toBuffer(){const e=new ArrayBuffer(4),t=new DataView(e);return t.setUint8(0,(this._fin?1:0)<<7|(this._hasExtension?1:0)<<6|this._version<<4|15&this._frameType),t.setUint8(1,(this._isEncrypted?1:0)<<7|(this._isCompressed?1:0)<<6|15&this._signalType),t.setUint16(2,this._payloadLength),e}static parse(e){const t=new DataView(e),n=t.getUint8(0)>>7==1,r=(64&t.getUint8(0))>>6==1,a=(48&t.getUint8(0))>>4,s=15&t.getUint8(0),o=t.getUint8(1)>>7==1,c=(64&t.getUint8(1))>>6==1,h=15&t.getUint8(1),l=t.getUint16(2);return new bo(l,n,s,r,a,o,c,h)}}class ns{constructor(e,t){V(this,"_body"),V(this,"_header",new bo),this._header=e,this._body=t}get header(){return this._header}get isFin(){return this._header.fin}get body(){return this._body}toGRTNBuffer(){const e=this._header.toBuffer(),t=this._body,n=new ArrayBuffer(4);new DataView(n).setUint8(0,1*Math.pow(2,4));const r=new Uint8Array(n.byteLength+e.byteLength+t.byteLength);return r.set(new Uint8Array(n),0),r.set(new Uint8Array(e),n.byteLength),r.set(new Uint8Array(t),n.byteLength+e.byteLength),r.buffer}static parse(e){const t=e.slice(0,4),n=bo.parse(t);let r=new ArrayBuffer(0);return e.byteLength-4>=n.payloadLength&&(r=e.slice(4,4+n.payloadLength)),new ns(n,r)}}const Ba=i=>{const e=i.byteLength,t=new DataView(i);let n=0;for(let r=0;r<e;r++)n=256*n+t.getUint8(r);return n};let ih=0;class zn{constructor(e,t=0,n=0,r=0){V(this,"data"),V(this,"networkTime"),V(this,"futureOrProgress"),V(this,"type"),this.data=e,this.type=t,this.networkTime=n,this.futureOrProgress=r}toBuffer(){const e=new is(0,0,0);e.write(1,Uint8Array.from([0]).buffer),e.write(2,Uint16Array.from([0]).buffer),ih++,e.write(3,Uint32Array.from([ih]).buffer);const t=new is;return t.write(1,Uint8Array.from([0]).buffer),t.write(2,Uint8Array.from([this.type]).buffer),t.write(3,Uint32Array.from([this.futureOrProgress]).buffer),t.write(4,Uint32Array.from([Number(this.networkTime>>32&4294967295),Number(4294967295&this.networkTime)]).buffer),t.write(5,this.data),e.write(30,t.buffer),e.buffer}static parse(e){if(!e||e.byteLength<4)return;ts.parse(e.slice(0,4));const t=is.parse(e.slice(4))[30];if(!t)return;const n=is.parse(t),r=n[2],a=n[3],s=n[4],o=n[5];return o.byteLength!==0?new zn(o,Ba(r),Ba(s),Ba(a)):void 0}}var wm=Object.defineProperty,Mm=Object.getOwnPropertyDescriptor,Lt=(i,e,t,n)=>{for(var r,a=Mm(e,t),s=i.length-1;s>=0;s--)(r=i[s])&&(a=r(e,t,a)||a);return a&&wm(e,t,a),a};class yo extends Kt{constructor(){super(),V(this,"_state"),V(this,"time"),this._state=nt.AliRtcStatePublishIdle,this.time=Date.now()}get state(){return this._state}setState(e){const t=this._state,n=this.time;this._state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-n)/1e3))}}var yn;const Pt=(yn=class extends qd{constructor(i){const{rtsManager:e,localStreamManager:t,slsReporter:n,signalingManager:r,audioVolumeIndicationInterval:a,parameter:s}=i;super("","",e,a),V(this,"sessionId",""),V(this,"traceId",""),V(this,"_url",""),V(this,"joinTime",0),V(this,"publishPromise",Promise.resolve({traceId:"",l1ip:void 0})),V(this,"previewElements",[]),V(this,"screenPreviewElements",[]),V(this,"streamManager"),V(this,"dc"),V(this,"streamTracks"),V(this,"publishId",Ai()),V(this,"signalingManager"),V(this,"shouldPublish",!1),V(this,"monitorTimerId"),V(this,"monitorDataCache",{}),V(this,"candidateDataCache",[]),V(this,"pcMediaStatsMap",{}),V(this,"slsReporter"),V(this,"audioPubState"),V(this,"videoPubState"),V(this,"videoSmallPubState"),V(this,"screenPubState"),V(this,"dataPubState"),V(this,"parameter",{}),V(this,"onTrackEnd",o=>{this.emit(o)}),this.streamManager=t,this.signalingManager=r,this.slsReporter=n,this.parameter=s,this.streamManager.on("trackended",o=>{this.onTrackEnd(o)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new yo,this.audioPubState.on("change",(o,c,h)=>{this.emit("audioPublishStateChanged",o,c,h)}),this.videoPubState=new yo,this.videoPubState.on("change",(o,c,h)=>{this.emit("videoPublishStateChanged",o,c,h)}),this.videoSmallPubState=new yo,this.videoSmallPubState.on("change",(o,c,h)=>{this.emit("dualStreamPublishStateChanged",o,c,h)}),this.screenPubState=new yo,this.screenPubState.on("change",(o,c,h)=>{this.emit("screenPublishStateChanged",o,c,h)}),this.dataPubState=new yo,this.dataPubState.on("change",(o,c,h)=>{this.emit("dataPublishStateChanged",o,c,h)}),this.startStreamMonitor(),this.createCallId()}get url(){return this._url}set url(i){this._url=i,this.rtsManager.updateAuth(i)}get joined(){return!!this.uid}get isPublishing(){return this.rtsManager.publishingTracks.length>0}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var i;return!!((i=this.streamTracks)!=null&&i.find(({ssrc:e,type:t,msid:n})=>t==="video"&&e&&n===Me.VideoLarge))}get hasCameraDualTrackInMS(){var i;return!!((i=this.streamTracks)!=null&&i.find(({ssrc:e,type:t,msid:n})=>t==="video"&&e&&n===Me.VideoSmall))}get hasScreenTrackInMS(){var i;return!!((i=this.streamTracks)!=null&&i.find(({ssrc:e,type:t,msid:n})=>t==="video"&&e&&n===Me.Screen))}get hasAudioTrackInMS(){var i;return!!((i=this.streamTracks)!=null&&i.find(({ssrc:e,type:t,msid:n})=>t==="audio"&&e&&n===Me.Audio))}get cameraDirection(){var i,e;return(e=(i=this.streamManager.cameraStreamInfo)==null?void 0:i.cameraVideoConstraints)==null?void 0:e.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(i){this.streamManager.publishLocalAudioStreamEnabled=i}setPublishLocalVideoStreamEnabled(i){this.streamManager.publishLocalVideoStreamEnabled=i}setPublishLocalScreenStreamEnabled(i){this.streamManager.publishLocalScreenStreamEnabled=i}initInfo(i,e){this.joinTime=Date.now(),this.rtsManager.localJoinTime=this.joinTime,this.setUserInfo(i.userId,i.userId),this.url=e,this.sessionId=i.sessionId||kt.createCallid("web"),this.updatePubId()}setVideoProfile(i){return le(this,null,function*(){yield this.streamManager.setVideoProfile(Jd,i)})}setVideoContentHint(i){this.streamManager.setVideoContentHint(i)}setScreenContentHint(i){this.streamManager.setScreenContentHint(i)}setAudioProfile(i){return le(this,null,function*(){yield this.streamManager.setAudioProfile(i)})}setScreenProfile(i){return le(this,null,function*(){yield this.streamManager.setScreenProfile(Qd,i)})}setCameraDirection(i){if(i===mo.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else{if(i!==mo.CAMERA_REAR)throw new Le(Ne.ERR_CAMERA_OPEN_FAIL,`camera direction set to  ${i} failed`);this.streamManager.setCameraVideoConstraints({facingMode:"environment"})}}setCameraDeviceId(i){this.streamManager.setCameraVideoConstraints({deviceId:i})}muteLocalCamera(i){this.streamManager.setCameraMuted(i),this.slsReporter.reportMute(this.callId,!i,"video")}muteLocalMic(i){this.streamManager.setAudioMuted(i),this.slsReporter.reportMute(this.callId,!i,"audio")}muteLocalScreen(i){this.streamManager.setScreenMuted(i),this.slsReporter.reportMute(this.callId,!i,"screen")}setMicrophoneDeviceId(i){this.streamManager.setMicAudioConstraints({deviceId:i})}setMicrophoneConstraints(i){this.streamManager.setMicAudioConstraints(i)}updatePubId(){this.publishId=Ai()}clearPublishState(){this.streamTracks=void 0}leave(){return le(this,null,function*(){this.shouldPublish=!1,this.isPublishing&&(yield this.unPublish()),this.joinTime=0,this.dc=void 0})}clear(){return le(this,null,function*(){Ul(yn.prototype,this,"clear").call(this),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),yield this.leave(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(i){this.previewElements.includes(i)&&(hn(i),this.previewElements.splice(this.previewElements.indexOf(i),1)),this.screenPreviewElements.includes(i)&&(hn(i),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(i),1))}setPreviewElement(i){const{videoElement:e,screen:t}=i;t?this.screenPreviewElements.includes(e)||(this.screenPreviewElements.push(e),this.preview(i)):this.previewElements.includes(e)||(this.previewElements.push(e),this.preview(i))}startDefaultCameraAndMic(i){return le(this,null,function*(){const{hasCamera:e,cameraCaptureDisabled:t,publishLocalVideoStreamEnabled:n}=this,{hasMicrophone:r,audioCaptureDisabled:a,publishLocalAudioStreamEnabled:s}=this,o=!e&&!i&&!t&&n,c=!r&&!a&&s;try{o&&c?yield this.startCameraAndMic():o?yield this.startCameraCapture():c&&(yield this.startAudioCapture())}catch(h){const l=h.errorCode;let f=Ne.ERR_CAMERA_OPEN_FAIL;throw o?((l===So.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED||So.ERROR_DEVICE_NOTALLOWED)&&(f=Ne.ERR_CAMERA_AUTH_FAIL),f=Ne.ERR_CAMERA_OPEN_FAIL):((l===So.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED||So.ERROR_DEVICE_NOTALLOWED)&&(f=Ne.ERR_MIC_AUTH_FAIL),f=Ne.ERR_MIC_OPEN_FAIL),new Le(f,`auto open fail: ${h.message}`)}})}setViewConfig(i,e){if(i){if(![ft.AliRtcVideoTrackCamera,ft.AliRtcVideoTrackScreen].includes(e))throw new Le(Ne.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:e});i.forEach(t=>{this.setPreviewElement({videoElement:t,screen:e===ft.AliRtcVideoTrackScreen})})}else e===ft.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0})}startCameraCapture(){return le(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream({video:!0})})}stopCameraCapture(){return le(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}startAudioCapture(){return le(this,null,function*(){return this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({audio:!0})})}stopAudioCapture(){return le(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}startCameraAndMic(){return le(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({video:!0,audio:!0})})}preview(i){return le(this,null,function*(){const{videoElement:e,screen:t}=i??{};try{let n=t?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!e)throw new Le(Ne.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:e});return n?(eh(e,n.mediaStream),this.setPreviewElement(i),n.mediaStream):void Re.info(`[${yn.logName}]`,"preview no stream founded")}catch(n){const r=Ne.ERR_INNER;throw Le.fromError(n,r,"preview failed")}})}previewAll(i){return le(this,null,function*(){const{primary:e=!0,screen:t=!0}=i??{};if(e&&this.previewElements.length)for(let n=0;n<this.previewElements.length;n++){const r=this.previewElements[n];yield this.preview({videoElement:r})}if(t&&this.screenPreviewElements.length)for(let n=0;n<this.screenPreviewElements.length;n++){const r=this.screenPreviewElements[n];yield this.preview({videoElement:r,screen:!0})}})}stopPreview(i){const{videoElement:e,primary:t=!0,screen:n=!0}=i||{};if(e){const r=this.previewElements.findIndex(a=>a===e);if(r>=0)this.previewElements.splice(r,1),hn(e);else{const a=this.screenPreviewElements.findIndex(s=>s===e);a>=0&&(this.screenPreviewElements.splice(a,1),hn(e))}}else t&&(this.previewElements.forEach(r=>{hn(r)}),this.previewElements=[]),n&&(this.screenPreviewElements.forEach(r=>{hn(r)}),this.screenPreviewElements=[])}resumePublish(){return le(this,null,function*(){this.shouldPublish&&(this.createCallId(!0),yield this.startPublish(!0))})}createLocalStream(i){return le(this,null,function*(){try{if(i.video)for(let t=0;t<this.previewElements.length;t++){const n=this.previewElements[t];hn(n)}else if(i.screen)for(let t=0;t<this.screenPreviewElements.length;t++){const n=this.screenPreviewElements[t];hn(n)}const e=yield this.streamManager.createLocalStream(i);return e!=null&&e.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(e.audioTrack,this.audioVolumeIndicationInterval),i.video?this.previewAll({primary:!0}):i.screen&&this.previewAll({screen:!0}),e}catch(e){const t=Cm[e.errorCode];throw t&&(i.audio?this.emit("localDeviceException",_n.AliEngineLocalDeviceTypeMic,t,""):i.video?this.emit("localDeviceException",_n.AliEngineLocalDeviceTypeCamera,t,""):i.screen?this.emit("localDeviceException",_n.AliEngineLocalDeviceTypeDisplay,t,""):this.emit("localDeviceException",_n.AliEngineLocalDeviceTypeUnknown,t,"")),e}})}stopLocalStream(i){return le(this,null,function*(){i.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(i)})}compareAndPublish(i,e,t){return le(this,null,function*(){var n,r;if(!i&&!e)return;if(i&&!e){const s={};return t===Me.Audio?s.audio=!0:t===Me.VideoLarge||t===Me.VideoSmall?(s.video=!0,s.vMsid=t):t===Me.Screen&&(s.screen=!0),yield this.publishDeleteTracks(s)}const a={};if(e!=null&&e.hasVideo&&(a.isScreen=t===Me.Screen,a.vMsid=t),e!=null&&e.hasAudio&&(a.aMsid=t),!i&&e)return yield this.publishAdd(e,a,!1);if(i&&e&&i.trackId!==(((n=e.videoTrack)==null?void 0:n.id)||((r=e.audioTrack)==null?void 0:r.id)))return yield this.publishReplace(e,a)})}reportAudioProfile(){const i=this.streamManager.cameraStreamInfo.audioProfile||"standard",e=St.AliRTS.AudioProfileMap.get(i);this.slsReporter.reportPublishProfile(Me.Audio,{a_profile:i,bits:(e==null?void 0:e.maxBitrate)||0,samplerate:(e==null?void 0:e.sampleRate)||0,channel:(e==null?void 0:e.channelCount)||0})}reportVideoProfile(){const i=this.streamManager.cameraStreamInfo.videoProfile||"",e=St.AliRTS.VideoProfileMap.get(i);e&&this.slsReporter.reportPublishProfile(Me.VideoLarge,{v_profile:i,wdth:(e==null?void 0:e.width)||0,hgt:(e==null?void 0:e.height)||0,fps:(e==null?void 0:e.frameRate)||0,bitrate:(e==null?void 0:e.maxBitrate)||0})}reportScreenProfile(){const i=this.streamManager.screenStreamInfo.videoProfile||"",e=St.AliRTS.VideoProfileMap.get(i);e&&this.slsReporter.reportPublishProfile(Me.Screen,{v_profile:i,wdth:(e==null?void 0:e.width)||0,hgt:(e==null?void 0:e.height)||0,fps:(e==null?void 0:e.frameRate)||0,bitrate:(e==null?void 0:e.maxBitrate)||0})}updateDataChannel(i){i&&(this.dc=i,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"))}publishDataChannel(){return le(this,null,function*(){if(this.dataPubState.state!==nt.AliRtcStatePublishing){this.dataPubState.setState(nt.AliRtcStatePublishing);try{const i=yield this.rtsManager.publishAddDataChannel(this.url);i?(this.updateDataChannel(i),this.dataPubState.setState(nt.AliRtcStatePublished)):(this.dataPubState.setState(nt.AliRtcStateNoPublish),this.emit("publishDataError",new Le(Ne.ERR_INNER,"publishDataError")))}catch(i){Re.error("[LocalUser]","publishDataChannel error",i),this.dataPubState.setState(nt.AliRtcStateNoPublish)}}})}startPublish(){return le(this,arguments,function*(i=!1,e=dn.MANUAL){var t;if(!this.joined)return;this.shouldPublish=!0;const n=this.streamManager.publishStreams,{audio:r,video:a,videoSmall:s,screen:o}=n;if(r||a||s||o)try{const c=new Date().getTime();r&&this.audioPubState.setState(nt.AliRtcStatePublishing),a&&this.videoPubState.setState(nt.AliRtcStatePublishing),s&&this.videoSmallPubState.setState(nt.AliRtcStatePublishing),o&&this.screenPubState.setState(nt.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this,i,e);const{traceId:h,l1ip:l}=yield this.publishPromise;this.streamTracks=this.rtsManager.publishingTracks,this.traceId=h;const f={type:Fn.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,resume:i,subscribe:{signal:"",pullstreamurl:this.url},l1ip:this.parameter.reportL1IP?l:void 0,callid:this.callId,tracks:this.streamTracks,traceid:h};(t=this.parameter.data)!=null&&t.enablePubDataChannel&&this.publishDataChannel().then(()=>{this.syncPublishToRoomServer(f,n,c)}),h&&(this.traceId=h),r&&this.reportAudioProfile(),a&&this.reportVideoProfile(),o&&this.reportScreenProfile(),yield this.syncPublishToRoomServer(f,n,c),r&&this.audioPubState.setState(nt.AliRtcStatePublished),a&&this.videoPubState.setState(nt.AliRtcStatePublished),s&&this.videoSmallPubState.setState(nt.AliRtcStatePublished),o&&this.screenPubState.setState(nt.AliRtcStatePublished)}catch(c){throw r&&this.audioPubState.setState(nt.AliRtcStateNoPublish),a&&this.videoPubState.setState(nt.AliRtcStateNoPublish),s&&this.videoSmallPubState.setState(nt.AliRtcStateNoPublish),o&&this.screenPubState.setState(nt.AliRtcStateNoPublish),c}else Re.event(`[${yn.logName}]`,"startPublish no stream founded")})}updateStreams(){return le(this,null,function*(){yield this.streamManager.updateStreams()})}publishUpdate(i){return le(this,null,function*(){var e,t,n,r,a;if(Re.info(`[${yn.logName}]`,"publishUpdate",i||"-",this.shouldPublish),!this.shouldPublish)return;if(!this.rtsManager.isConnecting&&!this.rtsManager.isConnected)return void(yield this.startPublish());yield this.publishPromise;const s=this.streamManager.publishStreams;let o;const c=new Date().getTime();try{const h=(e=this.streamTracks)==null?void 0:e.find(({ssrc:u,type:b,msid:y})=>b==="audio"&&u&&y===Me.Audio),l=yield this.compareAndPublish(h,s.audio,Me.Audio);l&&(o=l);const f=(t=this.streamTracks)==null?void 0:t.find(({ssrc:u,type:b,msid:y})=>b==="video"&&u&&y===Me.VideoLarge),v=yield this.compareAndPublish(f,s.video,Me.VideoLarge);v&&(o=v);const p=(n=this.streamTracks)==null?void 0:n.find(({ssrc:u,type:b,msid:y})=>b==="video"&&u&&y===Me.VideoSmall),_=yield this.compareAndPublish(p,s.videoSmall,Me.VideoSmall);_&&(o=_);const m=(r=this.streamTracks)==null?void 0:r.find(({ssrc:u,type:b,msid:y})=>b==="video"&&u&&y===Me.Screen),d=yield this.compareAndPublish(m,s.screen,Me.Screen);d&&(o=d),(a=this.parameter.data)!=null&&a.enablePubDataChannel&&!this.dc&&(yield this.publishDataChannel()),o||i!==dn.RECONNECT?o&&(yield this.syncPublishToRoomServer(o,s,c)):this.syncPublishToRoomServer({type:Fn.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.rtsManager.publishingTracks,traceid:this.traceId},s,Date.now())}catch(h){const{code:l}=h??{},f=this.url;throw l===403&&f&&(yield this.refreshPushStreamUrl(),o=yield this.publishUpdate()),h}return o})}syncPublishToRoomServer(i,e,t){return le(this,null,function*(){var n;if(!i)return void Re.event(`[${yn.logName}]`,"sync publish to room server failed because no publishInfo");let r=i;if(this.dc){const s=i,{tracks:o}=s,c=Bn(s,["tracks"]);r=Ki(Ze({},c),{tracks:[...o,{type:"data",msid:Me.Data,ssrc:`web_${this.callId.substring(0,8)}_${((n=this.dc.datachannel)==null?void 0:n.id)||"0"}`,codec:"text"}]})}const a=yield this.signalingManager.publish(r);i.signaltid=a.tid})}refreshPushStreamUrl(){return le(this,null,function*(){const i=new Le(Ne.ERR_INNER,"refresh push stream url error"),e=this.url;if(!e)throw i;const t=yield this.signalingManager.refreshUrl({pushstreamurl:e});if(!(t!=null&&t.pushstreamurl))throw i;this.url=t.pushstreamurl})}publishAdd(i,e,t=!1,n=0){return le(this,null,function*(){const r=(e==null?void 0:e.aMsid)===Me.Audio,a=(e==null?void 0:e.vMsid)===Me.VideoLarge,s=(e==null?void 0:e.vMsid)===Me.VideoSmall,o=(e==null?void 0:e.vMsid)===Me.Screen;r&&this.audioPubState.setState(nt.AliRtcStatePublishing),a&&this.videoPubState.setState(nt.AliRtcStatePublishing),s&&this.videoSmallPubState.setState(nt.AliRtcStatePublishing),o&&this.screenPubState.setState(nt.AliRtcStatePublishing);try{const c=yield this.rtsManager.publishAdd(this,i,e,!1,!0);c&&(this.traceId=c),r&&(this.audioPubState.setState(nt.AliRtcStatePublished),this.reportAudioProfile()),a&&(this.videoPubState.setState(nt.AliRtcStatePublished),this.reportVideoProfile()),s&&this.videoSmallPubState.setState(nt.AliRtcStatePublished),o&&(this.screenPubState.setState(nt.AliRtcStatePublished),this.reportScreenProfile()),this.streamTracks=this.rtsManager.publishingTracks;const h={type:Fn.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:t,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceid:c};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),h}catch(c){let h=Ne.ERR_SDK_PUBLISH_INVAILD;if(r&&(this.audioPubState.setState(nt.AliRtcStateNoPublish),h=Ne.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),a&&(this.videoPubState.setState(nt.AliRtcStateNoPublish),h=Ne.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),s&&(this.videoSmallPubState.setState(nt.AliRtcStateNoPublish),h=Ne.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED),o&&(this.screenPubState.setState(nt.AliRtcStateNoPublish),h=Ne.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),c.errorCode===15006&&n<3)return this.publishAdd(i,e,t,n+1);throw Le.fromError(c,h,"publish add failed")}})}publishReplace(i,e){return le(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,i,e),this.streamTracks=this.rtsManager.publishingTracks;const t=(e==null?void 0:e.vMsid)===Me.VideoLarge,n=(e==null?void 0:e.vMsid)===Me.Screen;t&&this.streamManager.setVideoProfile(void 0,void 0,!0),n&&this.streamManager.setScreenProfile(void 0,void 0);const r={type:Fn.Replace,userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),r}catch(t){throw Le.fromError(t,Ne.ERR_INNER,`publish replace failed, vMsid: ${e==null?void 0:e.vMsid} aMsid: ${e==null?void 0:e.aMsid}`)}})}publishDeleteTracks(i){return le(this,null,function*(){const e={type:Fn.Delete,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,i),this.streamTracks=this.rtsManager.publishingTracks,i.audio&&this.audioPubState.setState(nt.AliRtcStateNoPublish),i.video&&(i.vMsid===Me.VideoSmall?this.videoSmallPubState.setState(nt.AliRtcStateNoPublish):this.videoPubState.setState(nt.AliRtcStateNoPublish)),i.screen&&this.screenPubState.setState(nt.AliRtcStateNoPublish),e.tracks=this.streamTracks,this.reportSelfDeviceStatus(),e}catch(t){throw Le.fromError(t,Ne.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return le(this,null,function*(){Re.info(`[${yn.logName}]`,"publishStop",{url:this.url});const i=new Date().getTime();try{const e=this.hasAudioTrackInMS,t=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,r=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),e&&this.audioPubState.setState(nt.AliRtcStateNoPublish),t&&this.videoPubState.setState(nt.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(nt.AliRtcStateNoPublish),r&&this.screenPubState.setState(nt.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(s=>{this.reportPublishMonitor(s)}),this.streamTracks=[];const a={type:Fn.Stop,userid:this.userId,sessionid:this.sessionId,displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(a,{},i),a}catch(e){throw Le.fromError(e,Ne.ERR_INNER,"publish stop failed")}})}unPublish(){return le(this,null,function*(){this.shouldPublish=!1;const i=new Date().getTime();let e={type:Fn.UnPublish,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this.isPublishing){const t=this.hasAudioTrackInMS,n=this.hasCameraTrackInMS,r=this.hasCameraDualTrackInMS,a=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),this.streamTracks=[],this.stopStreamMonitor(),t&&this.audioPubState.setState(nt.AliRtcStateNoPublish),n&&this.videoPubState.setState(nt.AliRtcStateNoPublish),r&&this.videoSmallPubState.setState(nt.AliRtcStateNoPublish),a&&this.screenPubState.setState(nt.AliRtcStateNoPublish),this.traceId="",this.clearStream()}return this.dc&&(this.rtsManager.publishStopDataChannel(this.url,this.dc),this.dataPubState.setState(nt.AliRtcStateNoPublish),this.dc=void 0),this.slsReporter.reportUnpublish(this.callId||"",i,0,""),e}catch(t){throw Le.fromError(t,Ne.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(ai.Local,this.getDeviceStatus())}getDeviceStatus(){var i,e,t,n;let r={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return r.cameraOpen=this.hasCameraTrackInMS,r.videoDisable=this.hasCamera&&!((i=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&i.enabled),r.micOpen=this.hasAudioTrackInMS,r.audioDisable=this.hasMicrophone&&!((e=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&e.enabled),r.screenShare=this.hasScreenTrackInMS,r.screenDisable=this.hasScreenShare&&!((n=(t=this.streamManager.screenStreamInfo)==null?void 0:t.originVideoTrack)!=null&&n.enabled),Yd.getCurrentStatus(r)}resetPreviewElements(){this.previewElements.forEach(i=>{i.srcObject=null,i._playPromise=void 0},[]),this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements.forEach(i=>{i.srcObject=null,i._playPromise=void 0},[]),this.screenPreviewElements=[]}getMediaStats(i){return this.pcMediaStatsMap[i]}reportPublishMonitor(i){if(!i)return;let e;try{e=i===Me.Audio?this.rtsManager.getStreamByMsid({url:this.url,aMsid:i}).audioTrack:this.rtsManager.getStreamByMsid({url:this.url,vMsid:i}).videoTrack}catch{}this.slsReporter.reportPublishMonitor(this.callId,this.traceId||"",i,e,this.monitorDataCache[i]),this.monitorDataCache[i]=[]}reportNetwork(){this.slsReporter.reportNetworkMonitor(this.candidateDataCache),this.candidateDataCache=[]}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>le(this,null,function*(){var i,e;try{const t=yield this.rtsManager.getPCStats();let n,r;if(t==null||t.forEach(s=>{s.type==="media-source"||s.type==="media-playout"?s.id&&(this.pcMediaStatsMap[s.id]=s):s.type==="candidate-pair"&&s.state==="succeeded"&&(n=s)}),((i=this.candidateDataCache)==null?void 0:i.length)>0){const s=this.candidateDataCache[this.candidateDataCache.length-1]||{},o=s,{_last:c}=o;r=Bn(o,["_last"])}((e=this.candidateDataCache)==null?void 0:e.length)>=30&&this.reportNetwork(),n&&(n._last=r,this.candidateDataCache.push(n));let a=Object.keys(this.monitorDataCache).filter(s=>{var o;return((o=this.monitorDataCache[s])==null?void 0:o.length)>0});(this.streamTracks||[]).forEach(s=>{const o=s.msid;if(!o)return;let c;a.includes(o)&&(a=a.filter(h=>h!==o)),c=o===Me.Audio?this.rtsManager.getPublishAudioStats(this.url):this.rtsManager.getPublishVideoStats(this.url,o),c.then(h=>{if(!h.timestamp)return;this.monitorDataCache[o]||(this.monitorDataCache[o]=[]);const l=this.getMediaStats(h.mediaSourceId);h._source=l;const f=this.monitorDataCache[o];let v;if((f==null?void 0:f.length)>0){const p=f[f.length-1]||{},_=p,{_last:m}=_;v=Bn(_,["_last"])}(f==null?void 0:f.length)>=30&&this.reportPublishMonitor(o),h._last=v,h._codec=s.codec||"",this.monitorDataCache[o].push(h)})}),a.forEach(s=>{this.reportPublishMonitor(s)})}catch{}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(i=>{this.reportPublishMonitor(i)})}clearStream(){this.streamManager.stop(),this.audioPubState.setState(nt.AliRtcStatePublishIdle),this.videoPubState.setState(nt.AliRtcStatePublishIdle),this.videoSmallPubState.setState(nt.AliRtcStatePublishIdle),this.screenPubState.setState(nt.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var i;return(i=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:i.getSettings().deviceId}getCurrentMicDeviceId(){var i;return(i=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:i.getSettings().deviceId}enableAudioVolumeIndication(i){this.audioVolumeIndicationInterval!==i&&(this.audioVolumeIndicationInterval>0&&i<=0&&this.audioLevelMonitor.stop(),i>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,i),this.audioVolumeIndicationInterval=i)}sendSEI(i,e,t){return le(this,null,function*(){if(!this.url)return;let n=0;return n=!e||e<1?1:e-1,this.rtsManager.sendSEI(this.url,i,n,t)})}sendDataChannelMessage(i){var e;if(!((e=this.parameter.data)!=null&&e.enablePubDataChannel))throw new Le(Ne.ERR_INNER,"data channel publish is not enabled");if(!this.dc)throw new Le(Ne.ERR_INNER,"data channel is not ready");const t=function(n,r){let a=0;const s=[];for(;a<n.byteLength;){const o=Math.min(r,n.byteLength-a),c=n.slice(a,a+o);s.push(c),a+=o}return s}(i.toBuffer(),1156);t.forEach((n,r)=>{const a=new ns(new bo(n.byteLength,r===t.length-1,r===0?1:0),n);this.dc.send(a.toGRTNBuffer())})}getStats(){return le(this,null,function*(){const i=[];if(this.hasAudioTrackInMS){const r=yield this.rtsManager.getPublishAudioStats(this.url);r&&i.push({stats:r,track:xr.AliRtcAudioTrackMic})}const e=[];if(this.hasCameraTrackInMS){const r=yield this.rtsManager.getPublishVideoStats(this.url,Me.VideoLarge);r&&e.push({track:ft.AliRtcVideoTrackCamera,streamType:ti.AliRtcVideoStreamTypeHigh,stats:r})}if(this.hasCameraDualTrackInMS){const r=yield this.rtsManager.getPublishVideoStats(this.url,Me.VideoSmall);r&&e.push({track:ft.AliRtcVideoTrackCamera,streamType:ti.AliRtcVideoStreamTypeLow,stats:r})}if(this.hasScreenTrackInMS){const r=yield this.rtsManager.getPublishVideoStats(this.url,Me.Screen);r&&e.push({track:ft.AliRtcVideoTrackScreen,stats:r})}let t;const n=yield this.rtsManager.getPCStats();return n==null||n.forEach(r=>{r.type==="candidate-pair"&&r.state==="succeeded"&&(t=r)}),{audio:i,video:e,candidate:t}})}markReconnect(i){const e=[],t=this.streamManager.publishStreams;!t.audio||i&&!i.includes(Me.Audio)||e.push(this.audioPubState),!t.video||i&&!i.includes(Me.VideoLarge)||e.push(this.videoPubState),!t.screen||i&&!i.includes(Me.Screen)||e.push(this.screenPubState),!this.dc||i&&!i.includes(Me.Data)||e.push(this.dataPubState),e.forEach(n=>{n.setState(nt.AliRtcStateReconnecting)})}markReconnected(i){var e;const t=[],n=this.streamManager.publishStreams;if(!n.audio||i&&!i.includes(Me.Audio)||t.push(this.audioPubState),!n.video||i&&!i.includes(Me.VideoLarge)||t.push(this.videoPubState),!n.screen||i&&!i.includes(Me.Screen)||t.push(this.screenPubState),this.dc&&(!i||i.includes(Me.Data))&&(t.push(this.dataPubState),(e=this.parameter.data)==null?void 0:e.enablePubDataChannel)){const r=this.rtsManager.getDatachannelByMsid({url:this.url,msid:Me.Data});this.updateDataChannel(r)}this.publishUpdate(dn.RECONNECT),t.forEach(r=>{r.setState(nt.AliRtcStatePublished)})}},V(yn,"logName","LocalUser"),yn);Lt([ge()],Pt.prototype,"clearPublishState"),Lt([ge()],Pt.prototype,"clear"),Lt([ge(ke)],Pt.prototype,"startDefaultCameraAndMic"),Lt([ge()],Pt.prototype,"setViewConfig"),Lt([ge()],Pt.prototype,"startCameraCapture"),Lt([ge()],Pt.prototype,"stopCameraCapture"),Lt([ge()],Pt.prototype,"startAudioCapture"),Lt([ge()],Pt.prototype,"stopAudioCapture"),Lt([ge()],Pt.prototype,"startCameraAndMic"),Lt([ge()],Pt.prototype,"stopPreview"),Lt([ge()],Pt.prototype,"resumePublish"),Lt([ge()],Pt.prototype,"createLocalStream"),Lt([ge()],Pt.prototype,"stopLocalStream"),Lt([ge()],Pt.prototype,"updateDataChannel"),Lt([ge(ke)],Pt.prototype,"startPublish"),Lt([ge()],Pt.prototype,"updateStreams"),Lt([ge(([i])=>[i])],Pt.prototype,"syncPublishToRoomServer"),Lt([ge()],Pt.prototype,"refreshPushStreamUrl"),Lt([ge(([i,e,t])=>[JSON.stringify(t)])],Pt.prototype,"publishAdd"),Lt([ge(([i,e])=>[JSON.stringify(e)])],Pt.prototype,"publishReplace"),Lt([ge(ke)],Pt.prototype,"publishDeleteTracks"),Lt([ge()],Pt.prototype,"publishStop"),Lt([ge()],Pt.prototype,"unPublish"),Lt([ge(([i,e,t])=>[i.length,e,t])],Pt.prototype,"sendSEI"),Lt([ge(ke)],Pt.prototype,"markReconnect"),Lt([ge(ke)],Pt.prototype,"markReconnected");let xm=Pt;var Vi=(i=>(i.OPUS="opus",i.H264="H264",i.H265="H265",i.AV1="AV1",i.UNKNOWN="",i))(Vi||{}),pt=(i=>(i[i.NotSubscribe=0]="NotSubscribe",i[i.Subscribing=1]="Subscribing",i[i.Subscribed=2]="Subscribed",i))(pt||{}),lr=(i=>(i.VideoTrackEnded="videoTrackEnded",i.AudioTrackEnded="audioTrackEnded",i.ScreenTrackEnded="screenTrackEnded",i))(lr||{});const nh=i=>le(void 0,null,function*(){return yield St.AliRTS.createStream({custom:!0,mediaStream:i})}),Eo=i=>le(void 0,null,function*(){const e=(t=>{const n=new MediaStream;return n.addTrack(t),n})(i);return yield nh(e)});var Im=Object.defineProperty,Pm=Object.getOwnPropertyDescriptor;class Va extends Kt{constructor(){super(),V(this,"audioInfo",{subscribeState:pt.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:Vi.UNKNOWN}),V(this,"videoLargeInfo",{subscribeState:pt.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:Vi.UNKNOWN}),V(this,"videoSmallInfo",{subscribeState:pt.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:Vi.UNKNOWN}),V(this,"screenInfo",{subscribeState:pt.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:Vi.UNKNOWN}),V(this,"dataInfo",{subscribeState:pt.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:Vi.UNKNOWN}),V(this,"audioVolume",1),V(this,"audioMuted",!1),V(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}getDataInfo(){return this.dataInfo}get subscribingInfos(){return[this.audioInfo,this.videoLargeInfo,this.videoSmallInfo,this.screenInfo].filter(e=>e.msid&&e.subscribeState===pt.Subscribed)}get hasTrack(){return this.hasAudio||this.hasVideo||this.hasScreen||this.hasData}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get hasData(){return this.dataInfo.ssrc!==""}get isAudioSubscribed(){return this.audioInfo.subscribeState===pt.Subscribed}get isAudioSubscribing(){return this.audioInfo.subscribeState===pt.Subscribing}get isVideoSubscribed(){return this.isVideoLargeSubscribed||this.isVideoSmallSubscribed}get isVideoSubscribing(){return this.isVideoLargeSubscribing||this.isVideoSmallSubscribing}get isVideoLargeSubscribed(){return this.videoLargeInfo.subscribeState===pt.Subscribed}get isVideoLargeSubscribing(){return this.videoLargeInfo.subscribeState===pt.Subscribing}get isVideoSmallSubscribed(){return this.videoSmallInfo.subscribeState===pt.Subscribed}get isVideoSmallSubscribing(){return this.videoSmallInfo.subscribeState===pt.Subscribing}get isScreenSubscribed(){return this.screenInfo.subscribeState===pt.Subscribed}get isScreenSubscribing(){return this.screenInfo.subscribeState===pt.Subscribing}get isDataSubscribed(){return this.dataInfo.subscribeState===pt.Subscribed}get isDataSubscribing(){return this.dataInfo.subscribeState===pt.Subscribing}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:Vi.UNKNOWN}get audioTrackInfo(){return this.hasAudio?xr.AliRtcAudioTrackMic:xr.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?ft.AliRtcVideoTrackBoth:this.hasVideo?ft.AliRtcVideoTrackCamera:this.hasScreen?ft.AliRtcVideoTrackScreen:ft.AliRtcVideoTrackNo}updateTracks(e){let t="",n="",r="",a="",s="";return e?(e.forEach(o=>{var c;let h=Vi.UNKNOWN;const l=((c=o==null?void 0:o.attr)==null?void 0:c.reason)==="reconnect";if(o.userdata){const{codec:v}=JSON.parse(o.userdata);v&&(h=v)}var f;(f=o.msid)===Me.Audio||f===ra.Audio?(t=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=h,(l||this.audioInfo.ssrc!==t)&&(this.audioInfo.subscribeState=pt.NotSubscribe)):(v=>v===Me.VideoSmall)(o.msid)?(r=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=h,(l||this.videoSmallInfo.ssrc!==r)&&(this.videoSmallInfo.subscribeState=pt.NotSubscribe)):(v=>v===Me.VideoLarge||v===ra.VideoLarge)(o.msid)?(n=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=h,(l||this.videoLargeInfo.ssrc!==n)&&(this.videoLargeInfo.subscribeState=pt.NotSubscribe)):(v=>v===Me.Screen)(o.msid)?(a=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=h,(l||this.screenInfo.ssrc!==a)&&(this.screenInfo.subscribeState=pt.NotSubscribe)):(v=>v===Me.Data)(o.msid)&&(s=o.ssrc,this.dataInfo.msid=o.msid,this.dataInfo.codec=h,(l||this.dataInfo.ssrc!==s)&&(this.dataInfo.subscribeState=pt.NotSubscribe))}),this.updateRemoteTrackSsrc(t,n,r,a,s)):this.updateRemoteTrackSsrc(t,n,r,a,s),{}}updateRemoteTrackSsrc(e,t,n,r,a){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=n,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=r,this.dataInfo.ssrc=a}markRemoteTrackSubscribing(e){return e.video&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=pt.Subscribing),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=pt.Subscribing)),e.screen&&(this.screenInfo.subscribeState=pt.Subscribing),e.audio&&(this.audioInfo.subscribeState=pt.Subscribing),e.data&&(this.dataInfo.subscribeState=pt.Subscribing),{videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo}}updateRemoteTrackSubState(e){return e.video!==void 0&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=e.video?pt.Subscribed:pt.NotSubscribe),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=e.video?pt.Subscribed:pt.NotSubscribe)),e.screen!==void 0&&(this.screenInfo.subscribeState=e.screen?pt.Subscribed:pt.NotSubscribe),e.audio!==void 0&&(this.audioInfo.subscribeState=e.audio?pt.Subscribed:pt.NotSubscribe),e.data!==void 0&&(this.dataInfo.subscribeState=e.data?pt.Subscribed:pt.NotSubscribe),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo,dataInfo:this.dataInfo}}updateRemoteUserDeviceStatus(e){let t=Yd.parseStatus(e);const{audioDisable:n,videoDisable:r,screenDisable:a}=t;return this.userStatus?(this.userStatus.audioDisable!=n&&(this.userStatus.audioDisable=n,this.emit(ai.Remote,n?Nt.MuteAudio:Nt.UnmuteAudio)),this.userStatus.videoDisable!=r&&(this.userStatus.videoDisable=r,this.emit(ai.Remote,r?Nt.MuteVideo:Nt.UnmuteVideo)),this.userStatus.screenDisable!=a&&(this.userStatus.screenDisable=a,this.emit(ai.Remote,a?Nt.MuteScreen:Nt.UnmuteScreen))):(this.userStatus=t,this.emit(ai.Remote,n?Nt.MuteAudio:Nt.UnmuteAudio),this.emit(ai.Remote,r?Nt.MuteVideo:Nt.UnmuteVideo),this.emit(ai.Remote,a?Nt.MuteScreen:Nt.UnmuteScreen)),!1}}V(Va,"logName","RemoteStreamInfo"),((i,e,t,n)=>{for(var r,a=Pm(e,t),s=i.length-1;s>=0;s--)(r=i[s])&&(a=r(e,t,a)||a);a&&Im(e,t,a)})([ge()],Va.prototype,"updateRemoteTrackSubState");class Dm{constructor(e){V(this,"remoteUser"),this.remoteUser=e}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}get audioElement(){return this.remoteUser.getAudioElement()}}var Lm=Object.defineProperty,Om=Object.getOwnPropertyDescriptor,qt=(i,e,t,n)=>{for(var r,a=Om(e,t),s=i.length-1;s>=0;s--)(r=i[s])&&(a=r(e,t,a)||a);return a&&Lm(e,t,a),a};class Dr extends Kt{constructor(){super(),V(this,"state"),V(this,"time"),V(this,"_enabled"),this.state=ut.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,n=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-n)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}var Ro;const Gt=(Ro=class extends qd{constructor(i){var e;const{userId:t,displayName:n,rtsManager:r,usersViewMap:a,slsReporter:s,signalingManager:o,localUser:c,audioVolumeIndicationInterval:h,playoutVolume:l,parameter:f}=i;super(t,n,r,h),V(this,"remoteCallId",""),V(this,"remoteUserInfo"),V(this,"localUser"),V(this,"lastPubId",""),V(this,"stream"),V(this,"screenStream"),V(this,"viewMap"),V(this,"audioTrack"),V(this,"audioElement"),V(this,"subscribed",!1),V(this,"mediaStream"),V(this,"secondaryMediaStream"),V(this,"prevSubConfig"),V(this,"signalingManager"),V(this,"slsReporter"),V(this,"wantSubAudio",!1),V(this,"wantSubVideo",!1),V(this,"wantSubScreen",!1),V(this,"defaultVideoStreamType",ti.AliRtcVideoStreamTypeHigh),V(this,"audioMuted",!1),V(this,"playoutVolume",1),V(this,"playoutGainNode"),V(this,"audioSubState"),V(this,"videoSubState"),V(this,"videoLargeSubState",new Dr),V(this,"videoSmallSubState",new Dr),V(this,"screenSubState"),V(this,"dataSubState"),V(this,"dc"),V(this,"dcMsgWaitingPieces",[]),V(this,"streamInfo"),V(this,"_streamUrl",""),V(this,"parameter",{}),V(this,"monitorTimerId"),V(this,"monitorDataCache",{}),V(this,"traceId",""),V(this,"handleAudioContextSuspended",v=>{v.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")}),V(this,"onDataChannelMessage",v=>{var p;const _=ns.parse(v.slice(4));let m;if(_.body){if(!_.isFin)return _.header.frameType===1&&(this.dcMsgWaitingPieces=[]),void this.dcMsgWaitingPieces.push(_.body);if(this.dcMsgWaitingPieces.length>0){const d=this.dcMsgWaitingPieces.reduce((u,b)=>u+b.byteLength,_.body.byteLength);try{const u=new ArrayBuffer(d);let b=0;for(let y=0;y<this.dcMsgWaitingPieces.length;y++){const g=this.dcMsgWaitingPieces[y];new Uint8Array(u,b,g.byteLength).set(new Uint8Array(g)),b+=g.byteLength}new Uint8Array(u,b,_.body.byteLength).set(new Uint8Array(_.body)),m=zn.parse(u)}catch{}this.dcMsgWaitingPieces=[],m||(m=zn.parse(_.body))}else m=zn.parse(_.body);m||Re.event(`[${this.logName}]`,`parse data channel message fail, piece count: ${this.dcMsgWaitingPieces.length+1}`)}m&&(Re.event(`[${this.logName}]`,`receive dc message, length(${(p=m.data)==null?void 0:p.byteLength})`),this.emit("remoteDataChannelMessage",this.uid,m))}),V(this,"onDataChannelError",v=>{this.emit("occurError",Le.fromError(v,Ne.ERR_SDK_SUBSCRIBE_DATA_ERROR))}),V(this,"dataChannelConnected",v=>{v&&(this.dc=v,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"),this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dc.on("message",this.onDataChannelMessage),this.dc.on("error",this.onDataChannelError))}),V(this,"handleAudioPaused",()=>{this.emit("remoteAudioPlayError",this.uid,"paused")}),this.streamInfo=new Va,this.remoteUserInfo=new Dm(this),this.parameter=f,this.streamInfo.on(ai.Remote,v=>{this.emit(ai.Remote,v,this.userId)}),this.signalingManager=o,this.viewMap=(e=a[t])!=null?e:{cameraViews:[],screenViews:[]},a[t]=this.viewMap,this.slsReporter=s,this.localUser=c,this.audioSubState=new Dr,this.audioSubState.on("change",(v,p,_)=>{this.emit("audioSubscribeStateChanged",this.uid,v,p,_)}),this.videoSubState=new Dr,this.videoSubState.on("change",(v,p,_)=>{this.emit("videoSubscribeStateChanged",this.uid,v,p,_)}),this.screenSubState=new Dr,this.screenSubState.on("change",(v,p,_)=>{this.emit("screenSubscribeStateChanged",this.uid,v,p,_)}),this.dataSubState=new Dr,this.dataSubState.on("change",(v,p,_)=>{this.emit("dataSubscribeStateChanged",this.uid,v,p,_)}),this.playoutVolume=l}get logName(){return`${Ro.logName}(${this.userId})`}get streamUrl(){return this._streamUrl}set streamUrl(i){this._streamUrl=i,this.rtsManager.updateAuth(i)}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(i){this.wantSubAudio=i}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(i){this.wantSubVideo=i}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(i){this.wantSubScreen=i}setRemoteDefaultVideoStreamType(i){i!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=i,this.updateSubscribe(Ct.User))}setAudioMuted(i){this.audioMuted=i,this.toggleAudio(!i)}getAudioElement(){return this.audioElement}setPlayoutVolume(i){if(this.playoutVolume=i,this.audioElement)if(this.parameter.enableAudioContextPlayoutVolume)if(this.playoutGainNode)this.playoutGainNode.gain.value=i;else{const e=this.audioElement.srcObject;if(e){const t=_o.getInstance();t.addEventListener("statechange",this.handleAudioContextSuspended);const n=t.createMediaStreamSource(e);this.audioElement.muted=!0,this.playoutGainNode=t.createGain(),n.connect(this.playoutGainNode),this.playoutGainNode.gain.value=i,this.playoutGainNode.connect(t.destination)}}else this.audioElement.volume=i}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){return this.streamInfo.hasAudio}get audioSSRC(){var i;return this.streamInfo.isAudioSubscribed&&((i=this.streamInfo.getAudioInfo())==null?void 0:i.ssrc)||""}get hasVideoTrack(){return this.streamInfo.hasVideo}get videoSSRC(){var i,e;return this.streamInfo.isVideoSubscribed?((i=this.streamInfo.getVideoLargeInfo())==null?void 0:i.ssrc)||"":this.streamInfo.isVideoSmallSubscribed&&((e=this.streamInfo.getVideoSmallInfo())==null?void 0:e.ssrc)||""}get hasVideoLargeTrack(){return this.streamInfo.hasVideoLarge}get hasVideoSmallTrack(){return this.streamInfo.hasVideoSmall}get hasScreenTrack(){return this.streamInfo.hasScreen}get isAudioSubscribing(){return this.streamInfo.isAudioSubscribed||this.streamInfo.isAudioSubscribing}get isVideoSubscribing(){return this.streamInfo.isVideoSubscribed||this.streamInfo.isVideoSubscribing}get isVideoLargeSubscribing(){return this.streamInfo.isVideoLargeSubscribed||this.streamInfo.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing}get isScreenSubscribing(){return this.streamInfo.isScreenSubscribed||this.streamInfo.isScreenSubscribing}get isDataSubscribing(){return this.streamInfo.isDataSubscribed||this.streamInfo.isDataSubscribing}get audioEnabled(){var i,e;return!!((e=(i=this.stream)==null?void 0:i.audioTrack)!=null&&e.enabled)}get videoEnabled(){var i,e;return!!((e=(i=this.stream)==null?void 0:i.videoTrack)!=null&&e.enabled)}get screenEnabled(){var i,e;return!!((e=(i=this.screenStream)==null?void 0:i.videoTrack)!=null&&e.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(i,e){if(e!==ft.AliRtcVideoTrackScreen&&e!==ft.AliRtcVideoTrackCamera)throw new Le(Ne.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");i?oa(i).forEach(t=>{t.setAttribute("playsinline",""),St.AliRTS.BrowserUtil.isMicroMessenger&&(t.setAttribute("x5-video-player-type","h5-page"),t.setAttribute("x5-playsinline",""),St.AliRTS.SystenUtil.isAndroid||St.AliRTS.SystenUtil.isIos&&t.setAttribute("x-webkit-airplay","allow")),e===ft.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(t):this.viewMap.cameraViews.push(t),this.play(t,e===ft.AliRtcVideoTrackScreen)}):(this.stopPlayAll(e===ft.AliRtcVideoTrackScreen),e===ft.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(i=!0){return le(this,null,function*(){Ul(Ro.prototype,this,"clear").call(this),this.stopPlayAudio(),this.stopStreamMonitor(),i&&this.subscribeDeleteAllTracks(this.streamUrl).catch(e=>{Re.event(`[${this.logName}]`,`stopSubscribeAllTracks error: ${e.message||e}`)}),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,_o.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),this.streamInfo.removeAllListeners(ai.Remote)})}updateRemoteUserDeviceStatus(i){this.streamInfo.updateRemoteUserDeviceStatus(i)}updateRemoteTracks(i,e,t,n){return le(this,null,function*(){return this.remoteCallId=i,this.streamUrl&&this.streamInfo.hasTrack||(this.streamUrl=e),this.streamInfo.updateTracks(n)})}subscribe(i,e){return le(this,arguments,function*(t,n,r=Date.now()){var a,s;this.createCallId();let o=t;if(!o){const{hasAudio:p,hasVideo:_,hasScreen:m,hasData:d}=(a=this.streamInfo)!=null?a:{};o={audio:this.wantSubAudio&&p,video:this.wantSubVideo&&_,screen:this.wantSubScreen&&m,data:((s=this.parameter.data)==null?void 0:s.enableSubDataChannel)&&d}}this.streamInfo.markRemoteTrackSubscribing(o);const{screen:c,audio:h,video:l,vMsid:f}=o,v=[];(l||h)&&v.push({audio:h,video:l,vMsid:f}),c&&v.push({screen:c}),(v.length!==0||t!=null&&t.data)&&(yield Promise.all(v.map(p=>this.subscribeProxy(p,n||Ct.User,r))),t!=null&&t.data&&this.subscribeDataChannel())})}subscribeProxy(i,e,t){return le(this,null,function*(){var n,r;let a=new Date().getTime(),s="";try{i.audio&&this.audioSubState.setState(ut.AliRtcStateSubscribing),i.video&&(this.videoSubState.currentState!==ut.AliRtcStateSubscribeIdle&&this.videoSubState.currentState!==ut.AliRtcStateNoSubscribe||this.videoSubState.setState(ut.AliRtcStateSubscribing)),i.screen&&this.screenSubState.setState(ut.AliRtcStateSubscribing);const o=yield this.rtsManager.subscribe({remoteUser:this,options:i},e,((n=this.localUser)==null?void 0:n.callId)||"",this.callId,t);if(!o)return i.audio&&this.audioSubState.setState(ut.AliRtcStateNoSubscribe),i.video&&this.videoSubState.setState(ut.AliRtcStateNoSubscribe),i.screen&&this.screenSubState.setState(ut.AliRtcStateNoSubscribe),void this.streamInfo.updateRemoteTrackSubState({audio:i.audio!==!0&&void 0,video:i.video!==!0&&void 0,screen:i.screen!==!0&&void 0,vMsid:i.vMsid});this.streamInfo.updateRemoteTrackSubState(i),s=o.traceId||"";const{stream:c}=o;if(s&&(this.traceId=s),i.audio){const f=c.audioTrack;f&&(this.audioTrack=f,(r=c.mediaStream)==null||r.removeTrack(f),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(f,this.audioVolumeIndicationInterval)),this.audioSubState.getEnabled()||this.toggleAudio(!1),this.audioSubState.setState(ut.AliRtcStateSubscribed)}i.video&&(this.updateStream(c,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.videoSubState.setState(ut.AliRtcStateSubscribed),i.vMsid===Me.VideoSmall?this.videoSmallSubState.setState(ut.AliRtcStateSubscribed):this.videoLargeSubState.setState(ut.AliRtcStateSubscribed)),i.screen&&(this.updateScreenStream(c),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.screenSubState.setState(ut.AliRtcStateSubscribed));const h=new Date().getTime()-a,l=Date.now();setTimeout(()=>{this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!i.video&&i.vMsid===Me.VideoLarge,!!i.video&&i.vMsid===Me.VideoSmall,!!i.screen,!!i.audio,0,"",h,{pctid:this.rtsManager.pcTraceId,subtid:this.traceId,ajsub:e===Ct.Join?1:0,url:this.streamUrl,est:a},l)},6e3),this.startStreamMonitor(),o.isHTTP&&o.statsCheckPromise&&(yield Promise.race([o.statsCheckPromise,Hn(1500)]))}catch(o){const c=new Date().getTime()-a;i.audio&&this.audioSubState.setState(ut.AliRtcStateNoSubscribe),i.video&&this.videoSubState.setState(ut.AliRtcStateNoSubscribe),i.screen&&this.screenSubState.setState(ut.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({audio:i.audio!==!0&&void 0,video:i.video!==!0&&void 0,screen:i.screen!==!0&&void 0,vMsid:i.vMsid}),o&&(o.message=`user(${this.uid}) subscribe error, ${(o==null?void 0:o.message)||""}`);let h=Ne.ERR_INNER;i.audio&&(h=Ne.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED),i.video&&(h=i.vMsid===Me.VideoSmall?Ne.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED:Ne.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED),i.screen&&(h=Ne.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED),this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!i.video&&i.vMsid===Me.VideoLarge,!!i.video&&i.vMsid===Me.VideoSmall,!!i.screen,!!i.audio,h,"",c,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:e===Ct.Join?1:0,url:this.streamUrl,est:a});const l=Le.fromError(o,h);this.emit("remoteSubscribeError",l)}})}subscribeDeleteTracks(i){return le(this,null,function*(){const{audio:e,video:t,screen:n,data:r,vMsid:a}=i,s=[];(e||t||r)&&s.push({audio:e,video:t,vMsid:a}),n&&s.push({screen:n}),s.length!==0&&(yield Promise.all(s.map(o=>this.subscribeDeleteProxy(o))),i.data&&this.subscribeDeleteDataChannel())})}subscribeDeleteProxy(i){return le(this,null,function*(){try{const e=yield this.rtsManager.subscribeDelete({remoteUser:this,options:i}),{stream:t}=e??{},n={};i.audio===!0&&(n.audio=!1,this.audioSubState.setState(ut.AliRtcStateNoSubscribe)),i.video===!0&&(n.video=!1,i.vMsid===Me.VideoSmall?(this.videoSmallSubState.setState(ut.AliRtcStateNoSubscribe),this.videoLargeSubState.currentState!==ut.AliRtcStateNoSubscribe&&this.videoLargeSubState.currentState!==ut.AliRtcStateSubscribeIdle||this.videoSubState.setState(ut.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(ut.AliRtcStateNoSubscribe),this.videoSmallSubState.currentState!==ut.AliRtcStateNoSubscribe&&this.videoSmallSubState.currentState!==ut.AliRtcStateSubscribeIdle||this.videoSubState.setState(ut.AliRtcStateNoSubscribe))),i.screen===!0&&(n.screen=!1,this.screenSubState.setState(ut.AliRtcStateNoSubscribe));const{callId:r,remoteCallId:a}=this,s={callid:r,remoteCallid:a,remoteStream:t};return i.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:i.audio!==!0&&void 0,video:i.video!==!0&&void 0,screen:i.screen!==!0&&void 0,vMsid:i.vMsid}),s}catch(e){throw Le.fromError(e,Ne.ERR_INNER,"subscribe delete failed")}})}restore(){this.callId="",this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1,data:!1}),this.audioElement&&this.audioElement.removeEventListener("pause",this.handleAudioPaused)}resumeAudio(){return le(this,null,function*(){const i=_o.getInstance();return i.state!=="running"&&i.resume(),this.audioElement?this.audioElement.play():this.playAudio()})}resumeVideo(i){return le(this,null,function*(){return i&&i!==ft.AliRtcVideoTrackCamera&&i!==ft.AliRtcVideoTrackBoth?i&&i!==ft.AliRtcVideoTrackScreen&&i!==ft.AliRtcVideoTrackBoth?void 0:this.playAll(!0):this.playAll()})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(i){return le(this,null,function*(){let e=new Date().getTime();try{i?yield this.subscribeDeleteTracks(i):yield this.subscribeDeleteAllTracks(this.streamUrl),this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-e,0,"")}catch(t){throw this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-e,0,""),t}})}subscribeDeleteAllTracks(i){return le(this,null,function*(){var e,t,n,r;const{callId:a,remoteCallId:s}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing||this.dc)&&i)try{yield this.subscribeDeleteTracks({audio:this.isAudioSubscribing,video:this.isVideoSubscribing,screen:this.isScreenSubscribing,data:!!this.dc}),this.restore();const o={callid:a,remoteCallid:s,remoteStream:this.stream};return this.callId="",o}catch(o){if(((r=(n=(t=(e=o==null?void 0:o.extraInfo)==null?void 0:e.parsedData)==null?void 0:t.streams)==null?void 0:n[0])==null?void 0:r.res_code)!==404)throw Le.fromError(o,Ne.ERR_INNER,"subscribe stop failed")}})}updateStream(i,e=!1){return le(this,null,function*(){this.stream&&this.stream.videoTrack&&i.mediaStream&&e&&(yield new Promise(t=>{let n,r;if(i.mediaStream){r=document.createElement("video");const a=()=>{Re.event(`[${this.logName}]`,"new mediaStream canplay"),r&&r.removeEventListener("canplaythrough",a,!1),r=void 0,clearTimeout(n),t(!0)};r.addEventListener("canplaythrough",a,!1),(r._playPromise||Promise.resolve()).then(()=>{r&&i.mediaStream&&(r.srcObject=i.mediaStream)})}else t(!0);n=window.setTimeout(()=>{Re.event(`[${this.logName}]`,"new mediaStream timeout"),r=void 0,t(!0)},3e3)}),this.updateSubscribe(Ct.User)),this.stream=i,this.playAll(!1,e),!this.subscribed&&i&&(this.subscribed=!0),i.hasAudio&&this.isAudioSubscribing&&i.enableAudio(),i.hasVideo&&this.isVideoSubscribing&&i.enableVideo()})}updateScreenStream(i){this.screenStream=i,this.playAll(!0),!this.subscribed&&i&&(this.subscribed=!0),i.hasVideo&&this.isScreenSubscribing&&i.enableVideo()}clearStream(){var i;(i=this.stream)==null||i.stop(),this.stream=void 0}clearScreenStream(){var i;(i=this.screenStream)==null||i.stop(),this.screenStream=void 0}subscribeDataChannel(){if(this.dc)try{this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc=void 0}catch{}if(!this.streamInfo.hasAudio&&!this.streamInfo.hasVideo&&!this.streamInfo.hasScreen)return this.dataSubState.setState(ut.AliRtcStateNoSubscribe),void this.streamInfo.updateRemoteTrackSubState({data:!1});this.dataSubState.setState(ut.AliRtcStateSubscribing),this.rtsManager.subscribeAddDataChannel(this.streamUrl).then(i=>{if(i)return this.dataChannelConnected(i),this.dataSubState.setState(ut.AliRtcStateSubscribed),void this.streamInfo.updateRemoteTrackSubState({data:!0});throw new Error("no dc founded")}).catch(i=>{const e=Le.fromError(i,Ne.ERR_INNER,"subscribe data failed");this.emit("remoteSubscribeError",e),this.dataSubState.setState(ut.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({data:!1})})}subscribeDeleteDataChannel(){if(this.dc){try{this.rtsManager.subscribeDeleteDatachannel(this.streamUrl,this.dc)}catch{}this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dataSubState.setState(ut.AliRtcStateNoSubscribe),this.dc=void 0,this.streamInfo.updateRemoteTrackSubState({data:!1})}}getRetryOptions(){var i,e;const t={};this.wantSubAudio&&this.streamInfo.hasAudio&&(t.audio=!0,t.aMsid=((i=this.streamInfo.getAudioInfo())==null?void 0:i.msid)||Me.Audio),this.wantSubVideo&&this.streamInfo.hasVideo&&(this.defaultVideoStreamType===ti.AliRtcVideoStreamTypeLow&&this.streamInfo.hasVideoSmall?(t.video=!0,t.vMsid=Me.VideoSmall):this.streamInfo.hasVideoLarge&&(t.video=!0,t.vMsid=((e=this.streamInfo.getVideoLargeInfo())==null?void 0:e.msid)||Me.VideoLarge)),this.wantSubScreen&&this.streamInfo.hasScreen&&(t.screen=!0);let n={};if(t.audio||t.video)n={audio:t.audio,video:t.video},this.streamInfo.updateRemoteTrackSubState({screen:!1,data:!1});else{if(!t.screen)return;n={screen:t.screen},this.streamInfo.updateRemoteTrackSubState({data:!1})}return{remoteUser:this,options:n}}updateSubscribe(i){var e,t,n,r,a,s;const o=Date.now(),c={},h={};return this.wantSubAudio&&!this.isAudioSubscribing&&this.streamInfo.hasAudio&&this.audioSubState.currentState!==ut.AliRtcStateReconnecting?(c.audio=!0,c.aMsid=((e=this.streamInfo.getAudioInfo())==null?void 0:e.msid)||Me.Audio):this.wantSubAudio&&this.streamInfo.hasAudio||!this.isAudioSubscribing||(h.audio=!0,h.aMsid=((t=this.streamInfo.getAudioInfo())==null?void 0:t.msid)||Me.Audio),this.wantSubVideo&&this.streamInfo.hasVideo?(this.defaultVideoStreamType===ti.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall&&this.videoSmallSubState.currentState!==ut.AliRtcStateReconnecting?(c.video=!0,c.vMsid=Me.VideoSmall):this.isVideoLargeSubscribing||!this.streamInfo.hasVideoLarge||this.defaultVideoStreamType===ti.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall||this.videoLargeSubState.currentState===ut.AliRtcStateReconnecting||(c.video=!0,c.vMsid=((n=this.streamInfo.getVideoLargeInfo())==null?void 0:n.msid)||Me.VideoLarge),this.defaultVideoStreamType===ti.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(h.video=!0,h.vMsid=Me.VideoLarge):this.defaultVideoStreamType!==ti.AliRtcVideoStreamTypeHigh&&this.streamInfo.hasVideoSmall||!this.isVideoLargeSubscribing||!this.isVideoSmallSubscribing||(h.video=!0,h.vMsid=Me.VideoSmall)):this.wantSubVideo&&this.streamInfo.hasVideo||!this.isVideoSubscribing||(h.video=!0,h.vMsid=this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?Me.VideoSmall:((r=this.streamInfo.getVideoLargeInfo())==null?void 0:r.msid)||Me.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&this.streamInfo.hasScreen&&this.screenSubState.currentState!==ut.AliRtcStateReconnecting?c.screen=!0:this.wantSubScreen&&this.streamInfo.hasScreen||!this.isScreenSubscribing||(h.screen=!0),(a=this.parameter.data)!=null&&a.enableSubDataChannel&&!this.isDataSubscribing&&this.streamInfo.hasData&&this.dataSubState.currentState!==ut.AliRtcStateReconnecting?c.data=!0:(s=this.parameter.data)!=null&&s.enableSubDataChannel&&this.streamInfo.hasData||!this.isDataSubscribing||(h.data=!0),this.dc&&c.data&&this.subscribeDeleteDataChannel(),(c.audio||c.video||c.screen||c.data)&&this.subscribe(c,i,o),(h.audio||h.video||h.screen)&&this.subscribeDeleteTracks(h),{addOption:c,deleteOption:h}}handleAutoPlayFailed(){Re.event(`[${this.logName}]`,"auto play failed"),this.emit("remoteAudioAutoPlayFail",this.uid);const i=()=>{this.resumeAudio().then(()=>{document.removeEventListener("click",i,!1),document.removeEventListener("touchstart",i,!1)})};document.addEventListener("click",i,!1),document.addEventListener("touchstart",i,!1)}handleVideoPlayFailded(i,e){this.emit("remoteVideoAutoPlayFail",this.uid,e);const t=()=>{var n;const r=(n=e===ft.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;i.srcObject===r&&this.play(i,e===ft.AliRtcVideoTrackScreen),document.removeEventListener("click",t,!1),document.removeEventListener("touchstart",t,!1)};document.addEventListener("click",t,!1),document.addEventListener("touchstart",t,!1)}playAudio(){return le(this,null,function*(){var i,e;if(this.audioTrack){if(this.toggleAudio(!this.audioMuted),this.audioElement||(Re.event(`[${this.logName}]`,"create audio element"),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("autoplay","autoplay"),this.audioElement.addEventListener("pause",this.handleAudioPaused),this.setPlayoutVolume(this.playoutVolume)),((e=(i=this.audioElement.srcObject)==null?void 0:i.getAudioTracks())==null?void 0:e[0])!==this.audioTrack){let t=this.audioElement.srcObject;t?t.getAudioTracks().forEach(n=>{t.removeTrack(n)}):(t=new MediaStream,this.audioElement.srcObject=t),t.addTrack(this.audioTrack)}if(St.AliRTS.SystenUtil.isIos&&parseInt(St.AliRTS.SystenUtil.systemVersion)<=13){Re.event(`[${this.logName}]`,"play audio for iOS 13-");const t=this.audioElement;t.setAttribute("autoplay","");const n=()=>{t.removeEventListener("playing",n),t.pause(),t.play().catch(()=>{this.handleAutoPlayFailed()})};this.audioElement.addEventListener("playing",n)}else(()=>{var t;Re.event(`[${this.logName}]`,"try play audio"),(t=this.audioElement)==null||t.play().then(()=>{Re.event(`[${this.logName}]`,"play audio success")}).catch(()=>{this.handleAutoPlayFailed()})})()}else Re.event(`[${this.logName}]`,"audio track is null")})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.removeEventListener("pause",this.handleAudioPaused))}playAll(i=!1,e=!1){i?(this.viewMap.screenViews||[]).forEach(t=>{this.play(t,i,e)}):(this.viewMap.cameraViews||[]).forEach(t=>{this.play(t,i,e)})}play(i,e=!1,t=!1){const n=e?this.screenStream:this.stream;i&&n&&n.mediaStream&&eh(i,n.mediaStream,t).catch(r=>{r.code!==20&&r.name!=="AbortError"&&this.handleVideoPlayFailded(i,e?ft.AliRtcVideoTrackScreen:ft.AliRtcVideoTrackCamera)})}stopPlayAll(i=!1){i?this.viewMap.screenViews.forEach(e=>{hn(e)}):this.viewMap.cameraViews.forEach(e=>{hn(e)})}toggleAudio(i=!0){this.audioSubState.setEnabled(i),this.audioElement&&(this.audioElement.muted=!i)}toggleVideo(i=!0){this.videoSubState.setEnabled(i),this.stream&&(i?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(i=!0){this.screenSubState.setEnabled(i),this.screenStream&&(i?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return le(this,null,function*(){var i,e,t;const n=[];if(this.isAudioSubscribing){const a=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);a&&n.push({uid:this.uid,track:xr.AliRtcAudioTrackMic,stats:a})}const r=[];if(this.streamInfo.isVideoLargeSubscribed){const a=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((i=this.streamInfo.getVideoLargeInfo())==null?void 0:i.msid)||Me.VideoLarge);a&&r.push({uid:this.uid,track:ft.AliRtcVideoTrackCamera,streamType:ti.AliRtcVideoStreamTypeHigh,stats:a})}if(this.streamInfo.isVideoSmallSubscribed){const a=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((e=this.streamInfo.getVideoSmallInfo())==null?void 0:e.msid)||Me.VideoSmall);a&&r.push({uid:this.uid,track:ft.AliRtcVideoTrackCamera,streamType:ti.AliRtcVideoStreamTypeLow,stats:a})}if(this.isScreenSubscribing){const a=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((t=this.streamInfo.getScreenInfo())==null?void 0:t.msid)||Me.Screen);a&&r.push({uid:this.uid,track:ft.AliRtcVideoTrackScreen,stats:a})}return{audio:n,video:r}})}enableAudioVolumeIndication(i){this.audioVolumeIndicationInterval!==i&&(this.audioVolumeIndicationInterval>0&&i<=0&&this.audioLevelMonitor.stop(),i>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,i),this.audioVolumeIndicationInterval=i)}reportSubscribeMonitor(i){i&&(this.slsReporter.reportSubscribeMonitor(this.callId,this.remoteCallId,this.traceId,i,this.monitorDataCache[i]),this.monitorDataCache[i]=[])}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>le(this,null,function*(){try{if(this.streamInfo.subscribingInfos.length===0)return void this.stopStreamMonitor();let i=Object.keys(this.monitorDataCache).filter(e=>{var t;return((t=this.monitorDataCache[e])==null?void 0:t.length)>0});this.streamInfo.subscribingInfos.forEach(e=>{const t=e.msid;if(!t)return;let n;i.includes(t)&&(i=i.filter(a=>a!==t));const r=t===Me.Audio;n=r?this.rtsManager.getSubscribeAudioStats(this.streamUrl):this.rtsManager.getSubscribeVideoStats(this.streamUrl,t),n.then(a=>{var s;if(!a.timestamp)return;this.monitorDataCache[t]||(this.monitorDataCache[t]=[]);const o=this.monitorDataCache[t];let c;if((o==null?void 0:o.length)>0){const h=o[o.length-1]||{},l=h,{_last:f}=l;c=Bn(l,["_last"])}(o==null?void 0:o.length)>=30&&this.reportSubscribeMonitor(t),a._last=c,a._codec=e.codec,r&&(a._source=(s=this.localUser)==null?void 0:s.getMediaStats(a.playoutId)),this.monitorDataCache[t].push(a)})}),i.forEach(e=>{this.reportSubscribeMonitor(e)})}catch{}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(i=>{this.reportSubscribeMonitor(i)})}markReconnect(i){const e=[];!this.isAudioSubscribing||i&&!i.includes(this.streamInfo.getAudioInfo().msid)||e.push(this.audioSubState),this.isVideoSubscribing&&(!i||i.includes(this.streamInfo.getVideoLargeInfo().msid)||i.includes(this.streamInfo.getVideoSmallInfo().msid))&&e.push(this.videoSubState),!this.isScreenSubscribing||i&&!i.includes(this.streamInfo.getScreenInfo().msid)||e.push(this.screenSubState),!this.isDataSubscribing||i&&!i.includes(Me.Data)||e.push(this.dataSubState),e.forEach(t=>{t.setState(ut.AliRtcStateReconnecting)})}markReconnected(i){const e=[],t=this.streamInfo.getAudioInfo().msid||Me.Audio;if(this.isAudioSubscribing&&(!i||i.includes(t))){e.push(this.audioSubState);const s=this.rtsManager.getStreamByMsid({url:this.streamUrl,aMsid:t});s&&s.audioTrack&&(this.audioTrack=s.audioTrack,this.audioVolumeIndicationInterval>0&&(this.audioLevelMonitor.stop(),this.audioLevelMonitor.start(this.audioTrack,this.audioVolumeIndicationInterval)),this.playAudio())}const n=this.streamInfo.getVideoLargeInfo().msid||Me.VideoLarge,r=this.streamInfo.getVideoSmallInfo().msid||Me.VideoSmall;if(this.isVideoSubscribing&&(!i||i.includes(n)||i.includes(r))){e.push(this.videoSubState);const s=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?r:n});s&&s.mediaStream&&(this.stream=s,this.playAll(!1))}const a=this.streamInfo.getScreenInfo().msid||Me.Screen;if(this.isScreenSubscribing&&(!i||i.includes(a))){e.push(this.screenSubState);const s=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:a});s&&s.mediaStream&&(this.screenStream=s,this.playAll(!0))}if(this.isDataSubscribing&&(!i||i.includes(this.streamInfo.getDataInfo().msid))){e.push(this.dataSubState);const s=this.rtsManager.getDatachannelByMsid({url:this.streamUrl,msid:this.streamInfo.getDataInfo().msid||Me.Data});this.dataChannelConnected(s)}e.forEach(s=>{s.setState(ut.AliRtcStateSubscribed)}),i||this.updateSubscribe(Ct.Reconnect)}},V(Ro,"logName","RemoteUser"),Ro);qt([ge()],Gt.prototype,"clear"),qt([ge()],Gt.prototype,"updateRemoteUserDeviceStatus"),qt([ge()],Gt.prototype,"updateRemoteTracks"),qt([ge(ke)],Gt.prototype,"subscribe"),qt([ge()],Gt.prototype,"subscribeProxy"),qt([ge(ke)],Gt.prototype,"subscribeDeleteProxy"),qt([ge()],Gt.prototype,"restore"),qt([ge(ke)],Gt.prototype,"resumeAudio"),qt([ge(ke)],Gt.prototype,"stopSubscribe"),qt([ge(ke)],Gt.prototype,"subscribeDeleteAllTracks"),qt([ge()],Gt.prototype,"clearStream"),qt([ge()],Gt.prototype,"clearScreenStream"),qt([ge()],Gt.prototype,"updateSubscribe"),qt([ge()],Gt.prototype,"playAudio"),qt([ge()],Gt.prototype,"stopPlayAudio"),qt([ge((i,e,t)=>[typeof i=="string"?i:i==null?void 0:i.nodeType,e||"-",t||"-"])],Gt.prototype,"play"),qt([ge()],Gt.prototype,"stopPlayAll"),qt([ge(ke)],Gt.prototype,"markReconnect"),qt([ge(ke)],Gt.prototype,"markReconnected");let Nm=Gt;var Wn=(i=>(i[i.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",i[i.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",i[i.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",i[i.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",i[i.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",i[i.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",i[i.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",i[i.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",i))(Wn||{});class km extends Kt{constructor(){super(...arguments),V(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new Le(Wn.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new Le(Wn.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}removeAll(){this.plugins.forEach(e=>{this.remove(e.name)})}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}var Um=Object.defineProperty,Bm=Object.getOwnPropertyDescriptor,Yt=(i,e,t,n)=>{for(var r,a=Bm(e,t),s=i.length-1;s>=0;s--)(r=i[s])&&(a=r(e,t,a)||a);return a&&Um(e,t,a),a};const rs=([i])=>{const{remoteUser:e,options:t}=i;return[`user(${e.userId})`,t]};var vt;const zt=(vt=class extends Kt{constructor(i,e,t){super(),V(this,"rts"),V(this,"encodedInsertableStreams",!0),V(this,"audioRedEnabled",!1),V(this,"localStreamManager"),V(this,"slsReporter"),V(this,"_rtsPeerConnectionType","publish"),V(this,"connecting",!1),V(this,"connected",!1),V(this,"rtsDisconnected",!1),V(this,"_pcTraceId",""),V(this,"_localJoinTime",0),V(this,"connectionResolve"),V(this,"connectingPromise"),V(this,"dcResolve"),V(this,"dcReject"),V(this,"dcConnectingPromise"),V(this,"_dcReady",!1),V(this,"_prevDownlinkStat"),V(this,"_publishingTracks",[]),V(this,"parameter",{}),V(this,"preferredPubL1Ip"),V(this,"preferredSubL1Ip"),V(this,"httpPublishUrlMap",{}),V(this,"httpSubscribeUrlMap",{}),V(this,"traceIdMap",{}),V(this,"subUrlMap",{}),this.localStreamManager=i,this.slsReporter=e,this.parameter=t,this.rts=this.createRtsInstance(),this.addRTSListener()}createRtsInstance(){var i,e;return St.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0},datachannelDelayOpen:!1,signalDatachannelInitOptions:(e=(i=this.parameter)==null?void 0:i.net)!=null&&e.datachannelInitOptions?this.parameter.net.datachannelInitOptions:void 0})}addRTSListener(){this.rts.on("connectStatusChange",i=>{var e,t,n,r;if(Re.event(`[${vt.logName}]`,"rts connectStatusChange to:",i.status),i.status===St.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.dcReject&&this.dcReject(),this.setConnected(!1),this.rtsDisconnected=!0,this.slsReporter.reportWarning("rts disconnected"),this.emit("disconnected");else if(i.status===St.EConnectStatus.CONNECT_STATUS_CONNECTED){if(this.rtsDisconnected){const a=(r=(n=(t=(e=this.rts.commonController)==null?void 0:e.peerCore)==null?void 0:t.getSignal())==null?void 0:n.getDatachannelCore())==null?void 0:r.readyState;Re.event(`[${vt.logName}]`,"dcReadyState:",a),a==="open"&&this.dcResolve&&this.dcResolve(!0)}this.rtsDisconnected=!1,this.setConnected(!0)}}),this.rts.on("reconnect",i=>{var e,t,n;Re.debug(`[${vt.logName}]`,"reconnect",i),this.emit("reconnect",i.type,(e=i.extraInfo)==null?void 0:e.url,(n=(t=i.extraInfo)==null?void 0:t.msids)==null?void 0:n.map(r=>r.name))}),this.rts.on("reconnectFinish",i=>{var e;Re.debug(`[${vt.logName}]`,"reconnectFinish",i),this.emit("reconnectFinish",(i==null?void 0:i.type)||"pc",i==null?void 0:i.latestUrl,(e=i==null?void 0:i.msids)==null?void 0:e.map(t=>t.name));try{this.emit("connected",!0,this._rtsPeerConnectionType)}catch(t){Re.error(`[${vt.logName}]`,"emit connected error:",t)}this.logCandidateProtocol("reconnectFinish")}),this.rts.on("datachannelStatusChange",i=>{Re.event(`[${vt.logName}]`,"rts datachannelStatusChange to:",i.status),i.status===St.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?(this._dcReady=!0,this.dcResolve&&this.dcResolve(!0)):i.status===St.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this._dcReady=!1,this.dcReject&&this.dcReject(new Error("signal datachannel closed")),this.dcConnectingPromise=new Promise((e,t)=>{this.dcResolve=e,this.dcReject=t}))}),this.rts.on("receivedSEI",i=>{var e;if(this.emit("seimessage",i.url,i.sei.payloadType,i.sei.data),i.sei.payloadType===99)try{const t=JSON.parse(new TextDecoder().decode(i.sei.data));this.slsReporter.reportLoopAudioDelay(((e=this.publishingTracks.find(n=>n.type==="audio"))==null?void 0:e.ssrc)||"",t)}catch{}}),this.rts.on("onError",i=>{Re.event(`[${vt.logName}]`,"rts onError event:",i)}),this.rts.on("reconnect",i=>{Re.event(`[${vt.logName}]`,"rts reconnect event:",i)}),this.rts.on("traceId",({url:i,traceId:e})=>{i&&e&&this.traceIdMap[i]!==e&&(this.traceIdMap[i]=e,this.emit("traceIdUpdated",i,e))}),this.rts.on("signalSent",i=>{var e,t,n,r,a,s;let o=`${i.type} ${(t=(e=i.streams)==null?void 0:e[0])==null?void 0:t.method}`;i.type==="sub"&&(r=(n=i.streams)==null?void 0:n[0])!=null&&r.url&&(o+=` ${Object.keys(this.subUrlMap).find(c=>this.subUrlMap[c]===i.streams[0].url.split("?")[0])}`),(s=(a=i.streams)==null?void 0:a[0])!=null&&s.msid&&(o+=` ${i.streams[0].msid.map(c=>c.name).join("+")}`),Re.event(`[${vt.logName}]`,"rts signalSent event:",o,i)}),this.rts.on("signalReceived",i=>{var e,t,n,r,a,s,o,c;let h=`${i.type} ${(t=(e=i.streams)==null?void 0:e[0])==null?void 0:t.method}`;i.type==="sub"&&(r=(n=i.streams)==null?void 0:n[0])!=null&&r.url&&(h+=` ${Object.keys(this.subUrlMap).find(l=>this.subUrlMap[l]===i.streams[0].url.split("?")[0])}`),h+=` ${((s=(a=i.streams)==null?void 0:a[0])==null?void 0:s.res_code)||""}`,(c=(o=i.streams)==null?void 0:o[0])!=null&&c.msid&&(h+=` ${i.streams[0].msid.map(l=>l.name).join("+")}`),Re.event(`[${vt.logName}]`,"rts signalReceived event:",h,i)}),this.rts.on("hebtSent",i=>{var e,t,n;if((n=(t=(e=this.parameter)==null?void 0:e.net)==null?void 0:t.heartbeat)!=null&&n.enableLog){const r=Object.keys(this.subUrlMap).find(a=>{var s,o;return this.subUrlMap[a]===((o=(s=i.streams)==null?void 0:s[0])==null?void 0:o.url.split("?")[0])})||(i.streams?"pub":"empty");Re.event(`[${vt.logName}]`,"rts hebtSent event:",r,i)}}),this.rts.on("hebtReceived",i=>{var e,t,n,r,a,s,o;if((n=(t=(e=this.parameter)==null?void 0:e.net)==null?void 0:t.heartbeat)!=null&&n.enableLog){let c=`${Object.keys(this.subUrlMap).find(h=>{var l,f;return this.subUrlMap[h]===((f=(l=i.streams)==null?void 0:l[0])==null?void 0:f.url.split("?")[0])})||(i.streams?"pub":"empty")} ${((a=(r=i.streams)==null?void 0:r[0])==null?void 0:a.res_code)||""}`;(o=(s=i.streams)==null?void 0:s[0])!=null&&o.msid&&(c+=` ${i.streams[0].msid.map(h=>h.name).join("+")}`),Re.event(`[${vt.logName}]`,"rts hebtReceived event:",c,i)}})}updateAuth(i){this.rts.updateAuth(i)}get pcTraceId(){return this._pcTraceId}set localJoinTime(i){this._localJoinTime=i}setEncodedInsertableStreams(i){this.encodedInsertableStreams=i}setReceiverPreferredVideoCodecH265(){var i;let e=(i=RTCRtpReceiver.getCapabilities("video"))==null?void 0:i.codecs;if(!e||e.length===0)return;const t=e.filter(r=>r.mimeType.toLowerCase()!=="video/rtx");let n=t.findIndex(r=>r.mimeType==="video/H265");if(n+1){let r=t[n];t.splice(n,1),t.unshift(r),this.rts.setReceiverCodecPreferences({video:t})}}setSenderPreferredVideoCodecH265(){var i;let e=(i=RTCRtpSender.getCapabilities("video"))==null?void 0:i.codecs;if(!e||e.length===0)return;const t=e.filter(r=>r.mimeType.toLowerCase()!=="video/rtx");let n=t.findIndex(r=>r.mimeType==="video/H265");if(n+1){let r=t[n];t.splice(n,1),t.unshift(r),this.rts.setSenderCodecPreferences({video:t})}}supportVideoCodec(i){var e,t,n;return i===Vi.H265?(e=RTCRtpSender.getCapabilities("video"))==null?void 0:e.codecs.some(r=>r.mimeType==="video/H265"):i===Vi.H264?(t=RTCRtpSender.getCapabilities("video"))==null?void 0:t.codecs.some(r=>r.mimeType==="video/H264"):i===Vi.AV1&&((n=RTCRtpSender.getCapabilities("video"))==null?void 0:n.codecs.some(r=>r.mimeType==="video/AV1"))}changeVideoCodec(i){this.supportVideoCodec(i)?(Re.info(`[${vt.logName}]`,"changeVideoCodec to:",i),Vi.H265===i&&(this.setSenderPreferredVideoCodecH265(),this.setReceiverPreferredVideoCodecH265())):Re.warn(`[${vt.logName}]`,`not support video codec: ${i}`)}setAudioRedEnabled(i){var e;if(i!==this.audioRedEnabled){try{const t=[...((e=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:e.codecs)||[]];if(t.length>0){if(i){const n=t.findIndex(a=>a.mimeType==="audio/red"),r=t.findIndex(a=>a.mimeType==="audio/opus");if(n>-1&&r>-1&&n>r){const a=t[r];t[r]=t[n],t[n]=a}}this.rts.setSenderCodecPreferences({audio:t}),this.rts.setReceiverCodecPreferences({audio:t})}}catch{}this.audioRedEnabled=i}}clear(){this.setConnected(!1),this.rtsDisconnected=!1,this._dcReady=!1,this._publishingTracks=[],this._prevDownlinkStat=void 0;try{this.rts.removeAllListeners(),this.rts.unpublish(),this.rts.unsubscribe()}catch{}this.rts=this.createRtsInstance(),this.addRTSListener()}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(i=>{this.connectionResolve=i}),this._dcReady=!1,this.dcConnectingPromise=new Promise((i,e)=>{this.dcResolve=i,this.dcReject=e})}setConnected(i){var e;this.connected=i,this.connecting=!1,(e=this.connectionResolve)==null||e.call(this,!0)}get isConnecting(){return this.connecting}get isConnected(){return this.connected}suffixHttpUrl(i,e){const t=!e;let n=sa(i,t?this.preferredPubL1Ip:this.preferredSubL1Ip);const r={ip_migration:"on",exception_detection:"on"},a=new URL(n),s=a.searchParams;Object.keys(r).forEach(l=>{s.has(l)||s.set(l,r[l])});const o=a.toString(),c=i.split("?")[0];t?this.httpPublishUrlMap[c]=o:this.httpSubscribeUrlMap[c]=o;let h="";return e&&(e.vMsid?e.aMsid||(h="@subaudio=no"):h="@subvideo=no"),o+h}getSuffixedUrl(i,e){const t=i.split("?")[0];return e?this.httpPublishUrlMap[t]||i:this.httpSubscribeUrlMap[t]||i}get publishingTracks(){return this._publishingTracks}getPubMsid(i,e){const{aMsid:t,vMsid:n}=e??{},r={};return i.hasAudio&&(r.aMsid=[t??Me.Audio]),i.hasScreen&&(r.vMsid=[Me.Screen]),i.hasVideo&&(r.vMsid=[n??(e!=null&&e.isScreen?Me.Screen:Me.VideoLarge)]),r}updatePublishingTracks(i){i&&(this._publishingTracks=i.map(({msid:e,from:t,ssrc:n,codec:r,type:a,trackId:s})=>({msid:e,from:t,type:a,ssrc:`${n}`,codec:r??"",trackId:s})))}httpPublish(i){return le(this,arguments,function*(e,t=!1,n=dn.MANUAL){let r;const a=Date.now(),s=e.url,o=e.callId;this.startConnect();const{publishStream:c,videoSmallStream:h,screenStream:l,vMsid:f}=yield this.localStreamManager.createHTTPPublishStream();if(!c)return Re.warn(`[${vt.logName}]`,"publishStream is null"),{traceId:"",l1ip:r};const v=this.getPubMsid(c,{vMsid:f});v.answerSdpHook=b=>{const y=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(b);return y!=null&&y[0]&&(r=y[0]),b},this.handleHTTPConfig(v),this._rtsPeerConnectionType="publish";let p=!c.hasVideo,_=f,m="";const d=Date.now();try{m=yield this.publishWithPreferredL1Fallback(s,c,v)}catch(b){this.setConnected(!1);const y=2e3-(Date.now()-d);throw y<=0?this.emit("disconnected"):setTimeout(()=>{this.emit("disconnected")},y),this.slsReporter.reportPublish(t,s,o,c.hasVideo&&(!f||f===Me.VideoLarge),c.hasVideo&&f===Me.VideoSmall,c.hasVideo&&f===Me.Screen,c.hasAudio,(b==null?void 0:b.errorCode)||-1,this.pcTraceId,"",d,d),Le.fromRtsError(b)}m&&(this._pcTraceId=m),Re.event(`[${vt.logName}]`,"rts publish success",m);const u=Date.now();setTimeout(()=>{this.slsReporter.reportPublish(t,s,o,c.hasVideo&&(!f||f===Me.VideoLarge),c.hasVideo&&f===Me.VideoSmall,c.hasVideo&&f===Me.Screen,c.hasAudio,0,this.pcTraceId,e.traceId,d,u)},6e3),this.slsReporter.reportConnectionLatencyEvent(wi.HANDLE_PUB_TASK,Bi.START,o,m,a),this.slsReporter.reportConnectionLatencyEvent(wi.HANDLE_PUB_TASK,Bi.END,o,m,Date.now());try{const b=Date.now();return this._pcTraceId=m,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),h&&(yield this.publishAdd(e,h,{vMsid:Me.VideoSmall},t),p=!1,_=Me.VideoSmall),l&&(yield this.publishAdd(e,l,{vMsid:Me.Screen},t),p=!1,_=Me.Screen),yield this.waitPublishSender(s,p,_),this.slsReporter.reportPublishFirstPacket(t,o,d,b,this._localJoinTime,p?Me.Audio:v.vMsid,m||"",m||"",n),{traceId:m,l1ip:r}}catch(b){throw this.setConnected(!1),Le.fromError(b)}})}waitPublishSender(i,e=!1,t){return le(this,null,function*(){return Promise.race([Hn(1e3),((n,r)=>{let a=0;const s=()=>(e?this.rts.getPublishAudioStats(i,t):this.rts.getPublishVideoStats(i,t)).then(o=>!(o.bytesSent>0)&&a<n?(a++,new Promise(c=>setTimeout(()=>c(s()),r))):Promise.resolve());return s()})(5,100)]).catch(()=>{})})}getPublishVideoStats(i,e){return le(this,null,function*(){return yield this.rts.getPublishVideoStats(i,e)})}getPublishAudioStats(i,e){return le(this,null,function*(){return yield this.rts.getPublishAudioStats(i,e)})}publishAdd(i,e,t){return le(this,arguments,function*(n,r,a,s=!1,o=!1,c=dn.MANUAL){var h,l,f,v;const p=n.url,_=n.callId;this._dcReady||(yield this.dcConnectingPromise);const m=Date.now(),d=this.getPubMsid(r,a);try{const u=yield Fl(b=>le(this,null,function*(){return b>0&&Re.event(`[${vt.logName}]`,`publishAdd retry times: ${b}`),this.isConnected?(this._dcReady||(yield this.dcConnectingPromise),this.rts.publishAdd([Ze({url:p,stream:r,updateSourceStream:!1},d)])):Promise.reject(new Le(Ne.ERR_INNER,"rts not connected"))}),10,0,b=>(b==null?void 0:b.errorCode)===15006);if(u){const b=Date.now(),[y]=u,g=Date.now();return setTimeout(()=>{var S,R,E,I;this.slsReporter.reportPublish(!1,p,_,((S=d.vMsid)==null?void 0:S[0])===Me.VideoLarge,((R=d.vMsid)==null?void 0:R[0])===Me.VideoSmall,((E=d.vMsid)==null?void 0:E[0])===Me.Screen,((I=d.aMsid)==null?void 0:I[0])===Me.Audio,0,this.pcTraceId,y.traceId||"",m,g)},6e3),y.traceId&&(this._pcTraceId=y.traceId),this.updatePublishingTracks(y.trackInfoList),o&&(yield this.waitPublishSender(p,!r.hasVideo,r.hasVideo?a==null?void 0:a.vMsid:a==null?void 0:a.aMsid)),this.slsReporter.reportPublishFirstPacket(s,_,m,b,this._localJoinTime,(r.hasVideo?a==null?void 0:a.vMsid:a==null?void 0:a.aMsid)||"",this.pcTraceId,y.traceId||"",c),y.traceId||""}}catch(u){throw this.slsReporter.reportPublish(!1,p,_,((h=d.vMsid)==null?void 0:h[0])===Me.VideoLarge,((l=d.vMsid)==null?void 0:l[0])===Me.VideoSmall,((f=d.vMsid)==null?void 0:f[0])===Me.Screen,((v=d.aMsid)==null?void 0:v[0])===Me.Audio,(u==null?void 0:u.errorCode)||-1,this.pcTraceId,"",m),u!=null&&u.errorCode?Le.fromRtsError(u):Le.fromError(u)}return""})}publishDelete(i,e){return le(this,null,function*(){var t,n,r,a,s,o,c,h;this._dcReady||(yield this.dcConnectingPromise);const l=(n=(t=this.publishingTracks)==null?void 0:t.find(({msid:m})=>m===Me.Audio))==null?void 0:n.msid,f=(a=(r=this.publishingTracks)==null?void 0:r.find(({msid:m})=>m===Me.VideoLarge))==null?void 0:a.msid,v=(o=(s=this.publishingTracks)==null?void 0:s.find(({msid:m})=>m===Me.Screen))==null?void 0:o.msid,p=[];e.screen&&v?p.push(v):e.video&&p.push(e.vMsid||f);const _=[];e.audio&&l&&_.push(l),Re.event(vt.logName,"publishDelete",{streamUrl:i,aMsid:_,vMsid:p});try{const[m]=(yield this.rts.publishDeleteTracks([{url:i,aMsid:_,vMsid:p}]))||[];return Re.event(vt.logName,"publishDelete",{result:m}),m&&this.updatePublishingTracks(m.trackInfoList),((h=(c=m==null?void 0:m.trackInfoList)==null?void 0:c[0])==null?void 0:h.trackId)||""}catch(m){throw Le.fromRtsError(m)}})}publishReplace(i,e,t){return le(this,null,function*(){var n,r;this._dcReady||(yield this.dcConnectingPromise);const{vMsid:a,aMsid:s}=t??{};try{const o=yield this.rts.publishReplaceTracks([{url:i,stream:e,vMsid:a,aMsid:s}]),[c]=o;return this.updatePublishingTracks(c.trackInfoList),((r=(n=c==null?void 0:c.trackInfoList)==null?void 0:n[0])==null?void 0:r.trackId)||""}catch(o){throw Le.fromRtsError(o)}})}publishStop(i){return le(this,null,function*(){return yield this.rts.publishStop([{url:i}]),this._publishingTracks=[],""})}publishAddDataChannel(i){return le(this,null,function*(){this._dcReady||(yield this.dcConnectingPromise);const e=yield this.rts.publishAddDatachannel({signalUrl:i,url:this.getSuffixedUrl(i,!0),label:Me.Data,msid:Me.Data}),t=e==null?void 0:e.datachannel;if(t&&t.send){const n=new ArrayBuffer(4);new DataView(n).setUint8(0,240),t.datachannel.send(n)}return t})}publishStopDataChannel(i,e){return le(this,null,function*(){return yield this.rts.publishStopDatachannel({url:i,datachannel:e})})}unpublish(){return le(this,null,function*(){yield this.rts.unpublish(),this._publishingTracks=[],this.connecting=!1,this.connected=!1})}getSubscribeNetworkQuality(){return le(this,null,function*(){var i;const e=(i=this.rts.commonController.peerCore)==null?void 0:i.pc;if(!e||e.connectionState==="disconnected"||e.connectionState==="failed"||e.connectionState==="closed")return{rtt:0,loss:0,quality:Ui.AliRtcNetworkDisconnected};let t=0,n=0,r=0;const a=e.getReceivers();for(const v of a)(yield v.getStats()).forEach(p=>{p.type==="candidate-pair"&&typeof p.currentRoundTripTime=="number"&&(t=Math.round(1e3*p.currentRoundTripTime)),p.type!=="inbound-rtp"||p.mediaType!=="audio"&&p.mediaType!=="video"||(n+=p.packetsLost||0,r+=p.packetsReceived||0)});if(!this._prevDownlinkStat)return this._prevDownlinkStat={totalPacketsLost:n,totalPacketsReceived:r},{rtt:t,loss:0,quality:Ui.AliRtcNetworkUnknown};const{totalPacketsLost:s,totalPacketsReceived:o}=this._prevDownlinkStat,c=n-s,h=r-o;let l=0;c>0&&h>=0&&(l=Math.round(c/(c+h)*100));const f=Hl(l,t);return this._prevDownlinkStat={totalPacketsLost:n,totalPacketsReceived:r},{rtt:t,loss:l,quality:f}})}getSubConfig(i,e){let t=e??{};e||(t={audio:!0,video:!0,screen:!0});const n={};return t.audio&&(n.aMsid=[(i==null?void 0:i.getAudioInfo().msid)||Me.Audio]),t.video?t.vMsid?n.vMsid=[t.vMsid]:n.vMsid=i!=null&&i.hasVideoLarge?[(i==null?void 0:i.getVideoLargeInfo().msid)||Me.VideoLarge]:i!=null&&i.hasVideoSmall?[(i==null?void 0:i.getVideoSmallInfo().msid)||Me.VideoSmall]:[Me.VideoLarge]:t.screen&&(n.vMsid=[(i==null?void 0:i.getScreenInfo().msid)||Me.Screen]),n}handleHTTPConfig(i){var e,t,n,r,a,s,o,c,h,l,f,v;if(this.encodedInsertableStreams&&(i.encodedInsertableStreams=!0),(t=(e=this.parameter)==null?void 0:e.net)!=null&&t.useTCP&&(i.tcpOnly=!0),(r=(n=this.parameter)==null?void 0:n.net)!=null&&r.cumuDelay&&(i.cumuDelay=!0),(s=(a=this.parameter)==null?void 0:a.net)!=null&&s.disableHeartbeat&&(i.disableHeartbeat=!0),(c=(o=this.parameter)==null?void 0:o.net)!=null&&c.heartbeat&&(i.heartbeat=this.parameter.net.heartbeat),(l=(h=this.parameter)==null?void 0:h.net)==null?void 0:l.mediaTimeout){const p=(v=(f=this.parameter)==null?void 0:f.net)==null?void 0:v.mediaTimeout;p>1e3&&p<1e5&&(i.mediaTimeout=p)}i.offerSdpHook=Af,i.retryTimes=17,i.retryInterval=5e3,Re.info(`[${vt.logName}]`,"http config",i)}httpSubscribe(i){return le(this,null,function*(){const{remoteUser:e,options:t}=i,n=e.streamUrl,r=this.getSubConfig(e.streamInfo,t);this.handleHTTPConfig(r),this._rtsPeerConnectionType="subscribe";try{this.startConnect();const a=yield this.subscribeWithPreferredL1Fallback(n,r);return this._pcTraceId=a.traceId,this.setConnected(!0),{traceId:a.traceId,stream:a}}catch(a){throw this.setConnected(!1),this.emit("disconnected"),Le.fromRtsError(a)}})}subscribeWithPreferredL1Fallback(i,e){return le(this,null,function*(){if(this.preferredSubL1Ip){const n=this.suffixHttpUrl(i,e),r=new Promise((a,s)=>{setTimeout(()=>s(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const a=yield Promise.race([this.rts.subscribe(n,e),r]);return this.logCandidateProtocol("subscribe (preferred L1)"),a}catch(a){if(a.message==="PREFERRED_L1_TIMEOUT"){Re.warn(`[${vt.logName}]`,"Preferred L1 subscribe timeout, clearing preferredSubL1Ip and falling back to DNS"),this.preferredSubL1Ip=void 0;const s=yield this.rts.subscribe(this.suffixHttpUrl(i,e),e);return this.logCandidateProtocol("subscribe (fallback)"),s}throw a}}const t=yield this.rts.subscribe(this.suffixHttpUrl(i,e),e);return this.logCandidateProtocol("subscribe"),t})}publishWithPreferredL1Fallback(i,e,t){return le(this,null,function*(){if(this.preferredPubL1Ip){const r=this.suffixHttpUrl(i),a=new Promise((s,o)=>{setTimeout(()=>o(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const s=yield Promise.race([this.rts.publish(r,e,t),a]);return this.logCandidateProtocol("publish (preferred L1)"),s}catch(s){if(s.message==="PREFERRED_L1_TIMEOUT"){Re.warn(`[${vt.logName}]`,"Preferred L1 publish timeout, clearing preferredPubL1Ip and falling back to DNS"),this.preferredPubL1Ip=void 0;const o=yield this.rts.publish(this.suffixHttpUrl(i),e,t);return this.logCandidateProtocol("publish (fallback)"),o}throw s}}const n=yield this.rts.publish(this.suffixHttpUrl(i),e,t);return this.logCandidateProtocol("publish"),n})}subscribeAdd(i){return le(this,null,function*(){var e,t,n,r;const{remoteUser:a,options:s}=i,o=Ki(Ze({url:a.streamUrl,subAudio:!!s.audio,subVideo:!(!s.screen&&!s.video)},this.getSubConfig(a.streamInfo,s)),{targetStream:s.screen?a.getScreenStream:a.getCameraStream});this._dcReady||(yield this.dcConnectingPromise);try{return(yield Fl(c=>le(this,null,function*(){return this._dcReady||(yield this.dcConnectingPromise),c>0&&Re.event(`[${vt.logName}]`,`subscribeAdd retry times: ${c}`),this.isConnected?this.rts.subscribeAdd([o]):Promise.reject()}),10,100,c=>{var h,l,f,v;return(c==null?void 0:c.errorCode)===15006||(c==null?void 0:c.errorCode)===15004&&((v=(f=(l=(h=c.extraInfo)==null?void 0:h.parsedData)==null?void 0:l.streams)==null?void 0:f[0])==null?void 0:v.res_code)===404}))[0]}catch(c){if((c==null?void 0:c.errorCode)===15011)return Re.info(`[${vt.logName}]`,"subscribeAdd ignored",c==null?void 0:c.message),null;if(((r=(n=(t=(e=c==null?void 0:c.extraInfo)==null?void 0:e.parsedData)==null?void 0:t.streams)==null?void 0:n[0])==null?void 0:r.res_code)===508)return this.emit("subscribeexceeds"),null;throw Le.fromRtsError(c)}})}subscribeDelete(i){return le(this,null,function*(){var e,t,n,r;const{remoteUser:a,options:s}=i,o=Ki(Ze({url:a.streamUrl,subAudio:!!s.audio,subVideo:!(!s.screen&&!s.video)},this.getSubConfig(a.streamInfo,s)),{targetStream:s.screen?a.getScreenStream:a.getCameraStream});this._dcReady||(yield this.dcConnectingPromise);try{return Re.event(`[${vt.logName}]`,"subscribeDeleteTracks",JSON.stringify({url:o.url,subAudio:o.subAudio,subVideo:o.subVideo,aMsid:o.aMsid,vMsid:o.vMsid})),(yield this.rts.subscribeDeleteTracks([o]))[0]}catch(c){if(((r=(n=(t=(e=c==null?void 0:c.extraInfo)==null?void 0:e.parsedData)==null?void 0:t.streams)==null?void 0:n[0])==null?void 0:r.res_code)===404)return;throw Le.fromRtsError(c)}})}subscribeAddDataChannel(i){return le(this,null,function*(){this._dcReady||(yield this.dcConnectingPromise);const e=yield this.rts.subscribeAddDatachannel({signalUrl:i,url:this.getSuffixedUrl(i,!1),label:Me.Data,msid:Me.Data}),t=e==null?void 0:e.datachannel;if(t&&t.send){const n=new ArrayBuffer(4);new DataView(n).setUint8(0,240),t.send(n)}return t})}subscribeDeleteDatachannel(i,e){return le(this,null,function*(){let t;try{t=yield this.rts.subscribeDeleteDatachannel({url:i,msid:Me.Data,datachannel:e})}catch{}return t})}publish(i){return le(this,arguments,function*(e,t=!1,n=dn.MANUAL){const r=e.url;let a,s="";if(this.connecting&&(yield this.connectingPromise),this.connected){this._dcReady||(yield this.dcConnectingPromise);let o,c=!1;const{audio:h,video:l,videoSmall:f,screen:v}=this.localStreamManager.publishStreams;h&&(s=yield this.publishAdd(e,h,{aMsid:Me.Audio},t),c=!0,o=Me.Audio,yield Hn(100)),l&&(s=yield this.publishAdd(e,l,{vMsid:Me.VideoLarge},t),c=!1,o=Me.VideoLarge,yield Hn(100)),f&&(s=yield this.publishAdd(e,f,{vMsid:Me.VideoSmall},t),c=!1,o=Me.VideoSmall,yield Hn(100)),v&&(s=yield this.publishAdd(e,v,{isScreen:!0,vMsid:Me.Screen},t),c=!1,o=Me.Screen),o&&(yield this.waitPublishSender(r,c,o))}else{const o=yield this.httpPublish(e,t,n);s=o.traceId,a=o.l1ip}return{traceId:s,l1ip:a}})}reportSubscribeLatency(i,e,t,n){const r=[];i.audio&&r.push(i.aMsid||Me.Audio),i.video?r.push(i.vMsid||Me.VideoLarge):i.screen&&r.push(Me.Screen),r.forEach(a=>{this.slsReporter.reportConnectionLatencyEvent(wi.HANDLE_SUB_TASK,Bi.START,e,a,t,0,n),this.slsReporter.reportConnectionLatencyEvent(wi.HANDLE_SUB_TASK,Bi.END,e,a,Date.now(),0,n)})}subscribe(i,e,t,n,r){return le(this,null,function*(){let a=!1;const{options:s,remoteUser:o}=i;if(s.video&&s.screen)throw new Le(Ne.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");let c;this.connecting&&(yield this.connectingPromise),this.subUrlMap[o.userId]=o.streamUrl.split("?")[0];let h=Date.now();if(this.connected?c=yield this.subscribeAdd(i):(a=!0,c=yield this.httpSubscribe(i)),!c)return null;this.reportSubscribeLatency(s,t,h,a);const l=Date.now();let f=Me.VideoLarge,v=s.video||s.screen,p=s.audio;s.video&&s.vMsid?f=s.vMsid:s.screen&&(f=Me.Screen);let _=0,m=0,d=0;const u=((b,y)=>{let g=0;const S=()=>{let R;return p&&!_&&(R=this.rts.getSubscribeAudioStats(o.streamUrl).then(E=>{if(E.packetsReceived>0)_=Date.now(),Re.debug(`[${vt.logName}]`,o.userId,"Stats 音频首包");else if(!v)return g<b&&(g++,new Promise(I=>setTimeout(()=>I(S()),y)));return!0})),v&&!d&&(R=this.rts.getSubscribeVideoStats(o.streamUrl,f).then(E=>{if(typeof E.packetsReceived=="number")return!m&&E.packetsReceived>0&&(m=Date.now(),Re.debug(`[${vt.logName}]`,o.userId,"Stats 视频首包")),E.framesDecoded>0?(d=Date.now(),Re.debug(`[${vt.logName}]`,o.userId,"Stats 视频首帧数据"),!0):g<b?(g++,new Promise(I=>setTimeout(()=>I(S()),y))):(Re.event(`[${vt.logName}]`,o.userId,"尝试获取首帧数据失败"),!1)})),Promise.resolve(R)};return S()})(20,100);return u.then(()=>{m&&this.slsReporter.reportSubscribeFirstPacket(e===Ct.Resume,t,n,f,{fprt:m-h,ifsprtc:d?d-h:0,ajsub:e===Ct.Join?1:0,pctid:this.pcTraceId,subtid:(c==null?void 0:c.traceId)||"",sstc:l-h}),d&&this.slsReporter.reportSubscribeFirstFrame(e===Ct.Resume,t,n,f,{fvfrt:d-h,fp2fftc:d-m,ajsub:e===Ct.Join?1:0,tffrtc:e===Ct.Join?d-this.localJoinTime:d-r,pctid:this.pcTraceId,subtid:(c==null?void 0:c.traceId)||"",fvfdtc:d-h}),_&&(this.slsReporter.reportConnectionLatencyEvent(wi.FIRST_REMOTE,Bi.DECODED,t,Me.Audio,_),this.slsReporter.reportSubscribeFirstPacket(e===Ct.Resume,t,n,Me.Audio,{fprt:_-h,ifsprtc:_-h,ajsub:e===Ct.Join?1:0,pctid:this.pcTraceId,subtid:(c==null?void 0:c.traceId)||"",sstc:l-h}))}),c&&(c.isHTTP=a,c.statsCheckPromise=u),c})}getSubscribeVideoStats(i,e){return le(this,null,function*(){return yield this.rts.getSubscribeVideoStats(i,e)})}getSubscribeAudioStats(i,e){return le(this,null,function*(){return yield this.rts.getSubscribeAudioStats(i,e)})}getStreamByMsid(i){return this.rts.commonController.streamManager.getStreamByMsid(i)}getDatachannelByMsid(i){var e;return(e=this.rts.commonController.datachannelManager)==null?void 0:e.getByMsid(i)}getPCStats(){return le(this,null,function*(){var i,e;return(e=(i=this.rts.commonController.peerCore)==null?void 0:i.pc)==null?void 0:e.getStats()})}logCandidateProtocol(i){return le(this,null,function*(){var e,t;try{const n=(t=(e=this.rts.commonController)==null?void 0:e.peerCore)==null?void 0:t.pc;if(!n)return void Re.debug(`[${vt.logName}]`,`${i} - PC not available`);const r=yield n.getStats();let a,s,o,c;r.forEach(h=>{h.type==="candidate-pair"&&h.state==="succeeded"&&h.nominated&&(a=h.localCandidateId,s=h.remoteCandidateId)}),a||s||r.forEach(h=>{h.type!=="candidate-pair"||h.state!=="succeeded"&&h.state!=="in-progress"||a||(a=h.localCandidateId,s=h.remoteCandidateId)}),r.forEach(h=>{h.type==="local-candidate"&&h.id===a&&(o=h.protocol),h.type==="remote-candidate"&&h.id===s&&(c=h.protocol)}),Re.event(`[${vt.logName}]`,`${i} - Candidate Protocol: local=${o||"unknown"}, remote=${c||"unknown"}`)}catch(n){Re.warn(`[${vt.logName}]`,`${i} - Failed to get candidate protocol:`,n)}})}sendSEI(i,e,t,n){return le(this,null,function*(){return this.rts.sendSEI({url:i,vMsid:Me.VideoLarge,data:e,repeatCount:t,payloadType:n})})}},V(vt,"logName","RtsManager"),vt);Yt([ge(ke)],zt.prototype,"startConnect"),Yt([ge()],zt.prototype,"updatePublishingTracks"),Yt([ge(ke,ke)],zt.prototype,"httpPublish"),Yt([ge(ke,ke)],zt.prototype,"waitPublishSender"),Yt([ge(([i,e,t])=>[i,JSON.stringify(t)],ke)],zt.prototype,"publishAdd"),Yt([ge(ke,ke)],zt.prototype,"publishDelete"),Yt([ge(([i,e,t])=>[i,JSON.stringify(t)])],zt.prototype,"publishReplace"),Yt([ge(ke)],zt.prototype,"publishStop"),Yt([ge(ke)],zt.prototype,"publishAddDataChannel"),Yt([ge(ke)],zt.prototype,"publishStopDataChannel"),Yt([ge()],zt.prototype,"unpublish"),Yt([ge(rs,({traceId:i})=>i)],zt.prototype,"httpSubscribe"),Yt([ge(rs,({traceId:i})=>i)],zt.prototype,"subscribeAdd"),Yt([ge(rs)],zt.prototype,"subscribeDelete"),Yt([ge(ke)],zt.prototype,"subscribeAddDataChannel"),Yt([ge(ke)],zt.prototype,"subscribeDeleteDatachannel"),Yt([ge(ke)],zt.prototype,"publish"),Yt([ge(rs)],zt.prototype,"subscribe"),Yt([ge()],zt.prototype,"sendSEI");let Vm=zt;class Fa{constructor(e=Ua){V(this,"defaultProfile"),V(this,"profile"),V(this,"profileMap",new Map),V(this,"audioProfile"),V(this,"contentHint"),this.defaultProfile=Ze({},e)}updateProfile(e,t){this.profileMap.set(e,Ze(Ze(Ze({},this.defaultProfile),this.profileMap.get(e)||{}),t||{})),this.profile=e}get videoProfile(){return this.profile}updateAudioProfile(e){this.audioProfile=e}setContentHint(e,t){t&&(this.contentHint=t),this.contentHint&&e&&(e.contentHint=this.contentHint)}setVideoProfile(e,t,n=!1){return le(this,null,function*(){if(!this.profile)return;const r=this.profileMap.get(this.profile)||(t==null?void 0:t.VideoProfileMap.get(this.profile));if(r){if(!n&&e&&e.readyState==="live"&&e.applyConstraints)try{yield e.applyConstraints(r)}catch{}if(t){const a=Ze({},r);r.maxSendFrameRate&&(a.frameRate=r.maxSendFrameRate),t==null||t.VideoProfileMap.set(this.profile,a),yield t.setVideoProfile(this.profile)}}})}}var Wt=(i=>(i[i.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",i[i.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",i))(Wt||{});class rh extends Kt{constructor(e){super(),V(this,"type"),V(this,"originVideoTrack"),V(this,"videoSource"),V(this,"_videoMuted",!1),V(this,"originAudioTrack"),V(this,"audioSource"),V(this,"_audioMuted",!1),V(this,"_targetVideoTrack"),V(this,"_targetDualVideoTrack"),V(this,"_targetAudioTrack"),V(this,"_publishVideoStream"),V(this,"_publishDualVideoStream"),V(this,"_publishAudioStream"),V(this,"_previewStream"),V(this,"plugins",[]),V(this,"_profileManager"),V(this,"cameraVideoConstraints"),V(this,"micAudioConstraints"),V(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")}),V(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")}),this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,n){return le(this,null,function*(){var r,a,s,o,c,h;const{videoTrack:l,audioTrack:f}=e;l&&((r=this.originVideoTrack)==null||r.removeEventListener("ended",this.onVideoTrackEnded)),f&&((a=this.originAudioTrack)==null||a.removeEventListener("ended",this.onAudioTrackEnded)),this.type===Wt.AliRtcSdkStreamTypeScreen?this.stop():(l&&((s=this.originVideoTrack)==null||s.stop()),f&&((o=this.originAudioTrack)==null||o.stop())),l&&(this.originVideoTrack=l,(c=this.originVideoTrack)==null||c.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||go.Camera,this.updateVideoTrack(l)),f&&(this.originAudioTrack=f,(h=this.originAudioTrack)==null||h.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=n||$o.Microphone,this.updateAudioTrack(f))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return le(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return le(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return le(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,n;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(n=this.publishAudioStream)==null||n.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,n;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(n=this.publishVideoStream)==null||n.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return le(this,null,function*(){var t,n,r,a,s,o,c,h,l,f,v,p;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const _ of this.plugins)try{yield _.execute(this,e)}catch(m){console.error(`error in plugin-${_.name}, error: ${m}`)}this._targetVideoTrack?((n=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:n.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield Eo(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(r=this.profileManager)==null||r.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(a=this.profileManager)==null||a.setContentHint(this._targetVideoTrack),this.previewStream?(s=this.previewStream)==null||s.mergeStream(this._publishVideoStream):this._previewStream=yield Eo(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((h=(c=this._publishDualVideoStream)==null?void 0:c.videoTrack)==null?void 0:h.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield Eo(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((f=(l=this._publishAudioStream)==null?void 0:l.audioTrack)==null?void 0:f.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield Eo(this._targetAudioTrack),this.audioProfile&&(yield this._publishAudioStream.setAudioProfile(this.audioProfile)),this.setAudioMuted(this._audioMuted),this.previewStream?(v=this.previewStream)==null||v.mergeStream(this._publishAudioStream):this._previewStream=yield Eo(this._targetAudioTrack)):(this._publishAudioStream=void 0,(p=this.previewStream)==null||p.deleteTracks({audio:!0}))})}stopVideo(){var e,t;this.originVideoTrack&&((e=this.originVideoTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originVideoTrack)==null||t.stop(),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){var e,t;this.originAudioTrack&&((e=this.originAudioTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originAudioTrack)==null||t.stop(),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t,n=!1){return le(this,null,function*(){this._profileManager||(this._profileManager=new Fa(this.type===Wt.AliRtcSdkStreamTypeScreen?Zd:Ua)),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,n)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new Fa(this.type===Wt.AliRtcSdkStreamTypeScreen?Zd:Ua)),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return le(this,null,function*(){this._profileManager||(this._profileManager=new Fa),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return le(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}cloneAudioProfile(e){return le(this,null,function*(){this.audioProfile&&(yield e.setAudioProfile(this.audioProfile))})}addPlugin(e){const t=this.plugins.findIndex(n=>n.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1&&(e.clear(this),this.plugins.splice(t,1),!0)}}var Fm=Object.defineProperty,Hm=Object.getOwnPropertyDescriptor,Yi=(i,e,t,n)=>{for(var r,a=Hm(e,t),s=i.length-1;s>=0;s--)(r=i[s])&&(a=r(e,t,a)||a);return a&&Fm(e,t,a),a},Lr;const Fi=(Lr=class extends Kt{constructor(i,e){super(),V(this,"pluginManager"),V(this,"slsReporter"),V(this,"publishingCameraVideoStream"),V(this,"publishingScreenVideoStream"),V(this,"cameraStreamInfo",new rh(Wt.AliRtcSdkStreamTypeCapture)),V(this,"screenStreamInfo",new rh(Wt.AliRtcSdkStreamTypeScreen)),V(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]),V(this,"_audioCaptureDisabled",!1),V(this,"_cameraCaptureDisabled",!1),V(this,"_publishLocalAudioStreamEnabled",!0),V(this,"_publishLocalVideoStreamEnabled",!0),V(this,"_publishLocalScreenStreamEnabled",!0),this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=i,this.slsReporter=e,this.cameraStreamInfo.on("videotrackended",()=>le(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",lr.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>le(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",lr.AudioTrackEnded)})),this.screenStreamInfo.on("videotrackended",()=>le(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",lr.ScreenTrackEnded)})),this.pluginManager.on("added",t=>le(this,null,function*(){if(Re.info(`[${Lr.logName}]`,"plugin added",t.name),!t.isSupported("7.2.4"))return console.warn(`${t.name} is not supported!!!`),void t.emit("unsupported");try{yield t.init()}catch(n){t.emit("error",Le.fromError(n,Wn.AliRtcPluginErrorInitError))}t.streamType===Wt.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(t),yield this.cameraStreamInfo.process(this.streamInfos)),t.streamType===Wt.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(t),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("removed",t=>le(this,null,function*(){this.cameraStreamInfo.removePlugin(t)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(t)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>le(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(i){this._audioCaptureDisabled=i}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}set cameraCaptureDisabled(i){this._cameraCaptureDisabled=i}setAudioMuted(i){this.cameraStreamInfo.setAudioMuted(i)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(i){this.cameraStreamInfo.setVideoMuted(i)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(i){this.screenStreamInfo.setVideoMuted(i)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(i){this._publishLocalAudioStreamEnabled=i}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(i){this._publishLocalVideoStreamEnabled=i}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(i){this._publishLocalScreenStreamEnabled=i}updateStreams(){return le(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return le(this,null,function*(){var i,e,t,n;if((i=this.cameraStreamInfo.cameraVideoConstraints)!=null&&i.deviceId){let r=(e=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:e.deviceId;const a=yield St.AliRTS.getCameraList();a.find(s=>s.deviceId===r)||(r=(n=(t=a.find(s=>!!s.deviceId))==null?void 0:t.deviceId)!=null?n:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=r}})}setAvailableMicrophoneDeviceId(){return le(this,null,function*(){var i,e,t,n;if((i=this.cameraStreamInfo.micAudioConstraints)!=null&&i.deviceId){let r=(e=this.cameraStreamInfo.micAudioConstraints)==null?void 0:e.deviceId;const a=yield St.AliRTS.getMicList();a.find(s=>s.deviceId===r)||(r=(n=(t=a.find(s=>!!s.deviceId))==null?void 0:t.deviceId)!=null?n:""),this.cameraStreamInfo.micAudioConstraints.deviceId=r}})}createLocalStream(i){return le(this,null,function*(){var e;const{screen:t,mediaStream:n,videoProfile:r,screenProfile:a}=i;let{video:s,audio:o}=i;const c=(l=>{const{audio:f,video:v,screen:p}=l;if(v&&p)throw new Le(Ne.ERR_INNER,"create stream error, cannot create video && screen together");return!!(v||f||p)})(i);let h;if(c){n||(s===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),s=Ze({},this.cameraStreamInfo.cameraVideoConstraints)):typeof s=="object"&&(yield this.setAvailableCameraDeviceId(),s=Ze(Ze({},s),this.cameraStreamInfo.cameraVideoConstraints)),o===void 0&&this.audioCaptureDisabled?o=!1:o&&(o===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),o=Ze({},this.cameraStreamInfo.micAudioConstraints)):typeof o=="object"&&(yield this.setAvailableMicrophoneDeviceId(),o=Ze(Ze({},o),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1));const l=Date.now();try{h=yield St.AliRTS.createStream({audio:o,video:s,screen:t,custom:!!n,mediaStream:n,skipProfile:!0}),Re.info(`[${Lr.logName}]`,"createLocalStream",{audio:o,video:s,screen:t,custom:!!n,time:Date.now()-l}),o&&!n&&this.slsReporter.reportAudio(null,Date.now()-l,((e=h==null?void 0:h.audioTrack)==null?void 0:e.label)||""),t&&!n&&this.slsReporter.reportScreen(null,Date.now()-l)}catch(f){throw o&&!n&&this.slsReporter.reportAudio(f,Date.now()-l,""),t&&!n&&this.slsReporter.reportScreen(null,Date.now()-l),f}if(t)yield this.screenStreamInfo.updateSource(h,go.Screen,$o.Screen),yield this.setScreenProfile(a||Qd),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(h,go.Camera,$o.Microphone),h.hasVideo&&(yield this.setVideoProfile(r||Jd),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),h.hasAudio&&typeof o=="boolean"){const f=this.cameraStreamInfo.audioProfile;f&&(yield h.setAudioProfile(f))}}return St.AliRTS.SystenUtil.isIos&&St.AliRTS.SystenUtil.compareVersion("15.1")&&!St.AliRTS.SystenUtil.compareVersion("15.2")&&(yield Hn(1e3)),yield this.updateStreams(),h})}stopLocalStream(i){return le(this,null,function*(){const{screen:e,video:t,audio:n}=i??{};let r=!1;t&&this.cameraStreamInfo.originVideoTrack&&(r=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),n&&this.cameraStreamInfo.originAudioTrack&&(r=!0,this.cameraStreamInfo.stopAudio()),e&&this.screenStreamInfo.originVideoTrack&&(r=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0,this.slsReporter.reportScreenStop(null)),r&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:i,publishLocalAudioStreamEnabled:e,publishLocalScreenStreamEnabled:t}=this;return{video:i?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:i?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:e?this.cameraStreamInfo.publishAudioStream:void 0,screen:t?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return le(this,null,function*(){var i,e,t,n;let r,a,s,o,c=!1;const h=this.publishStreams;try{if(!(h.audio||h.video||h.videoSmall||h.screen))throw Re.error(`[${Lr.logName}]`,"no tracks founded"),new Le(Ne.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const l=new MediaStream;(i=h.audio)!=null&&i.audioTrack&&l.addTrack(h.audio.audioTrack),(e=h.video)!=null&&e.videoTrack?(l.addTrack(h.video.videoTrack),s=h.videoSmall,o=h.screen):(t=h.screen)!=null&&t.videoTrack&&(a=Me.Screen,l.addTrack((n=h.screen)==null?void 0:n.videoTrack),c=!0),r=yield nh(l),c?(this.screenStreamInfo.cloneVideoProfile(r),this.publishingScreenVideoStream=r):(this.cameraStreamInfo.cloneVideoProfile(r),this.publishingCameraVideoStream=r),this.cameraStreamInfo.cloneAudioProfile(r)}catch{}return{publishStream:r,videoSmallStream:s,screenStream:o,vMsid:a}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop(),this.updateStreams()}setVideoProfile(i,e,t=!1){return le(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(i,e,t),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(i){this.cameraStreamInfo.setVideoContentHint(i)}setAudioProfile(i){return le(this,null,function*(){var e;yield this.cameraStreamInfo.updateAudioProfile(i),yield(e=this.publishingCameraVideoStream)==null?void 0:e.setAudioProfile(i)})}setScreenProfile(i,e){return le(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(i,e),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(i){this.screenStreamInfo.setVideoContentHint(i)}setCameraVideoConstraints(i){var e;this.cameraStreamInfo.cameraVideoConstraints=Ze(Ze({},(e=this.cameraStreamInfo.cameraVideoConstraints)!=null?e:{}),i)}setMicAudioConstraints(i){var e;this.cameraStreamInfo.micAudioConstraints=Ze(Ze({},(e=this.cameraStreamInfo.micAudioConstraints)!=null?e:{}),i)}},V(Lr,"logName","LocalStreamManager"),Lr);Yi([ge(([i])=>{const{audio:e,video:t,screen:n,custom:r,skipProfile:a,videoProfile:s,screenProfile:o}=i;return[{audio:e,video:t,screen:n,custom:r,skipProfile:a,videoProfile:s,screenProfile:o}]})],Fi.prototype,"createLocalStream"),Yi([ge(ke)],Fi.prototype,"stopLocalStream"),Yi([ge()],Fi.prototype,"createHTTPPublishStream"),Yi([ge()],Fi.prototype,"stop"),Yi([ge(ke)],Fi.prototype,"setVideoProfile"),Yi([ge(ke)],Fi.prototype,"setVideoContentHint"),Yi([ge(ke)],Fi.prototype,"setAudioProfile"),Yi([ge(ke)],Fi.prototype,"setScreenProfile"),Yi([ge(ke)],Fi.prototype,"setScreenContentHint"),Yi([ge(ke)],Fi.prototype,"setCameraVideoConstraints"),Yi([ge(ke)],Fi.prototype,"setMicAudioConstraints");let Gm=Fi;const zm=i=>le(void 0,null,function*(){const e=new St.AliRTS.SupportUtil;window.isSecureContext||console.warn("WebRTC 需要 HTTPS 安全上下文,细节可参考:https://developer.mozilla.org/zh-CN/docs/Web/Security/Secure_Contexts");let t={support:!1,detail:{isWebRTCSupported:e.checkMediaDevices()&&e.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:!0}},n=!1;try{t.detail.isWebRTCSupported?(yield e.isSupport({isReceiveVideo:!0}),n=!0):console.warn("当前浏览器不支持 WebRTC")}catch{n=!1,t.detail.isBrowserSupported=e.checkBrowser({errorCode:0,message:""})}if(t.support=n,e.checkWebRtcSupport()&&i!=="sendonly"){const r=yield e.checkH264Decode();t.detail.isH264DecodeSupported=r,t.support=t.support&&r}if(e.checkWebRtcSupport()&&i!=="recvonly"){const r=yield e.checkH264Encode();t.detail.isH264EncodeSupported=r,t.support=t.support&&r}return t.detail.isScreenShareSupported=e.checkWebRtcSupport()&&e.checkScreenCapture()&&!St.AliRTS.SystenUtil.isAndroid&&!St.AliRTS.SystenUtil.isIos,t.detail.isSendMediaExtensionMsgSupported=e.checkWebRtcSupport()&&e.checkEncodedTransformSupport(),t});var Wm=(i=>(i[i.PRE_PROCESSOR=0]="PRE_PROCESSOR",i[i.POST_PROCESSOR=1]="POST_PROCESSOR",i))(Wm||{}),To=(i=>(i[i.AUDIO=0]="AUDIO",i[i.VIDEO=1]="VIDEO",i[i.BOTH=2]="BOTH",i))(To||{});class jn extends Kt{constructor(e,t=Wt.AliRtcSdkStreamTypeCapture,n=1){super(),V(this,"name"),V(this,"options"),V(this,"type",0),V(this,"streamType"),V(this,"trackType"),V(this,"zIndex",1),V(this,"_isEnable",!0),V(this,"shouldCache",!0),V(this,"lastInputAudioTrack"),V(this,"lastOutputAudioTrack"),V(this,"lastInputVideoTrack"),V(this,"lastOutputVideoTrack"),V(this,"_hasCleared",!0),this.name=e,this.streamType=t,this.trackType=n,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return le(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,n;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((n=e.currentAudioTrack)==null?void 0:n.id)}videoUpdated(e){var t,n;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((n=e.currentVideoTrack)==null?void 0:n.id)}execute(e,t){return le(this,null,function*(){const n=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,this._hasCleared||n?(yield this.process(e,t),this._hasCleared=!1):this.shouldCache&&(!this.lastOutputAudioTrack||this.trackType!==2&&this.trackType!==0||this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),!this.lastOutputVideoTrack||this.trackType!==2&&this.trackType!==1||this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this._hasCleared=!0,this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}class jm extends jn{constructor(){super("AliRtcScreenStandardize",Wt.AliRtcSdkStreamTypeScreen),V(this,"canvas"),V(this,"lastWidth"),V(this,"lastHeight"),V(this,"isProcessingScreenTrack",!1),this.shouldCache=!1}get initOptions(){return{base:4}}setOptions(e){this.options=e}isSupported(){return!(typeof TransformStream>"u"||typeof MediaStreamTrackProcessor>"u"||typeof MediaStreamTrackGenerator>"u")}updateProcessCanvas(e,t){if(this.canvas&&this.lastWidth===e&&this.lastHeight===t)return;const n=Math.ceil(e/this.options.base)*this.options.base,r=Math.ceil(t/this.options.base)*this.options.base;if(this.canvas||(this.canvas=document.createElement("canvas")),this.canvas.width=n,this.canvas.height=r,this.lastWidth&&e>this.lastWidth||this.lastHeight&&t>this.lastHeight){const a=this.canvas.getContext("2d");a&&a.clearRect(0,0,n,r)}this.lastWidth=e,this.lastHeight=t}shouldProcess(e){var t;let n=!1;if(e.originVideoTrack&&e.videoSource===go.Screen){const r=(t=e.originVideoTrack)==null?void 0:t.getSettings();if(r){const{width:a,height:s}=r;n=!a||!s||!(a%this.options.base===0&&s%this.options.base===0)}}return n}shouldUpdate(e){return this.shouldProcess(e)!==this.isProcessingScreenTrack}handleFrame(e){return le(this,null,function*(){var t;const{displayWidth:n,displayHeight:r}=e;if(!n||!r||n%this.options.base===0&&r%this.options.base===0)return e;this.updateProcessCanvas(n,r);const a=(t=this.canvas)==null?void 0:t.getContext("2d");if(this.canvas&&a){a.drawImage(e,0,0,n,r);const s=new VideoFrame(this.canvas,{timestamp:e.timestamp});return e.close(),s}return e})}process(e){return le(this,null,function*(){var t;if(!this.shouldProcess(e))return this.clear(e),void(this.isProcessingScreenTrack=!1);if(e.originVideoTrack){const h=e.originVideoTrack.getSettings();if(h){const{width:l,height:f}=h;if(!(!l||!f||!(l%this.options.base===0&&f%this.options.base===0)))return void this.clear(e)}}const n=new MediaStreamTrackProcessor({track:e.originVideoTrack}),r=new MediaStreamTrackGenerator({kind:"video"}),a=new MediaStream([r]),s=this,o=new TransformStream({transform(h,l){return le(this,null,function*(){const f=yield s.handleFrame(h);yield l.enqueue(f),f==null||f.close()})}});n.readable.pipeThrough(o).pipeTo(r.writable);const c=(t=a.getVideoTracks())==null?void 0:t[0];e.updateVideoTrack(c),this.isProcessingScreenTrack=!0})}clear(e){this.canvas=void 0,this.lastWidth=void 0,this.lastHeight=void 0,super.clear(e)}}class Xm extends jn{constructor(){super("blankAudio",Wt.AliRtcSdkStreamTypeCapture,To.BOTH),V(this,"hasTrack",!1),V(this,"oscillator",null),V(this,"audioTrack",null),V(this,"createAudioTrack",()=>{const e=new AudioContext;this.oscillator=e.createOscillator();const t=e.createGain();t.gain.value=0;const n=e.createMediaStreamDestination();this.oscillator.connect(t),t.connect(n),this.oscillator.start();const r=n.stream;return this.audioTrack=r.getAudioTracks()[0],this.audioTrack}),this.zIndex=9}isSupported(){return!0}setOptions(){throw new Error("Method not implemented.")}shouldUpdate(e,t){return this.hasTrack!==t.some(n=>n.originVideoTrack||n.originAudioTrack)}process(e,t){return le(this,null,function*(){var n;const r=t.some(a=>a.originVideoTrack||a.originAudioTrack);this.hasTrack=r,r?this.audioTrack&&((n=this.oscillator)==null||n.stop(),this.oscillator=null,this.audioTrack.stop(),this.audioTrack=null):(this.audioTrack||(this.audioTrack=this.createAudioTrack()),e.updateAudioTrack(this.audioTrack))})}}class oh{constructor(e){V(this,"name","COMMON"),this.name=e||this.name}info(...e){}warn(...e){}print(e,...t){const n=e.toLowerCase();n&&console[n](`[${e}][${this.name}]`,...t)}}V(oh,"LEVEL",0);class $m{constructor(){V(this,"logger",new oh("AudioMixer")),V(this,"audioContext",new AudioContext),V(this,"audioDestination",this.audioContext.createMediaStreamDestination()),V(this,"audioTrack",(e=>e.getAudioTracks()[0])(this.audioDestination.stream)),V(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(e=>e.sourceNode).filter(e=>!!e)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(e=>e.gainNode).filter(e=>!!e)}get sourceCount(){return this.sourceNodeList.length}resume(){var e;return(e=this.audioContext)==null?void 0:e.resume()}addTrack(e){this.connectTrack(e)}hasTrack(e){return!!this.sourceNodeMap[e]}removeTrack(e){const{sourceNode:t,gainNode:n}=this.sourceNodeMap[e]||{};n==null||n.disconnect(),t==null||t.disconnect(),delete this.sourceNodeMap[e],t?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${e} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(e,t){const{gainNode:n}=this.sourceNodeMap[t]||{};n?(this.logger.info(`Setting node(${t}) volume to ${this.scale(e)}`),n.gain.value=this.scale(e)):this.logger.warn(`GainNode ${t} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var e;this.reset(),(e=this.audioTrack)==null||e.stop(),this.audioDestination.disconnect(),this.audioContext.close()}connectTrack(e){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let t=new MediaStream;t.addTrack(e);const n=this.audioContext.createMediaStreamSource(t),r=this.audioContext.createGain();r.gain.value=1,n.connect(r),r.connect(this.audioDestination),this.sourceNodeMap[e.id]={track:e,sourceNode:n,gainNode:r},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(e=>e.disconnect()),this.gainNodeList.forEach(e=>e.disconnect())}scale(e){return e/100}}class Km extends jn{constructor(){super("audioMixer",Wt.AliRtcSdkStreamTypeCapture,To.AUDIO),V(this,"audioMixer"),V(this,"primaryAudioTrackId"),V(this,"screenAudioTrackId"),V(this,"dirty",!1),this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,n])=>{this.isValidVolume(n)&&(this.options[t]=n)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var n,r;if(e.type!==Wt.AliRtcSdkStreamTypeCapture)return!1;const a=t.find(o=>o.type===Wt.AliRtcSdkStreamTypeCapture),s=t.find(o=>o.type===Wt.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=a==null?void 0:a.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((r=s==null?void 0:s.currentAudioTrack)==null?void 0:r.id)&&!this.dirty)}process(e,t){return le(this,null,function*(){var n,r;this.dirty=!1;const a=t.find(c=>c.type===Wt.AliRtcSdkStreamTypeScreen),s=e.currentAudioTrack,o=a==null?void 0:a.currentAudioTrack;if(!o&&this.options.audio===1)return this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=s==null?void 0:s.id,void e.updateAudioTrack(s);this.audioMixer||(this.audioMixer=new $m),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(s==null?void 0:s.id)!==this.primaryAudioTrackId&&((n=this.audioMixer)==null||n.removeTrack(this.primaryAudioTrackId)),s&&!this.audioMixer.hasTrack(s==null?void 0:s.id)&&this.audioMixer.addTrack(s),this.primaryAudioTrackId=s==null?void 0:s.id,this.screenAudioTrackId&&(o==null?void 0:o.id)!==this.screenAudioTrackId&&((r=this.audioMixer)==null||r.removeTrack(this.screenAudioTrackId)),o&&!this.audioMixer.hasTrack(o==null?void 0:o.id)&&this.audioMixer.addTrack(o),this.screenAudioTrackId=o==null?void 0:o.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=4}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(100*this.options.audio,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(100*this.options.screen,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class qm extends jn{constructor(){super(...arguments),V(this,"isProcessing",!1),V(this,"videoScaler")}get initOptions(){return{width:320,height:180,frameRate:15}}setOptions(e){var t;this.options=e,(t=this.videoScaler)==null||t.updateOptions(e)}isSupported(){return Sa.isSupport()}shouldUpdate(e){const t=!!e.currentVideoTrack;return this.isProcessing!==t}process(e){return le(this,null,function*(){if(e.currentVideoTrack){if(this.isProcessing=!0,!this.videoScaler){const n=this.options||this.initOptions;this.videoScaler=Sa.getInstance(e.currentVideoTrack,n)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else this.isProcessing&&this.clear()})}clear(e){var t;super.clear(e),this.isProcessing=!1,e==null||e.updateDualVideoTrack(),(t=this.videoScaler)==null||t.dispose()}}function Or(i,e,t,n){return new(t||(t=Promise))(function(r,a){function s(h){try{c(n.next(h))}catch(l){a(l)}}function o(h){try{c(n.throw(h))}catch(l){a(l)}}function c(h){var l;h.done?r(h.value):(l=h.value,l instanceof t?l:new t(function(f){f(l)})).then(s,o)}c((n=n.apply(i,[])).next())})}var Xn,pn;function sh(){return Or(this,void 0,void 0,function*(){let i=!1;try{i=yield le(this,null,function*(){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,10,1,8,0,65,0,253,15,253,98,11]))})}catch{i=!1}return console.log("isSupportedSIMD",i),i})}typeof SuppressedError=="function"&&SuppressedError,(pn=Xn||(Xn={}))[pn.ERROR=0]="ERROR",pn[pn.WARN=1]="WARN",pn[pn.INFO=2]="INFO",pn[pn.LOG=3]="LOG",pn[pn.DEBUG=4]="DEBUG";class wt{static error(...e){var t;wt.logLevel>=Xn.ERROR&&((t=console.error)===null||t===void 0||t.call(console,`[${wt.logTag}] `,...e))}static warn(...e){var t;wt.logLevel>=Xn.WARN&&((t=console.warn)===null||t===void 0||t.call(console,`[${wt.logTag}] `,...e))}static info(...e){var t;wt.logLevel>=Xn.INFO&&((t=console.info)===null||t===void 0||t.call(console,`[${wt.logTag}] `,...e))}static log(...e){var t;wt.logLevel>=Xn.LOG&&((t=console.log)===null||t===void 0||t.call(console,`[${wt.logTag}] `,...e))}static debug(...e){var t;wt.logLevel>=Xn.DEBUG&&((t=console.debug)===null||t===void 0||t.call(console,`[${wt.logTag}] `,...e))}}wt.logLevel=Xn.WARN,wt.logTag="aliyun-audio-3a";class Ym{}class ah extends Ym{static isSupported(){return function(){if(typeof window=="object"&&window!==null){const e="AudioWorklet"in window,t="WebAssembly"in window;return e&&t}return!1}()}static isSupportedSIMD(){return Or(this,void 0,void 0,function*(){return yield sh()})}static setLogger(e){wt.logLevel=e}constructor(e){super(),this.channelCount=1,this.sampleRate=48e3,this.collectDumpOutputData=[],this.collectDumpNearInputData=[],this.collectDumpFarInputData=[],this.collectDumpMetaData=[],this.statUpdateTimer=0,this.statUpdateInterval=5e3,this.options=Object.assign({aecOn:!0,ansOn:!0,agcOn:!0,hdOn:!1,ansMode:1,dumpOn:!1,aiaecOn:!1,wasmCdnPath:"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"},e||{})}initWASM(e,t,n){return Or(this,void 0,void 0,function*(){wt.log("initWASM",e,t,n);const r=s=>Or(this,void 0,void 0,function*(){try{const o=yield fetch(s,{credentials:"same-origin"});return o.ok||this.onLoadError(new Error(`Failed to fetch WASM: ${o.status}:${o.statusText}, url:${s}`)),o.arrayBuffer()}catch(o){return this.onLoadError(new Error("WASM load error")),wt.error("Error fetching WASM:",o),new Uint8Array(0)}}),a=s=>Or(this,void 0,void 0,function*(){return fetch(s).then(o=>o.text())});try{const s=yield sh(),o=this.options.wasmCdnPath+"audio_module_v2.wasm",c=this.options.wasmCdnPath+"audio_module_v2_simd.wasm",h=yield r(s?c:o),l=this.options.wasmCdnPath+"audio_module_v2.js",f=this.options.wasmCdnPath+"audio_module_v2_simd.js",v=s?f:l,p=yield a(v);e.port.postMessage(Object.assign({type:"init",channelCount:t,sampleRate:n,wasmBuffer:h,isSupportSIMD:s,audioModuleScript:p,logLevel:wt.logLevel},this.options),[h])}catch(s){wt.error("Error initializing WASM:",s),this.onLoadError(new Error("WASM init error"))}e.port.onmessage=s=>{s.data.type==="init_done"&&this.onLoadSuccess(void 0),s.data.type==="dump_output_data"&&this.onDumpOutputData(s.data.data),s.data.type==="dump_near_data"&&this.onDumpNearInputData(s.data.data),s.data.type==="dump_far_data"&&this.onDumpFarInputData(s.data.data),s.data.type==="dump_meta_data"&&this.onDumpMeatData(s.data.data),s.data.type==="output_log"&&this.onOutputLog(s.data.data),s.data.type==="apm_stat_data"&&this.onStatData(s.data.data)}})}createProcessor(e,t,n,r,a){return Or(this,void 0,void 0,function*(){this.audioContext=e,this.audioContext.resume(),this.channelCount=n,this.sampleRate=r;try{const c=new Blob(['!function(){"use strict";function t(t,e,a,n){return new(a||(a=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function r(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof a?e:new a((function(t){t(e)}))).then(o,r)}h((n=n.apply(t,e||[])).next())}))}var e;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG"}(e||(e={}));class a{static error(...t){var n;a.logLevel>=e.ERROR&&(null===(n=console.error)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static warn(...t){var n;a.logLevel>=e.WARN&&(null===(n=console.warn)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static info(...t){var n;a.logLevel>=e.INFO&&(null===(n=console.info)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static log(...t){var n;a.logLevel>=e.LOG&&(null===(n=console.log)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static debug(...t){var n;a.logLevel>=e.DEBUG&&(null===(n=console.debug)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}}a.logLevel=e.WARN,a.logTag="aliyun-audio-3a";const n=Float32Array.BYTES_PER_ELEMENT,s=Uint16Array.BYTES_PER_ELEMENT;class i{constructor(t,e,a,n,s){this._channelData=[],this._name=t,this._isInitialized=!1,this._module=e,this._length=a,this._ringLength=2*a,this._maxChannelCount=s?Math.min(s,32):n,this._channelCount=n,this._allocateHeap(),this._isInitialized=!0,this._readIndex=0,this._writeIndex=0,this._framesAvailable=0,this._channelDataLocal=[];for(let t=0;t<this._channelCount;++t)this._channelDataLocal[t]=new Float32Array(this._ringLength)}_allocateHeap(){const t=this._length*n,e=this._channelCount*t;this._dataPtr=this._module._malloc(e),this._channelData=[];for(let e=0;e<this._channelCount;++e){const a=this._dataPtr+e*t,n=a+t;this._channelData[e]=this._module.HEAPF32.subarray(a>>s,n>>s)}}adaptChannel(t){t<this._maxChannelCount&&(this._channelCount=t)}get length(){return this._isInitialized?this._length:null}get numberOfChannels(){return this._isInitialized?this._channelCount:null}get maxChannelCount(){return this._isInitialized?this._maxChannelCount:null}getChannelData(t){return void 0!==t&&t>=this._channelCount?null:void 0===t?this._channelData:this._channelData[t]}getHeapAddress(){return this._dataPtr}getPointer(){return this._dataPtr}free(){this._isInitialized=!1,null!==this._dataPtr&&this._module._free(this._dataPtr),this._channelData=[]}get framesAvailable(){return this._framesAvailable}push(t){const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)this._channelDataLocal[e][this._writeIndex]=t[e][a];this._writeIndex=(this._writeIndex+1)%this._ringLength}this._framesAvailable+=e,this._framesAvailable>this._ringLength&&(console.warn(this._name,"Too many frames available, overflow"),this._framesAvailable=this._ringLength,this._writeIndex=0)}pull(t){if(0===this._framesAvailable)return void console.warn(this._name,"No frames available");const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)t[e][a]=this._channelDataLocal[e][this._readIndex];this._readIndex=(this._readIndex+1)%this._ringLength}this._framesAvailable-=e,this._framesAvailable<0&&(this._framesAvailable=0,this._readIndex=0)}}class o{constructor(t){this.inited=!1,this.handle=null,this.channelCount=1,this.isEnable=!0,this.dumpAudioData=!1,this.kernelBufferSize=512,this.node=t,this.onDumpOutputDataFunction=null,this.onDumpNearDataFunction=null,this.onDumpFarDataFunction=null,this.onDumpMetaDataFunction=null,this.wasmInvoker=null,this._nearAudioBuffer={},this._outputAudioBuffer={}}destructor(){this.wasmInvoker=null,this.handle=null}init(n){return t(this,void 0,void 0,(function*(){const{wasmBuffer:t,audioModuleScript:s,channelCount:o=1,sampleRate:r=44100,dumpAudioData:h=!1,logLevel:l=e.DEBUG}=n;a.logLevel=l,a.log("AudioAPM init",JSON.stringify(n)),this.channelCount=o,this.dumpAudioData=h;try{const e=new Function(`let module={};let exports={};${s}; return module`)();this.wasmInvoker=yield e.exports({wasmBinary:t})}catch(t){this.node.port.postMessage({type:"error",message:"audioModule init error"}),a.error(t)}this._nearAudioBuffer=new i("inBuffer",this.wasmInvoker,this.kernelBufferSize,2*this.channelCount,32),this._outputAudioBuffer=new i("outBuffer",this.wasmInvoker,this.kernelBufferSize,this.channelCount,32);const u=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=String.fromCharCode.apply(null,a);this.node&&this.node.port&&this.node.port.postMessage({type:"output_log",message:"output_log",data:n})}),"vii");if(this.wasmInvoker.__apm_log_callback(u),this.handle=this.wasmInvoker.__apm_create(n.aecOn?1:0,n.ansOn?1:0,n.agcOn?1:0,n.hdOn?1:0,r,o,n.dumpOn?1:0,this.kernelBufferSize),n.aiaecOn){const t=102;this.wasmInvoker.__apm_set_param(this.handle,t,7)}if(n.useHardOnly){const t=108;this.wasmInvoker.__apm_set_param(this.handle,t,1)}this.node.port.postMessage({type:"init_done",message:"init done"}),this.inited=!0}))}getStatData(){if(this.wasmInvoker&&this.isEnable){let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);this.wasmInvoker._free(t),this.node&&this.node.port&&this.node.port.postMessage({type:"apm_stat_data",message:"apm_stat_data",data:e})}}onOutputLog(t){console.log("[WASM_LOG]",t)}destory(){return t(this,void 0,void 0,(function*(){var t;try{null===(t=this.wasmInvoker)||void 0===t||t.__apm_destory(this.handle),this.inited=!1}catch(t){a.error(t)}finally{this.handle=null}}))}enable(){this.isEnable=!0,a.log("APM enable")}disable(){this.isEnable=!1,a.log("APM disable")}getStat(){if(null==this.wasmInvoker||null==this.handle)return"";let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);return this.wasmInvoker._free(t),e}startDump(){this.onDumpOutputDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_output_data",message:"dump_output_data",data:n})}),"vii"),this.onDumpNearDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_near_data",message:"dump_near_data",data:n})}),"vii"),this.onDumpFarDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_far_data",message:"dump_far_data",data:n})}),"vii"),this.onDumpMetaDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_meta_data",message:"dump_meta_data",data:n})}),"vii"),this.wasmInvoker.__apm_dump_start(this.handle,this.onDumpOutputDataFunction,this.onDumpNearDataFunction,this.onDumpFarDataFunction,this.onDumpMetaDataFunction)}stopDump(){this.wasmInvoker.__apm_dump_stop(this.handle),this.wasmInvoker&&(this.wasmInvoker.removeFunction(this.onDumpOutputDataFunction),this.wasmInvoker.removeFunction(this.onDumpNearDataFunction),this.wasmInvoker.removeFunction(this.onDumpFarDataFunction),this.wasmInvoker.removeFunction(this.onDumpMetaDataFunction))}process(t,e,a){if(!this.inited||!this.isEnable){for(let e=0;e<this.channelCount;e++){a[e].set(t[e])}return}const n=this.channelCount;let s=0;if(this.handle&&this.isEnable){const i=t[0].length,o=[];for(let a=0;a<n;a++)e[a]&&e[a].length>0&&(s=1),o.push(t[a]||new Float32Array(i).fill(0)),o.push(e[a]||new Float32Array(i).fill(0));if(this._nearAudioBuffer.push(o),this._nearAudioBuffer.framesAvailable>=this.kernelBufferSize){this._nearAudioBuffer.pull(this._nearAudioBuffer.getChannelData()),this.wasmInvoker.__apm_process_new(this.handle,this._nearAudioBuffer.getHeapAddress(),this._outputAudioBuffer.getHeapAddress(),n,s);const t=this._outputAudioBuffer.getChannelData();this._outputAudioBuffer.push(t)}this._outputAudioBuffer.pull(a)}}}class r extends AudioWorkletProcessor{constructor(){super(),this.apm=new o(this),this.port.onmessage=t=>{const e=t.data||{};switch(a.log("onmessage data",e),e.type){case"init":this.apm.init(e);break;case"destroy":this.apm.destory();break;case"enable":this.apm.enable();break;case"disable":this.apm.disable();break;case"start_dump":this.apm.startDump();break;case"stop_dump":this.apm.stopDump();break;case"get_stat_data":this.apm.getStatData();break;default:a.warn("Unknown message type:",e.type)}}}process(t,e){const a=t[0],n=t.length>1?t[1]:[],s=e[0];return this.apm.process(a,n,s),!0}}registerProcessor("aliyun-web-3a-processor",r)}();\n'],{type:"application/javascript"}),h=URL.createObjectURL(c);yield this.audioContext.audioWorklet.addModule(h)}catch(c){wt.error("Failed to add module to audio worklet:",c)}let s=new AudioWorkletNode(this.audioContext,"aliyun-web-3a-processor",{numberOfInputs:2,outputChannelCount:[n]});this.workletNode=s,t.connect(s),a&&(this.farNode=a,a.connect(s,0,1));const o=this.audioContext.createMediaStreamDestination();s.connect(o),this.targetMediaTrack=o.stream.getAudioTracks()[0],yield this.initWASM(s,n,r),this.statUpdateTimer=window.setInterval(()=>{this.getStatData()},this.statUpdateInterval)})}addFarNode(e){this.workletNode&&(this.farNode&&this.farNode.disconnect(this.workletNode),e&&(this.farNode=e,e.connect(this.workletNode,0,1)))}getStatData(){var e;try{(e=this.workletNode)===null||e===void 0||e.port.postMessage({type:"get_stat_data"})}catch(t){wt.error("Failed to post message to worklet node:",t)}}destroy(){if(this.statUpdateTimer&&window.clearInterval(this.statUpdateTimer),this.audioContext&&this.workletNode&&this.workletNode.port)try{this.workletNode.port.postMessage({type:"destroy"}),this.workletNode.port.onmessage=null,this.workletNode.disconnect(),wt.log("postMessage destroy")}catch(e){wt.error("Failed to post message to worklet node:",e)}}startDump(){var e;try{(e=this.workletNode)===null||e===void 0||e.port.postMessage({type:"start_dump"})}catch(t){wt.error("Failed to post message to worklet node:",t)}}stopDump(){var e;try{(e=this.workletNode)===null||e===void 0||e.port.postMessage({type:"stop_dump"})}catch(t){wt.error("Failed to post message to worklet node:",t)}setTimeout(()=>{this.onDumpOutputData(null,!0),this.onDumpNearInputData(null,!0),this.onDumpFarInputData(null,!0),this.onDumpMeatData(null,!0)},3e3)}onDumpOutputData(e,t=!1){if(e&&e.length>0&&this.collectDumpOutputData.push(e),t&&this.collectDumpOutputData.length>0||1024*this.collectDumpOutputData.length>=this.getMaxDumpBytes()){let n=new Blob(this.collectDumpOutputData);this.onDumpData(n,"output_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpOutputData=[]}}onDumpNearInputData(e,t=!1){if(e&&e.length>0&&this.collectDumpNearInputData.push(e),t&&this.collectDumpNearInputData.length>0||1024*this.collectDumpNearInputData.length>=this.getMaxDumpBytes()){let n=new Blob(this.collectDumpNearInputData);this.onDumpData(n,"near_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpNearInputData=[]}}onDumpFarInputData(e,t=!1){if(e&&e.length>0&&this.collectDumpFarInputData.push(e),t&&this.collectDumpFarInputData.length>0||1024*this.collectDumpFarInputData.length>=this.getMaxDumpBytes()){let n=new Blob(this.collectDumpFarInputData);this.onDumpData(n,"far_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpFarInputData=[]}}onDumpMeatData(e,t=!1){if(e&&e.length>0&&this.collectDumpMetaData.push(e),t&&this.collectDumpMetaData.length>0||1024*this.collectDumpMetaData.length>=this.getMaxDumpBytes()){let n=new Blob(this.collectDumpMetaData);this.onDumpData(n,"meta_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpMetaData=[]}}getMaxDumpBytes(){return 600*Number(this.sampleRate.toFixed(0))*Number(this.channelCount.toFixed(0))*2}enable(){var e;if(!((e=this.workletNode)===null||e===void 0)&&e.port)try{this.workletNode.port.postMessage({type:"enable"}),wt.log("postMessage enable")}catch(t){wt.error("Failed to post message to worklet node:",t)}}disable(){var e;if(!((e=this.workletNode)===null||e===void 0)&&e.port)try{wt.log("postMessage disable"),this.workletNode.port.postMessage({type:"disable"})}catch(t){wt.error("Failed to post message to worklet node:",t)}}on(e,t){e==="loaderror"&&(this.onLoadError=t),e==="loadsuccess"&&(this.onLoadSuccess=t),e==="dumpdata"&&(this.onDumpData=t),e==="outputlog"&&(this.onOutputLog=t),e==="statdata"&&(this.onStatData=t)}onLoadError(e){console.log("onLoadError",e)}onLoadSuccess(e){console.log("onLoadSuccess",e)}onDumpData(e,t){console.log("onDumpData",e,t)}onOutputLog(e){console.log("[WASM]",e)}onStatData(e){console.log("onStatData:",e)}}class Jm extends jn{constructor(e){super("AliRtcAudioProcessPlugin",Wt.AliRtcSdkStreamTypeCapture,To.AUDIO),V(this,"audioProcessor"),V(this,"slsReporter"),V(this,"enableSoft3ACheck",!1),V(this,"useHardOnly",!1),V(this,"lastDiffOutputLog",""),V(this,"audioContext",new AudioContext({sampleRate:48e3})),V(this,"farNode"),V(this,"createNode",t=>this.audioContext.createMediaStreamSource(new MediaStream([t]))),this.options=e,this.slsReporter=e==null?void 0:e.slsReporter,this.enableSoft3ACheck=(e==null?void 0:e.enableSoft3ACheck)||!1,this.useHardOnly=(e==null?void 0:e.useHardOnly)||!1,this.zIndex=7,document.addEventListener("click",this.activeAudioContext)}activeAudioContext(){var e;(e=this.audioContext)==null||e.resume(),document.removeEventListener("click",this.activeAudioContext)}audioUpdated(e){var t,n;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((n=e.currentAudioTrack)==null?void 0:n.id)}videoUpdated(e){return console.log("videoUpdated",e),!1}setOptions(e){var t;!this.farNode&&e.farMediaStream&&(this.farNode=this.audioContext.createMediaStreamSource(e.farMediaStream),this.audioProcessor&&((t=this.audioProcessor)==null||t.addFarNode(this.farNode)),this.options=Ze(Ze({},this.options),e))}isSupported(){return ah.isSupported()}shouldUpdate(e){return!!(e.originAudioTrack&&!this.audioProcessor||!e.originAudioTrack&&this.audioProcessor)}process(e){return le(this,null,function*(){var t;if(!e.currentAudioTrack)return e.updateAudioTrack(),void this.clear(e);if(!this.audioProcessor){this.audioProcessor=new ah({aecOn:!0,ansOn:!0,agcOn:!0,dumpOn:((t=this.options)==null?void 0:t.dumpAudioData)||!1,aiaecOn:this.options.aiaecOn||!1,useHardOnly:this.useHardOnly,wasmCdnPath:this.options.wasmCdnPath||"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"}),this.audioProcessor.on("dumpdata",(r,a)=>{let s=3e3;a.includes("far")?s=5e3:a.includes("output")?s=1e4:a.includes("meta")&&(s=8e3),setTimeout(()=>{const o=URL.createObjectURL(r),c=document.createElement("a");c.href=o,c.download=a,document.body.appendChild(c),c.click(),document.body.removeChild(c)},s)}),this.audioProcessor.on("loadsuccess",()=>{var r,a;this.enableSoft3ACheck||e.updateAudioTrack((r=this.audioProcessor)==null?void 0:r.targetMediaTrack),this.options.dumpAudioData&&((a=this.audioProcessor)==null||a.startDump())}),this.audioProcessor.on("loaderror",r=>{this.emit("error",r)}),this.audioProcessor.on("outputlog",r=>{r!=null&&r.includes("diff")&&(this.lastDiffOutputLog=r||"")}),this.audioProcessor.on("statdata",r=>{var a;if(r)try{let s=r;if(this.lastDiffOutputLog){const o=this.extractDiffValue(this.lastDiffOutputLog),c=JSON.parse(r);o!==null&&(c.diff=o);const h=this.extractLeakValue(this.lastDiffOutputLog);h!==null&&(c.leak=h),s=JSON.stringify(c)}(a=this.slsReporter)==null||a.reportPublishAudio3A("","","",s)}catch{}});const n=this.createNode(e.currentAudioTrack);yield this.audioProcessor.createProcessor(this.audioContext,n,1,48e3,this.farNode)}})}extractDiffValue(e){if(!e)return null;const t=e.match(/diff\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}extractLeakValue(e){if(!e)return null;const t=e.match(/leak\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}clear(e){var t,n,r;this.options.dumpAudioData&&((t=this.audioProcessor)==null||t.stopDump()),super.clear(e),(n=this.audioProcessor)==null||n.destroy(),this.audioProcessor=void 0,document.removeEventListener("click",this.activeAudioContext),(r=this.farNode)==null||r.disconnect(),this.farNode=void 0}dump(){var e;(e=this.audioProcessor)==null||e.stopDump()}}var os=(i=>(i[i.Default=0]="Default",i[i.Human=1]="Human",i[i.Robot=2]="Robot",i))(os||{}),Qm=Object.defineProperty,Zm=Object.getOwnPropertyDescriptor,ch=(i,e,t,n)=>{for(var r,a=Zm(e,t),s=i.length-1;s>=0;s--)(r=i[s])&&(a=r(e,t,a)||a);return a&&Qm(e,t,a),a},Nr;const Ha=(Nr=class extends Kt{constructor(i,e){super(),V(this,"self"),V(this,"remoteUser"),V(this,"sendReadyMsg",!1),V(this,"hasPubDataChannel",!1),V(this,"hasSubDataChannel",!1),V(this,"readyMsgSuccess",!1),V(this,"sendReadyMsgTimer"),V(this,"startReadyMsgTime"),V(this,"robotUserId"),V(this,"onSubscribeDataChannel",t=>{!this.remoteUser&&t&&(this.robotUserId&&this.robotUserId!==t.userId||(this.hasSubDataChannel=!0,this.remoteUser=t,this.remoteUser.on("remoteDataChannelMessage",this.onCheckReadyMsg),this.trySendReadyMsg()))}),V(this,"onCheckReadyMsg",(t,n)=>{var r,a;if(this.sendReadyMsg&&!this.readyMsgSuccess)try{const s=new TextDecoder().decode(n.data),o=JSON.parse(s);o.key==="aliyun_aigc"&&o.type==="ready_resp"&&((r=o.data)==null?void 0:r.ready)===!0&&(Re.event(`[${Nr.logName}]`,"onCheckReadyMsg success"),this.readyMsgSuccess=!0,this.emit("dcready",t),(a=this.remoteUser)==null||a.off("remoteDataChannelMessage",this.onCheckReadyMsg),window.clearTimeout(this.sendReadyMsgTimer))}catch{}}),V(this,"onDataPublishStateChange",(t,n)=>{n===nt.AliRtcStatePublished&&(this.hasPubDataChannel=!0,this.trySendReadyMsg())}),this.self=i,this.self.on("dataPublishStateChanged",this.onDataPublishStateChange),this.robotUserId=e}destroy(){this.self.off("dataPublishStateChanged",this.onDataPublishStateChange),window.clearTimeout(this.sendReadyMsgTimer),this.remoteUser=void 0,this.sendReadyMsg=!1,this.hasPubDataChannel=!1,this.hasSubDataChannel=!1,this.readyMsgSuccess=!1,this.startReadyMsgTime=0}trySendReadyMsg(){Re.event(`[${Nr.logName}]`,`trySendReadyMsg: pub(${this.hasPubDataChannel}, sub: ${this.hasSubDataChannel})`),this.hasPubDataChannel&&this.hasSubDataChannel&&(this.sendReadyMsg=!0,this.sendReadyMsgLoop())}sendReadyMsgLoop(i=0){return le(this,null,function*(){const e=JSON.stringify({key:"aliyun_aigc",version:"1.0",type:"ready_req",data:{ready:!0}});try{this.self.sendDataChannelMessage(new zn(new TextEncoder().encode(e).buffer))}catch{}this.startReadyMsgTime||(this.startReadyMsgTime=Date.now());let t=50;const n=Date.now()-this.startReadyMsgTime;t=n<1e3?50:n<2e3?100:n<3e3?500:2e3,i>30?Re.event(`[${Nr.logName}]`,"sendReadyMsgLoop fail after 30 times"):this.sendReadyMsgTimer=window.setTimeout(()=>{this.sendReadyMsgLoop(i+1)},t)})}},V(Nr,"logName","DataChannelReadyHelper"),Nr);ch([ge()],Ha.prototype,"destroy"),ch([ge()],Ha.prototype,"sendReadyMsgLoop");let eg=Ha;class tg{constructor(e){V(this,"_useSysEchoCancellation",!0),V(this,"_useSysNoiseSuppression",!0),V(this,"_useSysAutoGainControl",!0),V(this,"_useAIAEC",!1),V(this,"_enableSoft3A",!1),V(this,"_enableSoft3ACheck",!1),V(this,"_useHardOnly",!1),V(this,"_dumpAudioData",!1),V(this,"_useAudio3AConfigFromServer",!0),e&&Object.assign(this,e)}get useSysEchoCancellation(){return this._useSysEchoCancellation}set useSysEchoCancellation(e){this._useSysEchoCancellation=e}get useSysNoiseSuppression(){return this._useSysNoiseSuppression}set useSysNoiseSuppression(e){this._useSysNoiseSuppression=e}get useSysAutoGainControl(){return this._useSysAutoGainControl}set useSysAutoGainControl(e){this._useSysAutoGainControl=e}get useAIAEC(){return this._useAIAEC}set useAIAEC(e){this._useAIAEC=e}get enableSoft3A(){return this._enableSoft3A}set enableSoft3A(e){this._enableSoft3A=e}get enableSoft3ACheck(){return this._enableSoft3ACheck}set enableSoft3ACheck(e){this._enableSoft3ACheck=e}get useHardOnly(){return this._useHardOnly}set useHardOnly(e){this._useHardOnly=e}get dumpAudioData(){return this._dumpAudioData}set dumpAudioData(e){this._dumpAudioData=e}get useAudio3AConfigFromServer(){return this._useAudio3AConfigFromServer}set useAudio3AConfigFromServer(e){this._useAudio3AConfigFromServer=e}loadFromLocalConfig(e){var t,n,r,a,s,o,c,h,l;this.useAudio3AConfigFromServer=(t=e.useAudio3AConfigFromServer)!=null?t:this.useAudio3AConfigFromServer,this.useSysEchoCancellation=(n=e.useSysEchoCancellation)!=null?n:this.useSysEchoCancellation,this.useSysNoiseSuppression=(r=e.useSysNoiseSuppression)!=null?r:this.useSysNoiseSuppression,this.useSysAutoGainControl=(a=e.useSysAutoGainControl)!=null?a:this.useSysAutoGainControl,this.useAIAEC=(s=e.useAIAEC)!=null?s:this.useAIAEC,this.enableSoft3A=(o=e.enableSoft3A)!=null?o:this.enableSoft3A,this.dumpAudioData=(c=e.dumpAudioData)!=null?c:this.dumpAudioData,this.enableSoft3ACheck=(h=e.enableSoft3ACheck)!=null?h:this.enableSoft3ACheck,this.useHardOnly=(l=e.useHardOnly)!=null?l:this.useHardOnly}loadFromServerConfig(e){if(e&&typeof e=="object"){const t=rr(e,"enableSoft3A"),n=Ir(e,"enableSoft3A");if(t===!0&&n===!0&&(this.enableSoft3A=!0),this.enableSoft3A){if(e.archCfgs){const r=rr(e,"enableSoft3ACheck");r!==void 0&&(this.enableSoft3ACheck=r);const a=rr(e,"useAIAEC");a!==void 0&&(this.useAIAEC=a);const s=rr(e,"useSysNoiseSuppression");s!==void 0&&(this.useSysNoiseSuppression=s);const o=rr(e,"useSysEchoCancellation");o!==void 0&&(this.useSysEchoCancellation=o);const c=rr(e,"useSysAutoGainControl");c!==void 0&&(this.useSysAutoGainControl=c)}if(e.config){const r=Ir(e,"enableSoft3ACheck");r!==void 0&&(this.enableSoft3ACheck=r);const a=Ir(e,"useAIAEC");a!==void 0&&(this.useAIAEC=a);const s=Ir(e,"useSysNoiseSuppression");s!==void 0&&(this.useSysNoiseSuppression=s);const o=Ir(e,"useSysEchoCancellation");o!==void 0&&(this.useSysEchoCancellation=o);const c=Ir(e,"useSysAutoGainControl");c!==void 0&&(this.useSysAutoGainControl=c)}Re.info("setAudio3AConfig:","enableSoft3A",this.enableSoft3A,", enableSoft3ACheck",this.enableSoft3ACheck,", useAIAEC",this.useAIAEC,", useSysNoiseSuppression",this.useSysNoiseSuppression,", useSysEchoCancellation",this.useSysEchoCancellation,", useSysAutoGainControl",this.useSysAutoGainControl)}}}}var ig=Object.defineProperty,ng=Object.getOwnPropertyDescriptor,vi=(i,e,t,n)=>{for(var r,a=ng(e,t),s=i.length-1;s>=0;s--)(r=i[s])&&(a=r(e,t,a)||a);return a&&ig(e,t,a),a};class ri extends Kt{constructor(e){super(),V(this,"self"),V(this,"userMap",{}),V(this,"usersViewMap",{}),V(this,"rtsManager"),V(this,"localStreamManager"),V(this,"authInfo"),V(this,"signalingManager"),V(this,"pluginManager"),V(this,"audioMixerPlugin"),V(this,"dualVideoPlugin"),V(this,"blankAudioPlugin"),V(this,"audioProcessorPlugin"),V(this,"slsReporter"),V(this,"statsMonitorId"),V(this,"autoSubAudio",!0),V(this,"autoSubVideo",!0),V(this,"autoSubScreen",!0),V(this,"wantSubAudio",!0),V(this,"wantSubVideo",!0),V(this,"wantSubScreen",!0),V(this,"defaultStreamType",ti.AliRtcVideoStreamTypeHigh),V(this,"audioMuted",!1),V(this,"playoutVolume",1),V(this,"refreshUrlTimer"),V(this,"audioVolumeIndicationInterval",0),V(this,"indicationTimer",0),V(this,"parameter",{}),V(this,"audio3AConfig",new tg),V(this,"dcReadyHelper"),V(this,"networkQualityTimer");const{signalingManager:t,slsReporter:n,parameter:r}=e;this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=n,r&&(this.parameter=r),this.pluginManager=new km,this.localStreamManager=new Gm(this.pluginManager,this.slsReporter),this.rtsManager=new Vm(this.localStreamManager,this.slsReporter,this.parameter),this.addRTSListener(),this.self=new xm({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter}),this.audioMixerPlugin=new Km,this.pluginManager.add(this.audioMixerPlugin),this.dualVideoPlugin=new qm("dualVideoPlugin"),new St.AliRTS.SupportUtil().checkScreenCapture()&&this.pluginManager.add(new jm)}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{e.forEach(t=>{var n;(n=t==null?void 0:t.tracks)==null||n.forEach(r=>{var a;if(r.msid===Me.Audio&&r.userdata)try{const s=JSON.parse(r.userdata);s.agent_instance&&((a=this.slsReporter)==null||a.setCustomFields({ageniid:s.agent_instance}))}catch(s){console.error("Failed to parse userdata:",s)}})}),this.slsReporter.reportConnectionLatencyEvent(wi.RECV_NOTIFY_PUBLISH,"","",""),Re.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})})}addRTSListener(){this.rtsManager.on("traceIdUpdated",(e,t)=>{if(kt.removeQueryString(this.self.url)===kt.removeQueryString(e))return void(this.self.traceId=t);const n=this.remoteUsers.find(r=>kt.removeQueryString(r.streamUrl)===kt.removeQueryString(e));n&&(n.traceId=t)}),this.rtsManager.on("reconnect",(e,t,n)=>{if(!e||e==="pc"||e==="all")return this.self.markReconnect(),void this.remoteUsers.forEach(a=>{a.markReconnect()});if(e==="pub"||e==="pub-data")return void this.self.markReconnect(n);const r=this.remoteUsers.find(a=>kt.removeQueryString(a.streamUrl)===kt.removeQueryString(t||""));r==null||r.markReconnect(n)}),this.rtsManager.on("reconnectFinish",(e,t,n)=>{if(Re.event("[RtsManager]","reconnectFinish",e,t,n),!e||e==="pc"||e==="all")return this.self.markReconnected(),void this.remoteUsers.forEach(a=>{a.markReconnected()});if(e==="pub"||e==="pub-data")return void this.self.markReconnected(n);const r=this.remoteUsers.find(a=>kt.removeQueryString(a.streamUrl)===kt.removeQueryString(t||""));r==null||r.markReconnected(n)})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe(Ct.User)})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe(Ct.User)})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe(Ct.User)})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var n;(n=this.getRemoteUser(e))==null||n.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){if(!e)return this.publisher.setViewConfig(null,t);const n=oa(e);n.length!==0&&n.forEach(r=>{this.publisher.resetElement(r),Object.values(this.usersViewMap).forEach(({cameraViews:a=[],screenViews:s=[]})=>{a.includes(r)&&a.splice(a.indexOf(r),1),s.includes(r)&&s.splice(s.indexOf(r),1)}),this.publisher.setViewConfig(n,t)})}setRemoteViewConfig(e,t,n){var r,a;if(!t)return(r=this.userMap[e])==null?void 0:r.setViewConfig(null,n);const s=oa(t);s.length!==0&&(s.forEach(o=>{this.publisher.resetElement(o),Object.values(this.usersViewMap).forEach(({cameraViews:c=[],screenViews:h=[]})=>{c.includes(o)&&c.splice(c.indexOf(o),1),h.includes(o)&&h.splice(h.indexOf(o),1)})}),(a=this.userMap[e])==null||a.setViewConfig(s,n))}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{const{isAudioSubscribing:n,isVideoSubscribing:r,isScreenSubscribing:a}=t;return n||r||a})}onRemotePublishStateChange(e,t=!0){var n;const{userid:r,callid:a,subscribe:s,pubid:o="",tracks:c}=e,h=(n=s==null?void 0:s.pullstreamurl)!=null?n:"";let l=this.getRemoteUser(r);if(!l)return;const f=l.streamInfo.audioTrackInfo,v=l.streamInfo.videoTrackInfo;l.updateRemoteTracks(a,h,o,c),f===l.streamInfo.audioTrackInfo&&v===l.streamInfo.videoTrackInfo||this.emit("remoteTrackAvailableChange",r,l.streamInfo.audioTrackInfo,l.streamInfo.videoTrackInfo),t&&l.updateSubscribe(Ct.Publish)}setTimeoutToUpdateAllStreamUrls(e){var t;if(!e)return;let n=354e4;const r=(t=function(a){var s,o;try{const c=new URL(a),[h,l]=c.pathname.slice(1).split("/"),f=/(\w+)(web\w{5}-\w{4}-\w{4}-\w{4}-\w{12})/.exec(l),v=f==null?void 0:f[1],p=f==null?void 0:f[2],_=new URLSearchParams(c.search);return{appId:h,channelId:v,sessionId:p,timeoutTs:1e3*parseInt((o=(s=_.get("auth_key"))==null?void 0:s.split("-")[0])!=null?o:"0")}}catch{return null}}(e))==null?void 0:t.timeoutTs;r&&(n=r-Date.now()-6e4),this.refreshUrlTimer=window.setTimeout(()=>le(this,null,function*(){var a;const s=yield this.signalingManager.refreshUrl({pushstreamurl:this.self.url,users:this.remoteUsers.map(o=>({userid:o.userId,subscribe:{pullstreamurl:o.streamUrl}}))});s.pushstreamurl&&(this.self.url=s.pushstreamurl),(a=s.users)==null||a.forEach(o=>{var c;const h=this.getRemoteUser(o.userid);h&&(c=o.subscribe)!=null&&c.pullstreamurl&&(h.streamUrl=o.subscribe.pullstreamurl)}),this.setTimeoutToUpdateAllStreamUrls(s.pushstreamurl)}),n)}init(e,t,n){var r;this.authInfo=e,this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),this.self.initInfo(e,t.pushstreamurl),this.audio3AConfig.useAudio3AConfigFromServer&&this.audio3AConfig.loadFromServerConfig((r=t==null?void 0:t.config)==null?void 0:r.data),this.setupAudioProcessingPluginIfNeeded(),n.capabilityProfile===os.Human&&(this.dcReadyHelper=new eg(this.self,n.robotUserId),this.dcReadyHelper.on("dcready",a=>{var s;this.emit("remoteUserSubscribedDataChannel",a),(s=this.dcReadyHelper)==null||s.destroy(),this.dcReadyHelper=void 0})),this.setTimeoutToUpdateAllStreamUrls(t.pushstreamurl),t.users.forEach(a=>{this.addUser(a,Ct.InRoom)}),this.startStatsMonitor(),this.networkQualityTimer=window.setInterval(()=>le(this,null,function*(){if(this.remoteUsers.length===0)return void this.emit("networkQuality",{subscribe:{rtt:0,loss:0,quality:Ui.AliRtcNetworkUnknown}});const a=yield this.rtsManager.getSubscribeNetworkQuality();this.emit("networkQuality",{subscribe:a})}),2e3)}leave(){return le(this,null,function*(){var e;this.stopStatsMonitor(),this.refreshUrlTimer!==void 0&&(window.clearTimeout(this.refreshUrlTimer),this.refreshUrlTimer=void 0),Object.values(this.usersViewMap).forEach(({cameraViews:t=[],screenViews:n=[]})=>{t.forEach(r=>{r.srcObject=null,r._playPromise=void 0}),n.forEach(r=>{r.srcObject=null,r._playPromise=void 0})}),this.usersViewMap={};for(let t in this.userMap)this.userMap[t]&&(this.userMap[t].clear(),delete this.userMap[t]);this.self.leave(),(e=this.dcReadyHelper)==null||e.destroy(),this.dcReadyHelper=void 0,this.localStreamManager.stop(),this.rtsManager.clear(),this.authInfo=void 0,window.clearInterval(this.networkQualityTimer)})}clear(){return le(this,null,function*(){yield this.leave(),this.self.clear(),this.pluginManager.removeAll()})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>le(this,null,function*(){if(this.publisher){const{audio:n,video:r,candidate:a}=yield this.publisher.getStats();n&&n.length>0&&this.emit("rtcLocalAudioStats",n),r&&r.length>0&&this.emit("rtcLocalVideoStats",r),a&&this.emit("rtcStats",a)}const e=[],t=[];for(const n of this.remoteUsers){const{audio:r,video:a}=yield n.getStats();r&&r.forEach(s=>{e.push(s)}),a&&a.forEach(s=>{t.push(s)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&clearInterval(this.statsMonitorId)}addUser(e,t){const n=e.userid;let r=this.userMap[n];return r||(r=this.executeAddUser(n,e.displayname||"",t),this.userMap[n]=r,this.emit("remoteUserJoin",n,0)),this.onRemotePublishStateChange(e,t!==Ct.InRoom),r}executeAddUser(e,t,n){const r=new Nm({userId:e,displayName:t,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,slsReporter:this.slsReporter,localUser:this.self,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume,parameter:this.parameter});return r.on(ai.Remote,this.onRemoteDeviceStatusChange.bind(this)),r.on(Nt.PullStreamStats,this.onRemoteStatReport.bind(this)),r.on(Nt.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),r.on("audioSubscribeStateChanged",(a,s,o,c)=>{this.emit("audioSubscribeStateChanged",a,s,o,c,this.channel||"")}),r.on("videoSubscribeStateChanged",(a,s,o,c)=>{this.emit("videoSubscribeStateChanged",a,s,o,c,this.channel||"")}),r.on("screenSubscribeStateChanged",(a,s,o,c)=>{this.emit("screenSubscribeStateChanged",a,s,o,c,this.channel||"")}),r.on("dataSubscribeStateChanged",(a,s,o,c)=>{var h;o===ut.AliRtcStateSubscribed&&((h=this.dcReadyHelper)==null||h.onSubscribeDataChannel(this.userMap[a])),this.emit("dataSubscribeStateChanged",a,s,o,c,this.channel||"")}),r.on("remoteAudioAutoPlayFail",a=>{this.emit("remoteAudioAutoPlayFail",a)}),r.on("remoteVideoAutoPlayFail",(a,s)=>{this.emit("remoteVideoAutoPlayFail",a,s)}),r.on("remoteAudioPlayError",(a,s)=>{this.emit("remoteAudioPlayError",a,s)}),r.on("remoteVideoPlayError",(a,s)=>{this.emit("remoteVideoPlayError",a,s)}),r.on("remoteSubscribeError",a=>{this.emit("remoteSubscribeError",a,r.userId)}),r.on("occurError",a=>{this.emit("occurError",a,r.userId)}),r.on("remoteDataChannelMessage",(a,s)=>{this.emit("remoteDataChannelMessage",a,s)}),r.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),r.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),r.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),r.setRemoteDefaultVideoStreamType(this.defaultStreamType),r.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&r.updateSubscribe(n),r}onRemoteDeviceStatusChange(e,t){e===Nt.MuteAudio?this.emit("userAudioMuted",t,!0):e===Nt.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Nt.MuteVideo?this.emit("userVideoMuted",t,!0):e===Nt.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Nt.MuteScreen?this.emit("userScreenMuted",t,!0):e===Nt.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,n){this.emit(Nt.PullStreamStats,e,t,n)}onSubscribeExceeds(e,t){this.emit(Nt.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return le(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}diffUsers(e){const t=[],n=[];e.forEach(a=>{a.userid&&(this.userMap[a.userid]?n.push(a):t.push(a))});const r=Object.keys(this.userMap).filter(a=>!e.find(s=>s.userid===a)).map(a=>({userid:a,reason:"",leavecode:na.AliRtcUserOfflineQuit}));return{joinList:t,leaveList:r,presentList:n}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const n=this.userMap[e];if(!n)throw new Le(Ne.ERR_INNER,`no remote user(${e}) founded`);n.setWantSubAudio(t),t?n.updateSubscribe(Ct.User):n.stopSubscribe({audio:!0})}updateVideoWant(e,t){const n=this.userMap[e];if(!n)throw new Le(Ne.ERR_INNER,`no remote user(${e}) founded`);n.setWantSubVideo(t),t?n.updateSubscribe(Ct.User):n.stopSubscribe({video:!0})}updateScreenWant(e,t){const n=this.userMap[e];if(!n)throw new Le(Ne.ERR_INNER,`no remote user(${e}) founded`);n.setWantSubScreen(t),t?n.updateSubscribe(Ct.User):n.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&window.clearInterval(this.indicationTimer)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{const t=this.remoteUsers.map(n=>({userId:n.userId,volume:n.getAudioLevel()||0}));t.unshift({userId:"",volume:this.self.getAudioLevel()||0}),this.emit("audioVolume",t)},e)}setEnableDualVideoStream(e,t){if(!this.dualVideoPlugin)return;t&&this.dualVideoPlugin.setOptions(t);const n=this.pluginManager.has(this.dualVideoPlugin.name);e?!n&&this.pluginManager.add(this.dualVideoPlugin):n&&this.pluginManager.remove(this.dualVideoPlugin.name)}setAudioVolume(e){var t;(t=this.audioMixerPlugin)==null||t.setOptions(e)}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(t=>{t.enableAudioVolumeIndication(e)}),this.self.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){this.authInfo&&(this.authInfo=Ze(Ze({},this.authInfo),e)),e.userId&&this.self.refreshUserInfo(e.userId)}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}setVideoCodec(e){this.rtsManager.changeVideoCodec(e)}setParameter(e){var t,n,r,a;const s=JSON.parse(e);Object.keys(s).forEach(o=>{const c=this.parameter[o],h=s[o];this.parameter[o]=typeof c=="object"&&typeof h=="object"?Ze(Ze({},c),h):h}),s.enableBlankAudio===!0?(this.blankAudioPlugin||(this.blankAudioPlugin=new Xm),this.pluginManager.has((t=this.blankAudioPlugin)==null?void 0:t.name)||this.pluginManager.add(this.blankAudioPlugin)):s.enableBlankAudio===!1&&(this.blankAudioPlugin&&this.pluginManager.remove((n=this.blankAudioPlugin)==null?void 0:n.name),(r=this.blankAudioPlugin)==null||r.clear(),this.blankAudioPlugin=void 0),s.audio&&((a=this.audio3AConfig)==null||a.loadFromLocalConfig(s.audio))}setupAudioProcessingPluginIfNeeded(){if(this.audio3AConfig.enableSoft3A){let e=0;this.audio3AConfig.enableSoft3ACheck&&(e=1e4),setTimeout(()=>{this.audioProcessorPlugin||(this.audioProcessorPlugin=new Jm({dumpAudioData:this.audio3AConfig.dumpAudioData,aiaecOn:this.audio3AConfig.useAIAEC,slsReporter:this.slsReporter,enableSoft3ACheck:this.audio3AConfig.enableSoft3ACheck,useHardOnly:this.audio3AConfig.useHardOnly})),this.audioProcessorPlugin&&!this.pluginManager.has(this.audioProcessorPlugin.name)&&(this.audioProcessorPlugin.on("error",({message:t})=>{var n;Re.error("audioProcessorPlugin error:",t),(n=this.self.audioTrack)==null||n.applyConstraints({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0})}),this.pluginManager.add(this.audioProcessorPlugin))},e)}else this.audioProcessorPlugin&&(this.pluginManager.remove(this.audioProcessorPlugin.name),this.audioProcessorPlugin=void 0);this.self.setMicrophoneConstraints({echoCancellation:this.audio3AConfig.useSysEchoCancellation,noiseSuppression:this.audio3AConfig.useSysNoiseSuppression,autoGainControl:this.audio3AConfig.useSysAutoGainControl})}getParameter(){return JSON.stringify(this.parameter)}sendDataChannelMessage(e){return this.self.sendDataChannelMessage(e)}}V(ri,"logName","BizControl"),vi([ge()],ri.prototype,"init"),vi([ge()],ri.prototype,"leave"),vi([ge()],ri.prototype,"clear"),vi([ge(ke)],ri.prototype,"addUser"),vi([ge()],ri.prototype,"removeLeftUser"),vi([ge()],ri.prototype,"diffUsers"),vi([ge(ke)],ri.prototype,"updateAudioWant"),vi([ge(ke)],ri.prototype,"updateVideoWant"),vi([ge(ke)],ri.prototype,"updateScreenWant"),vi([ge()],ri.prototype,"stopIndication"),vi([ge()],ri.prototype,"startIndication"),vi([ge(ke)],ri.prototype,"setEnableDualVideoStream"),vi([ge(ke)],ri.prototype,"setAudioVolume"),vi([ge()],ri.prototype,"enableAudioVolumeIndication");var ss=(i=>(i[i.LiveTranscodingSingle=0]="LiveTranscodingSingle",i[i.LiveTranscodingMix=1]="LiveTranscodingMix",i))(ss||{}),lh=(i=>(i[i.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",i[i.LiveTranscodingAudio=1]="LiveTranscodingAudio",i[i.LiveTranscodingVideo=2]="LiveTranscodingVideo",i))(lh||{}),Ao=(i=>(i[i.LiveTranscodingCamera=0]="LiveTranscodingCamera",i[i.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",i))(Ao||{});const Co={0:"camera",1:"shareScreen"};var uh=(i=>(i[i.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",i[i.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",i[i.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",i[i.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",i[i.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",i[i.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",i[i.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",i[i.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",i[i.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",i[i.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",i[i.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",i[i.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",i[i.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",i[i.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",i[i.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",i[i.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",i[i.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",i[i.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",i[i.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",i))(uh||{});const rg={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var Ga=(i=>(i[i.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",i[i.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",i[i.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",i[i.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",i[i.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",i))(Ga||{}),as=(i=>(i[i.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",i[i.LiveTranscodingBody=1]="LiveTranscodingBody",i))(as||{}),cs=(i=>(i[i.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",i[i.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",i[i.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",i[i.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",i[i.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",i[i.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",i))(cs||{}),dh=(i=>(i[i.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",i[i.LiveTranscodingCrop=1]="LiveTranscodingCrop",i[i.LiveTranscodingFill=2]="LiveTranscodingFill",i))(dh||{}),za=(i=>(i[i.LiveTranscodingNormal=0]="LiveTranscodingNormal",i[i.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",i))(za||{}),hh=(i=>(i[i.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",i[i.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",i[i.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",i[i.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",i[i.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",i[i.LiveTranscodingState_END=5]="LiveTranscodingState_END",i))(hh||{}),En=(i=>(i[i.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",i[i.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",i[i.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",i[i.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",i[i.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",i[i.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",i[i.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",i[i.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",i[i.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",i))(En||{}),ph=(i=>(i[i.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",i[i.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",i[i.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",i))(ph||{}),_i=(i=>(i[i.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",i[i.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",i[i.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",i[i.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",i[i.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",i[i.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",i[i.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",i))(_i||{});const og={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class fh{constructor(e,t,n,r,a,s,o,c){V(this,"videoWidth"),V(this,"videoHeight"),V(this,"videoFramerate",20),V(this,"videoBitrate",2e3),V(this,"videoGop",30),V(this,"audioSamplerate",Ga.LiveTranscoding_HZ_44100),V(this,"audioBitrate",500),V(this,"audioChannels",1),this.videoWidth=e,this.videoHeight=t,n&&(this.videoFramerate=n),r&&(this.videoBitrate=r),a&&(this.videoGop=a),s&&(this.audioSamplerate=s),o&&(this.audioBitrate=o),c&&(this.audioChannels=c)}}const Wa=i=>((16711680&i)>>16)+(65280&i)+((255&i)<<16),Hi=(i=0,e)=>{if(e==0)return 0;let t=i/e;return t<0&&(t=0),t>1&&(t=1),t};class ja{constructor(e,t,n){V(this,"mixMode",ss.LiveTranscodingSingle),V(this,"singleParam"),V(this,"mixParam"),e&&(this.mixMode=e),t&&(this.singleParam=t),n&&(this.mixParam=n)}toJson(e,t,n,r,a){const s={appid:t.appId,channelid:t.channelId};if(e===_i.MPU_TASK_TRANSACTION_POLLING||e===_i.MPU_TASK_TRANSACTION_LIST||e===_i.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return e===_i.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(s.messageid=a),s;if(s.taskid=n,e!==_i.MPU_TASK_TRANSACTION_STOP){if(s.mixmode=this.mixMode,r&&(s.streamurl=r),this.mixMode===ss.LiveTranscodingSingle){const o=this.singleParam;if(o){s.streamtype=o.streamType,o.sourceType===Ao.LiveTranscodingShareScreen?s.sourcetype=Co[o.sourceType]:s.sourcetype=Co[Ao.LiveTranscodingCamera];const c=[];o.userId&&c.push(o.userId),s.subspecusers=c}}else if(e===_i.MPU_TASK_TRANSACTION_START||e===_i.MPU_TASK_TRANSACTION_UPDATE){const o=this.mixParam;if(o){o.taskProfile&&(s.taskprofile=rg[o.taskProfile]);const c=o.encodeParam||new fh(1280,720);let h=c.videoWidth,l=c.videoHeight;const f={};Object.keys(c).forEach(p=>{const _=c[p];_>0&&(f[p.toLowerCase()]=_)}),f.lowbitratehighquality=0,s.encodeparam=f,s.backgrounds=o.backgrounds.map(p=>p.toJson(h,l)),s.watermarks=o.watermarks.map(p=>p.toJson(h,l)),s.clockwidgets=o.clockWidgets.map(p=>p.toJson(h,l));const v=o.users.map(p=>p.userId);s.subspecusers=[...new Set(v)],s.layouts=[{audiomixcount:o.users.length,panes:o.users.map((p,_)=>p.toJson(_,h,l,o.mediaProcessMode))}],s.layoutids=["0"],s.cropmode=o.cropMode,s.backgroundcolor=Wa(o.backgroundColor),s.taskmode=o.mediaProcessMode}}}return s}}const Xa=i=>le(void 0,null,function*(){const e=new Uint8Array(160).fill(170),t=new TextEncoder().encode(i),n=yield window.crypto.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),r=yield window.crypto.subtle.sign("HMAC",n,t);return Array.from(new Uint8Array(r)).map(a=>a.toString(16).padStart(2,"0")).join("")});class sg{constructor(e){V(this,"authInfo"),V(this,"slsReporter"),this.slsReporter=e}doRequest(e,t){var n;const r=this.authInfo;if(!r)return Promise.reject(En.LiveTranscodingErrorInvalidParam);const a=og[e],s={appid:r.appId,userid:r.userId,channelid:r.channelId,timestamp:r.timestamp,token:r.token,nonce:r.nonce?r.nonce:"",requestid:kt.createCallid(),tokensid:!1,session:(n=r.sessionId)!=null?n:kt.createCallid()},o=Object.keys(s).map(c=>`${c}=${encodeURIComponent(s[c])}`).join("&");return fetch(`https://gw.rtn.aliyuncs.com${a}?${o}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(t)}).then(c=>c.status!==200?(this.slsReporter.reportTranscodingError(c.status,t.taskid||""),Promise.reject(new Le(Ne.ERR_INNER,`transcoding request failed, status: ${c.status}`))):c).catch(c=>Promise.reject(new Le(Ne.ERR_INNER,`transcoding request failed, err: ${c.message}`)))}setAuthInfo(e){this.authInfo=e}clear(){this.authInfo=void 0}startPublishLiveStream(e,t){return le(this,null,function*(){if(!this.authInfo)return Promise.reject(En.LiveTranscodingErrorInvalidParam);const n=yield Xa(e.split("?")[0]),r=_i.MPU_TASK_TRANSACTION_UPDATE,a=t.toJson(r,this.authInfo,n,e);return this.doRequest(r,a)})}startPublishLiveStreamWithTaskId(e,t){return le(this,null,function*(){if(!this.authInfo)return Promise.reject(En.LiveTranscodingErrorInvalidParam);const n=_i.MPU_TASK_TRANSACTION_UPDATE,r=t.toJson(n,this.authInfo,e);return this.doRequest(n,r)})}updatePublishLiveStream(e,t){return le(this,null,function*(){if(!this.authInfo)return Promise.reject(En.LiveTranscodingErrorInvalidParam);const n=yield Xa(e.split("?")[0]),r=_i.MPU_TASK_TRANSACTION_UPDATE,a=t.toJson(r,this.authInfo,n,e);return this.doRequest(r,a)})}updatePublishLiveStreamWithTaskId(e,t){return le(this,null,function*(){if(!this.authInfo)return Promise.reject(En.LiveTranscodingErrorInvalidParam);const n=_i.MPU_TASK_TRANSACTION_UPDATE,r=t.toJson(n,this.authInfo,e);return this.doRequest(n,r)})}stopPublishLiveStream(e){return le(this,null,function*(){if(!this.authInfo)return Promise.reject(En.LiveTranscodingErrorInvalidParam);const t=yield Xa(e.split("?")[0]),n=_i.MPU_TASK_TRANSACTION_STOP,r=new ja().toJson(n,this.authInfo,t,e);return this.doRequest(n,r)})}stopPublishLiveStreamWithTaskId(e){if(!this.authInfo)return Promise.reject(En.LiveTranscodingErrorInvalidParam);const t=_i.MPU_TASK_TRANSACTION_STOP,n=new ja().toJson(t,this.authInfo,e);return this.doRequest(t,n)}refreshAuthInfo(e){this.authInfo&&this.setAuthInfo(Ze(Ze({},this.authInfo),e))}}function mh(i,e){const t=new window.XMLHttpRequest;t.open("POST",`${i}?APIVersion=0.6.0`,!0),t.send(e)}function ag(i,e){try{if(e.length>=32768)return void mh(i,e);(function(t,n){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${t}?APIVersion=0.6.0`,n)})(i,e)||mh(i,e)}catch(t){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
`+t),console.error("Failed log data:",i))}}function cg(i,e,t){return n=this,r=null,a=function*(){try{i=i.slice(0,-6);const{data:s,header:o}=yield t.process(i,e),c=new window.XMLHttpRequest;c.open("POST",i,!0);for(let h in o)c.setRequestHeader(h,o[h]);c.send(s)}catch(s){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
`+s),console.error("Failed log data:",i))}},new Promise((s,o)=>{var c=f=>{try{l(a.next(f))}catch(v){o(v)}},h=f=>{try{l(a.throw(f))}catch(v){o(v)}},l=f=>f.done?s(f.value):Promise.resolve(f.value).then(c,h);l((a=a.apply(n,r)).next())});var n,r,a}class gh extends ed{constructor(e){super(Object.assign({},e,{installUnloadHook:t=>{window.addEventListener("beforeunload",()=>{t()})},sendPayload:(t,n)=>{ag(t,n)}}))}useStsPlugin(e){this.getOpt().sendPayload=(t,n)=>{cg(t,n,e)},this.overwriteTransString(e)}}jl(window,"SLS_Tracker",gh);const vh=class jo{constructor(){V(this,"ntpClock"),this.ntpClock=new St.AliRTS.Clock}static getInstance(){return jo.instance||(jo.instance=new jo),jo.instance}now(){return this.ntpClock.now()}};V(vh,"instance");let lg=vh;const _h=()=>lg.getInstance(),{BrowserUtil:$a,SystenUtil:Sh}=St.AliRTS,ls=6e5,ug={host:"cn-shanghai.log.aliyuncs.com",project:"apsara-video-client",logstore:"client"},dg={host:"ap-southeast-1.log.aliyuncs.com",project:"apsara-video-client-sgp",logstore:"client"};class hg{constructor(e){V(this,"tracker"),V(this,"param"),V(this,"msgCacheArr",[]),V(this,"index",0),V(this,"ntpClock"),V(this,"clientId",Ai()),V(this,"stsData"),V(this,"stsExpiration",Date.now()),V(this,"updateTaskTimer"),V(this,"globalEnv","DEFAULT"),this.ntpClock=_h(),e&&(this.globalEnv=e),this.startSTSUpdateTask()}createTracker(){if(!this.tracker&&this.stsData&&this.param){const e=this.globalEnv==="SEA"?dg:ug,t=new gh({host:e.host,project:e.project,logstore:e.logstore}),n={accessKeyId:this.stsData.AccessKeyId,accessKeySecret:this.stsData.AccessKeySecret,securityToken:this.stsData.SecurityToken,refreshSTSTokenInterval:ls,refreshSTSToken:()=>{this.refreshSTSToken().then(a=>{n.accessKeyId=a.AccessKeyId,n.accessKeySecret=a.AccessKeySecret,n.securityToken=a.SecurityToken}).catch(()=>{})}},r=da(n);t.useStsPlugin(r),this.tracker=t,this.msgCacheArr.forEach((a,s)=>{var o,c;(c=this.tracker)==null||c.send(Ze(Ki(Ze({},this.param),{stat_log_id:`${((o=this.param)==null?void 0:o.sesid)||"nosession"}-${s}`}),a))}),this.index=this.index+this.msgCacheArr.length,this.msgCacheArr=[]}}startSTSUpdateTask(){return le(this,null,function*(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer);try{this.stsData=yield this.refreshSTSToken(),this.createTracker()}catch{}this.updateTaskTimer=setTimeout(()=>{this.startSTSUpdateTask()},ls)})}refreshSTSToken(){return le(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()+ls){const e=yield this.requestSTSToken(),t=new Date(e==null?void 0:e.Expiration).getTime()||0,n=Date.now()+ls;this.stsExpiration=Math.max(t,n),this.stsData=e}return this.stsData})}requestSTSToken(){const e=Date.now(),t=`${this.clientId}|woMMssV6jmyol9fr|${e}`,n={Action:"AssumeSlsRoleV2",AuthInfo:ar.MD5(t).toString(ar.enc.Hex),ClientId:this.clientId,BusinessType:"rtc",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${e}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:Yo(e,"isoUtcDateTime")},r=new URLSearchParams(n).toString(),a=`https://${this.globalEnv==="SEA"?"vod.ap-southeast-1.aliyuncs.com":"vod.cn-shanghai.aliyuncs.com"}/?${r}`;return fetch(a).then(s=>s.json()).then(s=>JSON.parse(window.atob(s.SlsAuthResult)))}start(e){this.initParam(e),this.createTracker()}stop(){this.tracker=void 0,this.param=void 0,this.msgCacheArr=[],this.index=0,this.stsData=void 0,this.updateTaskTimer&&(clearTimeout(this.updateTaskTimer),this.updateTaskTimer=void 0)}sendReport(e){var t,n;let r;e.tm=Date.now();try{r=JSON.parse(JSON.stringify(Ze(Ki(Ze({bt:$a.browserName||"unknown",ntptm:this.ntpClock.now(),ntpofs:this.ntpClock.now()-Date.now()},this.param),{stat_log_id:`${((t=this.param)==null?void 0:t.sesid)||"nosession"}-${this.index}`}),e)))}catch{}r&&(this.tracker?((n=this.tracker)==null||n.send(r),this.index++):this.msgCacheArr.push(r))}initParam(e){let t="";try{t=(localStorage==null?void 0:localStorage.getItem("AliRtcUUID"))||"",t||(t=Ai(),localStorage==null||localStorage.setItem("AliRtcUUID",t))}catch{}this.param||(this.param={apid:e.appId,usrid:e.userId,statsvrs:"0.6.1",evetid:0,sesid:e.sessionId,sessionId:e.sessionId,channelid:e.channelId,usrn:e.userId,osn:Sh.systemName,osv:Sh.systemVersion,deb:rm(),den:tm(),udid:t,sdkvrs:vo,acs:"Unknown",cput:Zu(),dm:`${window.location.protocol}//${window.location.host}`,bt:$a.browserName,bv:$a.browserVersion,envir:"PRODUCT",args:"",instid:Ai()})}}const Dt=(i,e=1,t=6e4,n=0)=>{let r=i;return r||(r=0),Math.min(t,Math.max(n,Math.round(r*e)))},Gi=(i,e,t=2e7,n=0)=>{let r=e;(!e||e<0||e>1e4)&&(r=1e3);let a=i;return a||(a=0),Math.min(t,Math.max(n,Math.round(a/(r/1e3))))},ur=(i,e)=>{if(e===0||!e)return"0.00";let t=i;return(!t||t<0)&&(t=0),(t/e*100).toFixed(2)},bh=i=>i>=0&&i<=1?Dt(Math.floor(32767*i),1,32767):0,Ot=(i,e)=>{var t,n,r;let a=((t=i._last)==null?void 0:t[e])||0;return i.ssrc&&(n=i._last)!=null&&n.ssrc&&i.ssrc!==((r=i._last)==null?void 0:r.ssrc)&&(a=0),((i==null?void 0:i[e])||0)-a},yh=(i,e)=>Dt(Ot(i,e),1e3,1e4),dr=(i,e=2e7)=>Dt(i,1,e);class pg{constructor(e,t){V(this,"engine"),V(this,"logClient"),V(this,"authInfo"),V(this,"ntpClock"),V(this,"customFields",{}),this.logClient=new hg(t),this.engine=e,this.ntpClock=_h()}setCustomFields(e){this.customFields=Ze(Ze({},this.customFields),e)}getCustomField(e){return this.customFields[e]}start(e){this.authInfo=e,this.logClient.start(e)}stop(){this.logClient.stop()}reportPublishAudio3A(e,t,n,r){const a={};let s=JSON.parse(r);a.publevel=s.capture_audio_cur_level_db||0,a.eleakrate=s.echo_leak_rate||0,a.playbw=s.render_bandwidth||-1,a.capbw=s.capture_bandwidth||-1,a.diff=s.diff||0,a.leak=s.leak||0,this.log({evetid:10070,traceid:n,calid:e,rmtid:"",args:this.data2String(Ze({calid:e,tckid:t||"audio3a",rmtid:"",traceid:n},a))})}reportPublishMonitor(e,t,n,r,a){if(!n||a.length<=0)return;const s=n===Me.Audio,o={ctm:Math.floor(a[0].timestamp||0),src:a[0].ssrc||"",codec:a[0]._codec||""},c=[],h=[],l=[],f=[],v=[],p=[],_=[],m=[],d=[],u=[],b=[],y=[],g=[],S=[],R=[],E=[],I=[],C=[],A=[];try{if(a.forEach(w=>{var N,M,D,L,P,x;if(!w||!w.timestamp)return;const T=(N=w._last)!=null&&N.timestamp?w.timestamp-w._last.timestamp:1e3,O=Ot(w,"bytesSent"),k=Ot(w,"headerBytesSent"),H=Gi(Dt(O+k,8,2e7),T);c.push(H);const U=Gi(Dt(O,8,2e7),T);h.push(U);const ee=Gi(Dt(k,8,2e7),T);l.push(ee);const W=Ot(w,"packetsSent"),$=Gi(W,T);f.push($);const B=Ot(w,"packetsLost"),F=Gi(B,T);v.push(F);const G=ur(B,W);if(p.push(G),s)(M=w._source)!=null&&M.audioLevel&&_.push(bh(w._source.audioLevel)),m.push(0);else{d.push(yh(w,"totalEncodeTime")),u.push(dr((D=w._source)==null?void 0:D.framesPerSecond,100)),b.push(dr((L=w._source)==null?void 0:L.framesPerSecond,100)),y.push(dr(w.framesPerSecond,100)),g.push(dr((P=w._source)==null?void 0:P.height,4400)),S.push(dr((x=w._source)==null?void 0:x.width,7700)),R.push(dr(w.frameHeight,4400)),E.push(dr(w.frameWidth,7700));const q=Ot(w,"totalPacketSendDelay");I.push(Dt(q,1/(B||1),2e3));const X=Ot(w,"qpSum");C.push(Dt(X,1/(w.framesPerSecond||1),51)),A.push(0)}}),o.sbr=c.join(","),o.mbrs=h.join(","),o.pbrs=l.join(","),o.ps=f.join(","),o.pl=v.join(","),o.plr=p.join(","),s){const w=(r==null?void 0:r.getSettings().sampleRate)||0;o.ailevel=_.join(","),o.arpc=m.join(","),o.arsr=w,o.aesr=w,o.publevel=-90,o.rawlevel=-90}else o.em=d.join(","),o.cfps=u.join(","),o.ifps=b.join(","),o.sfps=y.join(","),o.ih=g.join(","),o.iw=S.join(","),o.sh=R.join(","),o.sw=E.join(","),o.sd=I.join(","),o.aqp=C.join(","),o.caf=A.join(","),o.can=A.join(","),o.cav=h.join(","),o.ifimax=A.join(","),o.ifimin=A.join(","),o.efimax=A.join(","),o.efimin=A.join(","),o.sfimax=A.join(","),o.sfimin=A.join(","),o.apsnr=A.join(",")}catch{}this.log({evetid:10070,traceid:t,calid:e,rmtid:"",args:this.data2String(Ze({calid:e,tckid:n,rmtid:"",traceid:t},o))})}reportSubscribeMonitor(e,t,n,r,a){if(!r||!a||a.length<=0)return;const s=r===Me.Audio,o={ctm:Math.floor(a[0].timestamp||0),src:a[0].ssrc||"",codec:a[0]._codec||""},c=[],h=[],l=[],f=[],v=[],p=[],_=[],m=[],d=[],u=[],b=[],y=[],g=[],S=[],R=[],E=[],I=[],C=[],A=[],w=[],N=[],M=[],D=[],L=[],P=[],x=[],T=[],O=[],k=[],H=[],U=[],ee=[],W=[],$=[];try{a.forEach(B=>{var F,G;if(!B||!B.timestamp)return;const q=(F=B._last)!=null&&F.timestamp?B.timestamp-B._last.timestamp:1e3,X=Ot(B,"bytesReceived"),J=Ot(B,"headerBytesReceived"),se=Gi(Dt(X+J,8,2e7),q);c.push(se);const ce=Gi(Dt(X,8,2e7),q);h.push(ce);const Y=Gi(Dt(J,8,2e7),q);l.push(Y);const fe=Ot(B,"packetsReceived"),he=Gi(fe,q);f.push(he);const pe=Ot(B,"packetsLost"),ue=Gi(pe,q);v.push(ue);const Te=ur(pe,fe);p.push(Te);const be=Ot(B,"jitterBufferDelay"),Z=Ot(B,"jitterBufferEmittedCount");if(B.jitterBufferDelay&&B.jitterBufferEmittedCount){const ye=Dt(be,1e3/Z,1e4);_.push(ye)}else _.push(0);const K=Ot(B,"fecPacketsReceived");y.push(ur(K,fe));const re=Ot(B,"retransmittedPacketsReceived"),de=fe+pe-re;if(d.push(ur(fe-re,de)),u.push(ur(pe,de)),m.push(ur(re,de)),b.push(de),W.push(0),$.push(""),s){S.push(bh(B.audioLevel));const ye=((De,Ue)=>{var Ye,Ie,Oe;return(((Ye=De==null?void 0:De._source)==null?void 0:Ye[Ue])||0)-(((Oe=(Ie=De==null?void 0:De._last)==null?void 0:Ie._source)==null?void 0:Oe[Ue])||0)})(B,"synthesizedSamplesEvents");R.push(ye);const Ee=yh(B,"synthesizedSamplesDuration");E.push(Ee);const Ve=ur(Ee,q);g.push(Ve),I.push(0)}else{const ye=(G=B._last)!=null&&G.totalInterFrameDelay?B.totalInterFrameDelay-B._last.totalInterFrameDelay:0;C.push(Dt(ye,1e3/(B.framesDecoded||30),500)),A.push(Dt(B.framesPerSecond,1,100)),w.push(Ot(B,"framesReceived")),ee.push(Ot(B,"framesRendered")),N.push(Dt(B.frameHeight,1,4400)),M.push(Dt(B.frameWidth,1,7700));const Ee=Ot(B,"totalProcessingDelay");D.push(Dt(Ee,1e3/(B.framesDecoded||30),12e4));const Ve=Ot(B,"nackCount");P.push(Ve);const De=Ot(B,"pliCount");L.push(De);const Ue=Ot(B,"qpSum");x.push(Dt(Ue,1/(B.framesPerSecond||1),51)),T.push(Dt(B.framesDropped));const Ye=Ot(B,"totalFreezesDuration");O.push(Dt(Ye,1e3,3e4));const Ie=Ot(B,"jitterBufferEmittedCount"),Oe=Ot(B,"jitterBufferDelay");Oe&&Ie?k.push(Dt(Oe,1e3/Ie,3e4)):k.push(0);const $e=Ot(B,"jitterBufferTargetDelay");$e&&Ie?H.push(Dt($e,1e3/Ie,3e4)):H.push(0);const Ke=Ot(B,"jitterBufferMinimumDelay");Ke&&Ie?U.push(Dt(Ke,1e3/Ie,3e4)):U.push(0)}}),o.rbr=c.join(","),o.mbrs=h.join(","),o.pbrs=l.join(","),o.pr=f.join(","),o.pl=v.join(","),o.plr=p.join(","),o.jd=_.join(","),o.fecr=y.join(","),o.retransr=m.join(","),o.baser=d.join(","),o.basel=u.join(","),o.recoverr=W.join(","),o.alll=u.join(","),o.totalc=b.join(","),s?(o.er=g.join(","),o.aolevel=S.join(","),o.asrc=I.join(","),o.scnt=R.join(","),o.sdura=E.join(",")):(o.dm=C.join(","),o.dfps=A.join(","),o.rfps=w.join(","),o.rh=N.join(","),o.rw=M.join(","),o.fpt=$.join(","),o.ns=P.join(","),o.pliss=L.join(","),o.aqp=x.join(","),o.ofimax=W.join(","),o.ofimin=W.join(","),o.dfimax=W.join(","),o.dfimin=W.join(","),o.rfimax=W.join(","),o.rfimin=W.join(","),o.vrstutter=O.join(","),o.cdm=k.join(","),o.tdm=H.join(","),o.pdm=U.join(","),o.ofps=ee.join(","),o.dfbd=T.join(","))}catch{}this.log({evetid:10080,traceid:n,rmtid:t,calid:e,args:this.data2String(Ze({calid:e,rmtid:t,tckid:r,traceid:n},o))})}reportNetworkMonitor(e){if(e.length<=0)return;const t=[],n=[],r=[],a=[],s=[],o=[],c=[],h=[],l=[],f=[];e.forEach((p,_)=>{var m;if(!p.timestamp)return;const d=(m=p._last)!=null&&m.timestamp?p.timestamp-p._last.timestamp:1e3;t.push(Dt(p.currentRoundTripTime,1e3)),n.push(Dt(p.availableOutgoingBitrate,8,2e8)),r.push(Gi(Dt(p.bytesSent,8,2e7),d,25e6)),a.push(Gi(Dt(p.bytesReceived,8,2e7),d,25e6)),s.push(0),o.push(0),_%5==0&&(c.push(""),h.push(""),l.push(""),f.push(""))});const v={ctm:Math.floor(e[0].timestamp||0),rtt:t.join(","),bsps:r.join(","),brps:a.join(","),cpu:c.join(","),mem:h.join(","),sysmem:l.join(","),systotalmem:f.join(","),audioonly:this.engine.isAudioOnly()?1:0};this.log({evetid:10071,args:this.data2String(Ze({asb:n.join(","),abms:s.join(","),vbms:o.join(",")},v))}),this.log({evetid:10081,args:this.data2String(Ze({},v))})}reportLoopAudioDelay(e,t){var n;const{AIAgent:r={},AIGrtn:a={},AIPub:s={},AISub:o={},pub:c={},sub:h={},grtn:l={}}=t||{};if(Object.keys(r).length===0)return;let f=0;f=Object.keys(l).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(l.totalCost||0)+(h.downRTTHalf||0)+(h.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(h.vJitterBufferDelay||0)+(h.vDecPlugCost||0);const v={};let p=0;for(let m=0;m<10;m++){const d=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${m}`,u=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${m}`,b=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${m}`;if(!l.hasOwnProperty(d))break;p+=l[d]||0,p+=l[u]||0,p+=l[b]||0,v[`_gnd${m}`]=`gnd[${m}]: {${this.data2String({gnirh:l[d]||0,gnbp:l[u]||0,gnpc:l[b]||0})}}`}const _={};for(let m=0;m<10;m++){const d=`aigrtninternalrtthalf_${m}`,u=`aigrtnbeforepacer_${m}`,b=`aigrtnpacercost_${m}`;if(!a.hasOwnProperty(d))break;_[`_lgnd${m}`]=`lgnd[${m}]: {${this.data2String({gnirh:a[d]||0,gnbp:a[u]||0,gnpc:a[b]||0})}}`}this.log({evetid:10073,args:this.data2String(Ki(Ze({tdlms:f+(r.aiagenttotalcost||0),_:`aiqud:{${this.data2String(Ki(Ze({uid:((n=this.authInfo)==null?void 0:n.userId)||"",sid:s.aAIClientScentenceId||0,quct:65535*(s.aAIClientQuestionTimestampHEAD||0)+(s.aAIClientQuestionTimestampTAIL||0),anct:65535*(s.aAIClientAnswerTimestampHEAD||0)+(s.aAIClientAnswerTimestampTAIL||0),casc:s.aAIClientSourceCost||0,camc:s.aAIClientMixerCost||0,caec:s.aAIClientEncoderCost||0,cantc:s.aIClientNetsdkThrCost||0,caqtc:s.aIClientQosThrCost||0,capc:s.aIClientPacerCost||0,cuphr:s.aIClientUpRTTHalf||0},_),{qgac:0,ldhr:l.ngxRtcSeiCumulativeDelayKeyDownRttHalf_0||0,larc:o.aAILinuxReceiveCost||0,lanqc:o.aAILinuxNeteqCost||0,larsc:o.aAILinuxRemoteSourceCost||0,lapmc:o.aAILinuxPlayMixerCost||0,lapc:o.aAILinuxPlayCost||0,lsdnc:o.aIClinetSmartDenoise||0,asrc:r.aiasrcost||0,llmc:r.aillmcost||0,ttsc:r.aittscost||0,aamc:r.aimutecost||0,aatc:r.aiagenttotalcost||0}))}};`,ssrc:e,tpd:0,scc:s.aAIClientSourceCost||0,mxc:s.aAIClientMixerCost||0,encc:s.aAIClientEncoderCost||0,netc:s.aIClientNetsdkThrCost||0,qostc:s.aIClientQosThrCost||0,pacerc:s.aIClientPacerCost||0,uphr:s.aIClientUpRTTHalf||0},v),{agac:p,dnhr:h.downRTTHalf||0,tsd:h.vTotalCost||0,rcc:o.aAILinuxReceiveCost||0,nqc:o.aAILinuxNeteqCost||0,rscc:o.aAILinuxRemoteSourceCost||0,plmxc:o.aAILinuxPlayMixerCost||0,plc:o.aAILinuxPlayCost||0,dvd:0}))})}reportCumuAudioDelay(e,t){const{pub:n={},sub:r={},grtn:a={}}=t||{};let s=0;s=Object.keys(a).length?(n.vTotalCost||0)+(n.upRTTHalf||0)+(a.totalCost||0)+(r.downRTTHalf||0)+(r.vTotalCost||0):(n.vEncPlugCost||0)+((n.timestampRecv||0)-(n.timestamp||0))+(r.vJitterBufferDelay||0)+(r.vDecPlugCost||0);const o={};let c=0;for(let h=0;h<10;h++){const l=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${h}`,f=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${h}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${h}`;if(!a.hasOwnProperty(l))break;c+=a[l]||0,c+=a[f]||0,c+=a[v]||0,o[`_gnd${h}`]=`gnd[${h}]: {${this.data2String({gnirh:a[l]||0,gnbp:a[f]||0,gnpc:a[v]||0})}}`}this.log({evetid:10074,args:this.data2String(Ki(Ze({ssrc:e,tpd:s,scc:(n==null?void 0:n.aSourceCCost)||0,mxc:(n==null?void 0:n.aMixerCost)||0,encc:(n==null?void 0:n.aEncodeCCost)||0,netc:(n==null?void 0:n.netsdkThrCost)||0,qostc:(n==null?void 0:n.qosThrCost)||0,pacerc:(n==null?void 0:n.pacerCost)||0,uphr:(n==null?void 0:n.upRTTHalf)||0},o),{agac:c,dnhr:(r==null?void 0:r.downRTTHalf)||0,tsd:(r==null?void 0:r.vTotalCost)||0,rcc:0,nqc:0,rscc:0,plmxc:0,plc:0,device_delay:0,psdkt:0,pub_sdk_version:vo}))})}reportCumuVideoDelay(e,t){const{pub:n={},sub:r={},grtn:a={}}=t||{};let s=0;s=Object.keys(a).length?(n.vTotalCost||0)+(n.upRTTHalf||0)+(a.totalCost||0)+(r.downRTTHalf||0)+(r.vTotalCost||0):(n.vEncPlugCost||0)+((n.timestampRecv||0)-(n.timestamp||0))+(r.vJitterBufferDelay||0)+(r.vDecPlugCost||0);const o={};let c=0;for(let h=0;h<10;h++){const l=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${h}`,f=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${h}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${h}`;if(!a.hasOwnProperty(l))break;c+=a[l]||0,c+=a[f]||0,c+=a[v]||0,o[`_gnd${h}`]=`vgnd[${h}]: {${this.data2String({vgnirh:a[l]||0,vgnbp:a[f]||0,vgnpc:a[v]||0})}}`}this.log({evetid:10075,args:this.data2String(Ki(Ze({vssrc:e,valld:s,vcdc:(n==null?void 0:n.capDeviceCost)||0,vpec:(n==null?void 0:n.pushExtCost)||0,vcpc:(n==null?void 0:n.capPlugCost)||0,vptc:(n==null?void 0:n.prepThrCost)||0,vppc:(n==null?void 0:n.prepPlugCost)||0,vdptc:(n==null?void 0:n.dispThrCost)||0,vdppc:(n==null?void 0:n.dispPlugCost)||0,vetc:(n==null?void 0:n.vEncThrCost)||0,vepc:(n==null?void 0:n.vEncPlugCost)||0,vntc:(n==null?void 0:n.netsdkThrCost)||0,vqtc:(n==null?void 0:n.qosThrCost)||0,vvpac:(n==null?void 0:n.pacerCost)||0,vuphr:(n==null?void 0:n.upRTTHalf)||0},o),{vagac:c,vdnhr:(r==null?void 0:r.downRTTHalf)||0,vrc:(r==null?void 0:r.vAssemblyCost)||0,vstc:0,vfbc:r.vJitterBufferDelay||0,vdtc:(r==null?void 0:r.vDecPlugCost)||0,vdvpc:(r==null?void 0:r.vDecPlugCost)||0,vrtc:0,vrpc:0}))})}reportJoin(e,t,n=""){var r,a;const{start:s,rs:o=0,re:c=0}=t,h=Date.now()-s,l=c-o;let f=0;o&&(f=o-s);let v=0;c&&(v=c-o),this.log({evetid:10010,args:this.data2String({sesid:((r=this.authInfo)==null?void 0:r.sessionId)||"",joitm:h,rslt:e,gslbtm:0,dnstm:0,avcftm:0,gslbrslt:0,dnsrslt:0,avcfrslt:0,mode:2,jrtc:l,usrn:(a=this.authInfo)==null?void 0:a.userId,mgt:"cdn",cttc:f,iptc:v,ndn:1,gslbloc:1,ccag:0,ucag:0,cpg:0,upg:0,tid:n})})}reportJoinConnection(e){this.log({evetid:20002,args:this.data2String(Ze({transretrynum:0,ldnstc:0,tcptc:0,ssltc:0,url:""},e))})}reportLeave(e,t,n){this.log({evetid:10020,args:this.data2String({lvetm:e,rslt:t,tid:n})})}reportPublish(e,t,n,r,a,s,o,c,h,l,f,v){this.log({evetid:e?10032:10030,calid:n,tm:v,args:this.data2String({calid:n,url:t,isvl:r?1:0,isvs:a?1:0,isvss:s?1:0,isaudio:o?1:0,rslt:c,tid:"123",pubtm:Date.now()-f,pctid:h,pubtid:l,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(e,t,n,r,a,s,o,c,h){const l=Date.now();this.log({evetid:e?10033:10031,calid:t,args:this.data2String({calid:t,fpst:l-n,tckid:s,est:n,pctid:o,pubtid:c,totaltm:l-a,jorm:h===dn.JOIN_CHANNEL?1:0,cptc:0,sptc:r-n,iptc:0,ipc2fptc:0,dctc:0,patc:0})})}reportUnpublish(e,t,n,r){var a;this.log({evetid:10040,args:this.data2String({calid:e,unpubtm:t,rslt:n,tid:r,sesid:((a=this.authInfo)==null?void 0:a.sessionId)||""})})}reportSubscribe(e,t,n,r,a,s,o,c,h,l,f){this.log({evetid:10050,calid:e,rmtid:t,tm:f,args:this.data2String(Ze({calid:e,rmtid:t,isvl:n?1:0,isvs:r?1:0,isvss:a?1:0,isaudio:s?1:0,rslt:o,tid:c,subtm:h,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},l))})}reportSubscribeFirstPacket(e,t,n,r,a){this.log({evetid:e?10054:10051,calid:t,rmtid:n,args:this.data2String(Ze({calid:t,rmtid:n,tckid:r,cptc:0,iptc:0,ipc2fptc:0,dctc:0,patc:0},a))})}reportSubscribeFirstFrame(e,t,n,r,a){this.log({evetid:e?10055:10052,calid:t,rmtid:n,args:this.data2String(Ze({calid:t,rmtid:n,tckid:r},a))}),this.log({evetid:e?10058:10057,args:this.data2String(Ze({calid:t,rmtid:n,tckid:r},a))})}reportUnsubscribe(e,t,n,r,a){this.log({evetid:10060,calid:e,args:this.data2String({calid:e,rmtid:t,unsubtm:n,rslt:r,tid:a})})}reportMute(e,t,n){this.log({evetid:11030,args:this.data2String({calid:e,rmtid:"",enable:t?1:0,mt:n})})}reportRoleUpdate(e,t){this.log({evetid:11040,args:this.data2String({or:e||"",nr:t,ctm:Date.now(),rslt:0})})}reportRoleUpdateResult(e,t,n,r){this.log({evetid:11041,args:this.data2String({or:e||"",nr:t,ctm:n,rslt:r})})}reportVideoProfile(e){this.log({evetid:20074,args:this.data2String({pf:e,tckid:"sophon_camera_large"})})}reportScreenProfile(e){this.log({evetid:20074,args:this.data2String({pf:e,tckid:"sophon_screenshare"})})}reportError(e){this.log({evetid:10091,args:this.data2String({rslt:(e==null?void 0:e.code)||-1})})}reportWarning(e){this.log({evetid:10092,args:this.data2String({rslt:-1,errmsg:e})})}reportRoomServerEvent(e,t,n,r){this.log({evetid:20005,args:this.data2String({calid:"",rmtid:"",rt:e?0:1,dr:e?"s":"r",mt:t,ri:n,cs:1,srt:Date.now(),rspc:(r==null?void 0:r.code)||"",mc:JSON.stringify(r)})})}reportTranscodingError(e,t){this.log({evetid:10101,args:this.data2String({rslt:e,taskid:t})})}reportBye(e){var t;this.log({evetid:10093,args:this.data2String({rslt:e,sesid:((t=this.authInfo)==null?void 0:t.sessionId)||""})})}reportAudio(e,t,n){var r;this.log({evetid:80013,args:this.data2String({rslt:e?-1:0,adm:1,adt:0,adr:e?2:0,acms:t,adrpn:n})}),this.log({evetid:80014,args:this.data2String({sesid:((r=this.authInfo)==null?void 0:r.sessionId)||"",rslt:e?-1:0,adm:1,adt:0,adr:e?2:0,acms:t,adrpn:n})})}reportScreen(e,t){var n,r,a,s;this.log({evetid:90013,args:this.data2String({rslt:e?-1:0,vcms:t,vde:(n=e==null?void 0:e.code)!=null?n:-1,sesid:((r=this.authInfo)==null?void 0:r.sessionId)||""})}),this.log({evetid:90014,args:this.data2String({rslt:e?-1:0,vcms:t,vde:(a=e==null?void 0:e.code)!=null?a:-1,sesid:((s=this.authInfo)==null?void 0:s.sessionId)||""})})}reportScreenStop(e){this.log({evetid:90019,args:this.data2String({rslt:e?e.code||-1:0})}),this.log({evetid:90020,args:this.data2String({rslt:e?e.code||-1:0})})}reportSwitchCamera(e){var t;this.log({evetid:90025,args:this.data2String({rslt:0,td:e,sesid:((t=this.authInfo)==null?void 0:t.sessionId)||""})})}reportPublishProfile(e,t){this.log({evetid:10201,args:this.data2String(Ze({tckid:e},t))})}reportSDKCreated(e){this.log({evetid:70011,createtm:Date.now()-e,tm:e})}reportJoinInvoked(e){this.log({evetid:70012,jnnonce:e.nonce||"",jntoken:e.token||"",jntm:e.timestamp||""})}reportJoinResult(e){this.log({evetid:70013,rslt:e?e.code||-1:0,dnsrslt:0})}reportSTSResult(e,t){this.log({evetid:70014,rslt:e,asty:1,reqtm:Date.now()-t})}reportLeaveInvoked(){this.log({evetid:70015})}reportSEIMessage(e,t,n,r,a){this.log({evetid:40301,args:this.data2String({tm:Date.now(),sei_pt:e,sei_len:t,sei_rep:n,sei_delay:r,sei_key:a})})}reportConnectionLatencyEvent(e,t,n,r,a,s,o=!1){const c={ageniid:this.getCustomField("ageniid")},h=Ze({tm:a||Date.now(),ntptm:s||this.ntpClock.now(),stage:e,status:t,calid:n,tckid:r,cltp:1,http:o?1:0},c);this.log({evetid:12001,args:this.data2String(h)})}log(e){e&&(e.tm=e.tm||new Date().getTime(),Re.debug("[ConsoleLogger]","log",e),this.logClient.sendReport(e))}data2String(e){let t="";for(let n in e)t.length&&(t+="&"),t+=n.startsWith("_")?e[n]:`${n}=${e[n]}`;return t}}const Eh=class ta extends Kt{constructor(e){super(),V(this,"ws"),V(this,"socketStatus",0),V(this,"wsUrl",""),V(this,"lastConnectStartTime",0),V(this,"connectRetryMinTimeGap",5e3),V(this,"shouldReconnect",!0),V(this,"connectRetryCount",0),V(this,"gotErr",!1),V(this,"closedByInvoke",!0),V(this,"isReconnecting",!1),V(this,"networkAvailableChecked",!0),V(this,"reconnectTimeoutId",0),e&&(this.connectRetryMinTimeGap=e),this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return!(!this.ws||this.socketStatus!==2)&&(this.ws.send(JSON.stringify(e)),!0)}close(){this.closedByInvoke=!0,this.uninitWebsocket()}markShouldReconnect(e){this.shouldReconnect=e}reconnect(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.emit("onWillReconnect"),this.shouldReconnect?(this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()):this.emit("onConnectFail")}onOpen(e){Re.info(`[${ta.logName}]`,"onOpen"),this.socketStatus=2,this.connectRetryCount=0,this.shouldReconnect=!0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.socketStatus!==2&&kt.isNetworkAvailable().then(t=>{t&&console.error(ta.logName,"onError, Network is available, token may be invalid")})}onClose(e){return le(this,null,function*(){if(this.closedByInvoke)this.socketStatus=0;else{if(Re.info(`[${ta.logName}]`,`onClose, code: ${e.code}, reason: ${e.reason}, status: ${status}, retryCount: ${this.connectRetryCount}`),(yield kt.isNetworkAvailable())&&!this.networkAvailableChecked)return this.reconnect(),void(this.networkAvailableChecked=!0);if(this.connectRetryCount||this.emit("onNetworkError"),!this.reconnectTimeoutId){this.connectRetryCount+=1;const t=Date.now()-this.lastConnectStartTime;t>=this.connectRetryMinTimeGap?this.reconnect():this.reconnectTimeoutId=window.setTimeout(()=>{this.reconnect()},this.connectRetryMinTimeGap-Math.max(0,t))}this.socketStatus=0,this.emit("onClose",e)}})}initWebSocket(){this.uninitWebsocket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebsocket(){this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=void 0,this.socketStatus=0)}};V(Eh,"logName","Socket");let fg=Eh;const Rh=class ln extends Kt{constructor(e,t,n,r,a,s){super(),V(this,"authInfo"),V(this,"userName"),V(this,"channelProfile"),V(this,"clientRole"),V(this,"slsReporter"),V(this,"wsClient"),V(this,"packageCreator"),V(this,"keepAliveTimer",0),V(this,"lastKeepAliveResponseTime",0),V(this,"maxConnectRetryDuration",90),V(this,"packageCache",new Map),V(this,"isFirstConnect",!0),V(this,"aliveChecker",0),V(this,"reconnectData"),V(this,"joinChannelExtraData"),this.authInfo=e,this.userName=t,this.packageCreator=new Zo(e,t),this.channelProfile=n,this.clientRole=r,this.slsReporter=a,s&&(this.maxConnectRetryDuration=s),this.wsClient=new fg,this.wsClient.on("onOpen",this.onOpen.bind(this)),this.wsClient.on("onMessage",this.onMessage.bind(this)),this.wsClient.on("onError",this.onError.bind(this)),this.wsClient.on("onClose",this.onClose.bind(this)),this.wsClient.on("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.on("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.on("onNetworkError",this.onNetworkError.bind(this)),this.wsClient.on("onWillReconnect",this.onWillReconnect.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}get retryCount(){return this.wsClient.connectRetryCount}destroy(){this.lastKeepAliveResponseTime=0,this.close()}start(e,t){this.joinChannelExtraData=t,this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreator.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreator.createLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreator.createStatusPackage(e);this.sendPackage(t)}publish(e){const t=e,{l1ip:n}=t,r=Bn(t,["l1ip"]);let a=this.packageCreator.createPublishPackage();a.data.users=[],a.data.l1ip=n,r.subscribe.signal=this.wsClient.connectUrl;const{tracks:s,resume:o}=r;let c="7.2.4";c&&(c=c.split("-")[0]),s.forEach(h=>{const{codec:l,ssrc:f}=h;h.userdata=JSON.stringify({sdk_version:c,codec:l}),h.ssrc=`${f}`,o&&(h.attr={reason:"reconnect"})}),a.data.users.push(r),this.sendPackage(a)}roleUpdate(e){let t=this.packageCreator.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreator.createRefreshUrlPackage();t.data=Ze(Ki(Ze({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreator.refreshAuthInfo(e)}close(){Re.info(`[${ln.logName}] close`),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen.bind(this)),this.wsClient.off("onMessage",this.onMessage.bind(this)),this.wsClient.off("onError",this.onError.bind(this)),this.wsClient.off("onClose",this.onClose.bind(this)),this.wsClient.off("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.off("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.off("onReconnectStart"),this.wsClient.off("onReconnectFail"),this.wsClient.close()}sendPackage(e){[Ht.KEEPALIVE,Ht.RECONNECT,Ht.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==Ht.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(Re.info(`[${ln.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreator.createJoinPackage(this.joinChannelExtraData);e.data.configure={channelprofile:this.channelProfile},this.channelProfile!==ki.AliRtcSdkInteractiveLive&&this.channelProfile!==ki.AliRtcSdkInteractiveWithLowLatencyLive||(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreator.createReconnectPackage(this.reconnectData);this.sendPackage(e)}}onMessage(e){try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t),t!=null&&t.msgtype&&(t==null?void 0:t.msgtype)!==Ht.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){Re.warn(`[${ln.logName}] onMessage err`,t,e)}}onError(e){Re.warn(`[${ln.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){Re.warn(`[${ln.logName}] onConnectFail`);const e=new Le(Ne.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){Re.warn(`[${ln.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){Re.warn(`[${ln.logName}] onNetworkError`);const e=new Le(Ne.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){Re.info(`[${ln.logName}] onClose`,e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.lastKeepAliveResponseTime=Date.now(),this.checkAlive()}onWillReconnect(){this.lastKeepAliveResponseTime||(this.lastKeepAliveResponseTime=Date.now()),Date.now()-this.lastKeepAliveResponseTime>1e3*this.maxConnectRetryDuration&&this.wsClient.markShouldReconnect(!1)}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new Le(Ne.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{Re.info(`[${ln.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},15e3)}onRecvMessage(e){switch(e.msgtype!==Ht.KEEPALIVE&&Re.info(`[${ln.logName}] recv msg: ${e.msgtype}`),e.msgtype){case Ht.JOINCHANNEL:this.onJoinResult(e);break;case Ht.KEEPALIVE:this.onKeepAliveRsp();break;case Ht.PUBLISH:this.onPublishResult(e);break;case Ht.NOTIFYJOIN:this.onNotifyJoin(e);break;case Ht.NOTIFYSTATUS:this.onNotifyStatus(e);break;case Ht.LEAVECHANNEL:this.onLeaveResult(e);break;case Ht.NOTIFYLEAVE:this.onNotifyLeave(e);break;case Ht.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case Ht.STATUSREPORT:this.onStatusReport(e);break;case Ht.BYE:this.onBye(e);break;case Ht.ROLEUPDATE:this.onRoleUpdateResult(e);break;case Ht.REFRESHURL:this.onRefreshUrlResult(e);break;case Ht.RECONNECT:this.onReconnectResult(e);break;default:this.onUnknownMessage(e)}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new Le(Ne.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}};V(Rh,"logName","RSMessageCenter");let mg=Rh;var gg=Object.defineProperty,vg=Object.getOwnPropertyDescriptor,Ka=(i,e,t,n)=>{for(var r,a=vg(e,t),s=i.length-1;s>=0;s--)(r=i[s])&&(a=r(e,t,a)||a);return a&&gg(e,t,a),a},Mi;const us=(Mi=class extends Kt{constructor(i,e,t,n=qi.prod){super(),V(this,"messageCenter"),V(this,"authInfo"),V(this,"userName"),V(this,"channelProfile"),V(this,"clientRole"),V(this,"slsReporter"),V(this,"reconnectData"),V(this,"roomServerUri",""),this.channelProfile=i,this.clientRole=e,this.slsReporter=t,this.reconnectData={role:{channelprofile:i,clientrole:e}};const r=n===qi.pre?Vn.pre:Vn.prod;this.roomServerUri=`wss://${r}/roomserver/v1/ws`}updateReconnectData(i){var e;this.reconnectData=i,(e=this.messageCenter)==null||e.updateReconnectData(this.reconnectData)}reset(){Re.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.destroy(),this.messageCenter=void 0),this.authInfo=void 0}join(i,e,t,n){return le(this,null,function*(){return new Promise((r,a)=>{const s={};this.authInfo=i,this.userName=e,this.messageCenter=new mg(i,e,this.channelProfile,this.clientRole,this.slsReporter,t),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",c=>{var h,l,f;if(Re.info(`[${Mi.logName}]`,"join result: ",c),s.taskretrynum=((h=this.messageCenter)==null?void 0:h.retryCount)||0,c.code==200){(l=this.messageCenter)==null||l.sendPkgCache(),(f=this.messageCenter)==null||f.startKeepAlive();let v=c.data;v.tid=c.tid,v.users=c.data.users,v.timestamp=c.timestamp,s.est&&(s.joinconnecttc=Date.now()-s.est),this.slsReporter.reportJoinConnection(s),r(v)}else this.reset(),a(this.handleSignalError(c.code,c.reason,Ne.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),a(new Le(Ne.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),Re.info(`[${Mi.logName}]`,"start ws connecting roomserver and auto join when connected");const o={appid:this.authInfo.appId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:Ai()};i.role&&(o.tokenrole=i.role),s.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+kt.queryingParam(o),n)})})}leave(){return Re.info("[roomsig] leave .."),new Promise((i,e)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(t,n)=>{Re.info(`[${Mi.logName}]`,"recv leave response "+t),t===200?(this.updateReconnectData(),this.reset(),i({tid:n})):e(this.handleSignalError(t,"leave error"))}),Re.info(`[${Mi.logName}]`,"send leave request"),this.messageCenter.leave()):(Re.info(`[${Mi.logName}]`,"no message center, ok to leave"),i({tid:""}))})}publish(i){return new Promise((e,t)=>{var n;this.messageCenter?(this.messageCenter.once("onPublishResult",(r,a,s)=>{Re.info(`[${Mi.logName}]`,"recv pubish response "+r),r===200?(this.updateReconnectData(Ki(Ze({},this.reconnectData),{publish:{users:[i]}})),e({tid:a})):t(this.handleSignalError(r,`publish error, ${s}`))}),this.authInfo&&(i.sessionid=(n=this.authInfo.sessionId)!=null?n:""),i.callid||(i.callid=Ai()),Re.info(`[${Mi.logName}]`,"assign callid "+i.callid+" and send publish request"),this.messageCenter.publish(i)):t(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(i){return new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onRoleUpdateResult",(n,r,a)=>{var s,o;Re.info(`[${Mi.logName}]`,"recv role update response "+n),n===200?((o=(s=this.reconnectData)==null?void 0:s.role)!=null&&o.clientrole&&(this.reconnectData.role.clientrole=i,this.updateReconnectData(this.reconnectData)),e({tid:r})):t(this.handleSignalError(n,`role update error, ${a}`))}),this.messageCenter.roleUpdate(i)):t(this.handleSignalError(-1,"role update error, no message center"))})}setChannelProfile(i){this.channelProfile=i}refreshUrl(i){return Re.info(`[${Mi.logName}]`,"refreshUrl .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onRefreshUrlResult",n=>{const{code:r,description:a,data:s={}}=n||{};Re.info("recv refresh url response "+r),r===200?e(s):t(this.handleSignalError(r,`refresh url error, ${a}`))}),Re.info("send refresh url request"),this.messageCenter.refreshUrl(i)):t(this.handleSignalError(-1,"refresh url error, no message center"))})}reportStatus(i){return Re.info(`[${Mi.logName}]`,"reportStatus "+i),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(n,r)=>{n===200?e():t(new Le(n,r))}),this.messageCenter.reportStatus(i)):t(new Le(-1,"No messageCenter"))})}handleSignalError(i,e,t=Ne.ERR_INNER){return new Le(t,`signal error: code - ${i}; description - ${e}`)}refreshAuthInfo(i){return le(this,null,function*(){var e;this.authInfo&&(this.authInfo=i,(e=this.messageCenter)==null||e.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var i,e,t,n,r,a,s,o,c,h,l,f,v;(i=this.messageCenter)==null||i.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(e=this.messageCenter)==null||e.on("onNotifyJoin",p=>{this.emit("onNotifyJoin",p)}),(t=this.messageCenter)==null||t.on("onNotifyStatus",p=>{this.emit("onNotifyStatus",p)}),(n=this.messageCenter)==null||n.on("onNotifyLeave",p=>{this.emit("onNotifyLeave",p)}),(r=this.messageCenter)==null||r.on("onNotifyPublish",p=>{this.emit("onNotifyPublish",p)}),(a=this.messageCenter)==null||a.on("onBye",(p,_)=>{this.emit("onBye",p,_)}),(s=this.messageCenter)==null||s.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(o=this.messageCenter)==null||o.on("onReconnectSuccess",p=>{this.emit("onReconnectSuccess",p)}),(c=this.messageCenter)==null||c.on("onReconnectFail",p=>{this.emit("onReconnectFail",p)}),(h=this.messageCenter)==null||h.on("onConnectFail",p=>{this.emit("onConnectFail",p),this.reset()}),(l=this.messageCenter)==null||l.on("onNetworkError",p=>{this.emit("onNetworkError",p)}),(f=this.messageCenter)==null||f.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")}),(v=this.messageCenter)==null||v.on("onUnknownMessage",p=>{this.emit("onUnknownMessage",p)})}},V(Mi,"logName","RoomServerSignaling"),Mi);Ka([ge()],us.prototype,"join"),Ka([ge()],us.prototype,"publish"),Ka([ge()],us.prototype,"roleUpdate");let _g=us;var Sg=Object.defineProperty,bg=Object.getOwnPropertyDescriptor;class qa extends Kt{constructor(e,t,n,r=qi.prod){super(),V(this,"signaling"),V(this,"authInfo"),V(this,"userName"),V(this,"channelProfile"),V(this,"clientRole"),V(this,"env",qi.prod),V(this,"maxSignalingReconnectDuration"),V(this,"slsReporter"),this.channelProfile=e,this.clientRole=t,this.env=r,this.slsReporter=n}reset(){var e;Re.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.signaling=void 0,this.authInfo=void 0}join(e,t=e.userId,n,r,a){return this.maxSignalingReconnectDuration=n,this.userName=t,new Promise((s,o)=>{this.signaling?o(new Le(Ne.ERR_JOIN_ALREADY_JOINED,"already joined")):(Re.info("[signalingmanager] create signaling"),this.signaling=new _g(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),r&&(r.rs=Date.now()),this.signaling.join(e,t,n,a).then(c=>{this.authInfo=e,r&&(r.re=Date.now()),s(c)}).catch(c=>{this.reset(),o(c)}))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxSignalingReconnectDuration)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(n=>{this.reset(),e(n)}).catch(n=>{t(n)}):e({tid:""})})}publish(e){return new Promise((t,n)=>{var r;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(r=this.userName)!=null?r:this.authInfo.userId,this.signaling.publish(e).then(a=>{t(a)}).catch(a=>{n(a)})):n(new Le(Ne.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,n)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(r=>{n(r)}):n(new Le(-1,"no signaling"))})}setClientRole(e){return le(this,null,function*(){const t=this.clientRole;if(!this.signaling)return void(this.clientRole=e);const n=Date.now();try{const r=yield this.signaling.roleUpdate(e);return this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-n,0),r}catch(r){this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-n,r.code||-1)}})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new Le(Ne.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return le(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=Ze(Ze({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo))}catch(n){throw n}})}initSignaling(){var e,t,n,r,a,s,o,c,h,l,f,v,p,_;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(n=this.signaling)==null||n.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(r=this.signaling)==null||r.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(a=this.signaling)==null||a.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(s=this.signaling)==null||s.on("onBye",this.onBye.bind(this)),(o=this.signaling)==null||o.on("onReconnectStart",this.onReconnectStart.bind(this)),(c=this.signaling)==null||c.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(h=this.signaling)==null||h.on("onReconnectFail",this.onReconnectFail.bind(this)),(l=this.signaling)==null||l.on("onConnectFail",this.onConnectFail.bind(this)),(f=this.signaling)==null||f.on("onNetworkError",this.onNetworkError.bind(this)),(v=this.signaling)==null||v.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(p=this.signaling)==null||p.on("onError",this.onError.bind(this)),(_=this.signaling)==null||_.on("onUnknownMessage",this.onUnknownMessage.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}}V(qa,"logName","SignalingManager"),((i,e,t,n)=>{for(var r,a=bg(e,t),s=i.length-1;s>=0;s--)(r=i[s])&&(a=r(e,t,a)||a);a&&Sg(e,t,a)})([ge(ke)],qa.prototype,"publish");class yg{constructor(e){V(this,"taskProfile"),V(this,"encodeParam"),V(this,"users",[]),V(this,"backgroundColor",0),V(this,"backgrounds",[]),V(this,"watermarks",[]),V(this,"clockWidgets",[]),V(this,"cropMode"),V(this,"mediaProcessMode"),this.taskProfile=e}}class Eg{constructor(e,t,n){V(this,"userId"),V(this,"streamType"),V(this,"sourceType"),this.userId=e,this.streamType=t,this.sourceType=n}}class Rg{constructor(e,t,n,r=0,a=16777215,s=cs.NOTO_SERIF_CJKSC_REGULAR){V(this,"x"),V(this,"y"),V(this,"fontSize"),V(this,"zOrder"),V(this,"fontColor"),V(this,"fontType"),this.x=e,this.y=t,this.fontSize=n,this.zOrder=r,this.fontColor=a,this.fontType=s}toJson(e,t){return{x:Hi(this.x,e),y:Hi(this.y,t),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Wa(this.fontColor),zorder:this.zOrder}}}var Th=(i=>(i[i.NOT_DISPLAY=0]="NOT_DISPLAY",i[i.ALWAYS=1]="ALWAYS",i[i.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",i))(Th||{});class Ah{constructor(e,t,n,r,a,s=0,o=1,c=1){V(this,"url"),V(this,"x"),V(this,"y"),V(this,"width"),V(this,"height"),V(this,"alpha"),V(this,"display",1),V(this,"zOrder"),this.url=e,this.x=t,this.y=n,this.width=r,this.height=a,this.zOrder=s,this.alpha=o,this.display=c}toJson(e,t){return{url:this.url,alpha:this.alpha,display:this.display,x:Hi(this.x,e),y:Hi(this.y,t),width:Hi(this.width,e),height:Hi(this.height,t),zorder:this.zOrder}}}V(Ah,"DisplayType",Th);class Tg{constructor(e,t,n,r,a=0,s=16777215,o=cs.NOTO_SERIF_CJKSC_REGULAR){V(this,"text"),V(this,"x"),V(this,"y"),V(this,"fontSize"),V(this,"zOrder"),V(this,"fontColor"),V(this,"fontType"),this.text=e,this.x=t,this.y=n,this.fontSize=r,this.zOrder=a,this.fontColor=s,this.fontType=o}toJson(e,t){return{text:this.text,x:Hi(this.x,e),y:Hi(this.y,t),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Wa(this.fontColor),zorder:this.zOrder}}}class Ag{constructor(e,t,n,r,a,s=0,o){V(this,"userId"),V(this,"x"),V(this,"y"),V(this,"width"),V(this,"height"),V(this,"zOrder"),V(this,"sourceType"),V(this,"segmentType",as.LiveTranscodingNoBody),V(this,"images",[]),V(this,"texts",[]),this.userId=typeof e=="number"?e.toString():e,this.x=t,this.y=n,this.width=r,this.height=a,this.zOrder=s,o&&(this.sourceType=o)}toJson(e,t,n,r){const a={paneid:e,majorpane:0,x:Hi(this.x,t),y:Hi(this.y,n),width:Hi(this.width,t),height:Hi(this.height,n),zorder:this.zOrder,userid:this.userId,images:this.images.map(s=>s.toJson(t,n)),texts:this.texts.map(s=>s.toJson(t,n))};return this.sourceType&&Co[this.sourceType]?a.sourcetype=Co[this.sourceType]:a.sourcetype=Co[Ao.LiveTranscodingCamera],this.segmentType&&r===za.LiveTranscodingVirtualBackground?a.segmenttype=this.segmentType:a.segmenttype=as.LiveTranscodingNoBody,a}}class Cg{constructor(e){V(this,"_updateables"),V(this,"_useWebworker"),V(this,"_inited"),V(this,"_active"),V(this,"_previousRAFTime"),V(this,"_previousWorkerTime"),V(this,"_webWorkerString"),V(this,"_webWorker"),V(this,"_intervalThreshold"),V(this,"_rafId"),this._updateables=[],this._useWebworker=!1,this._inited=!1,this._active=!1,this._previousRAFTime=void 0,this._previousWorkerTime=void 0,this._intervalThreshold=e&&e>0&&e<=60?1/e:.1,this._webWorkerString=`
          var running = false;
          function tick(){
              postMessage(Date.now());
              if (running){
                  setTimeout(tick, ${Math.floor(1e3*this._intervalThreshold)});
              }
          }
          self.addEventListener('message',function(msg){
              var data = msg.data;
              if (data === 'start'){
                  running = true;
                  tick();
              }
              if (data === 'stop') running = false;
          });`,this._webWorker=void 0}_initWebWorker(){window.URL=window.URL||window.webkitURL;let e=new Blob([this._webWorkerString],{type:"application/javascript"});this._webWorker=new Worker(URL.createObjectURL(e)),this._webWorker.onmessage=t=>{let n=t.data;this._updateWorkerTime(n)}}_lostVisibility(){var e;this._previousWorkerTime=Date.now(),this._useWebworker=!0,this._webWorker||this._initWebWorker(),this._active&&((e=this._webWorker)==null||e.postMessage("start"))}_gainedVisibility(){this._useWebworker=!1,this._previousRAFTime=void 0,this._webWorker&&this._webWorker.postMessage("stop"),this._active&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)))}_init(){if(window.Worker){if(document.hidden===void 0)return window.addEventListener("focus",this._gainedVisibility.bind(this)),void window.addEventListener("blur",this._lostVisibility.bind(this));document.addEventListener("visibilitychange",()=>{document.hidden===!0?this._lostVisibility():this._gainedVisibility()},!1)}}_updateWorkerTime(e){let t=(e-(this._previousWorkerTime||0))/1e3;t>this._intervalThreshold&&(this._update(t),this._previousWorkerTime=e)}_updateRAFTime(e){this._previousRAFTime===void 0&&(this._previousRAFTime=e);let t=(e-this._previousRAFTime)/1e3;t>this._intervalThreshold&&(this._update(t),this._previousRAFTime=e),!this._useWebworker&&this._active?this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)):this._rafId=0}_update(e){for(let t=0;t<this._updateables.length;t++)this._updateables[t]._update(typeof e=="number"?e:parseFloat(e))}register(e){this._updateables.push(e),this._inited===!1&&(this._inited=!0,this._init()),this._active===!1&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)),this._active=!0)}unregister(e){const t=this._updateables.indexOf(e);t!==-1&&this._updateables.splice(t,1),this._updateables.length===0&&(this._active=!1,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=0),this._useWebworker&&this._webWorker&&this._webWorker.postMessage("stop"))}}class wg extends jn{constructor(e,t=10){super("AliRtcImageHolder"),V(this,"url"),V(this,"image"),V(this,"canvas"),V(this,"mediaStream"),V(this,"updateableManager"),V(this,"updateable"),V(this,"hasVideoTrack",!1),this.url=e,this.canvas=document.createElement("canvas"),this.canvas.width=1280,this.canvas.height=720,this.drawImageToCanvas(),this.updateableManager=new Cg(t)}get initOptions(){return{imageUrl:""}}setOptions(e){e.imageUrl&&(this.options=e,e.imageUrl!==this.url&&this.drawImageToCanvas())}drawImageToCanvas(){return le(this,null,function*(){if(!this.url)return;const e=this.canvas.getContext("2d"),t=document.createElement("img");let n;this.image=t,t.crossOrigin="anonymous",t.src=this.url;const{width:r,height:a}=yield new Promise(s=>{t.onload=()=>{n&&clearTimeout(n),s({width:t.width||16,height:t.height||16})},t.onerror=()=>{n&&clearTimeout(n),s({width:16,height:16})},n=setTimeout(()=>{s({width:16,height:16})},5e3)});this.canvas.width=r,this.canvas.height=a,e.drawImage(t,0,0,r,a)})}start(){return le(this,null,function*(){var e;if(!this.url)throw new Error("no image url founded");if(!this.canvas)throw new Error("get canvas error");const t=this.canvas.captureStream(25),n=this.canvas.getContext("2d");return this.image&&this.image.width&&n.drawImage(this.image,0,0,this.image.width,this.image.height),this.mediaStream=t,n.fillStyle="transparent",this.updateable={_update:()=>{n.fillRect(0,0,1,1)}},this.updateableManager.register(this.updateable),(e=t.getVideoTracks())==null?void 0:e[0]})}stop(){var e,t;this.updateable&&(this.updateableManager.unregister(this.updateable),this.updateable=null),(t=(e=this.mediaStream)==null?void 0:e.getVideoTracks()[0])==null||t.stop(),this.mediaStream=void 0}isSupported(){return!0}shouldUpdate(e){return this.hasVideoTrack===!!e.originVideoTrack}process(e){return le(this,null,function*(){if(this.hasVideoTrack=!!e.originVideoTrack,e.originVideoTrack){const n=e.currentVideoTrack;return n&&n.id===e.originVideoTrack.id||e.updateVideoTrack(e.originVideoTrack),void this.stop()}const t=yield this.start();e.updateVideoTrack(t)})}}class wo{static checkString(e){return typeof e=="string"}static checkNumber(e){return typeof e=="number"}static checkHtmlVideoElement(e){return e&&e.nodeName==="VIDEO"}static checkHtmlAudioElement(e){return e&&e.nodeName==="AUDIO"}static checkAuthInfo(e){return e?e.appId?e.channelId?wo.checkString(e.channelId)?e.userId?wo.checkString(e.userId)?e.timestamp?wo.checkNumber(e.timestamp)?e.token?null:new Le(Ne.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no token founded"):new Le(Ne.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"timestamp is not number"):new Le(Ne.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no timestamp founded"):new Le(Ne.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"userId is not string"):new Le(Ne.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no userId founded"):new Le(Ne.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"channelId is not string"):new Le(Ne.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no channelId founded"):new Le(Ne.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no appId founded"):new Le(Ne.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no authInfo founded")}static checkMediaStreamTrack(e){return e instanceof MediaStreamTrack}static checkVideoEncoderConfiguration(e){return e&&(e.width||e.height||e.frameRate||e.bitrateMax)}}var Mg=Object.defineProperty,xg=Object.getOwnPropertyDescriptor,ze=(i,e,t,n)=>{for(var r,a=xg(e,t),s=i.length-1;s>=0;s--)(r=i[s])&&(a=r(e,t,a)||a);return a&&Mg(e,t,a),a};let kr;var qe;const Ge=(qe=class extends Kt{constructor(i){super(),V(this,"channelProfile"),V(this,"clientRole"),V(this,"signalingManager"),V(this,"bizControl"),V(this,"liveTranscoding"),V(this,"maxSignalingReconnectDuration"),V(this,"slsReporter"),V(this,"connectState",at.AliRtcConnectionStatusInit),V(this,"networkError",!1),V(this,"_audioOnlyMode",!1),V(this,"_authInfoWillExpireTimer",null),V(this,"_authInfoExpiredTimer",null),V(this,"_serverCheckAuthInfoTimestamp",null),V(this,"_localCheckAuthInfoTimestamp",null),V(this,"_proxyAiTid",null),V(this,"_agentParam",null),V(this,"sessionId"),this.config=i;const e=Date.now();Re.init(i==null?void 0:i.globalEnv),this.slsReporter=new pg(this,i==null?void 0:i.globalEnv),this.channelProfile=ki.AliRtcSdkCommunication,this.clientRole=un.AliRtcSdkLive,this.liveTranscoding=new sg(this.slsReporter),this.signalingManager=new qa(this.channelProfile,this.clientRole,this.slsReporter,(i==null?void 0:i.env)===qi.pre?qi.pre:qi.prod),this.addSignalingManagerListeners(),this.maxSignalingReconnectDuration=i==null?void 0:i.maxSignalingReconnectDuration,this.bizControl=new ri({slsReporter:this.slsReporter,signalingManager:this.signalingManager,parameter:i==null?void 0:i.parameter}),this.addBizControlListeners(),this.addPublisherListeners(),this.slsReporter.reportConnectionLatencyEvent(wi.CREATE_ENGINE,Bi.START,"","",e),this.slsReporter.reportConnectionLatencyEvent(wi.CREATE_ENGINE,Bi.END,"","",Date.now()),this.slsReporter.reportSDKCreated(e)}static getSdkVersion(){return vo}static setLogLevel(i){Re.setLogLevel(i)}static getInstance(i){return qe._instance||(St.AliRTS.ENV=(i==null?void 0:i.globalEnv)==="SEA"?"SEA":void 0,kr==null||kr.updateOptions({region:(i==null?void 0:i.globalEnv)==="SEA"?"sg":"cn"}),kr==null||kr.setReady(),qe._instance=new qe(i)),qe._instance}destroy(){return le(this,null,function*(){qe._instance=void 0,yield this.leaveChannel(),yield this.bizControl.clear(),Re.destroy()})}get channel(){return this.bizControl.channel}get userId(){return this.bizControl.userId}get remoteUsers(){return this.bizControl.remoteUsers}get publisher(){return this.bizControl.publisher}get publishAudioStream(){return this.publisher.publishStreams.audio}get isPublishing(){const{publisher:i}=this.bizControl;return!!i&&i.isPublishing}get currentRoleCanPublish(){return this.channelProfile===ki.AliRtcSdkCommunication||this.clientRole===un.AliRtcSdkInteractive}addPublisherListeners(){this.publisher.on(ai.Local,i=>{Re.event("[Publisher] Device Status Change",i),this.onLocalDeviceStatusChange(i)}),this.publisher.on(lr.VideoTrackEnded,()=>{Re.event("[Publisher] VideoTrack Ended"),this.emit("localDeviceException",_n.AliEngineLocalDeviceTypeCamera,Bt.AliEngineLocalDeviceExceptionTypeCameraInterrupt,"")}),this.publisher.on(lr.ScreenTrackEnded,()=>{Re.event("[Publisher] ScreenTrack Ended"),this.emit("localDeviceException",_n.AliEngineLocalDeviceTypeDisplay,Bt.AliEngineLocalDeviceExceptionTypeDisplayException,"")}),this.publisher.on(lr.AudioTrackEnded,()=>{Re.event("[Publisher] AudioTrack Ended"),this.emit("localDeviceException",_n.AliEngineLocalDeviceTypeMic,Bt.AliEngineLocalDeviceExceptionTypeMicInterrupt,"")}),this.publisher.on("localDeviceException",(i,e,t="")=>{this.emit("localDeviceException",i,e,t)}),this.publisher.on("audioPublishStateChanged",(i,e,t)=>{var n;this.emit("audioPublishStateChanged",i,e,t,(n=this.channel)!=null?n:"")}),this.publisher.on("videoPublishStateChanged",(i,e,t)=>{var n;this.emit("videoPublishStateChanged",i,e,t,(n=this.channel)!=null?n:"")}),this.publisher.on("dualStreamPublishStateChanged",(i,e,t)=>{var n;this.emit("dualStreamPublishStateChanged",i,e,t,(n=this.channel)!=null?n:"")}),this.publisher.on("screenPublishStateChanged",(i,e,t)=>{var n;this.emit("screenSharePublishStateChanged",i,e,t,(n=this.channel)!=null?n:"")}),this.publisher.on("dataPublishStateChanged",(i,e,t)=>{var n;this.emit("dataPublishStateChanged",i,e,t,(n=this.channel)!=null?n:"")})}occurError(i,e){Re.event(`[${qe.logName}]`,"Occur Error",i,e),this.emit("onOccurError",i,e),this.emit("occurError",i,e)}addBizControlListeners(){this.bizControl.rtsManager.on("disconnected",()=>le(this,null,function*(){Re.event(`[${qe.logName}]`,"RTS Disconnected"),(yield kt.isNetworkAvailable())?this.onNetworkRecovery():this.onNetworkError()})),this.bizControl.rtsManager.on("subscribeexceeds",()=>le(this,null,function*(){Re.event(`[${qe.logName}]`,"RTS SubscribeExceeds"),this.bizControl.rtsManager.clear(),yield this.resumePublishForNetworkRecovery(),yield this.resumeSubList()})),this.bizControl.rtsManager.on("seimessage",(i,e,t)=>le(this,null,function*(){const n=this.remoteUsers.find(r=>kt.removeQueryString(r.streamUrl)===kt.removeQueryString(i));if(n){try{this.emit("mediaExtensionMsgReceived",n.userId,t,e)}catch{}if(e===99)try{const r=JSON.parse(new TextDecoder().decode(t));if(n.audioSSRC&&this.slsReporter.reportCumuAudioDelay(n.audioSSRC,r),n.videoSSRC){const a=yield this.bizControl.rtsManager.getSubscribeVideoStats(i);(a==null?void 0:a.frameHeight)===16&&(a==null?void 0:a.frameWidth)===16||this.slsReporter.reportCumuVideoDelay(n.videoSSRC,r)}}catch{}}})),this.bizControl.on(ai.Remote,(i,e)=>{Re.event(`[${qe.logName}]`,"RemoteUser Device Status Change",i,e)}),this.bizControl.on("remoteUserJoin",(i,e)=>{this.emit("remoteUserOnLineNotify",i,e)}),this.bizControl.on("remoteTrackAvailableChange",(i,e,t)=>{this.emit("remoteTrackAvailableNotify",i,e,t)}),this.bizControl.on("audioSubscribeStateChanged",(i,e,t,n,r)=>{this.emit("audioSubscribeStateChanged",i,e,t,n,r)}),this.bizControl.on("videoSubscribeStateChanged",(i,e,t,n,r)=>{this.emit("videoSubscribeStateChanged",i,e,t,n,r)}),this.bizControl.on("screenSubscribeStateChanged",(i,e,t,n,r)=>{this.emit("screenShareSubscribeStateChanged",i,e,t,n,r)}),this.bizControl.on("dataSubscribeStateChanged",(i,e,t,n,r)=>{this.emit("dataSubscribeStateChanged",i,e,t,n,r)}),this.bizControl.on("userAudioMuted",(i,e)=>{this.emit("userAudioMuted",i,e)}),this.bizControl.on("userVideoMuted",(i,e)=>{this.emit("userVideoMuted",i,e)}),this.bizControl.on("userScreenMuted",(i,e)=>{this.emit("userScreenMuted",i,e)}),this.bizControl.on("audioVolume",i=>{this.emit("audioVolume",i)}),this.bizControl.on("remoteAudioAutoPlayFail",i=>{this.emit("remoteAudioAutoPlayFail",i)}),this.bizControl.on("remoteVideoAutoPlayFail",(i,e)=>{this.emit("remoteVideoAutoPlayFail",i,e)}),this.bizControl.on("remoteAudioPlayError",(i,e)=>{this.emit("remoteAudioPlayError",i,e)}),this.bizControl.on("remoteVideoPlayError",(i,e)=>{this.emit("remoteVideoPlayError",i,e)}),this.bizControl.on("rtcStats",i=>{this.emit("rtcStats",i)}),this.bizControl.on("rtcLocalAudioStats",i=>{this.emit("rtcLocalAudioStats",i)}),this.bizControl.on("rtcLocalVideoStats",i=>{this.emit("rtcLocalVideoStats",i)}),this.bizControl.on("rtcRemoteAudioStats",i=>{this.emit("rtcRemoteAudioStats",i)}),this.bizControl.on("rtcRemoteVideoStats",i=>{this.emit("rtcRemoteVideoStats",i)}),this.bizControl.on("remoteSubscribeError",(i,e)=>{this.occurError(i,e),this.slsReporter.reportError(i)}),this.bizControl.on("occurError",(i,e)=>{this.occurError(i,e),this.slsReporter.reportError(i)}),this.bizControl.on("remoteDataChannelMessage",(i,e)=>{this.emit("dataChannelMsg",i,e)}),this.bizControl.on("remoteUserSubscribedDataChannel",i=>{this.emit("remoteUserSubscribedDataChannel",i)}),this.bizControl.on("networkQuality",i=>{this.emit("networkQuality",i)})}addSignalingManagerListeners(){this.signalingManager.on("onKeepAliveRsp",()=>{this.networkError&&(Re.event("[Signaling] Receive KeepAlive Response",`networkError: ${this.networkError}`),this.onNetworkRecovery())}),this.signalingManager.on("onNotifyJoin",i=>{Re.event("[Signaling] Notify Join ",i),this.handleUsersJoin(i)}),this.signalingManager.on("onNotifyStatus",i=>{Re.event("[Signaling] Notify Status ",i),i.forEach(e=>{this.bizControl.updateRemoteUserDeviceStatus(e)})}),this.signalingManager.on("onNotifyLeave",i=>{Re.event("[Signaling] Notify Leave ",i),i.forEach(e=>le(this,null,function*(){yield this.bizControl.removeLeftUser(e),this.emit("remoteUserOffLineNotify",e.userid,e.leavecode)}))}),this.signalingManager.on("onBye",(i,e)=>{Re.event("[Signaling] Bye ",i,e),this.slsReporter.reportError({message:`reason: ${i}, description: ${e}`}),this.emit("bye",i),this.signalingManager.reset(),this.leaveChannel(),this.slsReporter.reportBye(i)}),this.signalingManager.on("onConnectFail",i=>{Re.event("[Signaling] Connect Failed ",i),this.onError(i),this.backToUnpublishStatus(),this.bizControl.leave(),this.signalingManager.reset(),this.connectState=at.AliRtcConnectionStatusFailed,this.emit("connectionStatusChange",at.AliRtcConnectionStatusFailed,Sn.AliRtcConnectionChangedNetworkInterrupted)}),this.signalingManager.on("onNetworkError",i=>{this.slsReporter.reportWarning("signaling network error"),Re.event("[Signaling] Network error ",i),this.onNetworkError()}),this.signalingManager.on("onAuthInvalid",()=>{Re.event("[Signaling] Auth Invalid")}),this.signalingManager.on("onReconnectStart",()=>{this.onNetworkError(),Re.event("[Signaling] Reconnect Start "),this.connectState=at.AliRtcConnectionStatusReconnecting,this.emit("connectionStatusChange",at.AliRtcConnectionStatusReconnecting,Sn.AliRtcConnectionSignalingConnecting)}),this.signalingManager.on("onReconnectSuccess",i=>{Re.event("[Signaling] Reconnect Success ",i),this.onNetworkRecovery(i)}),this.signalingManager.on("onReconnectFail",i=>{this.slsReporter.reportWarning("signaling reconnect fail: ${err.code}"),Re.event("[Signaling] Reconnect Failed ",i),i.code===403&&this.emit("authInfoExpired")}),this.signalingManager.on("onError",i=>{this.slsReporter.reportWarning("signaling error: ${err.message}"),Re.event("[Signaling] Error ",i),this.onError(i)}),this.signalingManager.on("onUnknownMessage",i=>{if(i.msgtype==="proxyai"&&i.tid===this._proxyAiTid){let e=i.data.retcode;e===200&&(e=0),this.emit("AIAgentResult",e,this._agentParam.action,i.data.body)}})}backToUnpublishStatus(){this.connectState=at.AliRtcConnectionStatusDisconnected,this.publisher.isPublishing&&this.publisher.clearPublishState(),this.networkError=!1}handleUsersJoin(i){i.forEach(e=>{this.bizControl.addUser(e,Ct.Join)})}onLocalDeviceStatusChange(i){Re.event(`[${qe.logName}]`,ai.Local,i),this.signalingManager.reportStatus(i).then(()=>{Re.debug("[signaling] reportStatus suc")}).catch(e=>{Re.error("[signaling] reportStatus failed",e)})}resumePublishForNetworkRecovery(){return le(this,null,function*(){try{yield this.publisher.resumePublish()}catch(i){const{code:e}=i;if(e===10205){let t=1;try{yield new Promise((n,r)=>{const a=setInterval(()=>le(this,null,function*(){t>1&&(clearInterval(a),r()),t+=1;try{yield this.publisher.resumePublish(),clearInterval(a),n()}catch(s){const{code:o}=s;o!==10205&&(clearInterval(a),r())}}),1e3)})}catch{}}throw i}})}onNetworkRecovery(i){return le(this,null,function*(){Re.event(qe.logName,"onNetworkRecovery",`rts isConnected: ${this.bizControl.rtsManager.isConnected}; rts isConnecting: ${this.bizControl.rtsManager.isConnecting}`,{users:i}),yield this.resumeSubList(i),this.networkError&&(this.networkError=!1,this.publisher.reportSelfDeviceStatus(),this.connectState=at.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",at.AliRtcConnectionStatusConnected,Sn.AliRtcConnectionSignalingHeartbeatAlive))})}resumeSubList(i){return le(this,null,function*(){if(i){const{joinList:e,leaveList:t,presentList:n}=this.bizControl.diffUsers(i);Re.info(`[${qe.logName}]`,"resumeSubList",{joinList:e,leaveList:t,presentList:n}),this.handleUsersJoin(e),t.forEach(r=>{Re.event(qe.logName,Nt.UserLeft,r.userid,r.reason),this.bizControl.onRemotePublishStateChange({userid:r.userid,displayname:"",callid:"",tracks:[]}),this.bizControl.removeLeftUser(r),this.emit("remoteUserOffLineNotify",r.userid,na.AliRtcUserOfflineQuit)}),n.forEach(r=>{this.bizControl.onRemotePublishStateChange(r)})}else for(let e=0;e<this.remoteUsers.length;e++){const t=this.remoteUsers[e];try{t.restore(),t.updateSubscribe(Ct.Resume)}catch{}}})}retrySubscribe(i){return le(this,null,function*(){const e=this.bizControl.getRemoteUser(i);if(!e)throw new Le(Ne.ERR_INNER,`no remote user(${i}) founded`);e.restore(),e.updateSubscribe(Ct.Retry)})}onNetworkError(){this.connectState===at.AliRtcConnectionStatusConnected&&(this.networkError||(this.connectState=at.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",at.AliRtcConnectionStatusDisconnected,Sn.AliRtcConnectionChangedNetworkInterrupted)),this.networkError=!0)}onError(i){this.slsReporter.reportError(i),Re.event(qe.logName,Nt.Error,i)}setEnableDualVideoStream(i,e){this.bizControl.setEnableDualVideoStream(i,e)}hadPushStream(i){if(!this.publisher||!i)throw new Le(Ne.ERR_INNER,"stream is not publishing")}getCurrentMicDeviceId(){return this.publisher.getCurrentMicDeviceId()}setChannelProfile(i){if(![at.AliRtcConnectionStatusInit,at.AliRtcConnectionStatusDisconnected,at.AliRtcConnectionStatusFailed].includes(this.connectState))throw new Le(Ne.ERR_INNER,"cannot set channel profile in call");this.channelProfile=i,this.channelProfile===ki.AliRtcSdkCommunication&&(this.clientRole=un.AliRtcSdkLive),this.signalingManager.setChannelProfile(i)}startDefaultDevices(){return le(this,null,function*(){if(!this.publisher)return;const{hasCamera:i,hasMicrophone:e,hasScreenShare:t}=this.publisher;if(!i&&!e&&!t){try{yield this.publisher.startDefaultCameraAndMic(this._audioOnlyMode)}catch(n){Re.warn(`[${qe.logName}]`,"startDefaultDevices failed",n.code,n.message),n instanceof Le&&this.occurError(n);const r=n.code;this.occurError(new Le(r>=Ne.ERR_CAMERA_OPEN_FAIL&&r<=Ne.ERR_CAMERA_NOT_AVAILABLE?Ne.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED:Ne.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED,`auto publish device failed, ${n.message||""}`))}yield this.publisher.previewAll()}})}startPublish(i){return le(this,null,function*(){try{yield this.publisher.startPublish(!1,i)}catch(e){const t=this.publisher.publishStreams||{},n=[];t!=null&&t.audio&&n.push(Ne.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),t!=null&&t.video&&n.push(Ne.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),n.forEach(r=>{this.occurError(new Le(r,`auto publish stream failed, ${e.message||""}`))})}})}setClientRole(i){return le(this,null,function*(){try{if(this.channelProfile===ki.AliRtcSdkCommunication)return;if(!Object.values(un).includes(i))throw new Le(Ne.ERR_INVALID_ARGUMENTS,`set client role error, role value(${i}) is invalid`);if(this.clientRole===i)return;this.slsReporter.reportRoleUpdate(this.clientRole,i),this.isInCall()?this.clientRole===un.AliRtcSdkInteractive?(this.publisher.isPublishing?yield this.publisher.unPublish():yield this.publisher.clearStream(),yield this.signalingManager.setClientRole(i)):(yield this.signalingManager.setClientRole(i),yield this.startDefaultDevices(),yield this.startPublish(dn.ROLE_CHANGE)):yield this.signalingManager.setClientRole(i),this.clientRole=i}catch(e){throw e.code===403&&this.emit("authInfoExpired"),e}})}getCurrentClientRole(){return this.clientRole}setAudioOnlyMode(i){if(this.isInCall())throw new Le(Ne.ERR_INNER,"can not change audioOnly mode in call");this._audioOnlyMode=i}setAudioRedEnabled(i){if(this.isInCall())throw new Le(Ne.ERR_INNER,"can not change audioRedEnabled in call");this.bizControl.setAudioRedEnabled(i)}setVideoCodec(i){this.bizControl.setVideoCodec(i)}setCheckAuthInfoTimer(i,e){const t=1e3*(i-e);this._authInfoExpiredTimer=window.setTimeout(()=>{this.emit("authInfoExpired")},t),this._authInfoWillExpireTimer=window.setTimeout(()=>{this.emit("authInfoWillExpire")},t-3e4),this._serverCheckAuthInfoTimestamp=e,this._localCheckAuthInfoTimestamp=+Date.now()/1e3}clearCheckAuthInfoTimer(){this._authInfoExpiredTimer&&window.clearTimeout(this._authInfoExpiredTimer),this._authInfoWillExpireTimer&&window.clearTimeout(this._authInfoWillExpireTimer)}joinChannel(i,e){return le(this,arguments,function*(t,n,r={}){const a=Date.now();let s,o=typeof n=="string"?n:n==null?void 0:n.userName;if(typeof t=="string")try{const l=JSON.parse(window.atob(t));s={appId:l.appid,channelId:l.channelid,userId:l.userid,timestamp:l.timestamp,nonce:l.nonce,token:l.token}}catch(l){throw new Le(Ne.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${l.message||""}`)}else s=t;o||(o=s.userId);const c={start:Date.now()};let h=wo.checkAuthInfo(s);if(at.AliRtcConnectionStatusInit!==this.connectState&&at.AliRtcConnectionStatusDisconnected!==this.connectState&&at.AliRtcConnectionStatusFailed!==this.connectState){const l=new Le(Ne.ERR_JOIN_ALREADY_JOINED,"already joined");throw this.connectState===at.AliRtcConnectionStatusConnecting&&(l.message="Repeated operation during login"),this.slsReporter.reportJoin(l.code,c,""),l}{if(h)throw this.connectState=at.AliRtcConnectionStatusFailed,this.slsReporter.reportJoin(h.code,c,""),this.slsReporter.reportJoinResult(h),h;s.sessionId=kt.createCallid("web"),this.sessionId=s.sessionId,this.slsReporter.start(s),this.slsReporter.reportConnectionLatencyEvent(wi.JOIN,Bi.START,"","",a),this.connectState=at.AliRtcConnectionStatusConnecting,this.emit("connectionStatusChange",at.AliRtcConnectionStatusConnecting,Sn.AliRtcConnectionSignalingConnecting),Re.setSessionID(s.appId,s.sessionId);const l=()=>le(this,null,function*(){var f,v;try{let m="Conference";typeof n=="object"&&n.capabilityProfile===os.Human&&(m="AIUser");const d=JSON.parse(this.getParameter());d.joinMode&&(m=d.joinMode);const u=new va(((f=this.config)==null?void 0:f.env)||qi.prod,s,m);if(u.result){const S=(p=u.result.config,_=Bl.EnableNonOnePcDefaultJoinMode,rr(p==null?void 0:p.data,_));u.result.useonepc&&S!==!1||(m=""),Re.info(`[${va.logName}]`,"got allocate result from localStorage",`joinMode: ${m}`,u.result.useonepc,S)}else Re.info(`[${va.logName}]`,"no allocate result in localStorage",`joinMode: ${m}`);m&&(r.joinmode=m);const b=Date.now(),y=yield this.signalingManager.join(s,o,this.maxSignalingReconnectDuration,c,r);y.l1ip?(Re.info("allocate l1 pub ip with mode",m,y.l1ip),this.bizControl.rtsManager.preferredPubL1Ip=y.l1ip):this.bizControl.rtsManager.preferredPubL1Ip=void 0,y.l1subip?(Re.info("allocate l1 sub ip with mode",m,y.l1subip),this.bizControl.rtsManager.preferredSubL1Ip=y.l1subip):this.bizControl.rtsManager.preferredSubL1Ip=void 0;const g=Date.now();this.connectState=at.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",at.AliRtcConnectionStatusConnected,Sn.AliRtcConnectionSignalingJoinRoomSuccess),this.bizControl.init(s,y,{capabilityProfile:typeof n=="object"?n.capabilityProfile:os.Default,robotUserId:typeof n=="object"?n.robotUserId:void 0}),this.setCheckAuthInfoTimer(s.timestamp,y.timestamp),this.liveTranscoding.setAuthInfo(s),this.slsReporter.reportJoin(0,c,y.tid),this.slsReporter.reportJoinResult(null),this.slsReporter.reportConnectionLatencyEvent(wi.JOIN,Bi.SEND_SIG,"","",b),this.slsReporter.reportConnectionLatencyEvent(wi.JOIN,Bi.RECV_RST,"","",g),this.slsReporter.reportConnectionLatencyEvent(wi.JOIN,Bi.END,"","")}catch(m){const d=(v=m.code)!=null?v:-1,u=m.reason||m.message||"";throw this.connectState=at.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",at.AliRtcConnectionStatusDisconnected,Sn.AliRtcConnectionSignalingJoinRoomFailure),this.slsReporter.reportJoin(d,c,""),this.slsReporter.reportJoinResult(m),new Le(d,u)}var p,_});this.currentRoleCanPublish?(yield Promise.all([l(),this.startDefaultDevices()]),yield this.startPublish(dn.JOIN_CHANNEL)):yield l(),this.publisher.reportSelfDeviceStatus(),this.remoteUsers.forEach(f=>{f.updateSubscribe(Ct.Join)})}})}joinAIChannel(i,e,t){return le(this,null,function*(){return this._proxyAiTid=Ai(),this._agentParam=t,this.joinChannel(i,e,{proxyai:{tid:this._proxyAiTid,region:t.region,proxydata:JSON.stringify({Region:t.region,Action:t.action,ActionParams:t.params})}})})}leaveChannel(){return le(this,null,function*(){var i;this.slsReporter.reportLeaveInvoked(),yield this.bizControl.leave();let e=new Date().getTime();if(at.AliRtcConnectionStatusConnected===this.connectState)try{let t;t=yield this.signalingManager.leave(),this.slsReporter.reportLeave(new Date().getTime()-e,0,(i=t==null?void 0:t.tid)!=null?i:"")}catch(t){this.slsReporter.reportLeave(new Date().getTime()-e,t.code,t.reason)}else this.slsReporter.reportLeave(0,0,"");this.sessionId=void 0,this.networkError=!1,this.connectState=at.AliRtcConnectionStatusDisconnected,this.clearCheckAuthInfoTimer(),this.liveTranscoding.clear(),this.slsReporter.stop(),this.signalingManager.reset(),Re.reportEnd()})}isInCall(){return this.connectState===at.AliRtcConnectionStatusConnected}refreshAuthInfo(i){return le(this,null,function*(){let e;if(typeof i=="string")try{const c=JSON.parse(window.atob(i));e={userId:c.userid,timestamp:c.timestamp,nonce:c.nonce,token:c.token}}catch(c){throw new Le(Ne.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${c.message||""}`)}else e=i;const{userId:t,nonce:n,timestamp:r,token:a,role:s}=e,o={userId:t,nonce:n,timestamp:r,token:a,role:s};try{yield this.signalingManager.refreshAuthInfo(o),this.bizControl.refreshAuthInfo(o),this.liveTranscoding.refreshAuthInfo(o),this.clearCheckAuthInfoTimer(),this._serverCheckAuthInfoTimestamp&&this._localCheckAuthInfoTimestamp&&e.timestamp&&this.setCheckAuthInfoTimer(e.timestamp,this._serverCheckAuthInfoTimestamp+(Date.now()-this._localCheckAuthInfoTimestamp))}catch(c){throw c}})}isAudioOnly(){return this._audioOnlyMode}publishLocalAudioStream(i){return le(this,null,function*(){this.publisher.setPublishLocalAudioStreamEnabled(i),this.connectState===at.AliRtcConnectionStatusConnected&&(i?this.publisher.hasMicrophone?yield this.publisher.updateStreams():yield this.startAudioCapture():yield this.publisher.publishUpdate())})}isLocalAudioStreamPublished(){var i;return(i=this.publisher.publishLocalAudioStreamEnabled)!=null?i:!0}setDefaultSubscribeAllRemoteAudioStreams(i){this.bizControl.setAutoSubAudio(i)}subscribeAllRemoteAudioStreams(i){this.bizControl.setWantSubAudio(i)}subscribeRemoteAudioStream(i,e){if(e&&!this.bizControl.isWantSubAudio)throw new Le(Ne.ERR_INVALID_ARGUMENTS,"subscribeAllRemoteAudioStreams(true) must be called first");this.bizControl.updateAudioWant(i,e)}resumeRemoteAudioStream(i){const e=this.bizControl.getRemoteUser(i);if(!e)throw new Le(Ne.ERR_INNER,`no remote user(${i}) founded`);e.resumeAudio()}stopRemoteAudioPlay(i){const e=this.bizControl.getRemoteUser(i);if(!e)throw new Le(Ne.ERR_INNER,`no remote user(${i}) founded`);e.stopPlayAudio()}publishLocalVideoStream(i){return le(this,null,function*(){this.publisher.setPublishLocalVideoStreamEnabled(i),this.connectState===at.AliRtcConnectionStatusConnected&&(i?this.publisher.hasCamera?yield this.publisher.updateStreams():yield this.enableLocalVideo():yield this.publisher.publishUpdate())})}isLocalVideoStreamPublished(){var i;return(i=this.publisher.publishLocalVideoStreamEnabled)!=null?i:!0}setRemoteDefaultVideoStreamType(i){[ti.AliRtcVideoStreamTypeHigh,ti.AliRtcVideoStreamTypeLow].includes(i)&&this.bizControl.setRemoteDefaultVideoStreamType(i)}setRemoteUserVideoStreamType(i,e){[ti.AliRtcVideoStreamTypeHigh,ti.AliRtcVideoStreamTypeLow].includes(e)&&this.bizControl.setRemoteUserVideoStreamType(i,e)}setDefaultSubscribeAllRemoteVideoStreams(i){this.bizControl.setAutoSubVideo(i),this.bizControl.setAutoSubScreen(i)}subscribeAllRemoteVideoStreams(i){this.bizControl.setWantSubVideo(i),this.bizControl.setWantSubScreen(i)}subscribeRemoteMediaStream(i,e,t,n){const r=this.bizControl.getRemoteUser(i);if(!r)throw new Le(Ne.ERR_INNER,`no remote user(${i}) founded`);!t||e!==ft.AliRtcVideoTrackScreen&&e!==ft.AliRtcVideoTrackBoth?r.setWantSubScreen(!1):r.setWantSubScreen(!0),!t||e!==ft.AliRtcVideoTrackCamera&&e!==ft.AliRtcVideoTrackBoth?r.setWantSubVideo(!1):r.setWantSubVideo(!0),r.setWantSubAudio(n),t||n?r.subscribe({video:t,audio:n},Ct.User):r.stopSubscribe({video:!0,audio:!0})}resumeRemoteMediaStream(i,e){const t=this.bizControl.getRemoteUser(i);t&&t.resumeVideo(e)}getOnlineRemoteUsers(){return this.bizControl.remoteUsers.map(i=>i.userId)}getUserInfo(i){var e;return(e=this.bizControl.getRemoteUser(i))==null?void 0:e.remoteUserInfo}isUserOnline(i){return!!this.bizControl.remoteUsers.find(e=>e.userId===i)}startScreenShare(i){return le(this,null,function*(){const e={video:!1,audio:!1},{audio:t=!1,videoTrack:n,audioTrack:r}=i||{};if(n||r){e.screen=!0;const a=new MediaStream;n&&a.addTrack(n),r&&a.addTrack(r),e.mediaStream=a}else e.screen=!t||{audio:!0};yield this.publisher.createLocalStream(e)})}stopScreenShare(){return le(this,null,function*(){this.publisher.stopLocalStream({screen:!0})})}setScreenShareConfiguration(i){return le(this,null,function*(){const{width:e,height:t}=i;if(e&&!isNaN(e)&&t&&!isNaN(t)&&e*t>9437184)throw new Le(Ne.ERR_INVALID_ARGUMENTS,"width * height must be less than 9437184");const n=i,{bitrate:r}=n,a=Bn(n,["bitrate"]),s=Ze({},a);r&&(s.maxBitrate=i.bitrate),yield this.publisher.setScreenProfile(s)})}setScreenShareContentHint(i){return le(this,null,function*(){i&&this.publisher.setScreenContentHint(i)})}publishLocalScreenShareStream(i,e){return le(this,null,function*(){this.publisher.setPublishLocalScreenStreamEnabled(i),this.connectState===at.AliRtcConnectionStatusConnected&&(i?this.publisher.hasScreenShare?yield this.publisher.updateStreams():yield this.startScreenShare(e):yield this.publisher.publishUpdate())})}isScreenSharePublished(){var i;return(i=this.publisher.publishLocalScreenStreamEnabled)!=null?i:!0}setAudioShareVolume(i){if(typeof i!="number")throw new Le(Ne.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({screen:Math.max(0,Math.min(i,400))/100})}enableAudioVolumeIndication(i){this.bizControl.enableAudioVolumeIndication(i)}muteLocalMic(i=!1){this.publisher.muteLocalMic(i),this.connectState===at.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()}muteRemoteAudioPlaying(i,e=!1){const t=this.bizControl.getRemoteUser(i);if(!t)throw new Le(Ne.ERR_INNER,`no remote user(${i}) founded`);t.setAudioMuted(e)}muteAllRemoteAudioPlaying(i=!1){this.bizControl.setAudioMuted(i)}startAudioCapture(i){return le(this,null,function*(){const e={audio:i||!0};yield this.publisher.createLocalStream(e)})}setAudioConstraints(i){return le(this,null,function*(){yield this.publisher.setMicrophoneConstraints(i)})}stopAudioCapture(){this.publisher.stopAudioCapture()}switchMicrophone(i,e){return le(this,null,function*(){if(yield this.publisher.setMicrophoneDeviceId(i),!this.publisher.audioCaptureDisabled){if(e)return void(yield this.publisher.createLocalStream({audio:!0,mediaStream:new MediaStream([e])}));yield this.publisher.createLocalStream({audio:{deviceId:i}})}})}setRecordingVolume(i){if(typeof i!="number")throw new Le(Ne.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({audio:Math.max(0,Math.min(i,400))/100})}setPlayoutVolume(i){if(typeof i!="number")throw new Le(Ne.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setPlayoutVolume(Math.max(0,Math.min(i,100))/100)}setRemoteAudioVolume(i,e){const t=this.bizControl.getRemoteUser(i);if(!t)throw new Le(Ne.ERR_INNER,`no remote user(${i}) founded`);if(typeof e!="number")throw new Le(Ne.ERR_INVALID_ARGUMENTS,"volume must be a number");t.setPlayoutVolume(Math.max(0,Math.min(e,100))/100)}setAudioProfile(i){return le(this,null,function*(){yield this.publisher.setAudioProfile(i)})}getAudioTrack(i){return le(this,null,function*(){if(!i)return this.publisher.audioTrack;const e=this.bizControl.getRemoteUser(i);return e==null?void 0:e.getAudioTrack})}setLocalViewConfig(i,e){return le(this,null,function*(){var t;if(this._audioOnlyMode)throw new Le(Ne.ERR_INNER,"Cannot set local view in audio only mode");(t=this.bizControl)==null||t.setLocalViewConfig(i,e),e===ft.AliRtcVideoTrackCamera&&this.publisher.hasCamera?yield this.startPreview():e===ft.AliRtcVideoTrackScreen&&this.publisher.hasScreenShare&&(yield this.startPreviewScreen())})}setCameraCapturerConfiguration(i){return le(this,null,function*(){const e=i,{cameraDirection:t,deviceId:n,bitrate:r,maxSendFrameRate:a}=e,s=Bn(e,["cameraDirection","deviceId","bitrate","maxSendFrameRate"]),o=Ze({},s);r&&(o.maxBitrate=r),a&&(o.maxSendFrameRate=a),Object.keys(o).length>0&&(yield this.publisher.setVideoProfile(o)),t!==void 0&&this.publisher.setCameraDirection(t),n&&this.publisher.setCameraDeviceId(n)})}setCameraCapturerContentHint(i){return le(this,null,function*(){i&&this.publisher.setVideoContentHint(i)})}enableLocalVideo(i=!0){return le(this,null,function*(){var e,t,n,r,a,s;if(this._audioOnlyMode)throw new Le(Ne.ERR_INNER,"Cannot enable local video in audio only mode");i?((e=this.publisher.publishStreams)!=null&&e.video&&((n=(t=this.publisher.publishStreams)==null?void 0:t.video)==null||n.disableVideo(),(s=(a=(r=this.publisher.publishStreams)==null?void 0:r.video)==null?void 0:a.videoTrack)==null||s.stop()),yield this.publisher.startCameraCapture()):yield this.publisher.stopCameraCapture()})}muteLocalCamera(i){return le(this,null,function*(){this.publisher.muteLocalCamera(i),this.connectState===at.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}muteLocalScreen(i){return le(this,null,function*(){this.publisher.muteLocalScreen(i),this.connectState===at.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}setRemoteViewConfig(i,e,t){this.bizControl.setRemoteViewConfig(e,i,t)}isCameraOn(){var i;return(i=this.publisher.hasCamera)!=null?i:!1}switchCamera(i,e){return le(this,null,function*(){var t;if(this._audioOnlyMode)throw new Le(Ne.ERR_INNER,"Cannot switch camera in audio only mode");const n={};if(i?(n.deviceId=i,this.slsReporter.reportSwitchCamera(i)):e||(n.cameraDirection=this.publisher.cameraDirection==="environment"?mo.CAMERA_FRONT:mo.CAMERA_REAR,this.slsReporter.reportSwitchCamera(this.publisher.cameraDirection||"")),yield this.setCameraCapturerConfiguration(n),!this.publisher.cameraCaptureDisabled){(t=this.publisher.cameraTrack)==null||t.stop();const r={video:!0};e&&(r.mediaStream=new MediaStream([e])),yield this.publisher.createLocalStream(r)}})}getCurrentCameraDeviceId(){return this.publisher.getCurrentCameraDeviceId()}startPreview(){return le(this,null,function*(){if(this._audioOnlyMode)throw new Le(Ne.ERR_INNER,"Cannot start preview camera in audio only mode");this.publisher.hasCamera||(yield this.enableLocalVideo(!0)),yield this.publisher.previewAll({screen:!1})})}startPreviewScreen(i){return le(this,null,function*(){if(this._audioOnlyMode)throw new Le(Ne.ERR_INNER,"Cannot start preview screen share in audio only mode");this.publisher.hasScreenShare||(yield this.startScreenShare(i)),yield this.publisher.previewAll({primary:!1})})}stopPreview(){return le(this,null,function*(){yield this.publisher.stopPreview({primary:!0,screen:!1})})}stopPreviewScreen(){return le(this,null,function*(){yield this.publisher.stopPreview({primary:!1,screen:!0})})}getVideoTrack(i){return le(this,null,function*(){var e,t;const{userId:n,streamType:r}=i;if(!n)return r===Wt.AliRtcSdkStreamTypeCapture?this.publisher.cameraTrack:this.publisher.screenTrack;const a=this.bizControl.getRemoteUser(n);return r===Wt.AliRtcSdkStreamTypeCapture?(e=a==null?void 0:a.getCameraStream)==null?void 0:e.videoTrack:(t=a==null?void 0:a.getScreenStream)==null?void 0:t.videoTrack})}startPublishLiveStream(i,e){return le(this,null,function*(){return this.liveTranscoding.startPublishLiveStream(i,e)})}updatePublishLiveStream(i,e){return le(this,null,function*(){return this.liveTranscoding.updatePublishLiveStream(i,e)})}updatePublishLiveStreamWithTaskId(i,e){return this.liveTranscoding.updatePublishLiveStreamWithTaskId(i,e)}stopPublishLiveStream(i){return le(this,null,function*(){return this.liveTranscoding.stopPublishLiveStream(i)})}stopPublishLiveStreamWithTaskId(i){return this.liveTranscoding.stopPublishLiveStreamWithTaskId(i)}setEnableMediaExtensionMsg(i){var e;(e=this.bizControl)==null||e.setEnableMediaExtensionMsg(!!i)}sendMediaExtensionMsg(i,e){return le(this,null,function*(){return this.sendMediaExtensionMsgEx(i,e,5)})}sendMediaExtensionMsgEx(i,e,t){return le(this,null,function*(){if(!this.publisher||!this.isPublishing)throw new Le(Ne.ERR_INNER,"you should publish first");return this.slsReporter.reportSEIMessage(t,i.byteLength,e,0,!1),this.publisher.sendSEI(i,e,t)})}enablePlugin(i,e){this.bizControl.pluginManager.add(i,e)}removePlugin(i){this.bizControl.pluginManager.remove(i)}setPluginOption(i,e){const t=this.bizControl.pluginManager.get(i);t&&e&&t.setOptions(e)}getPluginByName(i){return this.bizControl.pluginManager.get(i)}getPluginOption(i){const e=this.bizControl.pluginManager.get(i);return e==null?void 0:e.getOptions()}isBeautyAvailable(){return this.bizControl.pluginManager.has("AliRtcBeauty")}isBeautyEnabled(){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i)throw new Le(Wn.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");return!!(i!=null&&i.isEnable)}setBeautyEffect(i,e){const t=this.bizControl.pluginManager.get("AliRtcBeauty");if(!t)throw new Le(Wn.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");i?t.enable():t.disable(),t.setOptions({basicBeauty:{skinBuffing:Math.max(Math.min(1,+e.smoothnessLevel),0),whitening:Math.max(Math.min(1,+e.whiteningLevel),0)}})}enableBackgroundExchange(i,e){const t=this.bizControl.pluginManager.get("AliRtcBeauty");if(!t||!t.isEnable)throw new Le(Wn.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const n={setSegmentBackgroundImage:{backgroundImgUrl:i?e:""}};i&&(n.segmentBackgroundProcess={enable:!1}),t.setOptions(n)}enableBackgroundBlur(i){const e=this.bizControl.pluginManager.get("AliRtcBeauty");if(!e||!e.isEnable)throw new Le(Wn.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const t={segmentBackgroundProcess:{type:0,enable:i}};i&&(t.setSegmentBackgroundImage={type:0,backgroundImgUrl:""}),e.setOptions(t)}setParameter(i){this.bizControl.setParameter(i)}getParameter(){return this.bizControl.getParameter()}sendDataChannelMessage(i){this.bizControl.sendDataChannelMessage(i)}subscribeRemoteStream(i){const{currentUserId:e,targetUserId:t}=i;if(t===e)throw new Le(Ne.ERR_INNER,"targetUserId should not be equal to currentUserId");return new lm(i)}},V(qe,"logName","AliRtcEngine"),V(qe,"logError",!0),V(qe,"isSupported",zm),V(qe,"isDualVideoStreamSupported",Sa.isSupport),V(qe,"getCameraList",()=>le(qe,null,function*(){return(yield St.AliRTS.getCameraList()).filter(i=>i.deviceId)})),V(qe,"getMicrophoneList",()=>le(qe,null,function*(){return(yield St.AliRTS.getMicList()).filter(i=>i.deviceId)})),V(qe,"getSpeakerList",()=>le(qe,null,function*(){return(yield St.AliRTS.getSpeakerList()).filter(i=>i.deviceId)})),V(qe,"_instance"),V(qe,"AliRtcSdkChannelProfile",ki),V(qe,"AliRtcSdkClientRole",un),V(qe,"AliRtcVideoStreamType",ti),V(qe,"AliRtcVideoTrack",ft),V(qe,"AliRtcAudioTrack",xr),V(qe,"AliRtcPublishState",nt),V(qe,"AliRtcSubscribeState",ut),V(qe,"AliRtcRawDataStreamType",Wt),V(qe,"AliRtcLogLevel",ad),V(qe,"AliRtcEngineLocalDeviceType",_n),V(qe,"AliRtcEngineLocalDeviceExceptionType",Bt),V(qe,"AliRtcConnectionStatus",at),V(qe,"AliRtcConnectionStatusChangeReason",Sn),V(qe,"AliRtcPlugin",jn),V(qe,"AliRtcPluginTrackType",To),V(qe,"AliRtcImageHolderPlugin",wg),V(qe,"AliRtcLiveTranscodingParam",ja),V(qe,"AliRtcLiveTranscodingEncodeParam",fh),V(qe,"AliRtcLiveTranscodingMixParam",yg),V(qe,"AliRtcLiveTranscodingSingleParam",Eg),V(qe,"AliRtcTranscodingClockWidget",Rg),V(qe,"AliRtcTranscodingImage",Ah),V(qe,"AliRtcTranscodingText",Tg),V(qe,"AliRtcTranscodingUser",Ag),V(qe,"AliRtcLiveTranscodingMixMode",ss),V(qe,"AliRtcLiveTranscodingStreamType",lh),V(qe,"AliRtcLiveTranscodingSourceType",Ao),V(qe,"AliRtcLiveTranscodingTaskProfile",uh),V(qe,"AliRtcLiveTranscodingAudioSampleRate",Ga),V(qe,"AliRtcLiveTranscodingSegmentType",as),V(qe,"AliRtcLiveTranscodingFontType",cs),V(qe,"AliRtcLiveTranscodingCropMode",dh),V(qe,"AliRtcLiveTranscodingMediaProcessMode",za),V(qe,"AliRtcLiveTranscodingState",hh),V(qe,"AliRtcLiveTranscodingErrorCode",En),V(qe,"AliRtcTrascodingPublishTaskStatus",ph),V(qe,"AliRtcDataChannelMsg",zn),V(qe,"AliRtcDataMsgType",th),V(qe,"Plugin",jn),qe);ze([ge()],Ge.prototype,"destroy"),ze([ge()],Ge.prototype,"backToUnpublishStatus"),ze([ge()],Ge.prototype,"resumePublishForNetworkRecovery"),ze([ge()],Ge.prototype,"onNetworkRecovery"),ze([ge()],Ge.prototype,"resumeSubList"),ze([ge(ke)],Ge.prototype,"retrySubscribe"),ze([ge(ke)],Ge.prototype,"setEnableDualVideoStream"),ze([ge(ke)],Ge.prototype,"setChannelProfile"),ze([ge(ke)],Ge.prototype,"setClientRole"),ze([ge(ke)],Ge.prototype,"setAudioOnlyMode"),ze([ge()],Ge.prototype,"clearCheckAuthInfoTimer"),ze([ge(ke)],Ge.prototype,"joinChannel"),ze([ge(ke)],Ge.prototype,"joinAIChannel"),ze([ge(ke)],Ge.prototype,"leaveChannel"),ze([ge(ke)],Ge.prototype,"refreshAuthInfo"),ze([ge(ke)],Ge.prototype,"publishLocalAudioStream"),ze([ge(ke)],Ge.prototype,"setDefaultSubscribeAllRemoteAudioStreams"),ze([ge(ke)],Ge.prototype,"subscribeAllRemoteAudioStreams"),ze([ge(ke)],Ge.prototype,"subscribeRemoteAudioStream"),ze([ge(ke)],Ge.prototype,"resumeRemoteAudioStream"),ze([ge(ke)],Ge.prototype,"stopRemoteAudioPlay"),ze([ge(ke)],Ge.prototype,"publishLocalVideoStream"),ze([ge(ke)],Ge.prototype,"setRemoteDefaultVideoStreamType"),ze([ge(ke)],Ge.prototype,"setRemoteUserVideoStreamType"),ze([ge(ke)],Ge.prototype,"setDefaultSubscribeAllRemoteVideoStreams"),ze([ge(ke)],Ge.prototype,"subscribeAllRemoteVideoStreams"),ze([ge(ke)],Ge.prototype,"subscribeRemoteMediaStream"),ze([ge(ke)],Ge.prototype,"resumeRemoteMediaStream"),ze([ge(([i])=>[`${i==null?void 0:i.audio}`])],Ge.prototype,"startScreenShare"),ze([ge()],Ge.prototype,"stopScreenShare"),ze([ge(ke)],Ge.prototype,"setScreenShareConfiguration"),ze([ge(ke)],Ge.prototype,"setScreenShareContentHint"),ze([ge()],Ge.prototype,"publishLocalScreenShareStream"),ze([ge(ke)],Ge.prototype,"setAudioShareVolume"),ze([ge(ke)],Ge.prototype,"enableAudioVolumeIndication"),ze([ge(ke)],Ge.prototype,"muteLocalMic"),ze([ge(ke)],Ge.prototype,"muteRemoteAudioPlaying"),ze([ge(ke)],Ge.prototype,"muteAllRemoteAudioPlaying"),ze([ge(ke)],Ge.prototype,"startAudioCapture"),ze([ge(ke)],Ge.prototype,"setAudioConstraints"),ze([ge()],Ge.prototype,"stopAudioCapture"),ze([ge(ke)],Ge.prototype,"switchMicrophone"),ze([ge(ke)],Ge.prototype,"setRecordingVolume"),ze([ge(ke)],Ge.prototype,"setPlayoutVolume"),ze([ge(ke)],Ge.prototype,"setRemoteAudioVolume"),ze([ge(ke)],Ge.prototype,"setAudioProfile"),ze([ge(ke)],Ge.prototype,"getAudioTrack"),ze([ge(ke)],Ge.prototype,"setLocalViewConfig"),ze([ge(ke)],Ge.prototype,"setCameraCapturerConfiguration"),ze([ge(ke)],Ge.prototype,"setCameraCapturerContentHint"),ze([ge(ke)],Ge.prototype,"enableLocalVideo"),ze([ge(ke)],Ge.prototype,"muteLocalCamera"),ze([ge(ke)],Ge.prototype,"muteLocalScreen"),ze([ge(ke)],Ge.prototype,"setRemoteViewConfig"),ze([ge(ke)],Ge.prototype,"switchCamera"),ze([ge()],Ge.prototype,"startPreview"),ze([ge()],Ge.prototype,"startPreviewScreen"),ze([ge()],Ge.prototype,"stopPreview"),ze([ge()],Ge.prototype,"stopPreviewScreen"),ze([ge()],Ge.prototype,"startPublishLiveStream"),ze([ge()],Ge.prototype,"updatePublishLiveStream"),ze([ge()],Ge.prototype,"updatePublishLiveStreamWithTaskId"),ze([ge()],Ge.prototype,"stopPublishLiveStream"),ze([ge()],Ge.prototype,"stopPublishLiveStreamWithTaskId"),ze([ge(ke)],Ge.prototype,"setEnableMediaExtensionMsg"),ze([ge(([i,e,t])=>[i.byteLength,e,t])],Ge.prototype,"sendMediaExtensionMsgEx"),ze([ge(([i,e])=>[i.name||"",e])],Ge.prototype,"enablePlugin"),ze([ge(ke)],Ge.prototype,"removePlugin"),ze([ge(ke)],Ge.prototype,"setPluginOption"),ze([ge(ke)],Ge.prototype,"getPluginByName"),ze([ge(ke)],Ge.prototype,"getPluginOption"),ze([ge(ke)],Ge.prototype,"setBeautyEffect"),ze([ge(ke)],Ge.prototype,"enableBackgroundExchange"),ze([ge(ke)],Ge.prototype,"enableBackgroundBlur"),ze([ge(ke)],Ge.prototype,"setParameter"),ze([ge(([i])=>{var e;return[(e=i.data)==null?void 0:e.byteLength]})],Ge.prototype,"sendDataChannelMessage"),ze([ge(ke)],Ge.prototype,"subscribeRemoteStream"),ze([ge(ke)],Ge,"setLogLevel");let Ch=Ge;var wh;kr=new ka({businessName:"imp-web-rtc",version:(wh=Ch.getSdkVersion())!=null?wh:"unknown",env:"prod",disabled:window.AliRtcOptionsDisableProxy===!0,deferRegionSet:!0});const Ya=kr.shallowWrapClass(Ch);var ds={};ds.byteLength=Dg,ds.toByteArray=Og,ds.fromByteArray=Ug;for(var fn=[],zi=[],Ig=typeof Uint8Array<"u"?Uint8Array:Array,Ja="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ur=0,Pg=Ja.length;Ur<Pg;++Ur)fn[Ur]=Ja[Ur],zi[Ja.charCodeAt(Ur)]=Ur;zi[45]=62,zi[95]=63;function Mh(i){var e=i.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=i.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return[t,n]}function Dg(i){var e=Mh(i),t=e[0],n=e[1];return(t+n)*3/4-n}function Lg(i,e,t){return(e+t)*3/4-t}function Og(i){var e,t=Mh(i),n=t[0],r=t[1],a=new Ig(Lg(i,n,r)),s=0,o=r>0?n-4:n,c;for(c=0;c<o;c+=4)e=zi[i.charCodeAt(c)]<<18|zi[i.charCodeAt(c+1)]<<12|zi[i.charCodeAt(c+2)]<<6|zi[i.charCodeAt(c+3)],a[s++]=e>>16&255,a[s++]=e>>8&255,a[s++]=e&255;return r===2&&(e=zi[i.charCodeAt(c)]<<2|zi[i.charCodeAt(c+1)]>>4,a[s++]=e&255),r===1&&(e=zi[i.charCodeAt(c)]<<10|zi[i.charCodeAt(c+1)]<<4|zi[i.charCodeAt(c+2)]>>2,a[s++]=e>>8&255,a[s++]=e&255),a}function Ng(i){return fn[i>>18&63]+fn[i>>12&63]+fn[i>>6&63]+fn[i&63]}function kg(i,e,t){for(var n,r=[],a=e;a<t;a+=3)n=(i[a]<<16&16711680)+(i[a+1]<<8&65280)+(i[a+2]&255),r.push(Ng(n));return r.join("")}function Ug(i){for(var e,t=i.length,n=t%3,r=[],a=16383,s=0,o=t-n;s<o;s+=a)r.push(kg(i,s,s+a>o?o:s+a));return n===1?(e=i[t-1],r.push(fn[e>>2]+fn[e<<4&63]+"==")):n===2&&(e=(i[t-2]<<8)+i[t-1],r.push(fn[e>>10]+fn[e>>4&63]+fn[e<<2&63]+"=")),r.join("")}const Bg="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let Si=(i=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(i|=0));for(;i--;)e+=Bg[t[i]&63];return e};const Ji="LM_CHAT",Qi="v1";function Vg(i,e,t){Object.defineProperty(i,e,{writable:!0,enumerable:!0,configurable:!0,value:t})}function Fg(i,e,t,n){Vg(i,e,t)}Array(32);class Hg{constructor(e){this.total=0,this.count=0,this.peddings=[],this.total=e}append(e){this.peddings.push(e),this.run()}run(){if(!this.peddings.length||this.count>=this.total)return;const e=this.peddings.shift();e&&(this.count++,e().finally(()=>{this.count--,this.run()}))}}class Gg{constructor(e){this.timer=null,this.time=10,this.count=10,this.arr=[];var t,n,r;this.time=(t=e.time)!=null?t:10,this.count=(n=e.count)!=null?n:10,this.ccController=new Hg((r=e.maxReqCount)!=null?r:10),e.host.startsWith("http://")||e.host.startsWith("https://")?this.url=e.host+"/logstores/"+e.logstore+"/track":this.url="https://"+e.project+"."+e.host+"/logstores/"+e.logstore+"/track",this.opt=e,e.installUnloadHook&&typeof e.installUnloadHook=="function"&&e.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(e){const t={__logs__:e};return this.opt.tags&&(t.__tags__=this.opt.tags),this.opt.topic&&(t.__topic__=this.opt.topic),this.opt.source&&(t.__source__=this.opt.source),JSON.stringify(t)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const e=this.assemblePayload(this.arr);this.ccController.append(()=>this.opt.sendPayload(this.url,e))}}transString(e){let t={};for(let n in e)typeof e[n]=="object"?t[n]=JSON.stringify(e[n]):t[n]=String(e[n]);return t}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const e=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){e.sendImmediateInner()},this.time*1e3)}}send(e){const t=this.transString(e);this.arr.push(t),this.sendInner()}sendImmediate(e){const t=this.transString(e);this.arr.push(t),this.sendImmediateInner()}sendBatchLogs(e){const t=e.map(n=>this.transString(n));this.arr.push(...t),this.sendInner()}sendBatchLogsImmediate(e){const t=e.map(n=>this.transString(n));this.arr.push(...t),this.sendImmediateInner()}overwriteTransString(e){this.transString=e.transString}getOpt(){return this.opt}}var hs=(i,e,t)=>new Promise((n,r)=>{var a=c=>{try{o(t.next(c))}catch(h){r(h)}},s=c=>{try{o(t.throw(c))}catch(h){r(h)}},o=c=>c.done?n(c.value):Promise.resolve(c.value).then(a,s);o((t=t.apply(i,e)).next())});function zg(i,e){return navigator&&navigator.sendBeacon?navigator.sendBeacon(`${i}?APIVersion=0.6.0`,e):!1}function xh(i,e){const t=new window.XMLHttpRequest;t.open("POST",`${i}?APIVersion=0.6.0`,!0),t.send(e)}function Wg(i,e){try{if(e.length>=32768){xh(i,e);return}zg(i,e)||xh(i,e)}catch(t){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
`+t),console.error("Failed log data:",i))}}function jg(i,e,t){return hs(this,null,function*(){return new Promise(n=>hs(this,null,function*(){try{i=i.slice(0,-6);const{data:r,header:a}=yield t.process(i,e),s=new window.XMLHttpRequest;s.open("POST",i,!0);for(let o in a)s.setRequestHeader(o,a[o]);s.onreadystatechange=()=>{s.readyState===4&&(s.status===200||window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
`+s.status),console.error("Failed logdata:",i)),n())},s.send(r)}catch(r){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
`+r),console.error("Failed log data:",i))}}))})}class Ih extends Gg{constructor(e){const t=Object.assign({},e,{installUnloadHook:n=>{window.addEventListener("beforeunload",()=>{n()})},sendPayload:(n,r)=>hs(this,null,function*(){Wg(n,r)})});super(t)}useStsPlugin(e){this.getOpt().sendPayload=(t,n)=>hs(this,null,function*(){yield jg(t,n,e)}),this.overwriteTransString(e)}}Fg(window,"SLS_Tracker",Ih);var Ph={exports:{}};(function(i,e){(function(t,n){i.exports=n()})(mi,function(){var t=1e3,n=6e4,r=36e5,a="millisecond",s="second",o="minute",c="hour",h="day",l="week",f="month",v="quarter",p="year",_="date",m="Invalid Date",d=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,u=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,b={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(D){var L=["th","st","nd","rd"],P=D%100;return"["+D+(L[(P-20)%10]||L[P]||L[0])+"]"}},y=function(D,L,P){var x=String(D);return!x||x.length>=L?D:""+Array(L+1-x.length).join(P)+D},g={s:y,z:function(D){var L=-D.utcOffset(),P=Math.abs(L),x=Math.floor(P/60),T=P%60;return(L<=0?"+":"-")+y(x,2,"0")+":"+y(T,2,"0")},m:function D(L,P){if(L.date()<P.date())return-D(P,L);var x=12*(P.year()-L.year())+(P.month()-L.month()),T=L.clone().add(x,f),O=P-T<0,k=L.clone().add(x+(O?-1:1),f);return+(-(x+(P-T)/(O?T-k:k-T))||0)},a:function(D){return D<0?Math.ceil(D)||0:Math.floor(D)},p:function(D){return{M:f,y:p,w:l,d:h,D:_,h:c,m:o,s,ms:a,Q:v}[D]||String(D||"").toLowerCase().replace(/s$/,"")},u:function(D){return D===void 0}},S="en",R={};R[S]=b;var E="$isDayjsObject",I=function(D){return D instanceof N||!(!D||!D[E])},C=function D(L,P,x){var T;if(!L)return S;if(typeof L=="string"){var O=L.toLowerCase();R[O]&&(T=O),P&&(R[O]=P,T=O);var k=L.split("-");if(!T&&k.length>1)return D(k[0])}else{var H=L.name;R[H]=L,T=H}return!x&&T&&(S=T),T||!x&&S},A=function(D,L){if(I(D))return D.clone();var P=typeof L=="object"?L:{};return P.date=D,P.args=arguments,new N(P)},w=g;w.l=C,w.i=I,w.w=function(D,L){return A(D,{locale:L.$L,utc:L.$u,x:L.$x,$offset:L.$offset})};var N=function(){function D(P){this.$L=C(P.locale,null,!0),this.parse(P),this.$x=this.$x||P.x||{},this[E]=!0}var L=D.prototype;return L.parse=function(P){this.$d=function(x){var T=x.date,O=x.utc;if(T===null)return new Date(NaN);if(w.u(T))return new Date;if(T instanceof Date)return new Date(T);if(typeof T=="string"&&!/Z$/i.test(T)){var k=T.match(d);if(k){var H=k[2]-1||0,U=(k[7]||"0").substring(0,3);return O?new Date(Date.UTC(k[1],H,k[3]||1,k[4]||0,k[5]||0,k[6]||0,U)):new Date(k[1],H,k[3]||1,k[4]||0,k[5]||0,k[6]||0,U)}}return new Date(T)}(P),this.init()},L.init=function(){var P=this.$d;this.$y=P.getFullYear(),this.$M=P.getMonth(),this.$D=P.getDate(),this.$W=P.getDay(),this.$H=P.getHours(),this.$m=P.getMinutes(),this.$s=P.getSeconds(),this.$ms=P.getMilliseconds()},L.$utils=function(){return w},L.isValid=function(){return this.$d.toString()!==m},L.isSame=function(P,x){var T=A(P);return this.startOf(x)<=T&&T<=this.endOf(x)},L.isAfter=function(P,x){return A(P)<this.startOf(x)},L.isBefore=function(P,x){return this.endOf(x)<A(P)},L.$g=function(P,x,T){return w.u(P)?this[x]:this.set(T,P)},L.unix=function(){return Math.floor(this.valueOf()/1e3)},L.valueOf=function(){return this.$d.getTime()},L.startOf=function(P,x){var T=this,O=!!w.u(x)||x,k=w.p(P),H=function(q,X){var J=w.w(T.$u?Date.UTC(T.$y,X,q):new Date(T.$y,X,q),T);return O?J:J.endOf(h)},U=function(q,X){return w.w(T.toDate()[q].apply(T.toDate("s"),(O?[0,0,0,0]:[23,59,59,999]).slice(X)),T)},ee=this.$W,W=this.$M,$=this.$D,B="set"+(this.$u?"UTC":"");switch(k){case p:return O?H(1,0):H(31,11);case f:return O?H(1,W):H(0,W+1);case l:var F=this.$locale().weekStart||0,G=(ee<F?ee+7:ee)-F;return H(O?$-G:$+(6-G),W);case h:case _:return U(B+"Hours",0);case c:return U(B+"Minutes",1);case o:return U(B+"Seconds",2);case s:return U(B+"Milliseconds",3);default:return this.clone()}},L.endOf=function(P){return this.startOf(P,!1)},L.$set=function(P,x){var T,O=w.p(P),k="set"+(this.$u?"UTC":""),H=(T={},T[h]=k+"Date",T[_]=k+"Date",T[f]=k+"Month",T[p]=k+"FullYear",T[c]=k+"Hours",T[o]=k+"Minutes",T[s]=k+"Seconds",T[a]=k+"Milliseconds",T)[O],U=O===h?this.$D+(x-this.$W):x;if(O===f||O===p){var ee=this.clone().set(_,1);ee.$d[H](U),ee.init(),this.$d=ee.set(_,Math.min(this.$D,ee.daysInMonth())).$d}else H&&this.$d[H](U);return this.init(),this},L.set=function(P,x){return this.clone().$set(P,x)},L.get=function(P){return this[w.p(P)]()},L.add=function(P,x){var T,O=this;P=Number(P);var k=w.p(x),H=function(W){var $=A(O);return w.w($.date($.date()+Math.round(W*P)),O)};if(k===f)return this.set(f,this.$M+P);if(k===p)return this.set(p,this.$y+P);if(k===h)return H(1);if(k===l)return H(7);var U=(T={},T[o]=n,T[c]=r,T[s]=t,T)[k]||1,ee=this.$d.getTime()+P*U;return w.w(ee,this)},L.subtract=function(P,x){return this.add(-1*P,x)},L.format=function(P){var x=this,T=this.$locale();if(!this.isValid())return T.invalidDate||m;var O=P||"YYYY-MM-DDTHH:mm:ssZ",k=w.z(this),H=this.$H,U=this.$m,ee=this.$M,W=T.weekdays,$=T.months,B=T.meridiem,F=function(X,J,se,ce){return X&&(X[J]||X(x,O))||se[J].slice(0,ce)},G=function(X){return w.s(H%12||12,X,"0")},q=B||function(X,J,se){var ce=X<12?"AM":"PM";return se?ce.toLowerCase():ce};return O.replace(u,function(X,J){return J||function(se){switch(se){case"YY":return String(x.$y).slice(-2);case"YYYY":return w.s(x.$y,4,"0");case"M":return ee+1;case"MM":return w.s(ee+1,2,"0");case"MMM":return F(T.monthsShort,ee,$,3);case"MMMM":return F($,ee);case"D":return x.$D;case"DD":return w.s(x.$D,2,"0");case"d":return String(x.$W);case"dd":return F(T.weekdaysMin,x.$W,W,2);case"ddd":return F(T.weekdaysShort,x.$W,W,3);case"dddd":return W[x.$W];case"H":return String(H);case"HH":return w.s(H,2,"0");case"h":return G(1);case"hh":return G(2);case"a":return q(H,U,!0);case"A":return q(H,U,!1);case"m":return String(U);case"mm":return w.s(U,2,"0");case"s":return String(x.$s);case"ss":return w.s(x.$s,2,"0");case"SSS":return w.s(x.$ms,3,"0");case"Z":return k}return null}(X)||k.replace(":","")})},L.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},L.diff=function(P,x,T){var O,k=this,H=w.p(x),U=A(P),ee=(U.utcOffset()-this.utcOffset())*n,W=this-U,$=function(){return w.m(k,U)};switch(H){case p:O=$()/12;break;case f:O=$();break;case v:O=$()/3;break;case l:O=(W-ee)/6048e5;break;case h:O=(W-ee)/864e5;break;case c:O=W/r;break;case o:O=W/n;break;case s:O=W/t;break;default:O=W}return T?O:w.a(O)},L.daysInMonth=function(){return this.endOf(f).$D},L.$locale=function(){return R[this.$L]},L.locale=function(P,x){if(!P)return this.$L;var T=this.clone(),O=C(P,x,!0);return O&&(T.$L=O),T},L.clone=function(){return w.w(this.$d,this)},L.toDate=function(){return new Date(this.valueOf())},L.toJSON=function(){return this.isValid()?this.toISOString():null},L.toISOString=function(){return this.$d.toISOString()},L.toString=function(){return this.$d.toUTCString()},D}(),M=N.prototype;return A.prototype=M,[["$ms",a],["$s",s],["$m",o],["$H",c],["$W",h],["$M",f],["$y",p],["$D",_]].forEach(function(D){M[D[1]]=function(L){return this.$g(L,D[0],D[1])}}),A.extend=function(D,L){return D.$i||(D(L,N,A),D.$i=!0),A},A.locale=C,A.isDayjs=I,A.unix=function(D){return A(1e3*D)},A.en=R[S],A.Ls=R,A.p={},A})})(Ph);var Xg=Ph.exports;const $g=Un(Xg);var Dh={exports:{}};(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(mi,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],a={},s=null;function o(m,d){var u=m[d];if(typeof u.bind=="function")return u.bind(m);try{return Function.prototype.bind.call(u,m)}catch{return function(){return Function.prototype.apply.apply(u,[m,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function h(m){return m==="debug"&&(m="log"),typeof console===t?!1:m==="trace"&&n?c:console[m]!==void 0?o(console,m):console.log!==void 0?o(console,"log"):e}function l(){for(var m=this.getLevel(),d=0;d<r.length;d++){var u=r[d];this[u]=d<m?e:this.methodFactory(u,m,this.name)}if(this.log=this.debug,typeof console===t&&m<this.levels.SILENT)return"No console available for logging"}function f(m){return function(){typeof console!==t&&(l.call(this),this[m].apply(this,arguments))}}function v(m,d,u){return h(m)||f.apply(this,arguments)}function p(m,d){var u=this,b,y,g,S="loglevel";typeof m=="string"?S+=":"+m:typeof m=="symbol"&&(S=void 0);function R(w){var N=(r[w]||"silent").toUpperCase();if(!(typeof window===t||!S)){try{window.localStorage[S]=N;return}catch{}try{window.document.cookie=encodeURIComponent(S)+"="+N+";"}catch{}}}function E(){var w;if(!(typeof window===t||!S)){try{w=window.localStorage[S]}catch{}if(typeof w===t)try{var N=window.document.cookie,M=encodeURIComponent(S),D=N.indexOf(M+"=");D!==-1&&(w=/^([^;]+)/.exec(N.slice(D+M.length+1))[1])}catch{}return u.levels[w]===void 0&&(w=void 0),w}}function I(){if(!(typeof window===t||!S)){try{window.localStorage.removeItem(S)}catch{}try{window.document.cookie=encodeURIComponent(S)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function C(w){var N=w;if(typeof N=="string"&&u.levels[N.toUpperCase()]!==void 0&&(N=u.levels[N.toUpperCase()]),typeof N=="number"&&N>=0&&N<=u.levels.SILENT)return N;throw new TypeError("log.setLevel() called with invalid level: "+w)}u.name=m,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=d||v,u.getLevel=function(){return g??y??b},u.setLevel=function(w,N){return g=C(w),N!==!1&&R(g),l.call(u)},u.setDefaultLevel=function(w){y=C(w),E()||u.setLevel(w,!1)},u.resetLevel=function(){g=null,I(),l.call(u)},u.enableAll=function(w){u.setLevel(u.levels.TRACE,w)},u.disableAll=function(w){u.setLevel(u.levels.SILENT,w)},u.rebuild=function(){if(s!==u&&(b=C(s.getLevel())),l.call(u),s===u)for(var w in a)a[w].rebuild()},b=C(s?s.getLevel():"WARN");var A=E();A!=null&&(g=C(A)),l.call(u)}s=new p,s.getLogger=function(d){if(typeof d!="symbol"&&typeof d!="string"||d==="")throw new TypeError("You must supply a name when creating a logger.");var u=a[d];return u||(u=a[d]=new p(d,s.methodFactory)),u};var _=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=_),s},s.getLoggers=function(){return a},s.default=s,s})})(Dh);var Kg=Dh.exports;const Br=Un(Kg),qg={host:"cn-hangzhou.log.aliyuncs.com",project:"smart-chat-web-sdk",logstore:"web-client-log",time:10,count:10},Yg=new Ih(qg),Qa="1.1.4";var Lh=(i=>(i.dev="dev",i.pre="pre",i.prod="prod",i))(Lh||{});Br.setLevel("error");const hi=class hi{static enableTracking(){hi._enableTracking=!0}static disableTracking(){hi._enableTracking=!1}static setEnv(e){hi._BaseExt.env=e}static setApp(e){hi._BaseExt.app=e}static setLevel(e){Br.setLevel(e)}static setBaseExt(e){Object.assign(hi._BaseExt,e)}static resetBaseExt(){hi._BaseExt={env:hi._BaseExt.env||"prod",app:hi._BaseExt.app||"",version:hi._BaseExt.version||Qa}}static log(e){const t=$g().format("YYYY-MM-DD HH:mm:ss"),{level:n,msg:r="",stack:a="",action:s,code:o,event:c,ext:h}=e,l=`[${t}] [${n}]${s?` [${s}]`:""}${r?` [${r}]`:""}${o?` [${o}]`:""}${c?` [${c}]`:""} ${h?` [${JSON.stringify(h).slice(0,200)+`${JSON.stringify(h).length>200?"...":""}`}]`:""} ${a||""}`;switch(hi._enableTracking&&["info","warn","error"].includes(n)&&Yg.send({time:t,...e,ext:{...e.ext||{},...hi._BaseExt}}),n){case"trace":Br.trace(l);break;case"info":Br.info(l);break;case"warn":Br.warn(l);break;case"error":Br.error(l);break}}static trace(e){this.log({...e,level:"trace"})}static info(e){this.log({...e,level:"info"})}static warn(e){this.log({...e,level:"warn"})}static error(e){this.log({...e,level:"error"})}};We(hi,"_enableTracking",!0),We(hi,"_BaseExt",{env:"prod",app:"",version:Qa});let et=hi;class xi{constructor(){We(this,"beginTime",0);We(this,"container");We(this,"fpsPanel");We(this,"frames",0);We(this,"memPanel");We(this,"mode",0);We(this,"msPanel");We(this,"prevTime",0);We(this,"statsArea");We(this,"voiceChatPanels");this.container=document.createElement("div"),document.body.appendChild(this.container),this.statsArea=document.createElement("div"),this.container.style.cssText="position:fixed;top:0;right:0;cursor:pointer;opacity:0.9;z-index:10000;display:flex;flex-direction:column;";const e=document.createElement("select");e.style.cssText="height: 30px;";let t="";t+=`<option value="0">Chat延时</option><option value="1">FPS</option>
    <option value="2">MS</option>`,this.container.appendChild(e),this.container.appendChild(this.statsArea),e.addEventListener("change",()=>{this.showPanel(+e.value)},!1),this.beginTime=performance.now(),this.prevTime=this.beginTime,this.frames=0,this.voiceChatPanels=this.addPanels([xi.Panel("VAD","#0ff","#002"),xi.Panel("ASR判停","#0ff","#002"),xi.Panel("ASR未判停","#0ff","#002"),xi.Panel("LLM","#0ff","#002"),xi.Panel("TTS-total","#0ff","#002"),xi.Panel("TTS-frd","#0ff","#002"),xi.Panel("TTS-ATom","#0ff","#002"),xi.Panel("Avatar","#0ff","#002")]),this.fpsPanel=this.addPanel(xi.Panel("FPS","#0ff","#002")),this.msPanel=this.addPanel(xi.Panel("MS","#0f0","#020")),performance&&performance.memory&&(t+='<option value="3">MB</option>',this.memPanel=this.addPanel(xi.Panel("MB","#f08","#201"))),e.innerHTML=t,this.showPanel(0)}static Panel(e,t,n){let r=1/0,a=0;const s=Math.round,o=s(window.devicePixelRatio||1),c=80*o,h=48*o,l=3*o,f=2*o,v=3*o,p=11*o,_=74*o,m=32*o,d=document.createElement("canvas");d.width=c,d.height=h,d.style.cssText="width:160px; height:96px;";const u=d.getContext("2d");return u.font="bold "+6*o+"px Helvetica,Arial,sans-serif",u.textBaseline="top",u.fillStyle=n,u.fillRect(0,0,c,h),u.fillStyle=t,u.fillText(e,l,f),u.fillRect(v,p,_,m),u.fillStyle=n,u.globalAlpha=.9,u.fillRect(v,p,_,m),{dom:d,name:e,update:function(b,y){r=Math.min(r,b),a=Math.max(a,b),u.fillStyle=n,u.globalAlpha=1,u.fillRect(0,0,c,p),u.fillStyle=t,u.fillText(s(b)+" "+e+" ("+s(r)+"-"+s(a)+")",l,f),u.drawImage(d,v+o,p,_-o,m,v,p,_-o,m),u.fillRect(v+_-o,p,o,m),u.fillStyle=n,u.globalAlpha=.9,u.fillRect(v+_-o,p,o,s((1-b/y)*m))}}}addPanel(e){var t;return(t=this.statsArea)==null||t.appendChild(e.dom),e}addPanels(e){var r;const t=document.createElement("div");t.style.cssText="width: 324px; display:flex;justify-content:space-around;flex-wrap:wrap;",e.forEach(a=>{t.appendChild(a.dom),a.dom.style.cssText="width: 160px;margin-bottom: 4px;margin-right: 2px"});const n=document.createElement("div");return t.appendChild(n),(r=this.statsArea)==null||r.appendChild(t),e}begin(){this.beginTime=(performance||Date).now()}end(e){var n,r;if(e){const{vadDelay:a,asrAtomStopDelay:s,asrAtomDelay:o,llmDelay:c,ttsTotalDelay:h,ttsFrdDelay:l,ttsAtomDelay:f,avatarDelay:v}=e;this.voiceChatPanels[0].update(a,2e3),this.voiceChatPanels[1].update(o,1e3),this.voiceChatPanels[2].update(s,1e3),this.voiceChatPanels[3].update(c,3e3),this.voiceChatPanels[4].update(h,1e3),this.voiceChatPanels[5].update(l,1e3),this.voiceChatPanels[6].update(f,1e3),this.voiceChatPanels[7].update(v,1e3)}this.frames++;const t=(performance||Date).now();if((n=this.msPanel)==null||n.update(t-this.beginTime,200),t>=this.prevTime+1e3&&((r=this.fpsPanel)==null||r.update(this.frames*1e3/(t-this.prevTime),100),this.prevTime=t,this.frames=0,this.memPanel&&performance&&performance.memory)){const a=performance.memory;this.memPanel.update(a.usedJSHeapSize/1048576,a.jsHeapSizeLimit/1048576)}return t}hide(){this.container.style.visibility="hidden"}show(){this.container.style.visibility="visible"}showPanel(e){if(this.statsArea){for(let t=0;t<this.statsArea.children.length;t++)this.statsArea.children[t].style.display=t===e?"flex":"none";this.mode=e}}update(e){this.beginTime=this.end(e)}}var Mo=(i=>(i.duplex="duplex",i.push2talk="push2talk",i.tap2talk="tap2talk",i))(Mo||{}),ps=(i=>(i[i.speaking=0]="speaking",i[i.responding=1]="responding",i))(ps||{}),Za=(i=>(i.StandBy="StandBy",i.Idle="Idle",i.Listening="Listening",i.Responding="Responding",i.Thinking="Thinking",i.NONE="None",i))(Za||{}),ec=(i=>(i[i.SPEAKING=0]="SPEAKING",i[i.LISTENING=2]="LISTENING",i))(ec||{}),tc=(i=>(i[i.mic=0]="mic",i[i.player=1]="player",i))(tc||{}),Oh=(i=>(i.minimax="minimax",i.nls="nls",i))(Oh||{}),ic=(i=>(i.f32="f32",i.opus="opus",i.s16="s16",i))(ic||{}),bi=(i=>(i[i.invalidAuthParams=1e3]="invalidAuthParams",i[i.authFailed=1001]="authFailed",i[i.joinChannelFailed=1002]="joinChannelFailed",i[i.dataChannelLostPackets=1003]="dataChannelLostPackets",i[i.dataChannelBroken=1004]="dataChannelBroken",i[i.channelDestroyed=1005]="channelDestroyed",i[i.rtcKickOff=1006]="rtcKickOff",i[i.dataChannelDelay=1007]="dataChannelDelay",i))(bi||{}),li=(i=>(i.authFailed="rtc auth failed",i.channelDestroyed="channel destroyed",i.dataChannelBroken="data channel broken",i.dataChannelDelay="data channel delay",i.dataChannelLostPackets="data channel lost packets",i.invalidAuthParams="invalid auth params",i.joinChannelFailed="rtc join channel failed",i.rtcKickOff="rtc kick off",i))(li||{}),Ii=(i=>(i[i.RTCNoSupported=1100]="RTCNoSupported",i[i.CameraUnauthorized=1102]="CameraUnauthorized",i[i.MicUnauthorized=1103]="MicUnauthorized",i[i.AudioPublishFailed=1104]="AudioPublishFailed",i[i.VideoPublishFailed=1105]="VideoPublishFailed",i[i.UnknownError=1106]="UnknownError",i[i.UserActivationError=1107]="UserActivationError",i))(Ii||{}),Pi=(i=>(i.AudioPublishFailed="Audio publish failed",i.CameraUnauthorized="Camera unauthorized",i.MicUnauthorized="Mic unauthorized",i.RTCNoSupported="The current environment does not support WebRTC",i.UnknownError="unknown error",i.UserActivationError="当前网页未存在用户交互行为,默认会被浏览器拦截",i.VideoPublishFailed="Video publish failed",i))(Pi||{}),fs=(i=>(i[i.LinkChatServerFailed=1120]="LinkChatServerFailed",i))(fs||{}),ms=(i=>(i.LinkChatServerFailed="Link chat server failed",i))(ms||{}),Nh=(i=>(i.prompt="prompt",i.transcript="transcript",i))(Nh||{}),kh=(i=>(i.cloud="cloud",i.local="local",i))(kh||{}),xo=(i=>(i.TimestampStatistics="TimestampStatistics",i.RemoteRtcAudioStats="RemoteRtcAudioStats",i.RemoteRtcVideoStats="RemoteRtcVideoStats",i))(xo||{}),$n=(i=>(i.realBg="REAL_BG",i.serverReplaceBg="SERVER_REPLACE_BG",i.chromaKey="CHROMA_KEY",i.maskBlend="MASK_BLEND",i))($n||{}),mt=(i=>(i.ErrorReceived="ErrorReceived",i.FirstFrameReceived="FirstFrameReceived",i.SpeakStarted="SpeakStarted",i.SpeakEnded="SpeakEnded",i.ResponseStarted="ResponseStarted",i.ResponseEnded="ResponseEnded",i.MessageReceived="MessageReceived",i.ReadyToSpeech="ReadyToSpeech",i.StateChanged="StateChanged",i.StatsReceived="StatsReceived",i.VolumeChanged="VolumeChanged",i))(mt||{}),Zi=(i=>(i.audioVolume="audioVolume",i.bye="bye",i.dataChannelMsg="dataChannelMsg",i.dataPublishStateChanged="dataPublishStateChanged",i.localDeviceException="localDeviceException",i.mediaExtensionMsgReceived="mediaExtensionMsgReceived",i.onOccurError="onOccurError",i.videoSubscribeStateChanged="videoSubscribeStateChanged",i.rtcRemoteVideoStats="rtcRemoteVideoStats",i.rtcRemoteAudioStats="rtcRemoteAudioStats",i))(Zi||{}),nc=(i=>(i[i.AliRtcOnByeBeKickedOut=1]="AliRtcOnByeBeKickedOut",i[i.AliRtcOnByeChannelTerminated=2]="AliRtcOnByeChannelTerminated",i[i.AliRtcOnByeUserReplaced=3]="AliRtcOnByeUserReplaced",i))(nc||{});const Jg=24*1024;function rc(i){return typeof i=="object"&&i!==null&&(i instanceof Int16Array||Object.prototype.toString.call(i)==="[object Int16Array]")}function Qg(i){if(rc(i))return i;if(!Array.isArray(i)||i.length===0)return new Int16Array(0);const e=i[0];if(rc(e)){for(const a of i)if(!rc(a))return new Int16Array(0);let t=0;for(const a of i)t+=a.length;const n=new Int16Array(t);let r=0;for(const a of i){const s=a;n.set(s,r),r+=s.length}return n}return typeof e=="number"?Int16Array.from(i):new Int16Array(0)}function Zg(i){const{pcmSamples:e,sampleRate:t,batchId:n,endOfBatch:r}=i,a={batch_id:n,batch_name:`batch_${n}`,end_of_batch:r,data_records:{audio:{sample_rate:t,shape:[e.length],data_offset:0,data_type:"int16"}},events:[]},s=new TextEncoder().encode(JSON.stringify(a)),o=new Uint8Array(e.byteLength);o.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));const c=s.length,h=o.length,l=12+c+h,f=new Uint8Array(l);f[0]=74,f[1]=66,f[2]=73,f[3]=78;const v=new DataView(f.buffer);return v.setUint32(4,c,!0),v.setUint32(8,h,!0),f.set(s,12),f.set(o,12+c),f}function ev(i,e){if(i.length===0)return[];if(!Number.isFinite(e)||e<1)return[i];const t=[];for(let n=0;n<i.length;n+=e)t.push(i.subarray(n,Math.min(n+e,i.length)));return t}const tv=async()=>{var i;return(navigator==null?void 0:navigator.userActivation)!==void 0&&((i=navigator==null?void 0:navigator.userActivation)==null?void 0:i.hasBeenActive)!==void 0?navigator.userActivation.hasBeenActive:new Promise(e=>{const t=document.createElement("audio");t.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAESsAACJWAAACABAAZGF0YQAAAAA=",t.muted=!1,t.play().then(()=>{e(!0)},n=>{n.name==="NotAllowedError"&&(e(!1),t.remove())})})},iv=async()=>{var i;if(!((i=navigator.permissions)!=null&&i.query))return!1;try{return(await navigator.permissions.query({name:"microphone"})).state==="denied"}catch{return!1}},nv=()=>{try{const i=`${navigator.userAgent}-${window.screen.width}x${window.screen.height}-${window.devicePixelRatio}`;return btoa(i)}catch(i){return console.warn("getDeviceId:",i),crypto.randomUUID?crypto.randomUUID():Si()}},Uh=()=>{const i=new(window.AudioContext||window.webkitAudioContext),e=i.createMediaStreamDestination(),t=i.createOscillator(),n=i.createGain();t.type="sine",t.frequency.value=440,n.gain.value=1e-6,t.connect(n),n.connect(e),t.start();const[r]=e.stream.getAudioTracks();if(!r)throw new Error("Failed to create silent audio track");return{track:r,audioContext:i,stop:()=>{t.stop(),i.close()}}},rv=2e3;class ov{constructor(e){We(this,"ee");We(this,"initConfig",{deviceMode:0,ignoreAudioInput:!1,enableLocalVideo:!1});We(this,"silentAudioTrack");We(this,"engine");this.ee=e}async init(e){if(this.initConfig=Object.assign({},this.initConfig,e),et.trace({action:"init",msg:"阿里云rtc初始化",ext:{...this.initConfig}}),this.engine)return this.engine;if(!(await Ya.isSupported()).support){et.error({code:Ii.RTCNoSupported,msg:Pi.RTCNoSupported}),this.ee.emit(mt.ErrorReceived,{code:Ii.RTCNoSupported,message:Pi.RTCNoSupported});return}if(this.engine=Ya.getInstance(),this.initConfig.enableLocalVideo||await this.engine.enableLocalVideo(!1),this.engine.setParameter(JSON.stringify({data:{enablePubDataChannel:!0,enableSubDataChannel:!0}})),this.initConfig.cameraCapturerConfig){const{width:n,height:r,bitrate:a=rv}=this.initConfig.cameraCapturerConfig;try{await this.engine.setCameraCapturerConfiguration({width:n,height:r,bitrate:a})}catch(s){et.error({action:"init",msg:`setCameraCapturerConfiguration error: ${(s==null?void 0:s.message)||s}`})}}return this.engine.on(Zi.bye,n=>{n===nc.AliRtcOnByeBeKickedOut?(et.error({code:bi.rtcKickOff,msg:li.rtcKickOff}),this.ee.emit(mt.ErrorReceived,{code:bi.rtcKickOff,msg:li.rtcKickOff,terminate:!0})):n===nc.AliRtcOnByeChannelTerminated&&(et.error({code:bi.channelDestroyed,msg:li.channelDestroyed}),this.ee.emit(mt.ErrorReceived,{code:bi.channelDestroyed,msg:li.channelDestroyed,terminate:!0}))}),this.engine.on(Zi.onOccurError,n=>{n.code===16843857?(et.error({code:Ii.CameraUnauthorized,msg:Pi.CameraUnauthorized}),this.ee.emit(mt.ErrorReceived,{code:Ii.CameraUnauthorized,message:Pi.CameraUnauthorized,terminate:!0})):n.code===16843856?(et.error({code:Ii.AudioPublishFailed,msg:Pi.AudioPublishFailed}),this.ee.emit(mt.ErrorReceived,{code:Ii.AudioPublishFailed,message:Pi.AudioPublishFailed,terminate:!0})):n.code===16844118&&(et.error({code:bi.dataChannelBroken,msg:li.dataChannelBroken}),this.ee.emit(mt.ErrorReceived,{code:bi.dataChannelBroken,message:li.dataChannelBroken,terminate:!0}))}),this.engine.on(Zi.audioVolume,n=>{this._audioVolumeHandler(n)}),this.engine.on(Zi.localDeviceException,n=>{(n===Bt.AliEngineLocalDeviceExceptionTypeMicOpenFail||n===Bt.AliEngineLocalDeviceExceptionTypeMicAuthFail||n===Bt.AliEngineLocalDeviceExceptionTypeMicNotAvailable)&&(et.error({code:Ii.MicUnauthorized,msg:Pi.MicUnauthorized}),this.ee.emit(mt.ErrorReceived,{code:Ii.MicUnauthorized,message:Pi.MicUnauthorized,terminate:!0}))}),this.engine.on(Zi.rtcRemoteVideoStats,n=>{var a;const r=n&&((a=n[0])==null?void 0:a.stats);r&&(r.jitter>=.05||r.packetsLost>0)&&et.warn({action:"rtcRemoteVideoStatsWarning",msg:"推流视频传输异常",ext:{jitter:r.jitter,packetsLost:r.packetsLost}}),this.ee.emit(mt.StatsReceived,{type:xo.RemoteRtcVideoStats,data:n})}),this.engine.on(Zi.rtcRemoteAudioStats,n=>{this.ee.emit(mt.StatsReceived,{type:xo.RemoteRtcAudioStats,data:n})}),this.engine.enableAudioVolumeIndication(100),this.engine}async joinRoom(e){et.trace({action:"joinRoom",msg:"加入阿里云rtc通道",ext:{channelProfile:ki.AliRtcSdkInteractiveLive}});try{this.engine.publishLocalAudioStream(!0),this.initConfig.enableLocalVideo||this.engine.publishLocalVideoStream(!1),this.engine.setChannelProfile(ki.AliRtcSdkInteractiveLive),this.engine.setClientRole(un.AliRtcSdkInteractive),this.initConfig.ignoreAudioInput&&(this.silentAudioTrack||(this.silentAudioTrack=Uh()),await this.engine.switchMicrophone("",this.silentAudioTrack.track));const{appId:t,channelId:n,userId:r,token:a,timestamp:s,userName:o}=e;await this.engine.joinChannel({appId:t,channelId:n,userId:r,token:a,timestamp:s},o),et.info({action:"joinRoom",msg:"加入rtc房间成功",ext:{channelId:n,userId:r}})}catch(t){et.error({code:bi.joinChannelFailed,msg:li.joinChannelFailed,stack:t.stack}),this.ee.emit(mt.ErrorReceived,{code:bi.joinChannelFailed,message:li.joinChannelFailed,error:t,terminate:!0})}}async joinRoomAsLive(e){et.trace({action:"joinRoomAsLive",msg:"加入阿里云rtc通道",ext:{channelProfile:ki.AliRtcSdkCommunication}});try{this.engine.publishLocalAudioStream(!0),this.engine.setAudioProfile("standard"),this.initConfig.enableLocalVideo||this.engine.publishLocalVideoStream(!1),this.engine.setChannelProfile(ki.AliRtcSdkCommunication),this.engine.setClientRole(un.AliRtcSdkLive),this.initConfig.ignoreAudioInput&&(this.silentAudioTrack||(this.silentAudioTrack=Uh()),await this.engine.switchMicrophone("",this.silentAudioTrack.track));const{appId:t,channelId:n,userId:r,token:a,timestamp:s,userName:o}=e;await this.engine.joinChannel({appId:t,channelId:n,userId:r,token:a,timestamp:s},o),et.info({action:"joinRoomAsLive",msg:"加入rtc房间成功",ext:{channelId:n,userId:r}})}catch(t){et.error({code:bi.joinChannelFailed,msg:li.joinChannelFailed,stack:t.stack}),this.ee.emit(mt.ErrorReceived,{code:bi.joinChannelFailed,message:li.joinChannelFailed,error:t,terminate:!0})}}leave(){var e,t;this.engine&&((e=this.engine)==null||e.leaveChannel(),(t=this.engine)==null||t.destroy(),this.engine=void 0),this.silentAudioTrack&&(this.silentAudioTrack.stop(),this.silentAudioTrack=void 0)}muteLocalMic(e){this.engine&&this.engine.muteLocalMic(e)}setPlayoutVolume(e){if(this.engine){const t=Math.max(0,Math.min(100,e));this.engine.setPlayoutVolume(t)}}send(e){var t;(t=this.engine)==null||t.sendDataChannelMessage(new zn(new TextEncoder().encode(e)))}_audioVolumeHandler(e){let t=0,n=0;e.forEach(r=>{r.userId===""?t=r.volume:n+=r.volume}),this.ee.emit(mt.VolumeChanged,{volume:t/255,source:tc.mic}),this.initConfig.deviceMode===0&&this.ee.emit(mt.VolumeChanged,{volume:n/255,source:tc.player})}}class sv extends Kt{constructor(t,n="RtcAvatar"){super();We(this,"_curState",Za.Idle);We(this,"_isDataChannelReady",!1);We(this,"_isReadyTimer");We(this,"_isReady",!1);We(this,"_localMicMuted",!1);We(this,"_rtc",new ov(this));We(this,"_heartBeatTimer");We(this,"_deviceId");We(this,"_sessionId");We(this,"_avatarInitConfig");We(this,"_dialogConfig",{mode:Mo.tap2talk,keepAlive:!0,avatarAudioFormat:ic.s16,outboundSampleRate:48e3});We(this,"_serviceInitData",{transparentBackgroundType:$n.realBg});et.resetBaseExt(),et.setBaseExt({name:n}),et.trace({action:"constructor",ext:{name:n,...t}});const{appId:r,channel:a,timestamp:s,token:o,clientUserId:c,clientUserName:h,serverUserId:l,avatarUserId:f,sessionId:v,rootContainer:p}=t;if(r&&a&&s&&o&&c&&l&&f&&p)this._deviceId=nv(),this._avatarInitConfig=t,this._sessionId=v||Si(),et.setBaseExt({sessionId:this._sessionId}),h&&et.setBaseExt({clientName:h});else throw et.error({action:"constructor",code:bi.invalidAuthParams,msg:li.invalidAuthParams}),this.emit(mt.ErrorReceived,{code:bi.invalidAuthParams,message:li.invalidAuthParams}),new Error(li.invalidAuthParams)}async _checkUserActivation(){await tv()||et.error({code:Ii.UserActivationError,msg:Pi.UserActivationError})}async _checkMicPermissionDenied(){return await iv()?(et.error({code:Ii.MicUnauthorized,msg:Pi.MicUnauthorized}),this.emit(mt.ErrorReceived,{terminate:!0,code:Ii.MicUnauthorized,message:Pi.MicUnauthorized}),!0):!1}setDialogConfig(t){this._dialogConfig=Object.assign({},this._dialogConfig,t)}exit(){et.info({action:"exit",msg:"exit chat"}),this._isDataChannelReady=!1,this._isReady=!1,this._serviceInitData={transparentBackgroundType:$n.realBg},this._heartBeatTimer&&(clearInterval(this._heartBeatTimer),this._heartBeatTimer=void 0),this._isReadyTimer&&(clearInterval(this._isReadyTimer),this._isReadyTimer=void 0),this._rtc.send(JSON.stringify({header:{name:"Stop",version:Qi,namespace:Ji,sessionId:this._sessionId,requestId:Si(),deviceId:this._deviceId},payload:{}}));const t=setTimeout(()=>{this._rtc.leave(),clearTimeout(t)},350)}interrupt(){if(!this._sessionId)throw new Error("未创建对话");et.info({action:"interrupt",msg:"触发打断指令"}),this._rtc.send(JSON.stringify({header:{name:"RequestToSpeak",version:Qi,namespace:Ji,sessionId:this._sessionId,requestId:Si(),deviceId:this._deviceId},payload:{}}))}muteLocalMic(t){et.info({action:"muteLocalMic",msg:"设置本地麦克风静音",ext:{mute:t}}),this._rtc.muteLocalMic(t),this._localMicMuted=t}setVolume(t){this._rtc.setPlayoutVolume(t)}onErrorReceived(t){this.on(mt.ErrorReceived,t)}onFirstFrameReceived(t){this.on(mt.FirstFrameReceived,t)}onMessageReceived(t){this.on(mt.MessageReceived,t)}onReadyToSpeech(t){this.on(mt.ReadyToSpeech,t)}onStateChanged(t){this.on(mt.StateChanged,t)}onVolumeChanged(t){this.on(mt.VolumeChanged,t)}onPerformanceInfoTrack(t){this.on(mt.StatsReceived,t)}requestToRespond(t,n){et.info({action:"requestToRespond",ext:{type:t}}),this._rtc.send(JSON.stringify({header:{name:"RequestToRespond",version:Qi,namespace:Ji,sessionId:this._sessionId,requestId:Si(),deviceId:this._deviceId},payload:{type:t,content:n}}))}sendSpeech(){this._dialogConfig.mode===Mo.push2talk&&(et.info({action:"sendSpeech",msg:"push2talk手动发送语音"}),this._rtc.send(JSON.stringify({header:{name:"SendSpeech",version:Qi,namespace:Ji,sessionId:this._sessionId,requestId:Si(),deviceId:this._deviceId},payload:{}})))}setLogLevel(t){et.setLevel(t)}stopSpeech(){this._dialogConfig.mode===Mo.push2talk&&(et.info({action:"stopSpeech",msg:"push2talk手动结束语音"}),this._rtc.send(JSON.stringify({header:{name:"StopSpeech",version:Qi,namespace:Ji,sessionId:this._sessionId,requestId:Si(),deviceId:this._deviceId},payload:{}})))}_dataPublishStateChangedHandler(t,n){n===nt.AliRtcStatePublished&&(this._isDataChannelReady=!0,et.info({event:"dataPublishStateChangedHandler",msg:"dataChannel已准备好, 开始轮询发送IsReady"}),this._isReadyTimer&&(clearInterval(this._isReadyTimer),this._isReadyTimer=void 0),this._isReadyTimer=setInterval(()=>{this._rtc.send(JSON.stringify({header:{name:"IsReady",version:Qi,namespace:Ji,requestId:Si(),deviceId:this._deviceId},payload:{}}))},100))}_dataChannelMsgHandler(t,n){const r=JSON.parse(new TextDecoder().decode(n.data)),{header:a,payload:s}=r;switch(a==null?void 0:a.name){case"Ready":this._readyHandler(s);break;case"Started":this._startedHandler();break;case"AvatarStatusChanged":this._avatarStateChangedHandler(s);break;case"DialogStateChanged":this._dialogStateChangedHandler(s);break;case"RequestAccepted":break;case"RespondingStarted":this._respondingStarted();break;case"RespondingContent":this._respondingContent(a,s);break;case"RespondingEnded":this._respondingEnded();break;case"SpeechStarted":this._speechStarted();break;case"SpeechContent":this._speechContent(a,s);break;case"SpeechEnded":this._speechEnded();break;case"Stopped":this._stopped();break;case"Error":this._errorHandler(s);break;case"TimestampStatistics":this._timestampStatistics(a,s);break}return r}_respondingEnded(){et.trace({event:"_respondingEnded",msg:"接收到RespondingEnded"}),this.emit(mt.ResponseEnded)}_startedHandler(){this.emit(mt.ReadyToSpeech),et.info({event:"_startedHandler",msg:"接收到Started,触发ReadyToSpeech"}),this._heartBeat()}_heartBeat(){if(this._dialogConfig.keepAlive){if(this._heartBeatTimer)return;if(this._heartBeatTimer=setInterval(()=>{et.trace({action:"_heartBeat",msg:"发送心跳"}),this._rtc.send(JSON.stringify({header:{name:"HeartBeat",version:Qi,namespace:Ji,sessionId:this._sessionId,requestId:Si(),deviceId:this._deviceId},payload:{}}))},1e3*10),typeof this._dialogConfig.keepAlive=="number"){const t=setTimeout(()=>{clearInterval(this._heartBeatTimer),clearTimeout(t)},this._dialogConfig.keepAlive)}}}_readyHandler(t){const{transparentBackground:n}=t;n&&(this._serviceInitData.transparentBackgroundType=n),et.info({event:"_readyHandler",msg:"接收到Ready",ext:{transparentBackground:n}}),this._isReady=!0,this._isReadyTimer&&(clearInterval(this._isReadyTimer),this._isReadyTimer=void 0)}buildStartSignalPayload(t){return{mode:this._dialogConfig.mode,renderType:t,avatarAudioFormat:this._dialogConfig.avatarAudioFormat,outboundSampleRate:this._dialogConfig.outboundSampleRate,ignoreAudioInput:!!this._avatarInitConfig.ignoreAudioInput}}sendStartSignal(t){et.info({action:"sendStartSignal",msg:"通过dataChannel发送Start信号"}),this._rtc.send(JSON.stringify({header:{name:"Start",version:Qi,namespace:Ji,sessionId:this._sessionId,requestId:Si(),deviceId:this._deviceId},payload:this.buildStartSignalPayload(t)}))}startLinkDataChannel(t){let n=0;if(this._isReady)this.sendStartSignal(t);else{const r=setInterval(()=>{this._isReady?(this.sendStartSignal(t),clearInterval(r)):(n++,n>30&&(n=0,clearInterval(r),et.error({event:"start",code:fs.LinkChatServerFailed,msg:ms.LinkChatServerFailed}),this.emit(mt.ErrorReceived,{code:fs.LinkChatServerFailed,message:ms.LinkChatServerFailed,terminate:!0})))},500)}}emitFirstFrame(){if(et.info({action:"canplay",msg:"获取到了渲染首帧画面"}),this.emit(mt.FirstFrameReceived),this._isDataChannelReady)this.sendFirstFrameRendered();else{const t=setInterval(()=>{this._isDataChannelReady&&(this.sendFirstFrameRendered(),clearInterval(t))},100)}}sendFirstFrameRendered(){et.info({action:"sendFirstFrameRendered",msg:"通过dataChannel发送FirstFrameRendered信号"}),this._rtc.send(JSON.stringify({header:{name:"FirstFrameRendered",version:Qi,namespace:Ji,sessionId:this._sessionId,requestId:Si(),deviceId:this._deviceId},payload:{}}))}_respondingStarted(){et.trace({event:"_respondingStarted",msg:"接收到RespondingStarted"}),this.emit(mt.ResponseStarted)}_respondingContent(t,n){et.trace({event:"_respondingContent",msg:"接收到RespondingContent",ext:{isFinished:n.finished}}),this.emit(mt.MessageReceived,{type:ps.responding,text:n.spoken,rawText:n.text,isFinished:n.finished})}_speechStarted(){et.trace({event:"_speechStarted",msg:"接收到SpeechStarted"}),this.emit(mt.SpeakStarted)}_speechEnded(){et.trace({event:"_speechEnded",msg:"接收到SpeechEnded"}),this.emit(mt.SpeakEnded)}_speechContent(t,n){et.trace({event:"_speechContent",msg:"接收到SpeechContent",ext:{isFinished:n.finished}}),this.emit(mt.MessageReceived,{type:ps.speaking,text:n.text,isFinished:n.finished})}_stopped(){et.info({event:"_stopped",msg:"接收到Stopped"})}_errorHandler(t){const{code:n,message:r,terminate:a}=t;et.error({event:"errorHandler",msg:"接收到Error消息",code:n,ext:{message:r,terminate:a}}),this.emit(mt.ErrorReceived,{code:n,message:r,terminate:a})}_avatarStateChangedHandler(t){et.info({event:"_avatarStateChangedHandler",msg:"接收到AvatarStatusChanged,并发送AvatarStateChanged",ext:{currentStatus:t.currentStatus}});const n=t.currentStatus==="SPEAKING"?ec.SPEAKING:ec.LISTENING;this._rtc.send(JSON.stringify({header:{name:"AvatarStateChanged",version:Qi,namespace:Ji,sessionId:this._sessionId,requestId:Si(),deviceId:this._deviceId},payload:{to_state:n}}))}_dialogStateChangedHandler(t){if(!this._sessionId)return;const{state:n}=t;this._curState=n,et.info({event:"_dialogStateChangedHandler",msg:"接收到DialogStateChanged",ext:{state:this._curState}}),this.emit(mt.StateChanged,this._curState)}_timestampStatistics(t,n){const{roundId:r}=t,{roundCount:a,avatarDelay:s,llmDelay:o,ttsDelay:c,totalDelay:h,roundAverageTotalDelay:l}=n,f={roundId:r,roundCount:a,llmDelay:o,ttsDelay:c,avatarDelay:s,totalDelay:h,roundAverageTotalDelay:l};et.trace({event:"_timestampStatistics",msg:"接收到TimestampStatistics",ext:{ext:f}}),this.emit(mt.StatsReceived,{type:xo.TimestampStatistics,data:f})}}const av=`
attribute vec4 a_position;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
void main () {
  gl_Position = a_position;
  v_texCoord = a_texCoord;
}
`,cv=`
  precision mediump float;

  uniform sampler2D image;

  uniform float similarity;
  uniform float smoothness;

  uniform float videoWidth;
  uniform float videoHeight;

  varying vec2 v_texCoord;

  const mat4 yuv_mat = mat4(
  0.182586, -0.100644, 0.439216,  0.000000,
  0.614231, -0.338572, -0.398942, 0.000000,
  0.062007, 0.439216,  -0.040274, 0.000000,
  0.062745, 0.501961,  0.501961,  1.000000
  );

  vec3 despillByAvg(in vec3 rgb)
  {
      float r = rgb.r;
      float g = rgb.g;
      float b = rgb.b;
      if( (g > ((r + b) / 2.0))  && (g - r > 10.0/255.0) && (g - b > 10.0/255.0))
      {
          rgb.g = (r + b) / 2.0;
          return rgb;
      }
      else {
          return rgb;
      }
  }

  float GetChromaDist(in vec3 rgb)
  {
      vec4 green_color = vec4(0.0, 1.0, 0.0, 1.0);
      vec2 chroma_key =  (yuv_mat * vec4(green_color.rgb, 1.0)).yz;
      vec4 yuvx = (yuv_mat * vec4(rgb.rgb, 1.0));
      return distance(chroma_key, yuvx.yz);
  }

  vec4 SampleTexture(in vec2 uv)
  {
      return texture2D(image, uv);
  }

  float GetBoxFilteredChromaDist(in vec3 rgb, in vec2 texCoord)
  {
      vec2 pixel_size = vec2(1.0/videoWidth, 1.0/videoHeight);
      float distVal = GetChromaDist(rgb);
      distVal += GetChromaDist(SampleTexture(texCoord-pixel_size).rgb);
      distVal += GetChromaDist(SampleTexture(texCoord-vec2(pixel_size.x, 0.0)).rgb);
      distVal += GetChromaDist(SampleTexture(texCoord-vec2(pixel_size.x, -pixel_size.y)).rgb);

      distVal += GetChromaDist(SampleTexture(texCoord-vec2(0.0, pixel_size.y)).rgb);
      distVal += GetChromaDist(SampleTexture(texCoord+vec2(0.0, pixel_size.y)).rgb);

      distVal += GetChromaDist(SampleTexture(texCoord+vec2(pixel_size.x, -pixel_size.y)).rgb);
      distVal += GetChromaDist(SampleTexture(texCoord+vec2(pixel_size.x, 0.0)).rgb);
      distVal += GetChromaDist(SampleTexture(texCoord+pixel_size).rgb);
      return distVal / 9.0;
  }

  vec4 ProcessChromaKey(in vec4 rgba, in vec2 vTextureCoord)
  {
      float chromaDist = GetBoxFilteredChromaDist(rgba.rgb, vTextureCoord);
      float baseMask = chromaDist - similarity;
      if((rgba.r > 1.5 * rgba.b) &&
      (rgba.g > 1.5 * rgba.b) &&
      (rgba.r > 100.0/255.0) &&
      (rgba.g > 100.0/255.0)) // 黄颜色区域的透明度强制为1.0,保留黄色商品
      {
          baseMask = 1.0;
      }
      float fullMask = pow(clamp(baseMask / smoothness, 0.0, 1.0), 1.5);

      rgba.rgb = despillByAvg(rgba.rgb);
      rgba.a = fullMask;

      return rgba;
  }

  void main(void)
  {
      vec4 srcColor = texture2D(image, v_texCoord).rgba;
      gl_FragColor = ProcessChromaKey(srcColor, v_texCoord);
  }
`,lv=`
  attribute vec4 a_position;
  attribute vec2 a_texCoord;
  varying vec2 v_texCoord;
  void main () {
      gl_Position = a_position;
      v_texCoord = a_texCoord;
  }
`,uv=`
  precision mediump float;
  varying vec2 v_texCoord;

  uniform sampler2D screenTexture;

  uniform float videoWidth;
  uniform float videoHeight;

  vec4 blur(in vec2 vTextureCoord)
  {
      float alpha = 0.0;
      float dx = 1.0 / videoWidth;
      float dy = 1.0 / videoHeight;
      alpha +=  0.0625*texture2D(screenTexture, vTextureCoord - vec2(-dx, -dy)  ).a;
      alpha +=  0.1250*texture2D(screenTexture, vTextureCoord - vec2(0, -dy)  ).a;
      alpha +=  0.0625*texture2D(screenTexture, vTextureCoord - vec2(dx, -dy)  ).a;
      alpha +=  0.1250*texture2D(screenTexture, vTextureCoord - vec2(-dx, 0)  ).a;
      alpha +=  0.2500*texture2D(screenTexture, vTextureCoord).a;
      alpha +=  0.1250*texture2D(screenTexture, vTextureCoord - vec2(dx, 0)  ).a;
      alpha +=  0.0625*texture2D(screenTexture, vTextureCoord - vec2(-dx, dy)  ).a;
      alpha +=  0.1250*texture2D(screenTexture, vTextureCoord - vec2(0, dy)  ).a;
      alpha +=  0.0625*texture2D(screenTexture, vTextureCoord - vec2(dx, dy)  ).a;
      vec4 rgba = texture2D(screenTexture, vTextureCoord);
      rgba.a = alpha;
      return rgba;
  }

  void main(void)
  {
      gl_FragColor = blur(v_texCoord);
  }
`,dv=[-1,1,-1,-1,1,-1,1,-1,1,1,-1,1],hv=[0,1,0,0,1,0,1,0,1,1,0,1];function pv(){return typeof MediaStreamTrackProcessor<"u"&&typeof MediaStreamTrackGenerator<"u"}function fv(i){return i!=null&&typeof i.getVideoTracks=="function"&&typeof i.getAudioTracks=="function"}class mv{constructor(e,t,n,r,a){We(this,"canvas",null);We(this,"gl",null);We(this,"texture",null);We(this,"screenTexture",null);We(this,"mediaStream",null);We(this,"cutoutProgram",null);We(this,"getEdgeSmoothProgram",null);We(this,"frameBuffer",null);We(this,"onCompositeStream",null);We(this,"onReady");We(this,"onStop");We(this,"_ready",!1);We(this,"_inputVideo",null);We(this,"_outputStream",null);We(this,"_isSafariMode",!1);We(this,"_renderCallbackId",null);We(this,"_onLoadedMetadataBound",null);We(this,"_onCanPlayBound",null);We(this,"_fps",30);We(this,"_sourceVideo",null);We(this,"_ownsInputVideo",!0);We(this,"_safariRenderActive",!0);if(!fv(e)||typeof t!="function"){console.log("input parameters error!");return}this.mediaStream=e,this.onCompositeStream=t,this.onReady=n,this.onStop=r,this._fps=(a==null?void 0:a.fps)??30,this._sourceVideo=(a==null?void 0:a.sourceVideo)??null}loadShader(e,t){if(this.gl===null)throw Error("WebGLRenderingContext doesn't exist!");const n=this.gl.createShader(e);if(n===null)throw Error("createShader failed!");if(this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)===!1)throw this.gl.deleteShader(n),Error("An error occurred compiling the shaders");return n}initialize(){!this.mediaStream||!this.onCompositeStream||(pv()?this.initializeWithTrackProcessor():this.initializeWithSafariFallback())}initializeWithTrackProcessor(){if(!this.mediaStream||!this.onCompositeStream)return;const e=this.mediaStream.getVideoTracks()[0],t=this.mediaStream.getAudioTracks()[0],n=new MediaStreamTrackProcessor({track:e}),r=new MediaStreamTrackGenerator({kind:"video"}),a=async(c,h)=>{if(this.canvas===null&&this.initWebGL(c),this.canvas===null)throw Error("init webgl failed");this.updateFrame(c);const l=new VideoFrame(this.canvas,{alpha:"keep",timestamp:c.timestamp,duration:c.duration||void 0});c.close(),h.enqueue(l)},s=new TransformStream({transform:a});n.readable.pipeThrough(s).pipeTo(r.writable);const o=new MediaStream([r]);t&&o.addTrack(t),this.onCompositeStream(o)}initializeWithSafariFallback(){if(!this.mediaStream||!this.onCompositeStream)return;if(this._isSafariMode=!0,this._safariRenderActive=!0,!("requestVideoFrameCallback"in HTMLVideoElement.prototype)){console.error("Safari fallback requires requestVideoFrameCallback, which is not supported");return}let e;this._sourceVideo?(e=this._sourceVideo,this._ownsInputVideo=!1):(this._ownsInputVideo=!0,e=document.createElement("video"),e.playsInline=!0,e.muted=!0,e.autoplay=!0,e.setAttribute("playsinline","true"),e.setAttribute("webkit-playsinline","true"),document.body.appendChild(e)),this._inputVideo=e;const t=this.mediaStream.getAudioTracks()[0],n=()=>{const r=e.videoWidth,a=e.videoHeight;if(!r||!a){console.error("视频尺寸无效,无法启动 ChromaKeyProcessor");return}const s=document.createElement("canvas");s.width=r,s.height=a,s.style.position="absolute",s.style.visibility="hidden",s.style.width="1px",s.style.height="1px",s.style.top="-9999px",s.style.left="-9999px",document.body.appendChild(s),this.canvas=s,this.initWebGLForSafari(r,a),this._outputStream=s.captureStream(this._fps),t&&this._outputStream.addTrack(t),this.onCompositeStream&&this.onCompositeStream(this._outputStream);let o=!1,c=-1;const h=v=>{if(this._safariRenderActive){if(v!==c&&this.gl&&!this.gl.isContextLost())try{this.updateFrameFromVideo(e),c=v}catch(p){console.error("WebGL 渲染失败:",p),this.stop();return}this._safariRenderActive&&this._inputVideo&&!this._inputVideo.paused&&!this._inputVideo.ended&&(this._renderCallbackId=e.requestVideoFrameCallback(h))}},l=async()=>{if(!o){if(e.paused)try{await e.play()}catch(v){const p=v instanceof Error?v:new Error(String(v));if(this._ownsInputVideo)throw console.error("视频播放失败:",p),new Error(`ChromaKeyProcessor: 视频播放失败 - ${p.message}`)}this._safariRenderActive&&(o=!0,this._renderCallbackId=e.requestVideoFrameCallback(h),this._ready||(this._ready=!0,this.onReady&&this.onReady()))}},f=()=>{l().catch(v=>{console.error("启动视频播放时出错:",v)})};this._onCanPlayBound=f,e.addEventListener("canplay",f,{once:!0}),e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&l().catch(v=>{console.error("启动视频播放时出错:",v)})};this._onLoadedMetadataBound=n,this._ownsInputVideo?(e.addEventListener("loadedmetadata",n,{once:!0}),e.srcObject=this.mediaStream):e.videoWidth>0&&e.videoHeight>0?queueMicrotask(()=>n()):e.addEventListener("loadedmetadata",n,{once:!0})}initWebGL(e){const t=new OffscreenCanvas(e.codedWidth,e.codedHeight),n=t.getContext("webgl",{premultipliedAlpha:!1,alpha:!0});if(n==null)throw Error("Cant create gl context");this.canvas=t,this.gl=n,this.setupWebGLPrograms(e.codedWidth,e.codedHeight)}initWebGLForSafari(e,t){if(!(this.canvas instanceof HTMLCanvasElement))throw Error("Canvas must be HTMLCanvasElement for Safari mode");const n=this.canvas.getContext("webgl",{premultipliedAlpha:!1,alpha:!0});if(n==null)throw Error("Cant create gl context");this.gl=n,this.setupWebGLPrograms(e,t)}setupWebGLPrograms(e,t){if(!this.gl)throw Error("WebGL context not initialized");const n=this.gl;this.cutoutProgram=n.createProgram();const r=this.loadShader(n.VERTEX_SHADER,av),a=this.loadShader(n.FRAGMENT_SHADER,cv);if(!this.cutoutProgram)throw Error("no cutoutProgram!");if(n.attachShader(this.cutoutProgram,r),n.attachShader(this.cutoutProgram,a),n.linkProgram(this.cutoutProgram),n.getProgramParameter(this.cutoutProgram,n.LINK_STATUS)===!1)throw Error("Unable to initialize the shader program");this.getEdgeSmoothProgram=n.createProgram();const s=this.loadShader(n.VERTEX_SHADER,lv),o=this.loadShader(n.FRAGMENT_SHADER,uv);if(!this.getEdgeSmoothProgram)throw Error("no getEdgeSmoothProgram!");if(n.attachShader(this.getEdgeSmoothProgram,s),n.attachShader(this.getEdgeSmoothProgram,o),n.linkProgram(this.getEdgeSmoothProgram),n.getProgramParameter(this.getEdgeSmoothProgram,n.LINK_STATUS)===!1)throw Error("Unable to initialize the shader program");n.useProgram(this.cutoutProgram),n.uniform1f(n.getUniformLocation(this.cutoutProgram,"similarity"),.409),n.uniform1f(n.getUniformLocation(this.cutoutProgram,"smoothness"),.08),n.uniform1f(n.getUniformLocation(this.cutoutProgram,"videoWidth"),e),n.uniform1f(n.getUniformLocation(this.cutoutProgram,"videoHeight"),t),n.useProgram(this.getEdgeSmoothProgram),n.uniform1f(n.getUniformLocation(this.getEdgeSmoothProgram,"videoWidth"),e),n.uniform1f(n.getUniformLocation(this.getEdgeSmoothProgram,"videoHeight"),t);const c=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,c),n.bufferData(n.ARRAY_BUFFER,new Float32Array(dv),n.STATIC_DRAW);const h=n.getAttribLocation(this.cutoutProgram,"a_position");n.vertexAttribPointer(h,2,n.FLOAT,!1,Float32Array.BYTES_PER_ELEMENT*2,0),n.enableVertexAttribArray(h);const l=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,l),n.bufferData(n.ARRAY_BUFFER,new Float32Array(hv),n.STATIC_DRAW);const f=n.getAttribLocation(this.cutoutProgram,"a_texCoord");n.vertexAttribPointer(f,2,n.FLOAT,!1,Float32Array.BYTES_PER_ELEMENT*2,0),n.enableVertexAttribArray(f),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,1);const v=n.createTexture();if(v==null)throw Error("Create WebGL texture error");n.bindTexture(n.TEXTURE_2D,v),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([0,0,255,255])),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),this.texture=v,this.frameBuffer=n.createFramebuffer(),n.bindFramebuffer(n.FRAMEBUFFER,this.frameBuffer);const p=n.createTexture();if(p==null)throw Error("Create WebGL texture error");if(n.bindTexture(n.TEXTURE_2D,p),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,t,0,n.RGBA,n.UNSIGNED_BYTE,null),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),this.screenTexture=p,n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,this.screenTexture,0),n.checkFramebufferStatus(n.FRAMEBUFFER)!==n.FRAMEBUFFER_COMPLETE)throw Error("Framebuffer incomplete");n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null)}updateFrame(e){if(this.gl===null)throw Error("no webgl context!");this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.frameBuffer),this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.cutoutProgram),this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.drawArrays(this.gl.TRIANGLES,0,6),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.getEdgeSmoothProgram),this.gl.bindTexture(this.gl.TEXTURE_2D,this.screenTexture),this.gl.drawArrays(this.gl.TRIANGLES,0,6),this._ready||(this.gl.finish(),this._ready=!0,this.onReady&&this.onReady())}updateFrameFromVideo(e){if(this.gl===null)throw Error("no webgl context!");this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.frameBuffer),this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.cutoutProgram),this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.drawArrays(this.gl.TRIANGLES,0,6),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.getEdgeSmoothProgram),this.gl.bindTexture(this.gl.TEXTURE_2D,this.screenTexture),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}stop(){this._isSafariMode&&(this._safariRenderActive=!1,this._inputVideo&&this._renderCallbackId!==null&&"cancelVideoFrameCallback"in HTMLVideoElement.prototype&&this._inputVideo.cancelVideoFrameCallback(this._renderCallbackId),this._renderCallbackId=null,this._inputVideo&&(this._onLoadedMetadataBound&&(this._inputVideo.removeEventListener("loadedmetadata",this._onLoadedMetadataBound),this._onLoadedMetadataBound=null),this._onCanPlayBound&&(this._inputVideo.removeEventListener("canplay",this._onCanPlayBound),this._onCanPlayBound=null)),this._inputVideo&&this._ownsInputVideo&&(this._inputVideo.pause(),this._inputVideo.srcObject=null,this._inputVideo.parentNode&&this._inputVideo.parentNode.removeChild(this._inputVideo)),this._inputVideo=null,this._outputStream&&(this._outputStream.getTracks().forEach(e=>e.stop()),this._outputStream=null),this.canvas instanceof HTMLCanvasElement&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas)),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.gl&&(this.frameBuffer&&(this.gl.deleteFramebuffer(this.frameBuffer),this.frameBuffer=null),this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null),this.screenTexture&&(this.gl.deleteTexture(this.screenTexture),this.screenTexture=null),this.gl=null),this.canvas=null,this._ready=!1,this._isSafariMode=!1,this._renderCallbackId=null,this._ownsInputVideo=!0,this._sourceVideo=null,this.onStop&&this.onStop()}}/**
 * @license
 * Copyright 2010-2025 Three.js Authors
 * SPDX-License-Identifier: MIT
 */const oc="173",gv=0,Bh=1,vv=2,Vh=1,_v=2,Rn=3,Kn=0,yi=1,Tn=2,qn=0,Vr=1,Fh=2,Hh=3,Gh=4,Sv=5,hr=100,bv=101,yv=102,Ev=103,Rv=104,Tv=200,Av=201,Cv=202,wv=203,sc=204,ac=205,Mv=206,xv=207,Iv=208,Pv=209,Dv=210,Lv=211,Ov=212,Nv=213,kv=214,cc=0,lc=1,uc=2,Fr=3,dc=4,hc=5,pc=6,fc=7,zh=0,Uv=1,Bv=2,Yn=0,Vv=1,Fv=2,Hv=3,Gv=4,zv=5,Wv=6,jv=7,Wh=300,Hr=301,Gr=302,mc=303,gc=304,gs=306,vc=1e3,An=1001,_c=1002,en=1003,Xv=1004,vs=1005,Ei=1006,Sc=1007,pr=1008,Cn=1009,jh=1010,Xh=1011,Io=1012,bc=1013,fr=1014,wn=1015,Po=1016,yc=1017,Ec=1018,zr=1020,$h=35902,Kh=1021,qh=1022,tn=1023,Yh=1024,Jh=1025,Wr=1026,jr=1027,Qh=1028,Rc=1029,Zh=1030,Tc=1031,Ac=1033,_s=33776,Ss=33777,bs=33778,ys=33779,Cc=35840,wc=35841,Mc=35842,xc=35843,Ic=36196,Pc=37492,Dc=37496,Lc=37808,Oc=37809,Nc=37810,kc=37811,Uc=37812,Bc=37813,Vc=37814,Fc=37815,Hc=37816,Gc=37817,zc=37818,Wc=37819,jc=37820,Xc=37821,Es=36492,$c=36494,Kc=36495,ep=36283,qc=36284,Yc=36285,Jc=36286,$v=3200,Kv=3201,qv=0,Yv=1,Jn="",Wi="srgb",Xr="srgb-linear",Rs="linear",Mt="srgb",$r=7680,tp=519,Jv=512,Qv=513,Zv=514,ip=515,e0=516,t0=517,i0=518,n0=519,np=35044,rp="300 es",Mn=2e3,Ts=2001;class Kr{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const r=n[e];if(r!==void 0){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const r=n.slice(0);for(let a=0,s=r.length;a<s;a++)r[a].call(this,e);e.target=null}}}const oi=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],Qc=Math.PI/180,Zc=180/Math.PI;function Do(){const i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(oi[i&255]+oi[i>>8&255]+oi[i>>16&255]+oi[i>>24&255]+"-"+oi[e&255]+oi[e>>8&255]+"-"+oi[e>>16&15|64]+oi[e>>24&255]+"-"+oi[t&63|128]+oi[t>>8&255]+"-"+oi[t>>16&255]+oi[t>>24&255]+oi[n&255]+oi[n>>8&255]+oi[n>>16&255]+oi[n>>24&255]).toLowerCase()}function _t(i,e,t){return Math.max(e,Math.min(t,i))}function r0(i,e){return(i%e+e)%e}function el(i,e,t){return(1-t)*i+t*e}function Lo(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function Ri(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}class xt{constructor(e=0,t=0){xt.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=_t(this.x,e.x,t.x),this.y=_t(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=_t(this.x,e,t),this.y=_t(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(_t(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(_t(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),r=Math.sin(t),a=this.x-e.x,s=this.y-e.y;return this.x=a*n-s*r+e.x,this.y=a*r+s*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class dt{constructor(e,t,n,r,a,s,o,c,h){dt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,a,s,o,c,h)}set(e,t,n,r,a,s,o,c,h){const l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=a,l[5]=c,l[6]=n,l[7]=s,l[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,r=t.elements,a=this.elements,s=n[0],o=n[3],c=n[6],h=n[1],l=n[4],f=n[7],v=n[2],p=n[5],_=n[8],m=r[0],d=r[3],u=r[6],b=r[1],y=r[4],g=r[7],S=r[2],R=r[5],E=r[8];return a[0]=s*m+o*b+c*S,a[3]=s*d+o*y+c*R,a[6]=s*u+o*g+c*E,a[1]=h*m+l*b+f*S,a[4]=h*d+l*y+f*R,a[7]=h*u+l*g+f*E,a[2]=v*m+p*b+_*S,a[5]=v*d+p*y+_*R,a[8]=v*u+p*g+_*E,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],r=e[2],a=e[3],s=e[4],o=e[5],c=e[6],h=e[7],l=e[8];return t*s*l-t*o*h-n*a*l+n*o*c+r*a*h-r*s*c}invert(){const e=this.elements,t=e[0],n=e[1],r=e[2],a=e[3],s=e[4],o=e[5],c=e[6],h=e[7],l=e[8],f=l*s-o*h,v=o*c-l*a,p=h*a-s*c,_=t*f+n*v+r*p;if(_===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/_;return e[0]=f*m,e[1]=(r*h-l*n)*m,e[2]=(o*n-r*s)*m,e[3]=v*m,e[4]=(l*t-r*c)*m,e[5]=(r*a-o*t)*m,e[6]=p*m,e[7]=(n*c-h*t)*m,e[8]=(s*t-n*a)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,a,s,o){const c=Math.cos(a),h=Math.sin(a);return this.set(n*c,n*h,-n*(c*s+h*o)+s+e,-r*h,r*c,-r*(-h*s+c*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(tl.makeScale(e,t)),this}rotate(e){return this.premultiply(tl.makeRotation(-e)),this}translate(e,t){return this.premultiply(tl.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let r=0;r<9;r++)if(t[r]!==n[r])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const tl=new dt;function op(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function As(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function o0(){const i=As("canvas");return i.style.display="block",i}const sp={};function qr(i){i in sp||(sp[i]=!0,console.warn(i))}function s0(i,e,t){return new Promise(function(n,r){function a(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:r();break;case i.TIMEOUT_EXPIRED:setTimeout(a,t);break;default:n()}}setTimeout(a,t)})}function a0(i){const e=i.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}function c0(i){const e=i.elements;e[11]===-1?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=-e[14]+1)}const ap=new dt().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),cp=new dt().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function l0(){const i={enabled:!0,workingColorSpace:Xr,spaces:{},convert:function(r,a,s){return this.enabled===!1||a===s||!a||!s||(this.spaces[a].transfer===Mt&&(r.r=xn(r.r),r.g=xn(r.g),r.b=xn(r.b)),this.spaces[a].primaries!==this.spaces[s].primaries&&(r.applyMatrix3(this.spaces[a].toXYZ),r.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===Mt&&(r.r=Yr(r.r),r.g=Yr(r.g),r.b=Yr(r.b))),r},fromWorkingColorSpace:function(r,a){return this.convert(r,this.workingColorSpace,a)},toWorkingColorSpace:function(r,a){return this.convert(r,a,this.workingColorSpace)},getPrimaries:function(r){return this.spaces[r].primaries},getTransfer:function(r){return r===Jn?Rs:this.spaces[r].transfer},getLuminanceCoefficients:function(r,a=this.workingColorSpace){return r.fromArray(this.spaces[a].luminanceCoefficients)},define:function(r){Object.assign(this.spaces,r)},_getMatrix:function(r,a,s){return r.copy(this.spaces[a].toXYZ).multiply(this.spaces[s].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[Xr]:{primaries:e,whitePoint:n,transfer:Rs,toXYZ:ap,fromXYZ:cp,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Wi},outputColorSpaceConfig:{drawingBufferColorSpace:Wi}},[Wi]:{primaries:e,whitePoint:n,transfer:Mt,toXYZ:ap,fromXYZ:cp,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Wi}}}),i}const Et=l0();function xn(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function Yr(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let Jr;class u0{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{Jr===void 0&&(Jr=As("canvas")),Jr.width=e.width,Jr.height=e.height;const n=Jr.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),t=Jr}return t.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=As("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const r=n.getImageData(0,0,e.width,e.height),a=r.data;for(let s=0;s<a.length;s++)a[s]=xn(a[s]/255)*255;return n.putImageData(r,0,0),t}else if(e.data){const t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(xn(t[n]/255)*255):t[n]=xn(t[n]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let d0=0;class lp{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:d0++}),this.uuid=Do(),this.data=e,this.dataReady=!0,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const n={uuid:this.uuid,url:""},r=this.data;if(r!==null){let a;if(Array.isArray(r)){a=[];for(let s=0,o=r.length;s<o;s++)r[s].isDataTexture?a.push(il(r[s].image)):a.push(il(r[s]))}else a=il(r);n.url=a}return t||(e.images[this.uuid]=n),n}}function il(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?u0.getDataURL(i):i.data?{data:Array.from(i.data),width:i.width,height:i.height,type:i.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let h0=0;class ui extends Kr{constructor(e=ui.DEFAULT_IMAGE,t=ui.DEFAULT_MAPPING,n=An,r=An,a=Ei,s=pr,o=tn,c=Cn,h=ui.DEFAULT_ANISOTROPY,l=Jn){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:h0++}),this.uuid=Do(),this.name="",this.source=new lp(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=r,this.magFilter=a,this.minFilter=s,this.anisotropy=h,this.format=o,this.internalFormat=null,this.type=c,this.offset=new xt(0,0),this.repeat=new xt(1,1),this.center=new xt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new dt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=l,this.userData={},this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.pmremVersion=0}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Wh)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case vc:e.x=e.x-Math.floor(e.x);break;case An:e.x=e.x<0?0:1;break;case _c:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case vc:e.y=e.y-Math.floor(e.y);break;case An:e.y=e.y<0?0:1;break;case _c:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}ui.DEFAULT_IMAGE=null,ui.DEFAULT_MAPPING=Wh,ui.DEFAULT_ANISOTROPY=1;class Ft{constructor(e=0,t=0,n=0,r=1){Ft.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,r=this.z,a=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*r+s[12]*a,this.y=s[1]*t+s[5]*n+s[9]*r+s[13]*a,this.z=s[2]*t+s[6]*n+s[10]*r+s[14]*a,this.w=s[3]*t+s[7]*n+s[11]*r+s[15]*a,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,a;const c=e.elements,h=c[0],l=c[4],f=c[8],v=c[1],p=c[5],_=c[9],m=c[2],d=c[6],u=c[10];if(Math.abs(l-v)<.01&&Math.abs(f-m)<.01&&Math.abs(_-d)<.01){if(Math.abs(l+v)<.1&&Math.abs(f+m)<.1&&Math.abs(_+d)<.1&&Math.abs(h+p+u-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const y=(h+1)/2,g=(p+1)/2,S=(u+1)/2,R=(l+v)/4,E=(f+m)/4,I=(_+d)/4;return y>g&&y>S?y<.01?(n=0,r=.707106781,a=.707106781):(n=Math.sqrt(y),r=R/n,a=E/n):g>S?g<.01?(n=.707106781,r=0,a=.707106781):(r=Math.sqrt(g),n=R/r,a=I/r):S<.01?(n=.707106781,r=.707106781,a=0):(a=Math.sqrt(S),n=E/a,r=I/a),this.set(n,r,a,t),this}let b=Math.sqrt((d-_)*(d-_)+(f-m)*(f-m)+(v-l)*(v-l));return Math.abs(b)<.001&&(b=1),this.x=(d-_)/b,this.y=(f-m)/b,this.z=(v-l)/b,this.w=Math.acos((h+p+u-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=_t(this.x,e.x,t.x),this.y=_t(this.y,e.y,t.y),this.z=_t(this.z,e.z,t.z),this.w=_t(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=_t(this.x,e,t),this.y=_t(this.y,e,t),this.z=_t(this.z,e,t),this.w=_t(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(_t(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class p0 extends Kr{constructor(e=1,t=1,n={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new Ft(0,0,e,t),this.scissorTest=!1,this.viewport=new Ft(0,0,e,t);const r={width:e,height:t,depth:1};n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ei,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},n);const a=new ui(r,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace);a.flipY=!1,a.generateMipmaps=n.generateMipmaps,a.internalFormat=n.internalFormat,this.textures=[];const s=n.count;for(let o=0;o<s;o++)this.textures[o]=a.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,a=this.textures.length;r<a;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let n=0,r=e.textures.length;n<r;n++)this.textures[n]=e.textures[n].clone(),this.textures[n].isRenderTargetTexture=!0,this.textures[n].renderTarget=this;const t=Object.assign({},e.texture.image);return this.texture.source=new lp(t),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class mr extends p0{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class up extends ui{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=en,this.minFilter=en,this.wrapR=An,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class f0 extends ui{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=en,this.minFilter=en,this.wrapR=An,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Oo{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,a,s,o){let c=n[r+0],h=n[r+1],l=n[r+2],f=n[r+3];const v=a[s+0],p=a[s+1],_=a[s+2],m=a[s+3];if(o===0){e[t+0]=c,e[t+1]=h,e[t+2]=l,e[t+3]=f;return}if(o===1){e[t+0]=v,e[t+1]=p,e[t+2]=_,e[t+3]=m;return}if(f!==m||c!==v||h!==p||l!==_){let d=1-o;const u=c*v+h*p+l*_+f*m,b=u>=0?1:-1,y=1-u*u;if(y>Number.EPSILON){const S=Math.sqrt(y),R=Math.atan2(S,u*b);d=Math.sin(d*R)/S,o=Math.sin(o*R)/S}const g=o*b;if(c=c*d+v*g,h=h*d+p*g,l=l*d+_*g,f=f*d+m*g,d===1-o){const S=1/Math.sqrt(c*c+h*h+l*l+f*f);c*=S,h*=S,l*=S,f*=S}}e[t]=c,e[t+1]=h,e[t+2]=l,e[t+3]=f}static multiplyQuaternionsFlat(e,t,n,r,a,s){const o=n[r],c=n[r+1],h=n[r+2],l=n[r+3],f=a[s],v=a[s+1],p=a[s+2],_=a[s+3];return e[t]=o*_+l*f+c*p-h*v,e[t+1]=c*_+l*v+h*f-o*p,e[t+2]=h*_+l*p+o*v-c*f,e[t+3]=l*_-o*f-c*v-h*p,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,r=e._y,a=e._z,s=e._order,o=Math.cos,c=Math.sin,h=o(n/2),l=o(r/2),f=o(a/2),v=c(n/2),p=c(r/2),_=c(a/2);switch(s){case"XYZ":this._x=v*l*f+h*p*_,this._y=h*p*f-v*l*_,this._z=h*l*_+v*p*f,this._w=h*l*f-v*p*_;break;case"YXZ":this._x=v*l*f+h*p*_,this._y=h*p*f-v*l*_,this._z=h*l*_-v*p*f,this._w=h*l*f+v*p*_;break;case"ZXY":this._x=v*l*f-h*p*_,this._y=h*p*f+v*l*_,this._z=h*l*_+v*p*f,this._w=h*l*f-v*p*_;break;case"ZYX":this._x=v*l*f-h*p*_,this._y=h*p*f+v*l*_,this._z=h*l*_-v*p*f,this._w=h*l*f+v*p*_;break;case"YZX":this._x=v*l*f+h*p*_,this._y=h*p*f+v*l*_,this._z=h*l*_-v*p*f,this._w=h*l*f-v*p*_;break;case"XZY":this._x=v*l*f-h*p*_,this._y=h*p*f-v*l*_,this._z=h*l*_+v*p*f,this._w=h*l*f+v*p*_;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],r=t[4],a=t[8],s=t[1],o=t[5],c=t[9],h=t[2],l=t[6],f=t[10],v=n+o+f;if(v>0){const p=.5/Math.sqrt(v+1);this._w=.25/p,this._x=(l-c)*p,this._y=(a-h)*p,this._z=(s-r)*p}else if(n>o&&n>f){const p=2*Math.sqrt(1+n-o-f);this._w=(l-c)/p,this._x=.25*p,this._y=(r+s)/p,this._z=(a+h)/p}else if(o>f){const p=2*Math.sqrt(1+o-n-f);this._w=(a-h)/p,this._x=(r+s)/p,this._y=.25*p,this._z=(c+l)/p}else{const p=2*Math.sqrt(1+f-n-o);this._w=(s-r)/p,this._x=(a+h)/p,this._y=(c+l)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<Number.EPSILON?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(_t(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,r=e._y,a=e._z,s=e._w,o=t._x,c=t._y,h=t._z,l=t._w;return this._x=n*l+s*o+r*h-a*c,this._y=r*l+s*c+a*o-n*h,this._z=a*l+s*h+n*c-r*o,this._w=s*l-n*o-r*c-a*h,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const n=this._x,r=this._y,a=this._z,s=this._w;let o=s*e._w+n*e._x+r*e._y+a*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=s,this._x=n,this._y=r,this._z=a,this;const c=1-o*o;if(c<=Number.EPSILON){const p=1-t;return this._w=p*s+t*this._w,this._x=p*n+t*this._x,this._y=p*r+t*this._y,this._z=p*a+t*this._z,this.normalize(),this}const h=Math.sqrt(c),l=Math.atan2(h,o),f=Math.sin((1-t)*l)/h,v=Math.sin(t*l)/h;return this._w=s*f+this._w*v,this._x=n*f+this._x*v,this._y=r*f+this._y*v,this._z=a*f+this._z*v,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),a=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),a*Math.sin(t),a*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class we{constructor(e=0,t=0,n=0){we.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(dp.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(dp.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,r=this.z,a=e.elements;return this.x=a[0]*t+a[3]*n+a[6]*r,this.y=a[1]*t+a[4]*n+a[7]*r,this.z=a[2]*t+a[5]*n+a[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,r=this.z,a=e.elements,s=1/(a[3]*t+a[7]*n+a[11]*r+a[15]);return this.x=(a[0]*t+a[4]*n+a[8]*r+a[12])*s,this.y=(a[1]*t+a[5]*n+a[9]*r+a[13])*s,this.z=(a[2]*t+a[6]*n+a[10]*r+a[14])*s,this}applyQuaternion(e){const t=this.x,n=this.y,r=this.z,a=e.x,s=e.y,o=e.z,c=e.w,h=2*(s*r-o*n),l=2*(o*t-a*r),f=2*(a*n-s*t);return this.x=t+c*h+s*f-o*l,this.y=n+c*l+o*h-a*f,this.z=r+c*f+a*l-s*h,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,r=this.z,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r,this.y=a[1]*t+a[5]*n+a[9]*r,this.z=a[2]*t+a[6]*n+a[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=_t(this.x,e.x,t.x),this.y=_t(this.y,e.y,t.y),this.z=_t(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=_t(this.x,e,t),this.y=_t(this.y,e,t),this.z=_t(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(_t(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,r=e.y,a=e.z,s=t.x,o=t.y,c=t.z;return this.x=r*c-a*o,this.y=a*s-n*c,this.z=n*o-r*s,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return nl.copy(this).projectOnVector(e),this.sub(nl)}reflect(e){return this.sub(nl.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(_t(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const nl=new we,dp=new Oo;class No{constructor(e=new we(1/0,1/0,1/0),t=new we(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(nn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(nn.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=nn.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(n!==void 0){const a=n.getAttribute("position");if(t===!0&&a!==void 0&&e.isInstancedMesh!==!0)for(let s=0,o=a.count;s<o;s++)e.isMesh===!0?e.getVertexPosition(s,nn):nn.fromBufferAttribute(a,s),nn.applyMatrix4(e.matrixWorld),this.expandByPoint(nn);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Cs.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),Cs.copy(n.boundingBox)),Cs.applyMatrix4(e.matrixWorld),this.union(Cs)}const r=e.children;for(let a=0,s=r.length;a<s;a++)this.expandByObject(r[a],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,nn),nn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(ko),ws.subVectors(this.max,ko),Qr.subVectors(e.a,ko),Zr.subVectors(e.b,ko),eo.subVectors(e.c,ko),Qn.subVectors(Zr,Qr),Zn.subVectors(eo,Zr),gr.subVectors(Qr,eo);let t=[0,-Qn.z,Qn.y,0,-Zn.z,Zn.y,0,-gr.z,gr.y,Qn.z,0,-Qn.x,Zn.z,0,-Zn.x,gr.z,0,-gr.x,-Qn.y,Qn.x,0,-Zn.y,Zn.x,0,-gr.y,gr.x,0];return!rl(t,Qr,Zr,eo,ws)||(t=[1,0,0,0,1,0,0,0,1],!rl(t,Qr,Zr,eo,ws))?!1:(Ms.crossVectors(Qn,Zn),t=[Ms.x,Ms.y,Ms.z],rl(t,Qr,Zr,eo,ws))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,nn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(nn).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(In[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),In[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),In[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),In[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),In[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),In[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),In[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),In[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(In),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const In=[new we,new we,new we,new we,new we,new we,new we,new we],nn=new we,Cs=new No,Qr=new we,Zr=new we,eo=new we,Qn=new we,Zn=new we,gr=new we,ko=new we,ws=new we,Ms=new we,vr=new we;function rl(i,e,t,n,r){for(let a=0,s=i.length-3;a<=s;a+=3){vr.fromArray(i,a);const o=r.x*Math.abs(vr.x)+r.y*Math.abs(vr.y)+r.z*Math.abs(vr.z),c=e.dot(vr),h=t.dot(vr),l=n.dot(vr);if(Math.max(-Math.max(c,h,l),Math.min(c,h,l))>o)return!1}return!0}const m0=new No,Uo=new we,ol=new we;class sl{constructor(e=new we,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):m0.setFromPoints(e).getCenter(n);let r=0;for(let a=0,s=e.length;a<s;a++)r=Math.max(r,n.distanceToSquared(e[a]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Uo.subVectors(e,this.center);const t=Uo.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),r=(n-this.radius)*.5;this.center.addScaledVector(Uo,r/n),this.radius+=r}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(ol.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Uo.copy(e.center).add(ol)),this.expandByPoint(Uo.copy(e.center).sub(ol))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const Pn=new we,al=new we,xs=new we,er=new we,cl=new we,Is=new we,ll=new we;class g0{constructor(e=new we,t=new we(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Pn)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Pn.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Pn.copy(this.origin).addScaledVector(this.direction,t),Pn.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){al.copy(e).add(t).multiplyScalar(.5),xs.copy(t).sub(e).normalize(),er.copy(this.origin).sub(al);const a=e.distanceTo(t)*.5,s=-this.direction.dot(xs),o=er.dot(this.direction),c=-er.dot(xs),h=er.lengthSq(),l=Math.abs(1-s*s);let f,v,p,_;if(l>0)if(f=s*c-o,v=s*o-c,_=a*l,f>=0)if(v>=-_)if(v<=_){const m=1/l;f*=m,v*=m,p=f*(f+s*v+2*o)+v*(s*f+v+2*c)+h}else v=a,f=Math.max(0,-(s*v+o)),p=-f*f+v*(v+2*c)+h;else v=-a,f=Math.max(0,-(s*v+o)),p=-f*f+v*(v+2*c)+h;else v<=-_?(f=Math.max(0,-(-s*a+o)),v=f>0?-a:Math.min(Math.max(-a,-c),a),p=-f*f+v*(v+2*c)+h):v<=_?(f=0,v=Math.min(Math.max(-a,-c),a),p=v*(v+2*c)+h):(f=Math.max(0,-(s*a+o)),v=f>0?a:Math.min(Math.max(-a,-c),a),p=-f*f+v*(v+2*c)+h);else v=s>0?-a:a,f=Math.max(0,-(s*v+o)),p=-f*f+v*(v+2*c)+h;return n&&n.copy(this.origin).addScaledVector(this.direction,f),r&&r.copy(al).addScaledVector(xs,v),p}intersectSphere(e,t){Pn.subVectors(e.center,this.origin);const n=Pn.dot(this.direction),r=Pn.dot(Pn)-n*n,a=e.radius*e.radius;if(r>a)return null;const s=Math.sqrt(a-r),o=n-s,c=n+s;return c<0?null:o<0?this.at(c,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,a,s,o,c;const h=1/this.direction.x,l=1/this.direction.y,f=1/this.direction.z,v=this.origin;return h>=0?(n=(e.min.x-v.x)*h,r=(e.max.x-v.x)*h):(n=(e.max.x-v.x)*h,r=(e.min.x-v.x)*h),l>=0?(a=(e.min.y-v.y)*l,s=(e.max.y-v.y)*l):(a=(e.max.y-v.y)*l,s=(e.min.y-v.y)*l),n>s||a>r||((a>n||isNaN(n))&&(n=a),(s<r||isNaN(r))&&(r=s),f>=0?(o=(e.min.z-v.z)*f,c=(e.max.z-v.z)*f):(o=(e.max.z-v.z)*f,c=(e.min.z-v.z)*f),n>c||o>r)||((o>n||n!==n)&&(n=o),(c<r||r!==r)&&(r=c),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,Pn)!==null}intersectTriangle(e,t,n,r,a){cl.subVectors(t,e),Is.subVectors(n,e),ll.crossVectors(cl,Is);let s=this.direction.dot(ll),o;if(s>0){if(r)return null;o=1}else if(s<0)o=-1,s=-s;else return null;er.subVectors(this.origin,e);const c=o*this.direction.dot(Is.crossVectors(er,Is));if(c<0)return null;const h=o*this.direction.dot(cl.cross(er));if(h<0||c+h>s)return null;const l=-o*er.dot(ll);return l<0?null:this.at(l/s,a)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class jt{constructor(e,t,n,r,a,s,o,c,h,l,f,v,p,_,m,d){jt.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,r,a,s,o,c,h,l,f,v,p,_,m,d)}set(e,t,n,r,a,s,o,c,h,l,f,v,p,_,m,d){const u=this.elements;return u[0]=e,u[4]=t,u[8]=n,u[12]=r,u[1]=a,u[5]=s,u[9]=o,u[13]=c,u[2]=h,u[6]=l,u[10]=f,u[14]=v,u[3]=p,u[7]=_,u[11]=m,u[15]=d,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new jt().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,r=1/to.setFromMatrixColumn(e,0).length(),a=1/to.setFromMatrixColumn(e,1).length(),s=1/to.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*a,t[5]=n[5]*a,t[6]=n[6]*a,t[7]=0,t[8]=n[8]*s,t[9]=n[9]*s,t[10]=n[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,r=e.y,a=e.z,s=Math.cos(n),o=Math.sin(n),c=Math.cos(r),h=Math.sin(r),l=Math.cos(a),f=Math.sin(a);if(e.order==="XYZ"){const v=s*l,p=s*f,_=o*l,m=o*f;t[0]=c*l,t[4]=-c*f,t[8]=h,t[1]=p+_*h,t[5]=v-m*h,t[9]=-o*c,t[2]=m-v*h,t[6]=_+p*h,t[10]=s*c}else if(e.order==="YXZ"){const v=c*l,p=c*f,_=h*l,m=h*f;t[0]=v+m*o,t[4]=_*o-p,t[8]=s*h,t[1]=s*f,t[5]=s*l,t[9]=-o,t[2]=p*o-_,t[6]=m+v*o,t[10]=s*c}else if(e.order==="ZXY"){const v=c*l,p=c*f,_=h*l,m=h*f;t[0]=v-m*o,t[4]=-s*f,t[8]=_+p*o,t[1]=p+_*o,t[5]=s*l,t[9]=m-v*o,t[2]=-s*h,t[6]=o,t[10]=s*c}else if(e.order==="ZYX"){const v=s*l,p=s*f,_=o*l,m=o*f;t[0]=c*l,t[4]=_*h-p,t[8]=v*h+m,t[1]=c*f,t[5]=m*h+v,t[9]=p*h-_,t[2]=-h,t[6]=o*c,t[10]=s*c}else if(e.order==="YZX"){const v=s*c,p=s*h,_=o*c,m=o*h;t[0]=c*l,t[4]=m-v*f,t[8]=_*f+p,t[1]=f,t[5]=s*l,t[9]=-o*l,t[2]=-h*l,t[6]=p*f+_,t[10]=v-m*f}else if(e.order==="XZY"){const v=s*c,p=s*h,_=o*c,m=o*h;t[0]=c*l,t[4]=-f,t[8]=h*l,t[1]=v*f+m,t[5]=s*l,t[9]=p*f-_,t[2]=_*f-p,t[6]=o*l,t[10]=m*f+v}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(v0,e,_0)}lookAt(e,t,n){const r=this.elements;return Di.subVectors(e,t),Di.lengthSq()===0&&(Di.z=1),Di.normalize(),tr.crossVectors(n,Di),tr.lengthSq()===0&&(Math.abs(n.z)===1?Di.x+=1e-4:Di.z+=1e-4,Di.normalize(),tr.crossVectors(n,Di)),tr.normalize(),Ps.crossVectors(Di,tr),r[0]=tr.x,r[4]=Ps.x,r[8]=Di.x,r[1]=tr.y,r[5]=Ps.y,r[9]=Di.y,r[2]=tr.z,r[6]=Ps.z,r[10]=Di.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,r=t.elements,a=this.elements,s=n[0],o=n[4],c=n[8],h=n[12],l=n[1],f=n[5],v=n[9],p=n[13],_=n[2],m=n[6],d=n[10],u=n[14],b=n[3],y=n[7],g=n[11],S=n[15],R=r[0],E=r[4],I=r[8],C=r[12],A=r[1],w=r[5],N=r[9],M=r[13],D=r[2],L=r[6],P=r[10],x=r[14],T=r[3],O=r[7],k=r[11],H=r[15];return a[0]=s*R+o*A+c*D+h*T,a[4]=s*E+o*w+c*L+h*O,a[8]=s*I+o*N+c*P+h*k,a[12]=s*C+o*M+c*x+h*H,a[1]=l*R+f*A+v*D+p*T,a[5]=l*E+f*w+v*L+p*O,a[9]=l*I+f*N+v*P+p*k,a[13]=l*C+f*M+v*x+p*H,a[2]=_*R+m*A+d*D+u*T,a[6]=_*E+m*w+d*L+u*O,a[10]=_*I+m*N+d*P+u*k,a[14]=_*C+m*M+d*x+u*H,a[3]=b*R+y*A+g*D+S*T,a[7]=b*E+y*w+g*L+S*O,a[11]=b*I+y*N+g*P+S*k,a[15]=b*C+y*M+g*x+S*H,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],r=e[8],a=e[12],s=e[1],o=e[5],c=e[9],h=e[13],l=e[2],f=e[6],v=e[10],p=e[14],_=e[3],m=e[7],d=e[11],u=e[15];return _*(+a*c*f-r*h*f-a*o*v+n*h*v+r*o*p-n*c*p)+m*(+t*c*p-t*h*v+a*s*v-r*s*p+r*h*l-a*c*l)+d*(+t*h*f-t*o*p-a*s*f+n*s*p+a*o*l-n*h*l)+u*(-r*o*l-t*c*f+t*o*v+r*s*f-n*s*v+n*c*l)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],r=e[2],a=e[3],s=e[4],o=e[5],c=e[6],h=e[7],l=e[8],f=e[9],v=e[10],p=e[11],_=e[12],m=e[13],d=e[14],u=e[15],b=f*d*h-m*v*h+m*c*p-o*d*p-f*c*u+o*v*u,y=_*v*h-l*d*h-_*c*p+s*d*p+l*c*u-s*v*u,g=l*m*h-_*f*h+_*o*p-s*m*p-l*o*u+s*f*u,S=_*f*c-l*m*c-_*o*v+s*m*v+l*o*d-s*f*d,R=t*b+n*y+r*g+a*S;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const E=1/R;return e[0]=b*E,e[1]=(m*v*a-f*d*a-m*r*p+n*d*p+f*r*u-n*v*u)*E,e[2]=(o*d*a-m*c*a+m*r*h-n*d*h-o*r*u+n*c*u)*E,e[3]=(f*c*a-o*v*a-f*r*h+n*v*h+o*r*p-n*c*p)*E,e[4]=y*E,e[5]=(l*d*a-_*v*a+_*r*p-t*d*p-l*r*u+t*v*u)*E,e[6]=(_*c*a-s*d*a-_*r*h+t*d*h+s*r*u-t*c*u)*E,e[7]=(s*v*a-l*c*a+l*r*h-t*v*h-s*r*p+t*c*p)*E,e[8]=g*E,e[9]=(_*f*a-l*m*a-_*n*p+t*m*p+l*n*u-t*f*u)*E,e[10]=(s*m*a-_*o*a+_*n*h-t*m*h-s*n*u+t*o*u)*E,e[11]=(l*o*a-s*f*a-l*n*h+t*f*h+s*n*p-t*o*p)*E,e[12]=S*E,e[13]=(l*m*r-_*f*r+_*n*v-t*m*v-l*n*d+t*f*d)*E,e[14]=(_*o*r-s*m*r-_*n*c+t*m*c+s*n*d-t*o*d)*E,e[15]=(s*f*r-l*o*r+l*n*c-t*f*c-s*n*v+t*o*v)*E,this}scale(e){const t=this.elements,n=e.x,r=e.y,a=e.z;return t[0]*=n,t[4]*=r,t[8]*=a,t[1]*=n,t[5]*=r,t[9]*=a,t[2]*=n,t[6]*=r,t[10]*=a,t[3]*=n,t[7]*=r,t[11]*=a,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),r=Math.sin(t),a=1-n,s=e.x,o=e.y,c=e.z,h=a*s,l=a*o;return this.set(h*s+n,h*o-r*c,h*c+r*o,0,h*o+r*c,l*o+n,l*c-r*s,0,h*c-r*o,l*c+r*s,a*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,a,s){return this.set(1,n,a,0,e,1,s,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){const r=this.elements,a=t._x,s=t._y,o=t._z,c=t._w,h=a+a,l=s+s,f=o+o,v=a*h,p=a*l,_=a*f,m=s*l,d=s*f,u=o*f,b=c*h,y=c*l,g=c*f,S=n.x,R=n.y,E=n.z;return r[0]=(1-(m+u))*S,r[1]=(p+g)*S,r[2]=(_-y)*S,r[3]=0,r[4]=(p-g)*R,r[5]=(1-(v+u))*R,r[6]=(d+b)*R,r[7]=0,r[8]=(_+y)*E,r[9]=(d-b)*E,r[10]=(1-(v+m))*E,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){const r=this.elements;let a=to.set(r[0],r[1],r[2]).length();const s=to.set(r[4],r[5],r[6]).length(),o=to.set(r[8],r[9],r[10]).length();this.determinant()<0&&(a=-a),e.x=r[12],e.y=r[13],e.z=r[14],rn.copy(this);const h=1/a,l=1/s,f=1/o;return rn.elements[0]*=h,rn.elements[1]*=h,rn.elements[2]*=h,rn.elements[4]*=l,rn.elements[5]*=l,rn.elements[6]*=l,rn.elements[8]*=f,rn.elements[9]*=f,rn.elements[10]*=f,t.setFromRotationMatrix(rn),n.x=a,n.y=s,n.z=o,this}makePerspective(e,t,n,r,a,s,o=Mn){const c=this.elements,h=2*a/(t-e),l=2*a/(n-r),f=(t+e)/(t-e),v=(n+r)/(n-r);let p,_;if(o===Mn)p=-(s+a)/(s-a),_=-2*s*a/(s-a);else if(o===Ts)p=-s/(s-a),_=-s*a/(s-a);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=h,c[4]=0,c[8]=f,c[12]=0,c[1]=0,c[5]=l,c[9]=v,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=_,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,a,s,o=Mn){const c=this.elements,h=1/(t-e),l=1/(n-r),f=1/(s-a),v=(t+e)*h,p=(n+r)*l;let _,m;if(o===Mn)_=(s+a)*f,m=-2*f;else if(o===Ts)_=a*f,m=-1*f;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=2*h,c[4]=0,c[8]=0,c[12]=-v,c[1]=0,c[5]=2*l,c[9]=0,c[13]=-p,c[2]=0,c[6]=0,c[10]=m,c[14]=-_,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let r=0;r<16;r++)if(t[r]!==n[r])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const to=new we,rn=new jt,v0=new we(0,0,0),_0=new we(1,1,1),tr=new we,Ps=new we,Di=new we,hp=new jt,pp=new Oo;class Dn{constructor(e=0,t=0,n=0,r=Dn.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=r}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const r=e.elements,a=r[0],s=r[4],o=r[8],c=r[1],h=r[5],l=r[9],f=r[2],v=r[6],p=r[10];switch(t){case"XYZ":this._y=Math.asin(_t(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,p),this._z=Math.atan2(-s,a)):(this._x=Math.atan2(v,h),this._z=0);break;case"YXZ":this._x=Math.asin(-_t(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,p),this._z=Math.atan2(c,h)):(this._y=Math.atan2(-f,a),this._z=0);break;case"ZXY":this._x=Math.asin(_t(v,-1,1)),Math.abs(v)<.9999999?(this._y=Math.atan2(-f,p),this._z=Math.atan2(-s,h)):(this._y=0,this._z=Math.atan2(c,a));break;case"ZYX":this._y=Math.asin(-_t(f,-1,1)),Math.abs(f)<.9999999?(this._x=Math.atan2(v,p),this._z=Math.atan2(c,a)):(this._x=0,this._z=Math.atan2(-s,h));break;case"YZX":this._z=Math.asin(_t(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-l,h),this._y=Math.atan2(-f,a)):(this._x=0,this._y=Math.atan2(o,p));break;case"XZY":this._z=Math.asin(-_t(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(v,h),this._y=Math.atan2(o,a)):(this._x=Math.atan2(-l,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return hp.makeRotationFromQuaternion(e),this.setFromRotationMatrix(hp,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return pp.setFromEuler(this),this.setFromQuaternion(pp,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Dn.DEFAULT_ORDER="XYZ";class fp{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let S0=0;const mp=new we,io=new Oo,Ln=new jt,Ds=new we,Bo=new we,b0=new we,y0=new Oo,gp=new we(1,0,0),vp=new we(0,1,0),_p=new we(0,0,1),Sp={type:"added"},E0={type:"removed"},no={type:"childadded",child:null},ul={type:"childremoved",child:null};class Li extends Kr{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:S0++}),this.uuid=Do(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Li.DEFAULT_UP.clone();const e=new we,t=new Dn,n=new Oo,r=new we(1,1,1);function a(){n.setFromEuler(t,!1)}function s(){t.setFromQuaternion(n,void 0,!1)}t._onChange(a),n._onChange(s),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:r},modelViewMatrix:{value:new jt},normalMatrix:{value:new dt}}),this.matrix=new jt,this.matrixWorld=new jt,this.matrixAutoUpdate=Li.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Li.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new fp,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return io.setFromAxisAngle(e,t),this.quaternion.multiply(io),this}rotateOnWorldAxis(e,t){return io.setFromAxisAngle(e,t),this.quaternion.premultiply(io),this}rotateX(e){return this.rotateOnAxis(gp,e)}rotateY(e){return this.rotateOnAxis(vp,e)}rotateZ(e){return this.rotateOnAxis(_p,e)}translateOnAxis(e,t){return mp.copy(e).applyQuaternion(this.quaternion),this.position.add(mp.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(gp,e)}translateY(e){return this.translateOnAxis(vp,e)}translateZ(e){return this.translateOnAxis(_p,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Ln.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Ds.copy(e):Ds.set(e,t,n);const r=this.parent;this.updateWorldMatrix(!0,!1),Bo.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Ln.lookAt(Bo,Ds,this.up):Ln.lookAt(Ds,Bo,this.up),this.quaternion.setFromRotationMatrix(Ln),r&&(Ln.extractRotation(r.matrixWorld),io.setFromRotationMatrix(Ln),this.quaternion.premultiply(io.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Sp),no.child=e,this.dispatchEvent(no),no.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(E0),ul.child=e,this.dispatchEvent(ul),ul.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Ln.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Ln.multiply(e.parent.matrixWorld)),e.applyMatrix4(Ln),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Sp),no.child=e,this.dispatchEvent(no),no.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){const s=this.children[n].getObjectByProperty(e,t);if(s!==void 0)return s}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const r=this.children;for(let a=0,s=r.length;a<s;a++)r[a].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Bo,e,b0),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Bo,y0,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){const n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const r=this.children;for(let a=0,s=r.length;a<s;a++)r[a].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const r={};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.castShadow===!0&&(r.castShadow=!0),this.receiveShadow===!0&&(r.receiveShadow=!0),this.visible===!1&&(r.visible=!1),this.frustumCulled===!1&&(r.frustumCulled=!1),this.renderOrder!==0&&(r.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.visibility=this._visibility,r.active=this._active,r.bounds=this._bounds.map(o=>({boxInitialized:o.boxInitialized,boxMin:o.box.min.toArray(),boxMax:o.box.max.toArray(),sphereInitialized:o.sphereInitialized,sphereRadius:o.sphere.radius,sphereCenter:o.sphere.center.toArray()})),r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.geometryCount=this._geometryCount,r.matricesTexture=this._matricesTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere={center:r.boundingSphere.center.toArray(),radius:r.boundingSphere.radius}),this.boundingBox!==null&&(r.boundingBox={min:r.boundingBox.min.toArray(),max:r.boundingBox.max.toArray()}));function a(o,c){return o[c.uuid]===void 0&&(o[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=a(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const c=o.shapes;if(Array.isArray(c))for(let h=0,l=c.length;h<l;h++){const f=c[h];a(e.shapes,f)}else a(e.shapes,c)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(a(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let c=0,h=this.material.length;c<h;c++)o.push(a(e.materials,this.material[c]));r.material=o}else r.material=a(e.materials,this.material);if(this.children.length>0){r.children=[];for(let o=0;o<this.children.length;o++)r.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let o=0;o<this.animations.length;o++){const c=this.animations[o];r.animations.push(a(e.animations,c))}}if(t){const o=s(e.geometries),c=s(e.materials),h=s(e.textures),l=s(e.images),f=s(e.shapes),v=s(e.skeletons),p=s(e.animations),_=s(e.nodes);o.length>0&&(n.geometries=o),c.length>0&&(n.materials=c),h.length>0&&(n.textures=h),l.length>0&&(n.images=l),f.length>0&&(n.shapes=f),v.length>0&&(n.skeletons=v),p.length>0&&(n.animations=p),_.length>0&&(n.nodes=_)}return n.object=r,n;function s(o){const c=[];for(const h in o){const l=o[h];delete l.metadata,c.push(l)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){const r=e.children[n];this.add(r.clone())}return this}}Li.DEFAULT_UP=new we(0,1,0),Li.DEFAULT_MATRIX_AUTO_UPDATE=!0,Li.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const on=new we,On=new we,dl=new we,Nn=new we,ro=new we,oo=new we,bp=new we,hl=new we,pl=new we,fl=new we,ml=new Ft,gl=new Ft,vl=new Ft;class sn{constructor(e=new we,t=new we,n=new we){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),on.subVectors(e,t),r.cross(on);const a=r.lengthSq();return a>0?r.multiplyScalar(1/Math.sqrt(a)):r.set(0,0,0)}static getBarycoord(e,t,n,r,a){on.subVectors(r,t),On.subVectors(n,t),dl.subVectors(e,t);const s=on.dot(on),o=on.dot(On),c=on.dot(dl),h=On.dot(On),l=On.dot(dl),f=s*h-o*o;if(f===0)return a.set(0,0,0),null;const v=1/f,p=(h*c-o*l)*v,_=(s*l-o*c)*v;return a.set(1-p-_,_,p)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Nn)===null?!1:Nn.x>=0&&Nn.y>=0&&Nn.x+Nn.y<=1}static getInterpolation(e,t,n,r,a,s,o,c){return this.getBarycoord(e,t,n,r,Nn)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(a,Nn.x),c.addScaledVector(s,Nn.y),c.addScaledVector(o,Nn.z),c)}static getInterpolatedAttribute(e,t,n,r,a,s){return ml.setScalar(0),gl.setScalar(0),vl.setScalar(0),ml.fromBufferAttribute(e,t),gl.fromBufferAttribute(e,n),vl.fromBufferAttribute(e,r),s.setScalar(0),s.addScaledVector(ml,a.x),s.addScaledVector(gl,a.y),s.addScaledVector(vl,a.z),s}static isFrontFacing(e,t,n,r){return on.subVectors(n,t),On.subVectors(e,t),on.cross(On).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return on.subVectors(this.c,this.b),On.subVectors(this.a,this.b),on.cross(On).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return sn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return sn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,r,a){return sn.getInterpolation(e,this.a,this.b,this.c,t,n,r,a)}containsPoint(e){return sn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return sn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,r=this.b,a=this.c;let s,o;ro.subVectors(r,n),oo.subVectors(a,n),hl.subVectors(e,n);const c=ro.dot(hl),h=oo.dot(hl);if(c<=0&&h<=0)return t.copy(n);pl.subVectors(e,r);const l=ro.dot(pl),f=oo.dot(pl);if(l>=0&&f<=l)return t.copy(r);const v=c*f-l*h;if(v<=0&&c>=0&&l<=0)return s=c/(c-l),t.copy(n).addScaledVector(ro,s);fl.subVectors(e,a);const p=ro.dot(fl),_=oo.dot(fl);if(_>=0&&p<=_)return t.copy(a);const m=p*h-c*_;if(m<=0&&h>=0&&_<=0)return o=h/(h-_),t.copy(n).addScaledVector(oo,o);const d=l*_-p*f;if(d<=0&&f-l>=0&&p-_>=0)return bp.subVectors(a,r),o=(f-l)/(f-l+(p-_)),t.copy(r).addScaledVector(bp,o);const u=1/(d+m+v);return s=m*u,o=v*u,t.copy(n).addScaledVector(ro,s).addScaledVector(oo,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const yp={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ir={h:0,s:0,l:0},Ls={h:0,s:0,l:0};function _l(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}class It{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const r=e;r&&r.isColor?this.copy(r):typeof r=="number"?this.setHex(r):typeof r=="string"&&this.setStyle(r)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Wi){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Et.toWorkingColorSpace(this,t),this}setRGB(e,t,n,r=Et.workingColorSpace){return this.r=e,this.g=t,this.b=n,Et.toWorkingColorSpace(this,r),this}setHSL(e,t,n,r=Et.workingColorSpace){if(e=r0(e,1),t=_t(t,0,1),n=_t(n,0,1),t===0)this.r=this.g=this.b=n;else{const a=n<=.5?n*(1+t):n+t-n*t,s=2*n-a;this.r=_l(s,a,e+1/3),this.g=_l(s,a,e),this.b=_l(s,a,e-1/3)}return Et.toWorkingColorSpace(this,r),this}setStyle(e,t=Wi){function n(a){a!==void 0&&parseFloat(a)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let a;const s=r[1],o=r[2];switch(s){case"rgb":case"rgba":if(a=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(a[4]),this.setRGB(Math.min(255,parseInt(a[1],10))/255,Math.min(255,parseInt(a[2],10))/255,Math.min(255,parseInt(a[3],10))/255,t);if(a=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(a[4]),this.setRGB(Math.min(100,parseInt(a[1],10))/100,Math.min(100,parseInt(a[2],10))/100,Math.min(100,parseInt(a[3],10))/100,t);break;case"hsl":case"hsla":if(a=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(a[4]),this.setHSL(parseFloat(a[1])/360,parseFloat(a[2])/100,parseFloat(a[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){const a=r[1],s=a.length;if(s===3)return this.setRGB(parseInt(a.charAt(0),16)/15,parseInt(a.charAt(1),16)/15,parseInt(a.charAt(2),16)/15,t);if(s===6)return this.setHex(parseInt(a,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Wi){const n=yp[e.toLowerCase()];return n!==void 0?this.setHex(n,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=xn(e.r),this.g=xn(e.g),this.b=xn(e.b),this}copyLinearToSRGB(e){return this.r=Yr(e.r),this.g=Yr(e.g),this.b=Yr(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Wi){return Et.fromWorkingColorSpace(si.copy(this),e),Math.round(_t(si.r*255,0,255))*65536+Math.round(_t(si.g*255,0,255))*256+Math.round(_t(si.b*255,0,255))}getHexString(e=Wi){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Et.workingColorSpace){Et.fromWorkingColorSpace(si.copy(this),t);const n=si.r,r=si.g,a=si.b,s=Math.max(n,r,a),o=Math.min(n,r,a);let c,h;const l=(o+s)/2;if(o===s)c=0,h=0;else{const f=s-o;switch(h=l<=.5?f/(s+o):f/(2-s-o),s){case n:c=(r-a)/f+(r<a?6:0);break;case r:c=(a-n)/f+2;break;case a:c=(n-r)/f+4;break}c/=6}return e.h=c,e.s=h,e.l=l,e}getRGB(e,t=Et.workingColorSpace){return Et.fromWorkingColorSpace(si.copy(this),t),e.r=si.r,e.g=si.g,e.b=si.b,e}getStyle(e=Wi){Et.fromWorkingColorSpace(si.copy(this),e);const t=si.r,n=si.g,r=si.b;return e!==Wi?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`}offsetHSL(e,t,n){return this.getHSL(ir),this.setHSL(ir.h+e,ir.s+t,ir.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(ir),e.getHSL(Ls);const n=el(ir.h,Ls.h,t),r=el(ir.s,Ls.s,t),a=el(ir.l,Ls.l,t);return this.setHSL(n,r,a),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,r=this.b,a=e.elements;return this.r=a[0]*t+a[3]*n+a[6]*r,this.g=a[1]*t+a[4]*n+a[7]*r,this.b=a[2]*t+a[5]*n+a[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const si=new It;It.NAMES=yp;let R0=0;class Os extends Kr{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:R0++}),this.uuid=Do(),this.name="",this.type="Material",this.blending=Vr,this.side=Kn,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=sc,this.blendDst=ac,this.blendEquation=hr,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new It(0,0,0),this.blendAlpha=0,this.depthFunc=Fr,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=tp,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=$r,this.stencilZFail=$r,this.stencilZPass=$r,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const r=this[t];if(r===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==Vr&&(n.blending=this.blending),this.side!==Kn&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==sc&&(n.blendSrc=this.blendSrc),this.blendDst!==ac&&(n.blendDst=this.blendDst),this.blendEquation!==hr&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==Fr&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==tp&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==$r&&(n.stencilFail=this.stencilFail),this.stencilZFail!==$r&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==$r&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(a){const s=[];for(const o in a){const c=a[o];delete c.metadata,s.push(c)}return s}if(t){const a=r(e.textures),s=r(e.images);a.length>0&&(n.textures=a),s.length>0&&(n.images=s)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const r=t.length;n=new Array(r);for(let a=0;a!==r;++a)n[a]=t[a].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class Ep extends Os{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new It(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Dn,this.combine=zh,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Xt=new we,Ns=new xt;let T0=0;class mn{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:T0++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=np,this.updateRanges=[],this.gpuType=wn,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,a=this.itemSize;r<a;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Ns.fromBufferAttribute(this,t),Ns.applyMatrix3(e),this.setXY(t,Ns.x,Ns.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Xt.fromBufferAttribute(this,t),Xt.applyMatrix3(e),this.setXYZ(t,Xt.x,Xt.y,Xt.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Xt.fromBufferAttribute(this,t),Xt.applyMatrix4(e),this.setXYZ(t,Xt.x,Xt.y,Xt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Xt.fromBufferAttribute(this,t),Xt.applyNormalMatrix(e),this.setXYZ(t,Xt.x,Xt.y,Xt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Xt.fromBufferAttribute(this,t),Xt.transformDirection(e),this.setXYZ(t,Xt.x,Xt.y,Xt.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Lo(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Ri(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Lo(t,this.array)),t}setX(e,t){return this.normalized&&(t=Ri(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Lo(t,this.array)),t}setY(e,t){return this.normalized&&(t=Ri(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Lo(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Ri(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Lo(t,this.array)),t}setW(e,t){return this.normalized&&(t=Ri(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Ri(t,this.array),n=Ri(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=Ri(t,this.array),n=Ri(n,this.array),r=Ri(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,a){return e*=this.itemSize,this.normalized&&(t=Ri(t,this.array),n=Ri(n,this.array),r=Ri(r,this.array),a=Ri(a,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=a,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==np&&(e.usage=this.usage),e}}class Rp extends mn{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class Tp extends mn{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class _r extends mn{constructor(e,t,n){super(new Float32Array(e),t,n)}}let A0=0;const ji=new jt,Sl=new Li,so=new we,Oi=new No,Vo=new No,ei=new we;class Sr extends Kr{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:A0++}),this.uuid=Do(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(op(e)?Tp:Rp)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const a=new dt().getNormalMatrix(e);n.applyNormalMatrix(a),n.needsUpdate=!0}const r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return ji.makeRotationFromQuaternion(e),this.applyMatrix4(ji),this}rotateX(e){return ji.makeRotationX(e),this.applyMatrix4(ji),this}rotateY(e){return ji.makeRotationY(e),this.applyMatrix4(ji),this}rotateZ(e){return ji.makeRotationZ(e),this.applyMatrix4(ji),this}translate(e,t,n){return ji.makeTranslation(e,t,n),this.applyMatrix4(ji),this}scale(e,t,n){return ji.makeScale(e,t,n),this.applyMatrix4(ji),this}lookAt(e){return Sl.lookAt(e),Sl.updateMatrix(),this.applyMatrix4(Sl.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(so).negate(),this.translate(so.x,so.y,so.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const n=[];for(let r=0,a=e.length;r<a;r++){const s=e[r];n.push(s.x,s.y,s.z||0)}this.setAttribute("position",new _r(n,3))}else{const n=Math.min(e.length,t.count);for(let r=0;r<n;r++){const a=e[r];t.setXYZ(r,a.x,a.y,a.z||0)}e.length>t.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new No);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new we(-1/0,-1/0,-1/0),new we(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,r=t.length;n<r;n++){const a=t[n];Oi.setFromBufferAttribute(a),this.morphTargetsRelative?(ei.addVectors(this.boundingBox.min,Oi.min),this.boundingBox.expandByPoint(ei),ei.addVectors(this.boundingBox.max,Oi.max),this.boundingBox.expandByPoint(ei)):(this.boundingBox.expandByPoint(Oi.min),this.boundingBox.expandByPoint(Oi.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new sl);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new we,1/0);return}if(e){const n=this.boundingSphere.center;if(Oi.setFromBufferAttribute(e),t)for(let a=0,s=t.length;a<s;a++){const o=t[a];Vo.setFromBufferAttribute(o),this.morphTargetsRelative?(ei.addVectors(Oi.min,Vo.min),Oi.expandByPoint(ei),ei.addVectors(Oi.max,Vo.max),Oi.expandByPoint(ei)):(Oi.expandByPoint(Vo.min),Oi.expandByPoint(Vo.max))}Oi.getCenter(n);let r=0;for(let a=0,s=e.count;a<s;a++)ei.fromBufferAttribute(e,a),r=Math.max(r,n.distanceToSquared(ei));if(t)for(let a=0,s=t.length;a<s;a++){const o=t[a],c=this.morphTargetsRelative;for(let h=0,l=o.count;h<l;h++)ei.fromBufferAttribute(o,h),c&&(so.fromBufferAttribute(e,h),ei.add(so)),r=Math.max(r,n.distanceToSquared(ei))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const n=t.position,r=t.normal,a=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new mn(new Float32Array(4*n.count),4));const s=this.getAttribute("tangent"),o=[],c=[];for(let I=0;I<n.count;I++)o[I]=new we,c[I]=new we;const h=new we,l=new we,f=new we,v=new xt,p=new xt,_=new xt,m=new we,d=new we;function u(I,C,A){h.fromBufferAttribute(n,I),l.fromBufferAttribute(n,C),f.fromBufferAttribute(n,A),v.fromBufferAttribute(a,I),p.fromBufferAttribute(a,C),_.fromBufferAttribute(a,A),l.sub(h),f.sub(h),p.sub(v),_.sub(v);const w=1/(p.x*_.y-_.x*p.y);isFinite(w)&&(m.copy(l).multiplyScalar(_.y).addScaledVector(f,-p.y).multiplyScalar(w),d.copy(f).multiplyScalar(p.x).addScaledVector(l,-_.x).multiplyScalar(w),o[I].add(m),o[C].add(m),o[A].add(m),c[I].add(d),c[C].add(d),c[A].add(d))}let b=this.groups;b.length===0&&(b=[{start:0,count:e.count}]);for(let I=0,C=b.length;I<C;++I){const A=b[I],w=A.start,N=A.count;for(let M=w,D=w+N;M<D;M+=3)u(e.getX(M+0),e.getX(M+1),e.getX(M+2))}const y=new we,g=new we,S=new we,R=new we;function E(I){S.fromBufferAttribute(r,I),R.copy(S);const C=o[I];y.copy(C),y.sub(S.multiplyScalar(S.dot(C))).normalize(),g.crossVectors(R,C);const w=g.dot(c[I])<0?-1:1;s.setXYZW(I,y.x,y.y,y.z,w)}for(let I=0,C=b.length;I<C;++I){const A=b[I],w=A.start,N=A.count;for(let M=w,D=w+N;M<D;M+=3)E(e.getX(M+0)),E(e.getX(M+1)),E(e.getX(M+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new mn(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let v=0,p=n.count;v<p;v++)n.setXYZ(v,0,0,0);const r=new we,a=new we,s=new we,o=new we,c=new we,h=new we,l=new we,f=new we;if(e)for(let v=0,p=e.count;v<p;v+=3){const _=e.getX(v+0),m=e.getX(v+1),d=e.getX(v+2);r.fromBufferAttribute(t,_),a.fromBufferAttribute(t,m),s.fromBufferAttribute(t,d),l.subVectors(s,a),f.subVectors(r,a),l.cross(f),o.fromBufferAttribute(n,_),c.fromBufferAttribute(n,m),h.fromBufferAttribute(n,d),o.add(l),c.add(l),h.add(l),n.setXYZ(_,o.x,o.y,o.z),n.setXYZ(m,c.x,c.y,c.z),n.setXYZ(d,h.x,h.y,h.z)}else for(let v=0,p=t.count;v<p;v+=3)r.fromBufferAttribute(t,v+0),a.fromBufferAttribute(t,v+1),s.fromBufferAttribute(t,v+2),l.subVectors(s,a),f.subVectors(r,a),l.cross(f),n.setXYZ(v+0,l.x,l.y,l.z),n.setXYZ(v+1,l.x,l.y,l.z),n.setXYZ(v+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)ei.fromBufferAttribute(e,t),ei.normalize(),e.setXYZ(t,ei.x,ei.y,ei.z)}toNonIndexed(){function e(o,c){const h=o.array,l=o.itemSize,f=o.normalized,v=new h.constructor(c.length*l);let p=0,_=0;for(let m=0,d=c.length;m<d;m++){o.isInterleavedBufferAttribute?p=c[m]*o.data.stride+o.offset:p=c[m]*l;for(let u=0;u<l;u++)v[_++]=h[p++]}return new mn(v,l,f)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Sr,n=this.index.array,r=this.attributes;for(const o in r){const c=r[o],h=e(c,n);t.setAttribute(o,h)}const a=this.morphAttributes;for(const o in a){const c=[],h=a[o];for(let l=0,f=h.length;l<f;l++){const v=h[l],p=e(v,n);c.push(p)}t.morphAttributes[o]=c}t.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let o=0,c=s.length;o<c;o++){const h=s[o];t.addGroup(h.start,h.count,h.materialIndex)}return t}toJSON(){const e={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const h in c)c[h]!==void 0&&(e[h]=c[h]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const c in n){const h=n[c];e.data.attributes[c]=h.toJSON(e.data)}const r={};let a=!1;for(const c in this.morphAttributes){const h=this.morphAttributes[c],l=[];for(let f=0,v=h.length;f<v;f++){const p=h[f];l.push(p.toJSON(e.data))}l.length>0&&(r[c]=l,a=!0)}a&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone(t));const r=e.attributes;for(const h in r){const l=r[h];this.setAttribute(h,l.clone(t))}const a=e.morphAttributes;for(const h in a){const l=[],f=a[h];for(let v=0,p=f.length;v<p;v++)l.push(f[v].clone(t));this.morphAttributes[h]=l}this.morphTargetsRelative=e.morphTargetsRelative;const s=e.groups;for(let h=0,l=s.length;h<l;h++){const f=s[h];this.addGroup(f.start,f.count,f.materialIndex)}const o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Ap=new jt,br=new g0,ks=new sl,Cp=new we,Us=new we,Bs=new we,Vs=new we,bl=new we,Fs=new we,wp=new we,Hs=new we;class gn extends Li{constructor(e=new Sr,t=new Ep){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const r=t[n[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,s=r.length;a<s;a++){const o=r[a].name||String(a);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=a}}}}getVertexPosition(e,t){const n=this.geometry,r=n.attributes.position,a=n.morphAttributes.position,s=n.morphTargetsRelative;t.fromBufferAttribute(r,e);const o=this.morphTargetInfluences;if(a&&o){Fs.set(0,0,0);for(let c=0,h=a.length;c<h;c++){const l=o[c],f=a[c];l!==0&&(bl.fromBufferAttribute(f,e),s?Fs.addScaledVector(bl,l):Fs.addScaledVector(bl.sub(t),l))}t.add(Fs)}return t}raycast(e,t){const n=this.geometry,r=this.material,a=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),ks.copy(n.boundingSphere),ks.applyMatrix4(a),br.copy(e.ray).recast(e.near),!(ks.containsPoint(br.origin)===!1&&(br.intersectSphere(ks,Cp)===null||br.origin.distanceToSquared(Cp)>(e.far-e.near)**2))&&(Ap.copy(a).invert(),br.copy(e.ray).applyMatrix4(Ap),!(n.boundingBox!==null&&br.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,br)))}_computeIntersections(e,t,n){let r;const a=this.geometry,s=this.material,o=a.index,c=a.attributes.position,h=a.attributes.uv,l=a.attributes.uv1,f=a.attributes.normal,v=a.groups,p=a.drawRange;if(o!==null)if(Array.isArray(s))for(let _=0,m=v.length;_<m;_++){const d=v[_],u=s[d.materialIndex],b=Math.max(d.start,p.start),y=Math.min(o.count,Math.min(d.start+d.count,p.start+p.count));for(let g=b,S=y;g<S;g+=3){const R=o.getX(g),E=o.getX(g+1),I=o.getX(g+2);r=Gs(this,u,e,n,h,l,f,R,E,I),r&&(r.faceIndex=Math.floor(g/3),r.face.materialIndex=d.materialIndex,t.push(r))}}else{const _=Math.max(0,p.start),m=Math.min(o.count,p.start+p.count);for(let d=_,u=m;d<u;d+=3){const b=o.getX(d),y=o.getX(d+1),g=o.getX(d+2);r=Gs(this,s,e,n,h,l,f,b,y,g),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}else if(c!==void 0)if(Array.isArray(s))for(let _=0,m=v.length;_<m;_++){const d=v[_],u=s[d.materialIndex],b=Math.max(d.start,p.start),y=Math.min(c.count,Math.min(d.start+d.count,p.start+p.count));for(let g=b,S=y;g<S;g+=3){const R=g,E=g+1,I=g+2;r=Gs(this,u,e,n,h,l,f,R,E,I),r&&(r.faceIndex=Math.floor(g/3),r.face.materialIndex=d.materialIndex,t.push(r))}}else{const _=Math.max(0,p.start),m=Math.min(c.count,p.start+p.count);for(let d=_,u=m;d<u;d+=3){const b=d,y=d+1,g=d+2;r=Gs(this,s,e,n,h,l,f,b,y,g),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}}}function C0(i,e,t,n,r,a,s,o){let c;if(e.side===yi?c=n.intersectTriangle(s,a,r,!0,o):c=n.intersectTriangle(r,a,s,e.side===Kn,o),c===null)return null;Hs.copy(o),Hs.applyMatrix4(i.matrixWorld);const h=t.ray.origin.distanceTo(Hs);return h<t.near||h>t.far?null:{distance:h,point:Hs.clone(),object:i}}function Gs(i,e,t,n,r,a,s,o,c,h){i.getVertexPosition(o,Us),i.getVertexPosition(c,Bs),i.getVertexPosition(h,Vs);const l=C0(i,e,t,n,Us,Bs,Vs,wp);if(l){const f=new we;sn.getBarycoord(wp,Us,Bs,Vs,f),r&&(l.uv=sn.getInterpolatedAttribute(r,o,c,h,f,new xt)),a&&(l.uv1=sn.getInterpolatedAttribute(a,o,c,h,f,new xt)),s&&(l.normal=sn.getInterpolatedAttribute(s,o,c,h,f,new we),l.normal.dot(n.direction)>0&&l.normal.multiplyScalar(-1));const v={a:o,b:c,c:h,normal:new we,materialIndex:0};sn.getNormal(Us,Bs,Vs,v.normal),l.face=v,l.barycoord=f}return l}class Fo extends Sr{constructor(e=1,t=1,n=1,r=1,a=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:a,depthSegments:s};const o=this;r=Math.floor(r),a=Math.floor(a),s=Math.floor(s);const c=[],h=[],l=[],f=[];let v=0,p=0;_("z","y","x",-1,-1,n,t,e,s,a,0),_("z","y","x",1,-1,n,t,-e,s,a,1),_("x","z","y",1,1,e,n,t,r,s,2),_("x","z","y",1,-1,e,n,-t,r,s,3),_("x","y","z",1,-1,e,t,n,r,a,4),_("x","y","z",-1,-1,e,t,-n,r,a,5),this.setIndex(c),this.setAttribute("position",new _r(h,3)),this.setAttribute("normal",new _r(l,3)),this.setAttribute("uv",new _r(f,2));function _(m,d,u,b,y,g,S,R,E,I,C){const A=g/E,w=S/I,N=g/2,M=S/2,D=R/2,L=E+1,P=I+1;let x=0,T=0;const O=new we;for(let k=0;k<P;k++){const H=k*w-M;for(let U=0;U<L;U++){const ee=U*A-N;O[m]=ee*b,O[d]=H*y,O[u]=D,h.push(O.x,O.y,O.z),O[m]=0,O[d]=0,O[u]=R>0?1:-1,l.push(O.x,O.y,O.z),f.push(U/E),f.push(1-k/I),x+=1}}for(let k=0;k<I;k++)for(let H=0;H<E;H++){const U=v+H+L*k,ee=v+H+L*(k+1),W=v+(H+1)+L*(k+1),$=v+(H+1)+L*k;c.push(U,ee,$),c.push(ee,W,$),T+=6}o.addGroup(p,T,C),p+=T,v+=x}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Fo(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function ao(i){const e={};for(const t in i){e[t]={};for(const n in i[t]){const r=i[t][n];r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)?r.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=r.clone():Array.isArray(r)?e[t][n]=r.slice():e[t][n]=r}}return e}function di(i){const e={};for(let t=0;t<i.length;t++){const n=ao(i[t]);for(const r in n)e[r]=n[r]}return e}function w0(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function Mp(i){const e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Et.workingColorSpace}const M0={clone:ao,merge:di};var x0=`void main() {
	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,I0=`void main() {
	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`;class kn extends Os{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=x0,this.fragmentShader=I0,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=ao(e.uniforms),this.uniformsGroups=w0(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const r in this.uniforms){const s=this.uniforms[r].value;s&&s.isTexture?t.uniforms[r]={type:"t",value:s.toJSON(e).uuid}:s&&s.isColor?t.uniforms[r]={type:"c",value:s.getHex()}:s&&s.isVector2?t.uniforms[r]={type:"v2",value:s.toArray()}:s&&s.isVector3?t.uniforms[r]={type:"v3",value:s.toArray()}:s&&s.isVector4?t.uniforms[r]={type:"v4",value:s.toArray()}:s&&s.isMatrix3?t.uniforms[r]={type:"m3",value:s.toArray()}:s&&s.isMatrix4?t.uniforms[r]={type:"m4",value:s.toArray()}:t.uniforms[r]={value:s}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const r in this.extensions)this.extensions[r]===!0&&(n[r]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class xp extends Li{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new jt,this.projectionMatrix=new jt,this.projectionMatrixInverse=new jt,this.coordinateSystem=Mn}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const nr=new we,Ip=new xt,Pp=new xt;class an extends xp{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Zc*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Qc*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Zc*2*Math.atan(Math.tan(Qc*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){nr.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(nr.x,nr.y).multiplyScalar(-e/nr.z),nr.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(nr.x,nr.y).multiplyScalar(-e/nr.z)}getViewSize(e,t){return this.getViewBounds(e,Ip,Pp),t.subVectors(Pp,Ip)}setViewOffset(e,t,n,r,a,s){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=a,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Qc*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,a=-.5*r;const s=this.view;if(this.view!==null&&this.view.enabled){const c=s.fullWidth,h=s.fullHeight;a+=s.offsetX*r/c,t-=s.offsetY*n/h,r*=s.width/c,n*=s.height/h}const o=this.filmOffset;o!==0&&(a+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(a,a+r,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const co=-90,lo=1;class P0 extends Li{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const r=new an(co,lo,e,t);r.layers=this.layers,this.add(r);const a=new an(co,lo,e,t);a.layers=this.layers,this.add(a);const s=new an(co,lo,e,t);s.layers=this.layers,this.add(s);const o=new an(co,lo,e,t);o.layers=this.layers,this.add(o);const c=new an(co,lo,e,t);c.layers=this.layers,this.add(c);const h=new an(co,lo,e,t);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,r,a,s,o,c]=t;for(const h of t)this.remove(h);if(e===Mn)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),a.up.set(0,0,-1),a.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===Ts)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),a.up.set(0,0,1),a.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const h of t)this.add(h),h.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[a,s,o,c,h,l]=this.children,f=e.getRenderTarget(),v=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),_=e.xr.enabled;e.xr.enabled=!1;const m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,r),e.render(t,a),e.setRenderTarget(n,1,r),e.render(t,s),e.setRenderTarget(n,2,r),e.render(t,o),e.setRenderTarget(n,3,r),e.render(t,c),e.setRenderTarget(n,4,r),e.render(t,h),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),e.render(t,l),e.setRenderTarget(f,v,p),e.xr.enabled=_,n.texture.needsPMREMUpdate=!0}}class Dp extends ui{constructor(e,t,n,r,a,s,o,c,h,l){e=e!==void 0?e:[],t=t!==void 0?t:Hr,super(e,t,n,r,a,s,o,c,h,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class D0 extends mr{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},r=[n,n,n,n,n,n];this.texture=new Dp(r,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:Ei}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:`

				varying vec3 vWorldDirection;

				vec3 transformDirection( in vec3 dir, in mat4 matrix ) {

					return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );

				}

				void main() {

					vWorldDirection = transformDirection( position, modelMatrix );

					#include <begin_vertex>
					#include <project_vertex>

				}
			`,fragmentShader:`

				uniform sampler2D tEquirect;

				varying vec3 vWorldDirection;

				#include <common>

				void main() {

					vec3 direction = normalize( vWorldDirection );

					vec2 sampleUV = equirectUv( direction );

					gl_FragColor = texture2D( tEquirect, sampleUV );

				}
			`},r=new Fo(5,5,5),a=new kn({name:"CubemapFromEquirect",uniforms:ao(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:yi,blending:qn});a.uniforms.tEquirect.value=t;const s=new gn(r,a),o=t.minFilter;return t.minFilter===pr&&(t.minFilter=Ei),new P0(1,10,this).update(e,s),t.minFilter=o,s.geometry.dispose(),s.material.dispose(),this}clear(e,t,n,r){const a=e.getRenderTarget();for(let s=0;s<6;s++)e.setRenderTarget(this,s),e.clear(t,n,r);e.setRenderTarget(a)}}class zs extends Li{constructor(){super(),this.isGroup=!0,this.type="Group"}}const L0={type:"move"};class yl{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new zs,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new zs,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new we,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new we),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new zs,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new we,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new we),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,a=null,s=null;const o=this._targetRay,c=this._grip,h=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(h&&e.hand){s=!0;for(const m of e.hand.values()){const d=t.getJointPose(m,n),u=this._getHandJoint(h,m);d!==null&&(u.matrix.fromArray(d.transform.matrix),u.matrix.decompose(u.position,u.rotation,u.scale),u.matrixWorldNeedsUpdate=!0,u.jointRadius=d.radius),u.visible=d!==null}const l=h.joints["index-finger-tip"],f=h.joints["thumb-tip"],v=l.position.distanceTo(f.position),p=.02,_=.005;h.inputState.pinching&&v>p+_?(h.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!h.inputState.pinching&&v<=p-_&&(h.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(a=t.getPose(e.gripSpace,n),a!==null&&(c.matrix.fromArray(a.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,a.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(a.linearVelocity)):c.hasLinearVelocity=!1,a.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(a.angularVelocity)):c.hasAngularVelocity=!1));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&a!==null&&(r=a),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(L0)))}return o!==null&&(o.visible=r!==null),c!==null&&(c.visible=a!==null),h!==null&&(h.visible=s!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new zs;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class O0 extends Li{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Dn,this.environmentIntensity=1,this.environmentRotation=new Dn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}const El=new we,N0=new we,k0=new dt;class yr{constructor(e=new we(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const r=El.subVectors(n,t).cross(N0.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(El),r=this.normal.dot(n);if(r===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const a=-(e.start.dot(this.normal)+this.constant)/r;return a<0||a>1?null:t.copy(e.start).addScaledVector(n,a)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||k0.getNormalMatrix(e),r=this.coplanarPoint(El).applyMatrix4(e),a=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(a),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Er=new sl,Ws=new we;class Lp{constructor(e=new yr,t=new yr,n=new yr,r=new yr,a=new yr,s=new yr){this.planes=[e,t,n,r,a,s]}set(e,t,n,r,a,s){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(a),o[5].copy(s),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Mn){const n=this.planes,r=e.elements,a=r[0],s=r[1],o=r[2],c=r[3],h=r[4],l=r[5],f=r[6],v=r[7],p=r[8],_=r[9],m=r[10],d=r[11],u=r[12],b=r[13],y=r[14],g=r[15];if(n[0].setComponents(c-a,v-h,d-p,g-u).normalize(),n[1].setComponents(c+a,v+h,d+p,g+u).normalize(),n[2].setComponents(c+s,v+l,d+_,g+b).normalize(),n[3].setComponents(c-s,v-l,d-_,g-b).normalize(),n[4].setComponents(c-o,v-f,d-m,g-y).normalize(),t===Mn)n[5].setComponents(c+o,v+f,d+m,g+y).normalize();else if(t===Ts)n[5].setComponents(o,f,m,y).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Er.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Er.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Er)}intersectsSprite(e){return Er.center.set(0,0,0),Er.radius=.7071067811865476,Er.applyMatrix4(e.matrixWorld),this.intersectsSphere(Er)}intersectsSphere(e){const t=this.planes,n=e.center,r=-e.radius;for(let a=0;a<6;a++)if(t[a].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const r=t[n];if(Ws.x=r.normal.x>0?e.max.x:e.min.x,Ws.y=r.normal.y>0?e.max.y:e.min.y,Ws.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Ws)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class U0 extends ui{constructor(e,t,n,r,a,s,o,c,h){super(e,t,n,r,a,s,o,c,h),this.isVideoTexture=!0,this.minFilter=s!==void 0?s:Ei,this.magFilter=a!==void 0?a:Ei,this.generateMipmaps=!1;const l=this;function f(){l.needsUpdate=!0,e.requestVideoFrameCallback(f)}"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback(f)}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class Op extends ui{constructor(e,t,n,r,a,s,o,c,h,l=Wr){if(l!==Wr&&l!==jr)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");n===void 0&&l===Wr&&(n=fr),n===void 0&&l===jr&&(n=zr),super(null,r,a,s,o,c,l,n,h),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=o!==void 0?o:en,this.minFilter=c!==void 0?c:en,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class Ho extends Sr{constructor(e=1,t=1,n=1,r=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};const a=e/2,s=t/2,o=Math.floor(n),c=Math.floor(r),h=o+1,l=c+1,f=e/o,v=t/c,p=[],_=[],m=[],d=[];for(let u=0;u<l;u++){const b=u*v-s;for(let y=0;y<h;y++){const g=y*f-a;_.push(g,-b,0),m.push(0,0,1),d.push(y/o),d.push(1-u/c)}}for(let u=0;u<c;u++)for(let b=0;b<o;b++){const y=b+h*u,g=b+h*(u+1),S=b+1+h*(u+1),R=b+1+h*u;p.push(y,g,R),p.push(g,S,R)}this.setIndex(p),this.setAttribute("position",new _r(_,3)),this.setAttribute("normal",new _r(m,3)),this.setAttribute("uv",new _r(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ho(e.width,e.height,e.widthSegments,e.heightSegments)}}class B0 extends Os{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=$v,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class V0 extends Os{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class Np extends xp{constructor(e=-1,t=1,n=1,r=-1,a=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=a,this.far=s,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,a,s){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=a,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2;let a=n-e,s=n+e,o=r+t,c=r-t;if(this.view!==null&&this.view.enabled){const h=(this.right-this.left)/this.view.fullWidth/this.zoom,l=(this.top-this.bottom)/this.view.fullHeight/this.zoom;a+=h*this.view.offsetX,s=a+h*this.view.width,o-=l*this.view.offsetY,c=o-l*this.view.height}this.projectionMatrix.makeOrthographic(a,s,o,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class F0 extends an{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e,this.index=0}}function kp(i,e,t,n){const r=H0(n);switch(t){case Kh:return i*e;case Yh:return i*e;case Jh:return i*e*2;case Qh:return i*e/r.components*r.byteLength;case Rc:return i*e/r.components*r.byteLength;case Zh:return i*e*2/r.components*r.byteLength;case Tc:return i*e*2/r.components*r.byteLength;case qh:return i*e*3/r.components*r.byteLength;case tn:return i*e*4/r.components*r.byteLength;case Ac:return i*e*4/r.components*r.byteLength;case _s:case Ss:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case bs:case ys:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case wc:case xc:return Math.max(i,16)*Math.max(e,8)/4;case Cc:case Mc:return Math.max(i,8)*Math.max(e,8)/2;case Ic:case Pc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case Dc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Lc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Oc:return Math.floor((i+4)/5)*Math.floor((e+3)/4)*16;case Nc:return Math.floor((i+4)/5)*Math.floor((e+4)/5)*16;case kc:return Math.floor((i+5)/6)*Math.floor((e+4)/5)*16;case Uc:return Math.floor((i+5)/6)*Math.floor((e+5)/6)*16;case Bc:return Math.floor((i+7)/8)*Math.floor((e+4)/5)*16;case Vc:return Math.floor((i+7)/8)*Math.floor((e+5)/6)*16;case Fc:return Math.floor((i+7)/8)*Math.floor((e+7)/8)*16;case Hc:return Math.floor((i+9)/10)*Math.floor((e+4)/5)*16;case Gc:return Math.floor((i+9)/10)*Math.floor((e+5)/6)*16;case zc:return Math.floor((i+9)/10)*Math.floor((e+7)/8)*16;case Wc:return Math.floor((i+9)/10)*Math.floor((e+9)/10)*16;case jc:return Math.floor((i+11)/12)*Math.floor((e+9)/10)*16;case Xc:return Math.floor((i+11)/12)*Math.floor((e+11)/12)*16;case Es:case $c:case Kc:return Math.ceil(i/4)*Math.ceil(e/4)*16;case ep:case qc:return Math.ceil(i/4)*Math.ceil(e/4)*8;case Yc:case Jc:return Math.ceil(i/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function H0(i){switch(i){case Cn:case jh:return{byteLength:1,components:1};case Io:case Xh:case Po:return{byteLength:2,components:1};case yc:case Ec:return{byteLength:2,components:4};case fr:case bc:case wn:return{byteLength:4,components:1};case $h:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${i}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:oc}})),typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=oc);/**
 * @license
 * Copyright 2010-2025 Three.js Authors
 * SPDX-License-Identifier: MIT
 */function Up(){let i=null,e=!1,t=null,n=null;function r(a,s){t(a,s),n=i.requestAnimationFrame(r)}return{start:function(){e!==!0&&t!==null&&(n=i.requestAnimationFrame(r),e=!0)},stop:function(){i.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(a){t=a},setContext:function(a){i=a}}}function G0(i){const e=new WeakMap;function t(o,c){const h=o.array,l=o.usage,f=h.byteLength,v=i.createBuffer();i.bindBuffer(c,v),i.bufferData(c,h,l),o.onUploadCallback();let p;if(h instanceof Float32Array)p=i.FLOAT;else if(h instanceof Uint16Array)o.isFloat16BufferAttribute?p=i.HALF_FLOAT:p=i.UNSIGNED_SHORT;else if(h instanceof Int16Array)p=i.SHORT;else if(h instanceof Uint32Array)p=i.UNSIGNED_INT;else if(h instanceof Int32Array)p=i.INT;else if(h instanceof Int8Array)p=i.BYTE;else if(h instanceof Uint8Array)p=i.UNSIGNED_BYTE;else if(h instanceof Uint8ClampedArray)p=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+h);return{buffer:v,type:p,bytesPerElement:h.BYTES_PER_ELEMENT,version:o.version,size:f}}function n(o,c,h){const l=c.array,f=c.updateRanges;if(i.bindBuffer(h,o),f.length===0)i.bufferSubData(h,0,l);else{f.sort((p,_)=>p.start-_.start);let v=0;for(let p=1;p<f.length;p++){const _=f[v],m=f[p];m.start<=_.start+_.count+1?_.count=Math.max(_.count,m.start+m.count-_.start):(++v,f[v]=m)}f.length=v+1;for(let p=0,_=f.length;p<_;p++){const m=f[p];i.bufferSubData(h,m.start*l.BYTES_PER_ELEMENT,l,m.start,m.count)}c.clearUpdateRanges()}c.onUploadCallback()}function r(o){return o.isInterleavedBufferAttribute&&(o=o.data),e.get(o)}function a(o){o.isInterleavedBufferAttribute&&(o=o.data);const c=e.get(o);c&&(i.deleteBuffer(c.buffer),e.delete(o))}function s(o,c){if(o.isInterleavedBufferAttribute&&(o=o.data),o.isGLBufferAttribute){const l=e.get(o);(!l||l.version<o.version)&&e.set(o,{buffer:o.buffer,type:o.type,bytesPerElement:o.elementSize,version:o.version});return}const h=e.get(o);if(h===void 0)e.set(o,t(o,c));else if(h.version<o.version){if(h.size!==o.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");n(h.buffer,o,c),h.version=o.version}}return{get:r,remove:a,update:s}}var z0=`#ifdef USE_ALPHAHASH
	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,W0=`#ifdef USE_ALPHAHASH
	const float ALPHA_HASH_SCALE = 0.05;
	float hash2D( vec2 value ) {
		return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
	}
	float hash3D( vec3 value ) {
		return hash2D( vec2( hash2D( value.xy ), value.z ) );
	}
	float getAlphaHashThreshold( vec3 position ) {
		float maxDeriv = max(
			length( dFdx( position.xyz ) ),
			length( dFdy( position.xyz ) )
		);
		float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
		vec2 pixScales = vec2(
			exp2( floor( log2( pixScale ) ) ),
			exp2( ceil( log2( pixScale ) ) )
		);
		vec2 alpha = vec2(
			hash3D( floor( pixScales.x * position.xyz ) ),
			hash3D( floor( pixScales.y * position.xyz ) )
		);
		float lerpFactor = fract( log2( pixScale ) );
		float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
		float a = min( lerpFactor, 1.0 - lerpFactor );
		vec3 cases = vec3(
			x * x / ( 2.0 * a * ( 1.0 - a ) ),
			( x - 0.5 * a ) / ( 1.0 - a ),
			1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
		);
		float threshold = ( x < ( 1.0 - a ) )
			? ( ( x < a ) ? cases.x : cases.y )
			: cases.z;
		return clamp( threshold , 1.0e-6, 1.0 );
	}
#endif`,j0=`#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`,X0=`#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,$0=`#ifdef USE_ALPHATEST
	#ifdef ALPHA_TO_COVERAGE
	diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
	if ( diffuseColor.a == 0.0 ) discard;
	#else
	if ( diffuseColor.a < alphaTest ) discard;
	#endif
#endif`,K0=`#ifdef USE_ALPHATEST
	uniform float alphaTest;
#endif`,q0=`#ifdef USE_AOMAP
	float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
	reflectedLight.indirectDiffuse *= ambientOcclusion;
	#if defined( USE_CLEARCOAT ) 
		clearcoatSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_SHEEN ) 
		sheenSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD )
		float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
		reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
	#endif
#endif`,Y0=`#ifdef USE_AOMAP
	uniform sampler2D aoMap;
	uniform float aoMapIntensity;
#endif`,J0=`#ifdef USE_BATCHING
	#if ! defined( GL_ANGLE_multi_draw )
	#define gl_DrawID _gl_DrawID
	uniform int _gl_DrawID;
	#endif
	uniform highp sampler2D batchingTexture;
	uniform highp usampler2D batchingIdTexture;
	mat4 getBatchingMatrix( const in float i ) {
		int size = textureSize( batchingTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
	float getIndirectIndex( const in int i ) {
		int size = textureSize( batchingIdTexture, 0 ).x;
		int x = i % size;
		int y = i / size;
		return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
	}
#endif
#ifdef USE_BATCHING_COLOR
	uniform sampler2D batchingColorTexture;
	vec3 getBatchingColor( const in float i ) {
		int size = textureSize( batchingColorTexture, 0 ).x;
		int j = int( i );
		int x = j % size;
		int y = j / size;
		return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
	}
#endif`,Q0=`#ifdef USE_BATCHING
	mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`,Z0=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
	vPosition = vec3( position );
#endif`,e_=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
	vec3 objectTangent = vec3( tangent.xyz );
#endif`,t_=`float G_BlinnPhong_Implicit( ) {
	return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
	return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
}
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( specularColor, 1.0, dotVH );
	float G = G_BlinnPhong_Implicit( );
	float D = D_BlinnPhong( shininess, dotNH );
	return F * ( G * D );
} // validated`,i_=`#ifdef USE_IRIDESCENCE
	const mat3 XYZ_TO_REC709 = mat3(
		 3.2404542, -0.9692660,  0.0556434,
		-1.5371385,  1.8760108, -0.2040259,
		-0.4985314,  0.0415560,  1.0572252
	);
	vec3 Fresnel0ToIor( vec3 fresnel0 ) {
		vec3 sqrtF0 = sqrt( fresnel0 );
		return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
	}
	vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
	}
	float IorToFresnel0( float transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
	}
	vec3 evalSensitivity( float OPD, vec3 shift ) {
		float phase = 2.0 * PI * OPD * 1.0e-9;
		vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
		vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
		vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
		vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
		xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
		xyz /= 1.0685e-7;
		vec3 rgb = XYZ_TO_REC709 * xyz;
		return rgb;
	}
	vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
		vec3 I;
		float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
		float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
		float cosTheta2Sq = 1.0 - sinTheta2Sq;
		if ( cosTheta2Sq < 0.0 ) {
			return vec3( 1.0 );
		}
		float cosTheta2 = sqrt( cosTheta2Sq );
		float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
		float R12 = F_Schlick( R0, 1.0, cosTheta1 );
		float T121 = 1.0 - R12;
		float phi12 = 0.0;
		if ( iridescenceIOR < outsideIOR ) phi12 = PI;
		float phi21 = PI - phi12;
		vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );		vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
		vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
		vec3 phi23 = vec3( 0.0 );
		if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
		if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
		if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
		float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
		vec3 phi = vec3( phi21 ) + phi23;
		vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
		vec3 r123 = sqrt( R123 );
		vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
		vec3 C0 = R12 + Rs;
		I = C0;
		vec3 Cm = Rs - T121;
		for ( int m = 1; m <= 2; ++ m ) {
			Cm *= r123;
			vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
			I += Cm * Sm;
		}
		return max( I, vec3( 0.0 ) );
	}
#endif`,n_=`#ifdef USE_BUMPMAP
	uniform sampler2D bumpMap;
	uniform float bumpScale;
	vec2 dHdxy_fwd() {
		vec2 dSTdx = dFdx( vBumpMapUv );
		vec2 dSTdy = dFdy( vBumpMapUv );
		float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
		float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
		float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
		return vec2( dBx, dBy );
	}
	vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
		vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
		vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
		vec3 vN = surf_norm;
		vec3 R1 = cross( vSigmaY, vN );
		vec3 R2 = cross( vN, vSigmaX );
		float fDet = dot( vSigmaX, R1 ) * faceDirection;
		vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
		return normalize( abs( fDet ) * surf_norm - vGrad );
	}
#endif`,r_=`#if NUM_CLIPPING_PLANES > 0
	vec4 plane;
	#ifdef ALPHA_TO_COVERAGE
		float distanceToPlane, distanceGradient;
		float clipOpacity = 1.0;
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
			distanceGradient = fwidth( distanceToPlane ) / 2.0;
			clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			if ( clipOpacity == 0.0 ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			float unionClipOpacity = 1.0;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
				distanceGradient = fwidth( distanceToPlane ) / 2.0;
				unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			}
			#pragma unroll_loop_end
			clipOpacity *= 1.0 - unionClipOpacity;
		#endif
		diffuseColor.a *= clipOpacity;
		if ( diffuseColor.a == 0.0 ) discard;
	#else
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			bool clipped = true;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
			}
			#pragma unroll_loop_end
			if ( clipped ) discard;
		#endif
	#endif
#endif`,o_=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,s_=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
#endif`,a_=`#if NUM_CLIPPING_PLANES > 0
	vClipPosition = - mvPosition.xyz;
#endif`,c_=`#if defined( USE_COLOR_ALPHA )
	diffuseColor *= vColor;
#elif defined( USE_COLOR )
	diffuseColor.rgb *= vColor;
#endif`,l_=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR )
	varying vec3 vColor;
#endif`,u_=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	varying vec3 vColor;
#endif`,d_=`#if defined( USE_COLOR_ALPHA )
	vColor = vec4( 1.0 );
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	vColor = vec3( 1.0 );
#endif
#ifdef USE_COLOR
	vColor *= color;
#endif
#ifdef USE_INSTANCING_COLOR
	vColor.xyz *= instanceColor.xyz;
#endif
#ifdef USE_BATCHING_COLOR
	vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
	vColor.xyz *= batchingColor.xyz;
#endif`,h_=`#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
#define RECIPROCAL_PI2 0.15915494309189535
#define EPSILON 1e-6
#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
#define whiteComplement( a ) ( 1.0 - saturate( a ) )
float pow2( const in float x ) { return x*x; }
vec3 pow2( const in vec3 x ) { return x*x; }
float pow3( const in float x ) { return x*x*x; }
float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
highp float rand( const in vec2 uv ) {
	const highp float a = 12.9898, b = 78.233, c = 43758.5453;
	highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
	return fract( sin( sn ) * c );
}
#ifdef HIGH_PRECISION
	float precisionSafeLength( vec3 v ) { return length( v ); }
#else
	float precisionSafeLength( vec3 v ) {
		float maxComponent = max3( abs( v ) );
		return length( v / maxComponent ) * maxComponent;
	}
#endif
struct IncidentLight {
	vec3 color;
	vec3 direction;
	bool visible;
};
struct ReflectedLight {
	vec3 directDiffuse;
	vec3 directSpecular;
	vec3 indirectDiffuse;
	vec3 indirectSpecular;
};
#ifdef USE_ALPHAHASH
	varying vec3 vPosition;
#endif
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
}
mat3 transposeMat3( const in mat3 m ) {
	mat3 tmp;
	tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
	tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
	tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
	return tmp;
}
bool isPerspectiveMatrix( mat4 m ) {
	return m[ 2 ][ 3 ] == - 1.0;
}
vec2 equirectUv( in vec3 dir ) {
	float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
	float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
	return vec2( u, v );
}
vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
	return RECIPROCAL_PI * diffuseColor;
}
vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
}
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
} // validated`,p_=`#ifdef ENVMAP_TYPE_CUBE_UV
	#define cubeUV_minMipLevel 4.0
	#define cubeUV_minTileSize 16.0
	float getFace( vec3 direction ) {
		vec3 absDirection = abs( direction );
		float face = - 1.0;
		if ( absDirection.x > absDirection.z ) {
			if ( absDirection.x > absDirection.y )
				face = direction.x > 0.0 ? 0.0 : 3.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		} else {
			if ( absDirection.z > absDirection.y )
				face = direction.z > 0.0 ? 2.0 : 5.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		}
		return face;
	}
	vec2 getUV( vec3 direction, float face ) {
		vec2 uv;
		if ( face == 0.0 ) {
			uv = vec2( direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 1.0 ) {
			uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
		} else if ( face == 2.0 ) {
			uv = vec2( - direction.x, direction.y ) / abs( direction.z );
		} else if ( face == 3.0 ) {
			uv = vec2( - direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 4.0 ) {
			uv = vec2( - direction.x, direction.z ) / abs( direction.y );
		} else {
			uv = vec2( direction.x, direction.y ) / abs( direction.z );
		}
		return 0.5 * ( uv + 1.0 );
	}
	vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
		float face = getFace( direction );
		float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
		mipInt = max( mipInt, cubeUV_minMipLevel );
		float faceSize = exp2( mipInt );
		highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
		if ( face > 2.0 ) {
			uv.y += faceSize;
			face -= 3.0;
		}
		uv.x += face * faceSize;
		uv.x += filterInt * 3.0 * cubeUV_minTileSize;
		uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
		uv.x *= CUBEUV_TEXEL_WIDTH;
		uv.y *= CUBEUV_TEXEL_HEIGHT;
		#ifdef texture2DGradEXT
			return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
		#else
			return texture2D( envMap, uv ).rgb;
		#endif
	}
	#define cubeUV_r0 1.0
	#define cubeUV_m0 - 2.0
	#define cubeUV_r1 0.8
	#define cubeUV_m1 - 1.0
	#define cubeUV_r4 0.4
	#define cubeUV_m4 2.0
	#define cubeUV_r5 0.305
	#define cubeUV_m5 3.0
	#define cubeUV_r6 0.21
	#define cubeUV_m6 4.0
	float roughnessToMip( float roughness ) {
		float mip = 0.0;
		if ( roughness >= cubeUV_r1 ) {
			mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
		} else if ( roughness >= cubeUV_r4 ) {
			mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
		} else if ( roughness >= cubeUV_r5 ) {
			mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
		} else if ( roughness >= cubeUV_r6 ) {
			mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
		} else {
			mip = - 2.0 * log2( 1.16 * roughness );		}
		return mip;
	}
	vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
		float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
		float mipF = fract( mip );
		float mipInt = floor( mip );
		vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
		if ( mipF == 0.0 ) {
			return vec4( color0, 1.0 );
		} else {
			vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
			return vec4( mix( color0, color1, mipF ), 1.0 );
		}
	}
#endif`,f_=`vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
	vec3 transformedTangent = objectTangent;
#endif
#ifdef USE_BATCHING
	mat3 bm = mat3( batchingMatrix );
	transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
	transformedNormal = bm * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = bm * transformedTangent;
	#endif
#endif
#ifdef USE_INSTANCING
	mat3 im = mat3( instanceMatrix );
	transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
	transformedNormal = im * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = im * transformedTangent;
	#endif
#endif
transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
	transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
	transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
	#ifdef FLIP_SIDED
		transformedTangent = - transformedTangent;
	#endif
#endif`,m_=`#ifdef USE_DISPLACEMENTMAP
	uniform sampler2D displacementMap;
	uniform float displacementScale;
	uniform float displacementBias;
#endif`,g_=`#ifdef USE_DISPLACEMENTMAP
	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,v_=`#ifdef USE_EMISSIVEMAP
	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
	#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
		emissiveColor = sRGBTransferEOTF( emissiveColor );
	#endif
	totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,__=`#ifdef USE_EMISSIVEMAP
	uniform sampler2D emissiveMap;
#endif`,S_="gl_FragColor = linearToOutputTexel( gl_FragColor );",b_=`vec4 LinearTransferOETF( in vec4 value ) {
	return value;
}
vec4 sRGBTransferEOTF( in vec4 value ) {
	return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
}
vec4 sRGBTransferOETF( in vec4 value ) {
	return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
}`,y_=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vec3 cameraToFrag;
		if ( isOrthographic ) {
			cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToFrag = normalize( vWorldPosition - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vec3 reflectVec = reflect( cameraToFrag, worldNormal );
		#else
			vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
		#endif
	#else
		vec3 reflectVec = vReflect;
	#endif
	#ifdef ENVMAP_TYPE_CUBE
		vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
	#else
		vec4 envColor = vec4( 0.0 );
	#endif
	#ifdef ENVMAP_BLENDING_MULTIPLY
		outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_MIX )
		outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_ADD )
		outgoingLight += envColor.xyz * specularStrength * reflectivity;
	#endif
#endif`,E_=`#ifdef USE_ENVMAP
	uniform float envMapIntensity;
	uniform float flipEnvMap;
	uniform mat3 envMapRotation;
	#ifdef ENVMAP_TYPE_CUBE
		uniform samplerCube envMap;
	#else
		uniform sampler2D envMap;
	#endif
	
#endif`,R_=`#ifdef USE_ENVMAP
	uniform float reflectivity;
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		varying vec3 vWorldPosition;
		uniform float refractionRatio;
	#else
		varying vec3 vReflect;
	#endif
#endif`,T_=`#ifdef USE_ENVMAP
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		
		varying vec3 vWorldPosition;
	#else
		varying vec3 vReflect;
		uniform float refractionRatio;
	#endif
#endif`,A_=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vWorldPosition = worldPosition.xyz;
	#else
		vec3 cameraToVertex;
		if ( isOrthographic ) {
			cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vReflect = reflect( cameraToVertex, worldNormal );
		#else
			vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
		#endif
	#endif
#endif`,C_=`#ifdef USE_FOG
	vFogDepth = - mvPosition.z;
#endif`,w_=`#ifdef USE_FOG
	varying float vFogDepth;
#endif`,M_=`#ifdef USE_FOG
	#ifdef FOG_EXP2
		float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
	#else
		float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
	#endif
	gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
#endif`,x_=`#ifdef USE_FOG
	uniform vec3 fogColor;
	varying float vFogDepth;
	#ifdef FOG_EXP2
		uniform float fogDensity;
	#else
		uniform float fogNear;
		uniform float fogFar;
	#endif
#endif`,I_=`#ifdef USE_GRADIENTMAP
	uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
	float dotNL = dot( normal, lightDirection );
	vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
	#ifdef USE_GRADIENTMAP
		return vec3( texture2D( gradientMap, coord ).r );
	#else
		vec2 fw = fwidth( coord ) * 0.5;
		return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
	#endif
}`,P_=`#ifdef USE_LIGHTMAP
	uniform sampler2D lightMap;
	uniform float lightMapIntensity;
#endif`,D_=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,L_=`varying vec3 vViewPosition;
struct LambertMaterial {
	vec3 diffuseColor;
	float specularStrength;
};
void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Lambert
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Lambert`,O_=`uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
	uniform vec3 lightProbe[ 9 ];
#endif
vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
	float x = normal.x, y = normal.y, z = normal.z;
	vec3 result = shCoefficients[ 0 ] * 0.886227;
	result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
	result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
	result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
	result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
	result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
	result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
	result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
	result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
	return result;
}
vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
	vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
	vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
	return irradiance;
}
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
	vec3 irradiance = ambientLightColor;
	return irradiance;
}
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
	float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
	if ( cutoffDistance > 0.0 ) {
		distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
	}
	return distanceFalloff;
}
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
	return smoothstep( coneCosine, penumbraCosine, angleCosine );
}
#if NUM_DIR_LIGHTS > 0
	struct DirectionalLight {
		vec3 direction;
		vec3 color;
	};
	uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
	void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
		light.color = directionalLight.color;
		light.direction = directionalLight.direction;
		light.visible = true;
	}
#endif
#if NUM_POINT_LIGHTS > 0
	struct PointLight {
		vec3 position;
		vec3 color;
		float distance;
		float decay;
	};
	uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
	void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = pointLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float lightDistance = length( lVector );
		light.color = pointLight.color;
		light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
		light.visible = ( light.color != vec3( 0.0 ) );
	}
#endif
#if NUM_SPOT_LIGHTS > 0
	struct SpotLight {
		vec3 position;
		vec3 direction;
		vec3 color;
		float distance;
		float decay;
		float coneCos;
		float penumbraCos;
	};
	uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
	void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = spotLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float angleCos = dot( light.direction, spotLight.direction );
		float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
		if ( spotAttenuation > 0.0 ) {
			float lightDistance = length( lVector );
			light.color = spotLight.color * spotAttenuation;
			light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
			light.visible = ( light.color != vec3( 0.0 ) );
		} else {
			light.color = vec3( 0.0 );
			light.visible = false;
		}
	}
#endif
#if NUM_RECT_AREA_LIGHTS > 0
	struct RectAreaLight {
		vec3 color;
		vec3 position;
		vec3 halfWidth;
		vec3 halfHeight;
	};
	uniform sampler2D ltc_1;	uniform sampler2D ltc_2;
	uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
#endif
#if NUM_HEMI_LIGHTS > 0
	struct HemisphereLight {
		vec3 direction;
		vec3 skyColor;
		vec3 groundColor;
	};
	uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
	vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
		float dotNL = dot( normal, hemiLight.direction );
		float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
		vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
		return irradiance;
	}
#endif`,N_=`#ifdef USE_ENVMAP
	vec3 getIBLIrradiance( const in vec3 normal ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
			return PI * envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 reflectVec = reflect( - viewDir, normal );
			reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
			reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
			return envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	#ifdef USE_ANISOTROPY
		vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
			#ifdef ENVMAP_TYPE_CUBE_UV
				vec3 bentNormal = cross( bitangent, viewDir );
				bentNormal = normalize( cross( bentNormal, bitangent ) );
				bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
				return getIBLRadiance( viewDir, bentNormal, roughness );
			#else
				return vec3( 0.0 );
			#endif
		}
	#endif
#endif`,k_=`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,U_=`varying vec3 vViewPosition;
struct ToonMaterial {
	vec3 diffuseColor;
};
void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Toon
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Toon`,B_=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,V_=`varying vec3 vViewPosition;
struct BlinnPhongMaterial {
	vec3 diffuseColor;
	vec3 specularColor;
	float specularShininess;
	float specularStrength;
};
void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
	reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
}
void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_BlinnPhong
#define RE_IndirectDiffuse		RE_IndirectDiffuse_BlinnPhong`,F_=`PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
material.roughness = min( material.roughness, 1.0 );
#ifdef IOR
	material.ior = ior;
	#ifdef USE_SPECULAR
		float specularIntensityFactor = specularIntensity;
		vec3 specularColorFactor = specularColor;
		#ifdef USE_SPECULAR_COLORMAP
			specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
		#endif
		#ifdef USE_SPECULAR_INTENSITYMAP
			specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
		#endif
		material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
	#else
		float specularIntensityFactor = 1.0;
		vec3 specularColorFactor = vec3( 1.0 );
		material.specularF90 = 1.0;
	#endif
	material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
#else
	material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
	material.specularF90 = 1.0;
#endif
#ifdef USE_CLEARCOAT
	material.clearcoat = clearcoat;
	material.clearcoatRoughness = clearcoatRoughness;
	material.clearcoatF0 = vec3( 0.04 );
	material.clearcoatF90 = 1.0;
	#ifdef USE_CLEARCOATMAP
		material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
	#endif
	#ifdef USE_CLEARCOAT_ROUGHNESSMAP
		material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
	#endif
	material.clearcoat = saturate( material.clearcoat );	material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
	material.clearcoatRoughness += geometryRoughness;
	material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
#endif
#ifdef USE_DISPERSION
	material.dispersion = dispersion;
#endif
#ifdef USE_IRIDESCENCE
	material.iridescence = iridescence;
	material.iridescenceIOR = iridescenceIOR;
	#ifdef USE_IRIDESCENCEMAP
		material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
	#endif
	#ifdef USE_IRIDESCENCE_THICKNESSMAP
		material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
	#else
		material.iridescenceThickness = iridescenceThicknessMaximum;
	#endif
#endif
#ifdef USE_SHEEN
	material.sheenColor = sheenColor;
	#ifdef USE_SHEEN_COLORMAP
		material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
	#endif
	material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
	#ifdef USE_SHEEN_ROUGHNESSMAP
		material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
	#endif
#endif
#ifdef USE_ANISOTROPY
	#ifdef USE_ANISOTROPYMAP
		mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
		vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
		vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
	#else
		vec2 anisotropyV = anisotropyVector;
	#endif
	material.anisotropy = length( anisotropyV );
	if( material.anisotropy == 0.0 ) {
		anisotropyV = vec2( 1.0, 0.0 );
	} else {
		anisotropyV /= material.anisotropy;
		material.anisotropy = saturate( material.anisotropy );
	}
	material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
	material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
	material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
#endif`,H_=`struct PhysicalMaterial {
	vec3 diffuseColor;
	float roughness;
	vec3 specularColor;
	float specularF90;
	float dispersion;
	#ifdef USE_CLEARCOAT
		float clearcoat;
		float clearcoatRoughness;
		vec3 clearcoatF0;
		float clearcoatF90;
	#endif
	#ifdef USE_IRIDESCENCE
		float iridescence;
		float iridescenceIOR;
		float iridescenceThickness;
		vec3 iridescenceFresnel;
		vec3 iridescenceF0;
	#endif
	#ifdef USE_SHEEN
		vec3 sheenColor;
		float sheenRoughness;
	#endif
	#ifdef IOR
		float ior;
	#endif
	#ifdef USE_TRANSMISSION
		float transmission;
		float transmissionAlpha;
		float thickness;
		float attenuationDistance;
		vec3 attenuationColor;
	#endif
	#ifdef USE_ANISOTROPY
		float anisotropy;
		float alphaT;
		vec3 anisotropyT;
		vec3 anisotropyB;
	#endif
};
vec3 clearcoatSpecularDirect = vec3( 0.0 );
vec3 clearcoatSpecularIndirect = vec3( 0.0 );
vec3 sheenSpecularDirect = vec3( 0.0 );
vec3 sheenSpecularIndirect = vec3(0.0 );
vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
    float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
    float x2 = x * x;
    float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
    return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
}
float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
	float a2 = pow2( alpha );
	float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
	float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
	return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX( const in float alpha, const in float dotNH ) {
	float a2 = pow2( alpha );
	float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
	return RECIPROCAL_PI * a2 / pow2( denom );
}
#ifdef USE_ANISOTROPY
	float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
		float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
		float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
		float v = 0.5 / ( gv + gl );
		return saturate(v);
	}
	float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
		float a2 = alphaT * alphaB;
		highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
		highp float v2 = dot( v, v );
		float w2 = a2 / v2;
		return RECIPROCAL_PI * a2 * pow2 ( w2 );
	}
#endif
#ifdef USE_CLEARCOAT
	vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
		vec3 f0 = material.clearcoatF0;
		float f90 = material.clearcoatF90;
		float roughness = material.clearcoatRoughness;
		float alpha = pow2( roughness );
		vec3 halfDir = normalize( lightDir + viewDir );
		float dotNL = saturate( dot( normal, lightDir ) );
		float dotNV = saturate( dot( normal, viewDir ) );
		float dotNH = saturate( dot( normal, halfDir ) );
		float dotVH = saturate( dot( viewDir, halfDir ) );
		vec3 F = F_Schlick( f0, f90, dotVH );
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
		return F * ( V * D );
	}
#endif
vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
	vec3 f0 = material.specularColor;
	float f90 = material.specularF90;
	float roughness = material.roughness;
	float alpha = pow2( roughness );
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( f0, f90, dotVH );
	#ifdef USE_IRIDESCENCE
		F = mix( F, material.iridescenceFresnel, material.iridescence );
	#endif
	#ifdef USE_ANISOTROPY
		float dotTL = dot( material.anisotropyT, lightDir );
		float dotTV = dot( material.anisotropyT, viewDir );
		float dotTH = dot( material.anisotropyT, halfDir );
		float dotBL = dot( material.anisotropyB, lightDir );
		float dotBV = dot( material.anisotropyB, viewDir );
		float dotBH = dot( material.anisotropyB, halfDir );
		float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
		float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
	#else
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
	#endif
	return F * ( V * D );
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
	const float LUT_SIZE = 64.0;
	const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
	const float LUT_BIAS = 0.5 / LUT_SIZE;
	float dotNV = saturate( dot( N, V ) );
	vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
	uv = uv * LUT_SCALE + LUT_BIAS;
	return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
	float l = length( f );
	return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
	float x = dot( v1, v2 );
	float y = abs( x );
	float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
	float b = 3.4175940 + ( 4.1616724 + y ) * y;
	float v = a / b;
	float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
	return cross( v1, v2 ) * theta_sintheta;
}
vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
	vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
	vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
	vec3 lightNormal = cross( v1, v2 );
	if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
	vec3 T1, T2;
	T1 = normalize( V - N * dot( V, N ) );
	T2 = - cross( N, T1 );
	mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
	vec3 coords[ 4 ];
	coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
	coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
	coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
	coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
	coords[ 0 ] = normalize( coords[ 0 ] );
	coords[ 1 ] = normalize( coords[ 1 ] );
	coords[ 2 ] = normalize( coords[ 2 ] );
	coords[ 3 ] = normalize( coords[ 3 ] );
	vec3 vectorFormFactor = vec3( 0.0 );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
	float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
	return vec3( result );
}
#if defined( USE_SHEEN )
float D_Charlie( float roughness, float dotNH ) {
	float alpha = pow2( roughness );
	float invAlpha = 1.0 / alpha;
	float cos2h = dotNH * dotNH;
	float sin2h = max( 1.0 - cos2h, 0.0078125 );
	return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
}
float V_Neubelt( float dotNV, float dotNL ) {
	return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
}
vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float D = D_Charlie( sheenRoughness, dotNH );
	float V = V_Neubelt( dotNV, dotNL );
	return sheenColor * ( D * V );
}
#endif
float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	float r2 = roughness * roughness;
	float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
	float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
	float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
	return saturate( DG * RECIPROCAL_PI );
}
vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
	const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
	vec4 r = roughness * c0 + c1;
	float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
	vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
	return fab;
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	return specularColor * fab.x + specularF90 * fab.y;
}
#ifdef USE_IRIDESCENCE
void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#else
void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#endif
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	#ifdef USE_IRIDESCENCE
		vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
	#else
		vec3 Fr = specularColor;
	#endif
	vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
	float Ess = fab.x + fab.y;
	float Ems = 1.0 - Ess;
	vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;	vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
	singleScatter += FssEss;
	multiScatter += Fms * Ems;
}
#if NUM_RECT_AREA_LIGHTS > 0
	void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
		vec3 normal = geometryNormal;
		vec3 viewDir = geometryViewDir;
		vec3 position = geometryPosition;
		vec3 lightPos = rectAreaLight.position;
		vec3 halfWidth = rectAreaLight.halfWidth;
		vec3 halfHeight = rectAreaLight.halfHeight;
		vec3 lightColor = rectAreaLight.color;
		float roughness = material.roughness;
		vec3 rectCoords[ 4 ];
		rectCoords[ 0 ] = lightPos + halfWidth - halfHeight;		rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
		rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
		rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
		vec2 uv = LTC_Uv( normal, viewDir, roughness );
		vec4 t1 = texture2D( ltc_1, uv );
		vec4 t2 = texture2D( ltc_2, uv );
		mat3 mInv = mat3(
			vec3( t1.x, 0, t1.y ),
			vec3(    0, 1,    0 ),
			vec3( t1.z, 0, t1.w )
		);
		vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
		reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
		reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
	}
#endif
void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	#ifdef USE_CLEARCOAT
		float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
		vec3 ccIrradiance = dotNLcc * directLight.color;
		clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
	#endif
	reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
	#ifdef USE_CLEARCOAT
		clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
	#endif
	vec3 singleScattering = vec3( 0.0 );
	vec3 multiScattering = vec3( 0.0 );
	vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
	#ifdef USE_IRIDESCENCE
		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
	#else
		computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
	#endif
	vec3 totalScattering = singleScattering + multiScattering;
	vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
	reflectedLight.indirectSpecular += radiance * singleScattering;
	reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
	reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
}
#define RE_Direct				RE_Direct_Physical
#define RE_Direct_RectArea		RE_Direct_RectArea_Physical
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Physical
#define RE_IndirectSpecular		RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
	return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
}`,G_=`
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
	geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
	float dotNVi = saturate( dot( normal, geometryViewDir ) );
	if ( material.iridescenceThickness == 0.0 ) {
		material.iridescence = 0.0;
	} else {
		material.iridescence = saturate( material.iridescence );
	}
	if ( material.iridescence > 0.0 ) {
		material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
		material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
	}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
	PointLight pointLight;
	#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
		pointLight = pointLights[ i ];
		getPointLightInfo( pointLight, geometryPosition, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
		pointLightShadow = pointLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
	SpotLight spotLight;
	vec4 spotColor;
	vec3 spotLightCoord;
	bool inSpotLightMap;
	#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
		spotLight = spotLights[ i ];
		getSpotLightInfo( spotLight, geometryPosition, directLight );
		#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
		#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
		#else
		#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#endif
		#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
			spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
			inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
			spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
			directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
		#endif
		#undef SPOT_LIGHT_MAP_INDEX
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		spotLightShadow = spotLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
	DirectionalLight directionalLight;
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
		directionalLight = directionalLights[ i ];
		getDirectionalLightInfo( directionalLight, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
		directionalLightShadow = directionalLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
	RectAreaLight rectAreaLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
		rectAreaLight = rectAreaLights[ i ];
		RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
	vec3 iblIrradiance = vec3( 0.0 );
	vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
	#if defined( USE_LIGHT_PROBES )
		irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
	#endif
	#if ( NUM_HEMI_LIGHTS > 0 )
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
			irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
		}
		#pragma unroll_loop_end
	#endif
#endif
#if defined( RE_IndirectSpecular )
	vec3 radiance = vec3( 0.0 );
	vec3 clearcoatRadiance = vec3( 0.0 );
#endif`,z_=`#if defined( RE_IndirectDiffuse )
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
		irradiance += lightMapIrradiance;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
		iblIrradiance += getIBLIrradiance( geometryNormal );
	#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
	#ifdef USE_ANISOTROPY
		radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
	#else
		radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
	#endif
	#ifdef USE_CLEARCOAT
		clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
	#endif
#endif`,W_=`#if defined( RE_IndirectDiffuse )
	RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
	RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif`,j_=`#if defined( USE_LOGDEPTHBUF )
	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,X_=`#if defined( USE_LOGDEPTHBUF )
	uniform float logDepthBufFC;
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,$_=`#ifdef USE_LOGDEPTHBUF
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,K_=`#ifdef USE_LOGDEPTHBUF
	vFragDepth = 1.0 + gl_Position.w;
	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,q_=`#ifdef USE_MAP
	vec4 sampledDiffuseColor = texture2D( map, vMapUv );
	#ifdef DECODE_VIDEO_TEXTURE
		sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
	#endif
	diffuseColor *= sampledDiffuseColor;
#endif`,Y_=`#ifdef USE_MAP
	uniform sampler2D map;
#endif`,J_=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
	#if defined( USE_POINTS_UV )
		vec2 uv = vUv;
	#else
		vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
	#endif
#endif
#ifdef USE_MAP
	diffuseColor *= texture2D( map, uv );
#endif
#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, uv ).g;
#endif`,Q_=`#if defined( USE_POINTS_UV )
	varying vec2 vUv;
#else
	#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
		uniform mat3 uvTransform;
	#endif
#endif
#ifdef USE_MAP
	uniform sampler2D map;
#endif
#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,Z_=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
	metalnessFactor *= texelMetalness.b;
#endif`,eS=`#ifdef USE_METALNESSMAP
	uniform sampler2D metalnessMap;
#endif`,tS=`#ifdef USE_INSTANCING_MORPH
	float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		morphTargetInfluences[i] =  texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
	}
#endif`,iS=`#if defined( USE_MORPHCOLORS )
	vColor *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		#if defined( USE_COLOR_ALPHA )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
		#elif defined( USE_COLOR )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
		#endif
	}
#endif`,nS=`#ifdef USE_MORPHNORMALS
	objectNormal *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
	}
#endif`,rS=`#ifdef USE_MORPHTARGETS
	#ifndef USE_INSTANCING_MORPH
		uniform float morphTargetBaseInfluence;
		uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	#endif
	uniform sampler2DArray morphTargetsTexture;
	uniform ivec2 morphTargetsTextureSize;
	vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
		int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
		int y = texelIndex / morphTargetsTextureSize.x;
		int x = texelIndex - y * morphTargetsTextureSize.x;
		ivec3 morphUV = ivec3( x, y, morphTargetIndex );
		return texelFetch( morphTargetsTexture, morphUV, 0 );
	}
#endif`,oS=`#ifdef USE_MORPHTARGETS
	transformed *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
	}
#endif`,sS=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
	vec3 fdx = dFdx( vViewPosition );
	vec3 fdy = dFdy( vViewPosition );
	vec3 normal = normalize( cross( fdx, fdy ) );
#else
	vec3 normal = normalize( vNormal );
	#ifdef DOUBLE_SIDED
		normal *= faceDirection;
	#endif
#endif
#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
	#ifdef USE_TANGENT
		mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn = getTangentFrame( - vViewPosition, normal,
		#if defined( USE_NORMALMAP )
			vNormalMapUv
		#elif defined( USE_CLEARCOAT_NORMALMAP )
			vClearcoatNormalMapUv
		#else
			vUv
		#endif
		);
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn[0] *= faceDirection;
		tbn[1] *= faceDirection;
	#endif
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	#ifdef USE_TANGENT
		mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn2[0] *= faceDirection;
		tbn2[1] *= faceDirection;
	#endif
#endif
vec3 nonPerturbedNormal = normal;`,aS=`#ifdef USE_NORMALMAP_OBJECTSPACE
	normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	#ifdef FLIP_SIDED
		normal = - normal;
	#endif
	#ifdef DOUBLE_SIDED
		normal = normal * faceDirection;
	#endif
	normal = normalize( normalMatrix * normal );
#elif defined( USE_NORMALMAP_TANGENTSPACE )
	vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	mapN.xy *= normalScale;
	normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
	normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`,cS=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,lS=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,uS=`#ifndef FLAT_SHADED
	vNormal = normalize( transformedNormal );
	#ifdef USE_TANGENT
		vTangent = normalize( transformedTangent );
		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
	#endif
#endif`,dS=`#ifdef USE_NORMALMAP
	uniform sampler2D normalMap;
	uniform vec2 normalScale;
#endif
#ifdef USE_NORMALMAP_OBJECTSPACE
	uniform mat3 normalMatrix;
#endif
#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
	mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
		vec3 q0 = dFdx( eye_pos.xyz );
		vec3 q1 = dFdy( eye_pos.xyz );
		vec2 st0 = dFdx( uv.st );
		vec2 st1 = dFdy( uv.st );
		vec3 N = surf_norm;
		vec3 q1perp = cross( q1, N );
		vec3 q0perp = cross( N, q0 );
		vec3 T = q1perp * st0.x + q0perp * st1.x;
		vec3 B = q1perp * st0.y + q0perp * st1.y;
		float det = max( dot( T, T ), dot( B, B ) );
		float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
		return mat3( T * scale, B * scale, N );
	}
#endif`,hS=`#ifdef USE_CLEARCOAT
	vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,pS=`#ifdef USE_CLEARCOAT_NORMALMAP
	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
	clearcoatMapN.xy *= clearcoatNormalScale;
	clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,fS=`#ifdef USE_CLEARCOATMAP
	uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform sampler2D clearcoatNormalMap;
	uniform vec2 clearcoatNormalScale;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform sampler2D clearcoatRoughnessMap;
#endif`,mS=`#ifdef USE_IRIDESCENCEMAP
	uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform sampler2D iridescenceThicknessMap;
#endif`,gS=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,vS=`vec3 packNormalToRGB( const in vec3 normal ) {
	return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
	return 2.0 * rgb.xyz - 1.0;
}
const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
const float Inv255 = 1. / 255.;
const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
vec4 packDepthToRGBA( const in float v ) {
	if( v <= 0.0 )
		return vec4( 0., 0., 0., 0. );
	if( v >= 1.0 )
		return vec4( 1., 1., 1., 1. );
	float vuf;
	float af = modf( v * PackFactors.a, vuf );
	float bf = modf( vuf * ShiftRight8, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
}
vec3 packDepthToRGB( const in float v ) {
	if( v <= 0.0 )
		return vec3( 0., 0., 0. );
	if( v >= 1.0 )
		return vec3( 1., 1., 1. );
	float vuf;
	float bf = modf( v * PackFactors.b, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec3( vuf * Inv255, gf * PackUpscale, bf );
}
vec2 packDepthToRG( const in float v ) {
	if( v <= 0.0 )
		return vec2( 0., 0. );
	if( v >= 1.0 )
		return vec2( 1., 1. );
	float vuf;
	float gf = modf( v * 256., vuf );
	return vec2( vuf * Inv255, gf );
}
float unpackRGBAToDepth( const in vec4 v ) {
	return dot( v, UnpackFactors4 );
}
float unpackRGBToDepth( const in vec3 v ) {
	return dot( v, UnpackFactors3 );
}
float unpackRGToDepth( const in vec2 v ) {
	return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
}
vec4 pack2HalfToRGBA( const in vec2 v ) {
	vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
	return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
}
vec2 unpackRGBATo2Half( const in vec4 v ) {
	return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
}
float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
	return ( viewZ + near ) / ( near - far );
}
float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return depth * ( near - far ) - near;
}
float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
	return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return ( near * far ) / ( ( far - near ) * depth - far );
}`,_S=`#ifdef PREMULTIPLIED_ALPHA
	gl_FragColor.rgb *= gl_FragColor.a;
#endif`,SS=`vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
	mvPosition = batchingMatrix * mvPosition;
#endif
#ifdef USE_INSTANCING
	mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
gl_Position = projectionMatrix * mvPosition;`,bS=`#ifdef DITHERING
	gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,yS=`#ifdef DITHERING
	vec3 dithering( vec3 color ) {
		float grid_position = rand( gl_FragCoord.xy );
		vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
		dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
		return color + dither_shift_RGB;
	}
#endif`,ES=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
	roughnessFactor *= texelRoughness.g;
#endif`,RS=`#ifdef USE_ROUGHNESSMAP
	uniform sampler2D roughnessMap;
#endif`,TS=`#if NUM_SPOT_LIGHT_COORDS > 0
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
	uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
	float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
		return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );
	}
	vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
		return unpackRGBATo2Half( texture2D( shadow, uv ) );
	}
	float VSMShadow (sampler2D shadow, vec2 uv, float compare ){
		float occlusion = 1.0;
		vec2 distribution = texture2DDistribution( shadow, uv );
		float hard_shadow = step( compare , distribution.x );
		if (hard_shadow != 1.0 ) {
			float distance = compare - distribution.x ;
			float variance = max( 0.00000, distribution.y * distribution.y );
			float softness_probability = variance / (variance + distance * distance );			softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );			occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
		}
		return occlusion;
	}
	float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
		float shadow = 1.0;
		shadowCoord.xyz /= shadowCoord.w;
		shadowCoord.z += shadowBias;
		bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
		bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
		if ( frustumTest ) {
		#if defined( SHADOWMAP_TYPE_PCF )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx0 = - texelSize.x * shadowRadius;
			float dy0 = - texelSize.y * shadowRadius;
			float dx1 = + texelSize.x * shadowRadius;
			float dy1 = + texelSize.y * shadowRadius;
			float dx2 = dx0 / 2.0;
			float dy2 = dy0 / 2.0;
			float dx3 = dx1 / 2.0;
			float dy3 = dy1 / 2.0;
			shadow = (
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
			) * ( 1.0 / 17.0 );
		#elif defined( SHADOWMAP_TYPE_PCF_SOFT )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx = texelSize.x;
			float dy = texelSize.y;
			vec2 uv = shadowCoord.xy;
			vec2 f = fract( uv * shadowMapSize + 0.5 );
			uv -= f * texelSize;
			shadow = (
				texture2DCompare( shadowMap, uv, shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
						  f.x ),
					 mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
						  f.x ),
					 f.y )
			) * ( 1.0 / 9.0 );
		#elif defined( SHADOWMAP_TYPE_VSM )
			shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
		#else
			shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
		#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
	vec2 cubeToUV( vec3 v, float texelSizeY ) {
		vec3 absV = abs( v );
		float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
		absV *= scaleToCube;
		v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
		vec2 planar = v.xy;
		float almostATexel = 1.5 * texelSizeY;
		float almostOne = 1.0 - almostATexel;
		if ( absV.z >= almostOne ) {
			if ( v.z > 0.0 )
				planar.x = 4.0 - v.x;
		} else if ( absV.x >= almostOne ) {
			float signX = sign( v.x );
			planar.x = v.z * signX + 2.0 * signX;
		} else if ( absV.y >= almostOne ) {
			float signY = sign( v.y );
			planar.x = v.x + 2.0 * signY + 2.0;
			planar.y = v.z * signY - 2.0;
		}
		return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
	}
	float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
		float shadow = 1.0;
		vec3 lightToPosition = shadowCoord.xyz;
		
		float lightToPositionLength = length( lightToPosition );
		if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
			float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );			dp += shadowBias;
			vec3 bd3D = normalize( lightToPosition );
			vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
			#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
				vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
				shadow = (
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
				) * ( 1.0 / 9.0 );
			#else
				shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
			#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
#endif`,AS=`#if NUM_SPOT_LIGHT_COORDS > 0
	uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
#endif`,CS=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
	vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
	vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
	#if NUM_DIR_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
			vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
			vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
#endif
#if NUM_SPOT_LIGHT_COORDS > 0
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
		shadowWorldPosition = worldPosition;
		#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
			shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
		#endif
		vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
	}
	#pragma unroll_loop_end
#endif`,wS=`float getShadowMask() {
	float shadow = 1.0;
	#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
		directionalLight = directionalLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
		spotLight = spotLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
		pointLight = pointLightShadows[ i ];
		shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#endif
	return shadow;
}`,MS=`#ifdef USE_SKINNING
	mat4 boneMatX = getBoneMatrix( skinIndex.x );
	mat4 boneMatY = getBoneMatrix( skinIndex.y );
	mat4 boneMatZ = getBoneMatrix( skinIndex.z );
	mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,xS=`#ifdef USE_SKINNING
	uniform mat4 bindMatrix;
	uniform mat4 bindMatrixInverse;
	uniform highp sampler2D boneTexture;
	mat4 getBoneMatrix( const in float i ) {
		int size = textureSize( boneTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
#endif`,IS=`#ifdef USE_SKINNING
	vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
	vec4 skinned = vec4( 0.0 );
	skinned += boneMatX * skinVertex * skinWeight.x;
	skinned += boneMatY * skinVertex * skinWeight.y;
	skinned += boneMatZ * skinVertex * skinWeight.z;
	skinned += boneMatW * skinVertex * skinWeight.w;
	transformed = ( bindMatrixInverse * skinned ).xyz;
#endif`,PS=`#ifdef USE_SKINNING
	mat4 skinMatrix = mat4( 0.0 );
	skinMatrix += skinWeight.x * boneMatX;
	skinMatrix += skinWeight.y * boneMatY;
	skinMatrix += skinWeight.z * boneMatZ;
	skinMatrix += skinWeight.w * boneMatW;
	skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
	objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
	#ifdef USE_TANGENT
		objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
	#endif
#endif`,DS=`float specularStrength;
#ifdef USE_SPECULARMAP
	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
	specularStrength = texelSpecular.r;
#else
	specularStrength = 1.0;
#endif`,LS=`#ifdef USE_SPECULARMAP
	uniform sampler2D specularMap;
#endif`,OS=`#if defined( TONE_MAPPING )
	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,NS=`#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
vec3 LinearToneMapping( vec3 color ) {
	return saturate( toneMappingExposure * color );
}
vec3 ReinhardToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	return saturate( color / ( vec3( 1.0 ) + color ) );
}
vec3 CineonToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	color = max( vec3( 0.0 ), color - 0.004 );
	return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
}
vec3 RRTAndODTFit( vec3 v ) {
	vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
	vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
	return a / b;
}
vec3 ACESFilmicToneMapping( vec3 color ) {
	const mat3 ACESInputMat = mat3(
		vec3( 0.59719, 0.07600, 0.02840 ),		vec3( 0.35458, 0.90834, 0.13383 ),
		vec3( 0.04823, 0.01566, 0.83777 )
	);
	const mat3 ACESOutputMat = mat3(
		vec3(  1.60475, -0.10208, -0.00327 ),		vec3( -0.53108,  1.10813, -0.07276 ),
		vec3( -0.07367, -0.00605,  1.07602 )
	);
	color *= toneMappingExposure / 0.6;
	color = ACESInputMat * color;
	color = RRTAndODTFit( color );
	color = ACESOutputMat * color;
	return saturate( color );
}
const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
	vec3( 1.6605, - 0.1246, - 0.0182 ),
	vec3( - 0.5876, 1.1329, - 0.1006 ),
	vec3( - 0.0728, - 0.0083, 1.1187 )
);
const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
	vec3( 0.6274, 0.0691, 0.0164 ),
	vec3( 0.3293, 0.9195, 0.0880 ),
	vec3( 0.0433, 0.0113, 0.8956 )
);
vec3 agxDefaultContrastApprox( vec3 x ) {
	vec3 x2 = x * x;
	vec3 x4 = x2 * x2;
	return + 15.5 * x4 * x2
		- 40.14 * x4 * x
		+ 31.96 * x4
		- 6.868 * x2 * x
		+ 0.4298 * x2
		+ 0.1191 * x
		- 0.00232;
}
vec3 AgXToneMapping( vec3 color ) {
	const mat3 AgXInsetMatrix = mat3(
		vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
		vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
		vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
	);
	const mat3 AgXOutsetMatrix = mat3(
		vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
		vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
		vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
	);
	const float AgxMinEv = - 12.47393;	const float AgxMaxEv = 4.026069;
	color *= toneMappingExposure;
	color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
	color = AgXInsetMatrix * color;
	color = max( color, 1e-10 );	color = log2( color );
	color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
	color = clamp( color, 0.0, 1.0 );
	color = agxDefaultContrastApprox( color );
	color = AgXOutsetMatrix * color;
	color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
	color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
	color = clamp( color, 0.0, 1.0 );
	return color;
}
vec3 NeutralToneMapping( vec3 color ) {
	const float StartCompression = 0.8 - 0.04;
	const float Desaturation = 0.15;
	color *= toneMappingExposure;
	float x = min( color.r, min( color.g, color.b ) );
	float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
	color -= offset;
	float peak = max( color.r, max( color.g, color.b ) );
	if ( peak < StartCompression ) return color;
	float d = 1. - StartCompression;
	float newPeak = 1. - d * d / ( peak + d - StartCompression );
	color *= newPeak / peak;
	float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
	return mix( color, vec3( newPeak ), g );
}
vec3 CustomToneMapping( vec3 color ) { return color; }`,kS=`#ifdef USE_TRANSMISSION
	material.transmission = transmission;
	material.transmissionAlpha = 1.0;
	material.thickness = thickness;
	material.attenuationDistance = attenuationDistance;
	material.attenuationColor = attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
	#endif
	#ifdef USE_THICKNESSMAP
		material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
	#endif
	vec3 pos = vWorldPosition;
	vec3 v = normalize( cameraPosition - pos );
	vec3 n = inverseTransformDirection( normal, viewMatrix );
	vec4 transmitted = getIBLVolumeRefraction(
		n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
		pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
		material.attenuationColor, material.attenuationDistance );
	material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
	totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
#endif`,US=`#ifdef USE_TRANSMISSION
	uniform float transmission;
	uniform float thickness;
	uniform float attenuationDistance;
	uniform vec3 attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		uniform sampler2D transmissionMap;
	#endif
	#ifdef USE_THICKNESSMAP
		uniform sampler2D thicknessMap;
	#endif
	uniform vec2 transmissionSamplerSize;
	uniform sampler2D transmissionSamplerMap;
	uniform mat4 modelMatrix;
	uniform mat4 projectionMatrix;
	varying vec3 vWorldPosition;
	float w0( float a ) {
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
	}
	float w1( float a ) {
		return ( 1.0 / 6.0 ) * ( a *  a * ( 3.0 * a - 6.0 ) + 4.0 );
	}
	float w2( float a ){
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
	}
	float w3( float a ) {
		return ( 1.0 / 6.0 ) * ( a * a * a );
	}
	float g0( float a ) {
		return w0( a ) + w1( a );
	}
	float g1( float a ) {
		return w2( a ) + w3( a );
	}
	float h0( float a ) {
		return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
	}
	float h1( float a ) {
		return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
	}
	vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
		uv = uv * texelSize.zw + 0.5;
		vec2 iuv = floor( uv );
		vec2 fuv = fract( uv );
		float g0x = g0( fuv.x );
		float g1x = g1( fuv.x );
		float h0x = h0( fuv.x );
		float h1x = h1( fuv.x );
		float h0y = h0( fuv.y );
		float h1y = h1( fuv.y );
		vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
			g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
	}
	vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
		vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
		vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
		vec2 fLodSizeInv = 1.0 / fLodSize;
		vec2 cLodSizeInv = 1.0 / cLodSize;
		vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
		vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
		return mix( fSample, cSample, fract( lod ) );
	}
	vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
		vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
		vec3 modelScale;
		modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
		modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
		modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
		return normalize( refractionVector ) * thickness * modelScale;
	}
	float applyIorToRoughness( const in float roughness, const in float ior ) {
		return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
	}
	vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
		float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
		return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
	}
	vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
		if ( isinf( attenuationDistance ) ) {
			return vec3( 1.0 );
		} else {
			vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
			vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );			return transmittance;
		}
	}
	vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
		const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
		const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
		const in vec3 attenuationColor, const in float attenuationDistance ) {
		vec4 transmittedLight;
		vec3 transmittance;
		#ifdef USE_DISPERSION
			float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
			vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
			for ( int i = 0; i < 3; i ++ ) {
				vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
				vec3 refractedRayExit = position + transmissionRay;
				vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
				vec2 refractionCoords = ndcPos.xy / ndcPos.w;
				refractionCoords += 1.0;
				refractionCoords /= 2.0;
				vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
				transmittedLight[ i ] = transmissionSample[ i ];
				transmittedLight.a += transmissionSample.a;
				transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
			}
			transmittedLight.a /= 3.0;
		#else
			vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
			vec3 refractedRayExit = position + transmissionRay;
			vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
			vec2 refractionCoords = ndcPos.xy / ndcPos.w;
			refractionCoords += 1.0;
			refractionCoords /= 2.0;
			transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
			transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
		#endif
		vec3 attenuatedColor = transmittance * transmittedLight.rgb;
		vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
		float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
		return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
	}
#endif`,BS=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_SPECULARMAP
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`,VS=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	uniform mat3 mapTransform;
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	uniform mat3 alphaMapTransform;
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	uniform mat3 lightMapTransform;
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	uniform mat3 aoMapTransform;
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	uniform mat3 bumpMapTransform;
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	uniform mat3 normalMapTransform;
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_DISPLACEMENTMAP
	uniform mat3 displacementMapTransform;
	varying vec2 vDisplacementMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	uniform mat3 emissiveMapTransform;
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	uniform mat3 metalnessMapTransform;
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	uniform mat3 roughnessMapTransform;
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	uniform mat3 anisotropyMapTransform;
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	uniform mat3 clearcoatMapTransform;
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform mat3 clearcoatNormalMapTransform;
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform mat3 clearcoatRoughnessMapTransform;
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	uniform mat3 sheenColorMapTransform;
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	uniform mat3 sheenRoughnessMapTransform;
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	uniform mat3 iridescenceMapTransform;
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform mat3 iridescenceThicknessMapTransform;
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SPECULARMAP
	uniform mat3 specularMapTransform;
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	uniform mat3 specularColorMapTransform;
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	uniform mat3 specularIntensityMapTransform;
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`,FS=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	vUv = vec3( uv, 1 ).xy;
#endif
#ifdef USE_MAP
	vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ALPHAMAP
	vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_LIGHTMAP
	vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_AOMAP
	vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_BUMPMAP
	vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_NORMALMAP
	vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_DISPLACEMENTMAP
	vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_EMISSIVEMAP
	vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_METALNESSMAP
	vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ROUGHNESSMAP
	vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ANISOTROPYMAP
	vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOATMAP
	vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCEMAP
	vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_COLORMAP
	vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULARMAP
	vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_COLORMAP
	vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_TRANSMISSIONMAP
	vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_THICKNESSMAP
	vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
#endif`,HS=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
	vec4 worldPosition = vec4( transformed, 1.0 );
	#ifdef USE_BATCHING
		worldPosition = batchingMatrix * worldPosition;
	#endif
	#ifdef USE_INSTANCING
		worldPosition = instanceMatrix * worldPosition;
	#endif
	worldPosition = modelMatrix * worldPosition;
#endif`;const ht={alphahash_fragment:z0,alphahash_pars_fragment:W0,alphamap_fragment:j0,alphamap_pars_fragment:X0,alphatest_fragment:$0,alphatest_pars_fragment:K0,aomap_fragment:q0,aomap_pars_fragment:Y0,batching_pars_vertex:J0,batching_vertex:Q0,begin_vertex:Z0,beginnormal_vertex:e_,bsdfs:t_,iridescence_fragment:i_,bumpmap_pars_fragment:n_,clipping_planes_fragment:r_,clipping_planes_pars_fragment:o_,clipping_planes_pars_vertex:s_,clipping_planes_vertex:a_,color_fragment:c_,color_pars_fragment:l_,color_pars_vertex:u_,color_vertex:d_,common:h_,cube_uv_reflection_fragment:p_,defaultnormal_vertex:f_,displacementmap_pars_vertex:m_,displacementmap_vertex:g_,emissivemap_fragment:v_,emissivemap_pars_fragment:__,colorspace_fragment:S_,colorspace_pars_fragment:b_,envmap_fragment:y_,envmap_common_pars_fragment:E_,envmap_pars_fragment:R_,envmap_pars_vertex:T_,envmap_physical_pars_fragment:N_,envmap_vertex:A_,fog_vertex:C_,fog_pars_vertex:w_,fog_fragment:M_,fog_pars_fragment:x_,gradientmap_pars_fragment:I_,lightmap_pars_fragment:P_,lights_lambert_fragment:D_,lights_lambert_pars_fragment:L_,lights_pars_begin:O_,lights_toon_fragment:k_,lights_toon_pars_fragment:U_,lights_phong_fragment:B_,lights_phong_pars_fragment:V_,lights_physical_fragment:F_,lights_physical_pars_fragment:H_,lights_fragment_begin:G_,lights_fragment_maps:z_,lights_fragment_end:W_,logdepthbuf_fragment:j_,logdepthbuf_pars_fragment:X_,logdepthbuf_pars_vertex:$_,logdepthbuf_vertex:K_,map_fragment:q_,map_pars_fragment:Y_,map_particle_fragment:J_,map_particle_pars_fragment:Q_,metalnessmap_fragment:Z_,metalnessmap_pars_fragment:eS,morphinstance_vertex:tS,morphcolor_vertex:iS,morphnormal_vertex:nS,morphtarget_pars_vertex:rS,morphtarget_vertex:oS,normal_fragment_begin:sS,normal_fragment_maps:aS,normal_pars_fragment:cS,normal_pars_vertex:lS,normal_vertex:uS,normalmap_pars_fragment:dS,clearcoat_normal_fragment_begin:hS,clearcoat_normal_fragment_maps:pS,clearcoat_pars_fragment:fS,iridescence_pars_fragment:mS,opaque_fragment:gS,packing:vS,premultiplied_alpha_fragment:_S,project_vertex:SS,dithering_fragment:bS,dithering_pars_fragment:yS,roughnessmap_fragment:ES,roughnessmap_pars_fragment:RS,shadowmap_pars_fragment:TS,shadowmap_pars_vertex:AS,shadowmap_vertex:CS,shadowmask_pars_fragment:wS,skinbase_vertex:MS,skinning_pars_vertex:xS,skinning_vertex:IS,skinnormal_vertex:PS,specularmap_fragment:DS,specularmap_pars_fragment:LS,tonemapping_fragment:OS,tonemapping_pars_fragment:NS,transmission_fragment:kS,transmission_pars_fragment:US,uv_pars_fragment:BS,uv_pars_vertex:VS,uv_vertex:FS,worldpos_vertex:HS,background_vert:`varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
	vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	gl_Position = vec4( position.xy, 1.0, 1.0 );
}`,background_frag:`uniform sampler2D t2D;
uniform float backgroundIntensity;
varying vec2 vUv;
void main() {
	vec4 texColor = texture2D( t2D, vUv );
	#ifdef DECODE_VIDEO_TEXTURE
		texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,backgroundCube_vert:`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`,backgroundCube_frag:`#ifdef ENVMAP_TYPE_CUBE
	uniform samplerCube envMap;
#elif defined( ENVMAP_TYPE_CUBE_UV )
	uniform sampler2D envMap;
#endif
uniform float flipEnvMap;
uniform float backgroundBlurriness;
uniform float backgroundIntensity;
uniform mat3 backgroundRotation;
varying vec3 vWorldDirection;
#include <cube_uv_reflection_fragment>
void main() {
	#ifdef ENVMAP_TYPE_CUBE
		vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
	#elif defined( ENVMAP_TYPE_CUBE_UV )
		vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
	#else
		vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,cube_vert:`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`,cube_frag:`uniform samplerCube tCube;
uniform float tFlip;
uniform float opacity;
varying vec3 vWorldDirection;
void main() {
	vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
	gl_FragColor = texColor;
	gl_FragColor.a *= opacity;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,depth_vert:`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
varying vec2 vHighPrecisionZW;
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vHighPrecisionZW = gl_Position.zw;
}`,depth_frag:`#if DEPTH_PACKING == 3200
	uniform float opacity;
#endif
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
varying vec2 vHighPrecisionZW;
void main() {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#if DEPTH_PACKING == 3200
		diffuseColor.a = opacity;
	#endif
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <logdepthbuf_fragment>
	float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;
	#if DEPTH_PACKING == 3200
		gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
	#elif DEPTH_PACKING == 3201
		gl_FragColor = packDepthToRGBA( fragCoordZ );
	#elif DEPTH_PACKING == 3202
		gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
	#elif DEPTH_PACKING == 3203
		gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
	#endif
}`,distanceRGBA_vert:`#define DISTANCE
varying vec3 vWorldPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <worldpos_vertex>
	#include <clipping_planes_vertex>
	vWorldPosition = worldPosition.xyz;
}`,distanceRGBA_frag:`#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <clipping_planes_pars_fragment>
void main () {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	float dist = length( vWorldPosition - referencePosition );
	dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
	dist = saturate( dist );
	gl_FragColor = packDepthToRGBA( dist );
}`,equirect_vert:`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
}`,equirect_frag:`uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
	vec3 direction = normalize( vWorldDirection );
	vec2 sampleUV = equirectUv( direction );
	gl_FragColor = texture2D( tEquirect, sampleUV );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,linedashed_vert:`uniform float scale;
attribute float lineDistance;
varying float vLineDistance;
#include <common>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	vLineDistance = scale * lineDistance;
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`,linedashed_frag:`uniform vec3 diffuse;
uniform float opacity;
uniform float dashSize;
uniform float totalSize;
varying float vLineDistance;
#include <common>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	if ( mod( vLineDistance, totalSize ) > dashSize ) {
		discard;
	}
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`,meshbasic_vert:`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinbase_vertex>
		#include <skinnormal_vertex>
		#include <defaultnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <fog_vertex>
}`,meshbasic_frag:`uniform vec3 diffuse;
uniform float opacity;
#ifndef FLAT_SHADED
	varying vec3 vNormal;
#endif
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
	#else
		reflectedLight.indirectDiffuse += vec3( 1.0 );
	#endif
	#include <aomap_fragment>
	reflectedLight.indirectDiffuse *= diffuseColor.rgb;
	vec3 outgoingLight = reflectedLight.indirectDiffuse;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,meshlambert_vert:`#define LAMBERT
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,meshlambert_frag:`#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_lambert_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_lambert_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,meshmatcap_vert:`#define MATCAP
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <displacementmap_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
	vViewPosition = - mvPosition.xyz;
}`,meshmatcap_frag:`#define MATCAP
uniform vec3 diffuse;
uniform float opacity;
uniform sampler2D matcap;
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	vec3 viewDir = normalize( vViewPosition );
	vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
	vec3 y = cross( viewDir, x );
	vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
	#ifdef USE_MATCAP
		vec4 matcapColor = texture2D( matcap, uv );
	#else
		vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
	#endif
	vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,meshnormal_vert:`#define NORMAL
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	vViewPosition = - mvPosition.xyz;
#endif
}`,meshnormal_frag:`#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <packing>
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
	#ifdef OPAQUE
		gl_FragColor.a = 1.0;
	#endif
}`,meshphong_vert:`#define PHONG
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,meshphong_frag:`#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_phong_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_phong_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,meshphysical_vert:`#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
	varying vec3 vWorldPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
#ifdef USE_TRANSMISSION
	vWorldPosition = worldPosition.xyz;
#endif
}`,meshphysical_frag:`#define STANDARD
#ifdef PHYSICAL
	#define IOR
	#define USE_SPECULAR
#endif
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float roughness;
uniform float metalness;
uniform float opacity;
#ifdef IOR
	uniform float ior;
#endif
#ifdef USE_SPECULAR
	uniform float specularIntensity;
	uniform vec3 specularColor;
	#ifdef USE_SPECULAR_COLORMAP
		uniform sampler2D specularColorMap;
	#endif
	#ifdef USE_SPECULAR_INTENSITYMAP
		uniform sampler2D specularIntensityMap;
	#endif
#endif
#ifdef USE_CLEARCOAT
	uniform float clearcoat;
	uniform float clearcoatRoughness;
#endif
#ifdef USE_DISPERSION
	uniform float dispersion;
#endif
#ifdef USE_IRIDESCENCE
	uniform float iridescence;
	uniform float iridescenceIOR;
	uniform float iridescenceThicknessMinimum;
	uniform float iridescenceThicknessMaximum;
#endif
#ifdef USE_SHEEN
	uniform vec3 sheenColor;
	uniform float sheenRoughness;
	#ifdef USE_SHEEN_COLORMAP
		uniform sampler2D sheenColorMap;
	#endif
	#ifdef USE_SHEEN_ROUGHNESSMAP
		uniform sampler2D sheenRoughnessMap;
	#endif
#endif
#ifdef USE_ANISOTROPY
	uniform vec2 anisotropyVector;
	#ifdef USE_ANISOTROPYMAP
		uniform sampler2D anisotropyMap;
	#endif
#endif
varying vec3 vViewPosition;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <iridescence_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_physical_pars_fragment>
#include <transmission_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <clearcoat_pars_fragment>
#include <iridescence_pars_fragment>
#include <roughnessmap_pars_fragment>
#include <metalnessmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <roughnessmap_fragment>
	#include <metalnessmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <clearcoat_normal_fragment_begin>
	#include <clearcoat_normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_physical_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
	vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
	#include <transmission_fragment>
	vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
	#ifdef USE_SHEEN
		float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
		outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
	#endif
	#ifdef USE_CLEARCOAT
		float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
		vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
		outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
	#endif
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,meshtoon_vert:`#define TOON
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,meshtoon_frag:`#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <gradientmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_toon_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_toon_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,points_vert:`uniform float size;
uniform float scale;
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
#ifdef USE_POINTS_UV
	varying vec2 vUv;
	uniform mat3 uvTransform;
#endif
void main() {
	#ifdef USE_POINTS_UV
		vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	#endif
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	gl_PointSize = size;
	#ifdef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
	#endif
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <fog_vertex>
}`,points_frag:`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <color_pars_fragment>
#include <map_particle_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_particle_fragment>
	#include <color_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`,shadow_vert:`#include <common>
#include <batching_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <shadowmap_pars_vertex>
void main() {
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,shadow_frag:`uniform vec3 color;
uniform float opacity;
#include <common>
#include <packing>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <logdepthbuf_pars_fragment>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
	#include <logdepthbuf_fragment>
	gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`,sprite_vert:`uniform float rotation;
uniform vec2 center;
#include <common>
#include <uv_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	vec4 mvPosition = modelViewMatrix[ 3 ];
	vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
	#ifndef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) scale *= - mvPosition.z;
	#endif
	vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
	vec2 rotatedPosition;
	rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
	rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
	mvPosition.xy += rotatedPosition;
	gl_Position = projectionMatrix * mvPosition;
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`,sprite_frag:`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`},je={common:{diffuse:{value:new It(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new dt},alphaMap:{value:null},alphaMapTransform:{value:new dt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new dt}},envmap:{envMap:{value:null},envMapRotation:{value:new dt},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new dt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new dt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new dt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new dt},normalScale:{value:new xt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new dt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new dt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new dt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new dt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new It(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new It(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new dt},alphaTest:{value:0},uvTransform:{value:new dt}},sprite:{diffuse:{value:new It(16777215)},opacity:{value:1},center:{value:new xt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new dt},alphaMap:{value:null},alphaMapTransform:{value:new dt},alphaTest:{value:0}}},vn={basic:{uniforms:di([je.common,je.specularmap,je.envmap,je.aomap,je.lightmap,je.fog]),vertexShader:ht.meshbasic_vert,fragmentShader:ht.meshbasic_frag},lambert:{uniforms:di([je.common,je.specularmap,je.envmap,je.aomap,je.lightmap,je.emissivemap,je.bumpmap,je.normalmap,je.displacementmap,je.fog,je.lights,{emissive:{value:new It(0)}}]),vertexShader:ht.meshlambert_vert,fragmentShader:ht.meshlambert_frag},phong:{uniforms:di([je.common,je.specularmap,je.envmap,je.aomap,je.lightmap,je.emissivemap,je.bumpmap,je.normalmap,je.displacementmap,je.fog,je.lights,{emissive:{value:new It(0)},specular:{value:new It(1118481)},shininess:{value:30}}]),vertexShader:ht.meshphong_vert,fragmentShader:ht.meshphong_frag},standard:{uniforms:di([je.common,je.envmap,je.aomap,je.lightmap,je.emissivemap,je.bumpmap,je.normalmap,je.displacementmap,je.roughnessmap,je.metalnessmap,je.fog,je.lights,{emissive:{value:new It(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ht.meshphysical_vert,fragmentShader:ht.meshphysical_frag},toon:{uniforms:di([je.common,je.aomap,je.lightmap,je.emissivemap,je.bumpmap,je.normalmap,je.displacementmap,je.gradientmap,je.fog,je.lights,{emissive:{value:new It(0)}}]),vertexShader:ht.meshtoon_vert,fragmentShader:ht.meshtoon_frag},matcap:{uniforms:di([je.common,je.bumpmap,je.normalmap,je.displacementmap,je.fog,{matcap:{value:null}}]),vertexShader:ht.meshmatcap_vert,fragmentShader:ht.meshmatcap_frag},points:{uniforms:di([je.points,je.fog]),vertexShader:ht.points_vert,fragmentShader:ht.points_frag},dashed:{uniforms:di([je.common,je.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ht.linedashed_vert,fragmentShader:ht.linedashed_frag},depth:{uniforms:di([je.common,je.displacementmap]),vertexShader:ht.depth_vert,fragmentShader:ht.depth_frag},normal:{uniforms:di([je.common,je.bumpmap,je.normalmap,je.displacementmap,{opacity:{value:1}}]),vertexShader:ht.meshnormal_vert,fragmentShader:ht.meshnormal_frag},sprite:{uniforms:di([je.sprite,je.fog]),vertexShader:ht.sprite_vert,fragmentShader:ht.sprite_frag},background:{uniforms:{uvTransform:{value:new dt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ht.background_vert,fragmentShader:ht.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new dt}},vertexShader:ht.backgroundCube_vert,fragmentShader:ht.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ht.cube_vert,fragmentShader:ht.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ht.equirect_vert,fragmentShader:ht.equirect_frag},distanceRGBA:{uniforms:di([je.common,je.displacementmap,{referencePosition:{value:new we},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ht.distanceRGBA_vert,fragmentShader:ht.distanceRGBA_frag},shadow:{uniforms:di([je.lights,je.fog,{color:{value:new It(0)},opacity:{value:1}}]),vertexShader:ht.shadow_vert,fragmentShader:ht.shadow_frag}};vn.physical={uniforms:di([vn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new dt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new dt},clearcoatNormalScale:{value:new xt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new dt},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new dt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new dt},sheen:{value:0},sheenColor:{value:new It(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new dt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new dt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new dt},transmissionSamplerSize:{value:new xt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new dt},attenuationDistance:{value:0},attenuationColor:{value:new It(0)},specularColor:{value:new It(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new dt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new dt},anisotropyVector:{value:new xt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new dt}}]),vertexShader:ht.meshphysical_vert,fragmentShader:ht.meshphysical_frag};const js={r:0,b:0,g:0},Rr=new Dn,GS=new jt;function zS(i,e,t,n,r,a,s){const o=new It(0);let c=a===!0?0:1,h,l,f=null,v=0,p=null;function _(y){let g=y.isScene===!0?y.background:null;return g&&g.isTexture&&(g=(y.backgroundBlurriness>0?t:e).get(g)),g}function m(y){let g=!1;const S=_(y);S===null?u(o,c):S&&S.isColor&&(u(S,1),g=!0);const R=i.xr.getEnvironmentBlendMode();R==="additive"?n.buffers.color.setClear(0,0,0,1,s):R==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,s),(i.autoClear||g)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function d(y,g){const S=_(g);S&&(S.isCubeTexture||S.mapping===gs)?(l===void 0&&(l=new gn(new Fo(1,1,1),new kn({name:"BackgroundCubeMaterial",uniforms:ao(vn.backgroundCube.uniforms),vertexShader:vn.backgroundCube.vertexShader,fragmentShader:vn.backgroundCube.fragmentShader,side:yi,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(R,E,I){this.matrixWorld.copyPosition(I.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(l)),Rr.copy(g.backgroundRotation),Rr.x*=-1,Rr.y*=-1,Rr.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(Rr.y*=-1,Rr.z*=-1),l.material.uniforms.envMap.value=S,l.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,l.material.uniforms.backgroundBlurriness.value=g.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(GS.makeRotationFromEuler(Rr)),l.material.toneMapped=Et.getTransfer(S.colorSpace)!==Mt,(f!==S||v!==S.version||p!==i.toneMapping)&&(l.material.needsUpdate=!0,f=S,v=S.version,p=i.toneMapping),l.layers.enableAll(),y.unshift(l,l.geometry,l.material,0,0,null)):S&&S.isTexture&&(h===void 0&&(h=new gn(new Ho(2,2),new kn({name:"BackgroundMaterial",uniforms:ao(vn.background.uniforms),vertexShader:vn.background.vertexShader,fragmentShader:vn.background.fragmentShader,side:Kn,depthTest:!1,depthWrite:!1,fog:!1})),h.geometry.deleteAttribute("normal"),Object.defineProperty(h.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(h)),h.material.uniforms.t2D.value=S,h.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,h.material.toneMapped=Et.getTransfer(S.colorSpace)!==Mt,S.matrixAutoUpdate===!0&&S.updateMatrix(),h.material.uniforms.uvTransform.value.copy(S.matrix),(f!==S||v!==S.version||p!==i.toneMapping)&&(h.material.needsUpdate=!0,f=S,v=S.version,p=i.toneMapping),h.layers.enableAll(),y.unshift(h,h.geometry,h.material,0,0,null))}function u(y,g){y.getRGB(js,Mp(i)),n.buffers.color.setClear(js.r,js.g,js.b,g,s)}function b(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),h!==void 0&&(h.geometry.dispose(),h.material.dispose(),h=void 0)}return{getClearColor:function(){return o},setClearColor:function(y,g=1){o.set(y),c=g,u(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(y){c=y,u(o,c)},render:m,addToRenderList:d,dispose:b}}function WS(i,e){const t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},r=v(null);let a=r,s=!1;function o(A,w,N,M,D){let L=!1;const P=f(M,N,w);a!==P&&(a=P,h(a.object)),L=p(A,M,N,D),L&&_(A,M,N,D),D!==null&&e.update(D,i.ELEMENT_ARRAY_BUFFER),(L||s)&&(s=!1,g(A,w,N,M),D!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get(D).buffer))}function c(){return i.createVertexArray()}function h(A){return i.bindVertexArray(A)}function l(A){return i.deleteVertexArray(A)}function f(A,w,N){const M=N.wireframe===!0;let D=n[A.id];D===void 0&&(D={},n[A.id]=D);let L=D[w.id];L===void 0&&(L={},D[w.id]=L);let P=L[M];return P===void 0&&(P=v(c()),L[M]=P),P}function v(A){const w=[],N=[],M=[];for(let D=0;D<t;D++)w[D]=0,N[D]=0,M[D]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:w,enabledAttributes:N,attributeDivisors:M,object:A,attributes:{},index:null}}function p(A,w,N,M){const D=a.attributes,L=w.attributes;let P=0;const x=N.getAttributes();for(const T in x)if(x[T].location>=0){const k=D[T];let H=L[T];if(H===void 0&&(T==="instanceMatrix"&&A.instanceMatrix&&(H=A.instanceMatrix),T==="instanceColor"&&A.instanceColor&&(H=A.instanceColor)),k===void 0||k.attribute!==H||H&&k.data!==H.data)return!0;P++}return a.attributesNum!==P||a.index!==M}function _(A,w,N,M){const D={},L=w.attributes;let P=0;const x=N.getAttributes();for(const T in x)if(x[T].location>=0){let k=L[T];k===void 0&&(T==="instanceMatrix"&&A.instanceMatrix&&(k=A.instanceMatrix),T==="instanceColor"&&A.instanceColor&&(k=A.instanceColor));const H={};H.attribute=k,k&&k.data&&(H.data=k.data),D[T]=H,P++}a.attributes=D,a.attributesNum=P,a.index=M}function m(){const A=a.newAttributes;for(let w=0,N=A.length;w<N;w++)A[w]=0}function d(A){u(A,0)}function u(A,w){const N=a.newAttributes,M=a.enabledAttributes,D=a.attributeDivisors;N[A]=1,M[A]===0&&(i.enableVertexAttribArray(A),M[A]=1),D[A]!==w&&(i.vertexAttribDivisor(A,w),D[A]=w)}function b(){const A=a.newAttributes,w=a.enabledAttributes;for(let N=0,M=w.length;N<M;N++)w[N]!==A[N]&&(i.disableVertexAttribArray(N),w[N]=0)}function y(A,w,N,M,D,L,P){P===!0?i.vertexAttribIPointer(A,w,N,D,L):i.vertexAttribPointer(A,w,N,M,D,L)}function g(A,w,N,M){m();const D=M.attributes,L=N.getAttributes(),P=w.defaultAttributeValues;for(const x in L){const T=L[x];if(T.location>=0){let O=D[x];if(O===void 0&&(x==="instanceMatrix"&&A.instanceMatrix&&(O=A.instanceMatrix),x==="instanceColor"&&A.instanceColor&&(O=A.instanceColor)),O!==void 0){const k=O.normalized,H=O.itemSize,U=e.get(O);if(U===void 0)continue;const ee=U.buffer,W=U.type,$=U.bytesPerElement,B=W===i.INT||W===i.UNSIGNED_INT||O.gpuType===bc;if(O.isInterleavedBufferAttribute){const F=O.data,G=F.stride,q=O.offset;if(F.isInstancedInterleavedBuffer){for(let X=0;X<T.locationSize;X++)u(T.location+X,F.meshPerAttribute);A.isInstancedMesh!==!0&&M._maxInstanceCount===void 0&&(M._maxInstanceCount=F.meshPerAttribute*F.count)}else for(let X=0;X<T.locationSize;X++)d(T.location+X);i.bindBuffer(i.ARRAY_BUFFER,ee);for(let X=0;X<T.locationSize;X++)y(T.location+X,H/T.locationSize,W,k,G*$,(q+H/T.locationSize*X)*$,B)}else{if(O.isInstancedBufferAttribute){for(let F=0;F<T.locationSize;F++)u(T.location+F,O.meshPerAttribute);A.isInstancedMesh!==!0&&M._maxInstanceCount===void 0&&(M._maxInstanceCount=O.meshPerAttribute*O.count)}else for(let F=0;F<T.locationSize;F++)d(T.location+F);i.bindBuffer(i.ARRAY_BUFFER,ee);for(let F=0;F<T.locationSize;F++)y(T.location+F,H/T.locationSize,W,k,H*$,H/T.locationSize*F*$,B)}}else if(P!==void 0){const k=P[x];if(k!==void 0)switch(k.length){case 2:i.vertexAttrib2fv(T.location,k);break;case 3:i.vertexAttrib3fv(T.location,k);break;case 4:i.vertexAttrib4fv(T.location,k);break;default:i.vertexAttrib1fv(T.location,k)}}}}b()}function S(){I();for(const A in n){const w=n[A];for(const N in w){const M=w[N];for(const D in M)l(M[D].object),delete M[D];delete w[N]}delete n[A]}}function R(A){if(n[A.id]===void 0)return;const w=n[A.id];for(const N in w){const M=w[N];for(const D in M)l(M[D].object),delete M[D];delete w[N]}delete n[A.id]}function E(A){for(const w in n){const N=n[w];if(N[A.id]===void 0)continue;const M=N[A.id];for(const D in M)l(M[D].object),delete M[D];delete N[A.id]}}function I(){C(),s=!0,a!==r&&(a=r,h(a.object))}function C(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:o,reset:I,resetDefaultState:C,dispose:S,releaseStatesOfGeometry:R,releaseStatesOfProgram:E,initAttributes:m,enableAttribute:d,disableUnusedAttributes:b}}function jS(i,e,t){let n;function r(h){n=h}function a(h,l){i.drawArrays(n,h,l),t.update(l,n,1)}function s(h,l,f){f!==0&&(i.drawArraysInstanced(n,h,l,f),t.update(l,n,f))}function o(h,l,f){if(f===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,h,0,l,0,f);let p=0;for(let _=0;_<f;_++)p+=l[_];t.update(p,n,1)}function c(h,l,f,v){if(f===0)return;const p=e.get("WEBGL_multi_draw");if(p===null)for(let _=0;_<h.length;_++)s(h[_],l[_],v[_]);else{p.multiDrawArraysInstancedWEBGL(n,h,0,l,0,v,0,f);let _=0;for(let m=0;m<f;m++)_+=l[m]*v[m];t.update(_,n,1)}}this.setMode=r,this.render=a,this.renderInstances=s,this.renderMultiDraw=o,this.renderMultiDrawInstances=c}function XS(i,e,t,n){let r;function a(){if(r!==void 0)return r;if(e.has("EXT_texture_filter_anisotropic")===!0){const E=e.get("EXT_texture_filter_anisotropic");r=i.getParameter(E.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r}function s(E){return!(E!==tn&&n.convert(E)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(E){const I=E===Po&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(E!==Cn&&n.convert(E)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE)&&E!==wn&&!I)}function c(E){if(E==="highp"){if(i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.HIGH_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";E="mediump"}return E==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let h=t.precision!==void 0?t.precision:"highp";const l=c(h);l!==h&&(console.warn("THREE.WebGLRenderer:",h,"not supported, using",l,"instead."),h=l);const f=t.logarithmicDepthBuffer===!0,v=t.reverseDepthBuffer===!0&&e.has("EXT_clip_control"),p=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),_=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),m=i.getParameter(i.MAX_TEXTURE_SIZE),d=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),u=i.getParameter(i.MAX_VERTEX_ATTRIBS),b=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),y=i.getParameter(i.MAX_VARYING_VECTORS),g=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),S=_>0,R=i.getParameter(i.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:s,textureTypeReadable:o,precision:h,logarithmicDepthBuffer:f,reverseDepthBuffer:v,maxTextures:p,maxVertexTextures:_,maxTextureSize:m,maxCubemapSize:d,maxAttributes:u,maxVertexUniforms:b,maxVaryings:y,maxFragmentUniforms:g,vertexTextures:S,maxSamples:R}}function $S(i){const e=this;let t=null,n=0,r=!1,a=!1;const s=new yr,o=new dt,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(f,v){const p=f.length!==0||v||n!==0||r;return r=v,n=f.length,p},this.beginShadows=function(){a=!0,l(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(f,v){t=l(f,v,0)},this.setState=function(f,v,p){const _=f.clippingPlanes,m=f.clipIntersection,d=f.clipShadows,u=i.get(f);if(!r||_===null||_.length===0||a&&!d)a?l(null):h();else{const b=a?0:n,y=b*4;let g=u.clippingState||null;c.value=g,g=l(_,v,y,p);for(let S=0;S!==y;++S)g[S]=t[S];u.clippingState=g,this.numIntersection=m?this.numPlanes:0,this.numPlanes+=b}};function h(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function l(f,v,p,_){const m=f!==null?f.length:0;let d=null;if(m!==0){if(d=c.value,_!==!0||d===null){const u=p+m*4,b=v.matrixWorldInverse;o.getNormalMatrix(b),(d===null||d.length<u)&&(d=new Float32Array(u));for(let y=0,g=p;y!==m;++y,g+=4)s.copy(f[y]).applyMatrix4(b,o),s.normal.toArray(d,g),d[g+3]=s.constant}c.value=d,c.needsUpdate=!0}return e.numPlanes=m,e.numIntersection=0,d}}function KS(i){let e=new WeakMap;function t(s,o){return o===mc?s.mapping=Hr:o===gc&&(s.mapping=Gr),s}function n(s){if(s&&s.isTexture){const o=s.mapping;if(o===mc||o===gc)if(e.has(s)){const c=e.get(s).texture;return t(c,s.mapping)}else{const c=s.image;if(c&&c.height>0){const h=new D0(c.height);return h.fromEquirectangularTexture(i,s),e.set(s,h),s.addEventListener("dispose",r),t(h.texture,s.mapping)}else return null}}return s}function r(s){const o=s.target;o.removeEventListener("dispose",r);const c=e.get(o);c!==void 0&&(e.delete(o),c.dispose())}function a(){e=new WeakMap}return{get:n,dispose:a}}const uo=4,Bp=[.125,.215,.35,.446,.526,.582],Tr=20,Rl=new Np,Vp=new It;let Tl=null,Al=0,Cl=0,wl=!1;const Ar=(1+Math.sqrt(5))/2,ho=1/Ar,Fp=[new we(-Ar,ho,0),new we(Ar,ho,0),new we(-ho,0,Ar),new we(ho,0,Ar),new we(0,Ar,-ho),new we(0,Ar,ho),new we(-1,1,-1),new we(1,1,-1),new we(-1,1,1),new we(1,1,1)];class Hp{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,r=100){Tl=this._renderer.getRenderTarget(),Al=this._renderer.getActiveCubeFace(),Cl=this._renderer.getActiveMipmapLevel(),wl=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const a=this._allocateTargets();return a.depthBuffer=!0,this._sceneToCubeUV(e,n,r,a),t>0&&this._blur(a,0,0,t),this._applyPMREM(a),this._cleanup(a),a}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Wp(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=zp(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(Tl,Al,Cl),this._renderer.xr.enabled=wl,e.scissorTest=!1,Xs(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===Hr||e.mapping===Gr?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Tl=this._renderer.getRenderTarget(),Al=this._renderer.getActiveCubeFace(),Cl=this._renderer.getActiveMipmapLevel(),wl=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:Ei,minFilter:Ei,generateMipmaps:!1,type:Po,format:tn,colorSpace:Xr,depthBuffer:!1},r=Gp(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Gp(e,t,n);const{_lodMax:a}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=qS(a)),this._blurMaterial=YS(a,e,t)}return r}_compileMaterial(e){const t=new gn(this._lodPlanes[0],e);this._renderer.compile(t,Rl)}_sceneToCubeUV(e,t,n,r){const o=new an(90,1,t,n),c=[1,-1,1,1,1,1],h=[1,1,1,-1,-1,-1],l=this._renderer,f=l.autoClear,v=l.toneMapping;l.getClearColor(Vp),l.toneMapping=Yn,l.autoClear=!1;const p=new Ep({name:"PMREM.Background",side:yi,depthWrite:!1,depthTest:!1}),_=new gn(new Fo,p);let m=!1;const d=e.background;d?d.isColor&&(p.color.copy(d),e.background=null,m=!0):(p.color.copy(Vp),m=!0);for(let u=0;u<6;u++){const b=u%3;b===0?(o.up.set(0,c[u],0),o.lookAt(h[u],0,0)):b===1?(o.up.set(0,0,c[u]),o.lookAt(0,h[u],0)):(o.up.set(0,c[u],0),o.lookAt(0,0,h[u]));const y=this._cubeSize;Xs(r,b*y,u>2?y:0,y,y),l.setRenderTarget(r),m&&l.render(_,o),l.render(e,o)}_.geometry.dispose(),_.material.dispose(),l.toneMapping=v,l.autoClear=f,e.background=d}_textureToCubeUV(e,t){const n=this._renderer,r=e.mapping===Hr||e.mapping===Gr;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=Wp()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=zp());const a=r?this._cubemapMaterial:this._equirectMaterial,s=new gn(this._lodPlanes[0],a),o=a.uniforms;o.envMap.value=e;const c=this._cubeSize;Xs(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(s,Rl)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const r=this._lodPlanes.length;for(let a=1;a<r;a++){const s=Math.sqrt(this._sigmas[a]*this._sigmas[a]-this._sigmas[a-1]*this._sigmas[a-1]),o=Fp[(r-a-1)%Fp.length];this._blur(e,a-1,a,s,o)}t.autoClear=n}_blur(e,t,n,r,a){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,n,r,"latitudinal",a),this._halfBlur(s,e,n,n,r,"longitudinal",a)}_halfBlur(e,t,n,r,a,s,o){const c=this._renderer,h=this._blurMaterial;s!=="latitudinal"&&s!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const l=3,f=new gn(this._lodPlanes[r],h),v=h.uniforms,p=this._sizeLods[n]-1,_=isFinite(a)?Math.PI/(2*p):2*Math.PI/(2*Tr-1),m=a/_,d=isFinite(a)?1+Math.floor(l*m):Tr;d>Tr&&console.warn(`sigmaRadians, ${a}, is too large and will clip, as it requested ${d} samples when the maximum is set to ${Tr}`);const u=[];let b=0;for(let E=0;E<Tr;++E){const I=E/m,C=Math.exp(-I*I/2);u.push(C),E===0?b+=C:E<d&&(b+=2*C)}for(let E=0;E<u.length;E++)u[E]=u[E]/b;v.envMap.value=e.texture,v.samples.value=d,v.weights.value=u,v.latitudinal.value=s==="latitudinal",o&&(v.poleAxis.value=o);const{_lodMax:y}=this;v.dTheta.value=_,v.mipInt.value=y-n;const g=this._sizeLods[r],S=3*g*(r>y-uo?r-y+uo:0),R=4*(this._cubeSize-g);Xs(t,S,R,3*g,2*g),c.setRenderTarget(t),c.render(f,Rl)}}function qS(i){const e=[],t=[],n=[];let r=i;const a=i-uo+1+Bp.length;for(let s=0;s<a;s++){const o=Math.pow(2,r);t.push(o);let c=1/o;s>i-uo?c=Bp[s-i+uo-1]:s===0&&(c=0),n.push(c);const h=1/(o-2),l=-h,f=1+h,v=[l,l,f,l,f,f,l,l,f,f,l,f],p=6,_=6,m=3,d=2,u=1,b=new Float32Array(m*_*p),y=new Float32Array(d*_*p),g=new Float32Array(u*_*p);for(let R=0;R<p;R++){const E=R%3*2/3-1,I=R>2?0:-1,C=[E,I,0,E+2/3,I,0,E+2/3,I+1,0,E,I,0,E+2/3,I+1,0,E,I+1,0];b.set(C,m*_*R),y.set(v,d*_*R);const A=[R,R,R,R,R,R];g.set(A,u*_*R)}const S=new Sr;S.setAttribute("position",new mn(b,m)),S.setAttribute("uv",new mn(y,d)),S.setAttribute("faceIndex",new mn(g,u)),e.push(S),r>uo&&r--}return{lodPlanes:e,sizeLods:t,sigmas:n}}function Gp(i,e,t){const n=new mr(i,e,t);return n.texture.mapping=gs,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Xs(i,e,t,n,r){i.viewport.set(e,t,n,r),i.scissor.set(e,t,n,r)}function YS(i,e,t){const n=new Float32Array(Tr),r=new we(0,1,0);return new kn({name:"SphericalGaussianBlur",defines:{n:Tr,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:Ml(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;
			uniform int samples;
			uniform float weights[ n ];
			uniform bool latitudinal;
			uniform float dTheta;
			uniform float mipInt;
			uniform vec3 poleAxis;

			#define ENVMAP_TYPE_CUBE_UV
			#include <cube_uv_reflection_fragment>

			vec3 getSample( float theta, vec3 axis ) {

				float cosTheta = cos( theta );
				// Rodrigues' axis-angle rotation
				vec3 sampleDirection = vOutputDirection * cosTheta
					+ cross( axis, vOutputDirection ) * sin( theta )
					+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );

				return bilinearCubeUV( envMap, sampleDirection, mipInt );

			}

			void main() {

				vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );

				if ( all( equal( axis, vec3( 0.0 ) ) ) ) {

					axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );

				}

				axis = normalize( axis );

				gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
				gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );

				for ( int i = 1; i < n; i++ ) {

					if ( i >= samples ) {

						break;

					}

					float theta = dTheta * float( i );
					gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
					gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );

				}

			}
		`,blending:qn,depthTest:!1,depthWrite:!1})}function zp(){return new kn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Ml(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;

			#include <common>

			void main() {

				vec3 outputDirection = normalize( vOutputDirection );
				vec2 uv = equirectUv( outputDirection );

				gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );

			}
		`,blending:qn,depthTest:!1,depthWrite:!1})}function Wp(){return new kn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ml(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			uniform float flipEnvMap;

			varying vec3 vOutputDirection;

			uniform samplerCube envMap;

			void main() {

				gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );

			}
		`,blending:qn,depthTest:!1,depthWrite:!1})}function Ml(){return`

		precision mediump float;
		precision mediump int;

		attribute float faceIndex;

		varying vec3 vOutputDirection;

		// RH coordinate system; PMREM face-indexing convention
		vec3 getDirection( vec2 uv, float face ) {

			uv = 2.0 * uv - 1.0;

			vec3 direction = vec3( uv, 1.0 );

			if ( face == 0.0 ) {

				direction = direction.zyx; // ( 1, v, u ) pos x

			} else if ( face == 1.0 ) {

				direction = direction.xzy;
				direction.xz *= -1.0; // ( -u, 1, -v ) pos y

			} else if ( face == 2.0 ) {

				direction.x *= -1.0; // ( -u, v, 1 ) pos z

			} else if ( face == 3.0 ) {

				direction = direction.zyx;
				direction.xz *= -1.0; // ( -1, v, -u ) neg x

			} else if ( face == 4.0 ) {

				direction = direction.xzy;
				direction.xy *= -1.0; // ( -u, -1, v ) neg y

			} else if ( face == 5.0 ) {

				direction.z *= -1.0; // ( u, v, -1 ) neg z

			}

			return direction;

		}

		void main() {

			vOutputDirection = getDirection( uv, faceIndex );
			gl_Position = vec4( position, 1.0 );

		}
	`}function JS(i){let e=new WeakMap,t=null;function n(o){if(o&&o.isTexture){const c=o.mapping,h=c===mc||c===gc,l=c===Hr||c===Gr;if(h||l){let f=e.get(o);const v=f!==void 0?f.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==v)return t===null&&(t=new Hp(i)),f=h?t.fromEquirectangular(o,f):t.fromCubemap(o,f),f.texture.pmremVersion=o.pmremVersion,e.set(o,f),f.texture;if(f!==void 0)return f.texture;{const p=o.image;return h&&p&&p.height>0||l&&p&&r(p)?(t===null&&(t=new Hp(i)),f=h?t.fromEquirectangular(o):t.fromCubemap(o),f.texture.pmremVersion=o.pmremVersion,e.set(o,f),o.addEventListener("dispose",a),f.texture):null}}}return o}function r(o){let c=0;const h=6;for(let l=0;l<h;l++)o[l]!==void 0&&c++;return c===h}function a(o){const c=o.target;c.removeEventListener("dispose",a);const h=e.get(c);h!==void 0&&(e.delete(c),h.dispose())}function s(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:n,dispose:s}}function QS(i){const e={};function t(n){if(e[n]!==void 0)return e[n];let r;switch(n){case"WEBGL_depth_texture":r=i.getExtension("WEBGL_depth_texture")||i.getExtension("MOZ_WEBGL_depth_texture")||i.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":r=i.getExtension("EXT_texture_filter_anisotropic")||i.getExtension("MOZ_EXT_texture_filter_anisotropic")||i.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":r=i.getExtension("WEBGL_compressed_texture_s3tc")||i.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||i.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":r=i.getExtension("WEBGL_compressed_texture_pvrtc")||i.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:r=i.getExtension(n)}return e[n]=r,r}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){const r=t(n);return r===null&&qr("THREE.WebGLRenderer: "+n+" extension not supported."),r}}}function ZS(i,e,t,n){const r={},a=new WeakMap;function s(f){const v=f.target;v.index!==null&&e.remove(v.index);for(const _ in v.attributes)e.remove(v.attributes[_]);v.removeEventListener("dispose",s),delete r[v.id];const p=a.get(v);p&&(e.remove(p),a.delete(v)),n.releaseStatesOfGeometry(v),v.isInstancedBufferGeometry===!0&&delete v._maxInstanceCount,t.memory.geometries--}function o(f,v){return r[v.id]===!0||(v.addEventListener("dispose",s),r[v.id]=!0,t.memory.geometries++),v}function c(f){const v=f.attributes;for(const p in v)e.update(v[p],i.ARRAY_BUFFER)}function h(f){const v=[],p=f.index,_=f.attributes.position;let m=0;if(p!==null){const b=p.array;m=p.version;for(let y=0,g=b.length;y<g;y+=3){const S=b[y+0],R=b[y+1],E=b[y+2];v.push(S,R,R,E,E,S)}}else if(_!==void 0){const b=_.array;m=_.version;for(let y=0,g=b.length/3-1;y<g;y+=3){const S=y+0,R=y+1,E=y+2;v.push(S,R,R,E,E,S)}}else return;const d=new(op(v)?Tp:Rp)(v,1);d.version=m;const u=a.get(f);u&&e.remove(u),a.set(f,d)}function l(f){const v=a.get(f);if(v){const p=f.index;p!==null&&v.version<p.version&&h(f)}else h(f);return a.get(f)}return{get:o,update:c,getWireframeAttribute:l}}function eb(i,e,t){let n;function r(v){n=v}let a,s;function o(v){a=v.type,s=v.bytesPerElement}function c(v,p){i.drawElements(n,p,a,v*s),t.update(p,n,1)}function h(v,p,_){_!==0&&(i.drawElementsInstanced(n,p,a,v*s,_),t.update(p,n,_))}function l(v,p,_){if(_===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,p,0,a,v,0,_);let d=0;for(let u=0;u<_;u++)d+=p[u];t.update(d,n,1)}function f(v,p,_,m){if(_===0)return;const d=e.get("WEBGL_multi_draw");if(d===null)for(let u=0;u<v.length;u++)h(v[u]/s,p[u],m[u]);else{d.multiDrawElementsInstancedWEBGL(n,p,0,a,v,0,m,0,_);let u=0;for(let b=0;b<_;b++)u+=p[b]*m[b];t.update(u,n,1)}}this.setMode=r,this.setIndex=o,this.render=c,this.renderInstances=h,this.renderMultiDraw=l,this.renderMultiDrawInstances=f}function tb(i){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(a,s,o){switch(t.calls++,s){case i.TRIANGLES:t.triangles+=o*(a/3);break;case i.LINES:t.lines+=o*(a/2);break;case i.LINE_STRIP:t.lines+=o*(a-1);break;case i.LINE_LOOP:t.lines+=o*a;break;case i.POINTS:t.points+=o*a;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",s);break}}function r(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:r,update:n}}function ib(i,e,t){const n=new WeakMap,r=new Ft;function a(s,o,c){const h=s.morphTargetInfluences,l=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,f=l!==void 0?l.length:0;let v=n.get(o);if(v===void 0||v.count!==f){let C=function(){E.dispose(),n.delete(o),o.removeEventListener("dispose",C)};v!==void 0&&v.texture.dispose();const p=o.morphAttributes.position!==void 0,_=o.morphAttributes.normal!==void 0,m=o.morphAttributes.color!==void 0,d=o.morphAttributes.position||[],u=o.morphAttributes.normal||[],b=o.morphAttributes.color||[];let y=0;p===!0&&(y=1),_===!0&&(y=2),m===!0&&(y=3);let g=o.attributes.position.count*y,S=1;g>e.maxTextureSize&&(S=Math.ceil(g/e.maxTextureSize),g=e.maxTextureSize);const R=new Float32Array(g*S*4*f),E=new up(R,g,S,f);E.type=wn,E.needsUpdate=!0;const I=y*4;for(let A=0;A<f;A++){const w=d[A],N=u[A],M=b[A],D=g*S*4*A;for(let L=0;L<w.count;L++){const P=L*I;p===!0&&(r.fromBufferAttribute(w,L),R[D+P+0]=r.x,R[D+P+1]=r.y,R[D+P+2]=r.z,R[D+P+3]=0),_===!0&&(r.fromBufferAttribute(N,L),R[D+P+4]=r.x,R[D+P+5]=r.y,R[D+P+6]=r.z,R[D+P+7]=0),m===!0&&(r.fromBufferAttribute(M,L),R[D+P+8]=r.x,R[D+P+9]=r.y,R[D+P+10]=r.z,R[D+P+11]=M.itemSize===4?r.w:1)}}v={count:f,texture:E,size:new xt(g,S)},n.set(o,v),o.addEventListener("dispose",C)}if(s.isInstancedMesh===!0&&s.morphTexture!==null)c.getUniforms().setValue(i,"morphTexture",s.morphTexture,t);else{let p=0;for(let m=0;m<h.length;m++)p+=h[m];const _=o.morphTargetsRelative?1:1-p;c.getUniforms().setValue(i,"morphTargetBaseInfluence",_),c.getUniforms().setValue(i,"morphTargetInfluences",h)}c.getUniforms().setValue(i,"morphTargetsTexture",v.texture,t),c.getUniforms().setValue(i,"morphTargetsTextureSize",v.size)}return{update:a}}function nb(i,e,t,n){let r=new WeakMap;function a(c){const h=n.render.frame,l=c.geometry,f=e.get(c,l);if(r.get(f)!==h&&(e.update(f),r.set(f,h)),c.isInstancedMesh&&(c.hasEventListener("dispose",o)===!1&&c.addEventListener("dispose",o),r.get(c)!==h&&(t.update(c.instanceMatrix,i.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,i.ARRAY_BUFFER),r.set(c,h))),c.isSkinnedMesh){const v=c.skeleton;r.get(v)!==h&&(v.update(),r.set(v,h))}return f}function s(){r=new WeakMap}function o(c){const h=c.target;h.removeEventListener("dispose",o),t.remove(h.instanceMatrix),h.instanceColor!==null&&t.remove(h.instanceColor)}return{update:a,dispose:s}}const jp=new ui,Xp=new Op(1,1),$p=new up,Kp=new f0,qp=new Dp,Yp=[],Jp=[],Qp=new Float32Array(16),Zp=new Float32Array(9),ef=new Float32Array(4);function po(i,e,t){const n=i[0];if(n<=0||n>0)return i;const r=e*t;let a=Yp[r];if(a===void 0&&(a=new Float32Array(r),Yp[r]=a),e!==0){n.toArray(a,0);for(let s=1,o=0;s!==e;++s)o+=t,i[s].toArray(a,o)}return a}function Jt(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function Qt(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function $s(i,e){let t=Jp[e];t===void 0&&(t=new Int32Array(e),Jp[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function rb(i,e){const t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function ob(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Jt(t,e))return;i.uniform2fv(this.addr,e),Qt(t,e)}}function sb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(Jt(t,e))return;i.uniform3fv(this.addr,e),Qt(t,e)}}function ab(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Jt(t,e))return;i.uniform4fv(this.addr,e),Qt(t,e)}}function cb(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Jt(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),Qt(t,e)}else{if(Jt(t,n))return;ef.set(n),i.uniformMatrix2fv(this.addr,!1,ef),Qt(t,n)}}function lb(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Jt(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),Qt(t,e)}else{if(Jt(t,n))return;Zp.set(n),i.uniformMatrix3fv(this.addr,!1,Zp),Qt(t,n)}}function ub(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Jt(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),Qt(t,e)}else{if(Jt(t,n))return;Qp.set(n),i.uniformMatrix4fv(this.addr,!1,Qp),Qt(t,n)}}function db(i,e){const t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function hb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Jt(t,e))return;i.uniform2iv(this.addr,e),Qt(t,e)}}function pb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Jt(t,e))return;i.uniform3iv(this.addr,e),Qt(t,e)}}function fb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Jt(t,e))return;i.uniform4iv(this.addr,e),Qt(t,e)}}function mb(i,e){const t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function gb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Jt(t,e))return;i.uniform2uiv(this.addr,e),Qt(t,e)}}function vb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Jt(t,e))return;i.uniform3uiv(this.addr,e),Qt(t,e)}}function _b(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Jt(t,e))return;i.uniform4uiv(this.addr,e),Qt(t,e)}}function Sb(i,e,t){const n=this.cache,r=t.allocateTextureUnit();n[0]!==r&&(i.uniform1i(this.addr,r),n[0]=r);let a;this.type===i.SAMPLER_2D_SHADOW?(Xp.compareFunction=ip,a=Xp):a=jp,t.setTexture2D(e||a,r)}function bb(i,e,t){const n=this.cache,r=t.allocateTextureUnit();n[0]!==r&&(i.uniform1i(this.addr,r),n[0]=r),t.setTexture3D(e||Kp,r)}function yb(i,e,t){const n=this.cache,r=t.allocateTextureUnit();n[0]!==r&&(i.uniform1i(this.addr,r),n[0]=r),t.setTextureCube(e||qp,r)}function Eb(i,e,t){const n=this.cache,r=t.allocateTextureUnit();n[0]!==r&&(i.uniform1i(this.addr,r),n[0]=r),t.setTexture2DArray(e||$p,r)}function Rb(i){switch(i){case 5126:return rb;case 35664:return ob;case 35665:return sb;case 35666:return ab;case 35674:return cb;case 35675:return lb;case 35676:return ub;case 5124:case 35670:return db;case 35667:case 35671:return hb;case 35668:case 35672:return pb;case 35669:case 35673:return fb;case 5125:return mb;case 36294:return gb;case 36295:return vb;case 36296:return _b;case 35678:case 36198:case 36298:case 36306:case 35682:return Sb;case 35679:case 36299:case 36307:return bb;case 35680:case 36300:case 36308:case 36293:return yb;case 36289:case 36303:case 36311:case 36292:return Eb}}function Tb(i,e){i.uniform1fv(this.addr,e)}function Ab(i,e){const t=po(e,this.size,2);i.uniform2fv(this.addr,t)}function Cb(i,e){const t=po(e,this.size,3);i.uniform3fv(this.addr,t)}function wb(i,e){const t=po(e,this.size,4);i.uniform4fv(this.addr,t)}function Mb(i,e){const t=po(e,this.size,4);i.uniformMatrix2fv(this.addr,!1,t)}function xb(i,e){const t=po(e,this.size,9);i.uniformMatrix3fv(this.addr,!1,t)}function Ib(i,e){const t=po(e,this.size,16);i.uniformMatrix4fv(this.addr,!1,t)}function Pb(i,e){i.uniform1iv(this.addr,e)}function Db(i,e){i.uniform2iv(this.addr,e)}function Lb(i,e){i.uniform3iv(this.addr,e)}function Ob(i,e){i.uniform4iv(this.addr,e)}function Nb(i,e){i.uniform1uiv(this.addr,e)}function kb(i,e){i.uniform2uiv(this.addr,e)}function Ub(i,e){i.uniform3uiv(this.addr,e)}function Bb(i,e){i.uniform4uiv(this.addr,e)}function Vb(i,e,t){const n=this.cache,r=e.length,a=$s(t,r);Jt(n,a)||(i.uniform1iv(this.addr,a),Qt(n,a));for(let s=0;s!==r;++s)t.setTexture2D(e[s]||jp,a[s])}function Fb(i,e,t){const n=this.cache,r=e.length,a=$s(t,r);Jt(n,a)||(i.uniform1iv(this.addr,a),Qt(n,a));for(let s=0;s!==r;++s)t.setTexture3D(e[s]||Kp,a[s])}function Hb(i,e,t){const n=this.cache,r=e.length,a=$s(t,r);Jt(n,a)||(i.uniform1iv(this.addr,a),Qt(n,a));for(let s=0;s!==r;++s)t.setTextureCube(e[s]||qp,a[s])}function Gb(i,e,t){const n=this.cache,r=e.length,a=$s(t,r);Jt(n,a)||(i.uniform1iv(this.addr,a),Qt(n,a));for(let s=0;s!==r;++s)t.setTexture2DArray(e[s]||$p,a[s])}function zb(i){switch(i){case 5126:return Tb;case 35664:return Ab;case 35665:return Cb;case 35666:return wb;case 35674:return Mb;case 35675:return xb;case 35676:return Ib;case 5124:case 35670:return Pb;case 35667:case 35671:return Db;case 35668:case 35672:return Lb;case 35669:case 35673:return Ob;case 5125:return Nb;case 36294:return kb;case 36295:return Ub;case 36296:return Bb;case 35678:case 36198:case 36298:case 36306:case 35682:return Vb;case 35679:case 36299:case 36307:return Fb;case 35680:case 36300:case 36308:case 36293:return Hb;case 36289:case 36303:case 36311:case 36292:return Gb}}class Wb{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=Rb(t.type)}}class jb{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=zb(t.type)}}class Xb{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const r=this.seq;for(let a=0,s=r.length;a!==s;++a){const o=r[a];o.setValue(e,t[o.id],n)}}}const xl=/(\w+)(\])?(\[|\.)?/g;function tf(i,e){i.seq.push(e),i.map[e.id]=e}function $b(i,e,t){const n=i.name,r=n.length;for(xl.lastIndex=0;;){const a=xl.exec(n),s=xl.lastIndex;let o=a[1];const c=a[2]==="]",h=a[3];if(c&&(o=o|0),h===void 0||h==="["&&s+2===r){tf(t,h===void 0?new Wb(o,i,e):new jb(o,i,e));break}else{let f=t.map[o];f===void 0&&(f=new Xb(o),tf(t,f)),t=f}}}class Ks{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<n;++r){const a=e.getActiveUniform(t,r),s=e.getUniformLocation(t,a.name);$b(a,s,this)}}setValue(e,t,n,r){const a=this.map[t];a!==void 0&&a.setValue(e,n,r)}setOptional(e,t,n){const r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let a=0,s=t.length;a!==s;++a){const o=t[a],c=n[o.id];c.needsUpdate!==!1&&o.setValue(e,c.value,r)}}static seqWithValue(e,t){const n=[];for(let r=0,a=e.length;r!==a;++r){const s=e[r];s.id in t&&n.push(s)}return n}}function nf(i,e,t){const n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}const Kb=37297;let qb=0;function Yb(i,e){const t=i.split(`
`),n=[],r=Math.max(e-6,0),a=Math.min(e+6,t.length);for(let s=r;s<a;s++){const o=s+1;n.push(`${o===e?">":" "} ${o}: ${t[s]}`)}return n.join(`
`)}const rf=new dt;function Jb(i){Et._getMatrix(rf,Et.workingColorSpace,i);const e=`mat3( ${rf.elements.map(t=>t.toFixed(4))} )`;switch(Et.getTransfer(i)){case Rs:return[e,"LinearTransferOETF"];case Mt:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function of(i,e,t){const n=i.getShaderParameter(e,i.COMPILE_STATUS),r=i.getShaderInfoLog(e).trim();if(n&&r==="")return"";const a=/ERROR: 0:(\d+)/.exec(r);if(a){const s=parseInt(a[1]);return t.toUpperCase()+`

`+r+`

`+Yb(i.getShaderSource(e),s)}else return r}function Qb(i,e){const t=Jb(e);return[`vec4 ${i}( vec4 value ) {`,`	return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(`
`)}function Zb(i,e){let t;switch(e){case Vv:t="Linear";break;case Fv:t="Reinhard";break;case Hv:t="Cineon";break;case Gv:t="ACESFilmic";break;case Wv:t="AgX";break;case jv:t="Neutral";break;case zv:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+i+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const qs=new we;function ey(){Et.getLuminanceCoefficients(qs);const i=qs.x.toFixed(4),e=qs.y.toFixed(4),t=qs.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",`	const vec3 weights = vec3( ${i}, ${e}, ${t} );`,"	return dot( weights, rgb );","}"].join(`
`)}function ty(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Go).join(`
`)}function iy(i){const e=[];for(const t in i){const n=i[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(`
`)}function ny(i,e){const t={},n=i.getProgramParameter(e,i.ACTIVE_ATTRIBUTES);for(let r=0;r<n;r++){const a=i.getActiveAttrib(e,r),s=a.name;let o=1;a.type===i.FLOAT_MAT2&&(o=2),a.type===i.FLOAT_MAT3&&(o=3),a.type===i.FLOAT_MAT4&&(o=4),t[s]={type:a.type,location:i.getAttribLocation(e,s),locationSize:o}}return t}function Go(i){return i!==""}function sf(i,e){const t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return i.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function af(i,e){return i.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const ry=/^[ \t]*#include +<([\w\d./]+)>/gm;function Il(i){return i.replace(ry,sy)}const oy=new Map;function sy(i,e){let t=ht[e];if(t===void 0){const n=oy.get(e);if(n!==void 0)t=ht[n],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n);else throw new Error("Can not resolve #include <"+e+">")}return Il(t)}const ay=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function cf(i){return i.replace(ay,cy)}function cy(i,e,t,n){let r="";for(let a=parseInt(e);a<parseInt(t);a++)r+=n.replace(/\[\s*i\s*\]/g,"[ "+a+" ]").replace(/UNROLLED_LOOP_INDEX/g,a);return r}function lf(i){let e=`precision ${i.precision} float;
	precision ${i.precision} int;
	precision ${i.precision} sampler2D;
	precision ${i.precision} samplerCube;
	precision ${i.precision} sampler3D;
	precision ${i.precision} sampler2DArray;
	precision ${i.precision} sampler2DShadow;
	precision ${i.precision} samplerCubeShadow;
	precision ${i.precision} sampler2DArrayShadow;
	precision ${i.precision} isampler2D;
	precision ${i.precision} isampler3D;
	precision ${i.precision} isamplerCube;
	precision ${i.precision} isampler2DArray;
	precision ${i.precision} usampler2D;
	precision ${i.precision} usampler3D;
	precision ${i.precision} usamplerCube;
	precision ${i.precision} usampler2DArray;
	`;return i.precision==="highp"?e+=`
#define HIGH_PRECISION`:i.precision==="mediump"?e+=`
#define MEDIUM_PRECISION`:i.precision==="lowp"&&(e+=`
#define LOW_PRECISION`),e}function ly(i){let e="SHADOWMAP_TYPE_BASIC";return i.shadowMapType===Vh?e="SHADOWMAP_TYPE_PCF":i.shadowMapType===_v?e="SHADOWMAP_TYPE_PCF_SOFT":i.shadowMapType===Rn&&(e="SHADOWMAP_TYPE_VSM"),e}function uy(i){let e="ENVMAP_TYPE_CUBE";if(i.envMap)switch(i.envMapMode){case Hr:case Gr:e="ENVMAP_TYPE_CUBE";break;case gs:e="ENVMAP_TYPE_CUBE_UV";break}return e}function dy(i){let e="ENVMAP_MODE_REFLECTION";if(i.envMap)switch(i.envMapMode){case Gr:e="ENVMAP_MODE_REFRACTION";break}return e}function hy(i){let e="ENVMAP_BLENDING_NONE";if(i.envMap)switch(i.combine){case zh:e="ENVMAP_BLENDING_MULTIPLY";break;case Uv:e="ENVMAP_BLENDING_MIX";break;case Bv:e="ENVMAP_BLENDING_ADD";break}return e}function py(i){const e=i.envMapCubeUVHeight;if(e===null)return null;const t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),7*16)),texelHeight:n,maxMip:t}}function fy(i,e,t,n){const r=i.getContext(),a=t.defines;let s=t.vertexShader,o=t.fragmentShader;const c=ly(t),h=uy(t),l=dy(t),f=hy(t),v=py(t),p=ty(t),_=iy(a),m=r.createProgram();let d,u,b=t.glslVersion?"#version "+t.glslVersion+`
`:"";t.isRawShaderMaterial?(d=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,_].filter(Go).join(`
`),d.length>0&&(d+=`
`),u=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,_].filter(Go).join(`
`),u.length>0&&(u+=`
`)):(d=[lf(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,_,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","	attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","	attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","	uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","	attribute vec2 uv1;","#endif","#ifdef USE_UV2","	attribute vec2 uv2;","#endif","#ifdef USE_UV3","	attribute vec2 uv3;","#endif","#ifdef USE_TANGENT","	attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","	attribute vec4 color;","#elif defined( USE_COLOR )","	attribute vec3 color;","#endif","#ifdef USE_SKINNING","	attribute vec4 skinIndex;","	attribute vec4 skinWeight;","#endif",`
`].filter(Go).join(`
`),u=[lf(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,_,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.envMap?"#define "+l:"",t.envMap?"#define "+f:"",v?"#define CUBEUV_TEXEL_WIDTH "+v.texelWidth:"",v?"#define CUBEUV_TEXEL_HEIGHT "+v.texelHeight:"",v?"#define CUBEUV_MAX_MIP "+v.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Yn?"#define TONE_MAPPING":"",t.toneMapping!==Yn?ht.tonemapping_pars_fragment:"",t.toneMapping!==Yn?Zb("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",ht.colorspace_pars_fragment,Qb("linearToOutputTexel",t.outputColorSpace),ey(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
`].filter(Go).join(`
`)),s=Il(s),s=sf(s,t),s=af(s,t),o=Il(o),o=sf(o,t),o=af(o,t),s=cf(s),o=cf(o),t.isRawShaderMaterial!==!0&&(b=`#version 300 es
`,d=[p,"#define attribute in","#define varying out","#define texture2D texture"].join(`
`)+`
`+d,u=["#define varying in",t.glslVersion===rp?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===rp?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`
`)+`
`+u);const y=b+d+s,g=b+u+o,S=nf(r,r.VERTEX_SHADER,y),R=nf(r,r.FRAGMENT_SHADER,g);r.attachShader(m,S),r.attachShader(m,R),t.index0AttributeName!==void 0?r.bindAttribLocation(m,0,t.index0AttributeName):t.morphTargets===!0&&r.bindAttribLocation(m,0,"position"),r.linkProgram(m);function E(w){if(i.debug.checkShaderErrors){const N=r.getProgramInfoLog(m).trim(),M=r.getShaderInfoLog(S).trim(),D=r.getShaderInfoLog(R).trim();let L=!0,P=!0;if(r.getProgramParameter(m,r.LINK_STATUS)===!1)if(L=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(r,m,S,R);else{const x=of(r,S,"vertex"),T=of(r,R,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(m,r.VALIDATE_STATUS)+`

Material Name: `+w.name+`
Material Type: `+w.type+`

Program Info Log: `+N+`
`+x+`
`+T)}else N!==""?console.warn("THREE.WebGLProgram: Program Info Log:",N):(M===""||D==="")&&(P=!1);P&&(w.diagnostics={runnable:L,programLog:N,vertexShader:{log:M,prefix:d},fragmentShader:{log:D,prefix:u}})}r.deleteShader(S),r.deleteShader(R),I=new Ks(r,m),C=ny(r,m)}let I;this.getUniforms=function(){return I===void 0&&E(this),I};let C;this.getAttributes=function(){return C===void 0&&E(this),C};let A=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return A===!1&&(A=r.getProgramParameter(m,Kb)),A},this.destroy=function(){n.releaseStatesOfProgram(this),r.deleteProgram(m),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=qb++,this.cacheKey=e,this.usedTimes=1,this.program=m,this.vertexShader=S,this.fragmentShader=R,this}let my=0;class gy{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),a=this._getShaderStage(n),s=this._getShaderCacheForMaterial(e);return s.has(r)===!1&&(s.add(r),r.usedTimes++),s.has(a)===!1&&(s.add(a),a.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new vy(e),t.set(e,n)),n}}class vy{constructor(e){this.id=my++,this.code=e,this.usedTimes=0}}function _y(i,e,t,n,r,a,s){const o=new fp,c=new gy,h=new Set,l=[],f=r.logarithmicDepthBuffer,v=r.vertexTextures;let p=r.precision;const _={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function m(C){return h.add(C),C===0?"uv":`uv${C}`}function d(C,A,w,N,M){const D=N.fog,L=M.geometry,P=C.isMeshStandardMaterial?N.environment:null,x=(C.isMeshStandardMaterial?t:e).get(C.envMap||P),T=x&&x.mapping===gs?x.image.height:null,O=_[C.type];C.precision!==null&&(p=r.getMaxPrecision(C.precision),p!==C.precision&&console.warn("THREE.WebGLProgram.getParameters:",C.precision,"not supported, using",p,"instead."));const k=L.morphAttributes.position||L.morphAttributes.normal||L.morphAttributes.color,H=k!==void 0?k.length:0;let U=0;L.morphAttributes.position!==void 0&&(U=1),L.morphAttributes.normal!==void 0&&(U=2),L.morphAttributes.color!==void 0&&(U=3);let ee,W,$,B;if(O){const Pe=vn[O];ee=Pe.vertexShader,W=Pe.fragmentShader}else ee=C.vertexShader,W=C.fragmentShader,c.update(C),$=c.getVertexShaderID(C),B=c.getFragmentShaderID(C);const F=i.getRenderTarget(),G=i.state.buffers.depth.getReversed(),q=M.isInstancedMesh===!0,X=M.isBatchedMesh===!0,J=!!C.map,se=!!C.matcap,ce=!!x,Y=!!C.aoMap,fe=!!C.lightMap,he=!!C.bumpMap,pe=!!C.normalMap,ue=!!C.displacementMap,Te=!!C.emissiveMap,be=!!C.metalnessMap,Z=!!C.roughnessMap,K=C.anisotropy>0,re=C.clearcoat>0,de=C.dispersion>0,ye=C.iridescence>0,Ee=C.sheen>0,Ve=C.transmission>0,De=K&&!!C.anisotropyMap,Ue=re&&!!C.clearcoatMap,Ye=re&&!!C.clearcoatNormalMap,Ie=re&&!!C.clearcoatRoughnessMap,Oe=ye&&!!C.iridescenceMap,$e=ye&&!!C.iridescenceThicknessMap,Ke=Ee&&!!C.sheenColorMap,Fe=Ee&&!!C.sheenRoughnessMap,st=!!C.specularMap,tt=!!C.specularColorMap,z=!!C.specularIntensityMap,j=Ve&&!!C.transmissionMap,te=Ve&&!!C.thicknessMap,Q=!!C.gradientMap,ne=!!C.alphaMap,ae=C.alphaTest>0,oe=!!C.alphaHash,Se=!!C.extensions;let _e=Yn;C.toneMapped&&(F===null||F.isXRRenderTarget===!0)&&(_e=i.toneMapping);const xe={shaderID:O,shaderType:C.type,shaderName:C.name,vertexShader:ee,fragmentShader:W,defines:C.defines,customVertexShaderID:$,customFragmentShaderID:B,isRawShaderMaterial:C.isRawShaderMaterial===!0,glslVersion:C.glslVersion,precision:p,batching:X,batchingColor:X&&M._colorsTexture!==null,instancing:q,instancingColor:q&&M.instanceColor!==null,instancingMorph:q&&M.morphTexture!==null,supportsVertexTextures:v,outputColorSpace:F===null?i.outputColorSpace:F.isXRRenderTarget===!0?F.texture.colorSpace:Xr,alphaToCoverage:!!C.alphaToCoverage,map:J,matcap:se,envMap:ce,envMapMode:ce&&x.mapping,envMapCubeUVHeight:T,aoMap:Y,lightMap:fe,bumpMap:he,normalMap:pe,displacementMap:v&&ue,emissiveMap:Te,normalMapObjectSpace:pe&&C.normalMapType===Yv,normalMapTangentSpace:pe&&C.normalMapType===qv,metalnessMap:be,roughnessMap:Z,anisotropy:K,anisotropyMap:De,clearcoat:re,clearcoatMap:Ue,clearcoatNormalMap:Ye,clearcoatRoughnessMap:Ie,dispersion:de,iridescence:ye,iridescenceMap:Oe,iridescenceThicknessMap:$e,sheen:Ee,sheenColorMap:Ke,sheenRoughnessMap:Fe,specularMap:st,specularColorMap:tt,specularIntensityMap:z,transmission:Ve,transmissionMap:j,thicknessMap:te,gradientMap:Q,opaque:C.transparent===!1&&C.blending===Vr&&C.alphaToCoverage===!1,alphaMap:ne,alphaTest:ae,alphaHash:oe,combine:C.combine,mapUv:J&&m(C.map.channel),aoMapUv:Y&&m(C.aoMap.channel),lightMapUv:fe&&m(C.lightMap.channel),bumpMapUv:he&&m(C.bumpMap.channel),normalMapUv:pe&&m(C.normalMap.channel),displacementMapUv:ue&&m(C.displacementMap.channel),emissiveMapUv:Te&&m(C.emissiveMap.channel),metalnessMapUv:be&&m(C.metalnessMap.channel),roughnessMapUv:Z&&m(C.roughnessMap.channel),anisotropyMapUv:De&&m(C.anisotropyMap.channel),clearcoatMapUv:Ue&&m(C.clearcoatMap.channel),clearcoatNormalMapUv:Ye&&m(C.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ie&&m(C.clearcoatRoughnessMap.channel),iridescenceMapUv:Oe&&m(C.iridescenceMap.channel),iridescenceThicknessMapUv:$e&&m(C.iridescenceThicknessMap.channel),sheenColorMapUv:Ke&&m(C.sheenColorMap.channel),sheenRoughnessMapUv:Fe&&m(C.sheenRoughnessMap.channel),specularMapUv:st&&m(C.specularMap.channel),specularColorMapUv:tt&&m(C.specularColorMap.channel),specularIntensityMapUv:z&&m(C.specularIntensityMap.channel),transmissionMapUv:j&&m(C.transmissionMap.channel),thicknessMapUv:te&&m(C.thicknessMap.channel),alphaMapUv:ne&&m(C.alphaMap.channel),vertexTangents:!!L.attributes.tangent&&(pe||K),vertexColors:C.vertexColors,vertexAlphas:C.vertexColors===!0&&!!L.attributes.color&&L.attributes.color.itemSize===4,pointsUvs:M.isPoints===!0&&!!L.attributes.uv&&(J||ne),fog:!!D,useFog:C.fog===!0,fogExp2:!!D&&D.isFogExp2,flatShading:C.flatShading===!0,sizeAttenuation:C.sizeAttenuation===!0,logarithmicDepthBuffer:f,reverseDepthBuffer:G,skinning:M.isSkinnedMesh===!0,morphTargets:L.morphAttributes.position!==void 0,morphNormals:L.morphAttributes.normal!==void 0,morphColors:L.morphAttributes.color!==void 0,morphTargetsCount:H,morphTextureStride:U,numDirLights:A.directional.length,numPointLights:A.point.length,numSpotLights:A.spot.length,numSpotLightMaps:A.spotLightMap.length,numRectAreaLights:A.rectArea.length,numHemiLights:A.hemi.length,numDirLightShadows:A.directionalShadowMap.length,numPointLightShadows:A.pointShadowMap.length,numSpotLightShadows:A.spotShadowMap.length,numSpotLightShadowsWithMaps:A.numSpotLightShadowsWithMaps,numLightProbes:A.numLightProbes,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:C.dithering,shadowMapEnabled:i.shadowMap.enabled&&w.length>0,shadowMapType:i.shadowMap.type,toneMapping:_e,decodeVideoTexture:J&&C.map.isVideoTexture===!0&&Et.getTransfer(C.map.colorSpace)===Mt,decodeVideoTextureEmissive:Te&&C.emissiveMap.isVideoTexture===!0&&Et.getTransfer(C.emissiveMap.colorSpace)===Mt,premultipliedAlpha:C.premultipliedAlpha,doubleSided:C.side===Tn,flipSided:C.side===yi,useDepthPacking:C.depthPacking>=0,depthPacking:C.depthPacking||0,index0AttributeName:C.index0AttributeName,extensionClipCullDistance:Se&&C.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Se&&C.extensions.multiDraw===!0||X)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:C.customProgramCacheKey()};return xe.vertexUv1s=h.has(1),xe.vertexUv2s=h.has(2),xe.vertexUv3s=h.has(3),h.clear(),xe}function u(C){const A=[];if(C.shaderID?A.push(C.shaderID):(A.push(C.customVertexShaderID),A.push(C.customFragmentShaderID)),C.defines!==void 0)for(const w in C.defines)A.push(w),A.push(C.defines[w]);return C.isRawShaderMaterial===!1&&(b(A,C),y(A,C),A.push(i.outputColorSpace)),A.push(C.customProgramCacheKey),A.join()}function b(C,A){C.push(A.precision),C.push(A.outputColorSpace),C.push(A.envMapMode),C.push(A.envMapCubeUVHeight),C.push(A.mapUv),C.push(A.alphaMapUv),C.push(A.lightMapUv),C.push(A.aoMapUv),C.push(A.bumpMapUv),C.push(A.normalMapUv),C.push(A.displacementMapUv),C.push(A.emissiveMapUv),C.push(A.metalnessMapUv),C.push(A.roughnessMapUv),C.push(A.anisotropyMapUv),C.push(A.clearcoatMapUv),C.push(A.clearcoatNormalMapUv),C.push(A.clearcoatRoughnessMapUv),C.push(A.iridescenceMapUv),C.push(A.iridescenceThicknessMapUv),C.push(A.sheenColorMapUv),C.push(A.sheenRoughnessMapUv),C.push(A.specularMapUv),C.push(A.specularColorMapUv),C.push(A.specularIntensityMapUv),C.push(A.transmissionMapUv),C.push(A.thicknessMapUv),C.push(A.combine),C.push(A.fogExp2),C.push(A.sizeAttenuation),C.push(A.morphTargetsCount),C.push(A.morphAttributeCount),C.push(A.numDirLights),C.push(A.numPointLights),C.push(A.numSpotLights),C.push(A.numSpotLightMaps),C.push(A.numHemiLights),C.push(A.numRectAreaLights),C.push(A.numDirLightShadows),C.push(A.numPointLightShadows),C.push(A.numSpotLightShadows),C.push(A.numSpotLightShadowsWithMaps),C.push(A.numLightProbes),C.push(A.shadowMapType),C.push(A.toneMapping),C.push(A.numClippingPlanes),C.push(A.numClipIntersection),C.push(A.depthPacking)}function y(C,A){o.disableAll(),A.supportsVertexTextures&&o.enable(0),A.instancing&&o.enable(1),A.instancingColor&&o.enable(2),A.instancingMorph&&o.enable(3),A.matcap&&o.enable(4),A.envMap&&o.enable(5),A.normalMapObjectSpace&&o.enable(6),A.normalMapTangentSpace&&o.enable(7),A.clearcoat&&o.enable(8),A.iridescence&&o.enable(9),A.alphaTest&&o.enable(10),A.vertexColors&&o.enable(11),A.vertexAlphas&&o.enable(12),A.vertexUv1s&&o.enable(13),A.vertexUv2s&&o.enable(14),A.vertexUv3s&&o.enable(15),A.vertexTangents&&o.enable(16),A.anisotropy&&o.enable(17),A.alphaHash&&o.enable(18),A.batching&&o.enable(19),A.dispersion&&o.enable(20),A.batchingColor&&o.enable(21),C.push(o.mask),o.disableAll(),A.fog&&o.enable(0),A.useFog&&o.enable(1),A.flatShading&&o.enable(2),A.logarithmicDepthBuffer&&o.enable(3),A.reverseDepthBuffer&&o.enable(4),A.skinning&&o.enable(5),A.morphTargets&&o.enable(6),A.morphNormals&&o.enable(7),A.morphColors&&o.enable(8),A.premultipliedAlpha&&o.enable(9),A.shadowMapEnabled&&o.enable(10),A.doubleSided&&o.enable(11),A.flipSided&&o.enable(12),A.useDepthPacking&&o.enable(13),A.dithering&&o.enable(14),A.transmission&&o.enable(15),A.sheen&&o.enable(16),A.opaque&&o.enable(17),A.pointsUvs&&o.enable(18),A.decodeVideoTexture&&o.enable(19),A.decodeVideoTextureEmissive&&o.enable(20),A.alphaToCoverage&&o.enable(21),C.push(o.mask)}function g(C){const A=_[C.type];let w;if(A){const N=vn[A];w=M0.clone(N.uniforms)}else w=C.uniforms;return w}function S(C,A){let w;for(let N=0,M=l.length;N<M;N++){const D=l[N];if(D.cacheKey===A){w=D,++w.usedTimes;break}}return w===void 0&&(w=new fy(i,A,C,a),l.push(w)),w}function R(C){if(--C.usedTimes===0){const A=l.indexOf(C);l[A]=l[l.length-1],l.pop(),C.destroy()}}function E(C){c.remove(C)}function I(){c.dispose()}return{getParameters:d,getProgramCacheKey:u,getUniforms:g,acquireProgram:S,releaseProgram:R,releaseShaderCache:E,programs:l,dispose:I}}function Sy(){let i=new WeakMap;function e(s){return i.has(s)}function t(s){let o=i.get(s);return o===void 0&&(o={},i.set(s,o)),o}function n(s){i.delete(s)}function r(s,o,c){i.get(s)[o]=c}function a(){i=new WeakMap}return{has:e,get:t,remove:n,update:r,dispose:a}}function by(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.z!==e.z?i.z-e.z:i.id-e.id}function uf(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function df(){const i=[];let e=0;const t=[],n=[],r=[];function a(){e=0,t.length=0,n.length=0,r.length=0}function s(f,v,p,_,m,d){let u=i[e];return u===void 0?(u={id:f.id,object:f,geometry:v,material:p,groupOrder:_,renderOrder:f.renderOrder,z:m,group:d},i[e]=u):(u.id=f.id,u.object=f,u.geometry=v,u.material=p,u.groupOrder=_,u.renderOrder=f.renderOrder,u.z=m,u.group=d),e++,u}function o(f,v,p,_,m,d){const u=s(f,v,p,_,m,d);p.transmission>0?n.push(u):p.transparent===!0?r.push(u):t.push(u)}function c(f,v,p,_,m,d){const u=s(f,v,p,_,m,d);p.transmission>0?n.unshift(u):p.transparent===!0?r.unshift(u):t.unshift(u)}function h(f,v){t.length>1&&t.sort(f||by),n.length>1&&n.sort(v||uf),r.length>1&&r.sort(v||uf)}function l(){for(let f=e,v=i.length;f<v;f++){const p=i[f];if(p.id===null)break;p.id=null,p.object=null,p.geometry=null,p.material=null,p.group=null}}return{opaque:t,transmissive:n,transparent:r,init:a,push:o,unshift:c,finish:l,sort:h}}function yy(){let i=new WeakMap;function e(n,r){const a=i.get(n);let s;return a===void 0?(s=new df,i.set(n,[s])):r>=a.length?(s=new df,a.push(s)):s=a[r],s}function t(){i=new WeakMap}return{get:e,dispose:t}}function Ey(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new we,color:new It};break;case"SpotLight":t={position:new we,direction:new we,color:new It,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new we,color:new It,distance:0,decay:0};break;case"HemisphereLight":t={direction:new we,skyColor:new It,groundColor:new It};break;case"RectAreaLight":t={color:new It,position:new we,halfWidth:new we,halfHeight:new we};break}return i[e.id]=t,t}}}function Ry(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new xt};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new xt};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new xt,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}let Ty=0;function Ay(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function Cy(i){const e=new Ey,t=Ry(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let h=0;h<9;h++)n.probe.push(new we);const r=new we,a=new jt,s=new jt;function o(h){let l=0,f=0,v=0;for(let C=0;C<9;C++)n.probe[C].set(0,0,0);let p=0,_=0,m=0,d=0,u=0,b=0,y=0,g=0,S=0,R=0,E=0;h.sort(Ay);for(let C=0,A=h.length;C<A;C++){const w=h[C],N=w.color,M=w.intensity,D=w.distance,L=w.shadow&&w.shadow.map?w.shadow.map.texture:null;if(w.isAmbientLight)l+=N.r*M,f+=N.g*M,v+=N.b*M;else if(w.isLightProbe){for(let P=0;P<9;P++)n.probe[P].addScaledVector(w.sh.coefficients[P],M);E++}else if(w.isDirectionalLight){const P=e.get(w);if(P.color.copy(w.color).multiplyScalar(w.intensity),w.castShadow){const x=w.shadow,T=t.get(w);T.shadowIntensity=x.intensity,T.shadowBias=x.bias,T.shadowNormalBias=x.normalBias,T.shadowRadius=x.radius,T.shadowMapSize=x.mapSize,n.directionalShadow[p]=T,n.directionalShadowMap[p]=L,n.directionalShadowMatrix[p]=w.shadow.matrix,b++}n.directional[p]=P,p++}else if(w.isSpotLight){const P=e.get(w);P.position.setFromMatrixPosition(w.matrixWorld),P.color.copy(N).multiplyScalar(M),P.distance=D,P.coneCos=Math.cos(w.angle),P.penumbraCos=Math.cos(w.angle*(1-w.penumbra)),P.decay=w.decay,n.spot[m]=P;const x=w.shadow;if(w.map&&(n.spotLightMap[S]=w.map,S++,x.updateMatrices(w),w.castShadow&&R++),n.spotLightMatrix[m]=x.matrix,w.castShadow){const T=t.get(w);T.shadowIntensity=x.intensity,T.shadowBias=x.bias,T.shadowNormalBias=x.normalBias,T.shadowRadius=x.radius,T.shadowMapSize=x.mapSize,n.spotShadow[m]=T,n.spotShadowMap[m]=L,g++}m++}else if(w.isRectAreaLight){const P=e.get(w);P.color.copy(N).multiplyScalar(M),P.halfWidth.set(w.width*.5,0,0),P.halfHeight.set(0,w.height*.5,0),n.rectArea[d]=P,d++}else if(w.isPointLight){const P=e.get(w);if(P.color.copy(w.color).multiplyScalar(w.intensity),P.distance=w.distance,P.decay=w.decay,w.castShadow){const x=w.shadow,T=t.get(w);T.shadowIntensity=x.intensity,T.shadowBias=x.bias,T.shadowNormalBias=x.normalBias,T.shadowRadius=x.radius,T.shadowMapSize=x.mapSize,T.shadowCameraNear=x.camera.near,T.shadowCameraFar=x.camera.far,n.pointShadow[_]=T,n.pointShadowMap[_]=L,n.pointShadowMatrix[_]=w.shadow.matrix,y++}n.point[_]=P,_++}else if(w.isHemisphereLight){const P=e.get(w);P.skyColor.copy(w.color).multiplyScalar(M),P.groundColor.copy(w.groundColor).multiplyScalar(M),n.hemi[u]=P,u++}}d>0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=je.LTC_FLOAT_1,n.rectAreaLTC2=je.LTC_FLOAT_2):(n.rectAreaLTC1=je.LTC_HALF_1,n.rectAreaLTC2=je.LTC_HALF_2)),n.ambient[0]=l,n.ambient[1]=f,n.ambient[2]=v;const I=n.hash;(I.directionalLength!==p||I.pointLength!==_||I.spotLength!==m||I.rectAreaLength!==d||I.hemiLength!==u||I.numDirectionalShadows!==b||I.numPointShadows!==y||I.numSpotShadows!==g||I.numSpotMaps!==S||I.numLightProbes!==E)&&(n.directional.length=p,n.spot.length=m,n.rectArea.length=d,n.point.length=_,n.hemi.length=u,n.directionalShadow.length=b,n.directionalShadowMap.length=b,n.pointShadow.length=y,n.pointShadowMap.length=y,n.spotShadow.length=g,n.spotShadowMap.length=g,n.directionalShadowMatrix.length=b,n.pointShadowMatrix.length=y,n.spotLightMatrix.length=g+S-R,n.spotLightMap.length=S,n.numSpotLightShadowsWithMaps=R,n.numLightProbes=E,I.directionalLength=p,I.pointLength=_,I.spotLength=m,I.rectAreaLength=d,I.hemiLength=u,I.numDirectionalShadows=b,I.numPointShadows=y,I.numSpotShadows=g,I.numSpotMaps=S,I.numLightProbes=E,n.version=Ty++)}function c(h,l){let f=0,v=0,p=0,_=0,m=0;const d=l.matrixWorldInverse;for(let u=0,b=h.length;u<b;u++){const y=h[u];if(y.isDirectionalLight){const g=n.directional[f];g.direction.setFromMatrixPosition(y.matrixWorld),r.setFromMatrixPosition(y.target.matrixWorld),g.direction.sub(r),g.direction.transformDirection(d),f++}else if(y.isSpotLight){const g=n.spot[p];g.position.setFromMatrixPosition(y.matrixWorld),g.position.applyMatrix4(d),g.direction.setFromMatrixPosition(y.matrixWorld),r.setFromMatrixPosition(y.target.matrixWorld),g.direction.sub(r),g.direction.transformDirection(d),p++}else if(y.isRectAreaLight){const g=n.rectArea[_];g.position.setFromMatrixPosition(y.matrixWorld),g.position.applyMatrix4(d),s.identity(),a.copy(y.matrixWorld),a.premultiply(d),s.extractRotation(a),g.halfWidth.set(y.width*.5,0,0),g.halfHeight.set(0,y.height*.5,0),g.halfWidth.applyMatrix4(s),g.halfHeight.applyMatrix4(s),_++}else if(y.isPointLight){const g=n.point[v];g.position.setFromMatrixPosition(y.matrixWorld),g.position.applyMatrix4(d),v++}else if(y.isHemisphereLight){const g=n.hemi[m];g.direction.setFromMatrixPosition(y.matrixWorld),g.direction.transformDirection(d),m++}}}return{setup:o,setupView:c,state:n}}function hf(i){const e=new Cy(i),t=[],n=[];function r(l){h.camera=l,t.length=0,n.length=0}function a(l){t.push(l)}function s(l){n.push(l)}function o(){e.setup(t)}function c(l){e.setupView(t,l)}const h={lightsArray:t,shadowsArray:n,camera:null,lights:e,transmissionRenderTarget:{}};return{init:r,state:h,setupLights:o,setupLightsView:c,pushLight:a,pushShadow:s}}function wy(i){let e=new WeakMap;function t(r,a=0){const s=e.get(r);let o;return s===void 0?(o=new hf(i),e.set(r,[o])):a>=s.length?(o=new hf(i),s.push(o)):o=s[a],o}function n(){e=new WeakMap}return{get:t,dispose:n}}const My=`void main() {
	gl_Position = vec4( position, 1.0 );
}`,xy=`uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
#include <packing>
void main() {
	const float samples = float( VSM_SAMPLES );
	float mean = 0.0;
	float squared_mean = 0.0;
	float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
	float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
	for ( float i = 0.0; i < samples; i ++ ) {
		float uvOffset = uvStart + i * uvStride;
		#ifdef HORIZONTAL_PASS
			vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
			mean += distribution.x;
			squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
		#else
			float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
			mean += depth;
			squared_mean += depth * depth;
		#endif
	}
	mean = mean / samples;
	squared_mean = squared_mean / samples;
	float std_dev = sqrt( squared_mean - mean * mean );
	gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
}`;function Iy(i,e,t){let n=new Lp;const r=new xt,a=new xt,s=new Ft,o=new B0({depthPacking:Kv}),c=new V0,h={},l=t.maxTextureSize,f={[Kn]:yi,[yi]:Kn,[Tn]:Tn},v=new kn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new xt},radius:{value:4}},vertexShader:My,fragmentShader:xy}),p=v.clone();p.defines.HORIZONTAL_PASS=1;const _=new Sr;_.setAttribute("position",new mn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new gn(_,v),d=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Vh;let u=this.type;this.render=function(R,E,I){if(d.enabled===!1||d.autoUpdate===!1&&d.needsUpdate===!1||R.length===0)return;const C=i.getRenderTarget(),A=i.getActiveCubeFace(),w=i.getActiveMipmapLevel(),N=i.state;N.setBlending(qn),N.buffers.color.setClear(1,1,1,1),N.buffers.depth.setTest(!0),N.setScissorTest(!1);const M=u!==Rn&&this.type===Rn,D=u===Rn&&this.type!==Rn;for(let L=0,P=R.length;L<P;L++){const x=R[L],T=x.shadow;if(T===void 0){console.warn("THREE.WebGLShadowMap:",x,"has no shadow.");continue}if(T.autoUpdate===!1&&T.needsUpdate===!1)continue;r.copy(T.mapSize);const O=T.getFrameExtents();if(r.multiply(O),a.copy(T.mapSize),(r.x>l||r.y>l)&&(r.x>l&&(a.x=Math.floor(l/O.x),r.x=a.x*O.x,T.mapSize.x=a.x),r.y>l&&(a.y=Math.floor(l/O.y),r.y=a.y*O.y,T.mapSize.y=a.y)),T.map===null||M===!0||D===!0){const H=this.type!==Rn?{minFilter:en,magFilter:en}:{};T.map!==null&&T.map.dispose(),T.map=new mr(r.x,r.y,H),T.map.texture.name=x.name+".shadowMap",T.camera.updateProjectionMatrix()}i.setRenderTarget(T.map),i.clear();const k=T.getViewportCount();for(let H=0;H<k;H++){const U=T.getViewport(H);s.set(a.x*U.x,a.y*U.y,a.x*U.z,a.y*U.w),N.viewport(s),T.updateMatrices(x,H),n=T.getFrustum(),g(E,I,T.camera,x,this.type)}T.isPointLightShadow!==!0&&this.type===Rn&&b(T,I),T.needsUpdate=!1}u=this.type,d.needsUpdate=!1,i.setRenderTarget(C,A,w)};function b(R,E){const I=e.update(m);v.defines.VSM_SAMPLES!==R.blurSamples&&(v.defines.VSM_SAMPLES=R.blurSamples,p.defines.VSM_SAMPLES=R.blurSamples,v.needsUpdate=!0,p.needsUpdate=!0),R.mapPass===null&&(R.mapPass=new mr(r.x,r.y)),v.uniforms.shadow_pass.value=R.map.texture,v.uniforms.resolution.value=R.mapSize,v.uniforms.radius.value=R.radius,i.setRenderTarget(R.mapPass),i.clear(),i.renderBufferDirect(E,null,I,v,m,null),p.uniforms.shadow_pass.value=R.mapPass.texture,p.uniforms.resolution.value=R.mapSize,p.uniforms.radius.value=R.radius,i.setRenderTarget(R.map),i.clear(),i.renderBufferDirect(E,null,I,p,m,null)}function y(R,E,I,C){let A=null;const w=I.isPointLight===!0?R.customDistanceMaterial:R.customDepthMaterial;if(w!==void 0)A=w;else if(A=I.isPointLight===!0?c:o,i.localClippingEnabled&&E.clipShadows===!0&&Array.isArray(E.clippingPlanes)&&E.clippingPlanes.length!==0||E.displacementMap&&E.displacementScale!==0||E.alphaMap&&E.alphaTest>0||E.map&&E.alphaTest>0){const N=A.uuid,M=E.uuid;let D=h[N];D===void 0&&(D={},h[N]=D);let L=D[M];L===void 0&&(L=A.clone(),D[M]=L,E.addEventListener("dispose",S)),A=L}if(A.visible=E.visible,A.wireframe=E.wireframe,C===Rn?A.side=E.shadowSide!==null?E.shadowSide:E.side:A.side=E.shadowSide!==null?E.shadowSide:f[E.side],A.alphaMap=E.alphaMap,A.alphaTest=E.alphaTest,A.map=E.map,A.clipShadows=E.clipShadows,A.clippingPlanes=E.clippingPlanes,A.clipIntersection=E.clipIntersection,A.displacementMap=E.displacementMap,A.displacementScale=E.displacementScale,A.displacementBias=E.displacementBias,A.wireframeLinewidth=E.wireframeLinewidth,A.linewidth=E.linewidth,I.isPointLight===!0&&A.isMeshDistanceMaterial===!0){const N=i.properties.get(A);N.light=I}return A}function g(R,E,I,C,A){if(R.visible===!1)return;if(R.layers.test(E.layers)&&(R.isMesh||R.isLine||R.isPoints)&&(R.castShadow||R.receiveShadow&&A===Rn)&&(!R.frustumCulled||n.intersectsObject(R))){R.modelViewMatrix.multiplyMatrices(I.matrixWorldInverse,R.matrixWorld);const M=e.update(R),D=R.material;if(Array.isArray(D)){const L=M.groups;for(let P=0,x=L.length;P<x;P++){const T=L[P],O=D[T.materialIndex];if(O&&O.visible){const k=y(R,O,C,A);R.onBeforeShadow(i,R,E,I,M,k,T),i.renderBufferDirect(I,null,M,k,R,T),R.onAfterShadow(i,R,E,I,M,k,T)}}}else if(D.visible){const L=y(R,D,C,A);R.onBeforeShadow(i,R,E,I,M,L,null),i.renderBufferDirect(I,null,M,L,R,null),R.onAfterShadow(i,R,E,I,M,L,null)}}const N=R.children;for(let M=0,D=N.length;M<D;M++)g(N[M],E,I,C,A)}function S(R){R.target.removeEventListener("dispose",S);for(const I in h){const C=h[I],A=R.target.uuid;A in C&&(C[A].dispose(),delete C[A])}}}const Py={[cc]:lc,[uc]:pc,[dc]:fc,[Fr]:hc,[lc]:cc,[pc]:uc,[fc]:dc,[hc]:Fr};function Dy(i,e){function t(){let j=!1;const te=new Ft;let Q=null;const ne=new Ft(0,0,0,0);return{setMask:function(ae){Q!==ae&&!j&&(i.colorMask(ae,ae,ae,ae),Q=ae)},setLocked:function(ae){j=ae},setClear:function(ae,oe,Se,_e,xe){xe===!0&&(ae*=_e,oe*=_e,Se*=_e),te.set(ae,oe,Se,_e),ne.equals(te)===!1&&(i.clearColor(ae,oe,Se,_e),ne.copy(te))},reset:function(){j=!1,Q=null,ne.set(-1,0,0,0)}}}function n(){let j=!1,te=!1,Q=null,ne=null,ae=null;return{setReversed:function(oe){if(te!==oe){const Se=e.get("EXT_clip_control");te?Se.clipControlEXT(Se.LOWER_LEFT_EXT,Se.ZERO_TO_ONE_EXT):Se.clipControlEXT(Se.LOWER_LEFT_EXT,Se.NEGATIVE_ONE_TO_ONE_EXT);const _e=ae;ae=null,this.setClear(_e)}te=oe},getReversed:function(){return te},setTest:function(oe){oe?F(i.DEPTH_TEST):G(i.DEPTH_TEST)},setMask:function(oe){Q!==oe&&!j&&(i.depthMask(oe),Q=oe)},setFunc:function(oe){if(te&&(oe=Py[oe]),ne!==oe){switch(oe){case cc:i.depthFunc(i.NEVER);break;case lc:i.depthFunc(i.ALWAYS);break;case uc:i.depthFunc(i.LESS);break;case Fr:i.depthFunc(i.LEQUAL);break;case dc:i.depthFunc(i.EQUAL);break;case hc:i.depthFunc(i.GEQUAL);break;case pc:i.depthFunc(i.GREATER);break;case fc:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}ne=oe}},setLocked:function(oe){j=oe},setClear:function(oe){ae!==oe&&(te&&(oe=1-oe),i.clearDepth(oe),ae=oe)},reset:function(){j=!1,Q=null,ne=null,ae=null,te=!1}}}function r(){let j=!1,te=null,Q=null,ne=null,ae=null,oe=null,Se=null,_e=null,xe=null;return{setTest:function(Pe){j||(Pe?F(i.STENCIL_TEST):G(i.STENCIL_TEST))},setMask:function(Pe){te!==Pe&&!j&&(i.stencilMask(Pe),te=Pe)},setFunc:function(Pe,He,it){(Q!==Pe||ne!==He||ae!==it)&&(i.stencilFunc(Pe,He,it),Q=Pe,ne=He,ae=it)},setOp:function(Pe,He,it){(oe!==Pe||Se!==He||_e!==it)&&(i.stencilOp(Pe,He,it),oe=Pe,Se=He,_e=it)},setLocked:function(Pe){j=Pe},setClear:function(Pe){xe!==Pe&&(i.clearStencil(Pe),xe=Pe)},reset:function(){j=!1,te=null,Q=null,ne=null,ae=null,oe=null,Se=null,_e=null,xe=null}}}const a=new t,s=new n,o=new r,c=new WeakMap,h=new WeakMap;let l={},f={},v=new WeakMap,p=[],_=null,m=!1,d=null,u=null,b=null,y=null,g=null,S=null,R=null,E=new It(0,0,0),I=0,C=!1,A=null,w=null,N=null,M=null,D=null;const L=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let P=!1,x=0;const T=i.getParameter(i.VERSION);T.indexOf("WebGL")!==-1?(x=parseFloat(/^WebGL (\d)/.exec(T)[1]),P=x>=1):T.indexOf("OpenGL ES")!==-1&&(x=parseFloat(/^OpenGL ES (\d)/.exec(T)[1]),P=x>=2);let O=null,k={};const H=i.getParameter(i.SCISSOR_BOX),U=i.getParameter(i.VIEWPORT),ee=new Ft().fromArray(H),W=new Ft().fromArray(U);function $(j,te,Q,ne){const ae=new Uint8Array(4),oe=i.createTexture();i.bindTexture(j,oe),i.texParameteri(j,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(j,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let Se=0;Se<Q;Se++)j===i.TEXTURE_3D||j===i.TEXTURE_2D_ARRAY?i.texImage3D(te,0,i.RGBA,1,1,ne,0,i.RGBA,i.UNSIGNED_BYTE,ae):i.texImage2D(te+Se,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,ae);return oe}const B={};B[i.TEXTURE_2D]=$(i.TEXTURE_2D,i.TEXTURE_2D,1),B[i.TEXTURE_CUBE_MAP]=$(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),B[i.TEXTURE_2D_ARRAY]=$(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),B[i.TEXTURE_3D]=$(i.TEXTURE_3D,i.TEXTURE_3D,1,1),a.setClear(0,0,0,1),s.setClear(1),o.setClear(0),F(i.DEPTH_TEST),s.setFunc(Fr),he(!1),pe(Bh),F(i.CULL_FACE),Y(qn);function F(j){l[j]!==!0&&(i.enable(j),l[j]=!0)}function G(j){l[j]!==!1&&(i.disable(j),l[j]=!1)}function q(j,te){return f[j]!==te?(i.bindFramebuffer(j,te),f[j]=te,j===i.DRAW_FRAMEBUFFER&&(f[i.FRAMEBUFFER]=te),j===i.FRAMEBUFFER&&(f[i.DRAW_FRAMEBUFFER]=te),!0):!1}function X(j,te){let Q=p,ne=!1;if(j){Q=v.get(te),Q===void 0&&(Q=[],v.set(te,Q));const ae=j.textures;if(Q.length!==ae.length||Q[0]!==i.COLOR_ATTACHMENT0){for(let oe=0,Se=ae.length;oe<Se;oe++)Q[oe]=i.COLOR_ATTACHMENT0+oe;Q.length=ae.length,ne=!0}}else Q[0]!==i.BACK&&(Q[0]=i.BACK,ne=!0);ne&&i.drawBuffers(Q)}function J(j){return _!==j?(i.useProgram(j),_=j,!0):!1}const se={[hr]:i.FUNC_ADD,[bv]:i.FUNC_SUBTRACT,[yv]:i.FUNC_REVERSE_SUBTRACT};se[Ev]=i.MIN,se[Rv]=i.MAX;const ce={[Tv]:i.ZERO,[Av]:i.ONE,[Cv]:i.SRC_COLOR,[sc]:i.SRC_ALPHA,[Dv]:i.SRC_ALPHA_SATURATE,[Iv]:i.DST_COLOR,[Mv]:i.DST_ALPHA,[wv]:i.ONE_MINUS_SRC_COLOR,[ac]:i.ONE_MINUS_SRC_ALPHA,[Pv]:i.ONE_MINUS_DST_COLOR,[xv]:i.ONE_MINUS_DST_ALPHA,[Lv]:i.CONSTANT_COLOR,[Ov]:i.ONE_MINUS_CONSTANT_COLOR,[Nv]:i.CONSTANT_ALPHA,[kv]:i.ONE_MINUS_CONSTANT_ALPHA};function Y(j,te,Q,ne,ae,oe,Se,_e,xe,Pe){if(j===qn){m===!0&&(G(i.BLEND),m=!1);return}if(m===!1&&(F(i.BLEND),m=!0),j!==Sv){if(j!==d||Pe!==C){if((u!==hr||g!==hr)&&(i.blendEquation(i.FUNC_ADD),u=hr,g=hr),Pe)switch(j){case Vr:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Fh:i.blendFunc(i.ONE,i.ONE);break;case Hh:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case Gh:i.blendFuncSeparate(i.ZERO,i.SRC_COLOR,i.ZERO,i.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",j);break}else switch(j){case Vr:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Fh:i.blendFunc(i.SRC_ALPHA,i.ONE);break;case Hh:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case Gh:i.blendFunc(i.ZERO,i.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",j);break}b=null,y=null,S=null,R=null,E.set(0,0,0),I=0,d=j,C=Pe}return}ae=ae||te,oe=oe||Q,Se=Se||ne,(te!==u||ae!==g)&&(i.blendEquationSeparate(se[te],se[ae]),u=te,g=ae),(Q!==b||ne!==y||oe!==S||Se!==R)&&(i.blendFuncSeparate(ce[Q],ce[ne],ce[oe],ce[Se]),b=Q,y=ne,S=oe,R=Se),(_e.equals(E)===!1||xe!==I)&&(i.blendColor(_e.r,_e.g,_e.b,xe),E.copy(_e),I=xe),d=j,C=!1}function fe(j,te){j.side===Tn?G(i.CULL_FACE):F(i.CULL_FACE);let Q=j.side===yi;te&&(Q=!Q),he(Q),j.blending===Vr&&j.transparent===!1?Y(qn):Y(j.blending,j.blendEquation,j.blendSrc,j.blendDst,j.blendEquationAlpha,j.blendSrcAlpha,j.blendDstAlpha,j.blendColor,j.blendAlpha,j.premultipliedAlpha),s.setFunc(j.depthFunc),s.setTest(j.depthTest),s.setMask(j.depthWrite),a.setMask(j.colorWrite);const ne=j.stencilWrite;o.setTest(ne),ne&&(o.setMask(j.stencilWriteMask),o.setFunc(j.stencilFunc,j.stencilRef,j.stencilFuncMask),o.setOp(j.stencilFail,j.stencilZFail,j.stencilZPass)),Te(j.polygonOffset,j.polygonOffsetFactor,j.polygonOffsetUnits),j.alphaToCoverage===!0?F(i.SAMPLE_ALPHA_TO_COVERAGE):G(i.SAMPLE_ALPHA_TO_COVERAGE)}function he(j){A!==j&&(j?i.frontFace(i.CW):i.frontFace(i.CCW),A=j)}function pe(j){j!==gv?(F(i.CULL_FACE),j!==w&&(j===Bh?i.cullFace(i.BACK):j===vv?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):G(i.CULL_FACE),w=j}function ue(j){j!==N&&(P&&i.lineWidth(j),N=j)}function Te(j,te,Q){j?(F(i.POLYGON_OFFSET_FILL),(M!==te||D!==Q)&&(i.polygonOffset(te,Q),M=te,D=Q)):G(i.POLYGON_OFFSET_FILL)}function be(j){j?F(i.SCISSOR_TEST):G(i.SCISSOR_TEST)}function Z(j){j===void 0&&(j=i.TEXTURE0+L-1),O!==j&&(i.activeTexture(j),O=j)}function K(j,te,Q){Q===void 0&&(O===null?Q=i.TEXTURE0+L-1:Q=O);let ne=k[Q];ne===void 0&&(ne={type:void 0,texture:void 0},k[Q]=ne),(ne.type!==j||ne.texture!==te)&&(O!==Q&&(i.activeTexture(Q),O=Q),i.bindTexture(j,te||B[j]),ne.type=j,ne.texture=te)}function re(){const j=k[O];j!==void 0&&j.type!==void 0&&(i.bindTexture(j.type,null),j.type=void 0,j.texture=void 0)}function de(){try{i.compressedTexImage2D.apply(i,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function ye(){try{i.compressedTexImage3D.apply(i,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function Ee(){try{i.texSubImage2D.apply(i,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function Ve(){try{i.texSubImage3D.apply(i,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function De(){try{i.compressedTexSubImage2D.apply(i,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function Ue(){try{i.compressedTexSubImage3D.apply(i,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function Ye(){try{i.texStorage2D.apply(i,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function Ie(){try{i.texStorage3D.apply(i,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function Oe(){try{i.texImage2D.apply(i,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function $e(){try{i.texImage3D.apply(i,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function Ke(j){ee.equals(j)===!1&&(i.scissor(j.x,j.y,j.z,j.w),ee.copy(j))}function Fe(j){W.equals(j)===!1&&(i.viewport(j.x,j.y,j.z,j.w),W.copy(j))}function st(j,te){let Q=h.get(te);Q===void 0&&(Q=new WeakMap,h.set(te,Q));let ne=Q.get(j);ne===void 0&&(ne=i.getUniformBlockIndex(te,j.name),Q.set(j,ne))}function tt(j,te){const ne=h.get(te).get(j);c.get(te)!==ne&&(i.uniformBlockBinding(te,ne,j.__bindingPointIndex),c.set(te,ne))}function z(){i.disable(i.BLEND),i.disable(i.CULL_FACE),i.disable(i.DEPTH_TEST),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SCISSOR_TEST),i.disable(i.STENCIL_TEST),i.disable(i.SAMPLE_ALPHA_TO_COVERAGE),i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ZERO),i.blendFuncSeparate(i.ONE,i.ZERO,i.ONE,i.ZERO),i.blendColor(0,0,0,0),i.colorMask(!0,!0,!0,!0),i.clearColor(0,0,0,0),i.depthMask(!0),i.depthFunc(i.LESS),s.setReversed(!1),i.clearDepth(1),i.stencilMask(4294967295),i.stencilFunc(i.ALWAYS,0,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.clearStencil(0),i.cullFace(i.BACK),i.frontFace(i.CCW),i.polygonOffset(0,0),i.activeTexture(i.TEXTURE0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.useProgram(null),i.lineWidth(1),i.scissor(0,0,i.canvas.width,i.canvas.height),i.viewport(0,0,i.canvas.width,i.canvas.height),l={},O=null,k={},f={},v=new WeakMap,p=[],_=null,m=!1,d=null,u=null,b=null,y=null,g=null,S=null,R=null,E=new It(0,0,0),I=0,C=!1,A=null,w=null,N=null,M=null,D=null,ee.set(0,0,i.canvas.width,i.canvas.height),W.set(0,0,i.canvas.width,i.canvas.height),a.reset(),s.reset(),o.reset()}return{buffers:{color:a,depth:s,stencil:o},enable:F,disable:G,bindFramebuffer:q,drawBuffers:X,useProgram:J,setBlending:Y,setMaterial:fe,setFlipSided:he,setCullFace:pe,setLineWidth:ue,setPolygonOffset:Te,setScissorTest:be,activeTexture:Z,bindTexture:K,unbindTexture:re,compressedTexImage2D:de,compressedTexImage3D:ye,texImage2D:Oe,texImage3D:$e,updateUBOMapping:st,uniformBlockBinding:tt,texStorage2D:Ye,texStorage3D:Ie,texSubImage2D:Ee,texSubImage3D:Ve,compressedTexSubImage2D:De,compressedTexSubImage3D:Ue,scissor:Ke,viewport:Fe,reset:z}}function Ly(i,e,t,n,r,a,s){const o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),h=new xt,l=new WeakMap;let f;const v=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(Z,K){return p?new OffscreenCanvas(Z,K):As("canvas")}function m(Z,K,re){let de=1;const ye=be(Z);if((ye.width>re||ye.height>re)&&(de=re/Math.max(ye.width,ye.height)),de<1)if(typeof HTMLImageElement<"u"&&Z instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&Z instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&Z instanceof ImageBitmap||typeof VideoFrame<"u"&&Z instanceof VideoFrame){const Ee=Math.floor(de*ye.width),Ve=Math.floor(de*ye.height);f===void 0&&(f=_(Ee,Ve));const De=K?_(Ee,Ve):f;return De.width=Ee,De.height=Ve,De.getContext("2d").drawImage(Z,0,0,Ee,Ve),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+ye.width+"x"+ye.height+") to ("+Ee+"x"+Ve+")."),De}else return"data"in Z&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+ye.width+"x"+ye.height+")."),Z;return Z}function d(Z){return Z.generateMipmaps}function u(Z){i.generateMipmap(Z)}function b(Z){return Z.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:Z.isWebGL3DRenderTarget?i.TEXTURE_3D:Z.isWebGLArrayRenderTarget||Z.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function y(Z,K,re,de,ye=!1){if(Z!==null){if(i[Z]!==void 0)return i[Z];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+Z+"'")}let Ee=K;if(K===i.RED&&(re===i.FLOAT&&(Ee=i.R32F),re===i.HALF_FLOAT&&(Ee=i.R16F),re===i.UNSIGNED_BYTE&&(Ee=i.R8)),K===i.RED_INTEGER&&(re===i.UNSIGNED_BYTE&&(Ee=i.R8UI),re===i.UNSIGNED_SHORT&&(Ee=i.R16UI),re===i.UNSIGNED_INT&&(Ee=i.R32UI),re===i.BYTE&&(Ee=i.R8I),re===i.SHORT&&(Ee=i.R16I),re===i.INT&&(Ee=i.R32I)),K===i.RG&&(re===i.FLOAT&&(Ee=i.RG32F),re===i.HALF_FLOAT&&(Ee=i.RG16F),re===i.UNSIGNED_BYTE&&(Ee=i.RG8)),K===i.RG_INTEGER&&(re===i.UNSIGNED_BYTE&&(Ee=i.RG8UI),re===i.UNSIGNED_SHORT&&(Ee=i.RG16UI),re===i.UNSIGNED_INT&&(Ee=i.RG32UI),re===i.BYTE&&(Ee=i.RG8I),re===i.SHORT&&(Ee=i.RG16I),re===i.INT&&(Ee=i.RG32I)),K===i.RGB_INTEGER&&(re===i.UNSIGNED_BYTE&&(Ee=i.RGB8UI),re===i.UNSIGNED_SHORT&&(Ee=i.RGB16UI),re===i.UNSIGNED_INT&&(Ee=i.RGB32UI),re===i.BYTE&&(Ee=i.RGB8I),re===i.SHORT&&(Ee=i.RGB16I),re===i.INT&&(Ee=i.RGB32I)),K===i.RGBA_INTEGER&&(re===i.UNSIGNED_BYTE&&(Ee=i.RGBA8UI),re===i.UNSIGNED_SHORT&&(Ee=i.RGBA16UI),re===i.UNSIGNED_INT&&(Ee=i.RGBA32UI),re===i.BYTE&&(Ee=i.RGBA8I),re===i.SHORT&&(Ee=i.RGBA16I),re===i.INT&&(Ee=i.RGBA32I)),K===i.RGB&&re===i.UNSIGNED_INT_5_9_9_9_REV&&(Ee=i.RGB9_E5),K===i.RGBA){const Ve=ye?Rs:Et.getTransfer(de);re===i.FLOAT&&(Ee=i.RGBA32F),re===i.HALF_FLOAT&&(Ee=i.RGBA16F),re===i.UNSIGNED_BYTE&&(Ee=Ve===Mt?i.SRGB8_ALPHA8:i.RGBA8),re===i.UNSIGNED_SHORT_4_4_4_4&&(Ee=i.RGBA4),re===i.UNSIGNED_SHORT_5_5_5_1&&(Ee=i.RGB5_A1)}return(Ee===i.R16F||Ee===i.R32F||Ee===i.RG16F||Ee===i.RG32F||Ee===i.RGBA16F||Ee===i.RGBA32F)&&e.get("EXT_color_buffer_float"),Ee}function g(Z,K){let re;return Z?K===null||K===fr||K===zr?re=i.DEPTH24_STENCIL8:K===wn?re=i.DEPTH32F_STENCIL8:K===Io&&(re=i.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):K===null||K===fr||K===zr?re=i.DEPTH_COMPONENT24:K===wn?re=i.DEPTH_COMPONENT32F:K===Io&&(re=i.DEPTH_COMPONENT16),re}function S(Z,K){return d(Z)===!0||Z.isFramebufferTexture&&Z.minFilter!==en&&Z.minFilter!==Ei?Math.log2(Math.max(K.width,K.height))+1:Z.mipmaps!==void 0&&Z.mipmaps.length>0?Z.mipmaps.length:Z.isCompressedTexture&&Array.isArray(Z.image)?K.mipmaps.length:1}function R(Z){const K=Z.target;K.removeEventListener("dispose",R),I(K),K.isVideoTexture&&l.delete(K)}function E(Z){const K=Z.target;K.removeEventListener("dispose",E),A(K)}function I(Z){const K=n.get(Z);if(K.__webglInit===void 0)return;const re=Z.source,de=v.get(re);if(de){const ye=de[K.__cacheKey];ye.usedTimes--,ye.usedTimes===0&&C(Z),Object.keys(de).length===0&&v.delete(re)}n.remove(Z)}function C(Z){const K=n.get(Z);i.deleteTexture(K.__webglTexture);const re=Z.source,de=v.get(re);delete de[K.__cacheKey],s.memory.textures--}function A(Z){const K=n.get(Z);if(Z.depthTexture&&(Z.depthTexture.dispose(),n.remove(Z.depthTexture)),Z.isWebGLCubeRenderTarget)for(let de=0;de<6;de++){if(Array.isArray(K.__webglFramebuffer[de]))for(let ye=0;ye<K.__webglFramebuffer[de].length;ye++)i.deleteFramebuffer(K.__webglFramebuffer[de][ye]);else i.deleteFramebuffer(K.__webglFramebuffer[de]);K.__webglDepthbuffer&&i.deleteRenderbuffer(K.__webglDepthbuffer[de])}else{if(Array.isArray(K.__webglFramebuffer))for(let de=0;de<K.__webglFramebuffer.length;de++)i.deleteFramebuffer(K.__webglFramebuffer[de]);else i.deleteFramebuffer(K.__webglFramebuffer);if(K.__webglDepthbuffer&&i.deleteRenderbuffer(K.__webglDepthbuffer),K.__webglMultisampledFramebuffer&&i.deleteFramebuffer(K.__webglMultisampledFramebuffer),K.__webglColorRenderbuffer)for(let de=0;de<K.__webglColorRenderbuffer.length;de++)K.__webglColorRenderbuffer[de]&&i.deleteRenderbuffer(K.__webglColorRenderbuffer[de]);K.__webglDepthRenderbuffer&&i.deleteRenderbuffer(K.__webglDepthRenderbuffer)}const re=Z.textures;for(let de=0,ye=re.length;de<ye;de++){const Ee=n.get(re[de]);Ee.__webglTexture&&(i.deleteTexture(Ee.__webglTexture),s.memory.textures--),n.remove(re[de])}n.remove(Z)}let w=0;function N(){w=0}function M(){const Z=w;return Z>=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+Z+" texture units while this GPU supports only "+r.maxTextures),w+=1,Z}function D(Z){const K=[];return K.push(Z.wrapS),K.push(Z.wrapT),K.push(Z.wrapR||0),K.push(Z.magFilter),K.push(Z.minFilter),K.push(Z.anisotropy),K.push(Z.internalFormat),K.push(Z.format),K.push(Z.type),K.push(Z.generateMipmaps),K.push(Z.premultiplyAlpha),K.push(Z.flipY),K.push(Z.unpackAlignment),K.push(Z.colorSpace),K.join()}function L(Z,K){const re=n.get(Z);if(Z.isVideoTexture&&ue(Z),Z.isRenderTargetTexture===!1&&Z.version>0&&re.__version!==Z.version){const de=Z.image;if(de===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(de.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{W(re,Z,K);return}}t.bindTexture(i.TEXTURE_2D,re.__webglTexture,i.TEXTURE0+K)}function P(Z,K){const re=n.get(Z);if(Z.version>0&&re.__version!==Z.version){W(re,Z,K);return}t.bindTexture(i.TEXTURE_2D_ARRAY,re.__webglTexture,i.TEXTURE0+K)}function x(Z,K){const re=n.get(Z);if(Z.version>0&&re.__version!==Z.version){W(re,Z,K);return}t.bindTexture(i.TEXTURE_3D,re.__webglTexture,i.TEXTURE0+K)}function T(Z,K){const re=n.get(Z);if(Z.version>0&&re.__version!==Z.version){$(re,Z,K);return}t.bindTexture(i.TEXTURE_CUBE_MAP,re.__webglTexture,i.TEXTURE0+K)}const O={[vc]:i.REPEAT,[An]:i.CLAMP_TO_EDGE,[_c]:i.MIRRORED_REPEAT},k={[en]:i.NEAREST,[Xv]:i.NEAREST_MIPMAP_NEAREST,[vs]:i.NEAREST_MIPMAP_LINEAR,[Ei]:i.LINEAR,[Sc]:i.LINEAR_MIPMAP_NEAREST,[pr]:i.LINEAR_MIPMAP_LINEAR},H={[Jv]:i.NEVER,[n0]:i.ALWAYS,[Qv]:i.LESS,[ip]:i.LEQUAL,[Zv]:i.EQUAL,[i0]:i.GEQUAL,[e0]:i.GREATER,[t0]:i.NOTEQUAL};function U(Z,K){if(K.type===wn&&e.has("OES_texture_float_linear")===!1&&(K.magFilter===Ei||K.magFilter===Sc||K.magFilter===vs||K.magFilter===pr||K.minFilter===Ei||K.minFilter===Sc||K.minFilter===vs||K.minFilter===pr)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(Z,i.TEXTURE_WRAP_S,O[K.wrapS]),i.texParameteri(Z,i.TEXTURE_WRAP_T,O[K.wrapT]),(Z===i.TEXTURE_3D||Z===i.TEXTURE_2D_ARRAY)&&i.texParameteri(Z,i.TEXTURE_WRAP_R,O[K.wrapR]),i.texParameteri(Z,i.TEXTURE_MAG_FILTER,k[K.magFilter]),i.texParameteri(Z,i.TEXTURE_MIN_FILTER,k[K.minFilter]),K.compareFunction&&(i.texParameteri(Z,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(Z,i.TEXTURE_COMPARE_FUNC,H[K.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(K.magFilter===en||K.minFilter!==vs&&K.minFilter!==pr||K.type===wn&&e.has("OES_texture_float_linear")===!1)return;if(K.anisotropy>1||n.get(K).__currentAnisotropy){const re=e.get("EXT_texture_filter_anisotropic");i.texParameterf(Z,re.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(K.anisotropy,r.getMaxAnisotropy())),n.get(K).__currentAnisotropy=K.anisotropy}}}function ee(Z,K){let re=!1;Z.__webglInit===void 0&&(Z.__webglInit=!0,K.addEventListener("dispose",R));const de=K.source;let ye=v.get(de);ye===void 0&&(ye={},v.set(de,ye));const Ee=D(K);if(Ee!==Z.__cacheKey){ye[Ee]===void 0&&(ye[Ee]={texture:i.createTexture(),usedTimes:0},s.memory.textures++,re=!0),ye[Ee].usedTimes++;const Ve=ye[Z.__cacheKey];Ve!==void 0&&(ye[Z.__cacheKey].usedTimes--,Ve.usedTimes===0&&C(K)),Z.__cacheKey=Ee,Z.__webglTexture=ye[Ee].texture}return re}function W(Z,K,re){let de=i.TEXTURE_2D;(K.isDataArrayTexture||K.isCompressedArrayTexture)&&(de=i.TEXTURE_2D_ARRAY),K.isData3DTexture&&(de=i.TEXTURE_3D);const ye=ee(Z,K),Ee=K.source;t.bindTexture(de,Z.__webglTexture,i.TEXTURE0+re);const Ve=n.get(Ee);if(Ee.version!==Ve.__version||ye===!0){t.activeTexture(i.TEXTURE0+re);const De=Et.getPrimaries(Et.workingColorSpace),Ue=K.colorSpace===Jn?null:Et.getPrimaries(K.colorSpace),Ye=K.colorSpace===Jn||De===Ue?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,K.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,K.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,K.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ye);let Ie=m(K.image,!1,r.maxTextureSize);Ie=Te(K,Ie);const Oe=a.convert(K.format,K.colorSpace),$e=a.convert(K.type);let Ke=y(K.internalFormat,Oe,$e,K.colorSpace,K.isVideoTexture);U(de,K);let Fe;const st=K.mipmaps,tt=K.isVideoTexture!==!0,z=Ve.__version===void 0||ye===!0,j=Ee.dataReady,te=S(K,Ie);if(K.isDepthTexture)Ke=g(K.format===jr,K.type),z&&(tt?t.texStorage2D(i.TEXTURE_2D,1,Ke,Ie.width,Ie.height):t.texImage2D(i.TEXTURE_2D,0,Ke,Ie.width,Ie.height,0,Oe,$e,null));else if(K.isDataTexture)if(st.length>0){tt&&z&&t.texStorage2D(i.TEXTURE_2D,te,Ke,st[0].width,st[0].height);for(let Q=0,ne=st.length;Q<ne;Q++)Fe=st[Q],tt?j&&t.texSubImage2D(i.TEXTURE_2D,Q,0,0,Fe.width,Fe.height,Oe,$e,Fe.data):t.texImage2D(i.TEXTURE_2D,Q,Ke,Fe.width,Fe.height,0,Oe,$e,Fe.data);K.generateMipmaps=!1}else tt?(z&&t.texStorage2D(i.TEXTURE_2D,te,Ke,Ie.width,Ie.height),j&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,Ie.width,Ie.height,Oe,$e,Ie.data)):t.texImage2D(i.TEXTURE_2D,0,Ke,Ie.width,Ie.height,0,Oe,$e,Ie.data);else if(K.isCompressedTexture)if(K.isCompressedArrayTexture){tt&&z&&t.texStorage3D(i.TEXTURE_2D_ARRAY,te,Ke,st[0].width,st[0].height,Ie.depth);for(let Q=0,ne=st.length;Q<ne;Q++)if(Fe=st[Q],K.format!==tn)if(Oe!==null)if(tt){if(j)if(K.layerUpdates.size>0){const ae=kp(Fe.width,Fe.height,K.format,K.type);for(const oe of K.layerUpdates){const Se=Fe.data.subarray(oe*ae/Fe.data.BYTES_PER_ELEMENT,(oe+1)*ae/Fe.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,Q,0,0,oe,Fe.width,Fe.height,1,Oe,Se)}K.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,Q,0,0,0,Fe.width,Fe.height,Ie.depth,Oe,Fe.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,Q,Ke,Fe.width,Fe.height,Ie.depth,0,Fe.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else tt?j&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,Q,0,0,0,Fe.width,Fe.height,Ie.depth,Oe,$e,Fe.data):t.texImage3D(i.TEXTURE_2D_ARRAY,Q,Ke,Fe.width,Fe.height,Ie.depth,0,Oe,$e,Fe.data)}else{tt&&z&&t.texStorage2D(i.TEXTURE_2D,te,Ke,st[0].width,st[0].height);for(let Q=0,ne=st.length;Q<ne;Q++)Fe=st[Q],K.format!==tn?Oe!==null?tt?j&&t.compressedTexSubImage2D(i.TEXTURE_2D,Q,0,0,Fe.width,Fe.height,Oe,Fe.data):t.compressedTexImage2D(i.TEXTURE_2D,Q,Ke,Fe.width,Fe.height,0,Fe.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):tt?j&&t.texSubImage2D(i.TEXTURE_2D,Q,0,0,Fe.width,Fe.height,Oe,$e,Fe.data):t.texImage2D(i.TEXTURE_2D,Q,Ke,Fe.width,Fe.height,0,Oe,$e,Fe.data)}else if(K.isDataArrayTexture)if(tt){if(z&&t.texStorage3D(i.TEXTURE_2D_ARRAY,te,Ke,Ie.width,Ie.height,Ie.depth),j)if(K.layerUpdates.size>0){const Q=kp(Ie.width,Ie.height,K.format,K.type);for(const ne of K.layerUpdates){const ae=Ie.data.subarray(ne*Q/Ie.data.BYTES_PER_ELEMENT,(ne+1)*Q/Ie.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,ne,Ie.width,Ie.height,1,Oe,$e,ae)}K.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,Ie.width,Ie.height,Ie.depth,Oe,$e,Ie.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,Ke,Ie.width,Ie.height,Ie.depth,0,Oe,$e,Ie.data);else if(K.isData3DTexture)tt?(z&&t.texStorage3D(i.TEXTURE_3D,te,Ke,Ie.width,Ie.height,Ie.depth),j&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,Ie.width,Ie.height,Ie.depth,Oe,$e,Ie.data)):t.texImage3D(i.TEXTURE_3D,0,Ke,Ie.width,Ie.height,Ie.depth,0,Oe,$e,Ie.data);else if(K.isFramebufferTexture){if(z)if(tt)t.texStorage2D(i.TEXTURE_2D,te,Ke,Ie.width,Ie.height);else{let Q=Ie.width,ne=Ie.height;for(let ae=0;ae<te;ae++)t.texImage2D(i.TEXTURE_2D,ae,Ke,Q,ne,0,Oe,$e,null),Q>>=1,ne>>=1}}else if(st.length>0){if(tt&&z){const Q=be(st[0]);t.texStorage2D(i.TEXTURE_2D,te,Ke,Q.width,Q.height)}for(let Q=0,ne=st.length;Q<ne;Q++)Fe=st[Q],tt?j&&t.texSubImage2D(i.TEXTURE_2D,Q,0,0,Oe,$e,Fe):t.texImage2D(i.TEXTURE_2D,Q,Ke,Oe,$e,Fe);K.generateMipmaps=!1}else if(tt){if(z){const Q=be(Ie);t.texStorage2D(i.TEXTURE_2D,te,Ke,Q.width,Q.height)}j&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,Oe,$e,Ie)}else t.texImage2D(i.TEXTURE_2D,0,Ke,Oe,$e,Ie);d(K)&&u(de),Ve.__version=Ee.version,K.onUpdate&&K.onUpdate(K)}Z.__version=K.version}function $(Z,K,re){if(K.image.length!==6)return;const de=ee(Z,K),ye=K.source;t.bindTexture(i.TEXTURE_CUBE_MAP,Z.__webglTexture,i.TEXTURE0+re);const Ee=n.get(ye);if(ye.version!==Ee.__version||de===!0){t.activeTexture(i.TEXTURE0+re);const Ve=Et.getPrimaries(Et.workingColorSpace),De=K.colorSpace===Jn?null:Et.getPrimaries(K.colorSpace),Ue=K.colorSpace===Jn||Ve===De?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,K.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,K.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,K.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ue);const Ye=K.isCompressedTexture||K.image[0].isCompressedTexture,Ie=K.image[0]&&K.image[0].isDataTexture,Oe=[];for(let ne=0;ne<6;ne++)!Ye&&!Ie?Oe[ne]=m(K.image[ne],!0,r.maxCubemapSize):Oe[ne]=Ie?K.image[ne].image:K.image[ne],Oe[ne]=Te(K,Oe[ne]);const $e=Oe[0],Ke=a.convert(K.format,K.colorSpace),Fe=a.convert(K.type),st=y(K.internalFormat,Ke,Fe,K.colorSpace),tt=K.isVideoTexture!==!0,z=Ee.__version===void 0||de===!0,j=ye.dataReady;let te=S(K,$e);U(i.TEXTURE_CUBE_MAP,K);let Q;if(Ye){tt&&z&&t.texStorage2D(i.TEXTURE_CUBE_MAP,te,st,$e.width,$e.height);for(let ne=0;ne<6;ne++){Q=Oe[ne].mipmaps;for(let ae=0;ae<Q.length;ae++){const oe=Q[ae];K.format!==tn?Ke!==null?tt?j&&t.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,ae,0,0,oe.width,oe.height,Ke,oe.data):t.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,ae,st,oe.width,oe.height,0,oe.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):tt?j&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,ae,0,0,oe.width,oe.height,Ke,Fe,oe.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,ae,st,oe.width,oe.height,0,Ke,Fe,oe.data)}}}else{if(Q=K.mipmaps,tt&&z){Q.length>0&&te++;const ne=be(Oe[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,te,st,ne.width,ne.height)}for(let ne=0;ne<6;ne++)if(Ie){tt?j&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,0,0,0,Oe[ne].width,Oe[ne].height,Ke,Fe,Oe[ne].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,0,st,Oe[ne].width,Oe[ne].height,0,Ke,Fe,Oe[ne].data);for(let ae=0;ae<Q.length;ae++){const Se=Q[ae].image[ne].image;tt?j&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,ae+1,0,0,Se.width,Se.height,Ke,Fe,Se.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,ae+1,st,Se.width,Se.height,0,Ke,Fe,Se.data)}}else{tt?j&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,0,0,0,Ke,Fe,Oe[ne]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,0,st,Ke,Fe,Oe[ne]);for(let ae=0;ae<Q.length;ae++){const oe=Q[ae];tt?j&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,ae+1,0,0,Ke,Fe,oe.image[ne]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+ne,ae+1,st,Ke,Fe,oe.image[ne])}}}d(K)&&u(i.TEXTURE_CUBE_MAP),Ee.__version=ye.version,K.onUpdate&&K.onUpdate(K)}Z.__version=K.version}function B(Z,K,re,de,ye,Ee){const Ve=a.convert(re.format,re.colorSpace),De=a.convert(re.type),Ue=y(re.internalFormat,Ve,De,re.colorSpace),Ye=n.get(K),Ie=n.get(re);if(Ie.__renderTarget=K,!Ye.__hasExternalTextures){const Oe=Math.max(1,K.width>>Ee),$e=Math.max(1,K.height>>Ee);ye===i.TEXTURE_3D||ye===i.TEXTURE_2D_ARRAY?t.texImage3D(ye,Ee,Ue,Oe,$e,K.depth,0,Ve,De,null):t.texImage2D(ye,Ee,Ue,Oe,$e,0,Ve,De,null)}t.bindFramebuffer(i.FRAMEBUFFER,Z),pe(K)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,de,ye,Ie.__webglTexture,0,he(K)):(ye===i.TEXTURE_2D||ye>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&ye<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,de,ye,Ie.__webglTexture,Ee),t.bindFramebuffer(i.FRAMEBUFFER,null)}function F(Z,K,re){if(i.bindRenderbuffer(i.RENDERBUFFER,Z),K.depthBuffer){const de=K.depthTexture,ye=de&&de.isDepthTexture?de.type:null,Ee=g(K.stencilBuffer,ye),Ve=K.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,De=he(K);pe(K)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,De,Ee,K.width,K.height):re?i.renderbufferStorageMultisample(i.RENDERBUFFER,De,Ee,K.width,K.height):i.renderbufferStorage(i.RENDERBUFFER,Ee,K.width,K.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,Ve,i.RENDERBUFFER,Z)}else{const de=K.textures;for(let ye=0;ye<de.length;ye++){const Ee=de[ye],Ve=a.convert(Ee.format,Ee.colorSpace),De=a.convert(Ee.type),Ue=y(Ee.internalFormat,Ve,De,Ee.colorSpace),Ye=he(K);re&&pe(K)===!1?i.renderbufferStorageMultisample(i.RENDERBUFFER,Ye,Ue,K.width,K.height):pe(K)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,Ye,Ue,K.width,K.height):i.renderbufferStorage(i.RENDERBUFFER,Ue,K.width,K.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function G(Z,K){if(K&&K.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(i.FRAMEBUFFER,Z),!(K.depthTexture&&K.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const de=n.get(K.depthTexture);de.__renderTarget=K,(!de.__webglTexture||K.depthTexture.image.width!==K.width||K.depthTexture.image.height!==K.height)&&(K.depthTexture.image.width=K.width,K.depthTexture.image.height=K.height,K.depthTexture.needsUpdate=!0),L(K.depthTexture,0);const ye=de.__webglTexture,Ee=he(K);if(K.depthTexture.format===Wr)pe(K)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,ye,0,Ee):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,ye,0);else if(K.depthTexture.format===jr)pe(K)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,ye,0,Ee):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,ye,0);else throw new Error("Unknown depthTexture format")}function q(Z){const K=n.get(Z),re=Z.isWebGLCubeRenderTarget===!0;if(K.__boundDepthTexture!==Z.depthTexture){const de=Z.depthTexture;if(K.__depthDisposeCallback&&K.__depthDisposeCallback(),de){const ye=()=>{delete K.__boundDepthTexture,delete K.__depthDisposeCallback,de.removeEventListener("dispose",ye)};de.addEventListener("dispose",ye),K.__depthDisposeCallback=ye}K.__boundDepthTexture=de}if(Z.depthTexture&&!K.__autoAllocateDepthBuffer){if(re)throw new Error("target.depthTexture not supported in Cube render targets");G(K.__webglFramebuffer,Z)}else if(re){K.__webglDepthbuffer=[];for(let de=0;de<6;de++)if(t.bindFramebuffer(i.FRAMEBUFFER,K.__webglFramebuffer[de]),K.__webglDepthbuffer[de]===void 0)K.__webglDepthbuffer[de]=i.createRenderbuffer(),F(K.__webglDepthbuffer[de],Z,!1);else{const ye=Z.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Ee=K.__webglDepthbuffer[de];i.bindRenderbuffer(i.RENDERBUFFER,Ee),i.framebufferRenderbuffer(i.FRAMEBUFFER,ye,i.RENDERBUFFER,Ee)}}else if(t.bindFramebuffer(i.FRAMEBUFFER,K.__webglFramebuffer),K.__webglDepthbuffer===void 0)K.__webglDepthbuffer=i.createRenderbuffer(),F(K.__webglDepthbuffer,Z,!1);else{const de=Z.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ye=K.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,ye),i.framebufferRenderbuffer(i.FRAMEBUFFER,de,i.RENDERBUFFER,ye)}t.bindFramebuffer(i.FRAMEBUFFER,null)}function X(Z,K,re){const de=n.get(Z);K!==void 0&&B(de.__webglFramebuffer,Z,Z.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),re!==void 0&&q(Z)}function J(Z){const K=Z.texture,re=n.get(Z),de=n.get(K);Z.addEventListener("dispose",E);const ye=Z.textures,Ee=Z.isWebGLCubeRenderTarget===!0,Ve=ye.length>1;if(Ve||(de.__webglTexture===void 0&&(de.__webglTexture=i.createTexture()),de.__version=K.version,s.memory.textures++),Ee){re.__webglFramebuffer=[];for(let De=0;De<6;De++)if(K.mipmaps&&K.mipmaps.length>0){re.__webglFramebuffer[De]=[];for(let Ue=0;Ue<K.mipmaps.length;Ue++)re.__webglFramebuffer[De][Ue]=i.createFramebuffer()}else re.__webglFramebuffer[De]=i.createFramebuffer()}else{if(K.mipmaps&&K.mipmaps.length>0){re.__webglFramebuffer=[];for(let De=0;De<K.mipmaps.length;De++)re.__webglFramebuffer[De]=i.createFramebuffer()}else re.__webglFramebuffer=i.createFramebuffer();if(Ve)for(let De=0,Ue=ye.length;De<Ue;De++){const Ye=n.get(ye[De]);Ye.__webglTexture===void 0&&(Ye.__webglTexture=i.createTexture(),s.memory.textures++)}if(Z.samples>0&&pe(Z)===!1){re.__webglMultisampledFramebuffer=i.createFramebuffer(),re.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,re.__webglMultisampledFramebuffer);for(let De=0;De<ye.length;De++){const Ue=ye[De];re.__webglColorRenderbuffer[De]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,re.__webglColorRenderbuffer[De]);const Ye=a.convert(Ue.format,Ue.colorSpace),Ie=a.convert(Ue.type),Oe=y(Ue.internalFormat,Ye,Ie,Ue.colorSpace,Z.isXRRenderTarget===!0),$e=he(Z);i.renderbufferStorageMultisample(i.RENDERBUFFER,$e,Oe,Z.width,Z.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+De,i.RENDERBUFFER,re.__webglColorRenderbuffer[De])}i.bindRenderbuffer(i.RENDERBUFFER,null),Z.depthBuffer&&(re.__webglDepthRenderbuffer=i.createRenderbuffer(),F(re.__webglDepthRenderbuffer,Z,!0)),t.bindFramebuffer(i.FRAMEBUFFER,null)}}if(Ee){t.bindTexture(i.TEXTURE_CUBE_MAP,de.__webglTexture),U(i.TEXTURE_CUBE_MAP,K);for(let De=0;De<6;De++)if(K.mipmaps&&K.mipmaps.length>0)for(let Ue=0;Ue<K.mipmaps.length;Ue++)B(re.__webglFramebuffer[De][Ue],Z,K,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+De,Ue);else B(re.__webglFramebuffer[De],Z,K,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+De,0);d(K)&&u(i.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(Ve){for(let De=0,Ue=ye.length;De<Ue;De++){const Ye=ye[De],Ie=n.get(Ye);t.bindTexture(i.TEXTURE_2D,Ie.__webglTexture),U(i.TEXTURE_2D,Ye),B(re.__webglFramebuffer,Z,Ye,i.COLOR_ATTACHMENT0+De,i.TEXTURE_2D,0),d(Ye)&&u(i.TEXTURE_2D)}t.unbindTexture()}else{let De=i.TEXTURE_2D;if((Z.isWebGL3DRenderTarget||Z.isWebGLArrayRenderTarget)&&(De=Z.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(De,de.__webglTexture),U(De,K),K.mipmaps&&K.mipmaps.length>0)for(let Ue=0;Ue<K.mipmaps.length;Ue++)B(re.__webglFramebuffer[Ue],Z,K,i.COLOR_ATTACHMENT0,De,Ue);else B(re.__webglFramebuffer,Z,K,i.COLOR_ATTACHMENT0,De,0);d(K)&&u(De),t.unbindTexture()}Z.depthBuffer&&q(Z)}function se(Z){const K=Z.textures;for(let re=0,de=K.length;re<de;re++){const ye=K[re];if(d(ye)){const Ee=b(Z),Ve=n.get(ye).__webglTexture;t.bindTexture(Ee,Ve),u(Ee),t.unbindTexture()}}}const ce=[],Y=[];function fe(Z){if(Z.samples>0){if(pe(Z)===!1){const K=Z.textures,re=Z.width,de=Z.height;let ye=i.COLOR_BUFFER_BIT;const Ee=Z.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Ve=n.get(Z),De=K.length>1;if(De)for(let Ue=0;Ue<K.length;Ue++)t.bindFramebuffer(i.FRAMEBUFFER,Ve.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.RENDERBUFFER,null),t.bindFramebuffer(i.FRAMEBUFFER,Ve.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.TEXTURE_2D,null,0);t.bindFramebuffer(i.READ_FRAMEBUFFER,Ve.__webglMultisampledFramebuffer),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Ve.__webglFramebuffer);for(let Ue=0;Ue<K.length;Ue++){if(Z.resolveDepthBuffer&&(Z.depthBuffer&&(ye|=i.DEPTH_BUFFER_BIT),Z.stencilBuffer&&Z.resolveStencilBuffer&&(ye|=i.STENCIL_BUFFER_BIT)),De){i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,Ve.__webglColorRenderbuffer[Ue]);const Ye=n.get(K[Ue]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,Ye,0)}i.blitFramebuffer(0,0,re,de,0,0,re,de,ye,i.NEAREST),c===!0&&(ce.length=0,Y.length=0,ce.push(i.COLOR_ATTACHMENT0+Ue),Z.depthBuffer&&Z.resolveDepthBuffer===!1&&(ce.push(Ee),Y.push(Ee),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,Y)),i.invalidateFramebuffer(i.READ_FRAMEBUFFER,ce))}if(t.bindFramebuffer(i.READ_FRAMEBUFFER,null),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),De)for(let Ue=0;Ue<K.length;Ue++){t.bindFramebuffer(i.FRAMEBUFFER,Ve.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.RENDERBUFFER,Ve.__webglColorRenderbuffer[Ue]);const Ye=n.get(K[Ue]).__webglTexture;t.bindFramebuffer(i.FRAMEBUFFER,Ve.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.TEXTURE_2D,Ye,0)}t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Ve.__webglMultisampledFramebuffer)}else if(Z.depthBuffer&&Z.resolveDepthBuffer===!1&&c){const K=Z.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[K])}}}function he(Z){return Math.min(r.maxSamples,Z.samples)}function pe(Z){const K=n.get(Z);return Z.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&K.__useRenderToTexture!==!1}function ue(Z){const K=s.render.frame;l.get(Z)!==K&&(l.set(Z,K),Z.update())}function Te(Z,K){const re=Z.colorSpace,de=Z.format,ye=Z.type;return Z.isCompressedTexture===!0||Z.isVideoTexture===!0||re!==Xr&&re!==Jn&&(Et.getTransfer(re)===Mt?(de!==tn||ye!==Cn)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",re)),K}function be(Z){return typeof HTMLImageElement<"u"&&Z instanceof HTMLImageElement?(h.width=Z.naturalWidth||Z.width,h.height=Z.naturalHeight||Z.height):typeof VideoFrame<"u"&&Z instanceof VideoFrame?(h.width=Z.displayWidth,h.height=Z.displayHeight):(h.width=Z.width,h.height=Z.height),h}this.allocateTextureUnit=M,this.resetTextureUnits=N,this.setTexture2D=L,this.setTexture2DArray=P,this.setTexture3D=x,this.setTextureCube=T,this.rebindTextures=X,this.setupRenderTarget=J,this.updateRenderTargetMipmap=se,this.updateMultisampleRenderTarget=fe,this.setupDepthRenderbuffer=q,this.setupFrameBufferTexture=B,this.useMultisampledRTT=pe}function Oy(i,e){function t(n,r=Jn){let a;const s=Et.getTransfer(r);if(n===Cn)return i.UNSIGNED_BYTE;if(n===yc)return i.UNSIGNED_SHORT_4_4_4_4;if(n===Ec)return i.UNSIGNED_SHORT_5_5_5_1;if(n===$h)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===jh)return i.BYTE;if(n===Xh)return i.SHORT;if(n===Io)return i.UNSIGNED_SHORT;if(n===bc)return i.INT;if(n===fr)return i.UNSIGNED_INT;if(n===wn)return i.FLOAT;if(n===Po)return i.HALF_FLOAT;if(n===Kh)return i.ALPHA;if(n===qh)return i.RGB;if(n===tn)return i.RGBA;if(n===Yh)return i.LUMINANCE;if(n===Jh)return i.LUMINANCE_ALPHA;if(n===Wr)return i.DEPTH_COMPONENT;if(n===jr)return i.DEPTH_STENCIL;if(n===Qh)return i.RED;if(n===Rc)return i.RED_INTEGER;if(n===Zh)return i.RG;if(n===Tc)return i.RG_INTEGER;if(n===Ac)return i.RGBA_INTEGER;if(n===_s||n===Ss||n===bs||n===ys)if(s===Mt)if(a=e.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(n===_s)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Ss)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===bs)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===ys)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=e.get("WEBGL_compressed_texture_s3tc"),a!==null){if(n===_s)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Ss)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===bs)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===ys)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Cc||n===wc||n===Mc||n===xc)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(n===Cc)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===wc)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Mc)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===xc)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===Ic||n===Pc||n===Dc)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(n===Ic||n===Pc)return s===Mt?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(n===Dc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===Lc||n===Oc||n===Nc||n===kc||n===Uc||n===Bc||n===Vc||n===Fc||n===Hc||n===Gc||n===zc||n===Wc||n===jc||n===Xc)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(n===Lc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Oc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===Nc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===kc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===Uc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===Bc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===Vc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===Fc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===Hc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===Gc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===zc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===Wc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===jc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Xc)return s===Mt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===Es||n===$c||n===Kc)if(a=e.get("EXT_texture_compression_bptc"),a!==null){if(n===Es)return s===Mt?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===$c)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Kc)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===ep||n===qc||n===Yc||n===Jc)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(n===Es)return a.COMPRESSED_RED_RGTC1_EXT;if(n===qc)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Yc)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Jc)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===zr?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}const Ny=`
void main() {

	gl_Position = vec4( position, 1.0 );

}`,ky=`
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;

void main() {

	vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );

	if ( coord.x >= 1.0 ) {

		gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;

	} else {

		gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;

	}

}`;class Uy{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,n){if(this.texture===null){const r=new ui,a=e.properties.get(r);a.__webglTexture=t.texture,(t.depthNear!==n.depthNear||t.depthFar!==n.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=r}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new kn({vertexShader:Ny,fragmentShader:ky,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new gn(new Ho(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class By extends Kr{constructor(e,t){super();const n=this;let r=null,a=1,s=null,o="local-floor",c=1,h=null,l=null,f=null,v=null,p=null,_=null;const m=new Uy,d=t.getContextAttributes();let u=null,b=null;const y=[],g=[],S=new xt;let R=null;const E=new an;E.viewport=new Ft;const I=new an;I.viewport=new Ft;const C=[E,I],A=new F0;let w=null,N=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(W){let $=y[W];return $===void 0&&($=new yl,y[W]=$),$.getTargetRaySpace()},this.getControllerGrip=function(W){let $=y[W];return $===void 0&&($=new yl,y[W]=$),$.getGripSpace()},this.getHand=function(W){let $=y[W];return $===void 0&&($=new yl,y[W]=$),$.getHandSpace()};function M(W){const $=g.indexOf(W.inputSource);if($===-1)return;const B=y[$];B!==void 0&&(B.update(W.inputSource,W.frame,h||s),B.dispatchEvent({type:W.type,data:W.inputSource}))}function D(){r.removeEventListener("select",M),r.removeEventListener("selectstart",M),r.removeEventListener("selectend",M),r.removeEventListener("squeeze",M),r.removeEventListener("squeezestart",M),r.removeEventListener("squeezeend",M),r.removeEventListener("end",D),r.removeEventListener("inputsourceschange",L);for(let W=0;W<y.length;W++){const $=g[W];$!==null&&(g[W]=null,y[W].disconnect($))}w=null,N=null,m.reset(),e.setRenderTarget(u),p=null,v=null,f=null,r=null,b=null,ee.stop(),n.isPresenting=!1,e.setPixelRatio(R),e.setSize(S.width,S.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(W){a=W,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(W){o=W,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return h||s},this.setReferenceSpace=function(W){h=W},this.getBaseLayer=function(){return v!==null?v:p},this.getBinding=function(){return f},this.getFrame=function(){return _},this.getSession=function(){return r},this.setSession=async function(W){if(r=W,r!==null){if(u=e.getRenderTarget(),r.addEventListener("select",M),r.addEventListener("selectstart",M),r.addEventListener("selectend",M),r.addEventListener("squeeze",M),r.addEventListener("squeezestart",M),r.addEventListener("squeezeend",M),r.addEventListener("end",D),r.addEventListener("inputsourceschange",L),d.xrCompatible!==!0&&await t.makeXRCompatible(),R=e.getPixelRatio(),e.getSize(S),typeof XRWebGLBinding<"u"&&"createProjectionLayer"in XRWebGLBinding.prototype){let B=null,F=null,G=null;d.depth&&(G=d.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,B=d.stencil?jr:Wr,F=d.stencil?zr:fr);const q={colorFormat:t.RGBA8,depthFormat:G,scaleFactor:a};f=new XRWebGLBinding(r,t),v=f.createProjectionLayer(q),r.updateRenderState({layers:[v]}),e.setPixelRatio(1),e.setSize(v.textureWidth,v.textureHeight,!1),b=new mr(v.textureWidth,v.textureHeight,{format:tn,type:Cn,depthTexture:new Op(v.textureWidth,v.textureHeight,F,void 0,void 0,void 0,void 0,void 0,void 0,B),stencilBuffer:d.stencil,colorSpace:e.outputColorSpace,samples:d.antialias?4:0,resolveDepthBuffer:v.ignoreDepthValues===!1})}else{const B={antialias:d.antialias,alpha:!0,depth:d.depth,stencil:d.stencil,framebufferScaleFactor:a};p=new XRWebGLLayer(r,t,B),r.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),b=new mr(p.framebufferWidth,p.framebufferHeight,{format:tn,type:Cn,colorSpace:e.outputColorSpace,stencilBuffer:d.stencil})}b.isXRRenderTarget=!0,this.setFoveation(c),h=null,s=await r.requestReferenceSpace(o),ee.setContext(r),ee.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function L(W){for(let $=0;$<W.removed.length;$++){const B=W.removed[$],F=g.indexOf(B);F>=0&&(g[F]=null,y[F].disconnect(B))}for(let $=0;$<W.added.length;$++){const B=W.added[$];let F=g.indexOf(B);if(F===-1){for(let q=0;q<y.length;q++)if(q>=g.length){g.push(B),F=q;break}else if(g[q]===null){g[q]=B,F=q;break}if(F===-1)break}const G=y[F];G&&G.connect(B)}}const P=new we,x=new we;function T(W,$,B){P.setFromMatrixPosition($.matrixWorld),x.setFromMatrixPosition(B.matrixWorld);const F=P.distanceTo(x),G=$.projectionMatrix.elements,q=B.projectionMatrix.elements,X=G[14]/(G[10]-1),J=G[14]/(G[10]+1),se=(G[9]+1)/G[5],ce=(G[9]-1)/G[5],Y=(G[8]-1)/G[0],fe=(q[8]+1)/q[0],he=X*Y,pe=X*fe,ue=F/(-Y+fe),Te=ue*-Y;if($.matrixWorld.decompose(W.position,W.quaternion,W.scale),W.translateX(Te),W.translateZ(ue),W.matrixWorld.compose(W.position,W.quaternion,W.scale),W.matrixWorldInverse.copy(W.matrixWorld).invert(),G[10]===-1)W.projectionMatrix.copy($.projectionMatrix),W.projectionMatrixInverse.copy($.projectionMatrixInverse);else{const be=X+ue,Z=J+ue,K=he-Te,re=pe+(F-Te),de=se*J/Z*be,ye=ce*J/Z*be;W.projectionMatrix.makePerspective(K,re,de,ye,be,Z),W.projectionMatrixInverse.copy(W.projectionMatrix).invert()}}function O(W,$){$===null?W.matrixWorld.copy(W.matrix):W.matrixWorld.multiplyMatrices($.matrixWorld,W.matrix),W.matrixWorldInverse.copy(W.matrixWorld).invert()}this.updateCamera=function(W){if(r===null)return;let $=W.near,B=W.far;m.texture!==null&&(m.depthNear>0&&($=m.depthNear),m.depthFar>0&&(B=m.depthFar)),A.near=I.near=E.near=$,A.far=I.far=E.far=B,(w!==A.near||N!==A.far)&&(r.updateRenderState({depthNear:A.near,depthFar:A.far}),w=A.near,N=A.far),E.layers.mask=W.layers.mask|2,I.layers.mask=W.layers.mask|4,A.layers.mask=E.layers.mask|I.layers.mask;const F=W.parent,G=A.cameras;O(A,F);for(let q=0;q<G.length;q++)O(G[q],F);G.length===2?T(A,E,I):A.projectionMatrix.copy(E.projectionMatrix),k(W,A,F)};function k(W,$,B){B===null?W.matrix.copy($.matrixWorld):(W.matrix.copy(B.matrixWorld),W.matrix.invert(),W.matrix.multiply($.matrixWorld)),W.matrix.decompose(W.position,W.quaternion,W.scale),W.updateMatrixWorld(!0),W.projectionMatrix.copy($.projectionMatrix),W.projectionMatrixInverse.copy($.projectionMatrixInverse),W.isPerspectiveCamera&&(W.fov=Zc*2*Math.atan(1/W.projectionMatrix.elements[5]),W.zoom=1)}this.getCamera=function(){return A},this.getFoveation=function(){if(!(v===null&&p===null))return c},this.setFoveation=function(W){c=W,v!==null&&(v.fixedFoveation=W),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=W)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(A)};let H=null;function U(W,$){if(l=$.getViewerPose(h||s),_=$,l!==null){const B=l.views;p!==null&&(e.setRenderTargetFramebuffer(b,p.framebuffer),e.setRenderTarget(b));let F=!1;B.length!==A.cameras.length&&(A.cameras.length=0,F=!0);for(let X=0;X<B.length;X++){const J=B[X];let se=null;if(p!==null)se=p.getViewport(J);else{const Y=f.getViewSubImage(v,J);se=Y.viewport,X===0&&(e.setRenderTargetTextures(b,Y.colorTexture,v.ignoreDepthValues?void 0:Y.depthStencilTexture),e.setRenderTarget(b))}let ce=C[X];ce===void 0&&(ce=new an,ce.layers.enable(X),ce.viewport=new Ft,C[X]=ce),ce.matrix.fromArray(J.transform.matrix),ce.matrix.decompose(ce.position,ce.quaternion,ce.scale),ce.projectionMatrix.fromArray(J.projectionMatrix),ce.projectionMatrixInverse.copy(ce.projectionMatrix).invert(),ce.viewport.set(se.x,se.y,se.width,se.height),X===0&&(A.matrix.copy(ce.matrix),A.matrix.decompose(A.position,A.quaternion,A.scale)),F===!0&&A.cameras.push(ce)}const G=r.enabledFeatures;if(G&&G.includes("depth-sensing")&&r.depthUsage=="gpu-optimized"&&f){const X=f.getDepthInformation(B[0]);X&&X.isValid&&X.texture&&m.init(e,X,r.renderState)}}for(let B=0;B<y.length;B++){const F=g[B],G=y[B];F!==null&&G!==void 0&&G.update(F,$,h||s)}H&&H(W,$),$.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:$}),_=null}const ee=new Up;ee.setAnimationLoop(U),this.setAnimationLoop=function(W){H=W},this.dispose=function(){}}}const Cr=new Dn,Vy=new jt;function Fy(i,e){function t(d,u){d.matrixAutoUpdate===!0&&d.updateMatrix(),u.value.copy(d.matrix)}function n(d,u){u.color.getRGB(d.fogColor.value,Mp(i)),u.isFog?(d.fogNear.value=u.near,d.fogFar.value=u.far):u.isFogExp2&&(d.fogDensity.value=u.density)}function r(d,u,b,y,g){u.isMeshBasicMaterial||u.isMeshLambertMaterial?a(d,u):u.isMeshToonMaterial?(a(d,u),f(d,u)):u.isMeshPhongMaterial?(a(d,u),l(d,u)):u.isMeshStandardMaterial?(a(d,u),v(d,u),u.isMeshPhysicalMaterial&&p(d,u,g)):u.isMeshMatcapMaterial?(a(d,u),_(d,u)):u.isMeshDepthMaterial?a(d,u):u.isMeshDistanceMaterial?(a(d,u),m(d,u)):u.isMeshNormalMaterial?a(d,u):u.isLineBasicMaterial?(s(d,u),u.isLineDashedMaterial&&o(d,u)):u.isPointsMaterial?c(d,u,b,y):u.isSpriteMaterial?h(d,u):u.isShadowMaterial?(d.color.value.copy(u.color),d.opacity.value=u.opacity):u.isShaderMaterial&&(u.uniformsNeedUpdate=!1)}function a(d,u){d.opacity.value=u.opacity,u.color&&d.diffuse.value.copy(u.color),u.emissive&&d.emissive.value.copy(u.emissive).multiplyScalar(u.emissiveIntensity),u.map&&(d.map.value=u.map,t(u.map,d.mapTransform)),u.alphaMap&&(d.alphaMap.value=u.alphaMap,t(u.alphaMap,d.alphaMapTransform)),u.bumpMap&&(d.bumpMap.value=u.bumpMap,t(u.bumpMap,d.bumpMapTransform),d.bumpScale.value=u.bumpScale,u.side===yi&&(d.bumpScale.value*=-1)),u.normalMap&&(d.normalMap.value=u.normalMap,t(u.normalMap,d.normalMapTransform),d.normalScale.value.copy(u.normalScale),u.side===yi&&d.normalScale.value.negate()),u.displacementMap&&(d.displacementMap.value=u.displacementMap,t(u.displacementMap,d.displacementMapTransform),d.displacementScale.value=u.displacementScale,d.displacementBias.value=u.displacementBias),u.emissiveMap&&(d.emissiveMap.value=u.emissiveMap,t(u.emissiveMap,d.emissiveMapTransform)),u.specularMap&&(d.specularMap.value=u.specularMap,t(u.specularMap,d.specularMapTransform)),u.alphaTest>0&&(d.alphaTest.value=u.alphaTest);const b=e.get(u),y=b.envMap,g=b.envMapRotation;y&&(d.envMap.value=y,Cr.copy(g),Cr.x*=-1,Cr.y*=-1,Cr.z*=-1,y.isCubeTexture&&y.isRenderTargetTexture===!1&&(Cr.y*=-1,Cr.z*=-1),d.envMapRotation.value.setFromMatrix4(Vy.makeRotationFromEuler(Cr)),d.flipEnvMap.value=y.isCubeTexture&&y.isRenderTargetTexture===!1?-1:1,d.reflectivity.value=u.reflectivity,d.ior.value=u.ior,d.refractionRatio.value=u.refractionRatio),u.lightMap&&(d.lightMap.value=u.lightMap,d.lightMapIntensity.value=u.lightMapIntensity,t(u.lightMap,d.lightMapTransform)),u.aoMap&&(d.aoMap.value=u.aoMap,d.aoMapIntensity.value=u.aoMapIntensity,t(u.aoMap,d.aoMapTransform))}function s(d,u){d.diffuse.value.copy(u.color),d.opacity.value=u.opacity,u.map&&(d.map.value=u.map,t(u.map,d.mapTransform))}function o(d,u){d.dashSize.value=u.dashSize,d.totalSize.value=u.dashSize+u.gapSize,d.scale.value=u.scale}function c(d,u,b,y){d.diffuse.value.copy(u.color),d.opacity.value=u.opacity,d.size.value=u.size*b,d.scale.value=y*.5,u.map&&(d.map.value=u.map,t(u.map,d.uvTransform)),u.alphaMap&&(d.alphaMap.value=u.alphaMap,t(u.alphaMap,d.alphaMapTransform)),u.alphaTest>0&&(d.alphaTest.value=u.alphaTest)}function h(d,u){d.diffuse.value.copy(u.color),d.opacity.value=u.opacity,d.rotation.value=u.rotation,u.map&&(d.map.value=u.map,t(u.map,d.mapTransform)),u.alphaMap&&(d.alphaMap.value=u.alphaMap,t(u.alphaMap,d.alphaMapTransform)),u.alphaTest>0&&(d.alphaTest.value=u.alphaTest)}function l(d,u){d.specular.value.copy(u.specular),d.shininess.value=Math.max(u.shininess,1e-4)}function f(d,u){u.gradientMap&&(d.gradientMap.value=u.gradientMap)}function v(d,u){d.metalness.value=u.metalness,u.metalnessMap&&(d.metalnessMap.value=u.metalnessMap,t(u.metalnessMap,d.metalnessMapTransform)),d.roughness.value=u.roughness,u.roughnessMap&&(d.roughnessMap.value=u.roughnessMap,t(u.roughnessMap,d.roughnessMapTransform)),u.envMap&&(d.envMapIntensity.value=u.envMapIntensity)}function p(d,u,b){d.ior.value=u.ior,u.sheen>0&&(d.sheenColor.value.copy(u.sheenColor).multiplyScalar(u.sheen),d.sheenRoughness.value=u.sheenRoughness,u.sheenColorMap&&(d.sheenColorMap.value=u.sheenColorMap,t(u.sheenColorMap,d.sheenColorMapTransform)),u.sheenRoughnessMap&&(d.sheenRoughnessMap.value=u.sheenRoughnessMap,t(u.sheenRoughnessMap,d.sheenRoughnessMapTransform))),u.clearcoat>0&&(d.clearcoat.value=u.clearcoat,d.clearcoatRoughness.value=u.clearcoatRoughness,u.clearcoatMap&&(d.clearcoatMap.value=u.clearcoatMap,t(u.clearcoatMap,d.clearcoatMapTransform)),u.clearcoatRoughnessMap&&(d.clearcoatRoughnessMap.value=u.clearcoatRoughnessMap,t(u.clearcoatRoughnessMap,d.clearcoatRoughnessMapTransform)),u.clearcoatNormalMap&&(d.clearcoatNormalMap.value=u.clearcoatNormalMap,t(u.clearcoatNormalMap,d.clearcoatNormalMapTransform),d.clearcoatNormalScale.value.copy(u.clearcoatNormalScale),u.side===yi&&d.clearcoatNormalScale.value.negate())),u.dispersion>0&&(d.dispersion.value=u.dispersion),u.iridescence>0&&(d.iridescence.value=u.iridescence,d.iridescenceIOR.value=u.iridescenceIOR,d.iridescenceThicknessMinimum.value=u.iridescenceThicknessRange[0],d.iridescenceThicknessMaximum.value=u.iridescenceThicknessRange[1],u.iridescenceMap&&(d.iridescenceMap.value=u.iridescenceMap,t(u.iridescenceMap,d.iridescenceMapTransform)),u.iridescenceThicknessMap&&(d.iridescenceThicknessMap.value=u.iridescenceThicknessMap,t(u.iridescenceThicknessMap,d.iridescenceThicknessMapTransform))),u.transmission>0&&(d.transmission.value=u.transmission,d.transmissionSamplerMap.value=b.texture,d.transmissionSamplerSize.value.set(b.width,b.height),u.transmissionMap&&(d.transmissionMap.value=u.transmissionMap,t(u.transmissionMap,d.transmissionMapTransform)),d.thickness.value=u.thickness,u.thicknessMap&&(d.thicknessMap.value=u.thicknessMap,t(u.thicknessMap,d.thicknessMapTransform)),d.attenuationDistance.value=u.attenuationDistance,d.attenuationColor.value.copy(u.attenuationColor)),u.anisotropy>0&&(d.anisotropyVector.value.set(u.anisotropy*Math.cos(u.anisotropyRotation),u.anisotropy*Math.sin(u.anisotropyRotation)),u.anisotropyMap&&(d.anisotropyMap.value=u.anisotropyMap,t(u.anisotropyMap,d.anisotropyMapTransform))),d.specularIntensity.value=u.specularIntensity,d.specularColor.value.copy(u.specularColor),u.specularColorMap&&(d.specularColorMap.value=u.specularColorMap,t(u.specularColorMap,d.specularColorMapTransform)),u.specularIntensityMap&&(d.specularIntensityMap.value=u.specularIntensityMap,t(u.specularIntensityMap,d.specularIntensityMapTransform))}function _(d,u){u.matcap&&(d.matcap.value=u.matcap)}function m(d,u){const b=e.get(u).light;d.referencePosition.value.setFromMatrixPosition(b.matrixWorld),d.nearDistance.value=b.shadow.camera.near,d.farDistance.value=b.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:r}}function Hy(i,e,t,n){let r={},a={},s=[];const o=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(b,y){const g=y.program;n.uniformBlockBinding(b,g)}function h(b,y){let g=r[b.id];g===void 0&&(_(b),g=l(b),r[b.id]=g,b.addEventListener("dispose",d));const S=y.program;n.updateUBOMapping(b,S);const R=e.render.frame;a[b.id]!==R&&(v(b),a[b.id]=R)}function l(b){const y=f();b.__bindingPointIndex=y;const g=i.createBuffer(),S=b.__size,R=b.usage;return i.bindBuffer(i.UNIFORM_BUFFER,g),i.bufferData(i.UNIFORM_BUFFER,S,R),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,y,g),g}function f(){for(let b=0;b<o;b++)if(s.indexOf(b)===-1)return s.push(b),b;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function v(b){const y=r[b.id],g=b.uniforms,S=b.__cache;i.bindBuffer(i.UNIFORM_BUFFER,y);for(let R=0,E=g.length;R<E;R++){const I=Array.isArray(g[R])?g[R]:[g[R]];for(let C=0,A=I.length;C<A;C++){const w=I[C];if(p(w,R,C,S)===!0){const N=w.__offset,M=Array.isArray(w.value)?w.value:[w.value];let D=0;for(let L=0;L<M.length;L++){const P=M[L],x=m(P);typeof P=="number"||typeof P=="boolean"?(w.__data[0]=P,i.bufferSubData(i.UNIFORM_BUFFER,N+D,w.__data)):P.isMatrix3?(w.__data[0]=P.elements[0],w.__data[1]=P.elements[1],w.__data[2]=P.elements[2],w.__data[3]=0,w.__data[4]=P.elements[3],w.__data[5]=P.elements[4],w.__data[6]=P.elements[5],w.__data[7]=0,w.__data[8]=P.elements[6],w.__data[9]=P.elements[7],w.__data[10]=P.elements[8],w.__data[11]=0):(P.toArray(w.__data,D),D+=x.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,N,w.__data)}}}i.bindBuffer(i.UNIFORM_BUFFER,null)}function p(b,y,g,S){const R=b.value,E=y+"_"+g;if(S[E]===void 0)return typeof R=="number"||typeof R=="boolean"?S[E]=R:S[E]=R.clone(),!0;{const I=S[E];if(typeof R=="number"||typeof R=="boolean"){if(I!==R)return S[E]=R,!0}else if(I.equals(R)===!1)return I.copy(R),!0}return!1}function _(b){const y=b.uniforms;let g=0;const S=16;for(let E=0,I=y.length;E<I;E++){const C=Array.isArray(y[E])?y[E]:[y[E]];for(let A=0,w=C.length;A<w;A++){const N=C[A],M=Array.isArray(N.value)?N.value:[N.value];for(let D=0,L=M.length;D<L;D++){const P=M[D],x=m(P),T=g%S,O=T%x.boundary,k=T+O;g+=O,k!==0&&S-k<x.storage&&(g+=S-k),N.__data=new Float32Array(x.storage/Float32Array.BYTES_PER_ELEMENT),N.__offset=g,g+=x.storage}}}const R=g%S;return R>0&&(g+=S-R),b.__size=g,b.__cache={},this}function m(b){const y={boundary:0,storage:0};return typeof b=="number"||typeof b=="boolean"?(y.boundary=4,y.storage=4):b.isVector2?(y.boundary=8,y.storage=8):b.isVector3||b.isColor?(y.boundary=16,y.storage=12):b.isVector4?(y.boundary=16,y.storage=16):b.isMatrix3?(y.boundary=48,y.storage=48):b.isMatrix4?(y.boundary=64,y.storage=64):b.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",b),y}function d(b){const y=b.target;y.removeEventListener("dispose",d);const g=s.indexOf(y.__bindingPointIndex);s.splice(g,1),i.deleteBuffer(r[y.id]),delete r[y.id],delete a[y.id]}function u(){for(const b in r)i.deleteBuffer(r[b]);s=[],r={},a={}}return{bind:c,update:h,dispose:u}}class Gy{constructor(e={}){const{canvas:t=o0(),context:n=null,depth:r=!0,stencil:a=!1,alpha:s=!1,antialias:o=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:h=!1,powerPreference:l="default",failIfMajorPerformanceCaveat:f=!1,reverseDepthBuffer:v=!1}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=n.getContextAttributes().alpha}else p=s;const _=new Uint32Array(4),m=new Int32Array(4);let d=null,u=null;const b=[],y=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=Wi,this.toneMapping=Yn,this.toneMappingExposure=1;const g=this;let S=!1,R=0,E=0,I=null,C=-1,A=null;const w=new Ft,N=new Ft;let M=null;const D=new It(0);let L=0,P=t.width,x=t.height,T=1,O=null,k=null;const H=new Ft(0,0,P,x),U=new Ft(0,0,P,x);let ee=!1;const W=new Lp;let $=!1,B=!1;this.transmissionResolutionScale=1;const F=new jt,G=new jt,q=new we,X=new Ft,J={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let se=!1;function ce(){return I===null?T:1}let Y=n;function fe(ie,me){return t.getContext(ie,me)}try{const ie={alpha:!0,depth:r,stencil:a,antialias:o,premultipliedAlpha:c,preserveDrawingBuffer:h,powerPreference:l,failIfMajorPerformanceCaveat:f};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${oc}`),t.addEventListener("webglcontextlost",ne,!1),t.addEventListener("webglcontextrestored",ae,!1),t.addEventListener("webglcontextcreationerror",oe,!1),Y===null){const me="webgl2";if(Y=fe(me,ie),Y===null)throw fe(me)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(ie){throw console.error("THREE.WebGLRenderer: "+ie.message),ie}let he,pe,ue,Te,be,Z,K,re,de,ye,Ee,Ve,De,Ue,Ye,Ie,Oe,$e,Ke,Fe,st,tt,z,j;function te(){he=new QS(Y),he.init(),tt=new Oy(Y,he),pe=new XS(Y,he,e,tt),ue=new Dy(Y,he),pe.reverseDepthBuffer&&v&&ue.buffers.depth.setReversed(!0),Te=new tb(Y),be=new Sy,Z=new Ly(Y,he,ue,be,pe,tt,Te),K=new KS(g),re=new JS(g),de=new G0(Y),z=new WS(Y,de),ye=new ZS(Y,de,Te,z),Ee=new nb(Y,ye,de,Te),Ke=new ib(Y,pe,Z),Ie=new $S(be),Ve=new _y(g,K,re,he,pe,z,Ie),De=new Fy(g,be),Ue=new yy,Ye=new wy(he),$e=new zS(g,K,re,ue,Ee,p,c),Oe=new Iy(g,Ee,pe),j=new Hy(Y,Te,pe,ue),Fe=new jS(Y,he,Te),st=new eb(Y,he,Te),Te.programs=Ve.programs,g.capabilities=pe,g.extensions=he,g.properties=be,g.renderLists=Ue,g.shadowMap=Oe,g.state=ue,g.info=Te}te();const Q=new By(g,Y);this.xr=Q,this.getContext=function(){return Y},this.getContextAttributes=function(){return Y.getContextAttributes()},this.forceContextLoss=function(){const ie=he.get("WEBGL_lose_context");ie&&ie.loseContext()},this.forceContextRestore=function(){const ie=he.get("WEBGL_lose_context");ie&&ie.restoreContext()},this.getPixelRatio=function(){return T},this.setPixelRatio=function(ie){ie!==void 0&&(T=ie,this.setSize(P,x,!1))},this.getSize=function(ie){return ie.set(P,x)},this.setSize=function(ie,me,Ae=!0){if(Q.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}P=ie,x=me,t.width=Math.floor(ie*T),t.height=Math.floor(me*T),Ae===!0&&(t.style.width=ie+"px",t.style.height=me+"px"),this.setViewport(0,0,ie,me)},this.getDrawingBufferSize=function(ie){return ie.set(P*T,x*T).floor()},this.setDrawingBufferSize=function(ie,me,Ae){P=ie,x=me,T=Ae,t.width=Math.floor(ie*Ae),t.height=Math.floor(me*Ae),this.setViewport(0,0,ie,me)},this.getCurrentViewport=function(ie){return ie.copy(w)},this.getViewport=function(ie){return ie.copy(H)},this.setViewport=function(ie,me,Ae,Ce){ie.isVector4?H.set(ie.x,ie.y,ie.z,ie.w):H.set(ie,me,Ae,Ce),ue.viewport(w.copy(H).multiplyScalar(T).round())},this.getScissor=function(ie){return ie.copy(U)},this.setScissor=function(ie,me,Ae,Ce){ie.isVector4?U.set(ie.x,ie.y,ie.z,ie.w):U.set(ie,me,Ae,Ce),ue.scissor(N.copy(U).multiplyScalar(T).round())},this.getScissorTest=function(){return ee},this.setScissorTest=function(ie){ue.setScissorTest(ee=ie)},this.setOpaqueSort=function(ie){O=ie},this.setTransparentSort=function(ie){k=ie},this.getClearColor=function(ie){return ie.copy($e.getClearColor())},this.setClearColor=function(){$e.setClearColor.apply($e,arguments)},this.getClearAlpha=function(){return $e.getClearAlpha()},this.setClearAlpha=function(){$e.setClearAlpha.apply($e,arguments)},this.clear=function(ie=!0,me=!0,Ae=!0){let Ce=0;if(ie){let ve=!1;if(I!==null){const Be=I.texture.format;ve=Be===Ac||Be===Tc||Be===Rc}if(ve){const Be=I.texture.type,Xe=Be===Cn||Be===fr||Be===Io||Be===zr||Be===yc||Be===Ec,Je=$e.getClearColor(),Qe=$e.getClearAlpha(),ct=Je.r,lt=Je.g,rt=Je.b;Xe?(_[0]=ct,_[1]=lt,_[2]=rt,_[3]=Qe,Y.clearBufferuiv(Y.COLOR,0,_)):(m[0]=ct,m[1]=lt,m[2]=rt,m[3]=Qe,Y.clearBufferiv(Y.COLOR,0,m))}else Ce|=Y.COLOR_BUFFER_BIT}me&&(Ce|=Y.DEPTH_BUFFER_BIT),Ae&&(Ce|=Y.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Y.clear(Ce)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",ne,!1),t.removeEventListener("webglcontextrestored",ae,!1),t.removeEventListener("webglcontextcreationerror",oe,!1),$e.dispose(),Ue.dispose(),Ye.dispose(),be.dispose(),K.dispose(),re.dispose(),Ee.dispose(),z.dispose(),j.dispose(),Ve.dispose(),Q.dispose(),Q.removeEventListener("sessionstart",pi),Q.removeEventListener("sessionend",Js),wr.stop()};function ne(ie){ie.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),S=!0}function ae(){console.log("THREE.WebGLRenderer: Context Restored."),S=!1;const ie=Te.autoReset,me=Oe.enabled,Ae=Oe.autoUpdate,Ce=Oe.needsUpdate,ve=Oe.type;te(),Te.autoReset=ie,Oe.enabled=me,Oe.autoUpdate=Ae,Oe.needsUpdate=Ce,Oe.type=ve}function oe(ie){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",ie.statusMessage)}function Se(ie){const me=ie.target;me.removeEventListener("dispose",Se),_e(me)}function _e(ie){xe(ie),be.remove(ie)}function xe(ie){const me=be.get(ie).programs;me!==void 0&&(me.forEach(function(Ae){Ve.releaseProgram(Ae)}),ie.isShaderMaterial&&Ve.releaseShaderCache(ie))}this.renderBufferDirect=function(ie,me,Ae,Ce,ve,Be){me===null&&(me=J);const Xe=ve.isMesh&&ve.matrixWorld.determinant()<0,Je=qy(ie,me,Ae,Ce,ve);ue.setMaterial(Ce,Xe);let Qe=Ae.index,ct=1;if(Ce.wireframe===!0){if(Qe=ye.getWireframeAttribute(Ae),Qe===void 0)return;ct=2}const lt=Ae.drawRange,rt=Ae.attributes.position;let bt=lt.start*ct,Tt=(lt.start+lt.count)*ct;Be!==null&&(bt=Math.max(bt,Be.start*ct),Tt=Math.min(Tt,(Be.start+Be.count)*ct)),Qe!==null?(bt=Math.max(bt,0),Tt=Math.min(Tt,Qe.count)):rt!=null&&(bt=Math.max(bt,0),Tt=Math.min(Tt,rt.count));const $t=Tt-bt;if($t<0||$t===1/0)return;z.setup(ve,Ce,Je,Ae,Qe);let Vt,Rt=Fe;if(Qe!==null&&(Vt=de.get(Qe),Rt=st,Rt.setIndex(Vt)),ve.isMesh)Ce.wireframe===!0?(ue.setLineWidth(Ce.wireframeLinewidth*ce()),Rt.setMode(Y.LINES)):Rt.setMode(Y.TRIANGLES);else if(ve.isLine){let ot=Ce.linewidth;ot===void 0&&(ot=1),ue.setLineWidth(ot*ce()),ve.isLineSegments?Rt.setMode(Y.LINES):ve.isLineLoop?Rt.setMode(Y.LINE_LOOP):Rt.setMode(Y.LINE_STRIP)}else ve.isPoints?Rt.setMode(Y.POINTS):ve.isSprite&&Rt.setMode(Y.TRIANGLES);if(ve.isBatchedMesh)if(ve._multiDrawInstances!==null)Rt.renderMultiDrawInstances(ve._multiDrawStarts,ve._multiDrawCounts,ve._multiDrawCount,ve._multiDrawInstances);else if(he.get("WEBGL_multi_draw"))Rt.renderMultiDraw(ve._multiDrawStarts,ve._multiDrawCounts,ve._multiDrawCount);else{const ot=ve._multiDrawStarts,ni=ve._multiDrawCounts,At=ve._multiDrawCount,cn=Qe?de.get(Qe).bytesPerElement:1,fo=be.get(Ce).currentProgram.getUniforms();for(let Ni=0;Ni<At;Ni++)fo.setValue(Y,"_gl_DrawID",Ni),Rt.render(ot[Ni]/cn,ni[Ni])}else if(ve.isInstancedMesh)Rt.renderInstances(bt,$t,ve.count);else if(Ae.isInstancedBufferGeometry){const ot=Ae._maxInstanceCount!==void 0?Ae._maxInstanceCount:1/0,ni=Math.min(Ae.instanceCount,ot);Rt.renderInstances(bt,$t,ni)}else Rt.render(bt,$t)};function Pe(ie,me,Ae){ie.transparent===!0&&ie.side===Tn&&ie.forceSinglePass===!1?(ie.side=yi,ie.needsUpdate=!0,Zs(ie,me,Ae),ie.side=Kn,ie.needsUpdate=!0,Zs(ie,me,Ae),ie.side=Tn):Zs(ie,me,Ae)}this.compile=function(ie,me,Ae=null){Ae===null&&(Ae=ie),u=Ye.get(Ae),u.init(me),y.push(u),Ae.traverseVisible(function(ve){ve.isLight&&ve.layers.test(me.layers)&&(u.pushLight(ve),ve.castShadow&&u.pushShadow(ve))}),ie!==Ae&&ie.traverseVisible(function(ve){ve.isLight&&ve.layers.test(me.layers)&&(u.pushLight(ve),ve.castShadow&&u.pushShadow(ve))}),u.setupLights();const Ce=new Set;return ie.traverse(function(ve){if(!(ve.isMesh||ve.isPoints||ve.isLine||ve.isSprite))return;const Be=ve.material;if(Be)if(Array.isArray(Be))for(let Xe=0;Xe<Be.length;Xe++){const Je=Be[Xe];Pe(Je,Ae,ve),Ce.add(Je)}else Pe(Be,Ae,ve),Ce.add(Be)}),y.pop(),u=null,Ce},this.compileAsync=function(ie,me,Ae=null){const Ce=this.compile(ie,me,Ae);return new Promise(ve=>{function Be(){if(Ce.forEach(function(Xe){be.get(Xe).currentProgram.isReady()&&Ce.delete(Xe)}),Ce.size===0){ve(ie);return}setTimeout(Be,10)}he.get("KHR_parallel_shader_compile")!==null?Be():setTimeout(Be,10)})};let He=null;function it(ie){He&&He(ie)}function pi(){wr.stop()}function Js(){wr.start()}const wr=new Up;wr.setAnimationLoop(it),typeof self<"u"&&wr.setContext(self),this.setAnimationLoop=function(ie){He=ie,Q.setAnimationLoop(ie),ie===null?wr.stop():wr.start()},Q.addEventListener("sessionstart",pi),Q.addEventListener("sessionend",Js),this.render=function(ie,me){if(me!==void 0&&me.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(S===!0)return;if(ie.matrixWorldAutoUpdate===!0&&ie.updateMatrixWorld(),me.parent===null&&me.matrixWorldAutoUpdate===!0&&me.updateMatrixWorld(),Q.enabled===!0&&Q.isPresenting===!0&&(Q.cameraAutoUpdate===!0&&Q.updateCamera(me),me=Q.getCamera()),ie.isScene===!0&&ie.onBeforeRender(g,ie,me,I),u=Ye.get(ie,y.length),u.init(me),y.push(u),G.multiplyMatrices(me.projectionMatrix,me.matrixWorldInverse),W.setFromProjectionMatrix(G),B=this.localClippingEnabled,$=Ie.init(this.clippingPlanes,B),d=Ue.get(ie,b.length),d.init(),b.push(d),Q.enabled===!0&&Q.isPresenting===!0){const Be=g.xr.getDepthSensingMesh();Be!==null&&Pl(Be,me,-1/0,g.sortObjects)}Pl(ie,me,0,g.sortObjects),d.finish(),g.sortObjects===!0&&d.sort(O,k),se=Q.enabled===!1||Q.isPresenting===!1||Q.hasDepthSensing()===!1,se&&$e.addToRenderList(d,ie),this.info.render.frame++,$===!0&&Ie.beginShadows();const Ae=u.state.shadowsArray;Oe.render(Ae,ie,me),$===!0&&Ie.endShadows(),this.info.autoReset===!0&&this.info.reset();const Ce=d.opaque,ve=d.transmissive;if(u.setupLights(),me.isArrayCamera){const Be=me.cameras;if(ve.length>0)for(let Xe=0,Je=Be.length;Xe<Je;Xe++){const Qe=Be[Xe];ff(Ce,ve,ie,Qe)}se&&$e.render(ie);for(let Xe=0,Je=Be.length;Xe<Je;Xe++){const Qe=Be[Xe];pf(d,ie,Qe,Qe.viewport)}}else ve.length>0&&ff(Ce,ve,ie,me),se&&$e.render(ie),pf(d,ie,me);I!==null&&E===0&&(Z.updateMultisampleRenderTarget(I),Z.updateRenderTargetMipmap(I)),ie.isScene===!0&&ie.onAfterRender(g,ie,me),z.resetDefaultState(),C=-1,A=null,y.pop(),y.length>0?(u=y[y.length-1],$===!0&&Ie.setGlobalState(g.clippingPlanes,u.state.camera)):u=null,b.pop(),b.length>0?d=b[b.length-1]:d=null};function Pl(ie,me,Ae,Ce){if(ie.visible===!1)return;if(ie.layers.test(me.layers)){if(ie.isGroup)Ae=ie.renderOrder;else if(ie.isLOD)ie.autoUpdate===!0&&ie.update(me);else if(ie.isLight)u.pushLight(ie),ie.castShadow&&u.pushShadow(ie);else if(ie.isSprite){if(!ie.frustumCulled||W.intersectsSprite(ie)){Ce&&X.setFromMatrixPosition(ie.matrixWorld).applyMatrix4(G);const Xe=Ee.update(ie),Je=ie.material;Je.visible&&d.push(ie,Xe,Je,Ae,X.z,null)}}else if((ie.isMesh||ie.isLine||ie.isPoints)&&(!ie.frustumCulled||W.intersectsObject(ie))){const Xe=Ee.update(ie),Je=ie.material;if(Ce&&(ie.boundingSphere!==void 0?(ie.boundingSphere===null&&ie.computeBoundingSphere(),X.copy(ie.boundingSphere.center)):(Xe.boundingSphere===null&&Xe.computeBoundingSphere(),X.copy(Xe.boundingSphere.center)),X.applyMatrix4(ie.matrixWorld).applyMatrix4(G)),Array.isArray(Je)){const Qe=Xe.groups;for(let ct=0,lt=Qe.length;ct<lt;ct++){const rt=Qe[ct],bt=Je[rt.materialIndex];bt&&bt.visible&&d.push(ie,Xe,bt,Ae,X.z,rt)}}else Je.visible&&d.push(ie,Xe,Je,Ae,X.z,null)}}const Be=ie.children;for(let Xe=0,Je=Be.length;Xe<Je;Xe++)Pl(Be[Xe],me,Ae,Ce)}function pf(ie,me,Ae,Ce){const ve=ie.opaque,Be=ie.transmissive,Xe=ie.transparent;u.setupLightsView(Ae),$===!0&&Ie.setGlobalState(g.clippingPlanes,Ae),Ce&&ue.viewport(w.copy(Ce)),ve.length>0&&Qs(ve,me,Ae),Be.length>0&&Qs(Be,me,Ae),Xe.length>0&&Qs(Xe,me,Ae),ue.buffers.depth.setTest(!0),ue.buffers.depth.setMask(!0),ue.buffers.color.setMask(!0),ue.setPolygonOffset(!1)}function ff(ie,me,Ae,Ce){if((Ae.isScene===!0?Ae.overrideMaterial:null)!==null)return;u.state.transmissionRenderTarget[Ce.id]===void 0&&(u.state.transmissionRenderTarget[Ce.id]=new mr(1,1,{generateMipmaps:!0,type:he.has("EXT_color_buffer_half_float")||he.has("EXT_color_buffer_float")?Po:Cn,minFilter:pr,samples:4,stencilBuffer:a,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Et.workingColorSpace}));const Be=u.state.transmissionRenderTarget[Ce.id],Xe=Ce.viewport||w;Be.setSize(Xe.z*g.transmissionResolutionScale,Xe.w*g.transmissionResolutionScale);const Je=g.getRenderTarget();g.setRenderTarget(Be),g.getClearColor(D),L=g.getClearAlpha(),L<1&&g.setClearColor(16777215,.5),g.clear(),se&&$e.render(Ae);const Qe=g.toneMapping;g.toneMapping=Yn;const ct=Ce.viewport;if(Ce.viewport!==void 0&&(Ce.viewport=void 0),u.setupLightsView(Ce),$===!0&&Ie.setGlobalState(g.clippingPlanes,Ce),Qs(ie,Ae,Ce),Z.updateMultisampleRenderTarget(Be),Z.updateRenderTargetMipmap(Be),he.has("WEBGL_multisampled_render_to_texture")===!1){let lt=!1;for(let rt=0,bt=me.length;rt<bt;rt++){const Tt=me[rt],$t=Tt.object,Vt=Tt.geometry,Rt=Tt.material,ot=Tt.group;if(Rt.side===Tn&&$t.layers.test(Ce.layers)){const ni=Rt.side;Rt.side=yi,Rt.needsUpdate=!0,mf($t,Ae,Ce,Vt,Rt,ot),Rt.side=ni,Rt.needsUpdate=!0,lt=!0}}lt===!0&&(Z.updateMultisampleRenderTarget(Be),Z.updateRenderTargetMipmap(Be))}g.setRenderTarget(Je),g.setClearColor(D,L),ct!==void 0&&(Ce.viewport=ct),g.toneMapping=Qe}function Qs(ie,me,Ae){const Ce=me.isScene===!0?me.overrideMaterial:null;for(let ve=0,Be=ie.length;ve<Be;ve++){const Xe=ie[ve],Je=Xe.object,Qe=Xe.geometry,ct=Ce===null?Xe.material:Ce,lt=Xe.group;Je.layers.test(Ae.layers)&&mf(Je,me,Ae,Qe,ct,lt)}}function mf(ie,me,Ae,Ce,ve,Be){ie.onBeforeRender(g,me,Ae,Ce,ve,Be),ie.modelViewMatrix.multiplyMatrices(Ae.matrixWorldInverse,ie.matrixWorld),ie.normalMatrix.getNormalMatrix(ie.modelViewMatrix),ve.onBeforeRender(g,me,Ae,Ce,ie,Be),ve.transparent===!0&&ve.side===Tn&&ve.forceSinglePass===!1?(ve.side=yi,ve.needsUpdate=!0,g.renderBufferDirect(Ae,me,Ce,ve,ie,Be),ve.side=Kn,ve.needsUpdate=!0,g.renderBufferDirect(Ae,me,Ce,ve,ie,Be),ve.side=Tn):g.renderBufferDirect(Ae,me,Ce,ve,ie,Be),ie.onAfterRender(g,me,Ae,Ce,ve,Be)}function Zs(ie,me,Ae){me.isScene!==!0&&(me=J);const Ce=be.get(ie),ve=u.state.lights,Be=u.state.shadowsArray,Xe=ve.state.version,Je=Ve.getParameters(ie,ve.state,Be,me,Ae),Qe=Ve.getProgramCacheKey(Je);let ct=Ce.programs;Ce.environment=ie.isMeshStandardMaterial?me.environment:null,Ce.fog=me.fog,Ce.envMap=(ie.isMeshStandardMaterial?re:K).get(ie.envMap||Ce.environment),Ce.envMapRotation=Ce.environment!==null&&ie.envMap===null?me.environmentRotation:ie.envMapRotation,ct===void 0&&(ie.addEventListener("dispose",Se),ct=new Map,Ce.programs=ct);let lt=ct.get(Qe);if(lt!==void 0){if(Ce.currentProgram===lt&&Ce.lightsStateVersion===Xe)return vf(ie,Je),lt}else Je.uniforms=Ve.getUniforms(ie),ie.onBeforeCompile(Je,g),lt=Ve.acquireProgram(Je,Qe),ct.set(Qe,lt),Ce.uniforms=Je.uniforms;const rt=Ce.uniforms;return(!ie.isShaderMaterial&&!ie.isRawShaderMaterial||ie.clipping===!0)&&(rt.clippingPlanes=Ie.uniform),vf(ie,Je),Ce.needsLights=Jy(ie),Ce.lightsStateVersion=Xe,Ce.needsLights&&(rt.ambientLightColor.value=ve.state.ambient,rt.lightProbe.value=ve.state.probe,rt.directionalLights.value=ve.state.directional,rt.directionalLightShadows.value=ve.state.directionalShadow,rt.spotLights.value=ve.state.spot,rt.spotLightShadows.value=ve.state.spotShadow,rt.rectAreaLights.value=ve.state.rectArea,rt.ltc_1.value=ve.state.rectAreaLTC1,rt.ltc_2.value=ve.state.rectAreaLTC2,rt.pointLights.value=ve.state.point,rt.pointLightShadows.value=ve.state.pointShadow,rt.hemisphereLights.value=ve.state.hemi,rt.directionalShadowMap.value=ve.state.directionalShadowMap,rt.directionalShadowMatrix.value=ve.state.directionalShadowMatrix,rt.spotShadowMap.value=ve.state.spotShadowMap,rt.spotLightMatrix.value=ve.state.spotLightMatrix,rt.spotLightMap.value=ve.state.spotLightMap,rt.pointShadowMap.value=ve.state.pointShadowMap,rt.pointShadowMatrix.value=ve.state.pointShadowMatrix),Ce.currentProgram=lt,Ce.uniformsList=null,lt}function gf(ie){if(ie.uniformsList===null){const me=ie.currentProgram.getUniforms();ie.uniformsList=Ks.seqWithValue(me.seq,ie.uniforms)}return ie.uniformsList}function vf(ie,me){const Ae=be.get(ie);Ae.outputColorSpace=me.outputColorSpace,Ae.batching=me.batching,Ae.batchingColor=me.batchingColor,Ae.instancing=me.instancing,Ae.instancingColor=me.instancingColor,Ae.instancingMorph=me.instancingMorph,Ae.skinning=me.skinning,Ae.morphTargets=me.morphTargets,Ae.morphNormals=me.morphNormals,Ae.morphColors=me.morphColors,Ae.morphTargetsCount=me.morphTargetsCount,Ae.numClippingPlanes=me.numClippingPlanes,Ae.numIntersection=me.numClipIntersection,Ae.vertexAlphas=me.vertexAlphas,Ae.vertexTangents=me.vertexTangents,Ae.toneMapping=me.toneMapping}function qy(ie,me,Ae,Ce,ve){me.isScene!==!0&&(me=J),Z.resetTextureUnits();const Be=me.fog,Xe=Ce.isMeshStandardMaterial?me.environment:null,Je=I===null?g.outputColorSpace:I.isXRRenderTarget===!0?I.texture.colorSpace:Xr,Qe=(Ce.isMeshStandardMaterial?re:K).get(Ce.envMap||Xe),ct=Ce.vertexColors===!0&&!!Ae.attributes.color&&Ae.attributes.color.itemSize===4,lt=!!Ae.attributes.tangent&&(!!Ce.normalMap||Ce.anisotropy>0),rt=!!Ae.morphAttributes.position,bt=!!Ae.morphAttributes.normal,Tt=!!Ae.morphAttributes.color;let $t=Yn;Ce.toneMapped&&(I===null||I.isXRRenderTarget===!0)&&($t=g.toneMapping);const Vt=Ae.morphAttributes.position||Ae.morphAttributes.normal||Ae.morphAttributes.color,Rt=Vt!==void 0?Vt.length:0,ot=be.get(Ce),ni=u.state.lights;if($===!0&&(B===!0||ie!==A)){const fi=ie===A&&Ce.id===C;Ie.setState(Ce,ie,fi)}let At=!1;Ce.version===ot.__version?(ot.needsLights&&ot.lightsStateVersion!==ni.state.version||ot.outputColorSpace!==Je||ve.isBatchedMesh&&ot.batching===!1||!ve.isBatchedMesh&&ot.batching===!0||ve.isBatchedMesh&&ot.batchingColor===!0&&ve.colorTexture===null||ve.isBatchedMesh&&ot.batchingColor===!1&&ve.colorTexture!==null||ve.isInstancedMesh&&ot.instancing===!1||!ve.isInstancedMesh&&ot.instancing===!0||ve.isSkinnedMesh&&ot.skinning===!1||!ve.isSkinnedMesh&&ot.skinning===!0||ve.isInstancedMesh&&ot.instancingColor===!0&&ve.instanceColor===null||ve.isInstancedMesh&&ot.instancingColor===!1&&ve.instanceColor!==null||ve.isInstancedMesh&&ot.instancingMorph===!0&&ve.morphTexture===null||ve.isInstancedMesh&&ot.instancingMorph===!1&&ve.morphTexture!==null||ot.envMap!==Qe||Ce.fog===!0&&ot.fog!==Be||ot.numClippingPlanes!==void 0&&(ot.numClippingPlanes!==Ie.numPlanes||ot.numIntersection!==Ie.numIntersection)||ot.vertexAlphas!==ct||ot.vertexTangents!==lt||ot.morphTargets!==rt||ot.morphNormals!==bt||ot.morphColors!==Tt||ot.toneMapping!==$t||ot.morphTargetsCount!==Rt)&&(At=!0):(At=!0,ot.__version=Ce.version);let cn=ot.currentProgram;At===!0&&(cn=Zs(Ce,me,ve));let fo=!1,Ni=!1,zo=!1;const Ut=cn.getUniforms(),Xi=ot.uniforms;if(ue.useProgram(cn.program)&&(fo=!0,Ni=!0,zo=!0),Ce.id!==C&&(C=Ce.id,Ni=!0),fo||A!==ie){ue.buffers.depth.getReversed()?(F.copy(ie.projectionMatrix),a0(F),c0(F),Ut.setValue(Y,"projectionMatrix",F)):Ut.setValue(Y,"projectionMatrix",ie.projectionMatrix),Ut.setValue(Y,"viewMatrix",ie.matrixWorldInverse);const Ti=Ut.map.cameraPosition;Ti!==void 0&&Ti.setValue(Y,q.setFromMatrixPosition(ie.matrixWorld)),pe.logarithmicDepthBuffer&&Ut.setValue(Y,"logDepthBufFC",2/(Math.log(ie.far+1)/Math.LN2)),(Ce.isMeshPhongMaterial||Ce.isMeshToonMaterial||Ce.isMeshLambertMaterial||Ce.isMeshBasicMaterial||Ce.isMeshStandardMaterial||Ce.isShaderMaterial)&&Ut.setValue(Y,"isOrthographic",ie.isOrthographicCamera===!0),A!==ie&&(A=ie,Ni=!0,zo=!0)}if(ve.isSkinnedMesh){Ut.setOptional(Y,ve,"bindMatrix"),Ut.setOptional(Y,ve,"bindMatrixInverse");const fi=ve.skeleton;fi&&(fi.boneTexture===null&&fi.computeBoneTexture(),Ut.setValue(Y,"boneTexture",fi.boneTexture,Z))}ve.isBatchedMesh&&(Ut.setOptional(Y,ve,"batchingTexture"),Ut.setValue(Y,"batchingTexture",ve._matricesTexture,Z),Ut.setOptional(Y,ve,"batchingIdTexture"),Ut.setValue(Y,"batchingIdTexture",ve._indirectTexture,Z),Ut.setOptional(Y,ve,"batchingColorTexture"),ve._colorsTexture!==null&&Ut.setValue(Y,"batchingColorTexture",ve._colorsTexture,Z));const $i=Ae.morphAttributes;if(($i.position!==void 0||$i.normal!==void 0||$i.color!==void 0)&&Ke.update(ve,Ae,cn),(Ni||ot.receiveShadow!==ve.receiveShadow)&&(ot.receiveShadow=ve.receiveShadow,Ut.setValue(Y,"receiveShadow",ve.receiveShadow)),Ce.isMeshGouraudMaterial&&Ce.envMap!==null&&(Xi.envMap.value=Qe,Xi.flipEnvMap.value=Qe.isCubeTexture&&Qe.isRenderTargetTexture===!1?-1:1),Ce.isMeshStandardMaterial&&Ce.envMap===null&&me.environment!==null&&(Xi.envMapIntensity.value=me.environmentIntensity),Ni&&(Ut.setValue(Y,"toneMappingExposure",g.toneMappingExposure),ot.needsLights&&Yy(Xi,zo),Be&&Ce.fog===!0&&De.refreshFogUniforms(Xi,Be),De.refreshMaterialUniforms(Xi,Ce,T,x,u.state.transmissionRenderTarget[ie.id]),Ks.upload(Y,gf(ot),Xi,Z)),Ce.isShaderMaterial&&Ce.uniformsNeedUpdate===!0&&(Ks.upload(Y,gf(ot),Xi,Z),Ce.uniformsNeedUpdate=!1),Ce.isSpriteMaterial&&Ut.setValue(Y,"center",ve.center),Ut.setValue(Y,"modelViewMatrix",ve.modelViewMatrix),Ut.setValue(Y,"normalMatrix",ve.normalMatrix),Ut.setValue(Y,"modelMatrix",ve.matrixWorld),Ce.isShaderMaterial||Ce.isRawShaderMaterial){const fi=Ce.uniformsGroups;for(let Ti=0,Dl=fi.length;Ti<Dl;Ti++){const Mr=fi[Ti];j.update(Mr,cn),j.bind(Mr,cn)}}return cn}function Yy(ie,me){ie.ambientLightColor.needsUpdate=me,ie.lightProbe.needsUpdate=me,ie.directionalLights.needsUpdate=me,ie.directionalLightShadows.needsUpdate=me,ie.pointLights.needsUpdate=me,ie.pointLightShadows.needsUpdate=me,ie.spotLights.needsUpdate=me,ie.spotLightShadows.needsUpdate=me,ie.rectAreaLights.needsUpdate=me,ie.hemisphereLights.needsUpdate=me}function Jy(ie){return ie.isMeshLambertMaterial||ie.isMeshToonMaterial||ie.isMeshPhongMaterial||ie.isMeshStandardMaterial||ie.isShadowMaterial||ie.isShaderMaterial&&ie.lights===!0}this.getActiveCubeFace=function(){return R},this.getActiveMipmapLevel=function(){return E},this.getRenderTarget=function(){return I},this.setRenderTargetTextures=function(ie,me,Ae){be.get(ie.texture).__webglTexture=me,be.get(ie.depthTexture).__webglTexture=Ae;const Ce=be.get(ie);Ce.__hasExternalTextures=!0,Ce.__autoAllocateDepthBuffer=Ae===void 0,Ce.__autoAllocateDepthBuffer||he.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),Ce.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(ie,me){const Ae=be.get(ie);Ae.__webglFramebuffer=me,Ae.__useDefaultFramebuffer=me===void 0};const Qy=Y.createFramebuffer();this.setRenderTarget=function(ie,me=0,Ae=0){I=ie,R=me,E=Ae;let Ce=!0,ve=null,Be=!1,Xe=!1;if(ie){const Qe=be.get(ie);if(Qe.__useDefaultFramebuffer!==void 0)ue.bindFramebuffer(Y.FRAMEBUFFER,null),Ce=!1;else if(Qe.__webglFramebuffer===void 0)Z.setupRenderTarget(ie);else if(Qe.__hasExternalTextures)Z.rebindTextures(ie,be.get(ie.texture).__webglTexture,be.get(ie.depthTexture).__webglTexture);else if(ie.depthBuffer){const rt=ie.depthTexture;if(Qe.__boundDepthTexture!==rt){if(rt!==null&&be.has(rt)&&(ie.width!==rt.image.width||ie.height!==rt.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");Z.setupDepthRenderbuffer(ie)}}const ct=ie.texture;(ct.isData3DTexture||ct.isDataArrayTexture||ct.isCompressedArrayTexture)&&(Xe=!0);const lt=be.get(ie).__webglFramebuffer;ie.isWebGLCubeRenderTarget?(Array.isArray(lt[me])?ve=lt[me][Ae]:ve=lt[me],Be=!0):ie.samples>0&&Z.useMultisampledRTT(ie)===!1?ve=be.get(ie).__webglMultisampledFramebuffer:Array.isArray(lt)?ve=lt[Ae]:ve=lt,w.copy(ie.viewport),N.copy(ie.scissor),M=ie.scissorTest}else w.copy(H).multiplyScalar(T).floor(),N.copy(U).multiplyScalar(T).floor(),M=ee;if(Ae!==0&&(ve=Qy),ue.bindFramebuffer(Y.FRAMEBUFFER,ve)&&Ce&&ue.drawBuffers(ie,ve),ue.viewport(w),ue.scissor(N),ue.setScissorTest(M),Be){const Qe=be.get(ie.texture);Y.framebufferTexture2D(Y.FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Y.TEXTURE_CUBE_MAP_POSITIVE_X+me,Qe.__webglTexture,Ae)}else if(Xe){const Qe=be.get(ie.texture),ct=me;Y.framebufferTextureLayer(Y.FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Qe.__webglTexture,Ae,ct)}else if(ie!==null&&Ae!==0){const Qe=be.get(ie.texture);Y.framebufferTexture2D(Y.FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Y.TEXTURE_2D,Qe.__webglTexture,Ae)}C=-1},this.readRenderTargetPixels=function(ie,me,Ae,Ce,ve,Be,Xe){if(!(ie&&ie.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Je=be.get(ie).__webglFramebuffer;if(ie.isWebGLCubeRenderTarget&&Xe!==void 0&&(Je=Je[Xe]),Je){ue.bindFramebuffer(Y.FRAMEBUFFER,Je);try{const Qe=ie.texture,ct=Qe.format,lt=Qe.type;if(!pe.textureFormatReadable(ct)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!pe.textureTypeReadable(lt)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}me>=0&&me<=ie.width-Ce&&Ae>=0&&Ae<=ie.height-ve&&Y.readPixels(me,Ae,Ce,ve,tt.convert(ct),tt.convert(lt),Be)}finally{const Qe=I!==null?be.get(I).__webglFramebuffer:null;ue.bindFramebuffer(Y.FRAMEBUFFER,Qe)}}},this.readRenderTargetPixelsAsync=async function(ie,me,Ae,Ce,ve,Be,Xe){if(!(ie&&ie.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Je=be.get(ie).__webglFramebuffer;if(ie.isWebGLCubeRenderTarget&&Xe!==void 0&&(Je=Je[Xe]),Je){const Qe=ie.texture,ct=Qe.format,lt=Qe.type;if(!pe.textureFormatReadable(ct))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!pe.textureTypeReadable(lt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(me>=0&&me<=ie.width-Ce&&Ae>=0&&Ae<=ie.height-ve){ue.bindFramebuffer(Y.FRAMEBUFFER,Je);const rt=Y.createBuffer();Y.bindBuffer(Y.PIXEL_PACK_BUFFER,rt),Y.bufferData(Y.PIXEL_PACK_BUFFER,Be.byteLength,Y.STREAM_READ),Y.readPixels(me,Ae,Ce,ve,tt.convert(ct),tt.convert(lt),0);const bt=I!==null?be.get(I).__webglFramebuffer:null;ue.bindFramebuffer(Y.FRAMEBUFFER,bt);const Tt=Y.fenceSync(Y.SYNC_GPU_COMMANDS_COMPLETE,0);return Y.flush(),await s0(Y,Tt,4),Y.bindBuffer(Y.PIXEL_PACK_BUFFER,rt),Y.getBufferSubData(Y.PIXEL_PACK_BUFFER,0,Be),Y.deleteBuffer(rt),Y.deleteSync(Tt),Be}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(ie,me=null,Ae=0){ie.isTexture!==!0&&(qr("WebGLRenderer: copyFramebufferToTexture function signature has changed."),me=arguments[0]||null,ie=arguments[1]);const Ce=Math.pow(2,-Ae),ve=Math.floor(ie.image.width*Ce),Be=Math.floor(ie.image.height*Ce),Xe=me!==null?me.x:0,Je=me!==null?me.y:0;Z.setTexture2D(ie,0),Y.copyTexSubImage2D(Y.TEXTURE_2D,Ae,0,0,Xe,Je,ve,Be),ue.unbindTexture()};const Zy=Y.createFramebuffer(),eE=Y.createFramebuffer();this.copyTextureToTexture=function(ie,me,Ae=null,Ce=null,ve=0,Be=null){ie.isTexture!==!0&&(qr("WebGLRenderer: copyTextureToTexture function signature has changed."),Ce=arguments[0]||null,ie=arguments[1],me=arguments[2],Be=arguments[3]||0,Ae=null),Be===null&&(ve!==0?(qr("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),Be=ve,ve=0):Be=0);let Xe,Je,Qe,ct,lt,rt,bt,Tt,$t;const Vt=ie.isCompressedTexture?ie.mipmaps[Be]:ie.image;if(Ae!==null)Xe=Ae.max.x-Ae.min.x,Je=Ae.max.y-Ae.min.y,Qe=Ae.isBox3?Ae.max.z-Ae.min.z:1,ct=Ae.min.x,lt=Ae.min.y,rt=Ae.isBox3?Ae.min.z:0;else{const $i=Math.pow(2,-ve);Xe=Math.floor(Vt.width*$i),Je=Math.floor(Vt.height*$i),ie.isDataArrayTexture?Qe=Vt.depth:ie.isData3DTexture?Qe=Math.floor(Vt.depth*$i):Qe=1,ct=0,lt=0,rt=0}Ce!==null?(bt=Ce.x,Tt=Ce.y,$t=Ce.z):(bt=0,Tt=0,$t=0);const Rt=tt.convert(me.format),ot=tt.convert(me.type);let ni;me.isData3DTexture?(Z.setTexture3D(me,0),ni=Y.TEXTURE_3D):me.isDataArrayTexture||me.isCompressedArrayTexture?(Z.setTexture2DArray(me,0),ni=Y.TEXTURE_2D_ARRAY):(Z.setTexture2D(me,0),ni=Y.TEXTURE_2D),Y.pixelStorei(Y.UNPACK_FLIP_Y_WEBGL,me.flipY),Y.pixelStorei(Y.UNPACK_PREMULTIPLY_ALPHA_WEBGL,me.premultiplyAlpha),Y.pixelStorei(Y.UNPACK_ALIGNMENT,me.unpackAlignment);const At=Y.getParameter(Y.UNPACK_ROW_LENGTH),cn=Y.getParameter(Y.UNPACK_IMAGE_HEIGHT),fo=Y.getParameter(Y.UNPACK_SKIP_PIXELS),Ni=Y.getParameter(Y.UNPACK_SKIP_ROWS),zo=Y.getParameter(Y.UNPACK_SKIP_IMAGES);Y.pixelStorei(Y.UNPACK_ROW_LENGTH,Vt.width),Y.pixelStorei(Y.UNPACK_IMAGE_HEIGHT,Vt.height),Y.pixelStorei(Y.UNPACK_SKIP_PIXELS,ct),Y.pixelStorei(Y.UNPACK_SKIP_ROWS,lt),Y.pixelStorei(Y.UNPACK_SKIP_IMAGES,rt);const Ut=ie.isDataArrayTexture||ie.isData3DTexture,Xi=me.isDataArrayTexture||me.isData3DTexture;if(ie.isDepthTexture){const $i=be.get(ie),fi=be.get(me),Ti=be.get($i.__renderTarget),Dl=be.get(fi.__renderTarget);ue.bindFramebuffer(Y.READ_FRAMEBUFFER,Ti.__webglFramebuffer),ue.bindFramebuffer(Y.DRAW_FRAMEBUFFER,Dl.__webglFramebuffer);for(let Mr=0;Mr<Qe;Mr++)Ut&&(Y.framebufferTextureLayer(Y.READ_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,be.get(ie).__webglTexture,ve,rt+Mr),Y.framebufferTextureLayer(Y.DRAW_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,be.get(me).__webglTexture,Be,$t+Mr)),Y.blitFramebuffer(ct,lt,Xe,Je,bt,Tt,Xe,Je,Y.DEPTH_BUFFER_BIT,Y.NEAREST);ue.bindFramebuffer(Y.READ_FRAMEBUFFER,null),ue.bindFramebuffer(Y.DRAW_FRAMEBUFFER,null)}else if(ve!==0||ie.isRenderTargetTexture||be.has(ie)){const $i=be.get(ie),fi=be.get(me);ue.bindFramebuffer(Y.READ_FRAMEBUFFER,Zy),ue.bindFramebuffer(Y.DRAW_FRAMEBUFFER,eE);for(let Ti=0;Ti<Qe;Ti++)Ut?Y.framebufferTextureLayer(Y.READ_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,$i.__webglTexture,ve,rt+Ti):Y.framebufferTexture2D(Y.READ_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Y.TEXTURE_2D,$i.__webglTexture,ve),Xi?Y.framebufferTextureLayer(Y.DRAW_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,fi.__webglTexture,Be,$t+Ti):Y.framebufferTexture2D(Y.DRAW_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Y.TEXTURE_2D,fi.__webglTexture,Be),ve!==0?Y.blitFramebuffer(ct,lt,Xe,Je,bt,Tt,Xe,Je,Y.COLOR_BUFFER_BIT,Y.NEAREST):Xi?Y.copyTexSubImage3D(ni,Be,bt,Tt,$t+Ti,ct,lt,Xe,Je):Y.copyTexSubImage2D(ni,Be,bt,Tt,ct,lt,Xe,Je);ue.bindFramebuffer(Y.READ_FRAMEBUFFER,null),ue.bindFramebuffer(Y.DRAW_FRAMEBUFFER,null)}else Xi?ie.isDataTexture||ie.isData3DTexture?Y.texSubImage3D(ni,Be,bt,Tt,$t,Xe,Je,Qe,Rt,ot,Vt.data):me.isCompressedArrayTexture?Y.compressedTexSubImage3D(ni,Be,bt,Tt,$t,Xe,Je,Qe,Rt,Vt.data):Y.texSubImage3D(ni,Be,bt,Tt,$t,Xe,Je,Qe,Rt,ot,Vt):ie.isDataTexture?Y.texSubImage2D(Y.TEXTURE_2D,Be,bt,Tt,Xe,Je,Rt,ot,Vt.data):ie.isCompressedTexture?Y.compressedTexSubImage2D(Y.TEXTURE_2D,Be,bt,Tt,Vt.width,Vt.height,Rt,Vt.data):Y.texSubImage2D(Y.TEXTURE_2D,Be,bt,Tt,Xe,Je,Rt,ot,Vt);Y.pixelStorei(Y.UNPACK_ROW_LENGTH,At),Y.pixelStorei(Y.UNPACK_IMAGE_HEIGHT,cn),Y.pixelStorei(Y.UNPACK_SKIP_PIXELS,fo),Y.pixelStorei(Y.UNPACK_SKIP_ROWS,Ni),Y.pixelStorei(Y.UNPACK_SKIP_IMAGES,zo),Be===0&&me.generateMipmaps&&Y.generateMipmap(ni),ue.unbindTexture()},this.copyTextureToTexture3D=function(ie,me,Ae=null,Ce=null,ve=0){return ie.isTexture!==!0&&(qr("WebGLRenderer: copyTextureToTexture3D function signature has changed."),Ae=arguments[0]||null,Ce=arguments[1]||null,ie=arguments[2],me=arguments[3],ve=arguments[4]||0),qr('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'),this.copyTextureToTexture(ie,me,Ae,Ce,ve)},this.initRenderTarget=function(ie){be.get(ie).__webglFramebuffer===void 0&&Z.setupRenderTarget(ie)},this.initTexture=function(ie){ie.isCubeTexture?Z.setTextureCube(ie,0):ie.isData3DTexture?Z.setTexture3D(ie,0):ie.isDataArrayTexture||ie.isCompressedArrayTexture?Z.setTexture2DArray(ie,0):Z.setTexture2D(ie,0),ue.unbindTexture()},this.resetState=function(){R=0,E=0,I=null,ue.reset(),z.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Mn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorspace=Et._getDrawingBufferColorSpace(e),t.unpackColorSpace=Et._getUnpackColorSpace()}}const zy=`
        varying vec2 vUv;
        void main() {
          vUv = uv;
          gl_Position = vec4(position, 1.0);
        }
      `,Wy=`
        uniform sampler2D uVideo;
        uniform vec2 uResolution;
        uniform float uHalfWidth;
        uniform float uHeight;
        varying vec2 vUv;

        void main() {
          vec2 uv = vUv;

          // 当前像素坐标
          vec2 fragCoord = uv * uResolution;

          // 人像区域居中
          vec2 center = uResolution * 0.5;
          vec2 minCoord = center - vec2(uHalfWidth, uHeight) * 0.5;
          vec2 maxCoord = minCoord + vec2(uHalfWidth, uHeight);

          if (fragCoord.x >= minCoord.x && fragCoord.x < maxCoord.x &&
              fragCoord.y >= minCoord.y && fragCoord.y < maxCoord.y) {

            // 相对 UV
            vec2 personUV = (fragCoord - minCoord) / vec2(uHalfWidth, uHeight);
            vec2 textureUV = personUV * vec2(0.5, 1.0);

            // 防止越界
            textureUV.x = clamp(textureUV.x, 0.0, 0.5);

            // 采样颜色(左半)
            vec4 color = texture2D(uVideo, textureUV);

            // 采样 mask(右半)
            vec2 maskUV = textureUV + vec2(0.5, 0.0);

            // 计算像素偏移量(用于多采样)
            vec2 pixelSize = vec2(1.0 / uResolution.x, 1.0 / uResolution.y);
            
            // 多采样 mask 区域(3x3 采样,用于更好的边缘检测和平滑)
            // 使用高斯权重进行采样,减少边缘锯齿
            // 中心权重最高,边缘权重递减
            float maskSum = 0.0;
            
            // 3x3 采样,手动展开循环以确保兼容性
            vec2 offset;
            vec3 maskColor;
            float maskLuminance;
            
            // 第一行
            offset = maskUV + vec2(-1.0, -1.0) * pixelSize;
            maskColor = texture2D(uVideo, offset).rgb;
            maskLuminance = dot(maskColor, vec3(0.299, 0.587, 0.114));
            maskSum += maskLuminance * 0.0625;
            
            offset = maskUV + vec2( 0.0, -1.0) * pixelSize;
            maskColor = texture2D(uVideo, offset).rgb;
            maskLuminance = dot(maskColor, vec3(0.299, 0.587, 0.114));
            maskSum += maskLuminance * 0.125;
            
            offset = maskUV + vec2( 1.0, -1.0) * pixelSize;
            maskColor = texture2D(uVideo, offset).rgb;
            maskLuminance = dot(maskColor, vec3(0.299, 0.587, 0.114));
            maskSum += maskLuminance * 0.0625;
            
            // 第二行(中心行,权重最高)
            offset = maskUV + vec2(-1.0,  0.0) * pixelSize;
            maskColor = texture2D(uVideo, offset).rgb;
            maskLuminance = dot(maskColor, vec3(0.299, 0.587, 0.114));
            maskSum += maskLuminance * 0.125;
            
            offset = maskUV + vec2( 0.0,  0.0) * pixelSize; // 中心点
            maskColor = texture2D(uVideo, offset).rgb;
            maskLuminance = dot(maskColor, vec3(0.299, 0.587, 0.114));
            maskSum += maskLuminance * 0.25; // 中心权重最高
            
            offset = maskUV + vec2( 1.0,  0.0) * pixelSize;
            maskColor = texture2D(uVideo, offset).rgb;
            maskLuminance = dot(maskColor, vec3(0.299, 0.587, 0.114));
            maskSum += maskLuminance * 0.125;
            
            // 第三行
            offset = maskUV + vec2(-1.0,  1.0) * pixelSize;
            maskColor = texture2D(uVideo, offset).rgb;
            maskLuminance = dot(maskColor, vec3(0.299, 0.587, 0.114));
            maskSum += maskLuminance * 0.0625;
            
            offset = maskUV + vec2( 0.0,  1.0) * pixelSize;
            maskColor = texture2D(uVideo, offset).rgb;
            maskLuminance = dot(maskColor, vec3(0.299, 0.587, 0.114));
            maskSum += maskLuminance * 0.125;
            
            offset = maskUV + vec2( 1.0,  1.0) * pixelSize;
            maskColor = texture2D(uVideo, offset).rgb;
            maskLuminance = dot(maskColor, vec3(0.299, 0.587, 0.114));
            maskSum += maskLuminance * 0.0625;
            
            // 权重总和为 1.0,所以直接使用 maskSum
            float avgMask = maskSum;
            
            // 改进的边缘羽化:使用更平滑的过渡
            // 边缘收缩:轻微收缩 mask 以避免白边
            // 通过提高阈值来收缩边缘,去除边缘处的半透明区域
            float edgeContraction = 0.15; // 收缩量,值越大收缩越多
            float contractedMask = smoothstep(edgeContraction, 1.0 - edgeContraction * 0.5, avgMask);
            
            // 使用更平滑的过渡曲线
            float alpha = smoothstep(0.0, 1.0, contractedMask);
            
            // 边缘羽化:在边缘区域进行额外的平滑
            // 使用更宽的过渡区域来减少硬边
            alpha = smoothstep(0.1, 0.9, alpha);
            
            // 使用预乘 alpha 避免边缘白线
            // 关键:将颜色与 alpha 预乘,避免边缘处的颜色混合问题
            vec3 premultipliedColor = color.rgb * alpha;
            
            // 边缘去色:在低 alpha 区域,减少颜色强度,避免白边
            // 这可以去除边缘处可能残留的背景色(特别是白色背景)
            // 使用更激进的边缘去色来消除白边
            float edgeFade = smoothstep(0.0, 0.4, alpha);
            premultipliedColor *= edgeFade;
            
            // 额外的边缘清理:如果 alpha 很低,直接设为透明
            // 这可以完全去除边缘处的残留像素
            // 使用 mix 替代 if 语句,提高兼容性和性能
            float edgeThreshold = step(0.05, alpha); // alpha >= 0.05 时为 1.0,否则为 0.0
            alpha *= edgeThreshold;
            premultipliedColor *= edgeThreshold;
            
            gl_FragColor = vec4(premultipliedColor, alpha);
          } else {
            // 区域外透明
            gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
          }
        }
      `;class jy{constructor(e,t,n={}){We(this,"renderer");We(this,"scene");We(this,"camera");We(this,"material");We(this,"plane");We(this,"canvas");We(this,"stream",null);We(this,"isInitialized",!1);We(this,"fps");We(this,"onCanPlayBound",null);We(this,"inputVideo");We(this,"outputVideo");this.inputVideo=e,this.outputVideo=t,this.fps=n.fps||30,this.canvas=document.createElement("canvas"),this.canvas.style.display="none",document.body.appendChild(this.canvas),this.renderer=new Gy({canvas:this.canvas,alpha:!0,antialias:!0,preserveDrawingBuffer:!1}),this.renderer.setPixelRatio(window.devicePixelRatio||1),this.scene=new O0,this.camera=new Np(-1,1,1,-1,0,1),this.plane=new gn(new Ho(2,2)),this.scene.add(this.plane),this.material=new kn({uniforms:{uVideo:{value:null},uResolution:{value:new xt(1,1)},uHalfWidth:{value:1},uHeight:{value:1}},vertexShader:zy,fragmentShader:Wy,transparent:!0}),this.plane.material=this.material}start(){if(this.isInitialized)return;if(!("requestVideoFrameCallback"in HTMLVideoElement.prototype))throw new Error("[AlphaMaskProcessor] 当前浏览器不支持 requestVideoFrameCallback,无法保证帧同步,停止初始化。");const e=this.inputVideo,t=()=>{if(this.isInitialized)return;if(!e.videoWidth||!e.videoHeight){console.error("视频尺寸无效,无法启动 AlphaMaskProcessor");return}const n=e.videoWidth,r=e.videoHeight,a=n/2;this.canvas.width=n,this.canvas.height=r,this.renderer.setSize(n,r),this.material.uniforms.uResolution.value.set(n,r),this.material.uniforms.uHalfWidth.value=a,this.material.uniforms.uHeight.value=r;const s=new U0(e);s.minFilter=Ei,s.magFilter=Ei,s.generateMipmaps=!1,s.wrapS=An,s.wrapT=An,this.material.uniforms.uVideo.value=s,this.stream=this.canvas.captureStream(this.fps),this.outputVideo&&(this.outputVideo.srcObject=this.stream,this.outputVideo.play().catch(h=>{console.error("outputVideo 播放失败:",h)})),this.isInitialized=!0,console.log(`AlphaMaskProcessor 已启动,尺寸: ${n}x${r}, FPS: ${this.fps}`);let o=-1;const c=h=>{if(h!==o){try{const l=this.renderer.getContext();l&&!l.isContextLost()&&this.renderer.render(this.scene,this.camera)}catch(l){console.error("WebGL 渲染失败:",l),this.stop()}o=h}this.isInitialized&&!e.paused&&!e.ended&&e.requestVideoFrameCallback(c)};e.requestVideoFrameCallback(c)};this.onCanPlayBound=t,e.addEventListener("canplay",this.onCanPlayBound)}getStream(){return this.stream}stop(){if(!this.isInitialized){console.warn("⚠️ AlphaMaskProcessor 未启动即调用 stop");return}this.onCanPlayBound&&(this.inputVideo.removeEventListener("canplay",this.onCanPlayBound),this.onCanPlayBound=null),this.outputVideo&&(this.outputVideo.pause(),this.outputVideo.srcObject=null),this.stream&&this.stream.getTracks().forEach(e=>e.stop()),this.material.uniforms.uVideo.value&&this.material.uniforms.uVideo.value.dispose(),this.renderer.dispose(),this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.isInitialized=!1,console.log("AlphaMaskProcessor 已停止")}}const Xy=5;class Ys{constructor(e,t=25){We(this,"video",null);We(this,"targetFps");We(this,"thresholdMs");We(this,"lastFrameTime",null);We(this,"frameCount",0);We(this,"onStutterDetected");We(this,"onVideoFrame",(e,t)=>{const n=this.video;if(!n||n.paused||n.ended)return;const r=(t==null?void 0:t.presentationTime)||e||performance.now();if(this.frameCount++,this.frameCount<=Xy){this.lastFrameTime=r,this.requestNextFrame();return}if(this.lastFrameTime!==null){const a=r-this.lastFrameTime;if(a>this.thresholdMs){const s=a-this.thresholdMs;this.onStutterDetected(s)}}this.lastFrameTime=r,this.requestNextFrame()});this.targetFps=t,this.thresholdMs=1e3/this.targetFps*3,this.onStutterDetected=e}static isSupported(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}start(e){if(!Ys.isSupported()){console.warn("[StutterMonitor] requestVideoFrameCallback not supported, skipping.");return}this.stop(),this.video=e,this.lastFrameTime=null,this.frameCount=0,this.requestNextFrame()}stop(){this.video=null,this.lastFrameTime=null,this.frameCount=0}requestNextFrame(){this.video&&this.video.requestVideoFrameCallback(this.onVideoFrame)}}class $y extends sv{constructor(t){super(t,"CloudAvatar");We(this,"_avatarVideoEle");We(this,"_innerVideoEle",document.createElement("video"));We(this,"_chromaKeyProcessor",null);We(this,"_alphaMaskProcessor",null);We(this,"_stutterMonitor",null);We(this,"_clientMotionBatchSeq",0);this._init()}async _init(){if(et.trace({action:"init",msg:"初始化云渲染数字人",ext:{type:"CloudAvatar"}}),this._setupRTCView(this._avatarInitConfig.rootContainer),this._checkUserActivation(),await this._checkMicPermissionDenied())return!1;const n=await this._rtc.init({ignoreAudioInput:!!this._avatarInitConfig.ignoreAudioInput,enableLocalVideo:!1,cameraCapturerConfig:this._avatarInitConfig.cameraCapturerConfig});n&&(n.setParameter(JSON.stringify({reportL1IP:!0})),n.on(Zi.videoSubscribeStateChanged,(f,v,p)=>{this._videoSubscribeStateChangedHandler(f,v,p)}),n.on(Zi.dataPublishStateChanged,(f,v)=>{this._dataPublishStateChangedHandler(f,v)}),n.on(Zi.dataChannelMsg,(f,v)=>{this._dataChannelMsgHandler(f,v)}));const{appId:r,channel:a,timestamp:s,token:o,clientUserId:c,clientUserName:h}=this._avatarInitConfig,l={appId:r,channelId:a,timestamp:s,token:o,userId:c,userName:h};this._rtc.joinRoomAsLive(l)}exit(){var t,n,r;super.exit(),this._clientMotionBatchSeq=0,this.removeAllListeners(),(t=this._alphaMaskProcessor)==null||t.stop(),(n=this._chromaKeyProcessor)==null||n.stop(),(r=this._stutterMonitor)==null||r.stop(),this._stutterMonitor=null}_setupRTCView(t){var n;if(et.trace({action:"_setupRTCView",msg:"设置云渲数字人视图节点",ext:{rootContainer:t}}),Object.prototype.toString.call(t)==="[object String]"?this._avatarVideoEle=document.querySelector(t):this._avatarVideoEle=t,!this._avatarVideoEle)throw new Error("container is not exist");this._innerVideoEle.playsInline=!0,this._innerVideoEle.setAttribute("playsinline","true"),this._innerVideoEle.setAttribute("webkit-playsinline","true"),this._innerVideoEle.style.position="fixed",this._innerVideoEle.style.left="-9999px",this._innerVideoEle.style.top="0",this._innerVideoEle.style.width="1px",this._innerVideoEle.style.height="1px",this._innerVideoEle.style.opacity="0",this._innerVideoEle.style.pointerEvents="none",this._innerVideoEle.setAttribute("aria-hidden","true"),this._avatarVideoEle.insertAdjacentElement("afterend",this._innerVideoEle),(n=this._avatarVideoEle)==null||n.addEventListener("canplay",()=>{this._safePlayAvatarVideo().then(()=>{this.emitFirstFrame(),Ys.isSupported()&&(this._stutterMonitor=new Ys(r=>{et.warn({action:"frameStutter",msg:"检测到画面卡顿",ext:{stutterDuration:r,limitDuration:120}})}),this._stutterMonitor.start(this._avatarVideoEle))})},{once:!0})}_safePlayAvatarVideo(){const t=this._avatarVideoEle;if(!t)return Promise.resolve();t.playsInline=!0,t.setAttribute("playsinline","true"),t.setAttribute("webkit-playsinline","true");const n=!t.muted;return t.muted=!0,t.play().then(()=>{n&&(t.muted=!1)}).catch(r=>(et.warn({action:"_safePlayAvatarVideo",msg:"静音起播失败,尝试直接 play",ext:{err:r}}),t.play().catch(()=>{})))}async start(t){et.setBaseExt({mode:t.mode}),et.info({action:"start",msg:"开始对话",ext:{dialogParams:t}}),this.setDialogConfig(t),this.startLinkDataChannel(kh.cloud)}pushAudioData(t,n=!0){if(!this._sessionId)return;const r=Qg(t);if(r.length===0)return;const a=this._dialogConfig.outboundSampleRate??48e3,s=a;let o=0;for(;o<r.length;){const c=Math.min(o+s,r.length),h=r.subarray(o,c),l=c>=r.length,f=n&&l;this._clientMotionBatchSeq+=1;const v=Zg({pcmSamples:h,sampleRate:a,batchId:this._clientMotionBatchSeq,endOfBatch:f});this._sendClientMotionDataChunked(v),o=c}}_sendClientMotionDataChunked(t){if(t.length===0)return;const n=ev(t,Jg),r=n.length,a=t.length,s={version:Qi,namespace:Ji,sessionId:this._sessionId,deviceId:this._deviceId};this._rtc.send(JSON.stringify({header:{...s,name:"ClientMotionData",requestId:Si()},payload:{type:"pureAvatar",firstPackage:!0,binarySize:a,segmentNum:r,useBinaryFrame:!1}}));for(let o=0;o<r;o++)this._rtc.send(JSON.stringify({header:{...s,name:"ClientMotionData",requestId:Si()},payload:{type:"pureAvatar",firstPackage:!1,useBinaryFrame:!1,sliceIndex:o,motionDataSlice:ds.fromByteArray(n[o])}}))}async _videoSubscribeStateChangedHandler(t,n,r){var a,s,o,c;if(et.trace({action:"_videoSubscribeStateChangedHandler",msg:"远端视频流订阅状态变化",ext:{userId:t,oldState:n,newState:r}}),t===((a=this._avatarInitConfig)==null?void 0:a.avatarUserId)){const h=this._serviceInitData.transparentBackgroundType===$n.realBg,l=this._serviceInitData.transparentBackgroundType===$n.serverReplaceBg,f=h||l?this._avatarVideoEle:this._innerVideoEle;r===3?((s=this._rtc.engine)==null||s.setClientRole(un.AliRtcSdkInteractive),(o=this._rtc.engine)==null||o.setRemoteViewConfig(f,t,1),f.autoplay=!0,this._serviceInitData.transparentBackgroundType===$n.chromaKey&&f===this._innerVideoEle?f.muted=!0:f.muted=!1,!h&&!l&&this._remoteTransparentBackgroundProcessor()):r===1&&((c=this._rtc.engine)==null||c.setRemoteViewConfig(null,t,1),f.pause())}}_remoteTransparentBackgroundProcessor(){const t=this._serviceInitData.transparentBackgroundType;t===$n.chromaKey?this._innerVideoEle.requestVideoFrameCallback(()=>{const n=this._innerVideoEle.srcObject;n&&(this._chromaKeyProcessor=new mv(n,r=>{this._avatarVideoEle.srcObject=r},void 0,()=>{this._avatarVideoEle.pause(),this._avatarVideoEle.srcObject=null},{sourceVideo:this._innerVideoEle}),this._chromaKeyProcessor.initialize())}):t===$n.maskBlend&&(this._alphaMaskProcessor=new jy(this._innerVideoEle,this._avatarVideoEle),this._alphaMaskProcessor.start())}}function Ky(i){return new $y(i)}yt.AliRtcEngine=Ya,yt.ApplicationErrorCode=fs,yt.ApplicationErrorMsg=ms,yt.EventTypes=mt,yt.IAvatarAudioFormat=ic,yt.IEnv=Lh,yt.IRequestToRespondType=Nh,yt.Logger=et,yt.RTCErrorCode=bi,yt.RTCErrorMsg=li,yt.RTCEventTypes=Zi,yt.Stats=xi,yt.SystemErrorCode=Ii,yt.SystemErrorMsg=Pi,yt.TYPerformanceInfoType=xo,yt.TYVoiceChatMessageType=ps,yt.TYVoiceChatMode=Mo,yt.TYVoiceChatState=Za,yt.TYVoicePlatform=Oh,yt.VERSION=Qa,yt.createCloudAvatar=Ky,Object.defineProperty(yt,Symbol.toStringTag,{value:"Module"})});