trtc-sdk-v5 5.9.0-wasm.5 → 5.9.0-wasm.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/worker.js +11 -11
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/trtc.esm.js +21 -21
package/trtc.esm.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var jE=Object.create;var Hn=Object.defineProperty,qE=Object.defineProperties,Lf=Object.getOwnPropertyDescriptor,zE=Object.getOwnPropertyDescriptors,JE=Object.getOwnPropertyNames,kf=Object.getOwnPropertySymbols,Uf=Object.getPrototypeOf,Vf=Object.prototype.hasOwnProperty,XE=Object.prototype.propertyIsEnumerable,QE=Reflect.get;var Wn=Math.pow,Yl=(i,t,e)=>t in i?Hn(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,J=(i,t)=>{for(var e in t||(t={}))Vf.call(t,e)&&Yl(i,e,t[e]);if(kf)for(var e of kf(t))XE.call(t,e)&&Yl(i,e,t[e]);return i},me=(i,t)=>qE(i,zE(t));var Gn=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),li=(i,t)=>{for(var e in t)Hn(i,e,{get:t[e],enumerable:!0})},YE=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of JE(t))!Vf.call(i,o)&&o!==e&&Hn(i,o,{get:()=>t[o],enumerable:!(r=Lf(t,o))||r.enumerable});return i};var Pi=(i,t,e)=>(e=i!=null?jE(Uf(i)):{},YE(t||!i||!i.__esModule?Hn(e,"default",{value:i,enumerable:!0}):e,i));var q=(i,t,e,r)=>{for(var o=r>1?void 0:r?Lf(t,e):t,s=i.length-1,a;s>=0;s--)(a=i[s])&&(o=(r?a(t,e,o):a(o))||o);return r&&o&&Hn(t,e,o),o};var l=(i,t,e)=>(Yl(i,typeof t!="symbol"?t+"":t,e),e);var Lt=(i,t,e)=>QE(Uf(i),e,t);var v=(i,t,e)=>new Promise((r,o)=>{var s=h=>{try{d(e.next(h))}catch(p){o(p)}},a=h=>{try{d(e.throw(h))}catch(p){o(p)}},d=h=>h.done?r(h.value):Promise.resolve(h.value).then(s,a);d((e=e.apply(i,t)).next())});var Hi=Gn((XA,wp)=>{"use strict";var eI=Object.prototype.hasOwnProperty,Ut="~";function Ia(){}Object.create&&(Ia.prototype=Object.create(null),new Ia().__proto__||(Ut=!1));function tI(i,t,e){this.fn=i,this.context=t,this.once=e||!1}function h_(i,t,e,r,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new tI(e,r||i,o),a=Ut?Ut+t:t;return i._events[a]?i._events[a].fn?i._events[a]=[i._events[a],s]:i._events[a].push(s):(i._events[a]=s,i._eventsCount++),i}function Dd(i,t){--i._eventsCount===0?i._events=new Ia:delete i._events[t]}function vt(){this._events=new Ia,this._eventsCount=0}vt.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)eI.call(e,r)&&t.push(Ut?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};vt.prototype.listeners=function(t){var e=Ut?Ut+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,s=r.length,a=new Array(s);o<s;o++)a[o]=r[o].fn;return a};vt.prototype.listenerCount=function(t){var e=Ut?Ut+t:t,r=this._events[e];return r?r.fn?1:r.length:0};vt.prototype.emit=function(t,e,r,o,s,a){var d=Ut?Ut+t:t;if(!this._events[d])return!1;var h=this._events[d],p=arguments.length,T,y;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),p){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,r),!0;case 4:return h.fn.call(h.context,e,r,o),!0;case 5:return h.fn.call(h.context,e,r,o,s),!0;case 6:return h.fn.call(h.context,e,r,o,s,a),!0}for(y=1,T=new Array(p-1);y<p;y++)T[y-1]=arguments[y];h.fn.apply(h.context,T)}else{var R=h.length,N;for(y=0;y<R;y++)switch(h[y].once&&this.removeListener(t,h[y].fn,void 0,!0),p){case 1:h[y].fn.call(h[y].context);break;case 2:h[y].fn.call(h[y].context,e);break;case 3:h[y].fn.call(h[y].context,e,r);break;case 4:h[y].fn.call(h[y].context,e,r,o);break;default:if(!T)for(N=1,T=new Array(p-1);N<p;N++)T[N-1]=arguments[N];h[y].fn.apply(h[y].context,T)}}return!0};vt.prototype.on=function(t,e,r){return h_(this,t,e,r,!1)};vt.prototype.once=function(t,e,r){return h_(this,t,e,r,!0)};vt.prototype.removeListener=function(t,e,r,o){var s=Ut?Ut+t:t;if(!this._events[s])return this;if(!e)return Dd(this,s),this;var a=this._events[s];if(a.fn)a.fn===e&&(!o||a.once)&&(!r||a.context===r)&&Dd(this,s);else{for(var d=0,h=[],p=a.length;d<p;d++)(a[d].fn!==e||o&&!a[d].once||r&&a[d].context!==r)&&h.push(a[d]);h.length?this._events[s]=h.length===1?h[0]:h:Dd(this,s)}return this};vt.prototype.removeAllListeners=function(t){var e;return t?(e=Ut?Ut+t:t,this._events[e]&&Dd(this,e)):(this._events=new Ia,this._eventsCount=0),this};vt.prototype.off=vt.prototype.removeListener;vt.prototype.addListener=vt.prototype.on;vt.prefixed=Ut;vt.EventEmitter=vt;typeof wp!="undefined"&&(wp.exports=vt)});var jp=Gn((bb,C_)=>{var R_=C_.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(i){return i.encoding?"rtpmap:%d %s/%s/%s":i.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(i){return i.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(i){return i.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(i){return"extmap:%d"+(i.direction?"/%s":"%v")+(i["encrypt-uri"]?" %s":"%v")+" %s"+(i.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(i){return i.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(i){var t="candidate:%s %d %s %d %s %d typ %s";return t+=i.raddr!=null?" raddr %s rport %d":"%v%v",t+=i.tcptype!=null?" tcptype %s":"%v",i.generation!=null&&(t+=" generation %d"),t+=i["network-id"]!=null?" network-id %d":"%v",t+=i["network-cost"]!=null?" network-cost %d":"%v",t}},{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(i){var t="ssrc:%d";return i.attribute!=null&&(t+=" %s",i.value!=null&&(t+=":%s")),t}},{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(i){return i.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(i){return i.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(i){return"imageattr:%s %s %s"+(i.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(i){return"simulcast:%s %s"+(i.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(i){return"ts-refclk:%s"+(i.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(i){var t="mediaclk:";return t+=i.id!=null?"id=%s %s":"%v%s",t+=i.mediaClockValue!=null?"=%s":"",t+=i.rateNumerator!=null?" rate=%s":"",t+=i.rateDenominator!=null?"/%s":"",t}},{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(R_).forEach(function(i){var t=R_[i];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var w_=Gn(Si=>{var Bs=function(i){return String(Number(i))===i?Number(i):i},uI=function(i,t,e,r){if(r&&!e)t[r]=Bs(i[1]);else for(var o=0;o<e.length;o+=1)i[o+1]!=null&&(t[e[o]]=Bs(i[o+1]))},lI=function(i,t,e){var r=i.name&&i.names;i.push&&!t[i.push]?t[i.push]=[]:r&&!t[i.name]&&(t[i.name]={});var o=i.push?{}:r?t[i.name]:t;uI(e.match(i.reg),o,i.names,i.name),i.push&&t[i.push].push(o)},D_=jp(),pI=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Si.parse=function(i){var t={},e=[],r=t;return i.split(/(\r\n|\r|\n)/).filter(pI).forEach(function(o){var s=o[0],a=o.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),r=e[e.length-1]);for(var d=0;d<(D_[s]||[]).length;d+=1){var h=D_[s][d];if(h.reg.test(a))return lI(h,r,a)}}),t.media=e,t};var N_=function(i,t){var e=t.split(/=(.+)/,2);return e.length===2?i[e[0]]=Bs(e[1]):e.length===1&&t.length>1&&(i[e[0]]=void 0),i};Si.parseParams=function(i){return i.split(/;\s?/).reduce(N_,{})};Si.parseFmtpConfig=Si.parseParams;Si.parsePayloads=function(i){return i.toString().split(" ").map(Number)};Si.parseRemoteCandidates=function(i){for(var t=[],e=i.split(" ").map(Bs),r=0;r<e.length;r+=3)t.push({component:e[r],ip:e[r+1],port:e[r+2]});return t};Si.parseImageAttributes=function(i){return i.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(N_,{})})};Si.parseSimulcastStreamList=function(i){return i.split(";").map(function(t){return t.split(",").map(function(e){var r,o=!1;return e[0]!=="~"?r=Bs(e):(r=Bs(e.substring(1,e.length)),o=!0),{scid:r,paused:o}})})}});var M_=Gn((Rb,x_)=>{var qp=jp(),mI=/%[sdv%]/g,hI=function(i){var t=1,e=arguments,r=e.length;return i.replace(mI,function(o){if(t>=r)return o;var s=e[t];switch(t+=1,o){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Ra=function(i,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,o=[i+"="+r];if(t.names)for(var s=0;s<t.names.length;s+=1){var a=t.names[s];t.name?o.push(e[t.name][a]):o.push(e[t.names[s]])}else o.push(e[t.name]);return hI.apply(null,o)},fI=["v","o","s","i","u","e","p","c","b","t","r","z","a"],_I=["i","c","b","a"];x_.exports=function(i,t){t=t||{},i.version==null&&(i.version=0),i.name==null&&(i.name=" "),i.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=t.outerOrder||fI,r=t.innerOrder||_I,o=[];return e.forEach(function(s){qp[s].forEach(function(a){a.name in i&&i[a.name]!=null?o.push(Ra(s,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(d){o.push(Ra(s,a,d))})})}),i.media.forEach(function(s){o.push(Ra("m",qp.m[0],s)),r.forEach(function(a){qp[a].forEach(function(d){d.name in s&&s[d.name]!=null?o.push(Ra(a,d,s)):d.push in s&&s[d.push]!=null&&s[d.push].forEach(function(h){o.push(Ra(a,d,h))})})})}),o.join(`\r
|
|
1
|
+
var jE=Object.create;var Wn=Object.defineProperty,qE=Object.defineProperties,Lf=Object.getOwnPropertyDescriptor,zE=Object.getOwnPropertyDescriptors,JE=Object.getOwnPropertyNames,kf=Object.getOwnPropertySymbols,Uf=Object.getPrototypeOf,Vf=Object.prototype.hasOwnProperty,XE=Object.prototype.propertyIsEnumerable,QE=Reflect.get;var Gn=Math.pow,Yl=(i,t,e)=>t in i?Wn(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,J=(i,t)=>{for(var e in t||(t={}))Vf.call(t,e)&&Yl(i,e,t[e]);if(kf)for(var e of kf(t))XE.call(t,e)&&Yl(i,e,t[e]);return i},me=(i,t)=>qE(i,zE(t));var jn=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),li=(i,t)=>{for(var e in t)Wn(i,e,{get:t[e],enumerable:!0})},YE=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of JE(t))!Vf.call(i,o)&&o!==e&&Wn(i,o,{get:()=>t[o],enumerable:!(r=Lf(t,o))||r.enumerable});return i};var Pi=(i,t,e)=>(e=i!=null?jE(Uf(i)):{},YE(t||!i||!i.__esModule?Wn(e,"default",{value:i,enumerable:!0}):e,i));var q=(i,t,e,r)=>{for(var o=r>1?void 0:r?Lf(t,e):t,s=i.length-1,a;s>=0;s--)(a=i[s])&&(o=(r?a(t,e,o):a(o))||o);return r&&o&&Wn(t,e,o),o};var l=(i,t,e)=>(Yl(i,typeof t!="symbol"?t+"":t,e),e);var Lt=(i,t,e)=>QE(Uf(i),e,t);var v=(i,t,e)=>new Promise((r,o)=>{var s=h=>{try{d(e.next(h))}catch(p){o(p)}},a=h=>{try{d(e.throw(h))}catch(p){o(p)}},d=h=>h.done?r(h.value):Promise.resolve(h.value).then(s,a);d((e=e.apply(i,t)).next())});var Hi=jn((XA,wp)=>{"use strict";var eI=Object.prototype.hasOwnProperty,Ut="~";function Sa(){}Object.create&&(Sa.prototype=Object.create(null),new Sa().__proto__||(Ut=!1));function tI(i,t,e){this.fn=i,this.context=t,this.once=e||!1}function h_(i,t,e,r,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new tI(e,r||i,o),a=Ut?Ut+t:t;return i._events[a]?i._events[a].fn?i._events[a]=[i._events[a],s]:i._events[a].push(s):(i._events[a]=s,i._eventsCount++),i}function Dd(i,t){--i._eventsCount===0?i._events=new Sa:delete i._events[t]}function vt(){this._events=new Sa,this._eventsCount=0}vt.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)eI.call(e,r)&&t.push(Ut?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};vt.prototype.listeners=function(t){var e=Ut?Ut+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,s=r.length,a=new Array(s);o<s;o++)a[o]=r[o].fn;return a};vt.prototype.listenerCount=function(t){var e=Ut?Ut+t:t,r=this._events[e];return r?r.fn?1:r.length:0};vt.prototype.emit=function(t,e,r,o,s,a){var d=Ut?Ut+t:t;if(!this._events[d])return!1;var h=this._events[d],p=arguments.length,T,y;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),p){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,r),!0;case 4:return h.fn.call(h.context,e,r,o),!0;case 5:return h.fn.call(h.context,e,r,o,s),!0;case 6:return h.fn.call(h.context,e,r,o,s,a),!0}for(y=1,T=new Array(p-1);y<p;y++)T[y-1]=arguments[y];h.fn.apply(h.context,T)}else{var R=h.length,N;for(y=0;y<R;y++)switch(h[y].once&&this.removeListener(t,h[y].fn,void 0,!0),p){case 1:h[y].fn.call(h[y].context);break;case 2:h[y].fn.call(h[y].context,e);break;case 3:h[y].fn.call(h[y].context,e,r);break;case 4:h[y].fn.call(h[y].context,e,r,o);break;default:if(!T)for(N=1,T=new Array(p-1);N<p;N++)T[N-1]=arguments[N];h[y].fn.apply(h[y].context,T)}}return!0};vt.prototype.on=function(t,e,r){return h_(this,t,e,r,!1)};vt.prototype.once=function(t,e,r){return h_(this,t,e,r,!0)};vt.prototype.removeListener=function(t,e,r,o){var s=Ut?Ut+t:t;if(!this._events[s])return this;if(!e)return Dd(this,s),this;var a=this._events[s];if(a.fn)a.fn===e&&(!o||a.once)&&(!r||a.context===r)&&Dd(this,s);else{for(var d=0,h=[],p=a.length;d<p;d++)(a[d].fn!==e||o&&!a[d].once||r&&a[d].context!==r)&&h.push(a[d]);h.length?this._events[s]=h.length===1?h[0]:h:Dd(this,s)}return this};vt.prototype.removeAllListeners=function(t){var e;return t?(e=Ut?Ut+t:t,this._events[e]&&Dd(this,e)):(this._events=new Sa,this._eventsCount=0),this};vt.prototype.off=vt.prototype.removeListener;vt.prototype.addListener=vt.prototype.on;vt.prefixed=Ut;vt.EventEmitter=vt;typeof wp!="undefined"&&(wp.exports=vt)});var jp=jn((bb,C_)=>{var R_=C_.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(i){return i.encoding?"rtpmap:%d %s/%s/%s":i.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(i){return i.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(i){return i.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(i){return"extmap:%d"+(i.direction?"/%s":"%v")+(i["encrypt-uri"]?" %s":"%v")+" %s"+(i.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(i){return i.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(i){var t="candidate:%s %d %s %d %s %d typ %s";return t+=i.raddr!=null?" raddr %s rport %d":"%v%v",t+=i.tcptype!=null?" tcptype %s":"%v",i.generation!=null&&(t+=" generation %d"),t+=i["network-id"]!=null?" network-id %d":"%v",t+=i["network-cost"]!=null?" network-cost %d":"%v",t}},{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(i){var t="ssrc:%d";return i.attribute!=null&&(t+=" %s",i.value!=null&&(t+=":%s")),t}},{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(i){return i.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(i){return i.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(i){return"imageattr:%s %s %s"+(i.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(i){return"simulcast:%s %s"+(i.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(i){return"ts-refclk:%s"+(i.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(i){var t="mediaclk:";return t+=i.id!=null?"id=%s %s":"%v%s",t+=i.mediaClockValue!=null?"=%s":"",t+=i.rateNumerator!=null?" rate=%s":"",t+=i.rateDenominator!=null?"/%s":"",t}},{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(R_).forEach(function(i){var t=R_[i];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var w_=jn(Si=>{var Bs=function(i){return String(Number(i))===i?Number(i):i},uI=function(i,t,e,r){if(r&&!e)t[r]=Bs(i[1]);else for(var o=0;o<e.length;o+=1)i[o+1]!=null&&(t[e[o]]=Bs(i[o+1]))},lI=function(i,t,e){var r=i.name&&i.names;i.push&&!t[i.push]?t[i.push]=[]:r&&!t[i.name]&&(t[i.name]={});var o=i.push?{}:r?t[i.name]:t;uI(e.match(i.reg),o,i.names,i.name),i.push&&t[i.push].push(o)},D_=jp(),pI=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Si.parse=function(i){var t={},e=[],r=t;return i.split(/(\r\n|\r|\n)/).filter(pI).forEach(function(o){var s=o[0],a=o.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),r=e[e.length-1]);for(var d=0;d<(D_[s]||[]).length;d+=1){var h=D_[s][d];if(h.reg.test(a))return lI(h,r,a)}}),t.media=e,t};var N_=function(i,t){var e=t.split(/=(.+)/,2);return e.length===2?i[e[0]]=Bs(e[1]):e.length===1&&t.length>1&&(i[e[0]]=void 0),i};Si.parseParams=function(i){return i.split(/;\s?/).reduce(N_,{})};Si.parseFmtpConfig=Si.parseParams;Si.parsePayloads=function(i){return i.toString().split(" ").map(Number)};Si.parseRemoteCandidates=function(i){for(var t=[],e=i.split(" ").map(Bs),r=0;r<e.length;r+=3)t.push({component:e[r],ip:e[r+1],port:e[r+2]});return t};Si.parseImageAttributes=function(i){return i.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(N_,{})})};Si.parseSimulcastStreamList=function(i){return i.split(";").map(function(t){return t.split(",").map(function(e){var r,o=!1;return e[0]!=="~"?r=Bs(e):(r=Bs(e.substring(1,e.length)),o=!0),{scid:r,paused:o}})})}});var M_=jn((Rb,x_)=>{var qp=jp(),mI=/%[sdv%]/g,hI=function(i){var t=1,e=arguments,r=e.length;return i.replace(mI,function(o){if(t>=r)return o;var s=e[t];switch(t+=1,o){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Ca=function(i,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,o=[i+"="+r];if(t.names)for(var s=0;s<t.names.length;s+=1){var a=t.names[s];t.name?o.push(e[t.name][a]):o.push(e[t.names[s]])}else o.push(e[t.name]);return hI.apply(null,o)},fI=["v","o","s","i","u","e","p","c","b","t","r","z","a"],_I=["i","c","b","a"];x_.exports=function(i,t){t=t||{},i.version==null&&(i.version=0),i.name==null&&(i.name=" "),i.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=t.outerOrder||fI,r=t.innerOrder||_I,o=[];return e.forEach(function(s){qp[s].forEach(function(a){a.name in i&&i[a.name]!=null?o.push(Ca(s,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(d){o.push(Ca(s,a,d))})})}),i.media.forEach(function(s){o.push(Ca("m",qp.m[0],s)),r.forEach(function(a){qp[a].forEach(function(d){d.name in s&&s[d.name]!=null?o.push(Ca(a,d,s)):d.push in s&&s[d.push]!=null&&s[d.push].forEach(function(h){o.push(Ca(a,d,h))})})})}),o.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var O_=Gn(yi=>{var wo=w_(),gI=M_();yi.write=gI;yi.parse=wo.parse;yi.parseParams=wo.parseParams;yi.parseFmtpConfig=wo.parseFmtpConfig;yi.parsePayloads=wo.parsePayloads;yi.parseRemoteCandidates=wo.parseRemoteCandidates;yi.parseImageAttributes=wo.parseImageAttributes;yi.parseSimulcastStreamList=wo.parseSimulcastStreamList});var Bf=(P=>(P[P.INVALID_PARAMETER=4096]="INVALID_PARAMETER",P[P.INVALID_OPERATION=4097]="INVALID_OPERATION",P[P.NOT_SUPPORTED=4098]="NOT_SUPPORTED",P[P.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",P[P.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",P[P.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",P[P.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",P[P.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",P[P.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",P[P.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",P[P.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",P[P.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",P[P.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",P[P.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",P[P.CLIENT_BANNED=16448]="CLIENT_BANNED",P[P.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",P[P.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",P[P.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",P[P.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",P[P.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",P[P.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",P[P.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",P[P.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",P[P.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",P[P.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",P[P.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",P[P.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",P[P.API_CALL_ABORTED=16461]="API_CALL_ABORTED",P[P.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",P[P.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",P[P.UNKNOWN=65535]="UNKNOWN",P))(Bf||{}),Y=Bf;var ZE=function(i){for(let t in Y)if(Y[t]===i)return t;return"UNKNOWN"},Zl=class extends Error{constructor({name:e="RtcError",message:r,code:o=Y.UNKNOWN,extraCode:s=0,constraint:a}){let d=`<${ZE(o)} 0x${o.toString(16)}>`,h=`${r}${a?` constraint: ${a}`:""}${r!=null&&r.includes(d)?"":` ${d}`}`;super(h);l(this,"code");l(this,"extraCode");l(this,"message");l(this,"originMessage");l(this,"name");l(this,"constraint");this.code=o,this.extraCode=s,this.name=e,this.message=h,this.constraint=a,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},de=Zl;var OA=new Date().getTime(),KE=0;var jn=function(){return new Date().getTime()+KE},zc=function(){let i=new Date;return i.setTime(jn()),i.toLocaleString()};var Gr={};li(Gr,{bytes2ms:()=>Xf,convertObjectNumberToInt:()=>ia,copyProperties:()=>Jf,deepClone:()=>Io,deepMerge:()=>Wr,delay:()=>oa,fibonacci:()=>So,formatedTime:()=>nd,getConstructorName:()=>ta,getContainerFromElement:()=>i_,getEnv:()=>jf,getInternalVersion:()=>t_,getLoggerUrl:()=>fi,getMuteStateFromFlag:()=>ra,getNetworkType:()=>Kn,getNumNetworkType:()=>id,getReconnectionTimeout:()=>Yf,getStringByteLength:()=>o_,getTurnServer:()=>r_,getUint32Version:()=>dd,getValueType:()=>mt,getViewListFromView:()=>ys,glog:()=>ea,ipv4ToUint32:()=>Ss,isArray:()=>rt,isAudioWorkletSupported:()=>e_,isBoolean:()=>nt,isConstructor:()=>Is,isEmpty:()=>sd,isFunction:()=>Ve,isLangChinese:()=>vr,isMediaStreamTrack:()=>Zf,isNumber:()=>Fe,isObject:()=>lr,isOverseaSdkAppId:()=>Zn,isPlainObject:()=>$t,isPortrait:()=>cd,isPromise:()=>Li,isRemoteTrack:()=>Kf,isString:()=>Ae,isUndefined:()=>L,loadImage:()=>As,ms2bytes:()=>Qf,ms2samples:()=>pp,performanceNow:()=>ge,promiseAny:()=>od,samples2ms:()=>lp,setNetworkType:()=>zf,stringify:()=>pr,stringifyIncludeValue:()=>ad,throttlePromise:()=>ud});var up={};li(up,{AUDIO_MUTE_BIT:()=>Kc,AUDIO_STAT_BIT:()=>gs,AUX_STAT_BIT:()=>Jn,AUX_STREAM_MSID:()=>lT,BACKEND_ENV:()=>Zc,BASE_DOC_URL:()=>Fr,BASE_HOST:()=>Ff,CAPABILITIES_KEYS:()=>rd,CLASS_NAME:()=>kT,CLOUD_CONSOLE_URL:()=>iT,CROSS_ROOM_BIT:()=>dT,DATA_FREEZE_TIMING:()=>td,DEFAULT_ASSETS_URL:()=>Jc,DOC_URL:()=>oT,DTLS_STATE_UNKNOWN:()=>ST,ENV_NAME:()=>pi,EXCHANGE_SDP_TIMEOUT:()=>CT,INTERVAL:()=>To,IS_WORKER:()=>fs,IS_WORKLET:()=>qn,KIBANA_EVENT:()=>mi,LOCAL_STREAM_PUBLISH_STATE:()=>Hf,LOGGER_CMD_TYPE:()=>ki,LOGGER_DOMAIN:()=>tp,LOGGER_DOMAIN_OVERSEA:()=>rp,LOG_LEVEL:()=>br,LOG_LEVEL_NAME:()=>UT,MAIN_STREAM_MSID:()=>uT,MAX_RTT:()=>Qn,MICROPHONE_COMMUNICATIONS:()=>LT,MICROPHONE_DEFAULT:()=>Eo,MUTE_ALL_BIT:()=>cT,NAME:()=>D,NETWORK_TYPE:()=>go,NOT_SUPPORTED_H264:()=>NT,PAUSED_RETRY_COUNT:()=>ap,PEERCONNECTION_CONNECTING_TIMEOUT:()=>OT,PEER_CONNECTION_STATE:()=>yT,PEER_LEAVE_REASON:()=>Wf,RAF:()=>dp,RECOVER_CAPTURE_INTERVAL:()=>Es,REMOTE_STREAM_TYPE_AUX:()=>mT,REMOTE_STREAM_TYPE_MAIN:()=>pT,RENDER_FREEZE_TIMING:()=>wT,RIC:()=>cp,SCHEDULE_DOMAIN:()=>hi,SCHEDULE_TIMEOUT:()=>PT,SDP_SEMANTICS_PLAN_B:()=>DT,SDP_SEMANTICS_UNIFIED_PLAN:()=>np,SECOND_HOST:()=>tT,SIGNAL_PING_PONG_INTERVAL:()=>nT,SIGNAL_PING_TIMEOUT:()=>sT,SIGNAL_RECONNECTION_COUNT:()=>bT,SMALL_STAT_BIT:()=>op,SPEAKER_DEFAULT:()=>Xn,STORAGE_EXPIRES_TIME:()=>Xc,STREAM_TYPE_BIG:()=>xT,STREAM_TYPE_SMALL:()=>MT,SUBSCRIBE_SMALL_RETRY_COUNT:()=>VT,SYNC_USER_LIST_INTERVAL:()=>vT,Scene:()=>Hr,THIRD_HOST:()=>rT,TIMEOUT:()=>Ts,TRANSPORT_DIRECTION:()=>aT,TRTC_ERROR_ASSISTANCE:()=>ip,TRTC_QUALITY_BAD:()=>ET,TRTC_QUALITY_DISCONNECTED:()=>IT,TRTC_QUALITY_EXCELLENT:()=>fT,TRTC_QUALITY_GOOD:()=>_T,TRTC_QUALITY_POOR:()=>gT,TRTC_QUALITY_UNKNOWN:()=>hT,TRTC_QUALITY_VERY_BAD:()=>TT,UPDATE_OFFER_TIMEOUT:()=>RT,VIDEO_MUTE_BIT:()=>ed,VIDEO_STAT_BIT:()=>_s,audioProfileMap:()=>Qc,getRetryCount:()=>AT,getScriptDir:()=>eT,innerVersion:()=>Kl,loggerProxy:()=>zn,screenProfileMap:()=>Yc,setLoggerProxy:()=>_o,setRetryCount:()=>sp,setVersion:()=>ep,version:()=>Ke,videoProfileMap:()=>$r});var Kl="4.15.00.1600",Ke="5.0.0";function ep(i){Ke=i;let[t,e,r]=i.split(".").map(o=>parseInt(o,10));Kl=`${t}.${Math.min(15,e)}.${Math.min(15,r)}.${e.toString().padStart(2,"0")}${r.toString().padStart(2,"0")}`}var fs=typeof importScripts!="undefined",qn=typeof registerProcessor!="undefined",eT=()=>{let i=fs?self.location.href:document.currentScript.src;return i.substring(0,i.lastIndexOf("/")+1)},zn="",_o=i=>zn=i,Ff="web.sdk.qcloud.com",tT="web.sdk.tencent.cn",rT="web.sdk.cloud.tencent.cn",iT="https://console.cloud.tencent.com/trtc",Fr=`https://${Ff}/trtc/webrtc/v5/doc`,Jc="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",oT=`${Fr}/zh-cn/`,tp="https://yun.tim.qq.com",rp="https://apisgp.my-imcloud.com",ip="trtc_error_assistance",ki={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},pi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},br=(a=>(a[a.TRACE=0]="TRACE",a[a.DEBUG=1]="DEBUG",a[a.INFO=2]="INFO",a[a.WARN=3]="WARN",a[a.ERROR=4]="ERROR",a[a.NONE=5]="NONE",a))(br||{}),sT=18e3,nT=2e3,go={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Xc=7*24*3600*1e3,Qc={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},$r={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},Yc={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},D={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},aT={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Zc={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Hr=(e=>(e.LIVE="live",e.RTC="rtc",e))(Hr||{}),_s=1,op=2,Jn=4,gs=8,Kc=64,ed=16,cT=112,dT=128,uT="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",lT="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",pT=D.MAIN,mT=D.AUXILIARY,hT=0,fT=1,_T=2,gT=3,ET=4,TT=5,IT=6,ST="unknown",yT={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},$f=1/0;function sp(i){$f=i}function AT(){return $f}var bT=30,mi={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},vT=1e4,RT=1e4,CT=1e4,np="unified-plan",DT="plan-b",NT=1028,Hf=(r=>(r[r.UNPUBLISH=-1]="UNPUBLISH",r[r.PUBLISHING=0]="PUBLISHING",r[r.PUBLISHED=1]="PUBLISHED",r))(Hf||{}),td=500,wT=1e3,xT=D.BIG,MT=D.SMALL,OT=10*1e3,hi={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},PT=2e3,kT={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},ap=5,Eo="default",Xn=Eo,LT="communications",UT=Object.keys(br),Wf=["normal leave","timeout leave","kick","role change"],VT=10,Es=2e3,cp="ric",dp="raf",To="interval",Ts="timeout",rd=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Qn=10*1e3;var jf=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Zn=i=>Number(i)<14e8,fi=function(i,t){let e;zn?e=zn:e=Zn(i)?rp:tp;let r=Math.floor(Math.random()*Wn(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${i}&cmdtype=${t}`},Yn="unknown";function Kn(){if(Yn!=="unknown")return Yn;let{userAgent:i,connection:t}=navigator,e=(i.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let r=t&&t.type&&t.type.toLowerCase(),o=t&&t.effectiveType&&t.effectiveType.toLowerCase();return o==="slow-2"&&(o="2g"),r&&(Yn=qf(r,o)),Yn}function qf(i,t){if(go[i])return i;switch(i){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function zf(i){Yn=qf(i)}function id(){return go[Kn()]}function Jf(i,t){for(let e of Reflect.ownKeys(t))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let r=Object.getOwnPropertyDescriptor(t,e)||"";Object.defineProperty(i,e,r)}return i}function Xf(i,t=48e3){return lp(i/4,t)}function lp(i,t=48e3){return i*1e3/t}function Qf(i,t=48e3){return pp(i,t)*4}function pp(i,t=48e3){return i*t/1e3}var ea=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},vr=()=>{let i=navigator.language;return i=i.substring(0,2),i==="zh"},$t=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function So(i,t=1,e=1){return i<=1?e:So(i-1,e,t+e)}function Yf(i){return i>8?30*1e3:So(i)*1e3}function mt(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Ve=i=>typeof i=="function",L=i=>typeof i=="undefined",Ae=i=>typeof i=="string",Fe=i=>typeof i=="number",nt=i=>typeof i=="boolean",lr=i=>mt(i)==="object",rt=i=>mt(i)==="array",Zf=i=>mt(i)==="MediaStreamTrack".toLowerCase(),Kf=i=>i.isRemote,Li=i=>mt(i)==="promise",Is=i=>Ve(i)&&i.prototype.constructor===i,ta=i=>Is(i)?i.prototype.constructor.name:"",e_=typeof AudioWorkletNode!="undefined";function od(i){return new Promise((t,e)=>{let r=[];i.forEach(o=>{o.then(t).catch(s=>{r.push(s),r.length===i.length&&e(r)})})})}function ge(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Gf=i=>+i<10?`0${i}`:i,t_=i=>{let t=i.match(/^\d+\.\d+\.\d+/)[0];if(!t)return i;let e=t.split("."),r=Gf(e[1])+Gf(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${r}`},BT=Object.prototype.hasOwnProperty,{toString:VA}=Object.prototype;function sd(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if($t(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(BT.call(i,t))return!1;return!0}}return!1}function ra(i,t){return{userId:t,hasAudio:!!(i&gs),hasVideo:!!(i&_s),hasAuxiliary:!!(i&Jn),hasSmall:!!(i&op),audioMuted:!!(i&Kc),videoMuted:!!(i&ed),audioAvailable:!!(i&gs)&&!(i&Kc),videoAvailable:!!(i&_s)&&!(i&ed)}}function r_(i){let t={urls:i.url.startsWith("turn:")||i.url.startsWith("turns:")?i.url:`turn:${i.url}`};return!L(i.username)&&!L(i.credential)&&(t.username=i.username,t.credential=i.credential,t.credentialType="password",L(i.credentialType)||(t.credentialType=i.credentialType)),t}function Ss(i,t=!0){if(!Ae(i))return 0;let e=i.split(".");return t?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var Wr=function(i,t,e,r){if(!(lr(i)&&lr(t)))return 0;let o=0,s=Object.keys(t),a;for(let d=0,h=s.length;d<h;d++)if(a=s[d],!(L(t[a])||e&&e.includes(a)))if(lr(i[a])&&lr(t[a]))o+=Wr(i[a],t[a],e,r);else{if(r&&r.includes(t[a]))continue;i[a]!==t[a]&&(i[a]=Io(t[a]),o+=1)}return o};function Io(i){if(rt(i)){let t=[];return i.forEach((e,r)=>{t[r]=Io(e)}),t}if(lr(i)){let t={};return Object.keys(i).forEach(e=>{t[e]=Io(i[e])}),t}return i}var ys=i=>{let t=[];if(rt(i))t=[...i];else if(Ae(i)){let e=document.getElementById(i);e&&t.push(e)}else i&&t.push(i);return t},i_=i=>Ae(i)?document.getElementById(i):i,FT=i=>{let t=h=>h<10?`0${h}`:`${h}`,e=i.getFullYear(),r=i.getMonth()+1,o=i.getDate(),s=t(i.getHours()),a=t(i.getMinutes()),d=t(i.getSeconds());return`${e}/${r}/${o} ${s}:${a}:${d}`},nd=()=>FT(new Date);function pr(i,{keysToInclude:t,keysToExclude:e}){try{if(rt(i))return`[${i.map(a=>pr(a,{keysToInclude:t,keysToExclude:e})).join(",")}]`;if(!$t(i)||!rt(t)&&!rt(e))return JSON.stringify(i);let r={},o=new Set(t),s=new Set(e);return Object.keys(i).forEach(a=>{(s.size===0&&o.has(a)||o.size===0&&!s.has(a))&&(r[a]=$t(i[a])||rt(i[a])?JSON.parse(pr(i[a],{keysToExclude:e,keysToInclude:t})):i[a])}),JSON.stringify(r)}catch(r){return"{}"}}function ad(i,t=!1){let e=[];return Object.keys(i).forEach(r=>{t===i[r]&&e.push(r)}),pr(i,{keysToInclude:e})}function o_(i){return i.replace(/[\u4e00-\u9fa5]/g,"aa").length}var cd=()=>{var i,t,e,r;return(i=window.screen)!=null&&i.orientation?!!((r=(e=(t=window.screen)==null?void 0:t.orientation)==null?void 0:e.type)!=null&&r.includes("portrait")):window.orientation===0||window.orientation===180},As=i=>v(void 0,null,function*(){return new Promise((t,e)=>{let r;if(Ae(i))r=new Image,r.crossOrigin="anonymous",r.src=i;else if(r=i,r.complete){t(r);return}r.onload=()=>t(r),r.onerror=()=>{e(new de({code:Y.INVALID_PARAMETER,message:`load image failed, url: ${i}`}))}})}),dd=i=>{let t=i.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]<<0},ia=i=>(Object.keys(i).forEach(t=>{Fe(i[t])&&(t.startsWith("uint")||t.startsWith("int"))?i[t]=Math.floor(i[t]):($t(i[t])||rt(i[t]))&&ia(i[t])}),i);function oa(i,t){return new Promise(e=>{let r=setTimeout(e,i);t&&t(r)})}function ud(i,t){let e=null;return function(...r){return e||(e=i.apply(t||this,r),e.finally(()=>e=null),e)}}function _i({url:i,body:t,method:e="POST",timeout:r,priority:o}){return new Promise((s,a)=>{if("fetch"in window)return fetch(i,{method:e,body:t,priority:o}).then(h=>h.text()).then(h=>{try{s({data:JSON.parse(h)})}catch(p){s({data:h})}},a);let d=new XMLHttpRequest;d.onreadystatechange=()=>{if(d.readyState===4)if(d.status>=200&&d.status<300)try{let h=JSON.parse(d.response);s({data:h})}catch(h){s({data:d.response})}else a({status:d.status,statusText:d.statusText||"request failed!"})},d.timeout=r||5e3,d.open(e,i,!0),d.send(t)})}function mp(i){return v(this,null,function*(){let t=ge(),e=JSON.stringify(i);try{if(!CompressionStream||e.length<=2800)return e;let o=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),d=yield(yield(yield new Response(o)).blob()).arrayBuffer();return V.debug(`compressJSON ${e.length} -> ${d.byteLength} ${ge()-t}ms`),d}catch(r){return e}})}var $T=Object.prototype.hasOwnProperty;var Ui=i=>typeof i=="function",s_=i=>typeof i=="undefined";var n_=i=>typeof i=="boolean";var hp=i=>i.isRemote;var HT=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function a_(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(HT(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if($T.call(i,t))return!1;return!0}}return!1}var WT=0,GT=1,c_=2;function jT({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:a}){return function(...d){let{retries:h=5,timeout:p=1e3}=t,T=0,y=-1,R=WT,N=(j,W)=>v(this,null,function*(){let F=a||this;try{let Ie=yield i.apply(F,d);T>0&&s&&s.call(this,T),T=0,j(Ie)}catch(Ie){let Bt=()=>{clearTimeout(y),T=0,R=c_,W(Ie)},Xe=()=>{R!==c_&&T<(Ui(h)?h():h)?(T++,R=GT,Ui(r)&&r.call(this,T,Bt),y=window.setTimeout(()=>{y=-1,N(j,W)},Ui(p)?p(T):p)):(Bt(),Ui(o)&&o.call(this,Ie))};Ui(e)?e.call(this,{error:Ie,retry:Xe,reject:W,retryFuncArgs:d,retriedCount:T}):Xe()}});return new Promise(N)}}var Vi=jT;var bs=class{constructor(t){l(this,"userId");l(this,"remoteUserId");l(this,"id");l(this,"sdkAppId");l(this,"type");l(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=n_(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}createChild(t){return Object.setPrototypeOf(t,this)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${r?`|${r}`:""}]`),V.log(t,e,s_(this.userId)||a_(this.userId),this.userId,this.sdkAppId)}info(...t){this.log(2,t)}debug(...t){this.log(1,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}};var ks={};li(ks,{ANDROID_VERSION:()=>gp,CHROME_MAJOR_VERSION:()=>gi,CHROME_VERSION:()=>Cd,EDGE_VERSION:()=>pd,EDG_MAJOR_VERSION:()=>Tp,EDG_VERSION:()=>md,FIREFOX_MAJOR_VERSION:()=>Ep,FIREFOX_VERSION:()=>ld,HUAWEI_VERSION:()=>Ad,IE_VERSION:()=>QT,IOS_MAIN_VERSION:()=>ir,IOS_VERSION:()=>$i,IPADQQB_VERSION:()=>Sd,IS_ANDROID:()=>ft,IS_ANDROID_WEBVIEW:()=>vp,IS_ANY_SAFARI:()=>Bi,IS_CHROME:()=>Os,IS_CHROME_OS:()=>Ip,IS_CHROMIUM_BASE:()=>bo,IS_EDG:()=>Cs,IS_EDGE:()=>Rs,IS_ELECTRON:()=>ZT,IS_FIREFOX:()=>Cr,IS_HEADLESS_CHROME:()=>bp,IS_HONOR:()=>Ap,IS_HUAWEI:()=>yp,IS_HUAWEIBROWSER:()=>ha,IS_IE:()=>p_,IS_IE8:()=>XT,IS_IOS:()=>Ht,IS_IOS_13_OR_14:()=>Cp,IS_IOS_15_1:()=>Rp,IS_IPAD:()=>sa,IS_IPADQQB:()=>la,IS_IPAD_PRO:()=>_p,IS_IPHONE:()=>yo,IS_IPOD:()=>l_,IS_LINUX:()=>pa,IS_LOCAL:()=>wr,IS_MAC:()=>Nr,IS_MACQQB:()=>ua,IS_MIBROWSER:()=>ma,IS_MQQB:()=>ws,IS_NATIVE_ANDROID:()=>JT,IS_OLD_ANDROID:()=>zT,IS_OPPOBROWSER:()=>xs,IS_SAFARI:()=>Wt,IS_SAFARI_15_1:()=>KT,IS_SAMSUNGBROWSER:()=>fa,IS_SOGOU:()=>aa,IS_SOGOUM:()=>na,IS_TBS:()=>Dr,IS_UCBROWSER:()=>Sp,IS_VIVOBROWSER:()=>Ms,IS_WECHAT:()=>Ds,IS_WIN:()=>Ao,IS_WQQB:()=>da,IS_WX:()=>YT,IS_X5MQQB:()=>Ns,IS_XWEB:()=>ca,MACQQB_VERSION:()=>Id,MI_VERSION:()=>yd,MQQB_VERSION:()=>vs,OPPO_VERSION:()=>vd,SAFARI_VERSION:()=>Fi,SAMSUNG_VERSION:()=>bd,SOGOUM_VERSION:()=>hd,SOGOU_VERSION:()=>fd,TBS_VERSION:()=>_d,UA_DATA_STRING:()=>Rr,USER_AGENT:()=>rr,VIVO_VERSION:()=>Rd,WECHAT_VERSION:()=>Ed,WQQB_VERSION:()=>Td,XWEB_VERSION:()=>gd,browserInfo:()=>jr,getBrowserInfo:()=>m_,getChromeMajorVersion:()=>_a,getDeviceModel:()=>Ea,getOSName:()=>Ps,getOSNumber:()=>Ta,getOSString:()=>vo,getOSType:()=>Np,getTerminalType:()=>Dp,getUserAgentData:()=>ga,isLocalStorageEnabled:()=>Ei});var rr=typeof navigator=="undefined"?"":navigator.userAgent,Ee=i=>new RegExp(i,"i").test(rr),ht=i=>{if(Ee(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=rr.match(t);if(e&&e[1])return e[1]}return""},fp=i=>{if(Ee(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=rr.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},d_=/AppleWebKit\/([\d.]+)/i.exec(rr),qT=d_?parseFloat(d_[1]):NaN,sa=Ee("iPad"),_p=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ee("Macintosh"),yo=Ee("iPhone")&&!sa,l_=Ee("iPod"),Ht=yo||sa||l_||_p,ft=Ee("Android"),gp=function(){if(ft){let i=rr.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(i){let t=i[1]&&parseFloat(i[1]),e=i[2]&&parseFloat(i[2]);if(t&&e)return parseFloat(`${i[1]}.${i[2]}`);if(t)return t}}return NaN}(),zT=ft&&Ee("webkit")&&gp<2.3,JT=ft&&gp<5&&qT<537,Cr=Ee("Firefox"),ld=ht("Firefox"),Ep=fp("Firefox"),Rs=Ee("Edge"),pd=ht("Edge"),Cs=Ee("Edg"),md=ht("Edg"),Tp=fp("Edg"),na=Ee("SogouMobileBrowser"),hd=ht("SogouMobileBrowser"),aa=Ee("MetaSr\\s"),fd=ht("MetaSr\\s"),Dr=Ee("TBS"),_d=ht("TBS"),ca=Ee("XWEB"),gd=ht("XWEB"),XT=Ee("MSIE\\s8\\.0"),p_=Ee("MSIE\\/\\d+"),QT=function(){if(p_){let i=/MSIE\s(\d+)\.\d/.exec(rr),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(rr)&&/rv:11.0/.test(rr)&&(t=11),t}return NaN}(),Ds=Ee("(micromessenger|webbrowser)"),Ed=ht("MicroMessenger"),Ns=!Dr&&Ee("MQQBrowser")&&Ee("COVC"),ws=!Dr&&Ee("MQQBrowser")&&!Ee("COVC"),vs=ws||Ns?ht("MQQBrowser"):"",da=!Dr&&Ee(" QQBrowser"),Td=ht(" QQBrowser"),ua=!Dr&&Ee("QQBrowserLite"),Id=ht("QQBrowserLite"),la=!Dr&&Ee("MQBHD"),Sd=ht("MQBHD"),Ao=Ee("Windows"),Nr=!Ht&&Ee("MAC OS X"),pa=!ft&&Ee("Linux"),Ip=Ee("CrOS"),YT=Ee("MicroMessenger"),Sp=Ee("UCBrowser"),ZT=Ee("Electron"),ma=Ee("MiuiBrowser"),yd=ht("MiuiBrowser"),ha=Ee("HuaweiBrowser"),yp=Ee("Huawei")||Ee("HUAWEI"),Ap=Ee("Honor")||Ee("HONOR"),Ad=ht("HuaweiBrowser"),fa=Ee("SamsungBrowser"),bd=ht("SamsungBrowser"),xs=Ee("HeyTapBrowser"),vd=ht("HeyTapBrowser"),Ms=Ee("VivoBrowser"),Rd=ht("VivoBrowser"),_a=()=>fp("Chrome"),bo=Ee("Chrome"),Os=!Rs&&!aa&&!na&&!Dr&&!ca&&!Cs&&!da&&!ma&&!ha&&!fa&&!xs&&!Ms&&bo,bp=Ee("HeadlessChrome"),gi=_a(),Cd=ht("Chrome"),Wt=!bo&&!ws&&!Ns&&!ua&&!la&&Ee("Safari"),Bi=Wt||Ht,Fi=ht("Version"),vp=/Android.*(wv|.0.0.0)/.test(rr),$i=(()=>{if(_p)return Fi;if(Ht){let i=rr.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})(),ir=Number($i.split(".")[0]),KT=Fi==="15.1",Rp=$i==="15.1",Cp=(()=>{let i=Number($i.split(".")[0]);return i===14||i===13})(),wr=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Ei=(()=>{let i;return()=>{if(typeof i=="undefined")try{i=!!window.localStorage}catch(t){i=!1}return i}})(),jr=m_();function m_(){let i=new Map([[Cr,["Firefox",ld]],[Cs,["Edg",md]],[Os,["Chrome",Cd]],[Wt,["Safari",Fi]],[Dr,["TBS",_d]],[ca,["XWEB",gd]],[Ds&&yo,["WeChat",Ed]],[da,["QQ(Win)",Td]],[ws,["QQ(Mobile)",vs]],[Ns,["QQ(Mobile X5)",vs]],[ua,["QQ(Mac)",Id]],[la,["QQ(iPad)",Sd]],[ma,["MI",yd]],[ha,["HW",Ad]],[fa,["Samsung",bd]],[xs,["OPPO",vd]],[Ms,["VIVO",Rd]],[Rs,["EDGE",pd]],[na,["SogouMobile",hd]],[aa,["Sogou",fd]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var Be=null,Rr="";function ga(){return v(this,null,function*(){if(Be)return Be;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return Be=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),Be&&!Rr&&(Rr=`UAData: ${Be.platform}/${Be.platformVersion}`,Be.architecture&&Be.bitness&&(Rr+=` ${Be.architecture}/${Be.bitness}`),Be.mobile&&(Rr+=" mobile"),Be.model&&(Rr+=` model: ${Be.model}`),Be.fullVersionList&&(Rr+=` ${Be.fullVersionList.filter(i=>i.brand!=="Not/A)Brand").map(i=>`${i.brand}/${i.version}`).join(",")}`)),Be}catch(i){return null}})}function Ea(){return(Be==null?void 0:Be.model)||""}var u_=new Map([[ft,"Android"],[Ht,"iOS"],[Ao,"Windows"],[Nr,"MacOS"],[pa,"Linux"],[Ip,"ChromeOS"]]),Ps=function(){return u_.get(!0)?u_.get(!0):Be?Be.platform:"unknown"};function Ta(){return Ao?1:ft?2:Nr?3:Ht?4:pa?5:Ip?6:0}var vo=()=>{let i=Ps();return i+=`/${jr.name}/${Wt?jr.version:jr.version.split(".")[0]}`,Be!=null&&Be.platformVersion&&(i+=`/${Be.platformVersion}`),Be!=null&&Be.architecture&&(i+=`/${Be.architecture}`),i};function Dp(){return ft?4:yo?2:sa?3:Nr?12:Ao?5:pa?13:1}function Np(){return ft?"Android":yo?"iPhone":sa?"iPad":Nr?"Mac":Ao?"Windows":pa?"Linux":"unknown"}var f_=Pi(Hi(),1),rI=new f_.default,B=rI;var Ro=(se=>(se.ROOM_DESTROY="1",se.JOIN_START="21",se.JOIN_SCHEDULE_SUCCESS="22",se.JOIN_SIGNAL_CONNECTION_START="23",se.JOIN_SIGNAL_CONNECTION_END="24",se.JOIN_SEND_CMD="25",se.JOIN_RECEIVED_CMD_RES="26",se.JOIN_SUCCESS="27",se.JOIN_FAILED="28",se.LEAVE_START="51",se.LEAVE_SEND_CMD="52",se.LEAVE_SUCCESS="53",se.PUBLISH_START="61",se.SEND_FIRST_VIDEO_FRAME="62",se.PUBLISH_FAILED="63",se.SUBSCRIBE_START="81",se.SUBSCRIBE_SUCCESS="82",se.SUBSCRIBE_FAILED="84",se.UNSUBSCRIBE_SUCCESS="83",se.LOCAL_TRACK_CAPTURE_START="101",se.LOCAL_TRACK_CAPTURE_SUCCESS="102",se.LOCAL_TRACK_CAPTURE_FAILED="103",se.LOCAL_TRACK_PUBLISHED="104",se.LOCAL_TRACK_UNPUBLISHED="105",se.LOCAL_TRACK_REPLACED="106",se.SWITCH_DEVICE_SUCCESS="107",se.TRACK_MUTED="108",se.TRACK_UNMUTED="109",se.REMOTE_TRACK_SUBSCRIBED="110",se.REMOTE_TRACK_UNSUBSCRIBED="111",se.LOCAL_TRACK_RECAPTURE="112",se.PLAY_TRACK_START="151",se.PLAYER_STATE_CHANGED="152",se.VIDEO_LOADED_DATA="153",se.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",se.SIGNAL_CONNECTION_STATE_CHANGED="201",se.PEER_CONNECTION_STATE_CHANGED="202",se.SINGLE_CONNECTION_STAT="203",se.SPC_RECONNECTED="204",se.HEARTBEAT_REPORT="251",se.RECEIVED_PUBLISHED_USER_LIST="252",se.REMOTE_PUBLISH_STATE_CHANGED="253",se.AUDIO_LEVEL_INTERVAL="260",se.NETWORK_QUALITY="261",se.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",se.QUALITY_LIMITATION_CHANGED="263",se.LOG="264",se))(Ro||{});var O=Ro;var iI="%cTRTC%c%s",oI="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",sI="display: inline",nI=!(Ht||ft||bp),xp=class{constructor(){l(this,"_isEnableUploadLog",!0);l(this,"_localJoinedUser",new Map);l(this,"_queue",[]);l(this,"_timeoutId",-1);l(this,"_logLevel",1);l(this,"_logLevelToUpload",2);!fs&&!qn&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){B.on(O.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;((e=t==null?void 0:t.config)==null?void 0:e.logLevelToUpload)&&br[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),B.on(O.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),B.once(O.JOIN_FAILED,()=>{this.startUpload()}),B.on(O.LEAVE_SUCCESS,({room:t})=>{this.deleteJoinedUser(t.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let e=0;for(;e<this._queue.length&&e!==50;e++){let r=this._queue[e];if(r.forAllJoinedClients)this._localJoinedUser.forEach(({userId:o,sdkAppId:s})=>{t.map.has(o)?t.map.get(o).logs.push(r):t.map.set(o,{userId:o,sdkAppId:s,logs:[r]})});else if(Ae(r.userId)&&Fe(r.sdkAppId)){let{userId:o,sdkAppId:s}=r;t.map.has(o)?t.map.get(o).logs.push(r):t.map.set(o,{userId:o,sdkAppId:s,logs:[r]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,e)),t}upload(){return v(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:e}=this.getLogsToUpload();if(t.size===0)return;try{let o=[...t.values()];for(let s=0;s<o.length;s++){let{userId:a,sdkAppId:d,logs:h}=o[s];yield this.uploadLogWithRetry(JSON.stringify({timestamp:zc(),sdkAppId:String(d),userId:a,version:Ke,log:h.map(p=>p.log).join(`
|
|
4
|
-
`)}),d),h.forEach(p=>p.uploaded=!0)}}catch(o){}let r=e.filter(o=>!o.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e){return Vi({retryFunction:()=>_i({url:fi(e,ki.LOG),body:t,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:r})=>{r()}})()}getPrefix(t){let e=new Date;e.setTime(jn());let r=String(e.getMilliseconds());return"padStart"in String.prototype&&(r=r.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${r}] <${br[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){L(br[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(Ae(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}log(t,e,r=!0,o,s){var h;e.unshift(this.getPrefix(t));let a={log:e.reduce((p,T)=>`${p} ${this.logChunkToString(T)}`.trim(),""),level:t,userId:o,sdkAppId:s,forAllJoinedClients:r};if(B.emit(O.LOG,{log:a}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(a),t<this._logLevel)return;let d=((h=br[t])==null?void 0:h.toLowerCase())||"info";nI?console[d](iI,oI,sI,...e):console[d](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){return new bs(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;br[r]&&(this._logLevelToUpload=r)}getQueue(){return this._queue}},V=new xp;var aI=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let t=Math.random()*16|0;return(i=="x"?t:t&3|8).toString(16)})},Sa=aI;var Mp=class{constructor(){l(this,"_prefix","TRTC");l(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!Ei())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(r=>{if(r.startsWith(this._prefix))try{let o=localStorage.getItem(r);if(!o)return!1;let s=JSON.parse(o);if(s&&s.expiresIn<Date.now())return!0}catch(o){return!1}return!1}).forEach(r=>localStorage.removeItem(r))}doFlush(){if(!!Ei())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){V.warn(t)}}getItem(t){if(!Ei())return null;try{let e=localStorage.getItem(this.getRealKey(t));if(!e)return null;let r=JSON.parse(e);return r&&r.expiresIn>=Date.now()?r.value:null}catch(e){V.warn(e)}}setItem(t,e){if(!!Ei())try{let r={expiresIn:Date.now()+Xc,value:e};this._queue.set(this.getRealKey(t),r)}catch(r){V.warn(r)}}deleteItem(t){if(!Ei())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return V.warn(e),!1}}clear(){if(!!Ei())try{localStorage.clear()}catch(t){V.warn(t)}}},Ls=new Mp;var Gi={};li(Gi,{HTTPS_API:()=>bI,IS_GET_CAPABILITIES_SUPPORTED:()=>tm,IS_GET_SETTINGS_SUPPORTED:()=>Fs,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>OI,IS_INSERTABLE_STREAM_SUPPORTED:()=>wa,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>UI,IS_RTC_RTP_SENDER_SUPPORTED:()=>Na,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>W_,IS_SEI_SUPPORTED:()=>xa,IS_SPC_SUPPORTED:()=>NI,basis:()=>kI,capabilityCheck:()=>im,checkSystemRequirementsInternal:()=>$d,decodeSupportStatus:()=>L_,encodeSupportStatus:()=>Zp,getBrowserInfo:()=>Bd,getDisplayResolution:()=>U_,isAddTransceiverSupported:()=>H_,isBrowserSupported:()=>Kp,isGetReceiversSupported:()=>CI,isGetSendersSupported:()=>$_,isGetTransceiversSupported:()=>DI,isGetUserMediaSupported:()=>V_,isMediaDevicesSupported:()=>Fd,isMediaSessionSupported:()=>j_,isMediaStreamTrackProcessorSupported:()=>em,isReplaceTrackSupported:()=>xI,isRequestVideoFrameCallbackSupported:()=>Mo,isSIMDSupported:()=>PI,isScreenCaptureApiAvailable:()=>Ca,isSelectedCandidatePair:()=>vI,isSetParametersSupported:()=>MI,isSmallStreamAPISupported:()=>F_,isSmallStreamSupported:()=>Da,isStopTransceiverSupported:()=>wI,isTRTCSupported:()=>yI,isUnifiedPlanDefault:()=>RI,isUsedInHttpProtocol:()=>Ai,isWebAudioSupported:()=>B_,isWebCodecSupported:()=>G_,isWebCodecsSupported:()=>k_,isWebRTCSupported:()=>rm,isWebTransportSupported:()=>q_});var Gp={};li(Gp,{AUDIO_LEVEL_SCALE:()=>Ii,AudioCodecPipelineType:()=>Pd,AudioDecoderDowngradeState:()=>kp,AudioPlayerMode:()=>Bp,AudioType:()=>Up,BASIC_TYPE:()=>No,BannedReason:()=>Fp,CONNECTION_CLOSED_REASON:()=>g_,ClientEvent:()=>Op,CodecType:()=>b_,ConnectionEvent:()=>__,ConnectionState:()=>wd,DECODE_FAILED_ERROR_CODE:()=>Wp,FacingMode:()=>Md,LeaveReason:()=>$p,LocalTrackEvent:()=>Nd,MULTI_VIDEO_DATA_TYPE:()=>Ti,MediaType:()=>St,MediaTypeLabel:()=>cI,MonitorEventId:()=>Aa,MutedFlag:()=>T_,NetworkQualityValue:()=>y_,PlayerState:()=>Us,ReceiveMode:()=>A_,RemoteStreamType:()=>qr,RemoteTrackEvent:()=>Vs,RoomEvent:()=>Co,SceneNumber:()=>Pp,StreamEvent:()=>E_,StreamType:()=>S_,SubscribeMediaType:()=>ya,TRACK_ACTION:()=>I_,TRACK_KIND:()=>Lp,TrackEvent:()=>Wi,UserRole:()=>Gt,UserRoleNumber:()=>Do,VideoCodec:()=>Hp,VideoCodecPipelineType:()=>ba,VideoContentHint:()=>va,VideoDecoderDowngradeState:()=>xd,VideoPlayerMode:()=>Od,VideoType:()=>Vp});var __=(W=>(W.TRACK_ADDED="track-added",W.TRACK_UPDATED="track-updated",W.TRACK_SUBSCRIBED="track-subscribed",W.STREAM_ADDED="stream-added",W.STREAM_REMOVED="stream-removed",W.STREAM_UPDATED="stream-updated",W.STREAM_PUBLISHED="stream-published",W.STREAM_SUBSCRIBED="stream-subscribed",W.STREAM_UNSUBSCRIBED="stream-unsubscribed",W.STATE_CHANGED="state-changed",W.ERROR="error",W.CONNECTION_STATE_CHANGED="connection-state-changed",W.FIREWALL_RESTRICTION="firewall-restriction",W.SEI_MESSAGE="sei-message",W.CLOSED="closed",W))(__||{}),g_=(a=>(a.REMOTE_LEAVE="remote user exitRoom",a.REMOTE_UNPUBLISH="remote user unpublished",a.LOCAL_LEAVE="you exitRoom",a.LOCAL_UNPUBLISH="you unpublished",a.LOCAL_UNSUBSCRIBE="you unsubscribed",a.SWITCH_ROLE="you switch role to audience",a))(g_||{}),Op=(F=>(F.STREAM_ADDED="stream-added",F.STREAM_REMOVED="stream-removed",F.STREAM_UPDATED="stream-updated",F.STREAM_SUBSCRIBED="stream-subscribed",F.CONNECTION_STATE_CHANGED="connection-state-changed",F.PEER_JOIN="peer-join",F.PEER_LEAVE="peer-leave",F.MUTE_AUDIO="mute-audio",F.MUTE_VIDEO="mute-video",F.UNMUTE_AUDIO="unmute-audio",F.UNMUTE_VIDEO="unmute-video",F.CLIENT_BANNED="client-banned",F.NETWORK_QUALITY="network-quality",F.AUDIO_VOLUME="audio-volume",F.SEI_MESSAGE="sei-message",F.ERROR="error",F))(Op||{}),E_=(s=>(s.PLAYER_STATE_CHANGED="player-state-changed",s.SCREEN_SHARING_STOPPED="screen-sharing-stopped",s.CONNECTION_STATE_CHANGED="connection-state-changed",s.DEVICE_AUTO_RECOVERED="device-auto-recovered",s.ERROR="error",s))(E_||{}),Nd=(a=>(a.DEVICE_AUTO_RECOVERED="1",a.DEVICE_RECOVER_FAILED="5",a.DEVICE_CHANGED="2",a.ERROR="3",a.PUBLISH_STATE_CHANGED="4",a.ENCODE_FAILED="6",a))(Nd||{}),Us=(r=>(r.PAUSED="PAUSED",r.PLAYING="PLAYING",r.STOPPED="STOPPED",r))(Us||{}),Co=(F=>(F.PEER_JOIN="peer-join",F.PEER_LEAVE="peer-leave",F.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",F.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",F.BANNED="banned",F.NETWORK_QUALITY="network-quality",F.AUDIO_VOLUME="audio-volume",F.SEI_MESSAGE="sei-message",F.ERROR="error",F.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",F.REMOTE_PUBLISHED="remote-published",F.REMOTE_UNPUBLISHED="remote-unpublished",F.FIREWALL_RESTRICTION="firewall-restriction",F.HEARTBEAT_REPORT="heartbeat-report",F.CUSTOM_MESSAGE="custom-message",F.LAYER_DATA="layerData",F))(Co||{}),Wi=(a=>(a.PLAYER_STATE_CHANGED="player-state-changed",a.MUTE="mute",a.UNMUTE="unmute",a.ERROR="error",a.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",a.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",a))(Wi||{}),Vs=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(Vs||{}),T_=(d=>(d[d.VIDEO=1]="VIDEO",d[d.SMALL=2]="SMALL",d[d.AUX=4]="AUX",d[d.AUDIO=8]="AUDIO",d[d.VIDEO_MUTE=16]="VIDEO_MUTE",d[d.AUX_MUTE=32]="AUX_MUTE",d[d.AUDIO_MUTE=64]="AUDIO_MUTE",d))(T_||{}),Pp=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(Pp||{}),Do=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Do||{}),Gt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(Gt||{}),wd=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(wd||{}),kp=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(kp||{}),xd=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(xd||{}),Lp=(r=>(r.AUDIO="audio",r.VIDEO="video",r.AUXILIARY="auxVideo",r))(Lp||{}),I_=(e=>(e.ADD="add",e.REMOVE="remove",e))(I_||{}),St=(s=>(s[s.NULL=0]="NULL",s[s.AUDIO=1]="AUDIO",s[s.AUX_VIDEO=2]="AUX_VIDEO",s[s.BIG_VIDEO=4]="BIG_VIDEO",s[s.SMALL_VIDEO=8]="SMALL_VIDEO",s))(St||{}),cI={[1]:"audio",[2]:"auxVideo",[4]:"video"},Up=(t=>(t[t.opus=111]="opus",t))(Up||{}),Vp=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(Vp||{}),S_=(e=>(e.Big="big",e.Small="small",e))(S_||{}),qr=(e=>(e.Main="main",e.Aux="auxiliary",e))(qr||{}),Ti=(s=>(s[s.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",s[s.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",s[s.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",s[s.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",s[s.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",s))(Ti||{}),Aa=(z=>(z[z.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",z[z.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",z[z.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",z[z.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",z[z.MUTE_AUDIO=32772]="MUTE_AUDIO",z[z.MUTE_VIDEO=32773]="MUTE_VIDEO",z[z.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",z[z.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",z[z.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",z[z.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",z[z.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",z[z.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",z[z.SWITCH_CAMERA=32780]="SWITCH_CAMERA",z[z.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",z[z.REPLACE_VIDEO=32782]="REPLACE_VIDEO",z[z.REPLACE_AUDIO=32783]="REPLACE_AUDIO",z[z.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",z[z.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",z[z.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",z[z.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",z[z.JOIN=32788]="JOIN",z[z.LEAVE=32789]="LEAVE",z[z.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",z[z.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",z[z.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",z[z.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",z[z.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",z[z.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",z[z.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",z[z.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",z[z.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",z[z.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",z[z.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",z[z.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",z[z.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",z[z.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",z[z.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",z[z.PUBLISH_AUX=32805]="PUBLISH_AUX",z[z.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",z[z.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",z[z.VIDEO_ENCODER=4004]="VIDEO_ENCODER",z[z.VIDEO_DECODER=4005]="VIDEO_DECODER",z))(Aa||{}),y_=(d=>(d[d.UNKNOWN=0]="UNKNOWN",d[d.EXCELLENT=1]="EXCELLENT",d[d.GOOD=2]="GOOD",d[d.POOR=3]="POOR",d[d.BAD=4]="BAD",d[d.VERY_BAD=5]="VERY_BAD",d[d.DISCONNECTED=6]="DISCONNECTED",d))(y_||{}),A_=(o=>(o[o.MANUAL=0]="MANUAL",o[o.AUTO_AUDIO=1]="AUTO_AUDIO",o[o.AUTO_VIDEO=2]="AUTO_VIDEO",o[o.AUTO_ALL=3]="AUTO_ALL",o))(A_||{}),Md=(e=>(e.user="user",e.environment="environment",e))(Md||{}),Od=(r=>(r[r.ELEMENT=0]="ELEMENT",r[r.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",r[r.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",r))(Od||{}),Bp=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(Bp||{}),Fp=(o=>(o.BANNED="banned",o.KICK="kick",o.USER_TIME_OUT="user_time_out",o.ROOM_DISBAND="room_disband",o))(Fp||{}),$p=(p=>(p[p.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",p[p.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",p[p.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",p[p.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",p[p.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",p[p.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",p[p.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",p[p.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",p[p.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",p))($p||{}),Ii=1e8,ya=class{constructor(){this.mediaType=0}set audio(t){t?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(t){t?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(t){t?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(t){t?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},No=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(No||{}),Hp=(r=>(r.H264="h264",r.H265="h265",r.VP8="vp8",r))(Hp||{}),ba=(o=>(o[o.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",o[o.DUMP=1]="DUMP",o[o.SEI=2]="SEI",o[o.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",o))(ba||{}),Pd=(o=>(o[o.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",o[o.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",o[o.DUMP=2]="DUMP",o[o.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",o))(Pd||{}),b_=(r=>(r.WebRTC="webrtc",r.WebCodecs="webcodecs",r.WebAssembly="webassembly",r))(b_||{}),Wp=(y=>(y[y.SUCCESS=0]="SUCCESS",y[y.FAILED=1]="FAILED",y[y.WEBCODEC_INIT=2]="WEBCODEC_INIT",y[y.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",y[y.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",y[y.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",y[y.WASM_INIT=6]="WASM_INIT",y[y.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",y[y.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",y[y.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",y[y.TEST=10]="TEST",y))(Wp||{}),va=(o=>(o.NONE="",o.DETAIL="detail",o.MOTION="motion",o.TEXT="text",o))(va||{});var it={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},jt={AVOID_REPEATED_CALL(i){return`previous ${i.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${o}' must be type of ${s} when calling ${e}(), received type: ${mt(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${o}' must be instanceof ${s} when calling ${e}(), received type: ${mt(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_MIN({key:i,rule:t,fnName:e,value:r}){return`the min value of ${i||t.name} is ${t.min}, received: ${r}.`},INVALID_PARAMETER_MAX({key:i,rule:t,fnName:e,value:r}){return`the max value of ${i||t.name} is ${t.max}, received: ${r}.`},API_CALL_TIMEOUT(i){return`${i.commandDesc||i.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(i){return`SignalChannel setup failure: (errorCode: ${i.errorCode}, errorMsg: ${i.errorMsg} }).`},ERROR_MESSAGE(i){let t=`${i.type} failed`;return i.message&&(t=`${t}: ${i.message}.`),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(i){return`exchange sdp failed ${i.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(i){return`'${i}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(i){return`'${i}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:i,code:t}){return`Failed to join room - ${i} code: ${t}`},REJOIN_ROOM_FAILED(i){return`reJoin room: ${i.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:`no permission to publish() under live/${"audience"}, please call switchRole("${"anchor"}") firstly before publish().`,INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(i){return`duplicate ${i} stream publishing, please unpublish your prev ${i} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:i,userId:t,streamType:e}){return`failed to subscribe ${t} ${e} stream, reason: ${i}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:`role could only be set to a value as ${"anchor"} or ${"audience"}.`,INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(i){return`switchRole failed, errCode: ${i.code} errMsg: ${i.message}.`},CLIENT_BANNED(i){return`client was banned because of ${i.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(i){return`startPublishCDNStream failed, errMsg: ${i.message}.`},STOP_PUBLISH_CDN_FAILED(i){return`stopPublishCDNStream failed, errMsg: ${i.message}.`},INVALID_STREAM_ID(i){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(i){return`cannot replace ${i.kind} track because stream has not ${i.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(i){return`startMixTranscode failed, errMsg: ${i.message}.`},STOP_MIX_TRANSCODE_FAILED(i){return`stopMixTranscode failed, errMsg: ${i.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(i){return`'${i}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:i,fnName:t})=>`'${i}' is not found in the document object when calling ${t}().`,INVALID_ELEMENT_ID_TYPE:({key:i,fnName:t,type:e})=>`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`,PLAY_FAILED:i=>`${i.media} play failed, browser exception: ${i.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(i){return`${i}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(i){return`${i.signalResponse} failed, response code is ${i.code} , errMsg: ${i.message}.`},CATCH_HANDLER_ERROR({name:i,event:t}){return`an error was caught in ${i}.on('${t}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:i}){return`experimental api ${i} does not exist.`},REPEAT_JOIN:i=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:i}){return`failed to call ${i}() because client was destroyed.`},SEI_NOT_SUPPORT:i=>`not support to sendSEIMessage${i===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:i,name:t,timesInSecond:e,maxSizeInSecond:r})=>`api ${t} call ${i?"size":"times"} is over ${i?`${r} bytes`:e} in a second.`,CONNECTION_ABORTED(i){return`connection aborted due to: ${i}`},API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`Subscribe ${i.userId} ${i.streamType} stream aborted, reason: remote user ${i.userId} unpublished stream.`:t=`API aborted, reason: ${i.message}`,t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:i=>`'streamType' is required when 'userId' is not '*', calling ${i}()`};var v_=(i,t)=>t?`${Fr}/${i}/${t}`:`${Fr}/${i}/index.html`;var dI=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let i=localStorage==null?void 0:localStorage.getItem(ip);if(i){i=JSON.parse(i);let t=document.createElement("script");t.type="text/javascript",t.text=i.message,document.body.appendChild(t);let e=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:r}}return{}};function ot(i){let{key:t,data:e,link:r,addDocLink:o=!0}=i,s="",a="",d="";Ve(jt[t])?s=jt[t](e):Ae(jt[t])&&(s=jt[t]);let{TRTC_ERROR_INFO:h,TRTC_ERROR_LINK:p}=dI();r?d=`${r.className}.html#${r.fnName}`:p&&p[t]&&(Ve(p[t])?d=p[t](e):Ae(p[t])&&(d=p[t]));let T=s;return vr()&&(h&&h[t]&&(Ve(h[t])?a=h[t](e):Ae(h[t])&&(a=h[t])),a&&(o?T=`${a}
|
|
3
|
+
`}});var O_=jn(yi=>{var wo=w_(),gI=M_();yi.write=gI;yi.parse=wo.parse;yi.parseParams=wo.parseParams;yi.parseFmtpConfig=wo.parseFmtpConfig;yi.parsePayloads=wo.parsePayloads;yi.parseRemoteCandidates=wo.parseRemoteCandidates;yi.parseImageAttributes=wo.parseImageAttributes;yi.parseSimulcastStreamList=wo.parseSimulcastStreamList});var Bf=(P=>(P[P.INVALID_PARAMETER=4096]="INVALID_PARAMETER",P[P.INVALID_OPERATION=4097]="INVALID_OPERATION",P[P.NOT_SUPPORTED=4098]="NOT_SUPPORTED",P[P.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",P[P.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",P[P.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",P[P.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",P[P.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",P[P.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",P[P.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",P[P.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",P[P.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",P[P.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",P[P.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",P[P.CLIENT_BANNED=16448]="CLIENT_BANNED",P[P.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",P[P.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",P[P.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",P[P.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",P[P.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",P[P.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",P[P.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",P[P.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",P[P.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",P[P.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",P[P.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",P[P.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",P[P.API_CALL_ABORTED=16461]="API_CALL_ABORTED",P[P.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",P[P.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",P[P.UNKNOWN=65535]="UNKNOWN",P))(Bf||{}),Y=Bf;var ZE=function(i){for(let t in Y)if(Y[t]===i)return t;return"UNKNOWN"},Zl=class extends Error{constructor({name:e="RtcError",message:r,code:o=Y.UNKNOWN,extraCode:s=0,constraint:a}){let d=`<${ZE(o)} 0x${o.toString(16)}>`,h=`${r}${a?` constraint: ${a}`:""}${r!=null&&r.includes(d)?"":` ${d}`}`;super(h);l(this,"code");l(this,"extraCode");l(this,"message");l(this,"originMessage");l(this,"name");l(this,"constraint");this.code=o,this.extraCode=s,this.name=e,this.message=h,this.constraint=a,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},de=Zl;var OA=new Date().getTime(),KE=0;var qn=function(){return new Date().getTime()+KE},zc=function(){let i=new Date;return i.setTime(qn()),i.toLocaleString()};var Gr={};li(Gr,{bytes2ms:()=>Xf,convertObjectNumberToInt:()=>oa,copyProperties:()=>Jf,deepClone:()=>Io,deepMerge:()=>Wr,delay:()=>sa,fibonacci:()=>So,formatedTime:()=>nd,getConstructorName:()=>ra,getContainerFromElement:()=>i_,getEnv:()=>jf,getInternalVersion:()=>t_,getLoggerUrl:()=>fi,getMuteStateFromFlag:()=>ia,getNetworkType:()=>ea,getNumNetworkType:()=>id,getReconnectionTimeout:()=>Yf,getStringByteLength:()=>o_,getTurnServer:()=>r_,getUint32Version:()=>dd,getValueType:()=>mt,getViewListFromView:()=>ys,glog:()=>ta,ipv4ToUint32:()=>Ss,isArray:()=>rt,isAudioWorkletSupported:()=>e_,isBoolean:()=>nt,isConstructor:()=>Is,isEmpty:()=>sd,isFunction:()=>Ve,isLangChinese:()=>vr,isMediaStreamTrack:()=>Zf,isNumber:()=>Fe,isObject:()=>lr,isOverseaSdkAppId:()=>Kn,isPlainObject:()=>$t,isPortrait:()=>cd,isPromise:()=>Li,isRemoteTrack:()=>Kf,isString:()=>Ae,isUndefined:()=>L,loadImage:()=>As,ms2bytes:()=>Qf,ms2samples:()=>pp,performanceNow:()=>ge,promiseAny:()=>od,samples2ms:()=>lp,setNetworkType:()=>zf,stringify:()=>pr,stringifyIncludeValue:()=>ad,throttlePromise:()=>ud});var up={};li(up,{AUDIO_MUTE_BIT:()=>Kc,AUDIO_STAT_BIT:()=>gs,AUX_STAT_BIT:()=>Xn,AUX_STREAM_MSID:()=>lT,BACKEND_ENV:()=>Zc,BASE_DOC_URL:()=>Fr,BASE_HOST:()=>Ff,CAPABILITIES_KEYS:()=>rd,CLASS_NAME:()=>kT,CLOUD_CONSOLE_URL:()=>iT,CROSS_ROOM_BIT:()=>dT,DATA_FREEZE_TIMING:()=>td,DEFAULT_ASSETS_URL:()=>Jc,DOC_URL:()=>oT,DTLS_STATE_UNKNOWN:()=>ST,ENV_NAME:()=>pi,EXCHANGE_SDP_TIMEOUT:()=>CT,INTERVAL:()=>To,IS_WORKER:()=>fs,IS_WORKLET:()=>zn,KIBANA_EVENT:()=>mi,LOCAL_STREAM_PUBLISH_STATE:()=>Hf,LOGGER_CMD_TYPE:()=>ki,LOGGER_DOMAIN:()=>tp,LOGGER_DOMAIN_OVERSEA:()=>rp,LOG_LEVEL:()=>br,LOG_LEVEL_NAME:()=>UT,MAIN_STREAM_MSID:()=>uT,MAX_RTT:()=>Yn,MICROPHONE_COMMUNICATIONS:()=>LT,MICROPHONE_DEFAULT:()=>Eo,MUTE_ALL_BIT:()=>cT,NAME:()=>D,NETWORK_TYPE:()=>go,NOT_SUPPORTED_H264:()=>NT,PAUSED_RETRY_COUNT:()=>ap,PEERCONNECTION_CONNECTING_TIMEOUT:()=>OT,PEER_CONNECTION_STATE:()=>yT,PEER_LEAVE_REASON:()=>Wf,RAF:()=>dp,RECOVER_CAPTURE_INTERVAL:()=>Es,REMOTE_STREAM_TYPE_AUX:()=>mT,REMOTE_STREAM_TYPE_MAIN:()=>pT,RENDER_FREEZE_TIMING:()=>wT,RIC:()=>cp,SCHEDULE_DOMAIN:()=>hi,SCHEDULE_TIMEOUT:()=>PT,SDP_SEMANTICS_PLAN_B:()=>DT,SDP_SEMANTICS_UNIFIED_PLAN:()=>np,SECOND_HOST:()=>tT,SIGNAL_PING_PONG_INTERVAL:()=>nT,SIGNAL_PING_TIMEOUT:()=>sT,SIGNAL_RECONNECTION_COUNT:()=>bT,SMALL_STAT_BIT:()=>op,SPEAKER_DEFAULT:()=>Qn,STORAGE_EXPIRES_TIME:()=>Xc,STREAM_TYPE_BIG:()=>xT,STREAM_TYPE_SMALL:()=>MT,SUBSCRIBE_SMALL_RETRY_COUNT:()=>VT,SYNC_USER_LIST_INTERVAL:()=>vT,Scene:()=>Hr,THIRD_HOST:()=>rT,TIMEOUT:()=>Ts,TRANSPORT_DIRECTION:()=>aT,TRTC_ERROR_ASSISTANCE:()=>ip,TRTC_QUALITY_BAD:()=>ET,TRTC_QUALITY_DISCONNECTED:()=>IT,TRTC_QUALITY_EXCELLENT:()=>fT,TRTC_QUALITY_GOOD:()=>_T,TRTC_QUALITY_POOR:()=>gT,TRTC_QUALITY_UNKNOWN:()=>hT,TRTC_QUALITY_VERY_BAD:()=>TT,UPDATE_OFFER_TIMEOUT:()=>RT,VIDEO_MUTE_BIT:()=>ed,VIDEO_STAT_BIT:()=>_s,audioProfileMap:()=>Qc,getRetryCount:()=>AT,getScriptDir:()=>eT,innerVersion:()=>Kl,loggerProxy:()=>Jn,screenProfileMap:()=>Yc,setLoggerProxy:()=>_o,setRetryCount:()=>sp,setVersion:()=>ep,version:()=>Ke,videoProfileMap:()=>$r});var Kl="4.15.00.1600",Ke="5.0.0";function ep(i){Ke=i;let[t,e,r]=i.split(".").map(o=>parseInt(o,10));Kl=`${t}.${Math.min(15,e)}.${Math.min(15,r)}.${e.toString().padStart(2,"0")}${r.toString().padStart(2,"0")}`}var fs=typeof importScripts!="undefined",zn=typeof registerProcessor!="undefined",eT=()=>{let i=fs?self.location.href:document.currentScript.src;return i.substring(0,i.lastIndexOf("/")+1)},Jn="",_o=i=>Jn=i,Ff="web.sdk.qcloud.com",tT="web.sdk.tencent.cn",rT="web.sdk.cloud.tencent.cn",iT="https://console.cloud.tencent.com/trtc",Fr=`https://${Ff}/trtc/webrtc/v5/doc`,Jc="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",oT=`${Fr}/zh-cn/`,tp="https://yun.tim.qq.com",rp="https://apisgp.my-imcloud.com",ip="trtc_error_assistance",ki={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},pi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},br=(a=>(a[a.TRACE=0]="TRACE",a[a.DEBUG=1]="DEBUG",a[a.INFO=2]="INFO",a[a.WARN=3]="WARN",a[a.ERROR=4]="ERROR",a[a.NONE=5]="NONE",a))(br||{}),sT=18e3,nT=2e3,go={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Xc=7*24*3600*1e3,Qc={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},$r={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},Yc={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},D={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},aT={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Zc={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Hr=(e=>(e.LIVE="live",e.RTC="rtc",e))(Hr||{}),_s=1,op=2,Xn=4,gs=8,Kc=64,ed=16,cT=112,dT=128,uT="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",lT="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",pT=D.MAIN,mT=D.AUXILIARY,hT=0,fT=1,_T=2,gT=3,ET=4,TT=5,IT=6,ST="unknown",yT={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},$f=1/0;function sp(i){$f=i}function AT(){return $f}var bT=30,mi={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},vT=1e4,RT=1e4,CT=1e4,np="unified-plan",DT="plan-b",NT=1028,Hf=(r=>(r[r.UNPUBLISH=-1]="UNPUBLISH",r[r.PUBLISHING=0]="PUBLISHING",r[r.PUBLISHED=1]="PUBLISHED",r))(Hf||{}),td=500,wT=1e3,xT=D.BIG,MT=D.SMALL,OT=10*1e3,hi={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},PT=2e3,kT={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},ap=5,Eo="default",Qn=Eo,LT="communications",UT=Object.keys(br),Wf=["normal leave","timeout leave","kick","role change"],VT=10,Es=2e3,cp="ric",dp="raf",To="interval",Ts="timeout",rd=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Yn=10*1e3;var jf=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Kn=i=>Number(i)<14e8,fi=function(i,t){let e;Jn?e=Jn:e=Kn(i)?rp:tp;let r=Math.floor(Math.random()*Gn(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${i}&cmdtype=${t}`},Zn="unknown";function ea(){if(Zn!=="unknown")return Zn;let{userAgent:i,connection:t}=navigator,e=(i.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let r=t&&t.type&&t.type.toLowerCase(),o=t&&t.effectiveType&&t.effectiveType.toLowerCase();return o==="slow-2"&&(o="2g"),r&&(Zn=qf(r,o)),Zn}function qf(i,t){if(go[i])return i;switch(i){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function zf(i){Zn=qf(i)}function id(){return go[ea()]}function Jf(i,t){for(let e of Reflect.ownKeys(t))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let r=Object.getOwnPropertyDescriptor(t,e)||"";Object.defineProperty(i,e,r)}return i}function Xf(i,t=48e3){return lp(i/4,t)}function lp(i,t=48e3){return i*1e3/t}function Qf(i,t=48e3){return pp(i,t)*4}function pp(i,t=48e3){return i*t/1e3}var ta=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},vr=()=>{let i=navigator.language;return i=i.substring(0,2),i==="zh"},$t=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function So(i,t=1,e=1){return i<=1?e:So(i-1,e,t+e)}function Yf(i){return i>8?30*1e3:So(i)*1e3}function mt(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Ve=i=>typeof i=="function",L=i=>typeof i=="undefined",Ae=i=>typeof i=="string",Fe=i=>typeof i=="number",nt=i=>typeof i=="boolean",lr=i=>mt(i)==="object",rt=i=>mt(i)==="array",Zf=i=>mt(i)==="MediaStreamTrack".toLowerCase(),Kf=i=>i.isRemote,Li=i=>mt(i)==="promise",Is=i=>Ve(i)&&i.prototype.constructor===i,ra=i=>Is(i)?i.prototype.constructor.name:"",e_=typeof AudioWorkletNode!="undefined";function od(i){return new Promise((t,e)=>{let r=[];i.forEach(o=>{o.then(t).catch(s=>{r.push(s),r.length===i.length&&e(r)})})})}function ge(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Gf=i=>+i<10?`0${i}`:i,t_=i=>{let t=i.match(/^\d+\.\d+\.\d+/)[0];if(!t)return i;let e=t.split("."),r=Gf(e[1])+Gf(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${r}`},BT=Object.prototype.hasOwnProperty,{toString:VA}=Object.prototype;function sd(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if($t(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(BT.call(i,t))return!1;return!0}}return!1}function ia(i,t){return{userId:t,hasAudio:!!(i&gs),hasVideo:!!(i&_s),hasAuxiliary:!!(i&Xn),hasSmall:!!(i&op),audioMuted:!!(i&Kc),videoMuted:!!(i&ed),audioAvailable:!!(i&gs)&&!(i&Kc),videoAvailable:!!(i&_s)&&!(i&ed)}}function r_(i){let t={urls:i.url.startsWith("turn:")||i.url.startsWith("turns:")?i.url:`turn:${i.url}`};return!L(i.username)&&!L(i.credential)&&(t.username=i.username,t.credential=i.credential,t.credentialType="password",L(i.credentialType)||(t.credentialType=i.credentialType)),t}function Ss(i,t=!0){if(!Ae(i))return 0;let e=i.split(".");return t?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var Wr=function(i,t,e,r){if(!(lr(i)&&lr(t)))return 0;let o=0,s=Object.keys(t),a;for(let d=0,h=s.length;d<h;d++)if(a=s[d],!(L(t[a])||e&&e.includes(a)))if(lr(i[a])&&lr(t[a]))o+=Wr(i[a],t[a],e,r);else{if(r&&r.includes(t[a]))continue;i[a]!==t[a]&&(i[a]=Io(t[a]),o+=1)}return o};function Io(i){if(rt(i)){let t=[];return i.forEach((e,r)=>{t[r]=Io(e)}),t}if(lr(i)){let t={};return Object.keys(i).forEach(e=>{t[e]=Io(i[e])}),t}return i}var ys=i=>{let t=[];if(rt(i))t=[...i];else if(Ae(i)){let e=document.getElementById(i);e&&t.push(e)}else i&&t.push(i);return t},i_=i=>Ae(i)?document.getElementById(i):i,FT=i=>{let t=h=>h<10?`0${h}`:`${h}`,e=i.getFullYear(),r=i.getMonth()+1,o=i.getDate(),s=t(i.getHours()),a=t(i.getMinutes()),d=t(i.getSeconds());return`${e}/${r}/${o} ${s}:${a}:${d}`},nd=()=>FT(new Date);function pr(i,{keysToInclude:t,keysToExclude:e}){try{if(rt(i))return`[${i.map(a=>pr(a,{keysToInclude:t,keysToExclude:e})).join(",")}]`;if(!$t(i)||!rt(t)&&!rt(e))return JSON.stringify(i);let r={},o=new Set(t),s=new Set(e);return Object.keys(i).forEach(a=>{(s.size===0&&o.has(a)||o.size===0&&!s.has(a))&&(r[a]=$t(i[a])||rt(i[a])?JSON.parse(pr(i[a],{keysToExclude:e,keysToInclude:t})):i[a])}),JSON.stringify(r)}catch(r){return"{}"}}function ad(i,t=!1){let e=[];return Object.keys(i).forEach(r=>{t===i[r]&&e.push(r)}),pr(i,{keysToInclude:e})}function o_(i){return i.replace(/[\u4e00-\u9fa5]/g,"aa").length}var cd=()=>{var i,t,e,r;return(i=window.screen)!=null&&i.orientation?!!((r=(e=(t=window.screen)==null?void 0:t.orientation)==null?void 0:e.type)!=null&&r.includes("portrait")):window.orientation===0||window.orientation===180},As=i=>v(void 0,null,function*(){return new Promise((t,e)=>{let r;if(Ae(i))r=new Image,r.crossOrigin="anonymous",r.src=i;else if(r=i,r.complete){t(r);return}r.onload=()=>t(r),r.onerror=()=>{e(new de({code:Y.INVALID_PARAMETER,message:`load image failed, url: ${i}`}))}})}),dd=i=>{let t=i.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]<<0},oa=i=>(Object.keys(i).forEach(t=>{Fe(i[t])&&(t.startsWith("uint")||t.startsWith("int"))?i[t]=Math.floor(i[t]):($t(i[t])||rt(i[t]))&&oa(i[t])}),i);function sa(i,t){return new Promise(e=>{let r=setTimeout(e,i);t&&t(r)})}function ud(i,t){let e=null;return function(...r){return e||(e=i.apply(t||this,r),e.finally(()=>e=null),e)}}function _i({url:i,body:t,method:e="POST",timeout:r,priority:o}){return new Promise((s,a)=>{if("fetch"in window)return fetch(i,{method:e,body:t,priority:o}).then(h=>h.text()).then(h=>{try{s({data:JSON.parse(h)})}catch(p){s({data:h})}},a);let d=new XMLHttpRequest;d.onreadystatechange=()=>{if(d.readyState===4)if(d.status>=200&&d.status<300)try{let h=JSON.parse(d.response);s({data:h})}catch(h){s({data:d.response})}else a({status:d.status,statusText:d.statusText||"request failed!"})},d.timeout=r||5e3,d.open(e,i,!0),d.send(t)})}function mp(i){return v(this,null,function*(){let t=ge(),e=JSON.stringify(i);try{if(!CompressionStream||e.length<=2800)return e;let o=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),d=yield(yield(yield new Response(o)).blob()).arrayBuffer();return V.debug(`compressJSON ${e.length} -> ${d.byteLength} ${ge()-t}ms`),d}catch(r){return e}})}var $T=Object.prototype.hasOwnProperty;var Ui=i=>typeof i=="function",s_=i=>typeof i=="undefined";var n_=i=>typeof i=="boolean";var hp=i=>i.isRemote;var HT=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function a_(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(HT(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if($T.call(i,t))return!1;return!0}}return!1}var WT=0,GT=1,c_=2;function jT({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:a}){return function(...d){let{retries:h=5,timeout:p=1e3}=t,T=0,y=-1,R=WT,N=(j,W)=>v(this,null,function*(){let F=a||this;try{let Ie=yield i.apply(F,d);T>0&&s&&s.call(this,T),T=0,j(Ie)}catch(Ie){let Bt=()=>{clearTimeout(y),T=0,R=c_,W(Ie)},Xe=()=>{R!==c_&&T<(Ui(h)?h():h)?(T++,R=GT,Ui(r)&&r.call(this,T,Bt),y=window.setTimeout(()=>{y=-1,N(j,W)},Ui(p)?p(T):p)):(Bt(),Ui(o)&&o.call(this,Ie))};Ui(e)?e.call(this,{error:Ie,retry:Xe,reject:W,retryFuncArgs:d,retriedCount:T}):Xe()}});return new Promise(N)}}var Vi=jT;var bs=class{constructor(t){l(this,"userId");l(this,"remoteUserId");l(this,"id");l(this,"sdkAppId");l(this,"type");l(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=n_(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}createChild(t){return Object.setPrototypeOf(t,this)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${r?`|${r}`:""}]`),V.log(t,e,s_(this.userId)||a_(this.userId),this.userId,this.sdkAppId)}info(...t){this.log(2,t)}debug(...t){this.log(1,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}};var ks={};li(ks,{ANDROID_VERSION:()=>gp,CHROME_MAJOR_VERSION:()=>gi,CHROME_VERSION:()=>Cd,EDGE_VERSION:()=>pd,EDG_MAJOR_VERSION:()=>Tp,EDG_VERSION:()=>md,FIREFOX_MAJOR_VERSION:()=>Ep,FIREFOX_VERSION:()=>ld,HUAWEI_VERSION:()=>Ad,IE_VERSION:()=>QT,IOS_MAIN_VERSION:()=>ir,IOS_VERSION:()=>$i,IPADQQB_VERSION:()=>Sd,IS_ANDROID:()=>ft,IS_ANDROID_WEBVIEW:()=>vp,IS_ANY_SAFARI:()=>Bi,IS_CHROME:()=>Os,IS_CHROME_OS:()=>Ip,IS_CHROMIUM_BASE:()=>bo,IS_EDG:()=>Cs,IS_EDGE:()=>Rs,IS_ELECTRON:()=>ZT,IS_FIREFOX:()=>Cr,IS_HEADLESS_CHROME:()=>bp,IS_HONOR:()=>Ap,IS_HUAWEI:()=>yp,IS_HUAWEIBROWSER:()=>fa,IS_IE:()=>p_,IS_IE8:()=>XT,IS_IOS:()=>Ht,IS_IOS_13_OR_14:()=>Cp,IS_IOS_15_1:()=>Rp,IS_IPAD:()=>na,IS_IPADQQB:()=>pa,IS_IPAD_PRO:()=>_p,IS_IPHONE:()=>yo,IS_IPOD:()=>l_,IS_LINUX:()=>ma,IS_LOCAL:()=>wr,IS_MAC:()=>Nr,IS_MACQQB:()=>la,IS_MIBROWSER:()=>ha,IS_MQQB:()=>ws,IS_NATIVE_ANDROID:()=>JT,IS_OLD_ANDROID:()=>zT,IS_OPPOBROWSER:()=>xs,IS_SAFARI:()=>Wt,IS_SAFARI_15_1:()=>KT,IS_SAMSUNGBROWSER:()=>_a,IS_SOGOU:()=>ca,IS_SOGOUM:()=>aa,IS_TBS:()=>Dr,IS_UCBROWSER:()=>Sp,IS_VIVOBROWSER:()=>Ms,IS_WECHAT:()=>Ds,IS_WIN:()=>Ao,IS_WQQB:()=>ua,IS_WX:()=>YT,IS_X5MQQB:()=>Ns,IS_XWEB:()=>da,MACQQB_VERSION:()=>Id,MI_VERSION:()=>yd,MQQB_VERSION:()=>vs,OPPO_VERSION:()=>vd,SAFARI_VERSION:()=>Fi,SAMSUNG_VERSION:()=>bd,SOGOUM_VERSION:()=>hd,SOGOU_VERSION:()=>fd,TBS_VERSION:()=>_d,UA_DATA_STRING:()=>Rr,USER_AGENT:()=>rr,VIVO_VERSION:()=>Rd,WECHAT_VERSION:()=>Ed,WQQB_VERSION:()=>Td,XWEB_VERSION:()=>gd,browserInfo:()=>jr,getBrowserInfo:()=>m_,getChromeMajorVersion:()=>ga,getDeviceModel:()=>Ta,getOSName:()=>Ps,getOSNumber:()=>Ia,getOSString:()=>vo,getOSType:()=>Np,getTerminalType:()=>Dp,getUserAgentData:()=>Ea,isLocalStorageEnabled:()=>Ei});var rr=typeof navigator=="undefined"?"":navigator.userAgent,Ee=i=>new RegExp(i,"i").test(rr),ht=i=>{if(Ee(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=rr.match(t);if(e&&e[1])return e[1]}return""},fp=i=>{if(Ee(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=rr.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},d_=/AppleWebKit\/([\d.]+)/i.exec(rr),qT=d_?parseFloat(d_[1]):NaN,na=Ee("iPad"),_p=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ee("Macintosh"),yo=Ee("iPhone")&&!na,l_=Ee("iPod"),Ht=yo||na||l_||_p,ft=Ee("Android"),gp=function(){if(ft){let i=rr.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(i){let t=i[1]&&parseFloat(i[1]),e=i[2]&&parseFloat(i[2]);if(t&&e)return parseFloat(`${i[1]}.${i[2]}`);if(t)return t}}return NaN}(),zT=ft&&Ee("webkit")&&gp<2.3,JT=ft&&gp<5&&qT<537,Cr=Ee("Firefox"),ld=ht("Firefox"),Ep=fp("Firefox"),Rs=Ee("Edge"),pd=ht("Edge"),Cs=Ee("Edg"),md=ht("Edg"),Tp=fp("Edg"),aa=Ee("SogouMobileBrowser"),hd=ht("SogouMobileBrowser"),ca=Ee("MetaSr\\s"),fd=ht("MetaSr\\s"),Dr=Ee("TBS"),_d=ht("TBS"),da=Ee("XWEB"),gd=ht("XWEB"),XT=Ee("MSIE\\s8\\.0"),p_=Ee("MSIE\\/\\d+"),QT=function(){if(p_){let i=/MSIE\s(\d+)\.\d/.exec(rr),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(rr)&&/rv:11.0/.test(rr)&&(t=11),t}return NaN}(),Ds=Ee("(micromessenger|webbrowser)"),Ed=ht("MicroMessenger"),Ns=!Dr&&Ee("MQQBrowser")&&Ee("COVC"),ws=!Dr&&Ee("MQQBrowser")&&!Ee("COVC"),vs=ws||Ns?ht("MQQBrowser"):"",ua=!Dr&&Ee(" QQBrowser"),Td=ht(" QQBrowser"),la=!Dr&&Ee("QQBrowserLite"),Id=ht("QQBrowserLite"),pa=!Dr&&Ee("MQBHD"),Sd=ht("MQBHD"),Ao=Ee("Windows"),Nr=!Ht&&Ee("MAC OS X"),ma=!ft&&Ee("Linux"),Ip=Ee("CrOS"),YT=Ee("MicroMessenger"),Sp=Ee("UCBrowser"),ZT=Ee("Electron"),ha=Ee("MiuiBrowser"),yd=ht("MiuiBrowser"),fa=Ee("HuaweiBrowser"),yp=Ee("Huawei")||Ee("HUAWEI"),Ap=Ee("Honor")||Ee("HONOR"),Ad=ht("HuaweiBrowser"),_a=Ee("SamsungBrowser"),bd=ht("SamsungBrowser"),xs=Ee("HeyTapBrowser"),vd=ht("HeyTapBrowser"),Ms=Ee("VivoBrowser"),Rd=ht("VivoBrowser"),ga=()=>fp("Chrome"),bo=Ee("Chrome"),Os=!Rs&&!ca&&!aa&&!Dr&&!da&&!Cs&&!ua&&!ha&&!fa&&!_a&&!xs&&!Ms&&bo,bp=Ee("HeadlessChrome"),gi=ga(),Cd=ht("Chrome"),Wt=!bo&&!ws&&!Ns&&!la&&!pa&&Ee("Safari"),Bi=Wt||Ht,Fi=ht("Version"),vp=/Android.*(wv|.0.0.0)/.test(rr),$i=(()=>{if(_p)return Fi;if(Ht){let i=rr.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})(),ir=Number($i.split(".")[0]),KT=Fi==="15.1",Rp=$i==="15.1",Cp=(()=>{let i=Number($i.split(".")[0]);return i===14||i===13})(),wr=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Ei=(()=>{let i;return()=>{if(typeof i=="undefined")try{i=!!window.localStorage}catch(t){i=!1}return i}})(),jr=m_();function m_(){let i=new Map([[Cr,["Firefox",ld]],[Cs,["Edg",md]],[Os,["Chrome",Cd]],[Wt,["Safari",Fi]],[Dr,["TBS",_d]],[da,["XWEB",gd]],[Ds&&yo,["WeChat",Ed]],[ua,["QQ(Win)",Td]],[ws,["QQ(Mobile)",vs]],[Ns,["QQ(Mobile X5)",vs]],[la,["QQ(Mac)",Id]],[pa,["QQ(iPad)",Sd]],[ha,["MI",yd]],[fa,["HW",Ad]],[_a,["Samsung",bd]],[xs,["OPPO",vd]],[Ms,["VIVO",Rd]],[Rs,["EDGE",pd]],[aa,["SogouMobile",hd]],[ca,["Sogou",fd]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var Be=null,Rr="";function Ea(){return v(this,null,function*(){if(Be)return Be;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return Be=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),Be&&!Rr&&(Rr=`UAData: ${Be.platform}/${Be.platformVersion}`,Be.architecture&&Be.bitness&&(Rr+=` ${Be.architecture}/${Be.bitness}`),Be.mobile&&(Rr+=" mobile"),Be.model&&(Rr+=` model: ${Be.model}`),Be.fullVersionList&&(Rr+=` ${Be.fullVersionList.filter(i=>i.brand!=="Not/A)Brand").map(i=>`${i.brand}/${i.version}`).join(",")}`)),Be}catch(i){return null}})}function Ta(){return(Be==null?void 0:Be.model)||""}var u_=new Map([[ft,"Android"],[Ht,"iOS"],[Ao,"Windows"],[Nr,"MacOS"],[ma,"Linux"],[Ip,"ChromeOS"]]),Ps=function(){return u_.get(!0)?u_.get(!0):Be?Be.platform:"unknown"};function Ia(){return Ao?1:ft?2:Nr?3:Ht?4:ma?5:Ip?6:0}var vo=()=>{let i=Ps();return i+=`/${jr.name}/${Wt?jr.version:jr.version.split(".")[0]}`,Be!=null&&Be.platformVersion&&(i+=`/${Be.platformVersion}`),Be!=null&&Be.architecture&&(i+=`/${Be.architecture}`),i};function Dp(){return ft?4:yo?2:na?3:Nr?12:Ao?5:ma?13:1}function Np(){return ft?"Android":yo?"iPhone":na?"iPad":Nr?"Mac":Ao?"Windows":ma?"Linux":"unknown"}var f_=Pi(Hi(),1),rI=new f_.default,B=rI;var Ro=(se=>(se.ROOM_DESTROY="1",se.JOIN_START="21",se.JOIN_SCHEDULE_SUCCESS="22",se.JOIN_SIGNAL_CONNECTION_START="23",se.JOIN_SIGNAL_CONNECTION_END="24",se.JOIN_SEND_CMD="25",se.JOIN_RECEIVED_CMD_RES="26",se.JOIN_SUCCESS="27",se.JOIN_FAILED="28",se.LEAVE_START="51",se.LEAVE_SEND_CMD="52",se.LEAVE_SUCCESS="53",se.PUBLISH_START="61",se.SEND_FIRST_VIDEO_FRAME="62",se.PUBLISH_FAILED="63",se.SUBSCRIBE_START="81",se.SUBSCRIBE_SUCCESS="82",se.SUBSCRIBE_FAILED="84",se.UNSUBSCRIBE_SUCCESS="83",se.LOCAL_TRACK_CAPTURE_START="101",se.LOCAL_TRACK_CAPTURE_SUCCESS="102",se.LOCAL_TRACK_CAPTURE_FAILED="103",se.LOCAL_TRACK_PUBLISHED="104",se.LOCAL_TRACK_UNPUBLISHED="105",se.LOCAL_TRACK_REPLACED="106",se.SWITCH_DEVICE_SUCCESS="107",se.TRACK_MUTED="108",se.TRACK_UNMUTED="109",se.REMOTE_TRACK_SUBSCRIBED="110",se.REMOTE_TRACK_UNSUBSCRIBED="111",se.LOCAL_TRACK_RECAPTURE="112",se.PLAY_TRACK_START="151",se.PLAYER_STATE_CHANGED="152",se.VIDEO_LOADED_DATA="153",se.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",se.SIGNAL_CONNECTION_STATE_CHANGED="201",se.PEER_CONNECTION_STATE_CHANGED="202",se.SINGLE_CONNECTION_STAT="203",se.SPC_RECONNECTED="204",se.HEARTBEAT_REPORT="251",se.RECEIVED_PUBLISHED_USER_LIST="252",se.REMOTE_PUBLISH_STATE_CHANGED="253",se.AUDIO_LEVEL_INTERVAL="260",se.NETWORK_QUALITY="261",se.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",se.QUALITY_LIMITATION_CHANGED="263",se.LOG="264",se))(Ro||{});var O=Ro;var iI="%cTRTC%c%s",oI="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",sI="display: inline",nI=!(Ht||ft||bp),xp=class{constructor(){l(this,"_isEnableUploadLog",!0);l(this,"_localJoinedUser",new Map);l(this,"_queue",[]);l(this,"_timeoutId",-1);l(this,"_logLevel",1);l(this,"_logLevelToUpload",2);!fs&&!zn&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){B.on(O.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;((e=t==null?void 0:t.config)==null?void 0:e.logLevelToUpload)&&br[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),B.on(O.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),B.once(O.JOIN_FAILED,()=>{this.startUpload()}),B.on(O.LEAVE_SUCCESS,({room:t})=>{this.deleteJoinedUser(t.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let e=0;for(;e<this._queue.length&&e!==50;e++){let r=this._queue[e];if(r.forAllJoinedClients)this._localJoinedUser.forEach(({userId:o,sdkAppId:s})=>{t.map.has(o)?t.map.get(o).logs.push(r):t.map.set(o,{userId:o,sdkAppId:s,logs:[r]})});else if(Ae(r.userId)&&Fe(r.sdkAppId)){let{userId:o,sdkAppId:s}=r;t.map.has(o)?t.map.get(o).logs.push(r):t.map.set(o,{userId:o,sdkAppId:s,logs:[r]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,e)),t}upload(){return v(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:e}=this.getLogsToUpload();if(t.size===0)return;try{let o=[...t.values()];for(let s=0;s<o.length;s++){let{userId:a,sdkAppId:d,logs:h}=o[s];yield this.uploadLogWithRetry(JSON.stringify({timestamp:zc(),sdkAppId:String(d),userId:a,version:Ke,log:h.map(p=>p.log).join(`
|
|
4
|
+
`)}),d),h.forEach(p=>p.uploaded=!0)}}catch(o){}let r=e.filter(o=>!o.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e){return Vi({retryFunction:()=>_i({url:fi(e,ki.LOG),body:t,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:r})=>{r()}})()}getPrefix(t){let e=new Date;e.setTime(qn());let r=String(e.getMilliseconds());return"padStart"in String.prototype&&(r=r.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${r}] <${br[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){L(br[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(Ae(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}log(t,e,r=!0,o,s){var h;e.unshift(this.getPrefix(t));let a={log:e.reduce((p,T)=>`${p} ${this.logChunkToString(T)}`.trim(),""),level:t,userId:o,sdkAppId:s,forAllJoinedClients:r};if(B.emit(O.LOG,{log:a}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(a),t<this._logLevel)return;let d=((h=br[t])==null?void 0:h.toLowerCase())||"info";nI?console[d](iI,oI,sI,...e):console[d](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){return new bs(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;br[r]&&(this._logLevelToUpload=r)}getQueue(){return this._queue}},V=new xp;var aI=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let t=Math.random()*16|0;return(i=="x"?t:t&3|8).toString(16)})},ya=aI;var Mp=class{constructor(){l(this,"_prefix","TRTC");l(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!Ei())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(r=>{if(r.startsWith(this._prefix))try{let o=localStorage.getItem(r);if(!o)return!1;let s=JSON.parse(o);if(s&&s.expiresIn<Date.now())return!0}catch(o){return!1}return!1}).forEach(r=>localStorage.removeItem(r))}doFlush(){if(!!Ei())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){V.warn(t)}}getItem(t){if(!Ei())return null;try{let e=localStorage.getItem(this.getRealKey(t));if(!e)return null;let r=JSON.parse(e);return r&&r.expiresIn>=Date.now()?r.value:null}catch(e){V.warn(e)}}setItem(t,e){if(!!Ei())try{let r={expiresIn:Date.now()+Xc,value:e};this._queue.set(this.getRealKey(t),r)}catch(r){V.warn(r)}}deleteItem(t){if(!Ei())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return V.warn(e),!1}}clear(){if(!!Ei())try{localStorage.clear()}catch(t){V.warn(t)}}},Ls=new Mp;var Gi={};li(Gi,{HTTPS_API:()=>bI,IS_GET_CAPABILITIES_SUPPORTED:()=>tm,IS_GET_SETTINGS_SUPPORTED:()=>Fs,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>OI,IS_INSERTABLE_STREAM_SUPPORTED:()=>xa,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>UI,IS_RTC_RTP_SENDER_SUPPORTED:()=>wa,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>W_,IS_SEI_SUPPORTED:()=>Ma,IS_SPC_SUPPORTED:()=>NI,basis:()=>kI,capabilityCheck:()=>im,checkSystemRequirementsInternal:()=>$d,decodeSupportStatus:()=>L_,encodeSupportStatus:()=>Zp,getBrowserInfo:()=>Bd,getDisplayResolution:()=>U_,isAddTransceiverSupported:()=>H_,isBrowserSupported:()=>Kp,isGetReceiversSupported:()=>CI,isGetSendersSupported:()=>$_,isGetTransceiversSupported:()=>DI,isGetUserMediaSupported:()=>V_,isMediaDevicesSupported:()=>Fd,isMediaSessionSupported:()=>j_,isMediaStreamTrackProcessorSupported:()=>em,isReplaceTrackSupported:()=>xI,isRequestVideoFrameCallbackSupported:()=>Mo,isSIMDSupported:()=>PI,isScreenCaptureApiAvailable:()=>Da,isSelectedCandidatePair:()=>vI,isSetParametersSupported:()=>MI,isSmallStreamAPISupported:()=>F_,isSmallStreamSupported:()=>Na,isStopTransceiverSupported:()=>wI,isTRTCSupported:()=>yI,isUnifiedPlanDefault:()=>RI,isUsedInHttpProtocol:()=>Ai,isWebAudioSupported:()=>B_,isWebCodecSupported:()=>G_,isWebCodecsSupported:()=>k_,isWebRTCSupported:()=>rm,isWebTransportSupported:()=>q_});var Gp={};li(Gp,{AUDIO_LEVEL_SCALE:()=>Ii,AudioCodecPipelineType:()=>Pd,AudioDecoderDowngradeState:()=>kp,AudioPlayerMode:()=>Bp,AudioType:()=>Up,BASIC_TYPE:()=>No,BannedReason:()=>Fp,CONNECTION_CLOSED_REASON:()=>g_,ClientEvent:()=>Op,CodecType:()=>b_,ConnectionEvent:()=>__,ConnectionState:()=>wd,DECODE_FAILED_ERROR_CODE:()=>Wp,FacingMode:()=>Md,LeaveReason:()=>$p,LocalTrackEvent:()=>Nd,MULTI_VIDEO_DATA_TYPE:()=>Ti,MediaType:()=>St,MediaTypeLabel:()=>cI,MonitorEventId:()=>ba,MutedFlag:()=>T_,NetworkQualityValue:()=>y_,PlayerState:()=>Us,ReceiveMode:()=>A_,RemoteStreamType:()=>qr,RemoteTrackEvent:()=>Vs,RoomEvent:()=>Co,SceneNumber:()=>Pp,StreamEvent:()=>E_,StreamType:()=>S_,SubscribeMediaType:()=>Aa,TRACK_ACTION:()=>I_,TRACK_KIND:()=>Lp,TrackEvent:()=>Wi,UserRole:()=>Gt,UserRoleNumber:()=>Do,VideoCodec:()=>Hp,VideoCodecPipelineType:()=>va,VideoContentHint:()=>Ra,VideoDecoderDowngradeState:()=>xd,VideoPlayerMode:()=>Od,VideoType:()=>Vp});var __=(W=>(W.TRACK_ADDED="track-added",W.TRACK_UPDATED="track-updated",W.TRACK_SUBSCRIBED="track-subscribed",W.STREAM_ADDED="stream-added",W.STREAM_REMOVED="stream-removed",W.STREAM_UPDATED="stream-updated",W.STREAM_PUBLISHED="stream-published",W.STREAM_SUBSCRIBED="stream-subscribed",W.STREAM_UNSUBSCRIBED="stream-unsubscribed",W.STATE_CHANGED="state-changed",W.ERROR="error",W.CONNECTION_STATE_CHANGED="connection-state-changed",W.FIREWALL_RESTRICTION="firewall-restriction",W.SEI_MESSAGE="sei-message",W.CLOSED="closed",W))(__||{}),g_=(a=>(a.REMOTE_LEAVE="remote user exitRoom",a.REMOTE_UNPUBLISH="remote user unpublished",a.LOCAL_LEAVE="you exitRoom",a.LOCAL_UNPUBLISH="you unpublished",a.LOCAL_UNSUBSCRIBE="you unsubscribed",a.SWITCH_ROLE="you switch role to audience",a))(g_||{}),Op=(F=>(F.STREAM_ADDED="stream-added",F.STREAM_REMOVED="stream-removed",F.STREAM_UPDATED="stream-updated",F.STREAM_SUBSCRIBED="stream-subscribed",F.CONNECTION_STATE_CHANGED="connection-state-changed",F.PEER_JOIN="peer-join",F.PEER_LEAVE="peer-leave",F.MUTE_AUDIO="mute-audio",F.MUTE_VIDEO="mute-video",F.UNMUTE_AUDIO="unmute-audio",F.UNMUTE_VIDEO="unmute-video",F.CLIENT_BANNED="client-banned",F.NETWORK_QUALITY="network-quality",F.AUDIO_VOLUME="audio-volume",F.SEI_MESSAGE="sei-message",F.ERROR="error",F))(Op||{}),E_=(s=>(s.PLAYER_STATE_CHANGED="player-state-changed",s.SCREEN_SHARING_STOPPED="screen-sharing-stopped",s.CONNECTION_STATE_CHANGED="connection-state-changed",s.DEVICE_AUTO_RECOVERED="device-auto-recovered",s.ERROR="error",s))(E_||{}),Nd=(a=>(a.DEVICE_AUTO_RECOVERED="1",a.DEVICE_RECOVER_FAILED="5",a.DEVICE_CHANGED="2",a.ERROR="3",a.PUBLISH_STATE_CHANGED="4",a.ENCODE_FAILED="6",a))(Nd||{}),Us=(r=>(r.PAUSED="PAUSED",r.PLAYING="PLAYING",r.STOPPED="STOPPED",r))(Us||{}),Co=(F=>(F.PEER_JOIN="peer-join",F.PEER_LEAVE="peer-leave",F.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",F.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",F.BANNED="banned",F.NETWORK_QUALITY="network-quality",F.AUDIO_VOLUME="audio-volume",F.SEI_MESSAGE="sei-message",F.ERROR="error",F.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",F.REMOTE_PUBLISHED="remote-published",F.REMOTE_UNPUBLISHED="remote-unpublished",F.FIREWALL_RESTRICTION="firewall-restriction",F.HEARTBEAT_REPORT="heartbeat-report",F.CUSTOM_MESSAGE="custom-message",F.LAYER_DATA="layerData",F))(Co||{}),Wi=(a=>(a.PLAYER_STATE_CHANGED="player-state-changed",a.MUTE="mute",a.UNMUTE="unmute",a.ERROR="error",a.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",a.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",a))(Wi||{}),Vs=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(Vs||{}),T_=(d=>(d[d.VIDEO=1]="VIDEO",d[d.SMALL=2]="SMALL",d[d.AUX=4]="AUX",d[d.AUDIO=8]="AUDIO",d[d.VIDEO_MUTE=16]="VIDEO_MUTE",d[d.AUX_MUTE=32]="AUX_MUTE",d[d.AUDIO_MUTE=64]="AUDIO_MUTE",d))(T_||{}),Pp=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(Pp||{}),Do=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Do||{}),Gt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(Gt||{}),wd=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(wd||{}),kp=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(kp||{}),xd=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(xd||{}),Lp=(r=>(r.AUDIO="audio",r.VIDEO="video",r.AUXILIARY="auxVideo",r))(Lp||{}),I_=(e=>(e.ADD="add",e.REMOVE="remove",e))(I_||{}),St=(s=>(s[s.NULL=0]="NULL",s[s.AUDIO=1]="AUDIO",s[s.AUX_VIDEO=2]="AUX_VIDEO",s[s.BIG_VIDEO=4]="BIG_VIDEO",s[s.SMALL_VIDEO=8]="SMALL_VIDEO",s))(St||{}),cI={[1]:"audio",[2]:"auxVideo",[4]:"video"},Up=(t=>(t[t.opus=111]="opus",t))(Up||{}),Vp=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(Vp||{}),S_=(e=>(e.Big="big",e.Small="small",e))(S_||{}),qr=(e=>(e.Main="main",e.Aux="auxiliary",e))(qr||{}),Ti=(s=>(s[s.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",s[s.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",s[s.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",s[s.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",s[s.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",s))(Ti||{}),ba=(z=>(z[z.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",z[z.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",z[z.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",z[z.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",z[z.MUTE_AUDIO=32772]="MUTE_AUDIO",z[z.MUTE_VIDEO=32773]="MUTE_VIDEO",z[z.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",z[z.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",z[z.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",z[z.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",z[z.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",z[z.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",z[z.SWITCH_CAMERA=32780]="SWITCH_CAMERA",z[z.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",z[z.REPLACE_VIDEO=32782]="REPLACE_VIDEO",z[z.REPLACE_AUDIO=32783]="REPLACE_AUDIO",z[z.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",z[z.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",z[z.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",z[z.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",z[z.JOIN=32788]="JOIN",z[z.LEAVE=32789]="LEAVE",z[z.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",z[z.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",z[z.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",z[z.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",z[z.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",z[z.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",z[z.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",z[z.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",z[z.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",z[z.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",z[z.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",z[z.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",z[z.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",z[z.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",z[z.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",z[z.PUBLISH_AUX=32805]="PUBLISH_AUX",z[z.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",z[z.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",z[z.VIDEO_ENCODER=4004]="VIDEO_ENCODER",z[z.VIDEO_DECODER=4005]="VIDEO_DECODER",z))(ba||{}),y_=(d=>(d[d.UNKNOWN=0]="UNKNOWN",d[d.EXCELLENT=1]="EXCELLENT",d[d.GOOD=2]="GOOD",d[d.POOR=3]="POOR",d[d.BAD=4]="BAD",d[d.VERY_BAD=5]="VERY_BAD",d[d.DISCONNECTED=6]="DISCONNECTED",d))(y_||{}),A_=(o=>(o[o.MANUAL=0]="MANUAL",o[o.AUTO_AUDIO=1]="AUTO_AUDIO",o[o.AUTO_VIDEO=2]="AUTO_VIDEO",o[o.AUTO_ALL=3]="AUTO_ALL",o))(A_||{}),Md=(e=>(e.user="user",e.environment="environment",e))(Md||{}),Od=(r=>(r[r.ELEMENT=0]="ELEMENT",r[r.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",r[r.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",r))(Od||{}),Bp=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(Bp||{}),Fp=(o=>(o.BANNED="banned",o.KICK="kick",o.USER_TIME_OUT="user_time_out",o.ROOM_DISBAND="room_disband",o))(Fp||{}),$p=(p=>(p[p.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",p[p.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",p[p.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",p[p.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",p[p.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",p[p.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",p[p.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",p[p.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",p[p.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",p))($p||{}),Ii=1e8,Aa=class{constructor(){this.mediaType=0}set audio(t){t?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(t){t?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(t){t?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(t){t?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},No=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(No||{}),Hp=(r=>(r.H264="h264",r.H265="h265",r.VP8="vp8",r))(Hp||{}),va=(o=>(o[o.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",o[o.DUMP=1]="DUMP",o[o.SEI=2]="SEI",o[o.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",o))(va||{}),Pd=(o=>(o[o.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",o[o.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",o[o.DUMP=2]="DUMP",o[o.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",o))(Pd||{}),b_=(r=>(r.WebRTC="webrtc",r.WebCodecs="webcodecs",r.WebAssembly="webassembly",r))(b_||{}),Wp=(y=>(y[y.SUCCESS=0]="SUCCESS",y[y.FAILED=1]="FAILED",y[y.WEBCODEC_INIT=2]="WEBCODEC_INIT",y[y.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",y[y.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",y[y.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",y[y.WASM_INIT=6]="WASM_INIT",y[y.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",y[y.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",y[y.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",y[y.TEST=10]="TEST",y))(Wp||{}),Ra=(o=>(o.NONE="",o.DETAIL="detail",o.MOTION="motion",o.TEXT="text",o))(Ra||{});var it={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},jt={AVOID_REPEATED_CALL(i){return`previous ${i.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${o}' must be type of ${s} when calling ${e}(), received type: ${mt(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${o}' must be instanceof ${s} when calling ${e}(), received type: ${mt(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_MIN({key:i,rule:t,fnName:e,value:r}){return`the min value of ${i||t.name} is ${t.min}, received: ${r}.`},INVALID_PARAMETER_MAX({key:i,rule:t,fnName:e,value:r}){return`the max value of ${i||t.name} is ${t.max}, received: ${r}.`},API_CALL_TIMEOUT(i){return`${i.commandDesc||i.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(i){return`SignalChannel setup failure: (errorCode: ${i.errorCode}, errorMsg: ${i.errorMsg} }).`},ERROR_MESSAGE(i){let t=`${i.type} failed`;return i.message&&(t=`${t}: ${i.message}.`),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(i){return`exchange sdp failed ${i.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(i){return`'${i}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(i){return`'${i}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:i,code:t}){return`Failed to join room - ${i} code: ${t}`},REJOIN_ROOM_FAILED(i){return`reJoin room: ${i.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:`no permission to publish() under live/${"audience"}, please call switchRole("${"anchor"}") firstly before publish().`,INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(i){return`duplicate ${i} stream publishing, please unpublish your prev ${i} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:i,userId:t,streamType:e}){return`failed to subscribe ${t} ${e} stream, reason: ${i}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:`role could only be set to a value as ${"anchor"} or ${"audience"}.`,INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(i){return`switchRole failed, errCode: ${i.code} errMsg: ${i.message}.`},CLIENT_BANNED(i){return`client was banned because of ${i.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(i){return`startPublishCDNStream failed, errMsg: ${i.message}.`},STOP_PUBLISH_CDN_FAILED(i){return`stopPublishCDNStream failed, errMsg: ${i.message}.`},INVALID_STREAM_ID(i){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(i){return`cannot replace ${i.kind} track because stream has not ${i.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(i){return`startMixTranscode failed, errMsg: ${i.message}.`},STOP_MIX_TRANSCODE_FAILED(i){return`stopMixTranscode failed, errMsg: ${i.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(i){return`'${i}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:i,fnName:t})=>`'${i}' is not found in the document object when calling ${t}().`,INVALID_ELEMENT_ID_TYPE:({key:i,fnName:t,type:e})=>`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`,PLAY_FAILED:i=>`${i.media} play failed, browser exception: ${i.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(i){return`${i}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(i){return`${i.signalResponse} failed, response code is ${i.code} , errMsg: ${i.message}.`},CATCH_HANDLER_ERROR({name:i,event:t}){return`an error was caught in ${i}.on('${t}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:i}){return`experimental api ${i} does not exist.`},REPEAT_JOIN:i=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:i}){return`failed to call ${i}() because client was destroyed.`},SEI_NOT_SUPPORT:i=>`not support to sendSEIMessage${i===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:i,name:t,timesInSecond:e,maxSizeInSecond:r})=>`api ${t} call ${i?"size":"times"} is over ${i?`${r} bytes`:e} in a second.`,CONNECTION_ABORTED(i){return`connection aborted due to: ${i}`},API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`Subscribe ${i.userId} ${i.streamType} stream aborted, reason: remote user ${i.userId} unpublished stream.`:t=`API aborted, reason: ${i.message}`,t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:i=>`'streamType' is required when 'userId' is not '*', calling ${i}()`};var v_=(i,t)=>t?`${Fr}/${i}/${t}`:`${Fr}/${i}/index.html`;var dI=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let i=localStorage==null?void 0:localStorage.getItem(ip);if(i){i=JSON.parse(i);let t=document.createElement("script");t.type="text/javascript",t.text=i.message,document.body.appendChild(t);let e=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:r}}return{}};function ot(i){let{key:t,data:e,link:r,addDocLink:o=!0}=i,s="",a="",d="";Ve(jt[t])?s=jt[t](e):Ae(jt[t])&&(s=jt[t]);let{TRTC_ERROR_INFO:h,TRTC_ERROR_LINK:p}=dI();r?d=`${r.className}.html#${r.fnName}`:p&&p[t]&&(Ve(p[t])?d=p[t](e):Ae(p[t])&&(d=p[t]));let T=s;return vr()&&(h&&h[t]&&(Ve(h[t])?a=h[t](e):Ae(h[t])&&(a=h[t])),a&&(o?T=`${a}
|
|
5
5
|
\u8BF7\u67E5\u770B\u6587\u6863: ${v_("zh-cn",d)}
|
|
6
6
|
|
|
7
7
|
`:T=`${a}
|
|
8
8
|
|
|
9
9
|
`,T+=s)),o&&(T+=`
|
|
10
10
|
Refer to: ${v_("en",d)}
|
|
11
|
-
`),T}var Yp=Pi(O_(),1);var EI=1,TI=0,kd=class{constructor(t=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=V.createLogger({id:"kv"});t&&(B.on("102",({track:e,cost:r})=>{this.addSuccessEvent({key:e.kind===D.AUDIO?Ld.START_MICROPHONE:zp.START_CAMERA,cost:r})}),B.on("103",({track:e,error:r})=>{this.addFailedEvent({key:e.kind===D.AUDIO?Ld.START_MICROPHONE:zp.START_CAMERA,error:r})}))}getReportData(){let t={msg_sdk_basic_info:{uint32_sdk_version:dd(this.version||Ke),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,r])=>({uint32_key:e,uint32_count:r})),stats_distribution:[...this.distributionMap.entries()].map(([e,r])=>({uint32_key:e,distribution_items:[...r.entries()].map(([o,s])=>({uint32_item_key:o,uint32_item_value:s}))}))};return this.countMap.clear(),this.distributionMap.clear(),t}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(t){let e=+String(t).slice(-3);return e>=700&&e<799}isErrorCodeKey(t){let e=+String(t).slice(-3);return e>=600&&e<699}isCountKey(t){let e=+String(t).slice(-3);return e>=0&&e<599}isNumberKey(t){let e=+String(t).slice(-3);return e>=800&&e<899}addCount({key:t,useUV:e=!1}){if(!this.isCountKey(t)){this.log.debug(`${t} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1)}addEnum({key:t,value:e,useUV:r=!0}){var s;if(!this.isEnumKey(t))return this.log.debug(`${t} is not enum key, last 3 number should be 700~799`);if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=((s=this.distributionMap)==null?void 0:s.get(t))||new Map;o.set(e,(o.get(e)||0)+1),this.distributionMap.set(t,o)}addNumber({key:t,value:e,split:r=100,useUV:o=!1}){var d;if(!this.isNumberKey(t))return this.log.debug(`${t} is not number key, last 3 number should be 800~899`);if(o&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=((d=this.distributionMap)==null?void 0:d.get(t))||new Map,a=0;if(Fe(r))a=Math.floor(e/r);else for(let h=r.length-1;h>0;h--)if(e>r[h]){a=h;break}s.set(a,(s.get(a)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent({key:t,cost:e,timeKey:r,split:o}){if(!!t&&(this.addEnum({key:t,value:EI,useUV:!1}),e)){let s=+String(t).slice(-3);s<800&&s>=700?this.addNumber({key:r||t+100,value:e,split:o}):r||this.log.debug(`time stat ignored, ${t}`)}}addFailedEvent({key:t,error:e}){if(!t)return;let r=Y.UNKNOWN;e&&(Fe(e)?r=e:(!L(e.extraCode)||!L(e.code))&&(r=e.extraCode||e.code)),this.addEnum({key:t,value:TI,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},Ud=(fe=>(fe[fe.enterRoom=500700]="enterRoom",fe[fe.exitRoom=500701]="exitRoom",fe[fe.switchRole=500702]="switchRole",fe[fe.destroy=500703]="destroy",fe[fe.startLocalAudio=500704]="startLocalAudio",fe[fe.updateLocalAudio=500705]="updateLocalAudio",fe[fe.stopLocalAudio=500706]="stopLocalAudio",fe[fe.startLocalVideo=500707]="startLocalVideo",fe[fe.updateLocalVideo=500708]="updateLocalVideo",fe[fe.stopLocalVideo=500709]="stopLocalVideo",fe[fe.startScreenShare=500710]="startScreenShare",fe[fe.updateScreenShare=500711]="updateScreenShare",fe[fe.stopScreenShare=500712]="stopScreenShare",fe[fe.startRemoteVideo=500713]="startRemoteVideo",fe[fe.updateRemoteVideo=500714]="updateRemoteVideo",fe[fe.stopRemoteVideo=500715]="stopRemoteVideo",fe[fe.muteRemoteAudio=500716]="muteRemoteAudio",fe[fe.setRemoteAudioVolume=500717]="setRemoteAudioVolume",fe[fe.use=500718]="use",fe[fe.sendSEIMessage=5e5]="sendSEIMessage",fe[fe.sendCustomMessage=500001]="sendCustomMessage",fe))(Ud||{}),Jp=(p=>(p[p.AudioMixer=550700]="AudioMixer",p[p.AIDenoiser=551700]="AIDenoiser",p[p.VirtualBackground=570700]="VirtualBackground",p[p.Beauty=571700]="Beauty",p[p.Watermark=572700]="Watermark",p[p.BasicBeauty=574700]="BasicBeauty",p[p.CDNStreaming=590700]="CDNStreaming",p[p.DeviceDetector=591700]="DeviceDetector",p[p.Debug=592700]="Debug",p))(Jp||{}),Xp=(p=>(p[p.AudioMixer=550701]="AudioMixer",p[p.AIDenoiser=551701]="AIDenoiser",p[p.VirtualBackground=570701]="VirtualBackground",p[p.Beauty=571701]="Beauty",p[p.Watermark=572701]="Watermark",p[p.BasicBeauty=574701]="BasicBeauty",p[p.CDNStreaming=590701]="CDNStreaming",p[p.DeviceDetector=591701]="DeviceDetector",p[p.Debug=592701]="Debug",p))(Xp||{}),Qp=(p=>(p[p.AudioMixer=550702]="AudioMixer",p[p.AIDenoiser=551702]="AIDenoiser",p[p.VirtualBackground=570702]="VirtualBackground",p[p.Beauty=571702]="Beauty",p[p.Watermark=572702]="Watermark",p[p.BasicBeauty=574702]="BasicBeauty",p[p.CDNStreaming=590702]="CDNStreaming",p[p.DeviceDetector=591702]="DeviceDetector",p[p.Debug=592702]="Debug",p))(Qp||{});var Ld=(r=>(r[r.START_MICROPHONE=501700]="START_MICROPHONE",r[r.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",r[r.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",r))(Ld||{});var zp=(t=>(t[t.START_CAMERA=511700]="START_CAMERA",t))(zp||{});var II=new kd(!0),xo=new kd(!1);var X=II;var we={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},SI=new Map([[Cr,["Firefox",ld]],[Cs,["Edg",md]],[Os,["Chrome",Cd]],[Wt,["Safari",Fi]],[Dr,["TBS",_d]],[ca,["XWEB",gd]],[Ds&&yo,["WeChat",Ed]],[da,["QQ(Win)",Td]],[ws,["QQ(Mobile)",vs]],[Ns,["QQ(Mobile X5)",vs]],[ua,["QQ(Mac)",Id]],[la,["QQ(iPad)",Sd]],[ma,["MI",yd]],[ha,["HW",Ad]],[fa,["Samsung",bd]],[xs,["OPPO",vd]],[Ms,["VIVO",Rd]],[Rs,["EDGE",pd]],[na,["SogouMobile",hd]],[aa,["Sogou",fd]]]);function Bd(){let i=SI.get(!0),t=i?i[0]:"unknown",e=i?i[1]:"unknown";return{browserName:t,browserVersion:e}}var Kp=function(){return!(Sp||Rs||Cs&&Tp<80||Cr&&Ep<56)},k_=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(t=>t in window)},Fd=function(){if(!navigator.mediaDevices)return Ai()||V.error(jt.NOT_SUPPORTED_MEDIA),!1;let i=["getUserMedia","enumerateDevices"];return i.filter(t=>t in navigator.mediaDevices).length===i.length},P_=!1;function Ai(){return location.protocol==="http:"&&!wr?(P_||V.error(ot({key:it.NOT_SUPPORTED_HTTP})),P_=!0,!0):!1}var em=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Zp=function(){return v(this,null,function*(){if(we.detail.isH264EncodeSupported&&we.detail.isVp8EncodeSupported)return{isH264EncodeSupported:we.detail.isH264EncodeSupported,isVp8EncodeSupported:we.detail.isVp8EncodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection,o=document.createElement(D.CANVAS);o.getContext("2d");let s=o.captureStream(0);return r.addTrack(s.getVideoTracks()[0],s),i=yield r.createOffer(),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),we.detail.isH264EncodeSupported=t,we.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:we.detail.isH264EncodeSupported,isVp8EncodeSupported:we.detail.isVp8EncodeSupported}}catch(r){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},L_=function(){return v(this,null,function*(){if(we.detail.isH264DecodeSupported&&we.detail.isVp8DecodeSupported)return{isH264DecodeSupported:we.detail.isH264DecodeSupported,isVp8DecodeSupported:we.detail.isVp8DecodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection;return i=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:e}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},$d=ud(()=>v(void 0,null,function*(){if(we.result&&we.detail.isH264EncodeSupported&&we.detail.isVp8EncodeSupported&&we.detail.isH264DecodeSupported&&we.detail.isVp8DecodeSupported)return we;let i=Date.now(),t=Kp(),e=rm(),r=k_(),o=Fd(),{isH264EncodeSupported:s,isVp8EncodeSupported:a}=yield Zp(),{isH264DecodeSupported:d,isVp8DecodeSupported:h}=yield L_();if(!s||!a){let p=yield Zp();V.warn(`detect encode again h264:${s} vp8:${a} result: ${JSON.stringify(p)}`),s=p.isH264EncodeSupported,a=p.isVp8EncodeSupported}if(s&&d&&(xs||Ms||vp)&&!Dr&&_a()<79){let{encode:p,decode:T}=yield AI();s=p,d=T}return we.result=t&&e&&o&&(s||a)&&(d||h),we.detail.isBrowserSupported=t,we.detail.isWebRTCSupported=e,we.detail.isWebCodecsSupported=r,we.detail.isMediaDevicesSupported=o,we.detail.isScreenShareSupported=Ca(),we.detail.isSmallStreamSupported=Da(),we.detail.isH264EncodeSupported=s,we.detail.isVp8EncodeSupported=a,we.detail.isH264DecodeSupported=d,we.detail.isVp8DecodeSupported=h,we.result||V.error(`${navigator.userAgent} ${ad(we.detail,!1)}`),LI(),X.addNumber({key:523800,value:Date.now()-i}),we})),yI=function(){return we.result},Ca=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},Vd=null;function AI(){return v(this,null,function*(){return Vd||(Vd=new Promise(i=>v(this,null,function*(){let t={encode:!1,decode:!1},e=()=>{};try{V.warn("detectH264Supported start");let r=document.createElement("canvas"),o=r.getContext("2d");r.width=320,r.height=240;let s=setInterval(()=>{o.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),a=-1,d=-1;e=()=>{clearInterval(a),clearInterval(s),clearTimeout(d),p.close(),T.close(),h.getTracks().forEach(W=>W.stop())},d=setTimeout(()=>{e(),i(t)},2*1e3);let h=r.captureStream(),p=new RTCPeerConnection({}),T=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});p.addEventListener("icecandidate",W=>T.addIceCandidate(W.candidate)),T.addEventListener("icecandidate",W=>p.addIceCandidate(W.candidate)),p.addTrack(h.getVideoTracks()[0],h);let y=yield p.createOffer();yield p.setLocalDescription(y),yield T.setRemoteDescription(y);let R=yield T.createAnswer(),N=Yp.default.parse(R.sdp),j=N.media[0].rtp.findIndex(W=>W.codec==="H264");N.media[0].rtp=[N.media[0].rtp[j]],N.media[0].fmtp=N.media[0].fmtp.filter(W=>W.payload===N.media[0].rtp[0].payload),N.media[0].rtcpFb&&(N.media[0].rtcpFb=N.media[0].rtcpFb.filter(W=>W.payload===N.media[0].rtp[0].payload)),R.sdp=Yp.default.write(N),yield T.setLocalDescription(R),yield p.setRemoteDescription(R),a=setInterval(()=>v(this,null,function*(){t.encode&&t.decode&&(e(),i(t));let W=yield p.getSenders()[0].getStats(),F=yield T.getReceivers()[0].getStats();t.encode||W.forEach(Ie=>{Ie.type==="outbound-rtp"&&Ie.mediaType===D.VIDEO&&Ie.bytesSent>0&&(t.encode=!0)}),t.decode||F.forEach(Ie=>{Ie.type==="inbound-rtp"&&Ie.mediaType===D.VIDEO&&Ie.bytesReceived>0&&(t.decode=!0)})}),100)}catch(r){e(),V.warn(r),i(t)}})).then(i=>((!i.encode||!i.decode)&&V.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${Rr}`),i)),Vd)})}var bI=(i,t,e)=>{location.protocol==="http:"&&!wr&&(i[t]=()=>{throw new de({code:Y.INVALID_OPERATION,message:jt.NOT_SUPPORTED_HTTP})})},vI=function(i){return i.type==="candidate-pair"&&i.nominated&&(i.state==="in-progress"||i.state==="succeeded")?!(nt(i.selected)&&!i.selected):!1};function U_(){let i="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";i+=`${t} * ${e}`}return i}function V_(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function B_(){let i={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<t.length;e++)if(t[e]in window){i.isSupported=!0;break}return i.isSupported}function F_(){return"captureStream"in HTMLCanvasElement.prototype}function Da(){return Ds||Ht||gi&&gi<63?!1:!!(Kp()&&F_())}var RI=function(){if(L(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let i=null,t=!1;try{i=new RTCPeerConnection({sdpSemantics:np}),i.addTransceiver(D.AUDIO),t=!0}catch(e){}return i==null||i.close(),t};function CI(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function $_(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function DI(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function H_(){return ir===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var NI=(()=>!(!H_()||bo&&gi<86))();function wI(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var Na="RTCRtpSender"in window;function xI(){return Na&&"replaceTrack"in window.RTCRtpSender.prototype}function MI(){return Na&&"setParameters"in window.RTCRtpSender.prototype&&$_()}var OI="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Fs=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,tm=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,wa=Na&&"createEncodedStreams"in window.RTCRtpSender.prototype&&_a()>=86,W_="RTCRtpScriptTransform"in window,xa=Na&&(wa||W_),rm=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function G_(){let i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return L(window.AudioDecoder)||(i.AudioDecoder=!0),L(window.AudioEncoder)||(i.AudioEncoder=!0),L(window.VideoDecoder)||(i.VideoDecoder=!0),L(window.VideoEncoder)||(i.VideoEncoder=!0),L(window.ImageDecoder)||(i.ImageDecoder=!0),i}function j_(){return"mediaSession"in navigator&&!L(navigator.mediaSession.setActionHandler)}function q_(){return!L(window.WebTransport)}function PI(){return typeof WebAssembly=="undefined"?!1: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]))}function kI(){let i={browser:`${jr.name}/${jr.version}`,os:Ps(),displayResolution:U_(),isScreenShareSupported:Ca(),isWebRTCSupported:rm(),isGetUserMediaSupported:V_(),isWebAudioSupported:B_(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:G_(),isMediaSessionSupported:j_(),isWebTransportSupported:q_()};return navigator.userAgent.includes("miniProgram")&&(i.browser=`mini/${i.browser}`),i}var z_="checkResult";function LI(){Ls.setItem(z_,{ua:navigator.userAgent,checkResult:we})}function im(){Ai();let i=Ls.getItem(z_);i&&i.ua===navigator.userAgent&&(we=i.checkResult),$d()}function Mo(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var UI="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var X_=Pi(Hi(),1);var J_=Symbol("instance"),qb=Symbol("abortCtrl"),Hd=Symbol("cacheResult"),Ma=class{constructor(t,e,r){this.oldState=t,this.newState=e,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,Pa.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},$s=class extends Error{constructor(t,e,r){super(e),this.state=t,this.message=e,this.cause=r}};function VI(i){return typeof i=="object"&&i&&"then"in i}var Oa=new Map;function be(i,t,e={}){return(r,o,s)=>{let a=e.action||o;if(!e.context){let h=Oa.get(r)||[];Oa.has(r)||Oa.set(r,h),h.push({from:i,to:t,action:a})}let d=s.value;s.value=function(...h){let p=this;if(e.context&&(p=Z.get(typeof e.context=="function"?e.context.call(this,...h):e.context)),p.state===t)return e.sync?p[Hd]:Promise.resolve(p[Hd]);p.state instanceof Ma&&p.state.action==e.abortAction&&p.state.abort(p);let T=null;Array.isArray(i)?i.length==0?p.state instanceof Ma&&p.state.abort(p):(typeof p.state!="string"||!i.includes(p.state))&&(T=new $s(p._state,`${p.name} ${a} to ${t} failed: current state ${p._state} not from ${i.join("|")}`)):i!==p.state&&(T=new $s(p._state,`${p.name} ${a} to ${t} failed: current state ${p._state} not from ${i}`));let y=F=>{if(e.fail&&e.fail.call(this,F),e.sync){if(e.ignoreError)return F;throw F}else return e.ignoreError?Promise.resolve(F):Promise.reject(F)};if(T)return y(T);let R=p.state,N=new Ma(R,t,a);Pa.call(p,N);let j=F=>{var Ie;return p[Hd]=F,N.aborted||(Pa.call(p,t),(Ie=e.success)===null||Ie===void 0||Ie.call(this,p[Hd])),F},W=F=>(Pa.call(p,R,F),y(F));try{let F=d.apply(this,h);return VI(F)?F.then(j).catch(W):e.sync?j(F):Promise.resolve(j(F))}catch(F){return W(new $s(p._state,`${p.name} ${a} from ${i} to ${t} failed: ${F}`,F instanceof Error?F:new Error(String(F))))}}}}function Q_(...i){return(t,e,r)=>{let o=r.value,s=e;r.value=function(...a){if(!i.includes(this.state.toString()))throw new $s(this.state,`${this.name} ${s} failed: current state ${this.state} not in ${i}`);return o.apply(this,a)}}}var BI=(()=>typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{})();function Pa(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(Z.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var Z=class extends X_.default{constructor(t,e,r){super(),this.name=t,this.groupName=e,this._state=Z.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let o=r[J_];o?this.name=o.name+"-"+o.count++:r[J_]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=Oa.get(t)||[],r=new Set,o=[],s=[],a=new Set,d=Object.getPrototypeOf(t);Oa.has(d)&&(d.stateDiagram.forEach(p=>r.add(p)),d.allStates.forEach(p=>a.add(p))),e.forEach(({from:p,to:T,action:y})=>{typeof p=="string"?o.push({from:p,to:T,action:y}):p.length?p.forEach(R=>{o.push({from:R,to:T,action:y})}):s.push({to:T,action:y})}),o.forEach(({from:p,to:T,action:y})=>{a.add(p),a.add(T),a.add(y+"ing"),r.add(`${p} --> ${y}ing : ${y}`),r.add(`${y}ing --> ${T} : ${y} \u{1F7E2}`),r.add(`${y}ing --> ${p} : ${y} \u{1F534}`)}),s.forEach(({to:p,action:T})=>{r.add(`${T}ing --> ${p} : ${T} \u{1F7E2}`),a.forEach(y=>{y!==p&&r.add(`${y} --> ${T}ing : ${T}`)})});let h=[...r];return Object.defineProperties(t,{stateDiagram:{value:h},allStates:{value:a}}),h}static get(t){let e;return typeof t=="string"?(e=Z.instances.get(t),e||Z.instances.set(t,e=new Z(t,void 0,Object.create(Z.prototype)))):(e=Z.instances2.get(t),e||Z.instances2.set(t,e=new Z(t.constructor.name,void 0,Object.create(Z.prototype)))),e}static getState(t){var e;return(e=Z.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){BI(Z.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){Pa.call(this,t)}};Z.STATECHANGED="stateChanged";Z.UPDATEAFSM="updateAFSM";Z.INIT="[*]";Z.ON="on";Z.OFF="off";Z.instances=new Map;Z.instances2=new WeakMap;var om=typeof window!="undefined",Y_=om&&window.requestIdleCallback||function(i){let t=Date.now();return setTimeout(()=>{i({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},FI=om&&window.cancelIdleCallback||function(i){clearTimeout(i)},$I=om&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),ka=class{static generateTaskID(){return this.currentTaskID++}static run(t=Ts,e,r){t===To?r=J({delay:2e3,count:0,backgroundTask:!0},r):t===cp?r=J({delay:1e4,count:0},r):t===dp?r=J({fps:60,delay:16.6,count:0,backgroundTask:!0},r):r=J({delay:2e3,count:0,backgroundTask:!0},r),lr(e)&&(r=J(J({},r),e)),Ve(t)&&(e=t,t=Ts);let o=J({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:t,callback:e},r);return this.taskMap.set(o.taskID,o),this[t](o),o.taskID}static interval(t){let e=()=>{t.callback(),t.loopCount+=1,this.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static intervalInWorker(t){t.delay=(1e3/t.fps).toFixed(2);let e=new Worker(URL.createObjectURL(new Blob([`
|
|
11
|
+
`),T}var Yp=Pi(O_(),1);var EI=1,TI=0,kd=class{constructor(t=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=V.createLogger({id:"kv"});t&&(B.on("102",({track:e,cost:r})=>{this.addSuccessEvent({key:e.kind===D.AUDIO?Ld.START_MICROPHONE:zp.START_CAMERA,cost:r})}),B.on("103",({track:e,error:r})=>{this.addFailedEvent({key:e.kind===D.AUDIO?Ld.START_MICROPHONE:zp.START_CAMERA,error:r})}))}getReportData(){let t={msg_sdk_basic_info:{uint32_sdk_version:dd(this.version||Ke),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,r])=>({uint32_key:e,uint32_count:r})),stats_distribution:[...this.distributionMap.entries()].map(([e,r])=>({uint32_key:e,distribution_items:[...r.entries()].map(([o,s])=>({uint32_item_key:o,uint32_item_value:s}))}))};return this.countMap.clear(),this.distributionMap.clear(),t}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(t){let e=+String(t).slice(-3);return e>=700&&e<799}isErrorCodeKey(t){let e=+String(t).slice(-3);return e>=600&&e<699}isCountKey(t){let e=+String(t).slice(-3);return e>=0&&e<599}isNumberKey(t){let e=+String(t).slice(-3);return e>=800&&e<899}addCount({key:t,useUV:e=!1}){if(!this.isCountKey(t)){this.log.debug(`${t} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1)}addEnum({key:t,value:e,useUV:r=!0}){var s;if(!this.isEnumKey(t))return this.log.debug(`${t} is not enum key, last 3 number should be 700~799`);if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=((s=this.distributionMap)==null?void 0:s.get(t))||new Map;o.set(e,(o.get(e)||0)+1),this.distributionMap.set(t,o)}addNumber({key:t,value:e,split:r=100,useUV:o=!1}){var d;if(!this.isNumberKey(t))return this.log.debug(`${t} is not number key, last 3 number should be 800~899`);if(o&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=((d=this.distributionMap)==null?void 0:d.get(t))||new Map,a=0;if(Fe(r))a=Math.floor(e/r);else for(let h=r.length-1;h>0;h--)if(e>r[h]){a=h;break}s.set(a,(s.get(a)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent({key:t,cost:e,timeKey:r,split:o}){if(!!t&&(this.addEnum({key:t,value:EI,useUV:!1}),e)){let s=+String(t).slice(-3);s<800&&s>=700?this.addNumber({key:r||t+100,value:e,split:o}):r||this.log.debug(`time stat ignored, ${t}`)}}addFailedEvent({key:t,error:e}){if(!t)return;let r=Y.UNKNOWN;e&&(Fe(e)?r=e:(!L(e.extraCode)||!L(e.code))&&(r=e.extraCode||e.code)),this.addEnum({key:t,value:TI,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},Ud=(fe=>(fe[fe.enterRoom=500700]="enterRoom",fe[fe.exitRoom=500701]="exitRoom",fe[fe.switchRole=500702]="switchRole",fe[fe.destroy=500703]="destroy",fe[fe.startLocalAudio=500704]="startLocalAudio",fe[fe.updateLocalAudio=500705]="updateLocalAudio",fe[fe.stopLocalAudio=500706]="stopLocalAudio",fe[fe.startLocalVideo=500707]="startLocalVideo",fe[fe.updateLocalVideo=500708]="updateLocalVideo",fe[fe.stopLocalVideo=500709]="stopLocalVideo",fe[fe.startScreenShare=500710]="startScreenShare",fe[fe.updateScreenShare=500711]="updateScreenShare",fe[fe.stopScreenShare=500712]="stopScreenShare",fe[fe.startRemoteVideo=500713]="startRemoteVideo",fe[fe.updateRemoteVideo=500714]="updateRemoteVideo",fe[fe.stopRemoteVideo=500715]="stopRemoteVideo",fe[fe.muteRemoteAudio=500716]="muteRemoteAudio",fe[fe.setRemoteAudioVolume=500717]="setRemoteAudioVolume",fe[fe.use=500718]="use",fe[fe.sendSEIMessage=5e5]="sendSEIMessage",fe[fe.sendCustomMessage=500001]="sendCustomMessage",fe))(Ud||{}),Jp=(p=>(p[p.AudioMixer=550700]="AudioMixer",p[p.AIDenoiser=551700]="AIDenoiser",p[p.VirtualBackground=570700]="VirtualBackground",p[p.Beauty=571700]="Beauty",p[p.Watermark=572700]="Watermark",p[p.BasicBeauty=574700]="BasicBeauty",p[p.CDNStreaming=590700]="CDNStreaming",p[p.DeviceDetector=591700]="DeviceDetector",p[p.Debug=592700]="Debug",p))(Jp||{}),Xp=(p=>(p[p.AudioMixer=550701]="AudioMixer",p[p.AIDenoiser=551701]="AIDenoiser",p[p.VirtualBackground=570701]="VirtualBackground",p[p.Beauty=571701]="Beauty",p[p.Watermark=572701]="Watermark",p[p.BasicBeauty=574701]="BasicBeauty",p[p.CDNStreaming=590701]="CDNStreaming",p[p.DeviceDetector=591701]="DeviceDetector",p[p.Debug=592701]="Debug",p))(Xp||{}),Qp=(p=>(p[p.AudioMixer=550702]="AudioMixer",p[p.AIDenoiser=551702]="AIDenoiser",p[p.VirtualBackground=570702]="VirtualBackground",p[p.Beauty=571702]="Beauty",p[p.Watermark=572702]="Watermark",p[p.BasicBeauty=574702]="BasicBeauty",p[p.CDNStreaming=590702]="CDNStreaming",p[p.DeviceDetector=591702]="DeviceDetector",p[p.Debug=592702]="Debug",p))(Qp||{});var Ld=(r=>(r[r.START_MICROPHONE=501700]="START_MICROPHONE",r[r.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",r[r.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",r))(Ld||{});var zp=(t=>(t[t.START_CAMERA=511700]="START_CAMERA",t))(zp||{});var II=new kd(!0),xo=new kd(!1);var X=II;var we={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},SI=new Map([[Cr,["Firefox",ld]],[Cs,["Edg",md]],[Os,["Chrome",Cd]],[Wt,["Safari",Fi]],[Dr,["TBS",_d]],[da,["XWEB",gd]],[Ds&&yo,["WeChat",Ed]],[ua,["QQ(Win)",Td]],[ws,["QQ(Mobile)",vs]],[Ns,["QQ(Mobile X5)",vs]],[la,["QQ(Mac)",Id]],[pa,["QQ(iPad)",Sd]],[ha,["MI",yd]],[fa,["HW",Ad]],[_a,["Samsung",bd]],[xs,["OPPO",vd]],[Ms,["VIVO",Rd]],[Rs,["EDGE",pd]],[aa,["SogouMobile",hd]],[ca,["Sogou",fd]]]);function Bd(){let i=SI.get(!0),t=i?i[0]:"unknown",e=i?i[1]:"unknown";return{browserName:t,browserVersion:e}}var Kp=function(){return!(Sp||Rs||Cs&&Tp<80||Cr&&Ep<56)},k_=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(t=>t in window)},Fd=function(){if(!navigator.mediaDevices)return Ai()||V.error(jt.NOT_SUPPORTED_MEDIA),!1;let i=["getUserMedia","enumerateDevices"];return i.filter(t=>t in navigator.mediaDevices).length===i.length},P_=!1;function Ai(){return location.protocol==="http:"&&!wr?(P_||V.error(ot({key:it.NOT_SUPPORTED_HTTP})),P_=!0,!0):!1}var em=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Zp=function(){return v(this,null,function*(){if(we.detail.isH264EncodeSupported&&we.detail.isVp8EncodeSupported)return{isH264EncodeSupported:we.detail.isH264EncodeSupported,isVp8EncodeSupported:we.detail.isVp8EncodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection,o=document.createElement(D.CANVAS);o.getContext("2d");let s=o.captureStream(0);return r.addTrack(s.getVideoTracks()[0],s),i=yield r.createOffer(),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),we.detail.isH264EncodeSupported=t,we.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:we.detail.isH264EncodeSupported,isVp8EncodeSupported:we.detail.isVp8EncodeSupported}}catch(r){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},L_=function(){return v(this,null,function*(){if(we.detail.isH264DecodeSupported&&we.detail.isVp8DecodeSupported)return{isH264DecodeSupported:we.detail.isH264DecodeSupported,isVp8DecodeSupported:we.detail.isVp8DecodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection;return i=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:e}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},$d=ud(()=>v(void 0,null,function*(){if(we.result&&we.detail.isH264EncodeSupported&&we.detail.isVp8EncodeSupported&&we.detail.isH264DecodeSupported&&we.detail.isVp8DecodeSupported)return we;let i=Date.now(),t=Kp(),e=rm(),r=k_(),o=Fd(),{isH264EncodeSupported:s,isVp8EncodeSupported:a}=yield Zp(),{isH264DecodeSupported:d,isVp8DecodeSupported:h}=yield L_();if(!s||!a){let p=yield Zp();V.warn(`detect encode again h264:${s} vp8:${a} result: ${JSON.stringify(p)}`),s=p.isH264EncodeSupported,a=p.isVp8EncodeSupported}if(s&&d&&(xs||Ms||vp)&&!Dr&&ga()<79){let{encode:p,decode:T}=yield AI();s=p,d=T}return we.result=t&&e&&o&&(s||a)&&(d||h),we.detail.isBrowserSupported=t,we.detail.isWebRTCSupported=e,we.detail.isWebCodecsSupported=r,we.detail.isMediaDevicesSupported=o,we.detail.isScreenShareSupported=Da(),we.detail.isSmallStreamSupported=Na(),we.detail.isH264EncodeSupported=s,we.detail.isVp8EncodeSupported=a,we.detail.isH264DecodeSupported=d,we.detail.isVp8DecodeSupported=h,we.result||V.error(`${navigator.userAgent} ${ad(we.detail,!1)}`),LI(),X.addNumber({key:523800,value:Date.now()-i}),we})),yI=function(){return we.result},Da=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},Vd=null;function AI(){return v(this,null,function*(){return Vd||(Vd=new Promise(i=>v(this,null,function*(){let t={encode:!1,decode:!1},e=()=>{};try{V.warn("detectH264Supported start");let r=document.createElement("canvas"),o=r.getContext("2d");r.width=320,r.height=240;let s=setInterval(()=>{o.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),a=-1,d=-1;e=()=>{clearInterval(a),clearInterval(s),clearTimeout(d),p.close(),T.close(),h.getTracks().forEach(W=>W.stop())},d=setTimeout(()=>{e(),i(t)},2*1e3);let h=r.captureStream(),p=new RTCPeerConnection({}),T=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});p.addEventListener("icecandidate",W=>T.addIceCandidate(W.candidate)),T.addEventListener("icecandidate",W=>p.addIceCandidate(W.candidate)),p.addTrack(h.getVideoTracks()[0],h);let y=yield p.createOffer();yield p.setLocalDescription(y),yield T.setRemoteDescription(y);let R=yield T.createAnswer(),N=Yp.default.parse(R.sdp),j=N.media[0].rtp.findIndex(W=>W.codec==="H264");N.media[0].rtp=[N.media[0].rtp[j]],N.media[0].fmtp=N.media[0].fmtp.filter(W=>W.payload===N.media[0].rtp[0].payload),N.media[0].rtcpFb&&(N.media[0].rtcpFb=N.media[0].rtcpFb.filter(W=>W.payload===N.media[0].rtp[0].payload)),R.sdp=Yp.default.write(N),yield T.setLocalDescription(R),yield p.setRemoteDescription(R),a=setInterval(()=>v(this,null,function*(){t.encode&&t.decode&&(e(),i(t));let W=yield p.getSenders()[0].getStats(),F=yield T.getReceivers()[0].getStats();t.encode||W.forEach(Ie=>{Ie.type==="outbound-rtp"&&Ie.mediaType===D.VIDEO&&Ie.bytesSent>0&&(t.encode=!0)}),t.decode||F.forEach(Ie=>{Ie.type==="inbound-rtp"&&Ie.mediaType===D.VIDEO&&Ie.bytesReceived>0&&(t.decode=!0)})}),100)}catch(r){e(),V.warn(r),i(t)}})).then(i=>((!i.encode||!i.decode)&&V.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${Rr}`),i)),Vd)})}var bI=(i,t,e)=>{location.protocol==="http:"&&!wr&&(i[t]=()=>{throw new de({code:Y.INVALID_OPERATION,message:jt.NOT_SUPPORTED_HTTP})})},vI=function(i){return i.type==="candidate-pair"&&i.nominated&&(i.state==="in-progress"||i.state==="succeeded")?!(nt(i.selected)&&!i.selected):!1};function U_(){let i="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";i+=`${t} * ${e}`}return i}function V_(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function B_(){let i={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<t.length;e++)if(t[e]in window){i.isSupported=!0;break}return i.isSupported}function F_(){return"captureStream"in HTMLCanvasElement.prototype}function Na(){return Ds||Ht||gi&&gi<63?!1:!!(Kp()&&F_())}var RI=function(){if(L(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let i=null,t=!1;try{i=new RTCPeerConnection({sdpSemantics:np}),i.addTransceiver(D.AUDIO),t=!0}catch(e){}return i==null||i.close(),t};function CI(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function $_(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function DI(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function H_(){return ir===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var NI=(()=>!(!H_()||bo&&gi<86))();function wI(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var wa="RTCRtpSender"in window;function xI(){return wa&&"replaceTrack"in window.RTCRtpSender.prototype}function MI(){return wa&&"setParameters"in window.RTCRtpSender.prototype&&$_()}var OI="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Fs=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,tm=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,xa=wa&&"createEncodedStreams"in window.RTCRtpSender.prototype&&ga()>=86,W_="RTCRtpScriptTransform"in window,Ma=wa&&(xa||W_),rm=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function G_(){let i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return L(window.AudioDecoder)||(i.AudioDecoder=!0),L(window.AudioEncoder)||(i.AudioEncoder=!0),L(window.VideoDecoder)||(i.VideoDecoder=!0),L(window.VideoEncoder)||(i.VideoEncoder=!0),L(window.ImageDecoder)||(i.ImageDecoder=!0),i}function j_(){return"mediaSession"in navigator&&!L(navigator.mediaSession.setActionHandler)}function q_(){return!L(window.WebTransport)}function PI(){return typeof WebAssembly=="undefined"?!1: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]))}function kI(){let i={browser:`${jr.name}/${jr.version}`,os:Ps(),displayResolution:U_(),isScreenShareSupported:Da(),isWebRTCSupported:rm(),isGetUserMediaSupported:V_(),isWebAudioSupported:B_(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:G_(),isMediaSessionSupported:j_(),isWebTransportSupported:q_()};return navigator.userAgent.includes("miniProgram")&&(i.browser=`mini/${i.browser}`),i}var z_="checkResult";function LI(){Ls.setItem(z_,{ua:navigator.userAgent,checkResult:we})}function im(){Ai();let i=Ls.getItem(z_);i&&i.ua===navigator.userAgent&&(we=i.checkResult),$d()}function Mo(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var UI="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var X_=Pi(Hi(),1);var J_=Symbol("instance"),qb=Symbol("abortCtrl"),Hd=Symbol("cacheResult"),Oa=class{constructor(t,e,r){this.oldState=t,this.newState=e,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,ka.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},$s=class extends Error{constructor(t,e,r){super(e),this.state=t,this.message=e,this.cause=r}};function VI(i){return typeof i=="object"&&i&&"then"in i}var Pa=new Map;function be(i,t,e={}){return(r,o,s)=>{let a=e.action||o;if(!e.context){let h=Pa.get(r)||[];Pa.has(r)||Pa.set(r,h),h.push({from:i,to:t,action:a})}let d=s.value;s.value=function(...h){let p=this;if(e.context&&(p=Z.get(typeof e.context=="function"?e.context.call(this,...h):e.context)),p.state===t)return e.sync?p[Hd]:Promise.resolve(p[Hd]);p.state instanceof Oa&&p.state.action==e.abortAction&&p.state.abort(p);let T=null;Array.isArray(i)?i.length==0?p.state instanceof Oa&&p.state.abort(p):(typeof p.state!="string"||!i.includes(p.state))&&(T=new $s(p._state,`${p.name} ${a} to ${t} failed: current state ${p._state} not from ${i.join("|")}`)):i!==p.state&&(T=new $s(p._state,`${p.name} ${a} to ${t} failed: current state ${p._state} not from ${i}`));let y=F=>{if(e.fail&&e.fail.call(this,F),e.sync){if(e.ignoreError)return F;throw F}else return e.ignoreError?Promise.resolve(F):Promise.reject(F)};if(T)return y(T);let R=p.state,N=new Oa(R,t,a);ka.call(p,N);let j=F=>{var Ie;return p[Hd]=F,N.aborted||(ka.call(p,t),(Ie=e.success)===null||Ie===void 0||Ie.call(this,p[Hd])),F},W=F=>(ka.call(p,R,F),y(F));try{let F=d.apply(this,h);return VI(F)?F.then(j).catch(W):e.sync?j(F):Promise.resolve(j(F))}catch(F){return W(new $s(p._state,`${p.name} ${a} from ${i} to ${t} failed: ${F}`,F instanceof Error?F:new Error(String(F))))}}}}function Q_(...i){return(t,e,r)=>{let o=r.value,s=e;r.value=function(...a){if(!i.includes(this.state.toString()))throw new $s(this.state,`${this.name} ${s} failed: current state ${this.state} not in ${i}`);return o.apply(this,a)}}}var BI=(()=>typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{})();function ka(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(Z.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var Z=class extends X_.default{constructor(t,e,r){super(),this.name=t,this.groupName=e,this._state=Z.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let o=r[J_];o?this.name=o.name+"-"+o.count++:r[J_]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=Pa.get(t)||[],r=new Set,o=[],s=[],a=new Set,d=Object.getPrototypeOf(t);Pa.has(d)&&(d.stateDiagram.forEach(p=>r.add(p)),d.allStates.forEach(p=>a.add(p))),e.forEach(({from:p,to:T,action:y})=>{typeof p=="string"?o.push({from:p,to:T,action:y}):p.length?p.forEach(R=>{o.push({from:R,to:T,action:y})}):s.push({to:T,action:y})}),o.forEach(({from:p,to:T,action:y})=>{a.add(p),a.add(T),a.add(y+"ing"),r.add(`${p} --> ${y}ing : ${y}`),r.add(`${y}ing --> ${T} : ${y} \u{1F7E2}`),r.add(`${y}ing --> ${p} : ${y} \u{1F534}`)}),s.forEach(({to:p,action:T})=>{r.add(`${T}ing --> ${p} : ${T} \u{1F7E2}`),a.forEach(y=>{y!==p&&r.add(`${y} --> ${T}ing : ${T}`)})});let h=[...r];return Object.defineProperties(t,{stateDiagram:{value:h},allStates:{value:a}}),h}static get(t){let e;return typeof t=="string"?(e=Z.instances.get(t),e||Z.instances.set(t,e=new Z(t,void 0,Object.create(Z.prototype)))):(e=Z.instances2.get(t),e||Z.instances2.set(t,e=new Z(t.constructor.name,void 0,Object.create(Z.prototype)))),e}static getState(t){var e;return(e=Z.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){BI(Z.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){ka.call(this,t)}};Z.STATECHANGED="stateChanged";Z.UPDATEAFSM="updateAFSM";Z.INIT="[*]";Z.ON="on";Z.OFF="off";Z.instances=new Map;Z.instances2=new WeakMap;var om=typeof window!="undefined",Y_=om&&window.requestIdleCallback||function(i){let t=Date.now();return setTimeout(()=>{i({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},FI=om&&window.cancelIdleCallback||function(i){clearTimeout(i)},$I=om&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),La=class{static generateTaskID(){return this.currentTaskID++}static run(t=Ts,e,r){t===To?r=J({delay:2e3,count:0,backgroundTask:!0},r):t===cp?r=J({delay:1e4,count:0},r):t===dp?r=J({fps:60,delay:16.6,count:0,backgroundTask:!0},r):r=J({delay:2e3,count:0,backgroundTask:!0},r),lr(e)&&(r=J(J({},r),e)),Ve(t)&&(e=t,t=Ts);let o=J({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:t,callback:e},r);return this.taskMap.set(o.taskID,o),this[t](o),o.taskID}static interval(t){let e=()=>{t.callback(),t.loopCount+=1,this.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static intervalInWorker(t){t.delay=(1e3/t.fps).toFixed(2);let e=new Worker(URL.createObjectURL(new Blob([`
|
|
12
12
|
let timerID = null;
|
|
13
13
|
self.onmessage = function (e) {
|
|
14
14
|
if (e.data === 'start') {
|
|
@@ -19,14 +19,14 @@ Refer to: ${v_("en",d)}
|
|
|
19
19
|
clearInterval(timerID);
|
|
20
20
|
}
|
|
21
21
|
};
|
|
22
|
-
`],{type:"application/javascript"})));e.onmessage=r=>{r.data==="tick"&&(t.callback(),t.loopCount+=1,this.isBreakLoop(t)&&e.postMessage("stop"))},t.worker=e,e.postMessage("start")}static timeout(t){let e=()=>{if(t.callback(),t.loopCount+=1,!this.isBreakLoop(t))return t.timeoutID=setTimeout(e,t.delay)};return t.timeoutID=setTimeout(e,t.delay)}static ric(t){let e=ge(),r,o=()=>{if(r=ge()-e,r>=t.delay&&(e=ge()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.ricID=Y_(o,{timeout:t.delay})};return t.ricID=Y_(o,{timeout:t.delay})}static raf(t){t.delay=(1e3/t.fps).toFixed(2);let e=ge(),r,o=()=>{if(document.hidden&&t.backgroundTask)return r=ge()-e,e=ge(),t.callback(),t.loopCount+=1,this.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(o,t.delay-Math.floor(r%t.delay));if(r=ge()-e,r>=t.delay&&(e=ge()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.rafID=requestAnimationFrame(o)};if(t.rafID=requestAnimationFrame(o),t.backgroundTask){let s=()=>{if(document.hidden){let a=ge()-e;a>=t.delay?o():t.timeoutID=setTimeout(o,t.delay-a)}};document.addEventListener("visibilitychange",s),t.onVisibilitychange=s,document.hidden&&s()}return t.taskID}static hasTask(t){return this.taskMap.has(t)}static clearTask(t){if(!this.taskMap.has(t))return!0;let{intervalID:e,timeoutID:r,rafID:o,ricID:s,onVisibilitychange:a,worker:d}=this.taskMap.get(t);return d&&d.terminate(),e&&clearInterval(e),r&&clearTimeout(r),o&&$I(o),s&&FI(s),a&&document.removeEventListener("visibilitychange",a),this.taskMap.delete(t),!0}static isBreakLoop(t){return this.taskMap.has(t.taskID)?t.count!==0&&t.loopCount>=t.count?(this.clearTask(t.taskID),!0):!1:!0}};l(
|
|
23
|
-
${r.stack}`)),this.sendRequest(fi(this._configs.sdkAppId,ki.LOG),o)}sendRequest(t,e){setTimeout(()=>_i({url:t,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},Le=new sm;var Oo=new WeakMap;function ji({settings:i={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:r}){return function(o,s,a){let d=Vi({retryFunction:a.value,settings:i,onError({error:h,retry:p,reject:T,retryFuncArgs:y}){var R;t?t.call(this,h,()=>{var N;(N=Oo.get(o))!=null&&N.has(s)?p():T(h)},T,y):(R=Oo.get(o))!=null&&R.has(s)?p():T(h)},onRetrying(h,p){var T;Ui(e)&&e.call(this,h,p),(T=Oo.get(o))!=null&&T.has(s)&&(Oo.get(o).get(s).stopRetry=p)},onRetryFailed:r});return a.value=function(...h){let p=Oo.get(o);return p?p.set(s,{args:h}):Oo.set(o,new Map([[s,{args:h}]])),d.apply(this,h).finally(()=>{var T;return(T=Oo.get(o))==null?void 0:T.delete(s)})},a}}var Jr=class extends Z{constructor(e,r){super(e.id,`${r}-player`);this.kind=r;l(this,"id");l(this,"element",null);l(this,"track");l(this,"url");l(this,"attr");l(this,"mode");l(this,"muted");l(this,"_log");l(this,"_pausedRetryCount");l(this,"_isElementPlayingFired",!1);l(this,"_interval");l(this,"_delayDestroyTimeoutId",0);l(this,"_playSuccessResolve");l(this,"_isReplayByRecreateMediaStreamCalled",!1);l(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=ap,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${r}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&(((e=this.element)==null?void 0:e.paused)===!1||this.track&&this.track.readyState==="live"&&!this.track.muted)}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return v(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,r)=>{this._playSuccessResolve=e,this.element.play().then(e,r)})}catch(e){let r=ot({key:it.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),r.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new de({code:Y.PLAY_NOT_ALLOWED,message:r})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Bi?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(D.ENDED),this._interval>0&&Et.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Rp?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return Rt(this.element,this.element).add(D.PLAYING,e).add(D.ENDED,e).add(D.PAUSE,e).add(D.ERROR,e).add(D.LOADEDDATA,e)}}bindTrackEvents(e=this.track){if(e){let r=this.handleTrackEvent.bind(this);zr==null||zr.create(e,e).add(D.ENDED,r).add(D.MUTE,r).add(D.UNMUTE,r),e.readyState===D.ENDED&&this.handleTrackEvent({type:D.ENDED}),e.muted&&this.handleTrackEvent({type:D.MUTE})}}bindAutoPlayEvent(){B.on(O.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&ct(e)}unbindEvents(){this.element&&ct(this.element),this.unbindTrackEvents(),B.off(O.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case D.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(D.PLAYING),this._interval&&(Et.clearTask(this._interval),this._interval=-1);break;case D.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(D.ENDED);break;case D.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(D.PAUSE),Ht&&(this._interval=Et.run(Ts,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case D.ERROR:if(this.element&&this.element.error){this.handlePaused(D.ERROR);let{code:o,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${o} message: ${s} userAgent: ${navigator.userAgent}`),Le.uploadEvent({log:`stat-${this.kind}-${mi.PLAYER_ERROR}-${o}-${navigator.userAgent}`,error:this.element.error}),Ap||yp?this.emit(at.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case D.LOADEDDATA:this.kind===D.VIDEO&&this.emit(at.LOADED_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Le.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),X.addSuccessEvent({key:this.kind===D.AUDIO?506700:516700})}).catch(()=>{var r;this._log.error("replayByRecreateMediaStream failed"),Le.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),X.addFailedEvent({key:this.kind===D.AUDIO?506700:516700,error:(r=this.element)==null?void 0:r.error}),this.emit(at.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((r,o)=>{oa(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,a,d;this._log.warn(`element onerror ${(a=(s=this.element)==null?void 0:s.error)==null?void 0:a.code} fired after recreated mediaStream`),o((d=this.element)==null?void 0:d.error)}),oa(5e3).then(()=>{var s,a;(!this.isPlaying||((s=this.element)==null?void 0:s.error))&&o((a=this.element)==null?void 0:a.error),r()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case D.ENDED:this.handleStopped(D.ENDED);break;case D.MUTE:this.handlePaused(D.MUTE);break;case D.UNMUTE:this._isElementPlayingFired?this.handlePlaying(D.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString());break}}handlePlaying(e){var r;(r=this._playSuccessResolve)==null||r.call(this,e),this.emit(at.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(at.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(at.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};q([ji({settings:{retries:2,timeout:0},onError(i,t,e,r){r[0]=(r[0]||1e3)+1e3,t()}})],Jr.prototype,"doReplayByRecreateMediaStream",1),q([be([],"PLAYING",{sync:!0})],Jr.prototype,"handlePlaying",1),q([be("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],Jr.prototype,"handlePaused",1),q([be([],"STOPPED",{sync:!0})],Jr.prototype,"handleStopped",1);var bi="trtc_autoplay",nm=`${bi}_mask`,Hs=`${bi}_wrapper`,Z_=`${bi}_header`,am=`${bi}_content`,Wd=`${bi}_action_wrapper`,cm=`${bi}_question`,dm=`${bi}_collapse`,Gd=`${bi}_action_confirm`,K_=`${bi}_detail`,eg="#2473E8",lm="dialog",HI=`${lm}-show`,WI=`${lm}-1`,GI=`${lm}-2`,tg=!1,pm=()=>!!document.querySelector(`.${Hs}`),ig=`${Fr}/${vr()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,rg=`<br><a href='${ig}' target='_blank'>${vr()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,jI=`${vr()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${rg}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${rg}`}`,um=class{constructor(){l(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");l(this,"_dialogNode",null);l(this,"_bodyPosition","");l(this,"_showDetail",!1);l(this,"_isCollapseClicked",!1);l(this,"_isQuestionClicked",!1);if(vr()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!tg){let t=document.createElement("style");t.innerHTML=`.${nm}{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.${nm} div:not(.${Wd}){display:block !important;}.${Hs}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Hs} a{color:${eg};}.${Z_}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${am}{margin:8px 0;}.${Wd}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${dm}{margin-right:auto;cursor:pointer}.${cm}{height:100%;line-height:16px;cursor:pointer;}.${Gd}{margin-left:8px;color:#fff;background:${eg};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Gd}:hover{opacity:0.9;}.${dm},.${Gd},.${am},.${cm}{font-size:14px;}@media screen and (max-width:750px){.${Hs}{width:80vw;}}`,document.head.appendChild(t),tg=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${nm}"><div class='${Hs}'><div class='${Z_}'>${location.host}</div><div class='${am}'>${this.content}</div><div class='${K_}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${jI}</div><div class='${Wd}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Gd,e.innerText=vr()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=cm,r.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
22
|
+
`],{type:"application/javascript"})));e.onmessage=r=>{r.data==="tick"&&(t.callback(),t.loopCount+=1,this.isBreakLoop(t)&&e.postMessage("stop"))},t.worker=e,e.postMessage("start")}static timeout(t){let e=()=>{if(t.callback(),t.loopCount+=1,!this.isBreakLoop(t))return t.timeoutID=setTimeout(e,t.delay)};return t.timeoutID=setTimeout(e,t.delay)}static ric(t){let e=ge(),r,o=()=>{if(r=ge()-e,r>=t.delay&&(e=ge()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.ricID=Y_(o,{timeout:t.delay})};return t.ricID=Y_(o,{timeout:t.delay})}static raf(t){t.delay=(1e3/t.fps).toFixed(2);let e=ge(),r,o=()=>{if(document.hidden&&t.backgroundTask)return r=ge()-e,e=ge(),t.callback(),t.loopCount+=1,this.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(o,t.delay-Math.floor(r%t.delay));if(r=ge()-e,r>=t.delay&&(e=ge()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.rafID=requestAnimationFrame(o)};if(t.rafID=requestAnimationFrame(o),t.backgroundTask){let s=()=>{if(document.hidden){let a=ge()-e;a>=t.delay?o():t.timeoutID=setTimeout(o,t.delay-a)}};document.addEventListener("visibilitychange",s),t.onVisibilitychange=s,document.hidden&&s()}return t.taskID}static hasTask(t){return this.taskMap.has(t)}static clearTask(t){if(!this.taskMap.has(t))return!0;let{intervalID:e,timeoutID:r,rafID:o,ricID:s,onVisibilitychange:a,worker:d}=this.taskMap.get(t);return d&&d.terminate(),e&&clearInterval(e),r&&clearTimeout(r),o&&$I(o),s&&FI(s),a&&document.removeEventListener("visibilitychange",a),this.taskMap.delete(t),!0}static isBreakLoop(t){return this.taskMap.has(t.taskID)?t.count!==0&&t.loopCount>=t.count?(this.clearTask(t.taskID),!0):!1:!0}};l(La,"taskMap",new Map),l(La,"currentTaskID",1);var Et=La;var Zb={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:D.SEI_MESSAGE,ERROR:"error"};var at={LOADED_DATA:D.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var zr={};li(zr,{create:()=>Rt,remove:()=>ct});var Ua=new WeakMap;function Rt(i,t){Ua.has(i)||Ua.set(i,[]);let e=Ua.get(i),o={add:(s,a)=>("addEventListener"in t?(e.push(t.removeEventListener.bind(t,s,a)),t.addEventListener(s,a)):(e.push(t.off.bind(t,s,a)),t.on(s,a)),o)};return o}function ct(i){let t=Ua.get(i);t&&(t.forEach(e=>e()),Ua.delete(i))}var sm=class{constructor(){l(this,"_roomIdMap",new Map);l(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Ke,env:pi.QCLOUD,browserVersion:jr.name+jr.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:e,userId:r,roomId:o}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=e,this._configs.userId=r,this._roomIdMap.set(r,String(o))}logSuccessEvent(t){wr||!V.isAbleToUpload||this._configs.env===pi.QCLOUD&&this.uploadEventToKibana(me(J({},t),{result:"success"}))}logFailedEvent(t){if(wr||!V.isAbleToUpload)return;let{eventType:e,code:r,error:o,userId:s}=t,a={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:r||(o==null?void 0:o.extraCode)||(o==null?void 0:o.code)||Y.UNKNOWN};this._configs.env===pi.QCLOUD&&this.uploadEventToKibana(me(J({},a),{error:o}))}uploadEventToKibana(t){let e=`stat-${t.eventType}-${t.result}`;(t.eventType==="delta-join"||t.eventType==="delta-leave"||t.eventType==="delta-publish")&&(e=`${t.eventType}:${t.delta}`),this.uploadEvent({log:e,userId:t.userId}),t.result==="failed"&&(e=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:e,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:e,error:r}){let o={timestamp:zc(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Ke,log:t};r&&(o.errorInfo=r.message,r.stack&&(o.errorInfo+=`
|
|
23
|
+
${r.stack}`)),this.sendRequest(fi(this._configs.sdkAppId,ki.LOG),o)}sendRequest(t,e){setTimeout(()=>_i({url:t,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},Le=new sm;var Oo=new WeakMap;function ji({settings:i={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:r}){return function(o,s,a){let d=Vi({retryFunction:a.value,settings:i,onError({error:h,retry:p,reject:T,retryFuncArgs:y}){var R;t?t.call(this,h,()=>{var N;(N=Oo.get(o))!=null&&N.has(s)?p():T(h)},T,y):(R=Oo.get(o))!=null&&R.has(s)?p():T(h)},onRetrying(h,p){var T;Ui(e)&&e.call(this,h,p),(T=Oo.get(o))!=null&&T.has(s)&&(Oo.get(o).get(s).stopRetry=p)},onRetryFailed:r});return a.value=function(...h){let p=Oo.get(o);return p?p.set(s,{args:h}):Oo.set(o,new Map([[s,{args:h}]])),d.apply(this,h).finally(()=>{var T;return(T=Oo.get(o))==null?void 0:T.delete(s)})},a}}var Jr=class extends Z{constructor(e,r){super(e.id,`${r}-player`);this.kind=r;l(this,"id");l(this,"element",null);l(this,"track");l(this,"url");l(this,"attr");l(this,"mode");l(this,"muted");l(this,"_log");l(this,"_pausedRetryCount");l(this,"_isElementPlayingFired",!1);l(this,"_interval");l(this,"_delayDestroyTimeoutId",0);l(this,"_playSuccessResolve");l(this,"_isReplayByRecreateMediaStreamCalled",!1);l(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=ap,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${r}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&(((e=this.element)==null?void 0:e.paused)===!1||this.track&&this.track.readyState==="live"&&!this.track.muted)}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return v(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,r)=>{this._playSuccessResolve=e,this.element.play().then(e,r)})}catch(e){let r=ot({key:it.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),r.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new de({code:Y.PLAY_NOT_ALLOWED,message:r})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Bi?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(D.ENDED),this._interval>0&&Et.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Rp?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return Rt(this.element,this.element).add(D.PLAYING,e).add(D.ENDED,e).add(D.PAUSE,e).add(D.ERROR,e).add(D.LOADEDDATA,e)}}bindTrackEvents(e=this.track){if(e){let r=this.handleTrackEvent.bind(this);zr==null||zr.create(e,e).add(D.ENDED,r).add(D.MUTE,r).add(D.UNMUTE,r),e.readyState===D.ENDED&&this.handleTrackEvent({type:D.ENDED}),e.muted&&this.handleTrackEvent({type:D.MUTE})}}bindAutoPlayEvent(){B.on(O.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&ct(e)}unbindEvents(){this.element&&ct(this.element),this.unbindTrackEvents(),B.off(O.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case D.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(D.PLAYING),this._interval&&(Et.clearTask(this._interval),this._interval=-1);break;case D.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(D.ENDED);break;case D.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(D.PAUSE),Ht&&(this._interval=Et.run(Ts,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case D.ERROR:if(this.element&&this.element.error){this.handlePaused(D.ERROR);let{code:o,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${o} message: ${s} userAgent: ${navigator.userAgent}`),Le.uploadEvent({log:`stat-${this.kind}-${mi.PLAYER_ERROR}-${o}-${navigator.userAgent}`,error:this.element.error}),Ap||yp?this.emit(at.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case D.LOADEDDATA:this.kind===D.VIDEO&&this.emit(at.LOADED_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Le.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),X.addSuccessEvent({key:this.kind===D.AUDIO?506700:516700})}).catch(()=>{var r;this._log.error("replayByRecreateMediaStream failed"),Le.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),X.addFailedEvent({key:this.kind===D.AUDIO?506700:516700,error:(r=this.element)==null?void 0:r.error}),this.emit(at.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((r,o)=>{sa(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,a,d;this._log.warn(`element onerror ${(a=(s=this.element)==null?void 0:s.error)==null?void 0:a.code} fired after recreated mediaStream`),o((d=this.element)==null?void 0:d.error)}),sa(5e3).then(()=>{var s,a;(!this.isPlaying||((s=this.element)==null?void 0:s.error))&&o((a=this.element)==null?void 0:a.error),r()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case D.ENDED:this.handleStopped(D.ENDED);break;case D.MUTE:this.handlePaused(D.MUTE);break;case D.UNMUTE:this._isElementPlayingFired?this.handlePlaying(D.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString());break}}handlePlaying(e){var r;(r=this._playSuccessResolve)==null||r.call(this,e),this.emit(at.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(at.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(at.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};q([ji({settings:{retries:2,timeout:0},onError(i,t,e,r){r[0]=(r[0]||1e3)+1e3,t()}})],Jr.prototype,"doReplayByRecreateMediaStream",1),q([be([],"PLAYING",{sync:!0})],Jr.prototype,"handlePlaying",1),q([be("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],Jr.prototype,"handlePaused",1),q([be([],"STOPPED",{sync:!0})],Jr.prototype,"handleStopped",1);var bi="trtc_autoplay",nm=`${bi}_mask`,Hs=`${bi}_wrapper`,Z_=`${bi}_header`,am=`${bi}_content`,Wd=`${bi}_action_wrapper`,cm=`${bi}_question`,dm=`${bi}_collapse`,Gd=`${bi}_action_confirm`,K_=`${bi}_detail`,eg="#2473E8",lm="dialog",HI=`${lm}-show`,WI=`${lm}-1`,GI=`${lm}-2`,tg=!1,pm=()=>!!document.querySelector(`.${Hs}`),ig=`${Fr}/${vr()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,rg=`<br><a href='${ig}' target='_blank'>${vr()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,jI=`${vr()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${rg}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${rg}`}`,um=class{constructor(){l(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");l(this,"_dialogNode",null);l(this,"_bodyPosition","");l(this,"_showDetail",!1);l(this,"_isCollapseClicked",!1);l(this,"_isQuestionClicked",!1);if(vr()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!tg){let t=document.createElement("style");t.innerHTML=`.${nm}{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.${nm} div:not(.${Wd}){display:block !important;}.${Hs}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Hs} a{color:${eg};}.${Z_}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${am}{margin:8px 0;}.${Wd}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${dm}{margin-right:auto;cursor:pointer}.${cm}{height:100%;line-height:16px;cursor:pointer;}.${Gd}{margin-left:8px;color:#fff;background:${eg};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Gd}:hover{opacity:0.9;}.${dm},.${Gd},.${am},.${cm}{font-size:14px;}@media screen and (max-width:750px){.${Hs}{width:80vw;}}`,document.head.appendChild(t),tg=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${nm}"><div class='${Hs}'><div class='${Z_}'>${location.host}</div><div class='${am}'>${this.content}</div><div class='${K_}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${jI}</div><div class='${Wd}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Gd,e.innerText=vr()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=cm,r.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
24
24
|
<svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
|
|
25
25
|
<path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>
|
|
26
26
|
<path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
|
|
27
27
|
<path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
|
|
28
28
|
</svg>
|
|
29
|
-
`,r.onclick=this.onQuestionClick.bind(this);let o=document.createElement("div");o.className=dm,o.innerText=`${vr()?"\u8BE6\u60C5 >":"Detail >"}`,o.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,a=s.querySelector(`.${Wd}`);return a.appendChild(o),a.appendChild(r),a.appendChild(e),s}addDiaLog(){pm()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Hs}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",V.info("show autoplay dialog"),Le.uploadEvent({log:HI}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){V.warn("confirm clicked, try resume stream"),B.emit(O.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${K_}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Le.uploadEvent({log:WI}),this._isCollapseClicked=!0}onQuestionClick(){window.open(ig,"_blank"),this._isQuestionClicked||Le.uploadEvent({log:GI}),this._isQuestionClicked=!0}},og=um;var or=class extends Jr{constructor(e){super(e,D.VIDEO);l(this,"stat",{});l(this,"_calculateTimeout",-1);l(this,"viewMirror",!1);l(this,"objectFit");l(this,"container");l(this,"canvas");l(this,"canvasTrack");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,L(e.viewMirror)||(this.viewMirror=e.viewMirror),L(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var r;let e=document.createElement(D.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(r=this.container)==null||r.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var r;this.container=e,(this.track||this.canvasTrack)&&this.elementToRender&&((r=this.container)==null||r.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(D.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(D.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var r;super.handleTrackEvent(e),e.type===D.MUTE&&((r=this.stat)==null?void 0:r.fps)&&(this.stat.fps=0)}handleElementEvent(e){var o;if(this.mode===2)return;super.handleElementEvent(e);let r=e.type;if(r===D.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(o=this.container)==null?void 0:o.id}`),this._pausedRetryCount>0&&!pm()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let s=this.element.style.transform;r===D.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=s.replace("scaleX(-1)",""):r===D.LEAVE_PICTURE_IN_PICTURE&&!s.includes("scaleX")&&(this.element.style.transform=`${s} scaleX(-1)`)}}setCanvas(e,r=1){var o,s,a,d;this.canvas!==e&&((o=this.canvas)==null||o.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?r:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(a=this.container)==null||a.appendChild(e)):this.element&&((d=this.container)==null||d.appendChild(this.element)))}setAttr(e){let r=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);r.style=Object.assign({width:"100%",height:"100%"},r.style),super.setAttr(r)}get mirror(){return this.viewMirror}setRect(e,r){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${r}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}stop(e=0){var r;super.stop(e),(r=this.canvas)==null||r.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(at.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Mo()&&this.element&&this._calculateTimeout<0){let e=0,r=null,o=(s,a)=>{this.stat.width=a.width,this.stat.height=a.height,r&&(this.stat.fps=Math.round((a.presentedFrames-r.presentedFrames)/(s-e)*1e3)),e=s,r=a,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var d;return(d=this.element)==null?void 0:d.requestVideoFrameCallback(o)},2e3))};this.element.requestVideoFrameCallback(o)}}catch(e){this._log.warn("init stat failed",e)}}};function Po(i,t){return v(this,null,function*(){if(!i.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield i.audioWorklet.addModule(t),V.info("worklet addModule success")}catch(e){throw V.info(`worklet addModule catch error. ${e.message}`),e}})}var Ua;typeof AudioContext!="undefined"?Ua=AudioContext:typeof webkitAudioContext!="undefined"?Ua=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Ua=mozAudioContext);var vi,sg=-1;ng();function ng(){try{if(vi)return;vi=new Ua({sampleRate:48e3}),vi.onstatechange=()=>{V.info(`context state: ${vi.state}`),Ws()},clearTimeout(sg)}catch(i){V.error(`initAudioContext failed: ${i} typeof AudioContextClass: ${typeof Ua}`),sg=setTimeout(ng,1e3)}}var Ws=()=>{vi.state==="suspended"?(vi.resume(),document.addEventListener("click",Ws)):vi.state==="interrupted"?vi.resume().catch(i=>{V.warn(`resume failed: ${i}`),document.addEventListener("visibilitychange",Ws)}):(document.removeEventListener("visibilitychange",Ws),document.removeEventListener("click",Ws))};document.addEventListener("click",Ws);var qt=i=>vi;var mr=class{constructor(){l(this,"node");l(this,"pre",new Set);l(this,"next",new Set);l(this,"context");l(this,"connectedNodes",new Set);l(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(t){this._channelCount=t,this.node&&(this.node.channelCount=t),this.next.forEach(e=>e.channelCount=t)}setContext(t){this.context=t,this.node&&t.addMixWeight()}removeContext(){var t;this.node&&((t=this.context)==null||t.reduceMixWeight()),delete this.context}setNode(t){var e;if(!this.node)try{(e=this.context)==null||e.addMixWeight(),this.node=t,this.node.channelCountMode="explicit",this.node.channelCount=this._channelCount,this.preNodeReconnect(),this.reconnect(),X.addSuccessEvent({key:502701})}catch(r){V.error(r),X.addFailedEvent({key:502701,error:r})}}deleteNode(){var t;if(!!this.node)try{this._disconnect(),delete this.node,(t=this.context)==null||t.reduceMixWeight(),this.preNodeReconnect(),X.addSuccessEvent({key:502702})}catch(e){V.error(e),X.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(e=>t._connect(e.node)||e.connectNext(t))}_connect(t){return!this.node||!t?!1:(this.node.connect(t),this.connectedNodes.add(t),!0)}_disconnect(){this.connectedNodes.forEach(t=>{var e;return(e=this.node)==null?void 0:e.disconnect(t)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...t){return t.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},jd=class extends mr{constructor(e=256){super();this.fftSize=e;l(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),r=1,o=0,s=0,a=`M${o},${s}`;for(let d=0;d<e.length;d++)s=e[d]/128*100/2,a+=`L${o},${s}`,o+=r;return a}},Va=class{constructor(){l(this,"source",new mr);l(this,"gain",new mr);l(this,"destination",new mr)}get volume(){var t;return((t=this.gain.node)==null?void 0:t.gain.value)||1}setVolume(t){if(t===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=t}replaceSource(t){this.source.deleteNode(),this.source.setNode(mm(t))}get track(){var t;return(t=this.stream)==null?void 0:t.getAudioTracks()[0]}get stream(){var t;return(t=this.destination.node)==null?void 0:t.stream}},Gs=class extends Va{constructor(e){super();this.context=e;l(this,"denoiser",new mr);this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},qd=class{constructor(){l(this,"audioContext",qt("audio-mixer"));l(this,"destination",this.audioContext.createMediaStreamDestination());l(this,"inputs",new Set);l(this,"mixWeight",0)}addMixWeight(t=1){this.mixWeight+=t,this.mixWeight-1===t+1>>1&&this.mixOnChange()}reduceMixWeight(t=1){this.addMixWeight(-t)}close(){this.inputs.forEach(t=>t.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},ag=new WeakMap;function mm(i){let t=ag.get(i);if(t)return t;let e=qt();if(i instanceof HTMLAudioElement)t=e.createMediaElementSource(i);else if(i instanceof MediaStreamTrack)t=e.createMediaStreamSource(new MediaStream([i]));else return i;return ag.set(i,t),t}var Xr=class{constructor(t){l(this,"_volume",0);l(this,"_log");l(this,"_scriptProcessorNode",null);l(this,"_audioWorkletNode",null);l(this,"_interval",200);l(this,"ready",this.preload());let{log:e}=t;this._log=e,B.on(O.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Xr.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Xr.workletReady){let t='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,e){t=t[0],e=e[0];if(t||e){if(this.isStop)return!1;var s=e&&e[0]?e[0].length:0,i=this.cache.length,h=(s<i?(e[0].set(this.cache.slice(0,s)),this.cache=this.cache.slice(s)):this.unmute&&e[0].set(t[0]),(s<i?e:t)[0]);if(h){let e=0;for(let t=0;t<h.length;++t)e=Math.max(Math.abs(h[t]),e);this.volume=e,this.tick-=h.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,cacheLen:i,outputLen:s}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Xr.workletReady=Po(Xr.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return Xr.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error(`volumeMeter preload error: ${t}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Xr.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=e=>{Xr.lastMessageTime=Date.now(),this._volume=e.data.volume||0,!t&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(t){this._log.error(`volumeMeter init audio worklet error: ${t}`),Le.logFailedEvent({userId:this._log.userId,eventType:mi.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=qt("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{Xr.lastMessageTime=Date.now();let e=t.inputBuffer.getChannelData(0),r=0;for(let o=0;o<e.length;++o)r+=e[o]*e[o];this._volume=Math.sqrt(r/e.length)||0}}catch(t){this._log.error(`volumeMeter init script processor error: ${t}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,B.off(O.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(t){var r;let{interval:e}=t;this._interval=e,(r=this._audioWorkletNode)==null||r.port.postMessage({name:"setIntervalTime",intervalTime:e})}},js=Xr;l(js,"lastMessageTime",0),l(js,"audioContext",qt("volume-meter")),l(js,"workletReady");var zd=class extends mr{constructor(e){super();l(this,"_volumeMeter");this._volumeMeter=new js(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return v(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let r=e.allocationSize({planeIndex:0}),o=new Float32Array(r>>2);e.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),e.close()}}};var lg=Pi(Hi(),1);var dg=i=>t=>t.deviceId===i;var Ba=class{constructor(t,e="Input"){l(this,"kind");l(this,"type");l(this,"devices",[]);this.kind=t,this.type=e}update(t,e){let r=t.filter(o=>o.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&qs(this.devices[0])){this.devices=r;return}e&&(r.forEach(o=>{if(o.deviceId&&!this.devices.find(dg(o.deviceId))){let s=`${this.kind}${this.type}Added`;V.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}}),this.devices.forEach(o=>{if(o.deviceId&&!r.find(dg(o.deviceId))){let s=`${this.kind}${this.type}Removed`;V.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},hm=class extends lg.EventEmitter{constructor(){super();l(this,"audioInputs",new Ba(D.AUDIO));l(this,"videoInputs",new Ba(D.VIDEO));l(this,"audioOutputs",new Ba(D.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Et.run(To,()=>{this.update()},{delay:1e4}))}init(){Jd().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return v(this,arguments,function*(e=0){let r=yield Jd(e);return this.audioInputs.update(r,this),this.videoInputs.update(r,this),this.audioOutputs.update(r,this),this})}},_t=qn||fs?null:new hm;function qs(i){return i.deviceId===i.groupId&&i.groupId===""}function Jd(){return v(this,arguments,function*(i=0){if(Ai()||!Fd())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(i!==0){let e={audio:!1,video:!1};if(t.forEach(r=>{qs(r)&&(r.kind===D.AUDIO_INPUT?e.audio=!0:r.kind===D.VIDEO_INPUT&&(e.video=!0))}),i===2&&(e.audio=!1),i===1&&(e.video=!1),e.audio||e.video){let r;try{r=yield navigator.mediaDevices.getUserMedia(e)}catch(o){V.debug("capture before getDevices failed: ",o)}t=yield navigator.mediaDevices.enumerateDevices(),r==null||r.getTracks().forEach(o=>o.stop())}}return t.map((e,r)=>{let o={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${r}`};return e.deviceId.length>0&&fm.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(o.getCapabilities=()=>e.getCapabilities()),o})})}function zt(i=!1){return _t.update(i?1:0).then(t=>t.audioInputs.devices)}function sr(i=!1){return _t.update(i?2:0).then(t=>t.videoInputs.devices)}var ug=!1;function pg(){return v(this,null,function*(){try{ug||(ug=!0,V.info(`speakers:${(yield qi()).map(i=>` ${i.deviceId.slice(0,8)}: ${i.label}`)}`))}catch(i){}})}function qi(i=!1){return v(this,null,function*(){return _t.update(i?1:0).then(t=>t.audioOutputs.devices)})}var fm=new Set;function mg(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${D.VIDEO_INPUT}`;return!!fm.has(r)}function hg(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("\u9EA6\u514B\u98CE"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${D.AUDIO_INPUT}`;return!!fm.has(r)}function _m(i,t){return v(this,null,function*(){let r=(yield zt()).find(o=>o.deviceId===Eo);return!t&&(r==null?void 0:r.groupId)===i||(r==null?void 0:r.groupId)===i&&r.label===t})}function fg(s){return v(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:o}){return i!==t?!1:o===D.AUDIO&&i===Eo?yield _m(e,r):!0})}var Xd,gm=class extends Va{constructor(e){super();this.log=e;l(this,"volumeMeter");l(this,"volumeDestination");l(this,"analyser",new jd);this.volumeMeter=new zd({log:this.log}),this.volumeDestination=new mr,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},zs=class extends Jr{constructor(e){super(e,D.AUDIO);l(this,"_outputDeviceId");l(this,"_volume",1);l(this,"_destination",qt("player").createMediaStreamDestination());l(this,"pipeline");l(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new gm(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(($i==="15.2"||$i==="15.3"||$i==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let o=Xd||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.element=o,Fe(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),o===Xd&&(Xd=void 0),this.bindElementEvents()}play(e){return v(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(qt("player").createAnalyser()),pg(),Lt(zs.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return v(this,null,function*(){var r,o;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(o=(r=this.element).setSinkId)==null?void 0:o.call(r,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},Qd=class extends zs{constructor(t){super(t),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(t){var e;this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(at.MEDIA_TRACK_CHANGED,t),t?(this.bindTrackEvents(),this.pipeline.source.channelCount=((e=t.getSettings())==null?void 0:e.channelCount)||1,this.pipeline.replaceSource(t),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([t]))):this.pipeline.source.deleteNode())}setSourceNode(t){!t||this.pipeline.source.node===t||(this.pipeline.replaceSource(t),t instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(t){this._volume=t,this.element&&(this.element.volume=t)}},Yd=class extends zs{constructor(e){super(e);l(this,"_sourceElement");l(this,"_output",new mr);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(qt("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var r,o,s;((o=(r=this.element)==null?void 0:r.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(at.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),ct(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();let r=this._sourceElement||this.element;r&&Bi&&(Xd=r),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var ko=class extends Z{constructor({userId:e,sdkAppId:r,mediaType:o,room:s,PlayerClass:a=o===1?Yd:or}){var d;super();l(this,"id",Sa());l(this,"userId","");l(this,"isRemote");l(this,"mediaType");l(this,"room");l(this,"user");l(this,"_log");l(this,"_inputTrack");l(this,"_outputTrack");l(this,"isPlayCalled");l(this,"container",null);l(this,"player");l(this,"subVideoPlayerMap");l(this,"muted",!1);l(this,"abortCtrl");l(this,"objectFit","cover");l(this,"mirror");l(this,"isScreen",!1);l(this,"manager");l(this,"trackSettings");this.userId=e||"",this.mediaType=o,this._log=V.createLogger({id:`${this.kind[0]}t`,userId:(d=s||this.room)==null?void 0:d.userId,remoteUserId:this instanceof nr?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof nr}),this.player=new a({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(at.PLAYER_STATE_CHANGED,h=>{B.emit(O.PLAYER_STATE_CHANGED,J({track:this},h)),this.emit("player-state-changed",h)}),this.kind===D.VIDEO&&(this.player.on(at.LOADED_DATA,()=>{B.emit(O.VIDEO_LOADED_DATA,{track:this})}),this.player.on(at.MEDIA_TRACK_CHANGED,h=>{var p;(p=this.subVideoPlayerMap)==null||p.forEach(T=>T.setTrack(h))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(at.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||V}get kind(){return this.mediaType===1?D.AUDIO:D.VIDEO}get strMediaType(){return this.mediaType===4?D.VIDEO:this.mediaType===2?D.SCREEN:D.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,r){return v(this,null,function*(){let o=rt(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(r)}`),r&&!L(r.muted)&&this.setPlayerMute(r.muted),r&&!L(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof or&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(this.container=o,this.player.setContainer(o)),rt(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if(r&&!L(r.muted)?this.setPlayerMute(r.muted):(!this.isRemote||this.kind===D.VIDEO)&&this.setPlayerMute(!0),r&&!L(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof or&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof or&&this.player.setContainer(o)),B.emit(O.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(r)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(r),rt(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),r))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,r){if(this.isScreen||this.kind!==D.VIDEO||L(e)||e===this.mirror)return;this.mirror=e;let o=this.player;r&&(o=r);let s=this.manager;if(nt(this.mirror)){o.setViewMirror(this.mirror),s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),o.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),o.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),o.setViewMirror(!1)}}playSubContainer(e,r){return v(this,null,function*(){if(!this._outputTrack||this.kind===D.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,a)=>{var d;e.find(h=>a===h)||(s.stop(),(d=this.subVideoPlayerMap)==null||d.delete(a))});for(let[s,a]of e.entries()){let d=this.subVideoPlayerMap.get(a);d?r&&(L(r.objectFit)||d.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(a,new or({id:this.userId||this.id,track:this.playerMediaTrack,container:a,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let o=[...this.subVideoPlayerMap.values()];for(let s of o)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(hp(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(r=>{r.stop()}),this.container=null)}resume(){return v(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),B.emit(e?O.TRACK_MUTED:O.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){Rt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ct(e)}setInputMediaStreamTrack(e){var o;let r=this._inputTrack;if(e!==r)return this._inputTrack=e,this.trackSettings=(o=e.getSettings)==null?void 0:o.call(e),e.enabled=!this.muted,r&&this.uninstallTrackEvent(r),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,r||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var o;let r=this._outputTrack;e!==r&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(o=e.getSettings)==null?void 0:o.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(r=>this.handleAutoPlayFailed(r)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(hp(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new og;else{let r=()=>{this.resume().then(()=>{document.removeEventListener("click",r,!0)})};document.addEventListener("click",r,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof or?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};q([be([],Z.INIT,{sync:!0})],ko.prototype,"close",1);var qI=Object.prototype.hasOwnProperty,{toString:aC}=Object.prototype;function zI(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if($t(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(qI.call(i,t))return!1;return!0}}return!1}var Fa=zI;var JI=function(i){return v(this,null,function*(){let t=QI(i);V.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],r=[],o=["label","deviceId","groupId"];t.audio&&(e=yield zt(),V.info(`microphones: ${pr(e.map(s=>me(J({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:o})}`)),t.video&&(r=yield sr(),V.info(`cameras: ${pr(r,{keysToInclude:o})}`));try{let s=yield navigator.mediaDevices.getUserMedia(t);return tm&&s.getTracks().forEach(a=>{V.info(`${a.kind} capabilities: ${pr(a.getCapabilities(),{keysToInclude:rd})}`)}),s}catch(s){let{message:a}=s;throw s.name==="NotFoundError"&&(i.video&&r&&r.length===0&&(a=ot({key:it.CAMERA_NOT_FOUND})),i.audio&&e&&e.length===0&&(a=ot({key:it.MICROPHONE_NOT_FOUND}))),new de({code:Y.INITIALIZE_FAILED,name:s.name,message:a,constraint:s.constraint})}})},XI=Vi({retryFunction:JI,settings:{retries:3,timeout:500},onError:({error:i,retry:t,reject:e,retryFuncArgs:r,retriedCount:o})=>{let s=o+1;i.name==="NotReadableError"||i.name==="OverconstrainedError"?(s===1?(r[0].video&&(r[0].maxResolution=!1,(!Wt||r[0].width*r[0].height<=1920*1080)&&r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),r[0].retryWhenExactFailed&&r[0].useExactDeviceId&&(r[0].useExactDeviceId=!1)):s===2?r[0].useDeviceIdOnly=!0:s===3&&!r[0].useExactDeviceId&&(r[0].useTrueAsConstraint=!0),t()):e(i),r[0].microphoneId&&_g(r[0].microphoneId,!1),r[0].cameraId&&_g(r[0].cameraId,!0)},onRetrying:i=>{V.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)},onRetryFailed:i=>{Le.logFailedEvent({eventType:mi.GET_USER_MEDIA_RETRY,error:i})},onRetrySuccess:i=>{Le.logSuccessEvent({eventType:mi.GET_USER_MEDIA_RETRY}),Le.uploadEvent({log:`stat-${mi.GET_USER_MEDIA_RETRY}-success-${i}`})}});function _g(i,t){return v(this,null,function*(){let r=(t?yield sr():yield zt()).find(o=>o.deviceId===i);r&&Ve(r.getCapabilities)&&V.warn(pr(r.getCapabilities(),{keysToInclude:rd}))})}function QI(i){return{audio:YI(i),video:ZI(i)}}function YI(i){if(!i.audio)return!1;if(i.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:i.sampleRate};return!Fa(i.microphoneId)&&(t.deviceId=i.useExactDeviceId?{exact:i.microphoneId}:i.microphoneId,i.useDeviceIdOnly)?t:(Fe(i.channelCount)&&(t.channelCount=i.channelCount),nt(i.echoCancellation)&&!i.echoCancellation&&(t.echoCancellation=!1),nt(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),nt(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),Fa(t)?!0:t)}function ZI(i){if(!i.video)return!1;if(i.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=i,e={};return i.cameraId?e.deviceId=i.useExactDeviceId?{exact:i.cameraId}:i.cameraId:i.facingMode&&(e.facingMode=i.facingMode),i.useDeviceIdOnly&&!Fa(e)?e:(i.width&&(e.width={ideal:i.width},t&&!Cr&&(e.width.max=i.width)),i.height&&(e.height={ideal:i.height},t&&!Cr&&(e.height.max=i.height)),Cr&&Nr&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),Fa(e)?!0:e)}var gg=XI;function zi(i){return Ce((t,e)=>function(...r){return v(this,null,function*(){let o=yield t.apply(this,r);return yield i.call(this,...r),o})})}function Ce(i){return function(t,e,r){return r.value=i(r.value,e),r}}var Eg=(()=>{let i=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&V.info(`visibility change: ${document.visibilityState}`),!i&&(document.addEventListener("visibilitychange",()=>{V.info(`visibility change: ${document.visibilityState}`),t=document.visibilityState}),i=!0)}})();var KI=0,Zd=class{constructor(){this.log=V.createLogger({id:`fq${++KI}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(t,e=!1){var s,a;let r=J({},t),o=new Promise((d,h)=>{r.resolve=d,r.reject=h});return r.promise=o,e?this.length<=1?this.queue.push(r):(a=(s=this.lastQueueItem)==null?void 0:s.promise)==null||a.then(r.resolve,r.reject):this.queue.push(r),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),o}shift(){let t=this.queue.shift();return this.log.debug(`shift ${this.length}`),t}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:t,args:e,context:r,resolve:o,reject:s}=this.queue[0];this.isRunning=!0,t.apply(r,e).then(o,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Tg=new WeakMap,Ig=new WeakMap;function Sg(i=!1){return function(t,e,r){let o=r.value;return r.value=function(...s){let a=Tg.get(this)||new Zd;return Tg.set(this,a),a.push({fn:o,args:s,context:this},i)},r}}function Kd(i){return function(t,e,r){let o=r.value,s=a=>i(...a);return r.value=function(...a){let d=Ig.get(this)||new Map,h=d.get(s(a))||new Zd;return d.set(s(a),h),Ig.set(this,d),h.push({fn:o,args:a,context:this})},r}}function eu(i,t){return Ce((e,r)=>function(...o){let s=i;try{let a=e.apply(this,o),d=ge();return Li(a)?a.then(h=>(t?X.addSuccessEvent({key:s,cost:ge()-d}):X.addSuccessEvent({key:s}),h)).catch(h=>{throw X.addFailedEvent({key:s,error:h}),h}):(X.addSuccessEvent({key:s}),a)}catch(a){throw X.addFailedEvent({key:s,error:a}),a}})}var Em=class extends ko{constructor(e,r){super({mediaType:e,PlayerClass:r});l(this,"isRemote",!1);l(this,"deviceId");l(this,"groupId","");l(this,"label","");l(this,"_isRecapturing",!1);l(this,"_lastRecaptureTime",0);l(this,"_onMuteTimeoutId",-1);l(this,"_encodeCheckTimeoutId",-1);l(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,r){throw new Error("Method not implemented.")}installTrackEvent(e){Rt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ct(e)}setStateToCapture(){}capture(e){return v(this,null,function*(){var r;try{let o=ge();B.emit(O.LOCAL_TRACK_CAPTURE_START,{track:this});let s;e.customSource?(s=new MediaStream,s.addTrack(e.customSource)):((r=this.mediaTrack)==null||r.stop(),s=yield gg(e));let a=s.getTracks()[0];return yield this.setInputMediaStreamTrack(a),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),B.emit(O.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:ge()-o}),s}catch(o){throw B.emit(O.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:o}),this.log.error(`getUserMedia error observed ${o}`),o}})}setInputMediaStreamTrack(e){return this.state===Z.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(r=this.room)==null?void 0:r.replaceTrack(this)}publish(e,r){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),r}unpublish(){this.room&&this.room.localTracks.delete(this),B.emit(O.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return v(this,null,function*(){if(this.mediaTrack&&Fs){let{deviceId:e,groupId:r}=this.mediaTrack.getSettings(),{label:o}=this.mediaTrack;(yield fg({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=o,r&&(this.groupId=r),Jd().then(a=>{let d=a.find(h=>h.deviceId===e);d&&this.emit("2",d)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===D.AUDIO&&!hg(this.mediaTrack)||this.kind===D.VIDEO&&!mg(this.mediaTrack)||this._isRecapturing||e&&Nr&&Wt)}onTrackMuted(){if(super.onTrackMuted(),Eg(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Es){setTimeout(()=>this.onTrackMuted(),Es);return}this._onMuteTimeoutId=setTimeout(()=>v(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Ht||ft)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return v(this,null,function*(){if(Lt(Em.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Es){setTimeout(()=>this.onTrackEnded(),Es);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return v(this,null,function*(){var o;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(o=this._inputTrack)==null||o.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let r={useExactDeviceId:!0};if(e==="user"||e==="environment")r.facingMode=e;else{let s;(this.kind==="audio"?yield zt():yield sr()).find(d=>d.deviceId===e)&&(s=e),r.deviceId=s}return this.capture(r).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),B.emit(O.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(s=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${s.message}`),this.emit("5",s),B.emit(O.LOCAL_TRACK_RECAPTURE,{track:this,error:s})})})}getRecoverCaptureDeviceId(){return v(this,null,function*(){let e=this instanceof hr;if(e&&this.facingMode)return this.facingMode;let{deviceId:r}=this;if(r){let o=($a.get(r)||0)+1;if($a.set(r,o),o>=3){let s=e?(yield sr()).find(a=>!$a.has(a.deviceId)):(yield zt()).find(a=>!$a.has(a.deviceId));s&&(this.log.warn(`${r} capture fail ${o} times, change new ${s.deviceId}`),r=s.deviceId)}}return r})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}},nr=Em;q([be(Z.INIT,"capture",{ignoreError:!0,sync:!0})],nr.prototype,"setStateToCapture",1),q([Sg()],nr.prototype,"capture",1),q([be("capture","publish",{ignoreError:!0,success(){var t,e;this.room.localTracks.add(this),B.emit(O.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((e=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:e.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var o,s;if(!((((s=(o=this.room)==null?void 0:o.networkQuality)==null?void 0:s.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let a=this.kind===D.AUDIO,d=this.stat.bytesSent>0;X[d?"addSuccessEvent":"addFailedEvent"]({key:a?503700:513702}),d||(X.addEnum({key:a?503701:513703,value:Ta()}),Le.uploadEvent({log:`stat-encode-failed-${this.kind}-${Ea()||vo()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(i){let t="error";if(i.cause instanceof RTCError){let e=i.cause;e.message.includes("timeout")?t="timeout":e.code===Y.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i.cause||i})}}),eu(521714,!1)],nr.prototype,"publish",1),q([Ce(i=>function(){return v(this,null,function*(){let t=this.state==="publish"?"started":"starting";i.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),be([],"capture",{sync:!0})],nr.prototype,"unpublish",1);var $a=new Map;B.on(O.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&$a.delete(i.track.deviceId)});var ar=class extends nr{constructor(e){super(1,Qd);l(this,"mediaType",1);l(this,"volume",0);l(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});l(this,"playerMuted",!0);l(this,"pipeline");l(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new Gs(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return v(this,null,function*(){let r=this.trackSettings||{};X.addEnum({key:501701,value:r.channelCount||0,useUV:!1}),X.addEnum({key:501702,value:r.sampleRate||0,useUV:!1}),X.addEnum({key:502700,value:0});let{sampleRate:o,channelCount:s}=r;this._log.info(`local audio track input ${JSON.stringify({sampleRate:o,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Lt(ar.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:r,useExactDeviceId:o=!0,retryWhenExactFailed:s=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:o,retryWhenExactFailed:s,customSource:r})}switchDevice(e){return v(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===Eo){if(yield _m(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),B.emit(O.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(r){throw this.log.error(`switch microphone failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}}})}listenDeviceChange(){_t&&!_t.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&_t.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return v(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),ze(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield zt();r[0]?this.recapture(r[0].deviceId):_t.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(s){return v(this,arguments,function*({echoCancellation:e,noiseSuppression:r,autoGainControl:o}){let a=!1;!L(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a=!0),!L(r)&&r!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=r,a=!0),!L(o)&&o!==this.profile.autoGainControl&&(this.profile.autoGainControl=o,a=!0),a&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&X.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let r=this._inputTrack.getConstraints();return r.noiseSuppression=e,this._inputTrack.applyConstraints(r).catch(o=>this._log.warn(`${e?"enable":"disable"} ANS failed `,o))}addDenoiser(e){var r;if(gi<=92&&((r=this.trackSettings)==null?void 0:r.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}X.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),_t.off("audioInputAdded",this.handleMicrophoneAdded,this),_t.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return v(this,null,function*(){try{yield Lt(ar.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield zt()).find(s=>s.deviceId!==e);if(o)yield Lt(ar.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((r,o)=>o?o({frame:r}):r,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Lo=class{constructor(t,e=!1){this.dataView=t;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,r=[],o=0;for(let a=t;a<=e;a++){let d=this.dataView.getInt8(a);switch(d){case 0:case 1:case 2:case 3:o===2&&(r.push(3),o=0),d==0?o++:o=0,r.push(d);break;default:o=0,r.push(d);break}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}removePreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,r=[],o=0;for(let a=t;a<=e;a++)switch(this.dataView.getInt8(a)){case 0:o++,r.push(this.dataView.getInt8(a));break;case 3:o!==2&&r.push(this.dataView.getInt8(a)),o=0;break;default:r.push(this.dataView.getInt8(a)),o=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let t=6;for(let e=6;e<this.dataView.buffer.byteLength&&(t++,this.dataView.getUint8(e)===255);e++);return t}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let t=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let a=this.dataView.getUint8(s);if(e++,a===255)t+=255;else{t+=a;break}}let r=new ArrayBuffer(t),o=new DataView(r);for(let s=0;s<r.byteLength;s++,e++)o.setInt8(s,this.dataView.getInt8(e));return o}};var tu=class{constructor(){l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_seiPayloadType",243)}encodeSEINalu(t){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let d=0;d<r;d++)s.push(255);s.push(o);let a=new DataView(t);return s.push(...new Uint8Array(a.buffer)),s.push(128),new Lo(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(t,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(t),e!=null&&e.small&&this._smallSeiMessageList.push(t)}isEmpty(){return!this._seiMessageList.length}getNaluCount(t){let e=0,r=0,o=new DataView(t);for(let s=0;s<t.byteLength;s++)switch(o.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&r++,e=0;break;default:e=0;break}return r}encode(t,e){let r=e?this._smallSeiMessageList:this._seiMessageList;if(r.length>0&&t.data.byteLength>0){let o=this.getNaluCount(t.data),s=9-o;if(s<=0)return 0;let a=r.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),d=a.reduce((R,N)=>R+N.dataView.byteLength,0),h=new ArrayBuffer(d+t.data.byteLength),p=new DataView(h),T=new DataView(t.data),y=0;for(let R=0;R<a.length;R++)for(let N=0;N<a[R].dataView.byteLength;N++)p.setInt8(y++,a[R].dataView.getInt8(N));for(let R=0;R<t.data.byteLength;R++)p.setInt8(y++,T.getInt8(R));return t.data=h,a.length}return 0}};var Js=class extends nr{constructor(e,r=4){super(r,or);l(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});l(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});l(this,"small");l(this,"isNeedToSetBandwidth");l(this,"muteImage");l(this,"manager");l(this,"_seiCodec",new tu);this.manager=e;let o=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(me(J({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",o),this.on("publish",o),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Fs||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return v(this,null,function*(){var r,o,s;if(Ae(e)){if(this.muteImage===e)return;yield(r=this.manager)==null?void 0:r.deleteWatermark("mute"),yield(o=this.manager)==null?void 0:o.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Lt(Js.prototype,this,"setMute").call(this,!1)}else yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0,Lt(Js.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:r,useExactDeviceId:o=!0,customSource:s,retryWhenExactFailed:a=!0}){return super.capture({audio:!1,video:!0,facingMode:r||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:o,retryWhenExactFailed:a,customSource:s})}setProfile(e){let r=J({},e),o=r.width>r.height;r.width*r.height<=160*120&&ft&&bo&&(this.log.warn(`resolution is ${r.width}*${r.height}, fallback to 240*180`),r.width=o?240:180,r.height=o?180:240,r.bitrate=Math.max(r.bitrate,150)),r.width*r.height>1280*720&&Cp&&(r.width=o?1280:720,r.height=o?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(r):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(me(J({},this.profile),{width:1920,height:1080})))}applyProfile(){return v(this,null,function*(){var o;if(!this.mediaTrack)return;let e=this.settings;if(!(!(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)||!this.deviceId)&&(ir===16?yield this.recapture(this.deviceId):(yield(o=this.mediaTrack)==null?void 0:o.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth))return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:D.VIDEO,videoType:D.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Fs&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:cd()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var r;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((r=this.room.scheduleResult.trtcAutoConf)==null?void 0:r["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return v(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let r={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?r.facingMode=e:r.deviceId=e,this.mediaTrack.stop(),yield this.capture(r),B.emit(O.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(r){throw this.log.error(`switch camera failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}})}listenDeviceChange(){_t&&!_t.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&_t.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return v(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),ze(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield sr();r[0]?this.recapture(r[0].deviceId):_t.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return v(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,r){if(!this.manager)return e;let o=r?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,a)=>a?a({frame:s,mediaType:o}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,r){return L(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,r)}close(){_t.off("videoInputAdded",this.handleCameraAdded,this),_t.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return v(this,null,function*(){try{yield Lt(Js.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield sr()).find(s=>s.deviceId!==e);if(o)yield Lt(Js.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}},hr=Js;q([zi(function(i){this.setContentHint(i.contentHint||"motion")})],hr.prototype,"capture",1);var bg=Sa();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:bg,exposeOrigin:!0,permittedOrigins:["*"]})}catch(i){}var rS=function(i){return v(this,null,function*(){let t=null,e=sS(i);V.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);i.systemAudio&&r.getAudioTracks().length===0&&(Os&&gi<74||Wt||Cr)&&V.warn("Your browser not support capture system audio");let o=r.getVideoTracks()[0];if(o){if(i.frameRate)try{yield o.applyConstraints({frameRate:{min:i.frameRate,ideal:i.frameRate},width:i.width,height:i.height})}catch(s){V.warn(`screen applyConstraints failed: ${s}`)}i.captureElement&&(yield iS(o,i.captureElement))}if(i.audio){let s=oS(i);V.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})};function iS(i,t){return v(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&Ve(i.cropTo))try{if(!(((e=i.getCaptureHandle())==null?void 0:e.handle)===bg))return;let o=yield CropTarget.fromElement(t);yield i.cropTo(o)}catch(r){V.warn(`cropTo target failed ${r}`)}})}function oS(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return L(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function sS(i){let t={preferCurrentTab:i.preferDisplaySurface==="current-tab"||!!i.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Wt?{max:i.width}:{ideal:i.width,max:i.width},height:Wt?{max:i.height}:{ideal:i.height,max:i.height},frameRate:i.frameRate,displaySurface:i.preferDisplaySurface||"monitor"};if(t.video=e,i.systemAudio){let{echoCancellation:r=!0,noiseSuppression:o=!1,autoGainControl:s=!1}=i;t.audio={echoCancellation:r,noiseSuppression:o,autoGainControl:s,sampleRate:48e3}}return t}var vg=rS;var Ji=class extends hr{constructor(e){super(e,2);l(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});l(this,"objectFit","contain");l(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(T){return v(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:s,audioTrack:a,videoTrack:d,captureElement:h,preferDisplaySurface:p}){try{let y;return d||a?(y=new MediaStream,d&&y.addTrack(d),a&&y.addTrack(a)):y=yield vg({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:s,captureElement:h,preferDisplaySurface:p}),yield this.setInputMediaStreamTrack(y.getVideoTracks()[0]),y}catch(y){throw this.log.error(`getDisplayMedia error observed ${y}`),y instanceof de?y:new de({code:Y.INITIALIZE_FAILED,name:y.name,message:y.message})}})}switchDevice(e){return v(this,null,function*(){throw new Error("Method not implemented.")})}};q([zi(function(i){this.setContentHint(i.contentHint||"detail")})],Ji.prototype,"capture",1);var Uo=class extends ar{constructor(t){super(t),this._log.id=`s-${this._log.id}`}};var nS="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Im;function Ha(i){return v(this,null,function*(){let t=qt("dump");Im||(Im=Po(t,URL.createObjectURL(new Blob([nS],{type:"application/javascript"})))),yield Im;let e=new AudioWorkletNode(t,"dumper",{numberOfInputs:i.length,numberOfOutputs:0});return i.forEach((r,o)=>r.connect(e,0,o)),new ReadableStream({start(r){e.port.onmessage=o=>{r.enqueue(o.data)}},cancel(){i.forEach(r=>r.disconnect(e)),e.port.close()}})})}var ru=class extends qd{constructor(e){super();this.room=e;l(this,"_localAudioTrack");l(this,"_localScreenAudioTrack");l(this,"log",V.createLogger({id:"am"}));l(this,"denoiser");l(this,"mixChangedDebounce");l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var T,y;if(!this._localAudioTrack)return;let r=[],o=[];(T=this._localAudioPipline)!=null&&T.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),(y=this._localAudioPipline)!=null&&y.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),o.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),o.push("mix")),this.log.info(`dump audio track ${o}, duration: ${e}`);let s=new AbortController,a=[],d=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),h=()=>{for(let R=0;R<o.length;R++){let N=URL.createObjectURL(new Blob(a[R])),j=document.createElement("a");j.href=N,j.download=`${o[R]}.pcm`,j.style.display="none",document.body.appendChild(j),j.click(),URL.revokeObjectURL(N),j.remove()}clearTimeout(d),s.abort("download")},p=Ha(r).then(R=>R.pipeTo(new WritableStream({write(N){N.forEach((j,W)=>a[W]=a[W]?a[W].concat(j[0]):[j[0]])}}),s).catch(N=>h));return{then:p.then.bind(p),download:h}}getPCM(e){var a;if(L(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((a=this._localAudioPipline)!=null&&a.source.node)){this.log.warn("getPCM failed: no local audio track");return}this.log.warn("getPCM");let r=new Float32Array(1920),o=0,s=new AbortController;return Ha([this._localAudioPipline.source.node]).then(d=>d.pipeTo(new WritableStream({write(h){!h[0][0]||(r.set(h[0][0],o),o+=h[0][0].length,o>=1920&&(o=0,e(r),r=new Float32Array(1920)))}}),s).catch(h=>this.log.warn(`stop getPCM reason:${h}`))),s}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!L(this._localAudioTrack)}changeInput(e){if(e instanceof Uo)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof ar)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof Vo)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,r;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(r=this._localScreenAudioTrack)==null?void 0:r.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof Uo?delete this._localScreenAudioTrack:e instanceof ar?delete this._localAudioTrack:e instanceof Vo}addDenoiser(e){var r;this.denoiser=e,(r=this._localAudioTrack)==null||r.addDenoiser(e)}removeDenoiser(e){var r;delete this.denoiser,(r=this._localAudioTrack)==null||r.removeDenoiser(e)}destroy(){this.close()}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};function Rg(i=30,t=2){return Ce((e,r)=>function(...o){return new Promise((s,a)=>{let d=setTimeout(()=>{let h=new de({code:Y.API_CALL_TIMEOUT,message:`checkPendingPromise ${r}() timeout ${i}s`});V.warn(h),t===2?a(h):t===1&&s()},i*1e3);e.apply(this,o).then(s,a).finally(()=>{clearTimeout(d)})})})}var Sm=class extends ko{constructor(e,r,o){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:o,room:e});this.room=e;this.user=r;l(this,"tinyId");l(this,"isRemote",!0);l(this,"jitterBufferDelay",0);l(this,"_decodeCheckTimeoutId",-1);this.tinyId=r.tinyId}setMute(e){this.isAvailable&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isAvailable&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Sm.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,r){let o=this.kind===D.AUDIO;X[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),e||(X.addEnum({key:o?504701:514703,value:Ta()}),Le.uploadEvent({log:`stat-decode-failed-${this.kind}-${Ea()||vo()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===D.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:r}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isAvailable||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isAvailable} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.isAvailable)}onTrackMuted(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},fr=Sm;l(fr,"STATE_SUBSCRIBE","subscribe"),q([Rg(5,1)],fr.prototype,"waitHasMediaTrack",1),q([be(Z.INIT,fr.STATE_SUBSCRIBE,{success(){var t,e;this.log.info("subscribed"),B.emit(O.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),!((((e=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:e.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&(this._decodeCheckTimeoutId=setTimeout(()=>{var o,s;if(!((((s=(o=this.room)==null?void 0:o.networkQuality)==null?void 0:s.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let a=this.kind===D.AUDIO,d=this.player.isPlaying||(a?this.getAudioLevel()>0:this.stat.framesDecoded>0);this.reportDecodeResult(d)}},5e3),this.player.once(at.ERROR,r=>{r.code===MediaError.MEDIA_ERR_DECODE&&(clearTimeout(this._decodeCheckTimeoutId),this.reportDecodeResult(!1,3))}))},ignoreError:!0}),eu(521716,!1)],fr.prototype,"subscribe",1),q([be(fr.STATE_SUBSCRIBE,Z.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),B.emit(O.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],fr.prototype,"unsubscribe",1);var Vo=class extends fr{constructor(e,r){super(e,r,1);l(this,"volume",0);l(this,"mediaType",1);l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}decodeFrame(e){if(!this.manager)return e;let r=e;for(let o of this.manager.decodePipeline)if(!!o&&(r=o({frame:r,track:this}),!r))return;return r}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isAvailable(){return this.user.muteState.audioAvailable}};var cS=[-1,-1,1,-1,-1,1,1,1],dS=[0,0,1,0,0,1,1,1];var Vt=class extends Z{constructor(e,r){super();this.context=e;l(this,"name");l(this,"input");l(this,"output");l(this,"texture");l(this,"ctx2d",null);l(this,"fbo");l(this,"width",0);l(this,"height",0);l(this,"x",0);l(this,"y",0);l(this,"program");l(this,"vertexShader");l(this,"fragmentShader");l(this,"totalFrames",0);l(this,"dropFrames",0);l(this,"matchInputSize",!0);l(this,"texCoordBuffer");l(this,"positionBuffer");l(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});l(this,"cost",0);l(this,"_canvas",null);l(this,"_image");l(this,"log");if(this.context.on("disconnect",this.close,this),this.name=r.name,this.log=r.logger,this.matchInputSize=r.matchInputSize!==!1,this.width=r.width||e.width,this.height=r.height||e.height,this._image=r.image,e instanceof Ct){e.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&ir!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let o=e.ctx;this.texCoordBuffer=this.createBuffer(dS),this.positionBuffer=this.createBuffer(cS),r.createTexture!==!1&&(this.texture=o.createTexture(),this.useTexture(),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),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.pixelStorei(o.PACK_ALIGNMENT,1),o.pixelStorei(o.UNPACK_ALIGNMENT,1)),r.useFbo&&(this.fbo=o.createFramebuffer(),this.useBufferFrame(),this.useTexture(),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,this.width,this.height,0,o.RGBA,o.UNSIGNED_BYTE,null),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.texture,0)),r.useDefaultProgram?this.program=e.defaultProgam:(r.vertexShaderSource||r.fragmentShaderSource)&&(this.vertexShader=r.vertexShaderSource?e.createShader(o.VERTEX_SHADER,r.vertexShaderSource):e.defaultVShader,this.fragmentShader=r.fragmentShaderSource?e.createShader(o.FRAGMENT_SHADER,r.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(o){this.context.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${o.message||o}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let r=this.context.ctx,o=r.createFramebuffer();return r.bindFramebuffer(r.FRAMEBUFFER,o),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0),o}connect(e,...r){return e.addInput(this,...r),this.output=e,e}addInput(e,...r){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let r=Date.now();if(this.context instanceof st&&this.render(e)||this.context instanceof Ct&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-r,!0}render2d(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var r;(r=this.output)==null||r.update(e)}disconnect(...e){var r;(r=this.output)==null||r.removeInput(this,...e),delete this.output}removeInput(e,...r){delete this.input}close(){var e,r;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(r=this.input)==null||r.disconnect(),this.context instanceof st){let o=this.context.ctx;o.deleteBuffer(this.texCoordBuffer),o.deleteBuffer(this.positionBuffer),this.fbo&&o.deleteFramebuffer(this.fbo),this.texture&&o.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&o.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&o.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&o.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let r=this.context.ctx;e.forEach((o,s)=>{o&&(r.activeTexture(r.TEXTURE0+s),r.bindTexture(r.TEXTURE_2D,o))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let r=this.context.ctx,o=r.createBuffer();return r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW),o}setTexBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.texCoordBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}setPosBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.positionBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}changeBufferData(e,r){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,e),o.bufferData(o.ARRAY_BUFFER,new Float32Array(r),o.STATIC_DRAW)}setAttributes(...e){let r=this.context.ctx;e.forEach((o,s)=>{r.enableVertexAttribArray(s),r.bindBuffer(r.ARRAY_BUFFER,o),r.vertexAttribPointer(s,2,r.FLOAT,!1,0,0)})}getVertexPoint(e,r){return[e/this.width*2-1,r/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,r){if(!(this.width===e&&this.height===r)){if(this.width=e,this.height=r,this._canvas&&(this._canvas.width=e,this._canvas.height=r),this.texture&&this.fbo){this.useTexture();let o=this.context.ctx;o.texImage2D(o.TEXTURE_2D,0,o.RGBA,e,r,0,o.RGBA,o.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,r)}}draw(e,r){this.setAttributes(e||this.positionBuffer,r||this.texCoordBuffer);let o=this.context.ctx;o.drawArrays(o.TRIANGLE_STRIP,0,4)}draw2d(e,r,o,s,a){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,r,o):(this.ctx2d.drawImage(e,r,o,s,a),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var y;let{totalFrames:e,x:r,y:o,width:s,height:a,name:d,cost:h}=this,p=Date.now(),T=(e-this.lastInfo.totalFrames)/((p-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:a,timestamp:p,fps:T,name:d,cost:h},J({parent:(y=this.input)==null?void 0:y.getInfo()},this.lastInfo)}createTexture(e){let r=this.context.ctx,o=r.createTexture();return this.useTextures(o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),o}};q([be(Z.INIT,"connected",{sync:!0})],Vt.prototype,"connect",1),q([be("connected",Z.INIT,{ignoreError:!0,sync:!0})],Vt.prototype,"disconnect",1),q([be([],"closed",{sync:!0})],Vt.prototype,"close",1);var nh={};li(nh,{Events:()=>et,Inspect:()=>_r,LastSink:()=>Bo,Sink:()=>ae,Subscribe:()=>Fo,TimeoutError:()=>Wa,audit:()=>qS,bindCallback:()=>xS,bindNodeCallback:()=>MS,buffer:()=>IS,bufferCount:()=>TS,bufferTime:()=>ly,call:()=>Dg,catchError:()=>ja,combineLatest:()=>wg,concat:()=>hS,concatMap:()=>iy,concatMapTo:()=>oy,count:()=>kS,create:()=>ve,debounce:()=>zS,debounceTime:()=>JS,defer:()=>xg,delay:()=>py,deliver:()=>le,dispose:()=>iu,elementAt:()=>XS,empty:()=>Ho,every:()=>ey,exhaustMap:()=>ay,exhaustMapTo:()=>cy,filter:()=>Go,find:()=>QS,findIndex:()=>YS,first:()=>ZS,fromAnimationFrame:()=>NS,fromArray:()=>AS,fromEvent:()=>Je,fromEventPattern:()=>bS,fromFetch:()=>vS,fromIterable:()=>RS,fromPromise:()=>Pg,fromReadableStream:()=>DS,fromReader:()=>CS,groupBy:()=>dy,identity:()=>uS,ignoreElements:()=>BS,iif:()=>_S,inspect:()=>Ng,interval:()=>Cm,last:()=>KS,map:()=>fu,mapTo:()=>ry,max:()=>LS,merge:()=>pS,mergeMap:()=>sy,mergeMapTo:()=>ny,min:()=>US,never:()=>OS,nothing:()=>Ue,of:()=>yS,pairwise:()=>ty,pipe:()=>We,race:()=>mS,range:()=>wS,reduce:()=>Nm,retry:()=>fy,scan:()=>th,share:()=>Ri,shareReplay:()=>fS,skip:()=>$S,skipUntil:()=>HS,skipWhile:()=>cu,startWith:()=>$o,subject:()=>Jt,subscribe:()=>dt,sum:()=>VS,switchMap:()=>Qi,switchMapTo:()=>Ga,take:()=>xr,takeLast:()=>FS,takeUntil:()=>gt,takeWhile:()=>kg,tap:()=>oh,throttle:()=>GS,throwError:()=>PS,timeInterval:()=>uy,timeout:()=>sh,timer:()=>Dm,toPromise:()=>my,toReadableStream:()=>hy,withLatestFrom:()=>ES,zip:()=>gS});function Ue(...i){}var Dg=i=>i(),uS=i=>i;function iu(){this.dispose()}var Ng=()=>typeof __FASTRX_DEVTOOLS__!="undefined",lS=1,_r=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new Am(t,this,this.streamId++);return et.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Bo=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Ue,this.error=Ue,this.next=Ue,this.dispose=Ue,this.subscribe=Ue,this.doDefer()}subscribe(t){return t instanceof _r?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Dg),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},ae=class extends Bo{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},Fo=class extends Bo{constructor(t,e=Ue,r=Ue,o=Ue){if(super(),this._next=e,this._error=r,this._complete=o,this.then=Ue,t instanceof _r){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{et.defer(s,0)}),et.create(s),et.pipe(s),this.sourceId=s.id,this.subscribe(t),et.subscribe({id:s.id,end:!0}),e==Ue?this._next=a=>et.next(s,0,a):this.next=a=>{et.next(s,0,a),e(a)},o==Ue?this._complete=()=>et.complete(s,0):this.complete=()=>{this.dispose(),et.complete(s,0),o()},r==Ue?this._error=a=>et.complete(s,0,a):this.error=a=>{this.dispose(),et.complete(s,0,a),r()}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function We(i,...t){return t.reduce((e,r)=>r(e),i)}function ve(i,t,e){if(Ng()){let r=Object.defineProperties(Object.setPrototypeOf(i,_r.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});et.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof _r&&et.addSource(r,s)}return r}return i}function le(i,t){return function(...e){return r=>{if(r instanceof _r){let o=ve(s=>{let a=new i(s,...e);a.sourceId=o.id,a.subscribe(r)},t,arguments);return o.source=r,et.pipe(o),o}else return o=>r(new i(o,...e))}}}function Xi(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var Am=class extends ae{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{et.defer(this.source,this.id)})}next(t){et.next(this.source,this.id,t),this.sink.next(t)}complete(){et.complete(this.source,this.id),this.sink.complete()}error(t){et.complete(this.source,this.id,t),this.sink.error(t)}},et={addSource(i,t){Xi("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){Xi("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){Xi("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){Xi("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){Xi("defer",{id:i.id,streamId:t})},pipe(i){Xi("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){Xi("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=lS++),Xi("create",{name:i.toString(),id:i.id})}},Wa=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var ou=class extends Bo{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function Ri(){return i=>{let t=new ou(i);if(i instanceof _r){let e=ve(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,et.pipe(e),e}return ve(t.add.bind(t),"share",arguments)}}function pS(...i){return ve(t=>{let e=new ae(t),r=i.length;e.complete=()=>{--r===0&&t.complete()},i.forEach(e.bindSubscribe)},"merge",arguments)}function mS(...i){return ve(t=>{let e=new Map;i.forEach(r=>{let o=new ae(t);e.set(r,o),o.complete=()=>{e.delete(r),e.size===0?t.complete():o.dispose()},o.next=s=>{e.delete(r),e.forEach(a=>a.dispose()),o.resetNext(),o.resetComplete(),o.next(s)}}),i.forEach(r=>e.get(r).subscribe(r))},"race",arguments)}function hS(...i){return ve(t=>{let e=0,r=i.length,o=new ae(t);o.complete=()=>{e<r&&!o.disposed?(o.doDefer(),o.subscribe(i[e++])):t.complete()},o.complete()},"concat",arguments)}function fS(i){return t=>{let e=new ou(t),r=[];return e.next=function(o){r.push(o),r.length>i&&r.shift(),this.sinks.forEach(s=>s.next(o))},ve(o=>{o.defer(()=>e.remove(o)),r.forEach(s=>o.next(s)),e.add(o)},"shareReplay",arguments)}}function _S(i,t,e){return ve(r=>i()?t(r):e(r),"iif",arguments)}function wg(...i){return ve(t=>{let e=i.length,r=e,o=e,s=new Array(e),a=()=>{--o===0&&t.complete()},d=(h,p)=>{let T=new ae(t);T.next=y=>{--r===0?(T.next=R=>{s[p]=R,t.next(s)},T.next(y)):s[p]=y},T.complete=a,T.subscribe(h)};i.forEach(d)},"combineLatest",arguments)}function gS(...i){return ve(t=>{let e=i.length,r=e,o=new Array(e),s=()=>{--r===0&&t.complete()},a=(d,h)=>{let p=new ae(t),T=[];o[h]=T,p.next=y=>{T.push(y),o.every(R=>R.length)&&t.next(o.map(R=>R.shift()))},p.complete=s,p.subscribe(d)};i.forEach(a)},"zip",arguments)}function $o(...i){return t=>ve((e,r=0,o=i.length)=>{for(;r<o&&!e.disposed;)e.next(i[r++]);e.disposed||e.subscribe(t)},"startWith",arguments)}var bm=class extends ae{constructor(t,...e){super(t);let r=new ae(this.sink);r.next=o=>this.buffer=o,r.complete=Ue,r.subscribe(wg(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},ES=le(bm,"withLatestFrom"),vm=class extends ae{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(t=>this.sink.next(t)),super.complete()}},TS=le(vm,"bufferCount"),Rm=class extends ae{constructor(t,e){super(t),this.buffer=[];let r=new ae(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=Ue,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},IS=le(Rm,"buffer");var SS=function(i,t,e,r){function o(s){return s instanceof e?s:new e(function(a){a(s)})}return new(e||(e=Promise))(function(s,a){function d(T){try{p(r.next(T))}catch(y){a(y)}}function h(T){try{p(r.throw(T))}catch(y){a(y)}}function p(T){T.done?s(T.value):o(T.value).then(d,h)}p((r=r.apply(i,t||[])).next())})};function Jt(i){let t=arguments,e=Ri()(ve(r=>{e.next=o=>r.next(o),e.complete=()=>r.complete(),e.error=o=>r.error(o),i&&r.subscribe(i)},"subject",t));return e.next=Ue,e.complete=Ue,e.error=Ue,e}function xg(i){return ve(t=>t.subscribe(i()),"defer",arguments)}var Mg=i=>t=>{setTimeout(()=>i(t))},Og=i=>Mg(t=>{for(let e=0;!t.disposed&&e<i.length;e++)t.next(i[e]);t.complete()});function yS(...i){return ve(Og(i),"of",arguments)}function AS(i){return ve(Og(i),"fromArray",arguments)}function Cm(i){return ve(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function Dm(i,t){return ve(e=>{let r=0,o=setTimeout(()=>{if(e.removeDefer(s),e.next(r++),t){let a=setInterval(()=>e.next(r++),t);e.defer(()=>{clearInterval(a)})}else e.complete()},i),s=()=>{clearTimeout(o)};e.defer(s)},"timer",arguments)}function su(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function bS(i,t){return ve(su(i,t),"fromEventPattern",arguments)}function Je(i,t){if("on"in i&&"off"in i)return ve(su(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i&&"removeListener"in i)return ve(su(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return ve(su(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function Pg(i){return ve(t=>{i.then(t.next.bind(t),t.error.bind(t))},"fromPromise",arguments)}function vS(i,t){return ve(xg(()=>Pg(fetch(i,t))),"fromFetch",arguments)}function RS(i){return ve(Mg(t=>{try{for(let e of i){if(t.disposed)return;t.next(e)}t.complete()}catch(e){t.error(e)}}),"fromIterable",arguments)}function CS(i){let t=e=>SS(this,void 0,void 0,function*(){if(e.disposed)return;let{done:r,value:o}=yield i.read();if(r){e.complete();return}else e.next(o),t(e)});return ve(e=>{t(e)},"fromReader",arguments)}function DS(i){return ve(t=>{let e=new AbortController,r=e.signal;t.defer(()=>e.abort("cancelled")),i.pipeTo(new WritableStream({write(o){t.next(o)},close(){t.complete()},abort(o){t.error(o)}}),{signal:r}).then(()=>t.complete(),o=>t.error(o))},"fromReadableStream",arguments)}function NS(){return ve(i=>{let t=requestAnimationFrame(function e(r){i.disposed||(i.next(r),t=requestAnimationFrame(e))});i.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function wS(i,t){return ve((e,r=i,o=t+i)=>{for(;r<o&&!e.disposed;)e.next(r++);return e.complete(),"range"},"range",arguments)}function xS(i,t,...e){return ve(r=>{let o=e.concat(s=>(r.next(s),r.complete()));i.apply(t,o)},"bindCallback",arguments)}function MS(i,t,...e){return ve(r=>{let o=e.concat((s,a)=>s?r.error(s):(r.next(a),r.complete()));i.apply(t,o)},"bindNodeCallback",arguments)}function OS(){return ve(()=>{},"never",arguments)}function PS(i){return ve(t=>t.error(i),"throwError",arguments)}function Ho(){return ve(i=>i.complete(),"empty",arguments)}var Wo=class extends ae{constructor(t,e,r){super(t),this.f=e;let o=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=s=>{this.acc=s,this.complete=o,this.resetNext()}:(this.acc=r,this.complete=o)}next(t){this.acc=this.f(this.acc,t)}},Nm=le(Wo,"reduce"),kS=i=>le(Wo,"count")((t,e)=>i(e)?t+1:t,0),LS=()=>le(Wo,"max")(Math.max),US=()=>le(Wo,"min")(Math.min),VS=()=>le(Wo,"sum")((i,t)=>i+t,0);var wm=class extends ae{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},Go=le(wm,"filter"),xm=class extends ae{next(t){}},BS=le(xm,"ignoreElements"),Mm=class extends ae{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},xr=le(Mm,"take"),Om=class extends ae{constructor(t,e){super(t);let r=new ae(t);r.next=()=>t.complete(),r.complete=iu,r.subscribe(e)}},gt=le(Om,"takeUntil"),Pm=class extends ae{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},kg=le(Pm,"takeWhile"),FS=i=>Nm((t,e)=>(t.push(e),t.length>i&&t.shift(),t),[]),km=class extends ae{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},$S=le(km,"skip"),Lm=class extends ae{constructor(t,e){super(t),t.next=Ue;let r=new ae(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=iu,r.subscribe(e)}},HS=le(Lm,"skipUntil"),Um=class extends ae{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},cu=le(Um,"skipWhile"),WS={leading:!0,trailing:!1},Vm=class extends ae{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},nu=class extends ae{constructor(t,e,r=WS){super(t),this.durationSelector=e,this.config=r,this._throttle=new Vm(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=Ue,this._throttle.complete(),super.complete()}},GS=le(nu,"throttle"),jS={leading:!1,trailing:!0},qS=i=>le(nu,"audit")(i,jS),Bm=class extends ae{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},au=class extends ae{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Bm(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},zS=le(au,"debounce"),JS=i=>le(au,"debounceTime")(t=>Dm(i)),Fm=class extends ae{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},XS=le(Fm,"elementAt"),QS=i=>t=>xr(1)(cu(e=>!i(e))(t)),$m=class extends ae{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},YS=le($m,"findIndex"),Hm=class extends ae{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},ZS=le(Hm,"first"),Wm=class extends ae{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},KS=le(Wm,"last"),Gm=class extends ae{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},ey=le(Gm,"every");var jm=class extends ae{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=o=>{this.acc=o,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},th=le(jm,"scan"),qm=class extends ae{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},ty=le(qm,"pairwise"),du=class extends ae{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},fu=le(du,"map"),ry=i=>le(du,"mapTo")(t=>i),Xs=class extends ae{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},Qs=class extends ae{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},uu=class extends Xs{},lu=class extends Qs{next(t){this.subInner(t,uu),this.next=e=>{this.currentSink.dispose(),this.subInner(e,uu)}}},Qi=le(lu,"switchMap");function _u(i){return(t,e)=>i(()=>t,e)}var Ga=_u(le(lu,"switchMapTo")),zm=class extends Xs{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},pu=class extends Qs{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),zm),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},iy=le(pu,"concatMap"),oy=_u(le(pu,"concatMapTo")),Jm=class extends Xs{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},mu=class extends Qs{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Jm),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},sy=le(mu,"mergeMap"),ny=_u(le(mu,"mergeMapTo")),Xm=class extends Xs{dispose(){this.context.resetNext(),super.dispose()}},hu=class extends Qs{next(t){this.next=Ue,this.subInner(t,Xm)}},ay=le(hu,"exhaustMap"),cy=_u(le(hu,"exhaustMapTo")),Qm=class extends ae{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=Jt(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},dy=le(Qm,"groupBy"),Ym=class extends ae{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},uy=le(Ym,"timeInterval"),Zm=class extends ae{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},ly=le(Zm,"bufferTime"),Km=class extends ae{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:o}=e;super.next(o),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},py=le(Km,"delay"),eh=class extends ae{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},ja=le(eh,"catchError");var my=()=>i=>new Promise((t,e)=>{let r;new Fo(i,o=>r=o,e,()=>t(r))}),hy=()=>i=>{let t;return new ReadableStream({start(e){t=new Fo(i,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){t.dispose()}})},dt=(i=Ue,t=Ue,e=Ue)=>r=>new Fo(r,i,t,e),rh=class extends ae{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},oh=le(rh,"tap"),ih=class extends ae{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new Wa(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},sh=le(ih,"timeout"),fy=(i=1/0)=>t=>{if(t instanceof _r){let e=ve(r=>{let o=i,s=new ae(r);s.error=a=>{o-- >0?s.subscribe(t):r.error(a)},s.sourceId=e.id,s.subscribe(t)},"retry",[i]);return e.source=t,et.pipe(e),e}else return e=>{let r=i,o=new ae(e);o.error=s=>{r-- >0?t(o):e.error(s)},t(o)}};var Lg=We(Cm(250),fu(()=>performance.now()),Ri()),Ug=i=>t=>{let e=0,r=performance.now();We(Lg,fu(o=>(o-r)/i>>0),Go(o=>o!=e?(e=o,!0):!1))(t)},gu=i=>t=>{let e=performance.now();We(Lg,cu(r=>r-e<i),xr(1))(t)};var gy=[0,1,1,1,0,0,1,0],jo=class extends Vt{constructor(e,r){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},r));l(this,"_intervalId",0);l(this,"_sequence",0);l(this,"checkGLError",!1);l(this,"checkVisibilityChange");e instanceof Ct?this.ctx2d=e.ctx||null:e.available&&(r==null?void 0:r.mirrorUpAndDown)&&this.setTexBuffer(gy)}start(e){this.log.info(`${this.name} start render ${e} fps`),Et.clearTask(this._intervalId),this._intervalId=Et.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Et.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof st){let o=this.context.ctx.getError();o&&this.context.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${o}`}))}},{fps:this.context.frameRate})}render(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...r){super.addInput(e,...r),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(Et.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let r=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",r))};document.addEventListener("visibilitychange",r)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),Et.clearTask(this._intervalId)}resize(e,r){super.resize(e,r),this.context.setSize(e,r)}close(){super.close(),Et.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Ys=class extends jo{constructor(e,r){super(e,r);l(this,"_videoTrack");l(this,"_muteOb");l(this,"_closedOb",Je(this,"closed"));l(this,"_subscription");l(this,"_canvasContainer");Number(Fi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=Je(this._videoTrack,"mute"),We(Je(this._videoTrack,"ended"),gt(this._closedOb),dt(()=>{this.context.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=We(this._muteOb,gt(this._closedOb),Ga(gu(5e3)),dt(()=>{var e;!((e=this._videoTrack)!=null&&e.muted)||this.context.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,r;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(r=this._canvasContainer)==null||r.remove()}},Eu=class extends Ys{render(t){var e;return!!((e=this.input)!=null&&e.requestFrame(t))}};var Tu=class extends Ys{constructor(e,r,o){super(e,{name:"smallDestination",logger:o});this.resolution=r}resize(e,r){let o,s=e*r,a=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${r} small res: ${this.resolution.width}*${this.resolution.height} `),s>a?o=s/a:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${r} small: ${this.resolution.width} * ${this.resolution.height}`),o=s/(160*120)),super.resize(e/Math.sqrt(o),r/Math.sqrt(o))}};var qa=class extends Vt{constructor(e,r){super(e,J({name:"imageSource"},r));l(this,"_lastImage");l(this,"_totalFrames",0);l(this,"_autoResize",!1);l(this,"_canvasRendered");l(this,"_videoCallbackId",0);this._autoResize=(r==null?void 0:r.autoResize)!==!1,ir===16&&(this._canvasRendered=Jt(),We(this._canvasRendered,$o(this._image),Qi(o=>o instanceof HTMLCanvasElement?Je(o,"rendered"):Ho()),gt(Je(this,"closed")),dt(()=>{this.update()})))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Mo()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((r,o)=>{document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(e,r){var d;let{width:o,height:s}=this,{image:a}=this;if(a instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(a),{videoWidth:o,videoHeight:s}=a,!o||!s)return!1;a.width=o,a.height=s}else if(a instanceof HTMLImageElement||a instanceof ImageData||a instanceof ImageBitmap){if({width:o,height:s}=a,a!==this._lastImage)this._lastImage=a;else if(o===this.width&&s===this.height)return!1}else a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas?({width:o,height:s}=a,this._lastImage=a):typeof VideoFrame!="undefined"&&a instanceof VideoFrame&&({displayWidth:o,displayHeight:s}=a,(d=this._lastImage)==null||d.close(),this._lastImage=a);if(!this._autoResize)return!0;if(this.width===o&&this.height===s&&this.totalFrames){if(r){this.useTexture();let h=this.context.ctx;h.texSubImage2D(h.TEXTURE_2D,0,0,0,h.RGBA,h.UNSIGNED_BYTE,a)}}else{if(r){this.useTexture();let h=this.context.ctx;h.texImage2D(h.TEXTURE_2D,0,h.RGBA,h.RGBA,h.UNSIGNED_BYTE,a)}this.resize(o,s)}return!0}get image(){return this._image}set image(e){var r;(r=this._canvasRendered)==null||r.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},za=class extends qa{constructor(e,r,o){super(e,o);this._player=r;this.name="videoPlayerSource",We(Je(this._player,at.PLAYER_STATE_CHANGED),gt(Je(this,"closed")),Go(({state:s})=>s==="PLAYING"),dt(()=>{this.tryVideoFrameCallback(this._player.element)}))}get image(){return this._player.element}},Ci=class extends za{constructor(t,e,r){super(t,new or({id:r.name,track:e,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}};var Ty=`
|
|
29
|
+
`,r.onclick=this.onQuestionClick.bind(this);let o=document.createElement("div");o.className=dm,o.innerText=`${vr()?"\u8BE6\u60C5 >":"Detail >"}`,o.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,a=s.querySelector(`.${Wd}`);return a.appendChild(o),a.appendChild(r),a.appendChild(e),s}addDiaLog(){pm()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Hs}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",V.info("show autoplay dialog"),Le.uploadEvent({log:HI}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){V.warn("confirm clicked, try resume stream"),B.emit(O.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${K_}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Le.uploadEvent({log:WI}),this._isCollapseClicked=!0}onQuestionClick(){window.open(ig,"_blank"),this._isQuestionClicked||Le.uploadEvent({log:GI}),this._isQuestionClicked=!0}},og=um;var or=class extends Jr{constructor(e){super(e,D.VIDEO);l(this,"stat",{});l(this,"_calculateTimeout",-1);l(this,"viewMirror",!1);l(this,"objectFit");l(this,"container");l(this,"canvas");l(this,"canvasTrack");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,L(e.viewMirror)||(this.viewMirror=e.viewMirror),L(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var r;let e=document.createElement(D.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(r=this.container)==null||r.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var r;this.container=e,(this.track||this.canvasTrack)&&this.elementToRender&&((r=this.container)==null||r.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(D.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(D.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var r;super.handleTrackEvent(e),e.type===D.MUTE&&((r=this.stat)==null?void 0:r.fps)&&(this.stat.fps=0)}handleElementEvent(e){var o;if(this.mode===2)return;super.handleElementEvent(e);let r=e.type;if(r===D.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(o=this.container)==null?void 0:o.id}`),this._pausedRetryCount>0&&!pm()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let s=this.element.style.transform;r===D.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=s.replace("scaleX(-1)",""):r===D.LEAVE_PICTURE_IN_PICTURE&&!s.includes("scaleX")&&(this.element.style.transform=`${s} scaleX(-1)`)}}setCanvas(e,r=1){var o,s,a,d;this.canvas!==e&&((o=this.canvas)==null||o.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?r:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(a=this.container)==null||a.appendChild(e)):this.element&&((d=this.container)==null||d.appendChild(this.element)))}setAttr(e){let r=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);r.style=Object.assign({width:"100%",height:"100%"},r.style),super.setAttr(r)}get mirror(){return this.viewMirror}setRect(e,r){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${r}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}stop(e=0){var r;super.stop(e),(r=this.canvas)==null||r.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(at.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Mo()&&this.element&&this._calculateTimeout<0){let e=0,r=null,o=(s,a)=>{this.stat.width=a.width,this.stat.height=a.height,r&&(this.stat.fps=Math.round((a.presentedFrames-r.presentedFrames)/(s-e)*1e3)),e=s,r=a,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var d;return(d=this.element)==null?void 0:d.requestVideoFrameCallback(o)},2e3))};this.element.requestVideoFrameCallback(o)}}catch(e){this._log.warn("init stat failed",e)}}};function Po(i,t){return v(this,null,function*(){if(!i.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield i.audioWorklet.addModule(t),V.info("worklet addModule success")}catch(e){throw V.info(`worklet addModule catch error. ${e.message}`),e}})}var Va;typeof AudioContext!="undefined"?Va=AudioContext:typeof webkitAudioContext!="undefined"?Va=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Va=mozAudioContext);var vi,sg=-1;ng();function ng(){try{if(vi)return;vi=new Va({sampleRate:48e3}),vi.onstatechange=()=>{V.info(`context state: ${vi.state}`),Ws()},clearTimeout(sg)}catch(i){V.error(`initAudioContext failed: ${i} typeof AudioContextClass: ${typeof Va}`),sg=setTimeout(ng,1e3)}}var Ws=()=>{vi.state==="suspended"?(vi.resume(),document.addEventListener("click",Ws)):vi.state==="interrupted"?vi.resume().catch(i=>{V.warn(`resume failed: ${i}`),document.addEventListener("visibilitychange",Ws)}):(document.removeEventListener("visibilitychange",Ws),document.removeEventListener("click",Ws))};document.addEventListener("click",Ws);var qt=i=>vi;var mr=class{constructor(){l(this,"node");l(this,"pre",new Set);l(this,"next",new Set);l(this,"context");l(this,"connectedNodes",new Set);l(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(t){this._channelCount=t,this.node&&(this.node.channelCount=t),this.next.forEach(e=>e.channelCount=t)}setContext(t){this.context=t,this.node&&t.addMixWeight()}removeContext(){var t;this.node&&((t=this.context)==null||t.reduceMixWeight()),delete this.context}setNode(t){var e;if(!this.node)try{(e=this.context)==null||e.addMixWeight(),this.node=t,this.node.channelCountMode="explicit",this.node.channelCount=this._channelCount,this.preNodeReconnect(),this.reconnect(),X.addSuccessEvent({key:502701})}catch(r){V.error(r),X.addFailedEvent({key:502701,error:r})}}deleteNode(){var t;if(!!this.node)try{this._disconnect(),delete this.node,(t=this.context)==null||t.reduceMixWeight(),this.preNodeReconnect(),X.addSuccessEvent({key:502702})}catch(e){V.error(e),X.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(e=>t._connect(e.node)||e.connectNext(t))}_connect(t){return!this.node||!t?!1:(this.node.connect(t),this.connectedNodes.add(t),!0)}_disconnect(){this.connectedNodes.forEach(t=>{var e;return(e=this.node)==null?void 0:e.disconnect(t)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...t){return t.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},jd=class extends mr{constructor(e=256){super();this.fftSize=e;l(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),r=1,o=0,s=0,a=`M${o},${s}`;for(let d=0;d<e.length;d++)s=e[d]/128*100/2,a+=`L${o},${s}`,o+=r;return a}},Ba=class{constructor(){l(this,"source",new mr);l(this,"gain",new mr);l(this,"destination",new mr)}get volume(){var t;return((t=this.gain.node)==null?void 0:t.gain.value)||1}setVolume(t){if(t===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=t}replaceSource(t){this.source.deleteNode(),this.source.setNode(mm(t))}get track(){var t;return(t=this.stream)==null?void 0:t.getAudioTracks()[0]}get stream(){var t;return(t=this.destination.node)==null?void 0:t.stream}},Gs=class extends Ba{constructor(e){super();this.context=e;l(this,"denoiser",new mr);this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},qd=class{constructor(){l(this,"audioContext",qt("audio-mixer"));l(this,"destination",this.audioContext.createMediaStreamDestination());l(this,"inputs",new Set);l(this,"mixWeight",0)}addMixWeight(t=1){this.mixWeight+=t,this.mixWeight-1===t+1>>1&&this.mixOnChange()}reduceMixWeight(t=1){this.addMixWeight(-t)}close(){this.inputs.forEach(t=>t.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},ag=new WeakMap;function mm(i){let t=ag.get(i);if(t)return t;let e=qt();if(i instanceof HTMLAudioElement)t=e.createMediaElementSource(i);else if(i instanceof MediaStreamTrack)t=e.createMediaStreamSource(new MediaStream([i]));else return i;return ag.set(i,t),t}var Xr=class{constructor(t){l(this,"_volume",0);l(this,"_log");l(this,"_scriptProcessorNode",null);l(this,"_audioWorkletNode",null);l(this,"_interval",200);l(this,"ready",this.preload());let{log:e}=t;this._log=e,B.on(O.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Xr.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Xr.workletReady){let t='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,e){t=t[0],e=e[0];if(t||e){if(this.isStop)return!1;var s=e&&e[0]?e[0].length:0,i=this.cache.length,h=(s<i?(e[0].set(this.cache.slice(0,s)),this.cache=this.cache.slice(s)):this.unmute&&e[0].set(t[0]),(s<i?e:t)[0]);if(h){let e=0;for(let t=0;t<h.length;++t)e=Math.max(Math.abs(h[t]),e);this.volume=e,this.tick-=h.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,cacheLen:i,outputLen:s}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Xr.workletReady=Po(Xr.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return Xr.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error(`volumeMeter preload error: ${t}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Xr.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=e=>{Xr.lastMessageTime=Date.now(),this._volume=e.data.volume||0,!t&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(t){this._log.error(`volumeMeter init audio worklet error: ${t}`),Le.logFailedEvent({userId:this._log.userId,eventType:mi.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=qt("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{Xr.lastMessageTime=Date.now();let e=t.inputBuffer.getChannelData(0),r=0;for(let o=0;o<e.length;++o)r+=e[o]*e[o];this._volume=Math.sqrt(r/e.length)||0}}catch(t){this._log.error(`volumeMeter init script processor error: ${t}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,B.off(O.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(t){var r;let{interval:e}=t;this._interval=e,(r=this._audioWorkletNode)==null||r.port.postMessage({name:"setIntervalTime",intervalTime:e})}},js=Xr;l(js,"lastMessageTime",0),l(js,"audioContext",qt("volume-meter")),l(js,"workletReady");var zd=class extends mr{constructor(e){super();l(this,"_volumeMeter");this._volumeMeter=new js(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return v(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let r=e.allocationSize({planeIndex:0}),o=new Float32Array(r>>2);e.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),e.close()}}};var lg=Pi(Hi(),1);var dg=i=>t=>t.deviceId===i;var Fa=class{constructor(t,e="Input"){l(this,"kind");l(this,"type");l(this,"devices",[]);this.kind=t,this.type=e}update(t,e){let r=t.filter(o=>o.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&qs(this.devices[0])){this.devices=r;return}e&&(r.forEach(o=>{if(o.deviceId&&!this.devices.find(dg(o.deviceId))){let s=`${this.kind}${this.type}Added`;V.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}}),this.devices.forEach(o=>{if(o.deviceId&&!r.find(dg(o.deviceId))){let s=`${this.kind}${this.type}Removed`;V.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},hm=class extends lg.EventEmitter{constructor(){super();l(this,"audioInputs",new Fa(D.AUDIO));l(this,"videoInputs",new Fa(D.VIDEO));l(this,"audioOutputs",new Fa(D.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Et.run(To,()=>{this.update()},{delay:1e4}))}init(){Jd().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return v(this,arguments,function*(e=0){let r=yield Jd(e);return this.audioInputs.update(r,this),this.videoInputs.update(r,this),this.audioOutputs.update(r,this),this})}},_t=zn||fs?null:new hm;function qs(i){return i.deviceId===i.groupId&&i.groupId===""}function Jd(){return v(this,arguments,function*(i=0){if(Ai()||!Fd())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(i!==0){let e={audio:!1,video:!1};if(t.forEach(r=>{qs(r)&&(r.kind===D.AUDIO_INPUT?e.audio=!0:r.kind===D.VIDEO_INPUT&&(e.video=!0))}),i===2&&(e.audio=!1),i===1&&(e.video=!1),e.audio||e.video){let r;try{r=yield navigator.mediaDevices.getUserMedia(e)}catch(o){V.debug("capture before getDevices failed: ",o)}t=yield navigator.mediaDevices.enumerateDevices(),r==null||r.getTracks().forEach(o=>o.stop())}}return t.map((e,r)=>{let o={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${r}`};return e.deviceId.length>0&&fm.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(o.getCapabilities=()=>e.getCapabilities()),o})})}function zt(i=!1){return _t.update(i?1:0).then(t=>t.audioInputs.devices)}function sr(i=!1){return _t.update(i?2:0).then(t=>t.videoInputs.devices)}var ug=!1;function pg(){return v(this,null,function*(){try{ug||(ug=!0,V.info(`speakers:${(yield qi()).map(i=>` ${i.deviceId.slice(0,8)}: ${i.label}`)}`))}catch(i){}})}function qi(i=!1){return v(this,null,function*(){return _t.update(i?1:0).then(t=>t.audioOutputs.devices)})}var fm=new Set;function mg(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${D.VIDEO_INPUT}`;return!!fm.has(r)}function hg(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("\u9EA6\u514B\u98CE"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${D.AUDIO_INPUT}`;return!!fm.has(r)}function _m(i,t){return v(this,null,function*(){let r=(yield zt()).find(o=>o.deviceId===Eo);return!t&&(r==null?void 0:r.groupId)===i||(r==null?void 0:r.groupId)===i&&r.label===t})}function fg(s){return v(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:o}){return i!==t?!1:o===D.AUDIO&&i===Eo?yield _m(e,r):!0})}var Xd,gm=class extends Ba{constructor(e){super();this.log=e;l(this,"volumeMeter");l(this,"volumeDestination");l(this,"analyser",new jd);this.volumeMeter=new zd({log:this.log}),this.volumeDestination=new mr,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},zs=class extends Jr{constructor(e){super(e,D.AUDIO);l(this,"_outputDeviceId");l(this,"_volume",1);l(this,"_destination",qt("player").createMediaStreamDestination());l(this,"pipeline");l(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new gm(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(($i==="15.2"||$i==="15.3"||$i==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let o=Xd||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.element=o,Fe(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),o===Xd&&(Xd=void 0),this.bindElementEvents()}play(e){return v(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(qt("player").createAnalyser()),pg(),Lt(zs.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return v(this,null,function*(){var r,o;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(o=(r=this.element).setSinkId)==null?void 0:o.call(r,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},Qd=class extends zs{constructor(t){super(t),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(t){var e;this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(at.MEDIA_TRACK_CHANGED,t),t?(this.bindTrackEvents(),this.pipeline.source.channelCount=((e=t.getSettings())==null?void 0:e.channelCount)||1,this.pipeline.replaceSource(t),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([t]))):this.pipeline.source.deleteNode())}setSourceNode(t){!t||this.pipeline.source.node===t||(this.pipeline.replaceSource(t),t instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(t){this._volume=t,this.element&&(this.element.volume=t)}},Yd=class extends zs{constructor(e){super(e);l(this,"_sourceElement");l(this,"_output",new mr);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(qt("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var r,o,s;((o=(r=this.element)==null?void 0:r.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(at.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),ct(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();let r=this._sourceElement||this.element;r&&Bi&&(Xd=r),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var ko=class extends Z{constructor({userId:e,sdkAppId:r,mediaType:o,room:s,PlayerClass:a=o===1?Yd:or}){var d;super();l(this,"id",ya());l(this,"userId","");l(this,"isRemote");l(this,"mediaType");l(this,"room");l(this,"user");l(this,"_log");l(this,"_inputTrack");l(this,"_outputTrack");l(this,"isPlayCalled");l(this,"container",null);l(this,"player");l(this,"subVideoPlayerMap");l(this,"muted",!1);l(this,"abortCtrl");l(this,"objectFit","cover");l(this,"mirror");l(this,"isScreen",!1);l(this,"manager");l(this,"trackSettings");this.userId=e||"",this.mediaType=o,this._log=V.createLogger({id:`${this.kind[0]}t`,userId:(d=s||this.room)==null?void 0:d.userId,remoteUserId:this instanceof nr?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof nr}),this.player=new a({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(at.PLAYER_STATE_CHANGED,h=>{B.emit(O.PLAYER_STATE_CHANGED,J({track:this},h)),this.emit("player-state-changed",h)}),this.kind===D.VIDEO&&(this.player.on(at.LOADED_DATA,()=>{B.emit(O.VIDEO_LOADED_DATA,{track:this})}),this.player.on(at.MEDIA_TRACK_CHANGED,h=>{var p;(p=this.subVideoPlayerMap)==null||p.forEach(T=>T.setTrack(h))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(at.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||V}get kind(){return this.mediaType===1?D.AUDIO:D.VIDEO}get strMediaType(){return this.mediaType===4?D.VIDEO:this.mediaType===2?D.SCREEN:D.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,r){return v(this,null,function*(){let o=rt(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(r)}`),r&&!L(r.muted)&&this.setPlayerMute(r.muted),r&&!L(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof or&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(this.container=o,this.player.setContainer(o)),rt(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if(r&&!L(r.muted)?this.setPlayerMute(r.muted):(!this.isRemote||this.kind===D.VIDEO)&&this.setPlayerMute(!0),r&&!L(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof or&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof or&&this.player.setContainer(o)),B.emit(O.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(r)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(r),rt(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),r))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,r){if(this.isScreen||this.kind!==D.VIDEO||L(e)||e===this.mirror)return;this.mirror=e;let o=this.player;r&&(o=r);let s=this.manager;if(nt(this.mirror)){o.setViewMirror(this.mirror),s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),o.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),o.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),o.setViewMirror(!1)}}playSubContainer(e,r){return v(this,null,function*(){if(!this._outputTrack||this.kind===D.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,a)=>{var d;e.find(h=>a===h)||(s.stop(),(d=this.subVideoPlayerMap)==null||d.delete(a))});for(let[s,a]of e.entries()){let d=this.subVideoPlayerMap.get(a);d?r&&(L(r.objectFit)||d.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(a,new or({id:this.userId||this.id,track:this.playerMediaTrack,container:a,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let o=[...this.subVideoPlayerMap.values()];for(let s of o)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(hp(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(r=>{r.stop()}),this.container=null)}resume(){return v(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),B.emit(e?O.TRACK_MUTED:O.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){Rt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ct(e)}setInputMediaStreamTrack(e){var o;let r=this._inputTrack;if(e!==r)return this._inputTrack=e,this.trackSettings=(o=e.getSettings)==null?void 0:o.call(e),e.enabled=!this.muted,r&&this.uninstallTrackEvent(r),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,r||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var o;let r=this._outputTrack;e!==r&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(o=e.getSettings)==null?void 0:o.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(r=>this.handleAutoPlayFailed(r)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(hp(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new og;else{let r=()=>{this.resume().then(()=>{document.removeEventListener("click",r,!0)})};document.addEventListener("click",r,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof or?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};q([be([],Z.INIT,{sync:!0})],ko.prototype,"close",1);var qI=Object.prototype.hasOwnProperty,{toString:aC}=Object.prototype;function zI(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if($t(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(qI.call(i,t))return!1;return!0}}return!1}var $a=zI;var JI=function(i){return v(this,null,function*(){let t=QI(i);V.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],r=[],o=["label","deviceId","groupId"];t.audio&&(e=yield zt(),V.info(`microphones: ${pr(e.map(s=>me(J({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:o})}`)),t.video&&(r=yield sr(),V.info(`cameras: ${pr(r,{keysToInclude:o})}`));try{let s=yield navigator.mediaDevices.getUserMedia(t);return tm&&s.getTracks().forEach(a=>{V.info(`${a.kind} capabilities: ${pr(a.getCapabilities(),{keysToInclude:rd})}`)}),s}catch(s){let{message:a}=s;throw s.name==="NotFoundError"&&(i.video&&r&&r.length===0&&(a=ot({key:it.CAMERA_NOT_FOUND})),i.audio&&e&&e.length===0&&(a=ot({key:it.MICROPHONE_NOT_FOUND}))),new de({code:Y.INITIALIZE_FAILED,name:s.name,message:a,constraint:s.constraint})}})},XI=Vi({retryFunction:JI,settings:{retries:3,timeout:500},onError:({error:i,retry:t,reject:e,retryFuncArgs:r,retriedCount:o})=>{let s=o+1;i.name==="NotReadableError"||i.name==="OverconstrainedError"?(s===1?(r[0].video&&(r[0].maxResolution=!1,(!Wt||r[0].width*r[0].height<=1920*1080)&&r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),r[0].retryWhenExactFailed&&r[0].useExactDeviceId&&(r[0].useExactDeviceId=!1)):s===2?r[0].useDeviceIdOnly=!0:s===3&&!r[0].useExactDeviceId&&(r[0].useTrueAsConstraint=!0),t()):e(i),r[0].microphoneId&&_g(r[0].microphoneId,!1),r[0].cameraId&&_g(r[0].cameraId,!0)},onRetrying:i=>{V.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)},onRetryFailed:i=>{Le.logFailedEvent({eventType:mi.GET_USER_MEDIA_RETRY,error:i})},onRetrySuccess:i=>{Le.logSuccessEvent({eventType:mi.GET_USER_MEDIA_RETRY}),Le.uploadEvent({log:`stat-${mi.GET_USER_MEDIA_RETRY}-success-${i}`})}});function _g(i,t){return v(this,null,function*(){let r=(t?yield sr():yield zt()).find(o=>o.deviceId===i);r&&Ve(r.getCapabilities)&&V.warn(pr(r.getCapabilities(),{keysToInclude:rd}))})}function QI(i){return{audio:YI(i),video:ZI(i)}}function YI(i){if(!i.audio)return!1;if(i.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:i.sampleRate};return!$a(i.microphoneId)&&(t.deviceId=i.useExactDeviceId?{exact:i.microphoneId}:i.microphoneId,i.useDeviceIdOnly)?t:(Fe(i.channelCount)&&(t.channelCount=i.channelCount),nt(i.echoCancellation)&&!i.echoCancellation&&(t.echoCancellation=!1),nt(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),nt(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),$a(t)?!0:t)}function ZI(i){if(!i.video)return!1;if(i.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=i,e={};return i.cameraId?e.deviceId=i.useExactDeviceId?{exact:i.cameraId}:i.cameraId:i.facingMode&&(e.facingMode=i.facingMode),i.useDeviceIdOnly&&!$a(e)?e:(i.width&&(e.width={ideal:i.width},t&&!Cr&&(e.width.max=i.width)),i.height&&(e.height={ideal:i.height},t&&!Cr&&(e.height.max=i.height)),Cr&&Nr&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),$a(e)?!0:e)}var gg=XI;function zi(i){return Ce((t,e)=>function(...r){return v(this,null,function*(){let o=yield t.apply(this,r);return yield i.call(this,...r),o})})}function Ce(i){return function(t,e,r){return r.value=i(r.value,e),r}}var Eg=(()=>{let i=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&V.info(`visibility change: ${document.visibilityState}`),!i&&(document.addEventListener("visibilitychange",()=>{V.info(`visibility change: ${document.visibilityState}`),t=document.visibilityState}),i=!0)}})();var KI=0,Zd=class{constructor(){this.log=V.createLogger({id:`fq${++KI}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(t,e=!1){var s,a;let r=J({},t),o=new Promise((d,h)=>{r.resolve=d,r.reject=h});return r.promise=o,e?this.length<=1?this.queue.push(r):(a=(s=this.lastQueueItem)==null?void 0:s.promise)==null||a.then(r.resolve,r.reject):this.queue.push(r),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),o}shift(){let t=this.queue.shift();return this.log.debug(`shift ${this.length}`),t}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:t,args:e,context:r,resolve:o,reject:s}=this.queue[0];this.isRunning=!0,t.apply(r,e).then(o,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Tg=new WeakMap,Ig=new WeakMap;function Sg(i=!1){return function(t,e,r){let o=r.value;return r.value=function(...s){let a=Tg.get(this)||new Zd;return Tg.set(this,a),a.push({fn:o,args:s,context:this},i)},r}}function Kd(i){return function(t,e,r){let o=r.value,s=a=>i(...a);return r.value=function(...a){let d=Ig.get(this)||new Map,h=d.get(s(a))||new Zd;return d.set(s(a),h),Ig.set(this,d),h.push({fn:o,args:a,context:this})},r}}function eu(i,t){return Ce((e,r)=>function(...o){let s=i;try{let a=e.apply(this,o),d=ge();return Li(a)?a.then(h=>(t?X.addSuccessEvent({key:s,cost:ge()-d}):X.addSuccessEvent({key:s}),h)).catch(h=>{throw X.addFailedEvent({key:s,error:h}),h}):(X.addSuccessEvent({key:s}),a)}catch(a){throw X.addFailedEvent({key:s,error:a}),a}})}var Em=class extends ko{constructor(e,r){super({mediaType:e,PlayerClass:r});l(this,"isRemote",!1);l(this,"deviceId");l(this,"groupId","");l(this,"label","");l(this,"_isRecapturing",!1);l(this,"_lastRecaptureTime",0);l(this,"_onMuteTimeoutId",-1);l(this,"_encodeCheckTimeoutId",-1);l(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,r){throw new Error("Method not implemented.")}installTrackEvent(e){Rt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ct(e)}setStateToCapture(){}capture(e){return v(this,null,function*(){var r;try{let o=ge();B.emit(O.LOCAL_TRACK_CAPTURE_START,{track:this});let s;e.customSource?(s=new MediaStream,s.addTrack(e.customSource)):((r=this.mediaTrack)==null||r.stop(),s=yield gg(e));let a=s.getTracks()[0];return yield this.setInputMediaStreamTrack(a),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),B.emit(O.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:ge()-o}),s}catch(o){throw B.emit(O.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:o}),this.log.error(`getUserMedia error observed ${o}`),o}})}setInputMediaStreamTrack(e){return this.state===Z.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(r=this.room)==null?void 0:r.replaceTrack(this)}publish(e,r){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),r}unpublish(){this.room&&this.room.localTracks.delete(this),B.emit(O.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return v(this,null,function*(){if(this.mediaTrack&&Fs){let{deviceId:e,groupId:r}=this.mediaTrack.getSettings(),{label:o}=this.mediaTrack;(yield fg({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=o,r&&(this.groupId=r),Jd().then(a=>{let d=a.find(h=>h.deviceId===e);d&&this.emit("2",d)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===D.AUDIO&&!hg(this.mediaTrack)||this.kind===D.VIDEO&&!mg(this.mediaTrack)||this._isRecapturing||e&&Nr&&Wt)}onTrackMuted(){if(super.onTrackMuted(),Eg(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Es){setTimeout(()=>this.onTrackMuted(),Es);return}this._onMuteTimeoutId=setTimeout(()=>v(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Ht||ft)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return v(this,null,function*(){if(Lt(Em.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Es){setTimeout(()=>this.onTrackEnded(),Es);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return v(this,null,function*(){var o;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(o=this._inputTrack)==null||o.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let r={useExactDeviceId:!0};if(e==="user"||e==="environment")r.facingMode=e;else{let s;(this.kind==="audio"?yield zt():yield sr()).find(d=>d.deviceId===e)&&(s=e),r.deviceId=s}return this.capture(r).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),B.emit(O.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(s=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${s.message}`),this.emit("5",s),B.emit(O.LOCAL_TRACK_RECAPTURE,{track:this,error:s})})})}getRecoverCaptureDeviceId(){return v(this,null,function*(){let e=this instanceof hr;if(e&&this.facingMode)return this.facingMode;let{deviceId:r}=this;if(r){let o=(Ha.get(r)||0)+1;if(Ha.set(r,o),o>=3){let s=e?(yield sr()).find(a=>!Ha.has(a.deviceId)):(yield zt()).find(a=>!Ha.has(a.deviceId));s&&(this.log.warn(`${r} capture fail ${o} times, change new ${s.deviceId}`),r=s.deviceId)}}return r})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}},nr=Em;q([be(Z.INIT,"capture",{ignoreError:!0,sync:!0})],nr.prototype,"setStateToCapture",1),q([Sg()],nr.prototype,"capture",1),q([be("capture","publish",{ignoreError:!0,success(){var t,e;this.room.localTracks.add(this),B.emit(O.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((e=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:e.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var o,s;if(!((((s=(o=this.room)==null?void 0:o.networkQuality)==null?void 0:s.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let a=this.kind===D.AUDIO,d=this.stat.bytesSent>0;X[d?"addSuccessEvent":"addFailedEvent"]({key:a?503700:513702}),d||(X.addEnum({key:a?503701:513703,value:Ia()}),Le.uploadEvent({log:`stat-encode-failed-${this.kind}-${Ta()||vo()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(i){let t="error";if(i.cause instanceof RTCError){let e=i.cause;e.message.includes("timeout")?t="timeout":e.code===Y.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i.cause||i})}}),eu(521714,!1)],nr.prototype,"publish",1),q([Ce(i=>function(){return v(this,null,function*(){let t=this.state==="publish"?"started":"starting";i.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),be([],"capture",{sync:!0})],nr.prototype,"unpublish",1);var Ha=new Map;B.on(O.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&Ha.delete(i.track.deviceId)});var ar=class extends nr{constructor(e){super(1,Qd);l(this,"mediaType",1);l(this,"volume",0);l(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});l(this,"playerMuted",!0);l(this,"pipeline");l(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new Gs(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return v(this,null,function*(){let r=this.trackSettings||{};X.addEnum({key:501701,value:r.channelCount||0,useUV:!1}),X.addEnum({key:501702,value:r.sampleRate||0,useUV:!1}),X.addEnum({key:502700,value:0});let{sampleRate:o,channelCount:s}=r;this._log.info(`local audio track input ${JSON.stringify({sampleRate:o,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Lt(ar.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:r,useExactDeviceId:o=!0,retryWhenExactFailed:s=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:o,retryWhenExactFailed:s,customSource:r})}switchDevice(e){return v(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===Eo){if(yield _m(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),B.emit(O.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(r){throw this.log.error(`switch microphone failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}}})}listenDeviceChange(){_t&&!_t.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&_t.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return v(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),ze(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield zt();r[0]?this.recapture(r[0].deviceId):_t.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(s){return v(this,arguments,function*({echoCancellation:e,noiseSuppression:r,autoGainControl:o}){let a=!1;!L(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a=!0),!L(r)&&r!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=r,a=!0),!L(o)&&o!==this.profile.autoGainControl&&(this.profile.autoGainControl=o,a=!0),a&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&X.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let r=this._inputTrack.getConstraints();return r.noiseSuppression=e,this._inputTrack.applyConstraints(r).catch(o=>this._log.warn(`${e?"enable":"disable"} ANS failed `,o))}addDenoiser(e){var r;if(gi<=92&&((r=this.trackSettings)==null?void 0:r.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}X.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),_t.off("audioInputAdded",this.handleMicrophoneAdded,this),_t.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return v(this,null,function*(){try{yield Lt(ar.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield zt()).find(s=>s.deviceId!==e);if(o)yield Lt(ar.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((r,o)=>o?o({frame:r}):r,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Lo=class{constructor(t,e=!1){this.dataView=t;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,r=[],o=0;for(let a=t;a<=e;a++){let d=this.dataView.getInt8(a);switch(d){case 0:case 1:case 2:case 3:o===2&&(r.push(3),o=0),d==0?o++:o=0,r.push(d);break;default:o=0,r.push(d);break}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}removePreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,r=[],o=0;for(let a=t;a<=e;a++)switch(this.dataView.getInt8(a)){case 0:o++,r.push(this.dataView.getInt8(a));break;case 3:o!==2&&r.push(this.dataView.getInt8(a)),o=0;break;default:r.push(this.dataView.getInt8(a)),o=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let t=6;for(let e=6;e<this.dataView.buffer.byteLength&&(t++,this.dataView.getUint8(e)===255);e++);return t}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let t=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let a=this.dataView.getUint8(s);if(e++,a===255)t+=255;else{t+=a;break}}let r=new ArrayBuffer(t),o=new DataView(r);for(let s=0;s<r.byteLength;s++,e++)o.setInt8(s,this.dataView.getInt8(e));return o}};var tu=class{constructor(){l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_seiPayloadType",243)}encodeSEINalu(t){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let d=0;d<r;d++)s.push(255);s.push(o);let a=new DataView(t);return s.push(...new Uint8Array(a.buffer)),s.push(128),new Lo(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(t,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(t),e!=null&&e.small&&this._smallSeiMessageList.push(t)}isEmpty(){return!this._seiMessageList.length}getNaluCount(t){let e=0,r=0,o=new DataView(t);for(let s=0;s<t.byteLength;s++)switch(o.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&r++,e=0;break;default:e=0;break}return r}encode(t,e){let r=e?this._smallSeiMessageList:this._seiMessageList;if(r.length>0&&t.data.byteLength>0){let o=this.getNaluCount(t.data),s=9-o;if(s<=0)return 0;let a=r.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),d=a.reduce((R,N)=>R+N.dataView.byteLength,0),h=new ArrayBuffer(d+t.data.byteLength),p=new DataView(h),T=new DataView(t.data),y=0;for(let R=0;R<a.length;R++)for(let N=0;N<a[R].dataView.byteLength;N++)p.setInt8(y++,a[R].dataView.getInt8(N));for(let R=0;R<t.data.byteLength;R++)p.setInt8(y++,T.getInt8(R));return t.data=h,a.length}return 0}};var Js=class extends nr{constructor(e,r=4){super(r,or);l(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});l(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});l(this,"small");l(this,"isNeedToSetBandwidth");l(this,"muteImage");l(this,"manager");l(this,"_seiCodec",new tu);this.manager=e;let o=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(me(J({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",o),this.on("publish",o),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Fs||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return v(this,null,function*(){var r,o,s;if(Ae(e)){if(this.muteImage===e)return;yield(r=this.manager)==null?void 0:r.deleteWatermark("mute"),yield(o=this.manager)==null?void 0:o.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Lt(Js.prototype,this,"setMute").call(this,!1)}else yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0,Lt(Js.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:r,useExactDeviceId:o=!0,customSource:s,retryWhenExactFailed:a=!0}){return super.capture({audio:!1,video:!0,facingMode:r||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:o,retryWhenExactFailed:a,customSource:s})}setProfile(e){let r=J({},e),o=r.width>r.height;r.width*r.height<=160*120&&ft&&bo&&(this.log.warn(`resolution is ${r.width}*${r.height}, fallback to 240*180`),r.width=o?240:180,r.height=o?180:240,r.bitrate=Math.max(r.bitrate,150)),r.width*r.height>1280*720&&Cp&&(r.width=o?1280:720,r.height=o?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(r):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(me(J({},this.profile),{width:1920,height:1080})))}applyProfile(){return v(this,null,function*(){var o;if(!this.mediaTrack)return;let e=this.settings;if(!(!(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)||!this.deviceId)&&(ir===16?yield this.recapture(this.deviceId):(yield(o=this.mediaTrack)==null?void 0:o.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth))return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:D.VIDEO,videoType:D.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Fs&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:cd()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var r;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((r=this.room.scheduleResult.trtcAutoConf)==null?void 0:r["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return v(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let r={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?r.facingMode=e:r.deviceId=e,this.mediaTrack.stop(),yield this.capture(r),B.emit(O.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(r){throw this.log.error(`switch camera failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}})}listenDeviceChange(){_t&&!_t.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&_t.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return v(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),ze(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield sr();r[0]?this.recapture(r[0].deviceId):_t.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return v(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,r){if(!this.manager)return e;let o=r?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,a)=>a?a({frame:s,mediaType:o}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,r){return L(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,r)}close(){_t.off("videoInputAdded",this.handleCameraAdded,this),_t.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return v(this,null,function*(){try{yield Lt(Js.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield sr()).find(s=>s.deviceId!==e);if(o)yield Lt(Js.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}},hr=Js;q([zi(function(i){this.setContentHint(i.contentHint||"motion")})],hr.prototype,"capture",1);var bg=ya();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:bg,exposeOrigin:!0,permittedOrigins:["*"]})}catch(i){}var rS=function(i){return v(this,null,function*(){let t=null,e=sS(i);V.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);i.systemAudio&&r.getAudioTracks().length===0&&(Os&&gi<74||Wt||Cr)&&V.warn("Your browser not support capture system audio");let o=r.getVideoTracks()[0];if(o){if(i.frameRate)try{yield o.applyConstraints({frameRate:{min:i.frameRate,ideal:i.frameRate},width:i.width,height:i.height})}catch(s){V.warn(`screen applyConstraints failed: ${s}`)}i.captureElement&&(yield iS(o,i.captureElement))}if(i.audio){let s=oS(i);V.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})};function iS(i,t){return v(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&Ve(i.cropTo))try{if(!(((e=i.getCaptureHandle())==null?void 0:e.handle)===bg))return;let o=yield CropTarget.fromElement(t);yield i.cropTo(o)}catch(r){V.warn(`cropTo target failed ${r}`)}})}function oS(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return L(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function sS(i){let t={preferCurrentTab:i.preferDisplaySurface==="current-tab"||!!i.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Wt?{max:i.width}:{ideal:i.width,max:i.width},height:Wt?{max:i.height}:{ideal:i.height,max:i.height},frameRate:i.frameRate,displaySurface:i.preferDisplaySurface||"monitor"};if(t.video=e,i.systemAudio){let{echoCancellation:r=!0,noiseSuppression:o=!1,autoGainControl:s=!1}=i;t.audio={echoCancellation:r,noiseSuppression:o,autoGainControl:s,sampleRate:48e3}}return t}var vg=rS;var Ji=class extends hr{constructor(e){super(e,2);l(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});l(this,"objectFit","contain");l(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(T){return v(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:s,audioTrack:a,videoTrack:d,captureElement:h,preferDisplaySurface:p}){try{let y;return d||a?(y=new MediaStream,d&&y.addTrack(d),a&&y.addTrack(a)):y=yield vg({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:s,captureElement:h,preferDisplaySurface:p}),yield this.setInputMediaStreamTrack(y.getVideoTracks()[0]),y}catch(y){throw this.log.error(`getDisplayMedia error observed ${y}`),y instanceof de?y:new de({code:Y.INITIALIZE_FAILED,name:y.name,message:y.message})}})}switchDevice(e){return v(this,null,function*(){throw new Error("Method not implemented.")})}};q([zi(function(i){this.setContentHint(i.contentHint||"detail")})],Ji.prototype,"capture",1);var Uo=class extends ar{constructor(t){super(t),this._log.id=`s-${this._log.id}`}};var nS="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Im;function Wa(i){return v(this,null,function*(){let t=qt("dump");Im||(Im=Po(t,URL.createObjectURL(new Blob([nS],{type:"application/javascript"})))),yield Im;let e=new AudioWorkletNode(t,"dumper",{numberOfInputs:i.length,numberOfOutputs:0});return i.forEach((r,o)=>r.connect(e,0,o)),new ReadableStream({start(r){e.port.onmessage=o=>{r.enqueue(o.data)}},cancel(){i.forEach(r=>r.disconnect(e)),e.port.close()}})})}var ru=class extends qd{constructor(e){super();this.room=e;l(this,"_localAudioTrack");l(this,"_localScreenAudioTrack");l(this,"log",V.createLogger({id:"am"}));l(this,"denoiser");l(this,"mixChangedDebounce");l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var T,y;if(!this._localAudioTrack)return;let r=[],o=[];(T=this._localAudioPipline)!=null&&T.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),(y=this._localAudioPipline)!=null&&y.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),o.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),o.push("mix")),this.log.info(`dump audio track ${o}, duration: ${e}`);let s=new AbortController,a=[],d=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),h=()=>{for(let R=0;R<o.length;R++){let N=URL.createObjectURL(new Blob(a[R])),j=document.createElement("a");j.href=N,j.download=`${o[R]}.pcm`,j.style.display="none",document.body.appendChild(j),j.click(),URL.revokeObjectURL(N),j.remove()}clearTimeout(d),s.abort("download")},p=Wa(r).then(R=>R.pipeTo(new WritableStream({write(N){N.forEach((j,W)=>a[W]=a[W]?a[W].concat(j[0]):[j[0]])}}),s).catch(N=>h));return{then:p.then.bind(p),download:h}}getPCM(e){var a;if(L(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((a=this._localAudioPipline)!=null&&a.source.node)){this.log.warn("getPCM failed: no local audio track");return}this.log.warn("getPCM");let r=new Float32Array(1920),o=0,s=new AbortController;return Wa([this._localAudioPipline.source.node]).then(d=>d.pipeTo(new WritableStream({write(h){!h[0][0]||(r.set(h[0][0],o),o+=h[0][0].length,o>=1920&&(o=0,e(r),r=new Float32Array(1920)))}}),s).catch(h=>this.log.warn(`stop getPCM reason:${h}`))),s}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!L(this._localAudioTrack)}changeInput(e){if(e instanceof Uo)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof ar)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof Vo)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,r;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(r=this._localScreenAudioTrack)==null?void 0:r.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof Uo?delete this._localScreenAudioTrack:e instanceof ar?delete this._localAudioTrack:e instanceof Vo}addDenoiser(e){var r;this.denoiser=e,(r=this._localAudioTrack)==null||r.addDenoiser(e)}removeDenoiser(e){var r;delete this.denoiser,(r=this._localAudioTrack)==null||r.removeDenoiser(e)}destroy(){this.close()}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};function Rg(i=30,t=2){return Ce((e,r)=>function(...o){return new Promise((s,a)=>{let d=setTimeout(()=>{let h=new de({code:Y.API_CALL_TIMEOUT,message:`checkPendingPromise ${r}() timeout ${i}s`});V.warn(h),t===2?a(h):t===1&&s()},i*1e3);e.apply(this,o).then(s,a).finally(()=>{clearTimeout(d)})})})}var Sm=class extends ko{constructor(e,r,o){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:o,room:e});this.room=e;this.user=r;l(this,"tinyId");l(this,"isRemote",!0);l(this,"jitterBufferDelay",0);l(this,"_decodeCheckTimeoutId",-1);this.tinyId=r.tinyId}setMute(e){this.isAvailable&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isAvailable&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Sm.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,r){let o=this.kind===D.AUDIO;X[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),e||(X.addEnum({key:o?504701:514703,value:Ia()}),Le.uploadEvent({log:`stat-decode-failed-${this.kind}-${Ta()||vo()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===D.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:r}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isAvailable||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isAvailable} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.isAvailable)}onTrackMuted(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},fr=Sm;l(fr,"STATE_SUBSCRIBE","subscribe"),q([Rg(5,1)],fr.prototype,"waitHasMediaTrack",1),q([be(Z.INIT,fr.STATE_SUBSCRIBE,{success(){var t,e;this.log.info("subscribed"),B.emit(O.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),!((((e=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:e.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&(this._decodeCheckTimeoutId=setTimeout(()=>{var o,s;if(!((((s=(o=this.room)==null?void 0:o.networkQuality)==null?void 0:s.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let a=this.kind===D.AUDIO,d=this.player.isPlaying||(a?this.getAudioLevel()>0:this.stat.framesDecoded>0);this.reportDecodeResult(d)}},5e3),this.player.once(at.ERROR,r=>{r.code===MediaError.MEDIA_ERR_DECODE&&(clearTimeout(this._decodeCheckTimeoutId),this.reportDecodeResult(!1,3))}))},ignoreError:!0}),eu(521716,!1)],fr.prototype,"subscribe",1),q([be(fr.STATE_SUBSCRIBE,Z.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),B.emit(O.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],fr.prototype,"unsubscribe",1);var Vo=class extends fr{constructor(e,r){super(e,r,1);l(this,"volume",0);l(this,"mediaType",1);l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}decodeFrame(e){if(!this.manager)return e;let r=e;for(let o of this.manager.decodePipeline)if(!!o&&(r=o({frame:r,track:this}),!r))return;return r}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isAvailable(){return this.user.muteState.audioAvailable}};var cS=[-1,-1,1,-1,-1,1,1,1],dS=[0,0,1,0,0,1,1,1];var Vt=class extends Z{constructor(e,r){super();this.context=e;l(this,"name");l(this,"input");l(this,"output");l(this,"texture");l(this,"ctx2d",null);l(this,"fbo");l(this,"width",0);l(this,"height",0);l(this,"x",0);l(this,"y",0);l(this,"program");l(this,"vertexShader");l(this,"fragmentShader");l(this,"totalFrames",0);l(this,"dropFrames",0);l(this,"matchInputSize",!0);l(this,"texCoordBuffer");l(this,"positionBuffer");l(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});l(this,"cost",0);l(this,"_canvas",null);l(this,"_image");l(this,"log");if(this.context.on("disconnect",this.close,this),this.name=r.name,this.log=r.logger,this.matchInputSize=r.matchInputSize!==!1,this.width=r.width||e.width,this.height=r.height||e.height,this._image=r.image,e instanceof Ct){e.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&ir!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let o=e.ctx;this.texCoordBuffer=this.createBuffer(dS),this.positionBuffer=this.createBuffer(cS),r.createTexture!==!1&&(this.texture=o.createTexture(),this.useTexture(),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),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.pixelStorei(o.PACK_ALIGNMENT,1),o.pixelStorei(o.UNPACK_ALIGNMENT,1)),r.useFbo&&(this.fbo=o.createFramebuffer(),this.useBufferFrame(),this.useTexture(),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,this.width,this.height,0,o.RGBA,o.UNSIGNED_BYTE,null),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.texture,0)),r.useDefaultProgram?this.program=e.defaultProgam:(r.vertexShaderSource||r.fragmentShaderSource)&&(this.vertexShader=r.vertexShaderSource?e.createShader(o.VERTEX_SHADER,r.vertexShaderSource):e.defaultVShader,this.fragmentShader=r.fragmentShaderSource?e.createShader(o.FRAGMENT_SHADER,r.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(o){this.context.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${o.message||o}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let r=this.context.ctx,o=r.createFramebuffer();return r.bindFramebuffer(r.FRAMEBUFFER,o),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0),o}connect(e,...r){return e.addInput(this,...r),this.output=e,e}addInput(e,...r){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let r=Date.now();if(this.context instanceof st&&this.render(e)||this.context instanceof Ct&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-r,!0}render2d(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var r;(r=this.output)==null||r.update(e)}disconnect(...e){var r;(r=this.output)==null||r.removeInput(this,...e),delete this.output}removeInput(e,...r){delete this.input}close(){var e,r;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(r=this.input)==null||r.disconnect(),this.context instanceof st){let o=this.context.ctx;o.deleteBuffer(this.texCoordBuffer),o.deleteBuffer(this.positionBuffer),this.fbo&&o.deleteFramebuffer(this.fbo),this.texture&&o.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&o.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&o.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&o.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let r=this.context.ctx;e.forEach((o,s)=>{o&&(r.activeTexture(r.TEXTURE0+s),r.bindTexture(r.TEXTURE_2D,o))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let r=this.context.ctx,o=r.createBuffer();return r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW),o}setTexBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.texCoordBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}setPosBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.positionBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}changeBufferData(e,r){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,e),o.bufferData(o.ARRAY_BUFFER,new Float32Array(r),o.STATIC_DRAW)}setAttributes(...e){let r=this.context.ctx;e.forEach((o,s)=>{r.enableVertexAttribArray(s),r.bindBuffer(r.ARRAY_BUFFER,o),r.vertexAttribPointer(s,2,r.FLOAT,!1,0,0)})}getVertexPoint(e,r){return[e/this.width*2-1,r/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,r){if(!(this.width===e&&this.height===r)){if(this.width=e,this.height=r,this._canvas&&(this._canvas.width=e,this._canvas.height=r),this.texture&&this.fbo){this.useTexture();let o=this.context.ctx;o.texImage2D(o.TEXTURE_2D,0,o.RGBA,e,r,0,o.RGBA,o.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,r)}}draw(e,r){this.setAttributes(e||this.positionBuffer,r||this.texCoordBuffer);let o=this.context.ctx;o.drawArrays(o.TRIANGLE_STRIP,0,4)}draw2d(e,r,o,s,a){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,r,o):(this.ctx2d.drawImage(e,r,o,s,a),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var y;let{totalFrames:e,x:r,y:o,width:s,height:a,name:d,cost:h}=this,p=Date.now(),T=(e-this.lastInfo.totalFrames)/((p-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:a,timestamp:p,fps:T,name:d,cost:h},J({parent:(y=this.input)==null?void 0:y.getInfo()},this.lastInfo)}createTexture(e){let r=this.context.ctx,o=r.createTexture();return this.useTextures(o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),o}};q([be(Z.INIT,"connected",{sync:!0})],Vt.prototype,"connect",1),q([be("connected",Z.INIT,{ignoreError:!0,sync:!0})],Vt.prototype,"disconnect",1),q([be([],"closed",{sync:!0})],Vt.prototype,"close",1);var nh={};li(nh,{Events:()=>et,Inspect:()=>_r,LastSink:()=>Bo,Sink:()=>ae,Subscribe:()=>Fo,TimeoutError:()=>Ga,audit:()=>qS,bindCallback:()=>xS,bindNodeCallback:()=>MS,buffer:()=>IS,bufferCount:()=>TS,bufferTime:()=>ly,call:()=>Dg,catchError:()=>qa,combineLatest:()=>wg,concat:()=>hS,concatMap:()=>iy,concatMapTo:()=>oy,count:()=>kS,create:()=>ve,debounce:()=>zS,debounceTime:()=>JS,defer:()=>xg,delay:()=>py,deliver:()=>le,dispose:()=>iu,elementAt:()=>XS,empty:()=>Ho,every:()=>ey,exhaustMap:()=>ay,exhaustMapTo:()=>cy,filter:()=>Go,find:()=>QS,findIndex:()=>YS,first:()=>ZS,fromAnimationFrame:()=>NS,fromArray:()=>AS,fromEvent:()=>Je,fromEventPattern:()=>bS,fromFetch:()=>vS,fromIterable:()=>RS,fromPromise:()=>Pg,fromReadableStream:()=>DS,fromReader:()=>CS,groupBy:()=>dy,identity:()=>uS,ignoreElements:()=>BS,iif:()=>_S,inspect:()=>Ng,interval:()=>Cm,last:()=>KS,map:()=>fu,mapTo:()=>ry,max:()=>LS,merge:()=>pS,mergeMap:()=>sy,mergeMapTo:()=>ny,min:()=>US,never:()=>OS,nothing:()=>Ue,of:()=>yS,pairwise:()=>ty,pipe:()=>We,race:()=>mS,range:()=>wS,reduce:()=>Nm,retry:()=>fy,scan:()=>th,share:()=>Ri,shareReplay:()=>fS,skip:()=>$S,skipUntil:()=>HS,skipWhile:()=>cu,startWith:()=>$o,subject:()=>Jt,subscribe:()=>dt,sum:()=>VS,switchMap:()=>Qi,switchMapTo:()=>ja,take:()=>xr,takeLast:()=>FS,takeUntil:()=>gt,takeWhile:()=>kg,tap:()=>oh,throttle:()=>GS,throwError:()=>PS,timeInterval:()=>uy,timeout:()=>sh,timer:()=>Dm,toPromise:()=>my,toReadableStream:()=>hy,withLatestFrom:()=>ES,zip:()=>gS});function Ue(...i){}var Dg=i=>i(),uS=i=>i;function iu(){this.dispose()}var Ng=()=>typeof __FASTRX_DEVTOOLS__!="undefined",lS=1,_r=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new Am(t,this,this.streamId++);return et.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Bo=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Ue,this.error=Ue,this.next=Ue,this.dispose=Ue,this.subscribe=Ue,this.doDefer()}subscribe(t){return t instanceof _r?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Dg),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},ae=class extends Bo{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},Fo=class extends Bo{constructor(t,e=Ue,r=Ue,o=Ue){if(super(),this._next=e,this._error=r,this._complete=o,this.then=Ue,t instanceof _r){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{et.defer(s,0)}),et.create(s),et.pipe(s),this.sourceId=s.id,this.subscribe(t),et.subscribe({id:s.id,end:!0}),e==Ue?this._next=a=>et.next(s,0,a):this.next=a=>{et.next(s,0,a),e(a)},o==Ue?this._complete=()=>et.complete(s,0):this.complete=()=>{this.dispose(),et.complete(s,0),o()},r==Ue?this._error=a=>et.complete(s,0,a):this.error=a=>{this.dispose(),et.complete(s,0,a),r()}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function We(i,...t){return t.reduce((e,r)=>r(e),i)}function ve(i,t,e){if(Ng()){let r=Object.defineProperties(Object.setPrototypeOf(i,_r.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});et.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof _r&&et.addSource(r,s)}return r}return i}function le(i,t){return function(...e){return r=>{if(r instanceof _r){let o=ve(s=>{let a=new i(s,...e);a.sourceId=o.id,a.subscribe(r)},t,arguments);return o.source=r,et.pipe(o),o}else return o=>r(new i(o,...e))}}}function Xi(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var Am=class extends ae{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{et.defer(this.source,this.id)})}next(t){et.next(this.source,this.id,t),this.sink.next(t)}complete(){et.complete(this.source,this.id),this.sink.complete()}error(t){et.complete(this.source,this.id,t),this.sink.error(t)}},et={addSource(i,t){Xi("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){Xi("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){Xi("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){Xi("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){Xi("defer",{id:i.id,streamId:t})},pipe(i){Xi("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){Xi("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=lS++),Xi("create",{name:i.toString(),id:i.id})}},Ga=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var ou=class extends Bo{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function Ri(){return i=>{let t=new ou(i);if(i instanceof _r){let e=ve(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,et.pipe(e),e}return ve(t.add.bind(t),"share",arguments)}}function pS(...i){return ve(t=>{let e=new ae(t),r=i.length;e.complete=()=>{--r===0&&t.complete()},i.forEach(e.bindSubscribe)},"merge",arguments)}function mS(...i){return ve(t=>{let e=new Map;i.forEach(r=>{let o=new ae(t);e.set(r,o),o.complete=()=>{e.delete(r),e.size===0?t.complete():o.dispose()},o.next=s=>{e.delete(r),e.forEach(a=>a.dispose()),o.resetNext(),o.resetComplete(),o.next(s)}}),i.forEach(r=>e.get(r).subscribe(r))},"race",arguments)}function hS(...i){return ve(t=>{let e=0,r=i.length,o=new ae(t);o.complete=()=>{e<r&&!o.disposed?(o.doDefer(),o.subscribe(i[e++])):t.complete()},o.complete()},"concat",arguments)}function fS(i){return t=>{let e=new ou(t),r=[];return e.next=function(o){r.push(o),r.length>i&&r.shift(),this.sinks.forEach(s=>s.next(o))},ve(o=>{o.defer(()=>e.remove(o)),r.forEach(s=>o.next(s)),e.add(o)},"shareReplay",arguments)}}function _S(i,t,e){return ve(r=>i()?t(r):e(r),"iif",arguments)}function wg(...i){return ve(t=>{let e=i.length,r=e,o=e,s=new Array(e),a=()=>{--o===0&&t.complete()},d=(h,p)=>{let T=new ae(t);T.next=y=>{--r===0?(T.next=R=>{s[p]=R,t.next(s)},T.next(y)):s[p]=y},T.complete=a,T.subscribe(h)};i.forEach(d)},"combineLatest",arguments)}function gS(...i){return ve(t=>{let e=i.length,r=e,o=new Array(e),s=()=>{--r===0&&t.complete()},a=(d,h)=>{let p=new ae(t),T=[];o[h]=T,p.next=y=>{T.push(y),o.every(R=>R.length)&&t.next(o.map(R=>R.shift()))},p.complete=s,p.subscribe(d)};i.forEach(a)},"zip",arguments)}function $o(...i){return t=>ve((e,r=0,o=i.length)=>{for(;r<o&&!e.disposed;)e.next(i[r++]);e.disposed||e.subscribe(t)},"startWith",arguments)}var bm=class extends ae{constructor(t,...e){super(t);let r=new ae(this.sink);r.next=o=>this.buffer=o,r.complete=Ue,r.subscribe(wg(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},ES=le(bm,"withLatestFrom"),vm=class extends ae{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(t=>this.sink.next(t)),super.complete()}},TS=le(vm,"bufferCount"),Rm=class extends ae{constructor(t,e){super(t),this.buffer=[];let r=new ae(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=Ue,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},IS=le(Rm,"buffer");var SS=function(i,t,e,r){function o(s){return s instanceof e?s:new e(function(a){a(s)})}return new(e||(e=Promise))(function(s,a){function d(T){try{p(r.next(T))}catch(y){a(y)}}function h(T){try{p(r.throw(T))}catch(y){a(y)}}function p(T){T.done?s(T.value):o(T.value).then(d,h)}p((r=r.apply(i,t||[])).next())})};function Jt(i){let t=arguments,e=Ri()(ve(r=>{e.next=o=>r.next(o),e.complete=()=>r.complete(),e.error=o=>r.error(o),i&&r.subscribe(i)},"subject",t));return e.next=Ue,e.complete=Ue,e.error=Ue,e}function xg(i){return ve(t=>t.subscribe(i()),"defer",arguments)}var Mg=i=>t=>{setTimeout(()=>i(t))},Og=i=>Mg(t=>{for(let e=0;!t.disposed&&e<i.length;e++)t.next(i[e]);t.complete()});function yS(...i){return ve(Og(i),"of",arguments)}function AS(i){return ve(Og(i),"fromArray",arguments)}function Cm(i){return ve(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function Dm(i,t){return ve(e=>{let r=0,o=setTimeout(()=>{if(e.removeDefer(s),e.next(r++),t){let a=setInterval(()=>e.next(r++),t);e.defer(()=>{clearInterval(a)})}else e.complete()},i),s=()=>{clearTimeout(o)};e.defer(s)},"timer",arguments)}function su(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function bS(i,t){return ve(su(i,t),"fromEventPattern",arguments)}function Je(i,t){if("on"in i&&"off"in i)return ve(su(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i&&"removeListener"in i)return ve(su(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return ve(su(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function Pg(i){return ve(t=>{i.then(t.next.bind(t),t.error.bind(t))},"fromPromise",arguments)}function vS(i,t){return ve(xg(()=>Pg(fetch(i,t))),"fromFetch",arguments)}function RS(i){return ve(Mg(t=>{try{for(let e of i){if(t.disposed)return;t.next(e)}t.complete()}catch(e){t.error(e)}}),"fromIterable",arguments)}function CS(i){let t=e=>SS(this,void 0,void 0,function*(){if(e.disposed)return;let{done:r,value:o}=yield i.read();if(r){e.complete();return}else e.next(o),t(e)});return ve(e=>{t(e)},"fromReader",arguments)}function DS(i){return ve(t=>{let e=new AbortController,r=e.signal;t.defer(()=>e.abort("cancelled")),i.pipeTo(new WritableStream({write(o){t.next(o)},close(){t.complete()},abort(o){t.error(o)}}),{signal:r}).then(()=>t.complete(),o=>t.error(o))},"fromReadableStream",arguments)}function NS(){return ve(i=>{let t=requestAnimationFrame(function e(r){i.disposed||(i.next(r),t=requestAnimationFrame(e))});i.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function wS(i,t){return ve((e,r=i,o=t+i)=>{for(;r<o&&!e.disposed;)e.next(r++);return e.complete(),"range"},"range",arguments)}function xS(i,t,...e){return ve(r=>{let o=e.concat(s=>(r.next(s),r.complete()));i.apply(t,o)},"bindCallback",arguments)}function MS(i,t,...e){return ve(r=>{let o=e.concat((s,a)=>s?r.error(s):(r.next(a),r.complete()));i.apply(t,o)},"bindNodeCallback",arguments)}function OS(){return ve(()=>{},"never",arguments)}function PS(i){return ve(t=>t.error(i),"throwError",arguments)}function Ho(){return ve(i=>i.complete(),"empty",arguments)}var Wo=class extends ae{constructor(t,e,r){super(t),this.f=e;let o=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=s=>{this.acc=s,this.complete=o,this.resetNext()}:(this.acc=r,this.complete=o)}next(t){this.acc=this.f(this.acc,t)}},Nm=le(Wo,"reduce"),kS=i=>le(Wo,"count")((t,e)=>i(e)?t+1:t,0),LS=()=>le(Wo,"max")(Math.max),US=()=>le(Wo,"min")(Math.min),VS=()=>le(Wo,"sum")((i,t)=>i+t,0);var wm=class extends ae{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},Go=le(wm,"filter"),xm=class extends ae{next(t){}},BS=le(xm,"ignoreElements"),Mm=class extends ae{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},xr=le(Mm,"take"),Om=class extends ae{constructor(t,e){super(t);let r=new ae(t);r.next=()=>t.complete(),r.complete=iu,r.subscribe(e)}},gt=le(Om,"takeUntil"),Pm=class extends ae{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},kg=le(Pm,"takeWhile"),FS=i=>Nm((t,e)=>(t.push(e),t.length>i&&t.shift(),t),[]),km=class extends ae{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},$S=le(km,"skip"),Lm=class extends ae{constructor(t,e){super(t),t.next=Ue;let r=new ae(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=iu,r.subscribe(e)}},HS=le(Lm,"skipUntil"),Um=class extends ae{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},cu=le(Um,"skipWhile"),WS={leading:!0,trailing:!1},Vm=class extends ae{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},nu=class extends ae{constructor(t,e,r=WS){super(t),this.durationSelector=e,this.config=r,this._throttle=new Vm(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=Ue,this._throttle.complete(),super.complete()}},GS=le(nu,"throttle"),jS={leading:!1,trailing:!0},qS=i=>le(nu,"audit")(i,jS),Bm=class extends ae{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},au=class extends ae{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Bm(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},zS=le(au,"debounce"),JS=i=>le(au,"debounceTime")(t=>Dm(i)),Fm=class extends ae{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},XS=le(Fm,"elementAt"),QS=i=>t=>xr(1)(cu(e=>!i(e))(t)),$m=class extends ae{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},YS=le($m,"findIndex"),Hm=class extends ae{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},ZS=le(Hm,"first"),Wm=class extends ae{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},KS=le(Wm,"last"),Gm=class extends ae{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},ey=le(Gm,"every");var jm=class extends ae{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=o=>{this.acc=o,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},th=le(jm,"scan"),qm=class extends ae{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},ty=le(qm,"pairwise"),du=class extends ae{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},fu=le(du,"map"),ry=i=>le(du,"mapTo")(t=>i),Xs=class extends ae{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},Qs=class extends ae{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},uu=class extends Xs{},lu=class extends Qs{next(t){this.subInner(t,uu),this.next=e=>{this.currentSink.dispose(),this.subInner(e,uu)}}},Qi=le(lu,"switchMap");function _u(i){return(t,e)=>i(()=>t,e)}var ja=_u(le(lu,"switchMapTo")),zm=class extends Xs{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},pu=class extends Qs{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),zm),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},iy=le(pu,"concatMap"),oy=_u(le(pu,"concatMapTo")),Jm=class extends Xs{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},mu=class extends Qs{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Jm),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},sy=le(mu,"mergeMap"),ny=_u(le(mu,"mergeMapTo")),Xm=class extends Xs{dispose(){this.context.resetNext(),super.dispose()}},hu=class extends Qs{next(t){this.next=Ue,this.subInner(t,Xm)}},ay=le(hu,"exhaustMap"),cy=_u(le(hu,"exhaustMapTo")),Qm=class extends ae{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=Jt(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},dy=le(Qm,"groupBy"),Ym=class extends ae{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},uy=le(Ym,"timeInterval"),Zm=class extends ae{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},ly=le(Zm,"bufferTime"),Km=class extends ae{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:o}=e;super.next(o),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},py=le(Km,"delay"),eh=class extends ae{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},qa=le(eh,"catchError");var my=()=>i=>new Promise((t,e)=>{let r;new Fo(i,o=>r=o,e,()=>t(r))}),hy=()=>i=>{let t;return new ReadableStream({start(e){t=new Fo(i,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){t.dispose()}})},dt=(i=Ue,t=Ue,e=Ue)=>r=>new Fo(r,i,t,e),rh=class extends ae{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},oh=le(rh,"tap"),ih=class extends ae{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new Ga(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},sh=le(ih,"timeout"),fy=(i=1/0)=>t=>{if(t instanceof _r){let e=ve(r=>{let o=i,s=new ae(r);s.error=a=>{o-- >0?s.subscribe(t):r.error(a)},s.sourceId=e.id,s.subscribe(t)},"retry",[i]);return e.source=t,et.pipe(e),e}else return e=>{let r=i,o=new ae(e);o.error=s=>{r-- >0?t(o):e.error(s)},t(o)}};var Lg=We(Cm(250),fu(()=>performance.now()),Ri()),Ug=i=>t=>{let e=0,r=performance.now();We(Lg,fu(o=>(o-r)/i>>0),Go(o=>o!=e?(e=o,!0):!1))(t)},gu=i=>t=>{let e=performance.now();We(Lg,cu(r=>r-e<i),xr(1))(t)};var gy=[0,1,1,1,0,0,1,0],jo=class extends Vt{constructor(e,r){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},r));l(this,"_intervalId",0);l(this,"_sequence",0);l(this,"checkGLError",!1);l(this,"checkVisibilityChange");e instanceof Ct?this.ctx2d=e.ctx||null:e.available&&(r==null?void 0:r.mirrorUpAndDown)&&this.setTexBuffer(gy)}start(e){this.log.info(`${this.name} start render ${e} fps`),Et.clearTask(this._intervalId),this._intervalId=Et.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Et.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof st){let o=this.context.ctx.getError();o&&this.context.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${o}`}))}},{fps:this.context.frameRate})}render(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...r){super.addInput(e,...r),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(Et.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let r=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",r))};document.addEventListener("visibilitychange",r)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),Et.clearTask(this._intervalId)}resize(e,r){super.resize(e,r),this.context.setSize(e,r)}close(){super.close(),Et.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Ys=class extends jo{constructor(e,r){super(e,r);l(this,"_videoTrack");l(this,"_muteOb");l(this,"_closedOb",Je(this,"closed"));l(this,"_subscription");l(this,"_canvasContainer");Number(Fi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=Je(this._videoTrack,"mute"),We(Je(this._videoTrack,"ended"),gt(this._closedOb),dt(()=>{this.context.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=We(this._muteOb,gt(this._closedOb),ja(gu(5e3)),dt(()=>{var e;!((e=this._videoTrack)!=null&&e.muted)||this.context.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,r;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(r=this._canvasContainer)==null||r.remove()}},Eu=class extends Ys{render(t){var e;return!!((e=this.input)!=null&&e.requestFrame(t))}};var Tu=class extends Ys{constructor(e,r,o){super(e,{name:"smallDestination",logger:o});this.resolution=r}resize(e,r){let o,s=e*r,a=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${r} small res: ${this.resolution.width}*${this.resolution.height} `),s>a?o=s/a:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${r} small: ${this.resolution.width} * ${this.resolution.height}`),o=s/(160*120)),super.resize(e/Math.sqrt(o),r/Math.sqrt(o))}};var za=class extends Vt{constructor(e,r){super(e,J({name:"imageSource"},r));l(this,"_lastImage");l(this,"_totalFrames",0);l(this,"_autoResize",!1);l(this,"_canvasRendered");l(this,"_videoCallbackId",0);this._autoResize=(r==null?void 0:r.autoResize)!==!1,ir===16&&(this._canvasRendered=Jt(),We(this._canvasRendered,$o(this._image),Qi(o=>o instanceof HTMLCanvasElement?Je(o,"rendered"):Ho()),gt(Je(this,"closed")),dt(()=>{this.update()})))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Mo()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((r,o)=>{document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(e,r){var d;let{width:o,height:s}=this,{image:a}=this;if(a instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(a),{videoWidth:o,videoHeight:s}=a,!o||!s)return!1;a.width=o,a.height=s}else if(a instanceof HTMLImageElement||a instanceof ImageData||a instanceof ImageBitmap){if({width:o,height:s}=a,a!==this._lastImage)this._lastImage=a;else if(o===this.width&&s===this.height)return!1}else a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas?({width:o,height:s}=a,this._lastImage=a):typeof VideoFrame!="undefined"&&a instanceof VideoFrame&&({displayWidth:o,displayHeight:s}=a,(d=this._lastImage)==null||d.close(),this._lastImage=a);if(!this._autoResize)return!0;if(this.width===o&&this.height===s&&this.totalFrames){if(r){this.useTexture();let h=this.context.ctx;h.texSubImage2D(h.TEXTURE_2D,0,0,0,h.RGBA,h.UNSIGNED_BYTE,a)}}else{if(r){this.useTexture();let h=this.context.ctx;h.texImage2D(h.TEXTURE_2D,0,h.RGBA,h.RGBA,h.UNSIGNED_BYTE,a)}this.resize(o,s)}return!0}get image(){return this._image}set image(e){var r;(r=this._canvasRendered)==null||r.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Ja=class extends za{constructor(e,r,o){super(e,o);this._player=r;this.name="videoPlayerSource",We(Je(this._player,at.PLAYER_STATE_CHANGED),gt(Je(this,"closed")),Go(({state:s})=>s==="PLAYING"),dt(()=>{this.tryVideoFrameCallback(this._player.element)}))}get image(){return this._player.element}},Ci=class extends Ja{constructor(t,e,r){super(t,new or({id:r.name,track:e,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}};var Ty=`
|
|
30
30
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
31
31
|
attribute vec4 a_position;
|
|
32
32
|
attribute vec2 a_texCoord;
|
|
@@ -44,10 +44,10 @@ uniform sampler2D u_texture;
|
|
|
44
44
|
|
|
45
45
|
void main() {
|
|
46
46
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
47
|
-
} `;var qo=class extends Z{constructor(e){super();l(this,"frameRate");l(this,"_canvas");l(this,"log");l(this,"hasAlpha",!1);l(this,"name");l(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,r){this._canvas&&(this._canvas.width=e,this._canvas.height=r)}createVideoTrackSource(e,r){return new Ci(this,e,{logger:this.log,name:r})}createVideoTrackDestination(e){return new Ys(this,e)}createVideoImageSource(e,r){return new qa(this,r?Object.assign(r,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,r){return new za(this,e,r?Object.assign(r,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};l(qo,"_ids",0);var Sy={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},st=class extends qo{constructor(){super(...arguments);l(this,"defaultProgam");l(this,"defaultVShader");l(this,"defaultFShader");l(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qo._ids++}`),this.ctx=this._canvas.getContext("webgl2",Sy),!this.ctx)throw new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Ty),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,Iy),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}),this.log.info("video context created use webgl")}destroy(e){let r="";return e&&(r=e.message,this.error=e,X.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${r}`?`: ${r}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var r;(r=this.ctx)==null||r.viewport(0,0,e,this.height),super.width=e}set height(e){var r;(r=this.ctx)==null||r.viewport(0,0,this.width,e),super.height=e}setSize(e,r){var o;(o=this.ctx)==null||o.viewport(0,0,e,r),super.setSize(e,r)}createShader(e,r){let o=this.ctx,s=o.createShader(e);return o.shaderSource(s,r),o.compileShader(s),s}createProgram(e,r){let o=this.ctx,s=o.createProgram();return o.attachShader(s,e),o.attachShader(s,r),o.linkProgram(s),o.getProgramParameter(s,o.LINK_STATUS)||this.log.error(o.getProgramInfoLog(s)),s}};l(st,"UNAVAILABLE","unavailable"),q([be(Z.INIT,"created",{sync:!0,fail(i){X.addFailedEvent({key:512700,error:i.cause||i})},success(){X.addSuccessEvent({key:512700})}})],st.prototype,"create",1),q([be("created",Z.INIT,{ignoreError:!0,sync:!0,success(i){i&&this.emit(st.UNAVAILABLE,i),this.removeAllListeners()}})],st.prototype,"destroy",1);var Ct=class extends qo{constructor(){super(...arguments);l(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qo._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let r="";e&&(r=e.message,this.error=e,X.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${r?`: ${r}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),X.addSuccessEvent({key:512703})}};q([be(Z.INIT,"created",{sync:!0,fail(i){X.addFailedEvent({key:512701,error:i.cause||i})},success(){X.addSuccessEvent({key:512701})}})],Ct.prototype,"create",1),q([be("created",Z.INIT,{ignoreError:!0,sync:!0})],Ct.prototype,"destroy",1);function yy(i){return[15,30,45,60].reduce((e,r)=>Math.abs(r-i)<Math.abs(e-i)?r:e)}var Yi=class extends fr{constructor(e,r,o=4){super(e,r,o);l(this,"mediaType",4);l(this,"source");l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager}play(e,r){return(nt(r==null?void 0:r.canvasRender)?r.canvasRender:ir===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,r).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Ct({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let r=new jo(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(r),this.player.setCanvas(e._canvas),Mo()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let r=this.decodeFPS,o=yy(r);if(!Fe(r)||r<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${r} `);return}if(o===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${o} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${r}, closest: ${o}, current: ${e.frameRate}`),e.frameRate=o}get decodeFPS(){var a;let{msg_video_status:e}=((a=this.room.heartbeatReport)==null?void 0:a.msg_down_stream_info.find(d=>d.msg_user_info.str_identifier===this.userId))||{},r=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let o=e.find(d=>d.uint32_video_stream_type===r);return(o==null?void 0:o.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let r of this.manager.decodePipeline)if(!!r&&(e=r({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isAvailable(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Iu=class extends Yi{constructor(e,r){super(e,r,2);l(this,"mediaType",2);l(this,"objectFit","contain")}get isAvailable(){return this.user.muteState.hasAuxiliary}};var Zs=new Map;B.on(O.JOIN_SUCCESS,({room:i})=>{ze(i.userId,{eventId:32788})});B.on(O.LEAVE_START,({room:i})=>{ze(i.userId,{eventId:32789})});B.on(O.LOCAL_TRACK_PUBLISHED,({track:i})=>{if(i.room){let t=32769;i.mediaType===4?t=32768:i.mediaType===2&&(t=32805),ze(i.room.userId,{eventId:t})}});B.on(O.LOCAL_TRACK_UNPUBLISHED,({track:i})=>{if(i.room){let t=32771;i.mediaType===4?t=32770:i.mediaType===2&&(t=32806),ze(i.room.userId,{eventId:t})}});B.on(O.TRACK_MUTED,({track:i})=>{i.room&&(i.kind===D.AUDIO?ze(i.room.userId,{eventId:i.isRemote?32785:32772,remoteUserId:i.isRemote?i.userId:void 0}):ze(i.room.userId,{eventId:i.isRemote?32784:32773,remoteUserId:i.isRemote?i.userId:void 0}))});B.on(O.TRACK_UNMUTED,({track:i})=>{i.room&&(i.kind===D.AUDIO?ze(i.room.userId,{eventId:i.isRemote?32787:32774,remoteUserId:i.isRemote?i.userId:void 0}):ze(i.room.userId,{eventId:i.isRemote?32786:32775,remoteUserId:i.isRemote?i.userId:void 0}))});B.on(O.REMOTE_TRACK_SUBSCRIBED,({track:i})=>{!i.room||(i.mediaType===1&&ze(i.room.userId,{eventId:32777,remoteUserId:i.userId}),i.mediaType===4&&ze(i.room.userId,{eventId:32776,remoteUserId:i.userId}),i.mediaType===8&&ze(i.room.userId,{eventId:32803,remoteUserId:i.userId}))});B.on(O.REMOTE_TRACK_UNSUBSCRIBED,({track:i})=>{!i.room||(i.mediaType===1&&ze(i.room.userId,{eventId:32779,remoteUserId:i.userId}),i.mediaType===4&&ze(i.room.userId,{eventId:32778,remoteUserId:i.userId}),i.mediaType===8&&ze(i.room.userId,{eventId:32804,remoteUserId:i.userId}))});B.on(O.SWITCH_DEVICE_SUCCESS,({track:i})=>{i.room&&ze(i.room.userId,{eventId:i.kind===D.VIDEO?32780:32781})});B.on(O.LOCAL_TRACK_REPLACED,({track:i})=>{i.room&&ze(i.room.userId,{eventId:i.kind===D.VIDEO?32782:32783})});B.on(O.SIGNAL_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e})=>{let r;switch(e){case"CONNECTED":t==="RECONNECTING"?r=32795:r=32791;break;case"DISCONNECTED":t==="RECONNECTING"?r=32796:r=32790;break;case"RECONNECTING":r=32794;break}r&&ze(i.userId,{eventId:r})});B.on(O.PEER_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e,remoteUserId:r})=>{let o=!!r,s;switch(e){case"CONNECTED":t==="RECONNECTING"?s=o?32801:32798:s=o?32793:32792;break;case"DISCONNECTED":t==="RECONNECTING"&&(s=o?32802:32799);break;case"RECONNECTING":s=o?32800:32797;break}s&&ze(i.userId,{eventId:s,remoteUserId:r})});B.on(O.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:i,userId:t,remoteUserId:e,codec:r,isHWCodec:o,prevImplementation:s,streamType:a})=>{let d=o?1:0;s||(d=o?3:2);let h=r==="h264"?0:2,p={eventId:4004,param1:d,param2:h,streamType:a||2};e&&(p.remoteUserId=e,p.eventId=4005),ze(t,p),X.addEnum({key:e?514701:513701,value:d}),X.addEnum({key:e?514700:513700,value:h})});B.on(O.LOCAL_TRACK_RECAPTURE,({track:i,error:t})=>{if(i.userId){let e={eventId:2003,param1:0};i.kind===D.AUDIO?(e.streamType=1,t&&(e.param1=2)):(e.streamType=i.streamType==="auxiliary"?7:2,t&&(e.param1=8)),ze(i.userId,e)}});function ze(i,t){let e=me(J({},t),{timestamp:jn()});Zs.has(i)?Zs.get(i).push(e):Zs.set(i,[e])}function Vg(i){if(Zs.has(i)){let t=Zs.get(i).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return Zs.delete(i),t}return[]}var Ay=Pi(Hi(),1);var Di=class extends Z{initialize(){return v(this,null,function*(){this.decoder=new VideoDecoder({output:e=>{this.emit("videoFrame",e)},error:e=>{this.close(),this.emit("error",e)}})})}configure(e){this.config=e,this.decoder.configure(me(J({},e),{codec:this.getCodec(e)}))}getCodec(e){switch(e.codec){case"hevc":return"hvc1.1.6.L0.12.34.56.78.9A.BC";case"av1":return"av01.0.05M.08";case"avc":return"avc1.420028";default:return e.codec}}decode(e){this.decoder.state==="configured"&&this.decoder.decode(new EncodedVideoChunk(e))}flush(){this.decoder.flush()}reset(){this.decoder.reset()}close(){this.decoder.state!=="closed"&&this.decoder.close()}};q([be([Z.INIT,"closed"],"initialized")],Di.prototype,"initialize",1),q([be("initialized","configured",{sync:!0})],Di.prototype,"configure",1),q([Q_("configured")],Di.prototype,"decode",1),q([be([],Z.INIT)],Di.prototype,"reset",1),q([be([],"closed",{ignoreError:!0,sync:!0})],Di.prototype,"close",1);function by(){var i;self.onmessage=t=>{if(t.data.type==="init"){let{canvas:e,wasmScript:r,wasmBinary:o}=t.data,s=e==null?void 0:e.getContext("2d"),a=0,d=0,h={wasmBinary:o,postRun:()=>{i=new h.VideoDecoder({videoInfo(p,T){a=p,d=T,console.log("video info",p,T)},yuvData(p,T){let y=a*d,R=y>>2,N=h.HEAPU32[p>>2],j=h.HEAPU32[(p>>2)+1],W=h.HEAPU32[(p>>2)+2],F=h.HEAPU8.subarray(N,N+y),Ie=h.HEAPU8.subarray(j,j+R),Bt=h.HEAPU8.subarray(W,W+R),Xe=new Uint8Array(y+R+R);Xe.set(F),Xe.set(Ie,y),Xe.set(Bt,y+R);let wt=new VideoFrame(Xe,{codedWidth:a,codedHeight:d,format:"I420",timestamp:T});e?(s==null||s.drawImage(wt,0,0,e.width,e.height),s==null||s.commit()):self.postMessage({type:"yuvData",videoFrame:wt},[wt])}}),self.postMessage({type:"ready"})}};Function("var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;return "+r)()(h)}else if(t.data.type==="decode"){let{packet:e}=t.data;i==null||i.decode(e.data,e.type=="key",e.timestamp)}else if(t.data.type==="setCodec"){let{codec:e,format:r,description:o}=t.data;i==null||i.setCodec(e,r,o!=null?o:"")}}}var Qr=class extends Z{constructor(e,r,o=!1,s,a=!1){super();this.createModule=e;this.wasmBinary=r;this.workerMode=o;this.canvas=s;this.yuvMode=a;this.module={};this.width=0;this.height=0}initialize(e){return v(this,null,function*(){var o;if(this.workerMode){let s=new RegExp("\\{(.+)\\}","s").exec(by.toString())[1];this.worker=new Worker(URL.createObjectURL(new Blob([s],{type:"text/javascript"})));let a=(o=this.canvas)==null?void 0:o.transferControlToOffscreen(),d=yield this.wasmBinary;return console.warn("worker mode",d),this.worker.postMessage({type:"init",canvas:a,wasmScript:this.createModule.toString(),wasmBinary:d},a?[a,d]:[d]),new Promise(h=>{this.worker.onmessage=p=>{if(p.data.type==="ready")delete this.wasmBinary,h(),console.warn("worker mode initialize success");else if(p.data.type==="yuvData"){let{videoFrame:T}=p.data;this.emit("videoFrame",T)}}})}let r=this.module;return this.wasmBinary&&(r.wasmBinary=yield this.wasmBinary),r.print=s=>console.log(s),r.printErr=s=>console.log(`[JS] ERROR: ${s}`),r.onAbort=()=>console.log("[JS] FATAL: WASM ABORTED"),new Promise(s=>{r.postRun=a=>{this.decoder=new this.module.VideoDecoder(this),console.log("video soft decoder initialize success"),s()},e&&Object.assign(r,e),this.createModule(r)})})}configure(e){var r,o,s;this.config=e,(o=this.decoder)==null||o.setCodec(this.config.codec,this.config.description?"avcc":"annexb",(r=this.config.description)!=null?r:""),(s=this.worker)==null||s.postMessage({type:"setCodec",codec:this.config.codec,format:this.config.description?"avcc":"annexb",description:this.config.description})}decode(e){var r,o;(r=this.decoder)==null||r.decode(e.data,e.type=="key",e.timestamp),this.state==="configured"&&((o=this.worker)==null||o.postMessage({type:"decode",packet:e}))}flush(){}reset(){this.config=void 0,this.decoder&&this.decoder.clear()}close(){this.removeAllListeners(),this.decoder&&(this.decoder.clear(),this.decoder.delete())}videoInfo(e,r){this.width=e,this.height=r;let o={width:e,height:r};this.emit("videoCodecInfo",o)}yuvData(e,r){if(!this.module)return;let o=this.width*this.height,s=o>>2,a=this.module.HEAPU32[e>>2],d=this.module.HEAPU32[(e>>2)+1],h=this.module.HEAPU32[(e>>2)+2],p=this.module.HEAPU8.subarray(a,a+o),T=this.module.HEAPU8.subarray(d,d+s),y=this.module.HEAPU8.subarray(h,h+s);if(this.yuvMode){this.emit("videoFrame",[p,T,y]);return}let R=new Uint8Array(o+s+s);R.set(p),R.set(T,o),R.set(y,o+s),this.emit("videoFrame",new VideoFrame(R,{codedWidth:this.width,codedHeight:this.height,format:"I420",timestamp:r}))}errorInfo(e){let r={errMsg:e};this.emit("error",r)}};q([be([Z.INIT,"closed"],"initialized")],Qr.prototype,"initialize",1),q([be("initialized","configured")],Qr.prototype,"configure",1),q([be([],Z.INIT)],Qr.prototype,"reset",1),q([be([],"closed")],Qr.prototype,"close",1);var vy=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e=t,r,o;e.ready=new Promise((n,c)=>{r=n,o=c});var s=Object.assign({},e),a=[],d="./this.program",h=(n,c)=>{throw c},p=typeof window=="object",T=typeof importScripts=="function",y=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",R="";function N(n){return e.locateFile?e.locateFile(n,R):R+n}var j,W,F,Ie;(p||T)&&(T?R=self.location.href:typeof document!="undefined"&&document.currentScript&&(R=document.currentScript.src),i&&(R=i),R.indexOf("blob:")!==0?R=R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1):R="",j=n=>{var c=new XMLHttpRequest;return c.open("GET",n,!1),c.send(null),c.responseText},T&&(F=n=>{var c=new XMLHttpRequest;return c.open("GET",n,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),W=(n,c,u)=>{var m=new XMLHttpRequest;m.open("GET",n,!0),m.responseType="arraybuffer",m.onload=()=>{if(m.status==200||m.status==0&&m.response){c(m.response);return}u()},m.onerror=u,m.send(null)},Ie=n=>document.title=n);var Bt=e.print||console.log.bind(console),Xe=e.printErr||console.error.bind(console);Object.assign(e,s),s=null,e.arguments&&(a=e.arguments),e.thisProgram&&(d=e.thisProgram),e.quit&&(h=e.quit);var wt;e.wasmBinary&&(wt=e.wasmBinary);var fe=e.noExitRuntime||!0;typeof WebAssembly!="object"&&kr("no native wasm support detected");var hn,Ge,fn=!1,il;function ei(n,c){n||kr(c)}var Pe,tt,Yt,Zt,P,Me,_n,oc;function sc(){var n=hn.buffer;e.HEAP8=Pe=new Int8Array(n),e.HEAP16=Yt=new Int16Array(n),e.HEAP32=P=new Int32Array(n),e.HEAPU8=tt=new Uint8Array(n),e.HEAPU16=Zt=new Uint16Array(n),e.HEAPU32=Me=new Uint32Array(n),e.HEAPF32=_n=new Float32Array(n),e.HEAPF64=oc=new Float64Array(n)}var gn,En=[],Tn=[],nc=[],ol=!1;function sl(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)al(e.preRun.shift());An(En)}function z(){ol=!0,!e.noFSInit&&!g.init.initialized&&g.init(),g.ignorePermissions=!1,Lr.init(),An(Tn)}function nl(){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)ti(e.postRun.shift());An(nc)}function al(n){En.unshift(n)}function cl(n){Tn.unshift(n)}function ti(n){nc.unshift(n)}var se=0,ri=null,so=null;function Df(n){return n}function Ni(n){se++,e.monitorRunDependencies&&e.monitorRunDependencies(se)}function is(n){if(se--,e.monitorRunDependencies&&e.monitorRunDependencies(se),se==0&&(ri!==null&&(clearInterval(ri),ri=null),so)){var c=so;so=null,c()}}function kr(n){e.onAbort&&e.onAbort(n),n="Aborted("+n+")",Xe(n),fn=!0,il=1,n+=". Build with -sASSERTIONS for more info.";var c=new WebAssembly.RuntimeError(n);throw o(c),c}var wi="data:application/octet-stream;base64,";function In(n){return n.startsWith(wi)}var xi;xi="videodec.wasm",In(xi)||(xi=N(xi));function Sn(n){if(n==xi&&wt)return new Uint8Array(wt);if(F)return F(n);throw"both async and sync fetching of the wasm failed"}function dl(n){return!wt&&(p||T)&&typeof fetch=="function"?fetch(n,{credentials:"same-origin"}).then(c=>{if(!c.ok)throw"failed to load wasm binary file at '"+n+"'";return c.arrayBuffer()}).catch(()=>Sn(n)):Promise.resolve().then(()=>Sn(n))}function ac(n,c,u){return dl(n).then(m=>WebAssembly.instantiate(m,c)).then(m=>m).then(u,m=>{Xe("failed to asynchronously prepare wasm: "+m),kr(m)})}function yn(n,c,u,m){return!n&&typeof WebAssembly.instantiateStreaming=="function"&&!In(c)&&typeof fetch=="function"?fetch(c,{credentials:"same-origin"}).then(E=>{var S=WebAssembly.instantiateStreaming(E,u);return S.then(m,function(b){return Xe("wasm streaming compile failed: "+b),Xe("falling back to ArrayBuffer instantiation"),ac(c,u,m)})}):ac(c,u,m)}function w(){var n={a:$E};function c(m,E){var S=m.exports;return Ge=S,hn=Ge.E,sc(),gn=Ge.H,cl(Ge.F),is("wasm-instantiate"),S}Ni("wasm-instantiate");function u(m){c(m.instance)}if(e.instantiateWasm)try{return e.instantiateWasm(n,c)}catch(m){Xe("Module.instantiateWasm callback failed with error: "+m),o(m)}return yn(wt,xi,n,u).catch(o),{}}var ce,He,An=n=>{for(;n.length>0;)n.shift()(e)};function ul(n){this.excPtr=n,this.ptr=n-24,this.set_type=function(c){Me[this.ptr+4>>2]=c},this.get_type=function(){return Me[this.ptr+4>>2]},this.set_destructor=function(c){Me[this.ptr+8>>2]=c},this.get_destructor=function(){return Me[this.ptr+8>>2]},this.set_caught=function(c){c=c?1:0,Pe[this.ptr+12>>0]=c},this.get_caught=function(){return Pe[this.ptr+12>>0]!=0},this.set_rethrown=function(c){c=c?1:0,Pe[this.ptr+13>>0]=c},this.get_rethrown=function(){return Pe[this.ptr+13>>0]!=0},this.init=function(c,u){this.set_adjusted_ptr(0),this.set_type(c),this.set_destructor(u)},this.set_adjusted_ptr=function(c){Me[this.ptr+16>>2]=c},this.get_adjusted_ptr=function(){return Me[this.ptr+16>>2]},this.get_exception_ptr=function(){var c=Of(this.get_type());if(c)return Me[this.excPtr>>2];var u=this.get_adjusted_ptr();return u!==0?u:this.excPtr}}var os=0,ll=0;function cc(n,c,u){var m=new ul(n);throw m.init(c,u),os=n,ll++,os}var xt=n=>(P[xf()>>2]=n,n),De={isAbs:n=>n.charAt(0)==="/",splitPath:n=>{var c=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return c.exec(n).slice(1)},normalizeArray:(n,c)=>{for(var u=0,m=n.length-1;m>=0;m--){var E=n[m];E==="."?n.splice(m,1):E===".."?(n.splice(m,1),u++):u&&(n.splice(m,1),u--)}if(c)for(;u;u--)n.unshift("..");return n},normalize:n=>{var c=De.isAbs(n),u=n.substr(-1)==="/";return n=De.normalizeArray(n.split("/").filter(m=>!!m),!c).join("/"),!n&&!c&&(n="."),n&&u&&(n+="/"),(c?"/":"")+n},dirname:n=>{var c=De.splitPath(n),u=c[0],m=c[1];return!u&&!m?".":(m&&(m=m.substr(0,m.length-1)),u+m)},basename:n=>{if(n==="/")return"/";n=De.normalize(n),n=n.replace(/\/$/,"");var c=n.lastIndexOf("/");return c===-1?n:n.substr(c+1)},join:function(){var n=Array.prototype.slice.call(arguments);return De.normalize(n.join("/"))},join2:(n,c)=>De.normalize(n+"/"+c)},ii=()=>{if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function")return n=>crypto.getRandomValues(n);kr("initRandomDevice")},no=n=>(no=ii())(n),At={resolve:function(){for(var n="",c=!1,u=arguments.length-1;u>=-1&&!c;u--){var m=u>=0?arguments[u]:g.cwd();if(typeof m!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!m)return"";n=m+"/"+n,c=De.isAbs(m)}return n=De.normalizeArray(n.split("/").filter(E=>!!E),!c).join("/"),(c?"/":"")+n||"."},relative:(n,c)=>{n=At.resolve(n).substr(1),c=At.resolve(c).substr(1);function u(x){for(var K=0;K<x.length&&x[K]==="";K++);for(var ie=x.length-1;ie>=0&&x[ie]==="";ie--);return K>ie?[]:x.slice(K,ie-K+1)}for(var m=u(n.split("/")),E=u(c.split("/")),S=Math.min(m.length,E.length),b=S,A=0;A<S;A++)if(m[A]!==E[A]){b=A;break}for(var k=[],A=b;A<m.length;A++)k.push("..");return k=k.concat(E.slice(b)),k.join("/")}},Ne=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,oi=(n,c,u)=>{for(var m=c+u,E=c;n[E]&&!(E>=m);)++E;if(E-c>16&&n.buffer&&Ne)return Ne.decode(n.subarray(c,E));for(var S="";c<E;){var b=n[c++];if(!(b&128)){S+=String.fromCharCode(b);continue}var A=n[c++]&63;if((b&224)==192){S+=String.fromCharCode((b&31)<<6|A);continue}var k=n[c++]&63;if((b&240)==224?b=(b&15)<<12|A<<6|k:b=(b&7)<<18|A<<12|k<<6|n[c++]&63,b<65536)S+=String.fromCharCode(b);else{var x=b-65536;S+=String.fromCharCode(55296|x>>10,56320|x&1023)}}return S},Mi=[],si=n=>{for(var c=0,u=0;u<n.length;++u){var m=n.charCodeAt(u);m<=127?c++:m<=2047?c+=2:m>=55296&&m<=57343?(c+=4,++u):c+=3}return c},bn=(n,c,u,m)=>{if(!(m>0))return 0;for(var E=u,S=u+m-1,b=0;b<n.length;++b){var A=n.charCodeAt(b);if(A>=55296&&A<=57343){var k=n.charCodeAt(++b);A=65536+((A&1023)<<10)|k&1023}if(A<=127){if(u>=S)break;c[u++]=A}else if(A<=2047){if(u+1>=S)break;c[u++]=192|A>>6,c[u++]=128|A&63}else if(A<=65535){if(u+2>=S)break;c[u++]=224|A>>12,c[u++]=128|A>>6&63,c[u++]=128|A&63}else{if(u+3>=S)break;c[u++]=240|A>>18,c[u++]=128|A>>12&63,c[u++]=128|A>>6&63,c[u++]=128|A&63}}return c[u]=0,u-E};function Kt(n,c,u){var m=u>0?u:si(n)+1,E=new Array(m),S=bn(n,E,0,E.length);return c&&(E.length=S),E}var pl=()=>{if(!Mi.length){var n=null;if(typeof window!="undefined"&&typeof window.prompt=="function"?(n=window.prompt("Input: "),n!==null&&(n+=`
|
|
47
|
+
} `;var qo=class extends Z{constructor(e){super();l(this,"frameRate");l(this,"_canvas");l(this,"log");l(this,"hasAlpha",!1);l(this,"name");l(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,r){this._canvas&&(this._canvas.width=e,this._canvas.height=r)}createVideoTrackSource(e,r){return new Ci(this,e,{logger:this.log,name:r})}createVideoTrackDestination(e){return new Ys(this,e)}createVideoImageSource(e,r){return new za(this,r?Object.assign(r,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,r){return new Ja(this,e,r?Object.assign(r,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};l(qo,"_ids",0);var Sy={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},st=class extends qo{constructor(){super(...arguments);l(this,"defaultProgam");l(this,"defaultVShader");l(this,"defaultFShader");l(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qo._ids++}`),this.ctx=this._canvas.getContext("webgl2",Sy),!this.ctx)throw new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Ty),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,Iy),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}),this.log.info("video context created use webgl")}destroy(e){let r="";return e&&(r=e.message,this.error=e,X.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${r}`?`: ${r}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var r;(r=this.ctx)==null||r.viewport(0,0,e,this.height),super.width=e}set height(e){var r;(r=this.ctx)==null||r.viewport(0,0,this.width,e),super.height=e}setSize(e,r){var o;(o=this.ctx)==null||o.viewport(0,0,e,r),super.setSize(e,r)}createShader(e,r){let o=this.ctx,s=o.createShader(e);return o.shaderSource(s,r),o.compileShader(s),s}createProgram(e,r){let o=this.ctx,s=o.createProgram();return o.attachShader(s,e),o.attachShader(s,r),o.linkProgram(s),o.getProgramParameter(s,o.LINK_STATUS)||this.log.error(o.getProgramInfoLog(s)),s}};l(st,"UNAVAILABLE","unavailable"),q([be(Z.INIT,"created",{sync:!0,fail(i){X.addFailedEvent({key:512700,error:i.cause||i})},success(){X.addSuccessEvent({key:512700})}})],st.prototype,"create",1),q([be("created",Z.INIT,{ignoreError:!0,sync:!0,success(i){i&&this.emit(st.UNAVAILABLE,i),this.removeAllListeners()}})],st.prototype,"destroy",1);var Ct=class extends qo{constructor(){super(...arguments);l(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qo._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let r="";e&&(r=e.message,this.error=e,X.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${r?`: ${r}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),X.addSuccessEvent({key:512703})}};q([be(Z.INIT,"created",{sync:!0,fail(i){X.addFailedEvent({key:512701,error:i.cause||i})},success(){X.addSuccessEvent({key:512701})}})],Ct.prototype,"create",1),q([be("created",Z.INIT,{ignoreError:!0,sync:!0})],Ct.prototype,"destroy",1);function yy(i){return[15,30,45,60].reduce((e,r)=>Math.abs(r-i)<Math.abs(e-i)?r:e)}var Yi=class extends fr{constructor(e,r,o=4){super(e,r,o);l(this,"mediaType",4);l(this,"source");l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager}play(e,r){return(nt(r==null?void 0:r.canvasRender)?r.canvasRender:ir===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,r).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Ct({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let r=new jo(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(r),this.player.setCanvas(e._canvas),Mo()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let r=this.decodeFPS,o=yy(r);if(!Fe(r)||r<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${r} `);return}if(o===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${o} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${r}, closest: ${o}, current: ${e.frameRate}`),e.frameRate=o}get decodeFPS(){var a;let{msg_video_status:e}=((a=this.room.heartbeatReport)==null?void 0:a.msg_down_stream_info.find(d=>d.msg_user_info.str_identifier===this.userId))||{},r=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let o=e.find(d=>d.uint32_video_stream_type===r);return(o==null?void 0:o.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let r of this.manager.decodePipeline)if(!!r&&(e=r({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isAvailable(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Iu=class extends Yi{constructor(e,r){super(e,r,2);l(this,"mediaType",2);l(this,"objectFit","contain")}get isAvailable(){return this.user.muteState.hasAuxiliary}};var Zs=new Map;B.on(O.JOIN_SUCCESS,({room:i})=>{ze(i.userId,{eventId:32788})});B.on(O.LEAVE_START,({room:i})=>{ze(i.userId,{eventId:32789})});B.on(O.LOCAL_TRACK_PUBLISHED,({track:i})=>{if(i.room){let t=32769;i.mediaType===4?t=32768:i.mediaType===2&&(t=32805),ze(i.room.userId,{eventId:t})}});B.on(O.LOCAL_TRACK_UNPUBLISHED,({track:i})=>{if(i.room){let t=32771;i.mediaType===4?t=32770:i.mediaType===2&&(t=32806),ze(i.room.userId,{eventId:t})}});B.on(O.TRACK_MUTED,({track:i})=>{i.room&&(i.kind===D.AUDIO?ze(i.room.userId,{eventId:i.isRemote?32785:32772,remoteUserId:i.isRemote?i.userId:void 0}):ze(i.room.userId,{eventId:i.isRemote?32784:32773,remoteUserId:i.isRemote?i.userId:void 0}))});B.on(O.TRACK_UNMUTED,({track:i})=>{i.room&&(i.kind===D.AUDIO?ze(i.room.userId,{eventId:i.isRemote?32787:32774,remoteUserId:i.isRemote?i.userId:void 0}):ze(i.room.userId,{eventId:i.isRemote?32786:32775,remoteUserId:i.isRemote?i.userId:void 0}))});B.on(O.REMOTE_TRACK_SUBSCRIBED,({track:i})=>{!i.room||(i.mediaType===1&&ze(i.room.userId,{eventId:32777,remoteUserId:i.userId}),i.mediaType===4&&ze(i.room.userId,{eventId:32776,remoteUserId:i.userId}),i.mediaType===8&&ze(i.room.userId,{eventId:32803,remoteUserId:i.userId}))});B.on(O.REMOTE_TRACK_UNSUBSCRIBED,({track:i})=>{!i.room||(i.mediaType===1&&ze(i.room.userId,{eventId:32779,remoteUserId:i.userId}),i.mediaType===4&&ze(i.room.userId,{eventId:32778,remoteUserId:i.userId}),i.mediaType===8&&ze(i.room.userId,{eventId:32804,remoteUserId:i.userId}))});B.on(O.SWITCH_DEVICE_SUCCESS,({track:i})=>{i.room&&ze(i.room.userId,{eventId:i.kind===D.VIDEO?32780:32781})});B.on(O.LOCAL_TRACK_REPLACED,({track:i})=>{i.room&&ze(i.room.userId,{eventId:i.kind===D.VIDEO?32782:32783})});B.on(O.SIGNAL_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e})=>{let r;switch(e){case"CONNECTED":t==="RECONNECTING"?r=32795:r=32791;break;case"DISCONNECTED":t==="RECONNECTING"?r=32796:r=32790;break;case"RECONNECTING":r=32794;break}r&&ze(i.userId,{eventId:r})});B.on(O.PEER_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e,remoteUserId:r})=>{let o=!!r,s;switch(e){case"CONNECTED":t==="RECONNECTING"?s=o?32801:32798:s=o?32793:32792;break;case"DISCONNECTED":t==="RECONNECTING"&&(s=o?32802:32799);break;case"RECONNECTING":s=o?32800:32797;break}s&&ze(i.userId,{eventId:s,remoteUserId:r})});B.on(O.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:i,userId:t,remoteUserId:e,codec:r,isHWCodec:o,prevImplementation:s,streamType:a})=>{let d=o?1:0;s||(d=o?3:2);let h=r==="h264"?0:2,p={eventId:4004,param1:d,param2:h,streamType:a||2};e&&(p.remoteUserId=e,p.eventId=4005),ze(t,p),X.addEnum({key:e?514701:513701,value:d}),X.addEnum({key:e?514700:513700,value:h})});B.on(O.LOCAL_TRACK_RECAPTURE,({track:i,error:t})=>{if(i.userId){let e={eventId:2003,param1:0};i.kind===D.AUDIO?(e.streamType=1,t&&(e.param1=2)):(e.streamType=i.streamType==="auxiliary"?7:2,t&&(e.param1=8)),ze(i.userId,e)}});function ze(i,t){let e=me(J({},t),{timestamp:qn()});Zs.has(i)?Zs.get(i).push(e):Zs.set(i,[e])}function Vg(i){if(Zs.has(i)){let t=Zs.get(i).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return Zs.delete(i),t}return[]}var Ay=Pi(Hi(),1);var Di=class extends Z{initialize(){return v(this,null,function*(){this.decoder=new VideoDecoder({output:e=>{this.emit("videoFrame",e)},error:e=>{this.close(),this.emit("error",e)}})})}configure(e){this.config=e,this.decoder.configure(me(J({},e),{codec:this.getCodec(e)}))}getCodec(e){switch(e.codec){case"hevc":return"hvc1.1.6.L0.12.34.56.78.9A.BC";case"av1":return"av01.0.05M.08";case"avc":return"avc1.420028";default:return e.codec}}decode(e){this.decoder.state==="configured"&&this.decoder.decode(new EncodedVideoChunk(e))}flush(){this.decoder.flush()}reset(){this.decoder.reset()}close(){this.decoder.state!=="closed"&&this.decoder.close()}};q([be([Z.INIT,"closed"],"initialized")],Di.prototype,"initialize",1),q([be("initialized","configured",{sync:!0})],Di.prototype,"configure",1),q([Q_("configured")],Di.prototype,"decode",1),q([be([],Z.INIT)],Di.prototype,"reset",1),q([be([],"closed",{ignoreError:!0,sync:!0})],Di.prototype,"close",1);function by(){var i;self.onmessage=t=>{if(t.data.type==="init"){let{canvas:e,wasmScript:r,wasmBinary:o}=t.data,s=e==null?void 0:e.getContext("2d"),a=0,d=0,h={wasmBinary:o,postRun:()=>{i=new h.VideoDecoder({videoInfo(p,T){a=p,d=T,console.log("video info",p,T)},yuvData(p,T){let y=a*d,R=y>>2,N=h.HEAPU32[p>>2],j=h.HEAPU32[(p>>2)+1],W=h.HEAPU32[(p>>2)+2],F=h.HEAPU8.subarray(N,N+y),Ie=h.HEAPU8.subarray(j,j+R),Bt=h.HEAPU8.subarray(W,W+R),Xe=new Uint8Array(y+R+R);Xe.set(F),Xe.set(Ie,y),Xe.set(Bt,y+R);let wt=new VideoFrame(Xe,{codedWidth:a,codedHeight:d,format:"I420",timestamp:T});e?(s==null||s.drawImage(wt,0,0,e.width,e.height),s==null||s.commit()):self.postMessage({type:"yuvData",videoFrame:wt},[wt])}}),self.postMessage({type:"ready"})}};Function("var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;return "+r)()(h)}else if(t.data.type==="decode"){let{packet:e}=t.data;i==null||i.decode(e.data,e.type=="key",e.timestamp)}else if(t.data.type==="setCodec"){let{codec:e,format:r,description:o}=t.data;i==null||i.setCodec(e,r,o!=null?o:"")}}}var Qr=class extends Z{constructor(e,r,o=!1,s,a=!1){super();this.createModule=e;this.wasmBinary=r;this.workerMode=o;this.canvas=s;this.yuvMode=a;this.module={};this.width=0;this.height=0}initialize(e){return v(this,null,function*(){var o;if(this.workerMode){let s=new RegExp("\\{(.+)\\}","s").exec(by.toString())[1];this.worker=new Worker(URL.createObjectURL(new Blob([s],{type:"text/javascript"})));let a=(o=this.canvas)==null?void 0:o.transferControlToOffscreen(),d=yield this.wasmBinary;return console.warn("worker mode",d),this.worker.postMessage({type:"init",canvas:a,wasmScript:this.createModule.toString(),wasmBinary:d},a?[a,d]:[d]),new Promise(h=>{this.worker.onmessage=p=>{if(p.data.type==="ready")delete this.wasmBinary,h(),console.warn("worker mode initialize success");else if(p.data.type==="yuvData"){let{videoFrame:T}=p.data;this.emit("videoFrame",T)}}})}let r=this.module;return this.wasmBinary&&(r.wasmBinary=yield this.wasmBinary),r.print=s=>console.log(s),r.printErr=s=>console.log(`[JS] ERROR: ${s}`),r.onAbort=()=>console.log("[JS] FATAL: WASM ABORTED"),new Promise(s=>{r.postRun=a=>{this.decoder=new this.module.VideoDecoder(this),console.log("video soft decoder initialize success"),s()},e&&Object.assign(r,e),this.createModule(r)})})}configure(e){var r,o,s;this.config=e,(o=this.decoder)==null||o.setCodec(this.config.codec,this.config.description?"avcc":"annexb",(r=this.config.description)!=null?r:""),(s=this.worker)==null||s.postMessage({type:"setCodec",codec:this.config.codec,format:this.config.description?"avcc":"annexb",description:this.config.description})}decode(e){var r,o;(r=this.decoder)==null||r.decode(e.data,e.type=="key",e.timestamp),this.state==="configured"&&((o=this.worker)==null||o.postMessage({type:"decode",packet:e}))}flush(){}reset(){this.config=void 0,this.decoder&&this.decoder.clear()}close(){this.removeAllListeners(),this.decoder&&(this.decoder.clear(),this.decoder.delete())}videoInfo(e,r){this.width=e,this.height=r;let o={width:e,height:r};this.emit("videoCodecInfo",o)}yuvData(e,r){if(!this.module)return;let o=this.width*this.height,s=o>>2,a=this.module.HEAPU32[e>>2],d=this.module.HEAPU32[(e>>2)+1],h=this.module.HEAPU32[(e>>2)+2],p=this.module.HEAPU8.subarray(a,a+o),T=this.module.HEAPU8.subarray(d,d+s),y=this.module.HEAPU8.subarray(h,h+s);if(this.yuvMode){this.emit("videoFrame",[p,T,y]);return}let R=new Uint8Array(o+s+s);R.set(p),R.set(T,o),R.set(y,o+s),this.emit("videoFrame",new VideoFrame(R,{codedWidth:this.width,codedHeight:this.height,format:"I420",timestamp:r}))}errorInfo(e){let r={errMsg:e};this.emit("error",r)}};q([be([Z.INIT,"closed"],"initialized")],Qr.prototype,"initialize",1),q([be("initialized","configured")],Qr.prototype,"configure",1),q([be([],Z.INIT)],Qr.prototype,"reset",1),q([be([],"closed")],Qr.prototype,"close",1);var vy=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e=t,r,o;e.ready=new Promise((n,c)=>{r=n,o=c});var s=Object.assign({},e),a=[],d="./this.program",h=(n,c)=>{throw c},p=typeof window=="object",T=typeof importScripts=="function",y=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",R="";function N(n){return e.locateFile?e.locateFile(n,R):R+n}var j,W,F,Ie;(p||T)&&(T?R=self.location.href:typeof document!="undefined"&&document.currentScript&&(R=document.currentScript.src),i&&(R=i),R.indexOf("blob:")!==0?R=R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1):R="",j=n=>{var c=new XMLHttpRequest;return c.open("GET",n,!1),c.send(null),c.responseText},T&&(F=n=>{var c=new XMLHttpRequest;return c.open("GET",n,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),W=(n,c,u)=>{var m=new XMLHttpRequest;m.open("GET",n,!0),m.responseType="arraybuffer",m.onload=()=>{if(m.status==200||m.status==0&&m.response){c(m.response);return}u()},m.onerror=u,m.send(null)},Ie=n=>document.title=n);var Bt=e.print||console.log.bind(console),Xe=e.printErr||console.error.bind(console);Object.assign(e,s),s=null,e.arguments&&(a=e.arguments),e.thisProgram&&(d=e.thisProgram),e.quit&&(h=e.quit);var wt;e.wasmBinary&&(wt=e.wasmBinary);var fe=e.noExitRuntime||!0;typeof WebAssembly!="object"&&kr("no native wasm support detected");var fn,Ge,_n=!1,il;function ei(n,c){n||kr(c)}var Pe,tt,Yt,Zt,P,Me,gn,oc;function sc(){var n=fn.buffer;e.HEAP8=Pe=new Int8Array(n),e.HEAP16=Yt=new Int16Array(n),e.HEAP32=P=new Int32Array(n),e.HEAPU8=tt=new Uint8Array(n),e.HEAPU16=Zt=new Uint16Array(n),e.HEAPU32=Me=new Uint32Array(n),e.HEAPF32=gn=new Float32Array(n),e.HEAPF64=oc=new Float64Array(n)}var En,Tn=[],In=[],nc=[],ol=!1;function sl(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)al(e.preRun.shift());bn(Tn)}function z(){ol=!0,!e.noFSInit&&!g.init.initialized&&g.init(),g.ignorePermissions=!1,Lr.init(),bn(In)}function nl(){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)ti(e.postRun.shift());bn(nc)}function al(n){Tn.unshift(n)}function cl(n){In.unshift(n)}function ti(n){nc.unshift(n)}var se=0,ri=null,so=null;function Df(n){return n}function Ni(n){se++,e.monitorRunDependencies&&e.monitorRunDependencies(se)}function is(n){if(se--,e.monitorRunDependencies&&e.monitorRunDependencies(se),se==0&&(ri!==null&&(clearInterval(ri),ri=null),so)){var c=so;so=null,c()}}function kr(n){e.onAbort&&e.onAbort(n),n="Aborted("+n+")",Xe(n),_n=!0,il=1,n+=". Build with -sASSERTIONS for more info.";var c=new WebAssembly.RuntimeError(n);throw o(c),c}var wi="data:application/octet-stream;base64,";function Sn(n){return n.startsWith(wi)}var xi;xi="videodec.wasm",Sn(xi)||(xi=N(xi));function yn(n){if(n==xi&&wt)return new Uint8Array(wt);if(F)return F(n);throw"both async and sync fetching of the wasm failed"}function dl(n){return!wt&&(p||T)&&typeof fetch=="function"?fetch(n,{credentials:"same-origin"}).then(c=>{if(!c.ok)throw"failed to load wasm binary file at '"+n+"'";return c.arrayBuffer()}).catch(()=>yn(n)):Promise.resolve().then(()=>yn(n))}function ac(n,c,u){return dl(n).then(m=>WebAssembly.instantiate(m,c)).then(m=>m).then(u,m=>{Xe("failed to asynchronously prepare wasm: "+m),kr(m)})}function An(n,c,u,m){return!n&&typeof WebAssembly.instantiateStreaming=="function"&&!Sn(c)&&typeof fetch=="function"?fetch(c,{credentials:"same-origin"}).then(E=>{var S=WebAssembly.instantiateStreaming(E,u);return S.then(m,function(b){return Xe("wasm streaming compile failed: "+b),Xe("falling back to ArrayBuffer instantiation"),ac(c,u,m)})}):ac(c,u,m)}function w(){var n={a:$E};function c(m,E){var S=m.exports;return Ge=S,fn=Ge.E,sc(),En=Ge.H,cl(Ge.F),is("wasm-instantiate"),S}Ni("wasm-instantiate");function u(m){c(m.instance)}if(e.instantiateWasm)try{return e.instantiateWasm(n,c)}catch(m){Xe("Module.instantiateWasm callback failed with error: "+m),o(m)}return An(wt,xi,n,u).catch(o),{}}var ce,He,bn=n=>{for(;n.length>0;)n.shift()(e)};function ul(n){this.excPtr=n,this.ptr=n-24,this.set_type=function(c){Me[this.ptr+4>>2]=c},this.get_type=function(){return Me[this.ptr+4>>2]},this.set_destructor=function(c){Me[this.ptr+8>>2]=c},this.get_destructor=function(){return Me[this.ptr+8>>2]},this.set_caught=function(c){c=c?1:0,Pe[this.ptr+12>>0]=c},this.get_caught=function(){return Pe[this.ptr+12>>0]!=0},this.set_rethrown=function(c){c=c?1:0,Pe[this.ptr+13>>0]=c},this.get_rethrown=function(){return Pe[this.ptr+13>>0]!=0},this.init=function(c,u){this.set_adjusted_ptr(0),this.set_type(c),this.set_destructor(u)},this.set_adjusted_ptr=function(c){Me[this.ptr+16>>2]=c},this.get_adjusted_ptr=function(){return Me[this.ptr+16>>2]},this.get_exception_ptr=function(){var c=Of(this.get_type());if(c)return Me[this.excPtr>>2];var u=this.get_adjusted_ptr();return u!==0?u:this.excPtr}}var os=0,ll=0;function cc(n,c,u){var m=new ul(n);throw m.init(c,u),os=n,ll++,os}var xt=n=>(P[xf()>>2]=n,n),De={isAbs:n=>n.charAt(0)==="/",splitPath:n=>{var c=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return c.exec(n).slice(1)},normalizeArray:(n,c)=>{for(var u=0,m=n.length-1;m>=0;m--){var E=n[m];E==="."?n.splice(m,1):E===".."?(n.splice(m,1),u++):u&&(n.splice(m,1),u--)}if(c)for(;u;u--)n.unshift("..");return n},normalize:n=>{var c=De.isAbs(n),u=n.substr(-1)==="/";return n=De.normalizeArray(n.split("/").filter(m=>!!m),!c).join("/"),!n&&!c&&(n="."),n&&u&&(n+="/"),(c?"/":"")+n},dirname:n=>{var c=De.splitPath(n),u=c[0],m=c[1];return!u&&!m?".":(m&&(m=m.substr(0,m.length-1)),u+m)},basename:n=>{if(n==="/")return"/";n=De.normalize(n),n=n.replace(/\/$/,"");var c=n.lastIndexOf("/");return c===-1?n:n.substr(c+1)},join:function(){var n=Array.prototype.slice.call(arguments);return De.normalize(n.join("/"))},join2:(n,c)=>De.normalize(n+"/"+c)},ii=()=>{if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function")return n=>crypto.getRandomValues(n);kr("initRandomDevice")},no=n=>(no=ii())(n),At={resolve:function(){for(var n="",c=!1,u=arguments.length-1;u>=-1&&!c;u--){var m=u>=0?arguments[u]:g.cwd();if(typeof m!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!m)return"";n=m+"/"+n,c=De.isAbs(m)}return n=De.normalizeArray(n.split("/").filter(E=>!!E),!c).join("/"),(c?"/":"")+n||"."},relative:(n,c)=>{n=At.resolve(n).substr(1),c=At.resolve(c).substr(1);function u(x){for(var K=0;K<x.length&&x[K]==="";K++);for(var ie=x.length-1;ie>=0&&x[ie]==="";ie--);return K>ie?[]:x.slice(K,ie-K+1)}for(var m=u(n.split("/")),E=u(c.split("/")),S=Math.min(m.length,E.length),b=S,A=0;A<S;A++)if(m[A]!==E[A]){b=A;break}for(var k=[],A=b;A<m.length;A++)k.push("..");return k=k.concat(E.slice(b)),k.join("/")}},Ne=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,oi=(n,c,u)=>{for(var m=c+u,E=c;n[E]&&!(E>=m);)++E;if(E-c>16&&n.buffer&&Ne)return Ne.decode(n.subarray(c,E));for(var S="";c<E;){var b=n[c++];if(!(b&128)){S+=String.fromCharCode(b);continue}var A=n[c++]&63;if((b&224)==192){S+=String.fromCharCode((b&31)<<6|A);continue}var k=n[c++]&63;if((b&240)==224?b=(b&15)<<12|A<<6|k:b=(b&7)<<18|A<<12|k<<6|n[c++]&63,b<65536)S+=String.fromCharCode(b);else{var x=b-65536;S+=String.fromCharCode(55296|x>>10,56320|x&1023)}}return S},Mi=[],si=n=>{for(var c=0,u=0;u<n.length;++u){var m=n.charCodeAt(u);m<=127?c++:m<=2047?c+=2:m>=55296&&m<=57343?(c+=4,++u):c+=3}return c},vn=(n,c,u,m)=>{if(!(m>0))return 0;for(var E=u,S=u+m-1,b=0;b<n.length;++b){var A=n.charCodeAt(b);if(A>=55296&&A<=57343){var k=n.charCodeAt(++b);A=65536+((A&1023)<<10)|k&1023}if(A<=127){if(u>=S)break;c[u++]=A}else if(A<=2047){if(u+1>=S)break;c[u++]=192|A>>6,c[u++]=128|A&63}else if(A<=65535){if(u+2>=S)break;c[u++]=224|A>>12,c[u++]=128|A>>6&63,c[u++]=128|A&63}else{if(u+3>=S)break;c[u++]=240|A>>18,c[u++]=128|A>>12&63,c[u++]=128|A>>6&63,c[u++]=128|A&63}}return c[u]=0,u-E};function Kt(n,c,u){var m=u>0?u:si(n)+1,E=new Array(m),S=vn(n,E,0,E.length);return c&&(E.length=S),E}var pl=()=>{if(!Mi.length){var n=null;if(typeof window!="undefined"&&typeof window.prompt=="function"?(n=window.prompt("Input: "),n!==null&&(n+=`
|
|
48
48
|
`)):typeof readline=="function"&&(n=readline(),n!==null&&(n+=`
|
|
49
|
-
`)),!n)return null;Mi=Kt(n,!0)}return Mi.shift()},Lr={ttys:[],init:function(){},shutdown:function(){},register:function(n,c){Lr.ttys[n]={input:[],output:[],ops:c},g.registerDevice(n,Lr.stream_ops)},stream_ops:{open:function(n){var c=Lr.ttys[n.node.rdev];if(!c)throw new g.ErrnoError(43);n.tty=c,n.seekable=!1},close:function(n){n.tty.ops.fsync(n.tty)},fsync:function(n){n.tty.ops.fsync(n.tty)},read:function(n,c,u,m,E){if(!n.tty||!n.tty.ops.get_char)throw new g.ErrnoError(60);for(var S=0,b=0;b<m;b++){var A;try{A=n.tty.ops.get_char(n.tty)}catch(k){throw new g.ErrnoError(29)}if(A===void 0&&S===0)throw new g.ErrnoError(6);if(A==null)break;S++,c[u+b]=A}return S&&(n.node.timestamp=Date.now()),S},write:function(n,c,u,m,E){if(!n.tty||!n.tty.ops.put_char)throw new g.ErrnoError(60);try{for(var S=0;S<m;S++)n.tty.ops.put_char(n.tty,c[u+S])}catch(b){throw new g.ErrnoError(29)}return m&&(n.node.timestamp=Date.now()),S}},default_tty_ops:{get_char:function(n){return pl()},put_char:function(n,c){c===null||c===10?(Bt(oi(n.output,0)),n.output=[]):c!=0&&n.output.push(c)},fsync:function(n){n.output&&n.output.length>0&&(Bt(oi(n.output,0)),n.output=[])},ioctl_tcgets:function(n){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(n,c,u){return 0},ioctl_tiocgwinsz:function(n){return[24,80]}},default_tty1_ops:{put_char:function(n,c){c===null||c===10?(Xe(oi(n.output,0)),n.output=[]):c!=0&&n.output.push(c)},fsync:function(n){n.output&&n.output.length>0&&(Xe(oi(n.output,0)),n.output=[])}}},dc=n=>{kr()},he={ops_table:null,mount(n){return he.createNode(null,"/",16895,0)},createNode(n,c,u,m){if(g.isBlkdev(u)||g.isFIFO(u))throw new g.ErrnoError(63);he.ops_table||(he.ops_table={dir:{node:{getattr:he.node_ops.getattr,setattr:he.node_ops.setattr,lookup:he.node_ops.lookup,mknod:he.node_ops.mknod,rename:he.node_ops.rename,unlink:he.node_ops.unlink,rmdir:he.node_ops.rmdir,readdir:he.node_ops.readdir,symlink:he.node_ops.symlink},stream:{llseek:he.stream_ops.llseek}},file:{node:{getattr:he.node_ops.getattr,setattr:he.node_ops.setattr},stream:{llseek:he.stream_ops.llseek,read:he.stream_ops.read,write:he.stream_ops.write,allocate:he.stream_ops.allocate,mmap:he.stream_ops.mmap,msync:he.stream_ops.msync}},link:{node:{getattr:he.node_ops.getattr,setattr:he.node_ops.setattr,readlink:he.node_ops.readlink},stream:{}},chrdev:{node:{getattr:he.node_ops.getattr,setattr:he.node_ops.setattr},stream:g.chrdev_stream_ops}});var E=g.createNode(n,c,u,m);return g.isDir(E.mode)?(E.node_ops=he.ops_table.dir.node,E.stream_ops=he.ops_table.dir.stream,E.contents={}):g.isFile(E.mode)?(E.node_ops=he.ops_table.file.node,E.stream_ops=he.ops_table.file.stream,E.usedBytes=0,E.contents=null):g.isLink(E.mode)?(E.node_ops=he.ops_table.link.node,E.stream_ops=he.ops_table.link.stream):g.isChrdev(E.mode)&&(E.node_ops=he.ops_table.chrdev.node,E.stream_ops=he.ops_table.chrdev.stream),E.timestamp=Date.now(),n&&(n.contents[c]=E,n.timestamp=E.timestamp),E},getFileDataAsTypedArray(n){return n.contents?n.contents.subarray?n.contents.subarray(0,n.usedBytes):new Uint8Array(n.contents):new Uint8Array(0)},expandFileStorage(n,c){var u=n.contents?n.contents.length:0;if(!(u>=c)){var m=1024*1024;c=Math.max(c,u*(u<m?2:1.125)>>>0),u!=0&&(c=Math.max(c,256));var E=n.contents;n.contents=new Uint8Array(c),n.usedBytes>0&&n.contents.set(E.subarray(0,n.usedBytes),0)}},resizeFileStorage(n,c){if(n.usedBytes!=c)if(c==0)n.contents=null,n.usedBytes=0;else{var u=n.contents;n.contents=new Uint8Array(c),u&&n.contents.set(u.subarray(0,Math.min(c,n.usedBytes))),n.usedBytes=c}},node_ops:{getattr(n){var c={};return c.dev=g.isChrdev(n.mode)?n.id:1,c.ino=n.id,c.mode=n.mode,c.nlink=1,c.uid=0,c.gid=0,c.rdev=n.rdev,g.isDir(n.mode)?c.size=4096:g.isFile(n.mode)?c.size=n.usedBytes:g.isLink(n.mode)?c.size=n.link.length:c.size=0,c.atime=new Date(n.timestamp),c.mtime=new Date(n.timestamp),c.ctime=new Date(n.timestamp),c.blksize=4096,c.blocks=Math.ceil(c.size/c.blksize),c},setattr(n,c){c.mode!==void 0&&(n.mode=c.mode),c.timestamp!==void 0&&(n.timestamp=c.timestamp),c.size!==void 0&&he.resizeFileStorage(n,c.size)},lookup(n,c){throw g.genericErrors[44]},mknod(n,c,u,m){return he.createNode(n,c,u,m)},rename(n,c,u){if(g.isDir(n.mode)){var m;try{m=g.lookupNode(c,u)}catch(S){}if(m)for(var E in m.contents)throw new g.ErrnoError(55)}delete n.parent.contents[n.name],n.parent.timestamp=Date.now(),n.name=u,c.contents[u]=n,c.timestamp=n.parent.timestamp,n.parent=c},unlink(n,c){delete n.contents[c],n.timestamp=Date.now()},rmdir(n,c){var u=g.lookupNode(n,c);for(var m in u.contents)throw new g.ErrnoError(55);delete n.contents[c],n.timestamp=Date.now()},readdir(n){var c=[".",".."];for(var u in n.contents)!n.contents.hasOwnProperty(u)||c.push(u);return c},symlink(n,c,u){var m=he.createNode(n,c,41471,0);return m.link=u,m},readlink(n){if(!g.isLink(n.mode))throw new g.ErrnoError(28);return n.link}},stream_ops:{read(n,c,u,m,E){var S=n.node.contents;if(E>=n.node.usedBytes)return 0;var b=Math.min(n.node.usedBytes-E,m);if(b>8&&S.subarray)c.set(S.subarray(E,E+b),u);else for(var A=0;A<b;A++)c[u+A]=S[E+A];return b},write(n,c,u,m,E,S){if(!m)return 0;var b=n.node;if(b.timestamp=Date.now(),c.subarray&&(!b.contents||b.contents.subarray)){if(S)return b.contents=c.subarray(u,u+m),b.usedBytes=m,m;if(b.usedBytes===0&&E===0)return b.contents=c.slice(u,u+m),b.usedBytes=m,m;if(E+m<=b.usedBytes)return b.contents.set(c.subarray(u,u+m),E),m}if(he.expandFileStorage(b,E+m),b.contents.subarray&&c.subarray)b.contents.set(c.subarray(u,u+m),E);else for(var A=0;A<m;A++)b.contents[E+A]=c[u+A];return b.usedBytes=Math.max(b.usedBytes,E+m),m},llseek(n,c,u){var m=c;if(u===1?m+=n.position:u===2&&g.isFile(n.node.mode)&&(m+=n.node.usedBytes),m<0)throw new g.ErrnoError(28);return m},allocate(n,c,u){he.expandFileStorage(n.node,c+u),n.node.usedBytes=Math.max(n.node.usedBytes,c+u)},mmap(n,c,u,m,E){if(!g.isFile(n.node.mode))throw new g.ErrnoError(43);var S,b,A=n.node.contents;if(!(E&2)&&A.buffer===Pe.buffer)b=!1,S=A.byteOffset;else{if((u>0||u+c<A.length)&&(A.subarray?A=A.subarray(u,u+c):A=Array.prototype.slice.call(A,u,u+c)),b=!0,S=dc(c),!S)throw new g.ErrnoError(48);Pe.set(A,S)}return{ptr:S,allocated:b}},msync(n,c,u,m,E){return he.stream_ops.write(n,c,0,m,u,!1),0}}},vn=(n,c,u,m)=>{var E=m?"":`al ${n}`;W(n,S=>{ei(S,`Loading data file "${n}" failed (no arrayBuffer).`),c(new Uint8Array(S)),E&&is(E)},S=>{if(u)u();else throw`Loading data file "${n}" failed.`}),E&&Ni(E)},uc=e.preloadPlugins||[];function ml(n,c,u,m){typeof Browser!="undefined"&&Browser.init();var E=!1;return uc.forEach(function(S){E||S.canHandle(c)&&(S.handle(n,c,u,m),E=!0)}),E}function lc(n,c,u,m,E,S,b,A,k,x){var K=c?At.resolve(De.join2(n,c)):n,ie=`cp ${K}`;function te(Q){function ue($e){x&&x(),A||g.createDataFile(n,c,$e,m,E,k),S&&S(),is(ie)}ml(Q,K,ue,()=>{b&&b(),is(ie)})||ue(Q)}Ni(ie),typeof u=="string"?vn(u,Q=>te(Q),b):te(u)}function pc(n){var c={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},u=c[n];if(typeof u=="undefined")throw new Error(`Unknown file open mode: ${n}`);return u}function ss(n,c){var u=0;return n&&(u|=365),c&&(u|=146),u}var g={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(n,c={})=>{if(n=At.resolve(n),!n)return{path:"",node:null};var u={follow_mount:!0,recurse_count:0};if(c=Object.assign(u,c),c.recurse_count>8)throw new g.ErrnoError(32);for(var m=n.split("/").filter(ie=>!!ie),E=g.root,S="/",b=0;b<m.length;b++){var A=b===m.length-1;if(A&&c.parent)break;if(E=g.lookupNode(E,m[b]),S=De.join2(S,m[b]),g.isMountpoint(E)&&(!A||A&&c.follow_mount)&&(E=E.mounted.root),!A||c.follow)for(var k=0;g.isLink(E.mode);){var x=g.readlink(S);S=At.resolve(De.dirname(S),x);var K=g.lookupPath(S,{recurse_count:c.recurse_count+1});if(E=K.node,k++>40)throw new g.ErrnoError(32)}}return{path:S,node:E}},getPath:n=>{for(var c;;){if(g.isRoot(n)){var u=n.mount.mountpoint;return c?u[u.length-1]!=="/"?`${u}/${c}`:u+c:u}c=c?`${n.name}/${c}`:n.name,n=n.parent}},hashName:(n,c)=>{for(var u=0,m=0;m<c.length;m++)u=(u<<5)-u+c.charCodeAt(m)|0;return(n+u>>>0)%g.nameTable.length},hashAddNode:n=>{var c=g.hashName(n.parent.id,n.name);n.name_next=g.nameTable[c],g.nameTable[c]=n},hashRemoveNode:n=>{var c=g.hashName(n.parent.id,n.name);if(g.nameTable[c]===n)g.nameTable[c]=n.name_next;else for(var u=g.nameTable[c];u;){if(u.name_next===n){u.name_next=n.name_next;break}u=u.name_next}},lookupNode:(n,c)=>{var u=g.mayLookup(n);if(u)throw new g.ErrnoError(u,n);for(var m=g.hashName(n.id,c),E=g.nameTable[m];E;E=E.name_next){var S=E.name;if(E.parent.id===n.id&&S===c)return E}return g.lookup(n,c)},createNode:(n,c,u,m)=>{var E=new g.FSNode(n,c,u,m);return g.hashAddNode(E),E},destroyNode:n=>{g.hashRemoveNode(n)},isRoot:n=>n===n.parent,isMountpoint:n=>!!n.mounted,isFile:n=>(n&61440)===32768,isDir:n=>(n&61440)===16384,isLink:n=>(n&61440)===40960,isChrdev:n=>(n&61440)===8192,isBlkdev:n=>(n&61440)===24576,isFIFO:n=>(n&61440)===4096,isSocket:n=>(n&49152)===49152,flagsToPermissionString:n=>{var c=["r","w","rw"][n&3];return n&512&&(c+="w"),c},nodePermissions:(n,c)=>g.ignorePermissions?0:c.includes("r")&&!(n.mode&292)||c.includes("w")&&!(n.mode&146)||c.includes("x")&&!(n.mode&73)?2:0,mayLookup:n=>{var c=g.nodePermissions(n,"x");return c||(n.node_ops.lookup?0:2)},mayCreate:(n,c)=>{try{var u=g.lookupNode(n,c);return 20}catch(m){}return g.nodePermissions(n,"wx")},mayDelete:(n,c,u)=>{var m;try{m=g.lookupNode(n,c)}catch(S){return S.errno}var E=g.nodePermissions(n,"wx");if(E)return E;if(u){if(!g.isDir(m.mode))return 54;if(g.isRoot(m)||g.getPath(m)===g.cwd())return 10}else if(g.isDir(m.mode))return 31;return 0},mayOpen:(n,c)=>n?g.isLink(n.mode)?32:g.isDir(n.mode)&&(g.flagsToPermissionString(c)!=="r"||c&512)?31:g.nodePermissions(n,g.flagsToPermissionString(c)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var n=0;n<=g.MAX_OPEN_FDS;n++)if(!g.streams[n])return n;throw new g.ErrnoError(33)},getStreamChecked:n=>{var c=g.getStream(n);if(!c)throw new g.ErrnoError(8);return c},getStream:n=>g.streams[n],createStream:(n,c=-1)=>(g.FSStream||(g.FSStream=function(){this.shared={}},g.FSStream.prototype={},Object.defineProperties(g.FSStream.prototype,{object:{get(){return this.node},set(u){this.node=u}},isRead:{get(){return(this.flags&2097155)!==1}},isWrite:{get(){return(this.flags&2097155)!==0}},isAppend:{get(){return this.flags&1024}},flags:{get(){return this.shared.flags},set(u){this.shared.flags=u}},position:{get(){return this.shared.position},set(u){this.shared.position=u}}})),n=Object.assign(new g.FSStream,n),c==-1&&(c=g.nextfd()),n.fd=c,g.streams[c]=n,n),closeStream:n=>{g.streams[n]=null},chrdev_stream_ops:{open:n=>{var c=g.getDevice(n.node.rdev);n.stream_ops=c.stream_ops,n.stream_ops.open&&n.stream_ops.open(n)},llseek:()=>{throw new g.ErrnoError(70)}},major:n=>n>>8,minor:n=>n&255,makedev:(n,c)=>n<<8|c,registerDevice:(n,c)=>{g.devices[n]={stream_ops:c}},getDevice:n=>g.devices[n],getMounts:n=>{for(var c=[],u=[n];u.length;){var m=u.pop();c.push(m),u.push.apply(u,m.mounts)}return c},syncfs:(n,c)=>{typeof n=="function"&&(c=n,n=!1),g.syncFSRequests++,g.syncFSRequests>1&&Xe(`warning: ${g.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var u=g.getMounts(g.root.mount),m=0;function E(b){return g.syncFSRequests--,c(b)}function S(b){if(b)return S.errored?void 0:(S.errored=!0,E(b));++m>=u.length&&E(null)}u.forEach(b=>{if(!b.type.syncfs)return S(null);b.type.syncfs(b,n,S)})},mount:(n,c,u)=>{var m=u==="/",E=!u,S;if(m&&g.root)throw new g.ErrnoError(10);if(!m&&!E){var b=g.lookupPath(u,{follow_mount:!1});if(u=b.path,S=b.node,g.isMountpoint(S))throw new g.ErrnoError(10);if(!g.isDir(S.mode))throw new g.ErrnoError(54)}var A={type:n,opts:c,mountpoint:u,mounts:[]},k=n.mount(A);return k.mount=A,A.root=k,m?g.root=k:S&&(S.mounted=A,S.mount&&S.mount.mounts.push(A)),k},unmount:n=>{var c=g.lookupPath(n,{follow_mount:!1});if(!g.isMountpoint(c.node))throw new g.ErrnoError(28);var u=c.node,m=u.mounted,E=g.getMounts(m);Object.keys(g.nameTable).forEach(b=>{for(var A=g.nameTable[b];A;){var k=A.name_next;E.includes(A.mount)&&g.destroyNode(A),A=k}}),u.mounted=null;var S=u.mount.mounts.indexOf(m);u.mount.mounts.splice(S,1)},lookup:(n,c)=>n.node_ops.lookup(n,c),mknod:(n,c,u)=>{var m=g.lookupPath(n,{parent:!0}),E=m.node,S=De.basename(n);if(!S||S==="."||S==="..")throw new g.ErrnoError(28);var b=g.mayCreate(E,S);if(b)throw new g.ErrnoError(b);if(!E.node_ops.mknod)throw new g.ErrnoError(63);return E.node_ops.mknod(E,S,c,u)},create:(n,c)=>(c=c!==void 0?c:438,c&=4095,c|=32768,g.mknod(n,c,0)),mkdir:(n,c)=>(c=c!==void 0?c:511,c&=1023,c|=16384,g.mknod(n,c,0)),mkdirTree:(n,c)=>{for(var u=n.split("/"),m="",E=0;E<u.length;++E)if(!!u[E]){m+="/"+u[E];try{g.mkdir(m,c)}catch(S){if(S.errno!=20)throw S}}},mkdev:(n,c,u)=>(typeof u=="undefined"&&(u=c,c=438),c|=8192,g.mknod(n,c,u)),symlink:(n,c)=>{if(!At.resolve(n))throw new g.ErrnoError(44);var u=g.lookupPath(c,{parent:!0}),m=u.node;if(!m)throw new g.ErrnoError(44);var E=De.basename(c),S=g.mayCreate(m,E);if(S)throw new g.ErrnoError(S);if(!m.node_ops.symlink)throw new g.ErrnoError(63);return m.node_ops.symlink(m,E,n)},rename:(n,c)=>{var u=De.dirname(n),m=De.dirname(c),E=De.basename(n),S=De.basename(c),b,A,k;if(b=g.lookupPath(n,{parent:!0}),A=b.node,b=g.lookupPath(c,{parent:!0}),k=b.node,!A||!k)throw new g.ErrnoError(44);if(A.mount!==k.mount)throw new g.ErrnoError(75);var x=g.lookupNode(A,E),K=At.relative(n,m);if(K.charAt(0)!==".")throw new g.ErrnoError(28);if(K=At.relative(c,u),K.charAt(0)!==".")throw new g.ErrnoError(55);var ie;try{ie=g.lookupNode(k,S)}catch(ue){}if(x!==ie){var te=g.isDir(x.mode),Q=g.mayDelete(A,E,te);if(Q)throw new g.ErrnoError(Q);if(Q=ie?g.mayDelete(k,S,te):g.mayCreate(k,S),Q)throw new g.ErrnoError(Q);if(!A.node_ops.rename)throw new g.ErrnoError(63);if(g.isMountpoint(x)||ie&&g.isMountpoint(ie))throw new g.ErrnoError(10);if(k!==A&&(Q=g.nodePermissions(A,"w"),Q))throw new g.ErrnoError(Q);g.hashRemoveNode(x);try{A.node_ops.rename(x,k,S)}catch(ue){throw ue}finally{g.hashAddNode(x)}}},rmdir:n=>{var c=g.lookupPath(n,{parent:!0}),u=c.node,m=De.basename(n),E=g.lookupNode(u,m),S=g.mayDelete(u,m,!0);if(S)throw new g.ErrnoError(S);if(!u.node_ops.rmdir)throw new g.ErrnoError(63);if(g.isMountpoint(E))throw new g.ErrnoError(10);u.node_ops.rmdir(u,m),g.destroyNode(E)},readdir:n=>{var c=g.lookupPath(n,{follow:!0}),u=c.node;if(!u.node_ops.readdir)throw new g.ErrnoError(54);return u.node_ops.readdir(u)},unlink:n=>{var c=g.lookupPath(n,{parent:!0}),u=c.node;if(!u)throw new g.ErrnoError(44);var m=De.basename(n),E=g.lookupNode(u,m),S=g.mayDelete(u,m,!1);if(S)throw new g.ErrnoError(S);if(!u.node_ops.unlink)throw new g.ErrnoError(63);if(g.isMountpoint(E))throw new g.ErrnoError(10);u.node_ops.unlink(u,m),g.destroyNode(E)},readlink:n=>{var c=g.lookupPath(n),u=c.node;if(!u)throw new g.ErrnoError(44);if(!u.node_ops.readlink)throw new g.ErrnoError(28);return At.resolve(g.getPath(u.parent),u.node_ops.readlink(u))},stat:(n,c)=>{var u=g.lookupPath(n,{follow:!c}),m=u.node;if(!m)throw new g.ErrnoError(44);if(!m.node_ops.getattr)throw new g.ErrnoError(63);return m.node_ops.getattr(m)},lstat:n=>g.stat(n,!0),chmod:(n,c,u)=>{var m;if(typeof n=="string"){var E=g.lookupPath(n,{follow:!u});m=E.node}else m=n;if(!m.node_ops.setattr)throw new g.ErrnoError(63);m.node_ops.setattr(m,{mode:c&4095|m.mode&-4096,timestamp:Date.now()})},lchmod:(n,c)=>{g.chmod(n,c,!0)},fchmod:(n,c)=>{var u=g.getStreamChecked(n);g.chmod(u.node,c)},chown:(n,c,u,m)=>{var E;if(typeof n=="string"){var S=g.lookupPath(n,{follow:!m});E=S.node}else E=n;if(!E.node_ops.setattr)throw new g.ErrnoError(63);E.node_ops.setattr(E,{timestamp:Date.now()})},lchown:(n,c,u)=>{g.chown(n,c,u,!0)},fchown:(n,c,u)=>{var m=g.getStreamChecked(n);g.chown(m.node,c,u)},truncate:(n,c)=>{if(c<0)throw new g.ErrnoError(28);var u;if(typeof n=="string"){var m=g.lookupPath(n,{follow:!0});u=m.node}else u=n;if(!u.node_ops.setattr)throw new g.ErrnoError(63);if(g.isDir(u.mode))throw new g.ErrnoError(31);if(!g.isFile(u.mode))throw new g.ErrnoError(28);var E=g.nodePermissions(u,"w");if(E)throw new g.ErrnoError(E);u.node_ops.setattr(u,{size:c,timestamp:Date.now()})},ftruncate:(n,c)=>{var u=g.getStreamChecked(n);if((u.flags&2097155)===0)throw new g.ErrnoError(28);g.truncate(u.node,c)},utime:(n,c,u)=>{var m=g.lookupPath(n,{follow:!0}),E=m.node;E.node_ops.setattr(E,{timestamp:Math.max(c,u)})},open:(n,c,u)=>{if(n==="")throw new g.ErrnoError(44);c=typeof c=="string"?pc(c):c,u=typeof u=="undefined"?438:u,c&64?u=u&4095|32768:u=0;var m;if(typeof n=="object")m=n;else{n=De.normalize(n);try{var E=g.lookupPath(n,{follow:!(c&131072)});m=E.node}catch(k){}}var S=!1;if(c&64)if(m){if(c&128)throw new g.ErrnoError(20)}else m=g.mknod(n,u,0),S=!0;if(!m)throw new g.ErrnoError(44);if(g.isChrdev(m.mode)&&(c&=-513),c&65536&&!g.isDir(m.mode))throw new g.ErrnoError(54);if(!S){var b=g.mayOpen(m,c);if(b)throw new g.ErrnoError(b)}c&512&&!S&&g.truncate(m,0),c&=-131713;var A=g.createStream({node:m,path:g.getPath(m),flags:c,seekable:!0,position:0,stream_ops:m.stream_ops,ungotten:[],error:!1});return A.stream_ops.open&&A.stream_ops.open(A),e.logReadFiles&&!(c&1)&&(g.readFiles||(g.readFiles={}),n in g.readFiles||(g.readFiles[n]=1)),A},close:n=>{if(g.isClosed(n))throw new g.ErrnoError(8);n.getdents&&(n.getdents=null);try{n.stream_ops.close&&n.stream_ops.close(n)}catch(c){throw c}finally{g.closeStream(n.fd)}n.fd=null},isClosed:n=>n.fd===null,llseek:(n,c,u)=>{if(g.isClosed(n))throw new g.ErrnoError(8);if(!n.seekable||!n.stream_ops.llseek)throw new g.ErrnoError(70);if(u!=0&&u!=1&&u!=2)throw new g.ErrnoError(28);return n.position=n.stream_ops.llseek(n,c,u),n.ungotten=[],n.position},read:(n,c,u,m,E)=>{if(m<0||E<0)throw new g.ErrnoError(28);if(g.isClosed(n))throw new g.ErrnoError(8);if((n.flags&2097155)===1)throw new g.ErrnoError(8);if(g.isDir(n.node.mode))throw new g.ErrnoError(31);if(!n.stream_ops.read)throw new g.ErrnoError(28);var S=typeof E!="undefined";if(!S)E=n.position;else if(!n.seekable)throw new g.ErrnoError(70);var b=n.stream_ops.read(n,c,u,m,E);return S||(n.position+=b),b},write:(n,c,u,m,E,S)=>{if(m<0||E<0)throw new g.ErrnoError(28);if(g.isClosed(n))throw new g.ErrnoError(8);if((n.flags&2097155)===0)throw new g.ErrnoError(8);if(g.isDir(n.node.mode))throw new g.ErrnoError(31);if(!n.stream_ops.write)throw new g.ErrnoError(28);n.seekable&&n.flags&1024&&g.llseek(n,0,2);var b=typeof E!="undefined";if(!b)E=n.position;else if(!n.seekable)throw new g.ErrnoError(70);var A=n.stream_ops.write(n,c,u,m,E,S);return b||(n.position+=A),A},allocate:(n,c,u)=>{if(g.isClosed(n))throw new g.ErrnoError(8);if(c<0||u<=0)throw new g.ErrnoError(28);if((n.flags&2097155)===0)throw new g.ErrnoError(8);if(!g.isFile(n.node.mode)&&!g.isDir(n.node.mode))throw new g.ErrnoError(43);if(!n.stream_ops.allocate)throw new g.ErrnoError(138);n.stream_ops.allocate(n,c,u)},mmap:(n,c,u,m,E)=>{if((m&2)!==0&&(E&2)===0&&(n.flags&2097155)!==2)throw new g.ErrnoError(2);if((n.flags&2097155)===1)throw new g.ErrnoError(2);if(!n.stream_ops.mmap)throw new g.ErrnoError(43);return n.stream_ops.mmap(n,c,u,m,E)},msync:(n,c,u,m,E)=>n.stream_ops.msync?n.stream_ops.msync(n,c,u,m,E):0,munmap:n=>0,ioctl:(n,c,u)=>{if(!n.stream_ops.ioctl)throw new g.ErrnoError(59);return n.stream_ops.ioctl(n,c,u)},readFile:(n,c={})=>{if(c.flags=c.flags||0,c.encoding=c.encoding||"binary",c.encoding!=="utf8"&&c.encoding!=="binary")throw new Error(`Invalid encoding type "${c.encoding}"`);var u,m=g.open(n,c.flags),E=g.stat(n),S=E.size,b=new Uint8Array(S);return g.read(m,b,0,S,0),c.encoding==="utf8"?u=oi(b,0):c.encoding==="binary"&&(u=b),g.close(m),u},writeFile:(n,c,u={})=>{u.flags=u.flags||577;var m=g.open(n,u.flags,u.mode);if(typeof c=="string"){var E=new Uint8Array(si(c)+1),S=bn(c,E,0,E.length);g.write(m,E,0,S,void 0,u.canOwn)}else if(ArrayBuffer.isView(c))g.write(m,c,0,c.byteLength,void 0,u.canOwn);else throw new Error("Unsupported data type");g.close(m)},cwd:()=>g.currentPath,chdir:n=>{var c=g.lookupPath(n,{follow:!0});if(c.node===null)throw new g.ErrnoError(44);if(!g.isDir(c.node.mode))throw new g.ErrnoError(54);var u=g.nodePermissions(c.node,"x");if(u)throw new g.ErrnoError(u);g.currentPath=c.path},createDefaultDirectories:()=>{g.mkdir("/tmp"),g.mkdir("/home"),g.mkdir("/home/web_user")},createDefaultDevices:()=>{g.mkdir("/dev"),g.registerDevice(g.makedev(1,3),{read:()=>0,write:(m,E,S,b,A)=>b}),g.mkdev("/dev/null",g.makedev(1,3)),Lr.register(g.makedev(5,0),Lr.default_tty_ops),Lr.register(g.makedev(6,0),Lr.default_tty1_ops),g.mkdev("/dev/tty",g.makedev(5,0)),g.mkdev("/dev/tty1",g.makedev(6,0));var n=new Uint8Array(1024),c=0,u=()=>(c===0&&(c=no(n).byteLength),n[--c]);g.createDevice("/dev","random",u),g.createDevice("/dev","urandom",u),g.mkdir("/dev/shm"),g.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{g.mkdir("/proc");var n=g.mkdir("/proc/self");g.mkdir("/proc/self/fd"),g.mount({mount:()=>{var c=g.createNode(n,"fd",16895,73);return c.node_ops={lookup:(u,m)=>{var E=+m,S=g.getStreamChecked(E),b={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>S.path}};return b.parent=b,b}},c}},{},"/proc/self/fd")},createStandardStreams:()=>{e.stdin?g.createDevice("/dev","stdin",e.stdin):g.symlink("/dev/tty","/dev/stdin"),e.stdout?g.createDevice("/dev","stdout",null,e.stdout):g.symlink("/dev/tty","/dev/stdout"),e.stderr?g.createDevice("/dev","stderr",null,e.stderr):g.symlink("/dev/tty1","/dev/stderr");var n=g.open("/dev/stdin",0),c=g.open("/dev/stdout",1),u=g.open("/dev/stderr",1)},ensureErrnoError:()=>{g.ErrnoError||(g.ErrnoError=function(c,u){this.name="ErrnoError",this.node=u,this.setErrno=function(m){this.errno=m},this.setErrno(c),this.message="FS error"},g.ErrnoError.prototype=new Error,g.ErrnoError.prototype.constructor=g.ErrnoError,[44].forEach(n=>{g.genericErrors[n]=new g.ErrnoError(n),g.genericErrors[n].stack="<generic error, no stack>"}))},staticInit:()=>{g.ensureErrnoError(),g.nameTable=new Array(4096),g.mount(he,{},"/"),g.createDefaultDirectories(),g.createDefaultDevices(),g.createSpecialDirectories(),g.filesystems={MEMFS:he}},init:(n,c,u)=>{g.init.initialized=!0,g.ensureErrnoError(),e.stdin=n||e.stdin,e.stdout=c||e.stdout,e.stderr=u||e.stderr,g.createStandardStreams()},quit:()=>{g.init.initialized=!1;for(var n=0;n<g.streams.length;n++){var c=g.streams[n];!c||g.close(c)}},findObject:(n,c)=>{var u=g.analyzePath(n,c);return u.exists?u.object:null},analyzePath:(n,c)=>{try{var u=g.lookupPath(n,{follow:!c});n=u.path}catch(E){}var m={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var u=g.lookupPath(n,{parent:!0});m.parentExists=!0,m.parentPath=u.path,m.parentObject=u.node,m.name=De.basename(n),u=g.lookupPath(n,{follow:!c}),m.exists=!0,m.path=u.path,m.object=u.node,m.name=u.node.name,m.isRoot=u.path==="/"}catch(E){m.error=E.errno}return m},createPath:(n,c,u,m)=>{n=typeof n=="string"?n:g.getPath(n);for(var E=c.split("/").reverse();E.length;){var S=E.pop();if(!!S){var b=De.join2(n,S);try{g.mkdir(b)}catch(A){}n=b}}return b},createFile:(n,c,u,m,E)=>{var S=De.join2(typeof n=="string"?n:g.getPath(n),c),b=ss(m,E);return g.create(S,b)},createDataFile:(n,c,u,m,E,S)=>{var b=c;n&&(n=typeof n=="string"?n:g.getPath(n),b=c?De.join2(n,c):n);var A=ss(m,E),k=g.create(b,A);if(u){if(typeof u=="string"){for(var x=new Array(u.length),K=0,ie=u.length;K<ie;++K)x[K]=u.charCodeAt(K);u=x}g.chmod(k,A|146);var te=g.open(k,577);g.write(te,u,0,u.length,0,S),g.close(te),g.chmod(k,A)}return k},createDevice:(n,c,u,m)=>{var E=De.join2(typeof n=="string"?n:g.getPath(n),c),S=ss(!!u,!!m);g.createDevice.major||(g.createDevice.major=64);var b=g.makedev(g.createDevice.major++,0);return g.registerDevice(b,{open:A=>{A.seekable=!1},close:A=>{m&&m.buffer&&m.buffer.length&&m(10)},read:(A,k,x,K,ie)=>{for(var te=0,Q=0;Q<K;Q++){var ue;try{ue=u()}catch($e){throw new g.ErrnoError(29)}if(ue===void 0&&te===0)throw new g.ErrnoError(6);if(ue==null)break;te++,k[x+Q]=ue}return te&&(A.node.timestamp=Date.now()),te},write:(A,k,x,K,ie)=>{for(var te=0;te<K;te++)try{m(k[x+te])}catch(Q){throw new g.ErrnoError(29)}return K&&(A.node.timestamp=Date.now()),te}}),g.mkdev(E,S,b)},forceLoadFile:n=>{if(n.isDevice||n.isFolder||n.link||n.contents)return!0;if(typeof XMLHttpRequest!="undefined")throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(j)try{n.contents=Kt(j(n.url),!0),n.usedBytes=n.contents.length}catch(c){throw new g.ErrnoError(29)}else throw new Error("Cannot load without read() or XMLHttpRequest.")},createLazyFile:(n,c,u,m,E)=>{function S(){this.lengthKnown=!1,this.chunks=[]}if(S.prototype.get=function(Q){if(!(Q>this.length-1||Q<0)){var ue=Q%this.chunkSize,$e=Q/this.chunkSize|0;return this.getter($e)[ue]}},S.prototype.setDataGetter=function(Q){this.getter=Q},S.prototype.cacheLength=function(){var Q=new XMLHttpRequest;if(Q.open("HEAD",u,!1),Q.send(null),!(Q.status>=200&&Q.status<300||Q.status===304))throw new Error("Couldn't load "+u+". Status: "+Q.status);var ue=Number(Q.getResponseHeader("Content-length")),$e,qe=($e=Q.getResponseHeader("Accept-Ranges"))&&$e==="bytes",lt=($e=Q.getResponseHeader("Content-Encoding"))&&$e==="gzip",kt=1024*1024;qe||(kt=ue);var Ze=(tr,ui)=>{if(tr>ui)throw new Error("invalid range ("+tr+", "+ui+") or no bytes requested!");if(ui>ue-1)throw new Error("only "+ue+" bytes available! programmer error!");var pt=new XMLHttpRequest;if(pt.open("GET",u,!1),ue!==kt&&pt.setRequestHeader("Range","bytes="+tr+"-"+ui),pt.responseType="arraybuffer",pt.overrideMimeType&&pt.overrideMimeType("text/plain; charset=x-user-defined"),pt.send(null),!(pt.status>=200&&pt.status<300||pt.status===304))throw new Error("Couldn't load "+u+". Status: "+pt.status);return pt.response!==void 0?new Uint8Array(pt.response||[]):Kt(pt.responseText||"",!0)},fo=this;fo.setDataGetter(tr=>{var ui=tr*kt,pt=(tr+1)*kt-1;if(pt=Math.min(pt,ue-1),typeof fo.chunks[tr]=="undefined"&&(fo.chunks[tr]=Ze(ui,pt)),typeof fo.chunks[tr]=="undefined")throw new Error("doXHR failed!");return fo.chunks[tr]}),(lt||!ue)&&(kt=ue=1,ue=this.getter(0).length,kt=ue,Bt("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=ue,this._chunkSize=kt,this.lengthKnown=!0},typeof XMLHttpRequest!="undefined"){if(!T)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var b=new S;Object.defineProperties(b,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var A={isDevice:!1,contents:b}}else var A={isDevice:!1,url:u};var k=g.createFile(n,c,A,m,E);A.contents?k.contents=A.contents:A.url&&(k.contents=null,k.url=A.url),Object.defineProperties(k,{usedBytes:{get:function(){return this.contents.length}}});var x={},K=Object.keys(k.stream_ops);K.forEach(te=>{var Q=k.stream_ops[te];x[te]=function(){return g.forceLoadFile(k),Q.apply(null,arguments)}});function ie(te,Q,ue,$e,qe){var lt=te.node.contents;if(qe>=lt.length)return 0;var kt=Math.min(lt.length-qe,$e);if(lt.slice)for(var Ze=0;Ze<kt;Ze++)Q[ue+Ze]=lt[qe+Ze];else for(var Ze=0;Ze<kt;Ze++)Q[ue+Ze]=lt.get(qe+Ze);return kt}return x.read=(te,Q,ue,$e,qe)=>(g.forceLoadFile(k),ie(te,Q,ue,$e,qe)),x.mmap=(te,Q,ue,$e,qe)=>{g.forceLoadFile(k);var lt=dc(Q);if(!lt)throw new g.ErrnoError(48);return ie(te,Pe,lt,Q,ue),{ptr:lt,allocated:!0}},k.stream_ops=x,k}},mc=(n,c)=>n?oi(tt,n,c):"",Qe={DEFAULT_POLLMASK:5,calculateAt:function(n,c,u){if(De.isAbs(c))return c;var m;if(n===-100)m=g.cwd();else{var E=Qe.getStreamFromFD(n);m=E.path}if(c.length==0){if(!u)throw new g.ErrnoError(44);return m}return De.join2(m,c)},doStat:function(n,c,u){try{var m=n(c)}catch(A){if(A&&A.node&&De.normalize(c)!==De.normalize(g.getPath(A.node)))return-54;throw A}P[u>>2]=m.dev,P[u+4>>2]=m.mode,Me[u+8>>2]=m.nlink,P[u+12>>2]=m.uid,P[u+16>>2]=m.gid,P[u+20>>2]=m.rdev,He=[m.size>>>0,(ce=m.size,+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[u+24>>2]=He[0],P[u+28>>2]=He[1],P[u+32>>2]=4096,P[u+36>>2]=m.blocks;var E=m.atime.getTime(),S=m.mtime.getTime(),b=m.ctime.getTime();return He=[Math.floor(E/1e3)>>>0,(ce=Math.floor(E/1e3),+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[u+40>>2]=He[0],P[u+44>>2]=He[1],Me[u+48>>2]=E%1e3*1e3,He=[Math.floor(S/1e3)>>>0,(ce=Math.floor(S/1e3),+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[u+56>>2]=He[0],P[u+60>>2]=He[1],Me[u+64>>2]=S%1e3*1e3,He=[Math.floor(b/1e3)>>>0,(ce=Math.floor(b/1e3),+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[u+72>>2]=He[0],P[u+76>>2]=He[1],Me[u+80>>2]=b%1e3*1e3,He=[m.ino>>>0,(ce=m.ino,+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[u+88>>2]=He[0],P[u+92>>2]=He[1],0},doMsync:function(n,c,u,m,E){if(!g.isFile(c.node.mode))throw new g.ErrnoError(43);if(m&2)return 0;var S=tt.slice(n,n+u);g.msync(c,S,E,u,m)},varargs:void 0,get(){Qe.varargs+=4;var n=P[Qe.varargs-4>>2];return n},getStr(n){var c=mc(n);return c},getStreamFromFD:function(n){var c=g.getStreamChecked(n);return c}};function Rn(n,c,u){Qe.varargs=u;try{var m=Qe.getStreamFromFD(n);switch(c){case 0:{var E=Qe.get();if(E<0)return-28;var S;return S=g.createStream(m,E),S.fd}case 1:case 2:return 0;case 3:return m.flags;case 4:{var E=Qe.get();return m.flags|=E,0}case 5:{var E=Qe.get(),b=0;return Yt[E+b>>1]=2,0}case 6:case 7:return 0;case 16:case 8:return-28;case 9:return xt(28),-1;default:return-28}}catch(A){if(typeof g=="undefined"||A.name!=="ErrnoError")throw A;return-A.errno}}function ao(n,c,u,m){Qe.varargs=m;try{c=Qe.getStr(c),c=Qe.calculateAt(n,c);var E=m?Qe.get():0;return g.open(c,u,E).fd}catch(S){if(typeof g=="undefined"||S.name!=="ErrnoError")throw S;return-S.errno}}function hl(n,c,u,m,E){}function Cn(n){switch(n){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${n}`)}}function co(){for(var n=new Array(256),c=0;c<256;++c)n[c]=String.fromCharCode(c);hc=n}var hc=void 0;function Mt(n){for(var c="",u=n;tt[u];)c+=hc[tt[u++]];return c}var Er={},ni={},Ur={},Oi=void 0;function xe(n){throw new Oi(n)}var fc=void 0;function ns(n){throw new fc(n)}function uo(n,c,u){n.forEach(function(A){Ur[A]=c});function m(A){var k=u(A);k.length!==n.length&&ns("Mismatched type converter count");for(var x=0;x<n.length;++x)Tr(n[x],k[x])}var E=new Array(c.length),S=[],b=0;c.forEach((A,k)=>{ni.hasOwnProperty(A)?E[k]=ni[A]:(S.push(A),Er.hasOwnProperty(A)||(Er[A]=[]),Er[A].push(()=>{E[k]=ni[A],++b,b===S.length&&m(E)}))}),S.length===0&&m(E)}function Vr(n,c,u={}){var m=c.name;if(n||xe(`type "${m}" must have a positive integer typeid pointer`),ni.hasOwnProperty(n)){if(u.ignoreDuplicateRegistrations)return;xe(`Cannot register type '${m}' twice`)}if(ni[n]=c,delete Ur[n],Er.hasOwnProperty(n)){var E=Er[n];delete Er[n],E.forEach(S=>S())}}function Tr(n,c,u={}){if(!("argPackAdvance"in c))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Vr(n,c,u)}function fl(n,c,u,m,E){var S=Cn(u);c=Mt(c),Tr(n,{name:c,fromWireType:function(b){return!!b},toWireType:function(b,A){return A?m:E},argPackAdvance:8,readValueFromPointer:function(b){var A;if(u===1)A=Pe;else if(u===2)A=Yt;else if(u===4)A=P;else throw new TypeError("Unknown boolean type size: "+c);return this.fromWireType(A[b>>S])},destructorFunction:null})}function as(n){if(!(this instanceof Sr)||!(n instanceof Sr))return!1;for(var c=this.$$.ptrType.registeredClass,u=this.$$.ptr,m=n.$$.ptrType.registeredClass,E=n.$$.ptr;c.baseClass;)u=c.upcast(u),c=c.baseClass;for(;m.baseClass;)E=m.upcast(E),m=m.baseClass;return c===m&&u===E}function Dn(n){return{count:n.count,deleteScheduled:n.deleteScheduled,preservePointerOnDelete:n.preservePointerOnDelete,ptr:n.ptr,ptrType:n.ptrType,smartPtr:n.smartPtr,smartPtrType:n.smartPtrType}}function cs(n){function c(u){return u.$$.ptrType.registeredClass.name}xe(c(n)+" instance already deleted")}var Nn=!1;function _c(n){}function wn(n){n.smartPtr?n.smartPtrType.rawDestructor(n.smartPtr):n.ptrType.registeredClass.rawDestructor(n.ptr)}function gc(n){n.count.value-=1;var c=n.count.value===0;c&&wn(n)}function Ec(n,c,u){if(c===u)return n;if(u.baseClass===void 0)return null;var m=Ec(n,c,u.baseClass);return m===null?null:u.downcast(m)}var Tc={};function ds(){return Object.keys(mo).length}function _l(){var n=[];for(var c in mo)mo.hasOwnProperty(c)&&n.push(mo[c]);return n}var lo=[];function xn(){for(;lo.length;){var n=lo.pop();n.$$.deleteScheduled=!1,n.delete()}}var po=void 0;function Ir(n){po=n,lo.length&&po&&po(xn)}function gl(){e.getInheritedInstanceCount=ds,e.getLiveInheritedInstances=_l,e.flushPendingDeletes=xn,e.setDelayFunction=Ir}var mo={};function us(n,c){for(c===void 0&&xe("ptr should not be undefined");n.baseClass;)c=n.upcast(c),n=n.baseClass;return c}function Ic(n,c){return c=us(n,c),mo[c]}function ls(n,c){(!c.ptrType||!c.ptr)&&ns("makeClassHandle requires ptr and ptrType");var u=!!c.smartPtrType,m=!!c.smartPtr;return u!==m&&ns("Both smartPtrType and smartPtr must be specified"),c.count={value:1},ur(Object.create(n,{$$:{value:c}}))}function El(n){var c=this.getPointee(n);if(!c)return this.destructor(n),null;var u=Ic(this.registeredClass,c);if(u!==void 0){if(u.$$.count.value===0)return u.$$.ptr=c,u.$$.smartPtr=n,u.clone();var m=u.clone();return this.destructor(n),m}function E(){return this.isSmartPointer?ls(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:c,smartPtrType:this,smartPtr:n}):ls(this.registeredClass.instancePrototype,{ptrType:this,ptr:n})}var S=this.registeredClass.getActualType(c),b=Tc[S];if(!b)return E.call(this);var A;this.isConst?A=b.constPointerType:A=b.pointerType;var k=Ec(c,this.registeredClass,A.registeredClass);return k===null?E.call(this):this.isSmartPointer?ls(A.registeredClass.instancePrototype,{ptrType:A,ptr:k,smartPtrType:this,smartPtr:n}):ls(A.registeredClass.instancePrototype,{ptrType:A,ptr:k})}var ur=function(n){return typeof FinalizationRegistry=="undefined"?(ur=c=>c,n):(Nn=new FinalizationRegistry(c=>{gc(c.$$)}),ur=c=>{var u=c.$$,m=!!u.smartPtr;if(m){var E={$$:u};Nn.register(c,E,c)}return c},_c=c=>Nn.unregister(c),ur(n))};function Tl(){if(this.$$.ptr||cs(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var n=ur(Object.create(Object.getPrototypeOf(this),{$$:{value:Dn(this.$$)}}));return n.$$.count.value+=1,n.$$.deleteScheduled=!1,n}function Sc(){this.$$.ptr||cs(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&xe("Object already scheduled for deletion"),_c(this),gc(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function yc(){return!this.$$.ptr}function Mn(){return this.$$.ptr||cs(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&xe("Object already scheduled for deletion"),lo.push(this),lo.length===1&&po&&po(xn),this.$$.deleteScheduled=!0,this}function Il(){Sr.prototype.isAliasOf=as,Sr.prototype.clone=Tl,Sr.prototype.delete=Sc,Sr.prototype.isDeleted=yc,Sr.prototype.deleteLater=Mn}function Sr(){}var Sl=48,Ac=57;function ho(n){if(n===void 0)return"_unknown";n=n.replace(/[^a-zA-Z0-9_]/g,"$");var c=n.charCodeAt(0);return c>=Sl&&c<=Ac?`_${n}`:n}function On(n,c){return n=ho(n),{[n]:function(){return c.apply(this,arguments)}}[n]}function bc(n,c,u){if(n[c].overloadTable===void 0){var m=n[c];n[c]=function(){return n[c].overloadTable.hasOwnProperty(arguments.length)||xe(`Function '${u}' called with an invalid number of arguments (${arguments.length}) - expects one of (${n[c].overloadTable})!`),n[c].overloadTable[arguments.length].apply(this,arguments)},n[c].overloadTable=[],n[c].overloadTable[m.argCount]=m}}function yl(n,c,u){e.hasOwnProperty(n)?((u===void 0||e[n].overloadTable!==void 0&&e[n].overloadTable[u]!==void 0)&&xe(`Cannot register public name '${n}' twice`),bc(e,n,n),e.hasOwnProperty(u)&&xe(`Cannot register multiple overloads of a function with the same number of arguments (${u})!`),e[n].overloadTable[u]=c):(e[n]=c,u!==void 0&&(e[n].numArguments=u))}function vc(n,c,u,m,E,S,b,A){this.name=n,this.constructor=c,this.instancePrototype=u,this.rawDestructor=m,this.baseClass=E,this.getActualType=S,this.upcast=b,this.downcast=A,this.pureVirtualFunctions=[]}function Ot(n,c,u){for(;c!==u;)c.upcast||xe(`Expected null or instance of ${u.name}, got an instance of ${c.name}`),n=c.upcast(n),c=c.baseClass;return n}function Rc(n,c){if(c===null)return this.isReference&&xe(`null is not a valid ${this.name}`),0;c.$$||xe(`Cannot pass "${Un(c)}" as a ${this.name}`),c.$$.ptr||xe(`Cannot pass deleted object as a pointer of type ${this.name}`);var u=c.$$.ptrType.registeredClass,m=Ot(c.$$.ptr,u,this.registeredClass);return m}function Al(n,c){var u;if(c===null)return this.isReference&&xe(`null is not a valid ${this.name}`),this.isSmartPointer?(u=this.rawConstructor(),n!==null&&n.push(this.rawDestructor,u),u):0;c.$$||xe(`Cannot pass "${Un(c)}" as a ${this.name}`),c.$$.ptr||xe(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&c.$$.ptrType.isConst&&xe(`Cannot convert argument of type ${c.$$.smartPtrType?c.$$.smartPtrType.name:c.$$.ptrType.name} to parameter type ${this.name}`);var m=c.$$.ptrType.registeredClass;if(u=Ot(c.$$.ptr,m,this.registeredClass),this.isSmartPointer)switch(c.$$.smartPtr===void 0&&xe("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:c.$$.smartPtrType===this?u=c.$$.smartPtr:xe(`Cannot convert argument of type ${c.$$.smartPtrType?c.$$.smartPtrType.name:c.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:u=c.$$.smartPtr;break;case 2:if(c.$$.smartPtrType===this)u=c.$$.smartPtr;else{var E=c.clone();u=this.rawShare(u,ms.toHandle(function(){E.delete()})),n!==null&&n.push(this.rawDestructor,u)}break;default:xe("Unsupporting sharing policy")}return u}function bl(n,c){if(c===null)return this.isReference&&xe(`null is not a valid ${this.name}`),0;c.$$||xe(`Cannot pass "${Un(c)}" as a ${this.name}`),c.$$.ptr||xe(`Cannot pass deleted object as a pointer of type ${this.name}`),c.$$.ptrType.isConst&&xe(`Cannot convert argument of type ${c.$$.ptrType.name} to parameter type ${this.name}`);var u=c.$$.ptrType.registeredClass,m=Ot(c.$$.ptr,u,this.registeredClass);return m}function ai(n){return this.fromWireType(P[n>>2])}function vl(n){return this.rawGetPointee&&(n=this.rawGetPointee(n)),n}function Pn(n){this.rawDestructor&&this.rawDestructor(n)}function Rl(n){n!==null&&n.delete()}function Cl(){yr.prototype.getPointee=vl,yr.prototype.destructor=Pn,yr.prototype.argPackAdvance=8,yr.prototype.readValueFromPointer=ai,yr.prototype.deleteObject=Rl,yr.prototype.fromWireType=El}function yr(n,c,u,m,E,S,b,A,k,x,K){this.name=n,this.registeredClass=c,this.isReference=u,this.isConst=m,this.isSmartPointer=E,this.pointeeType=S,this.sharingPolicy=b,this.rawGetPointee=A,this.rawConstructor=k,this.rawShare=x,this.rawDestructor=K,!E&&c.baseClass===void 0?m?(this.toWireType=Rc,this.destructorFunction=null):(this.toWireType=bl,this.destructorFunction=null):this.toWireType=Al}function Dl(n,c,u){e.hasOwnProperty(n)||ns("Replacing nonexistant public symbol"),e[n].overloadTable!==void 0&&u!==void 0?e[n].overloadTable[u]=c:(e[n]=c,e[n].argCount=u)}var Nl=(n,c,u)=>{var m=e["dynCall_"+n];return u&&u.length?m.apply(null,[c].concat(u)):m.call(null,c)},ps=[],Cc=n=>{var c=ps[n];return c||(n>=ps.length&&(ps.length=n+1),ps[n]=c=gn.get(n)),c},wl=(n,c,u)=>{if(n.includes("j"))return Nl(n,c,u);var m=Cc(c).apply(null,u);return m},Dc=(n,c)=>{var u=[];return function(){return u.length=0,Object.assign(u,arguments),wl(n,c,u)}};function ci(n,c){n=Mt(n);function u(){return n.includes("j")?Dc(n,c):Cc(c)}var m=u();return typeof m!="function"&&xe(`unknown function pointer with signature ${n}: ${c}`),m}function Nc(n,c){var u=On(c,function(m){this.name=c,this.message=m;var E=new Error(m).stack;E!==void 0&&(this.stack=this.toString()+`
|
|
50
|
-
`+E.replace(/^Error(:[^\n]*)?\n/,""))});return u.prototype=Object.create(n.prototype),u.prototype.constructor=u,u.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},u}var wc=void 0;function
|
|
49
|
+
`)),!n)return null;Mi=Kt(n,!0)}return Mi.shift()},Lr={ttys:[],init:function(){},shutdown:function(){},register:function(n,c){Lr.ttys[n]={input:[],output:[],ops:c},g.registerDevice(n,Lr.stream_ops)},stream_ops:{open:function(n){var c=Lr.ttys[n.node.rdev];if(!c)throw new g.ErrnoError(43);n.tty=c,n.seekable=!1},close:function(n){n.tty.ops.fsync(n.tty)},fsync:function(n){n.tty.ops.fsync(n.tty)},read:function(n,c,u,m,E){if(!n.tty||!n.tty.ops.get_char)throw new g.ErrnoError(60);for(var S=0,b=0;b<m;b++){var A;try{A=n.tty.ops.get_char(n.tty)}catch(k){throw new g.ErrnoError(29)}if(A===void 0&&S===0)throw new g.ErrnoError(6);if(A==null)break;S++,c[u+b]=A}return S&&(n.node.timestamp=Date.now()),S},write:function(n,c,u,m,E){if(!n.tty||!n.tty.ops.put_char)throw new g.ErrnoError(60);try{for(var S=0;S<m;S++)n.tty.ops.put_char(n.tty,c[u+S])}catch(b){throw new g.ErrnoError(29)}return m&&(n.node.timestamp=Date.now()),S}},default_tty_ops:{get_char:function(n){return pl()},put_char:function(n,c){c===null||c===10?(Bt(oi(n.output,0)),n.output=[]):c!=0&&n.output.push(c)},fsync:function(n){n.output&&n.output.length>0&&(Bt(oi(n.output,0)),n.output=[])},ioctl_tcgets:function(n){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(n,c,u){return 0},ioctl_tiocgwinsz:function(n){return[24,80]}},default_tty1_ops:{put_char:function(n,c){c===null||c===10?(Xe(oi(n.output,0)),n.output=[]):c!=0&&n.output.push(c)},fsync:function(n){n.output&&n.output.length>0&&(Xe(oi(n.output,0)),n.output=[])}}},dc=n=>{kr()},he={ops_table:null,mount(n){return he.createNode(null,"/",16895,0)},createNode(n,c,u,m){if(g.isBlkdev(u)||g.isFIFO(u))throw new g.ErrnoError(63);he.ops_table||(he.ops_table={dir:{node:{getattr:he.node_ops.getattr,setattr:he.node_ops.setattr,lookup:he.node_ops.lookup,mknod:he.node_ops.mknod,rename:he.node_ops.rename,unlink:he.node_ops.unlink,rmdir:he.node_ops.rmdir,readdir:he.node_ops.readdir,symlink:he.node_ops.symlink},stream:{llseek:he.stream_ops.llseek}},file:{node:{getattr:he.node_ops.getattr,setattr:he.node_ops.setattr},stream:{llseek:he.stream_ops.llseek,read:he.stream_ops.read,write:he.stream_ops.write,allocate:he.stream_ops.allocate,mmap:he.stream_ops.mmap,msync:he.stream_ops.msync}},link:{node:{getattr:he.node_ops.getattr,setattr:he.node_ops.setattr,readlink:he.node_ops.readlink},stream:{}},chrdev:{node:{getattr:he.node_ops.getattr,setattr:he.node_ops.setattr},stream:g.chrdev_stream_ops}});var E=g.createNode(n,c,u,m);return g.isDir(E.mode)?(E.node_ops=he.ops_table.dir.node,E.stream_ops=he.ops_table.dir.stream,E.contents={}):g.isFile(E.mode)?(E.node_ops=he.ops_table.file.node,E.stream_ops=he.ops_table.file.stream,E.usedBytes=0,E.contents=null):g.isLink(E.mode)?(E.node_ops=he.ops_table.link.node,E.stream_ops=he.ops_table.link.stream):g.isChrdev(E.mode)&&(E.node_ops=he.ops_table.chrdev.node,E.stream_ops=he.ops_table.chrdev.stream),E.timestamp=Date.now(),n&&(n.contents[c]=E,n.timestamp=E.timestamp),E},getFileDataAsTypedArray(n){return n.contents?n.contents.subarray?n.contents.subarray(0,n.usedBytes):new Uint8Array(n.contents):new Uint8Array(0)},expandFileStorage(n,c){var u=n.contents?n.contents.length:0;if(!(u>=c)){var m=1024*1024;c=Math.max(c,u*(u<m?2:1.125)>>>0),u!=0&&(c=Math.max(c,256));var E=n.contents;n.contents=new Uint8Array(c),n.usedBytes>0&&n.contents.set(E.subarray(0,n.usedBytes),0)}},resizeFileStorage(n,c){if(n.usedBytes!=c)if(c==0)n.contents=null,n.usedBytes=0;else{var u=n.contents;n.contents=new Uint8Array(c),u&&n.contents.set(u.subarray(0,Math.min(c,n.usedBytes))),n.usedBytes=c}},node_ops:{getattr(n){var c={};return c.dev=g.isChrdev(n.mode)?n.id:1,c.ino=n.id,c.mode=n.mode,c.nlink=1,c.uid=0,c.gid=0,c.rdev=n.rdev,g.isDir(n.mode)?c.size=4096:g.isFile(n.mode)?c.size=n.usedBytes:g.isLink(n.mode)?c.size=n.link.length:c.size=0,c.atime=new Date(n.timestamp),c.mtime=new Date(n.timestamp),c.ctime=new Date(n.timestamp),c.blksize=4096,c.blocks=Math.ceil(c.size/c.blksize),c},setattr(n,c){c.mode!==void 0&&(n.mode=c.mode),c.timestamp!==void 0&&(n.timestamp=c.timestamp),c.size!==void 0&&he.resizeFileStorage(n,c.size)},lookup(n,c){throw g.genericErrors[44]},mknod(n,c,u,m){return he.createNode(n,c,u,m)},rename(n,c,u){if(g.isDir(n.mode)){var m;try{m=g.lookupNode(c,u)}catch(S){}if(m)for(var E in m.contents)throw new g.ErrnoError(55)}delete n.parent.contents[n.name],n.parent.timestamp=Date.now(),n.name=u,c.contents[u]=n,c.timestamp=n.parent.timestamp,n.parent=c},unlink(n,c){delete n.contents[c],n.timestamp=Date.now()},rmdir(n,c){var u=g.lookupNode(n,c);for(var m in u.contents)throw new g.ErrnoError(55);delete n.contents[c],n.timestamp=Date.now()},readdir(n){var c=[".",".."];for(var u in n.contents)!n.contents.hasOwnProperty(u)||c.push(u);return c},symlink(n,c,u){var m=he.createNode(n,c,41471,0);return m.link=u,m},readlink(n){if(!g.isLink(n.mode))throw new g.ErrnoError(28);return n.link}},stream_ops:{read(n,c,u,m,E){var S=n.node.contents;if(E>=n.node.usedBytes)return 0;var b=Math.min(n.node.usedBytes-E,m);if(b>8&&S.subarray)c.set(S.subarray(E,E+b),u);else for(var A=0;A<b;A++)c[u+A]=S[E+A];return b},write(n,c,u,m,E,S){if(!m)return 0;var b=n.node;if(b.timestamp=Date.now(),c.subarray&&(!b.contents||b.contents.subarray)){if(S)return b.contents=c.subarray(u,u+m),b.usedBytes=m,m;if(b.usedBytes===0&&E===0)return b.contents=c.slice(u,u+m),b.usedBytes=m,m;if(E+m<=b.usedBytes)return b.contents.set(c.subarray(u,u+m),E),m}if(he.expandFileStorage(b,E+m),b.contents.subarray&&c.subarray)b.contents.set(c.subarray(u,u+m),E);else for(var A=0;A<m;A++)b.contents[E+A]=c[u+A];return b.usedBytes=Math.max(b.usedBytes,E+m),m},llseek(n,c,u){var m=c;if(u===1?m+=n.position:u===2&&g.isFile(n.node.mode)&&(m+=n.node.usedBytes),m<0)throw new g.ErrnoError(28);return m},allocate(n,c,u){he.expandFileStorage(n.node,c+u),n.node.usedBytes=Math.max(n.node.usedBytes,c+u)},mmap(n,c,u,m,E){if(!g.isFile(n.node.mode))throw new g.ErrnoError(43);var S,b,A=n.node.contents;if(!(E&2)&&A.buffer===Pe.buffer)b=!1,S=A.byteOffset;else{if((u>0||u+c<A.length)&&(A.subarray?A=A.subarray(u,u+c):A=Array.prototype.slice.call(A,u,u+c)),b=!0,S=dc(c),!S)throw new g.ErrnoError(48);Pe.set(A,S)}return{ptr:S,allocated:b}},msync(n,c,u,m,E){return he.stream_ops.write(n,c,0,m,u,!1),0}}},Rn=(n,c,u,m)=>{var E=m?"":`al ${n}`;W(n,S=>{ei(S,`Loading data file "${n}" failed (no arrayBuffer).`),c(new Uint8Array(S)),E&&is(E)},S=>{if(u)u();else throw`Loading data file "${n}" failed.`}),E&&Ni(E)},uc=e.preloadPlugins||[];function ml(n,c,u,m){typeof Browser!="undefined"&&Browser.init();var E=!1;return uc.forEach(function(S){E||S.canHandle(c)&&(S.handle(n,c,u,m),E=!0)}),E}function lc(n,c,u,m,E,S,b,A,k,x){var K=c?At.resolve(De.join2(n,c)):n,ie=`cp ${K}`;function te(Q){function ue($e){x&&x(),A||g.createDataFile(n,c,$e,m,E,k),S&&S(),is(ie)}ml(Q,K,ue,()=>{b&&b(),is(ie)})||ue(Q)}Ni(ie),typeof u=="string"?Rn(u,Q=>te(Q),b):te(u)}function pc(n){var c={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},u=c[n];if(typeof u=="undefined")throw new Error(`Unknown file open mode: ${n}`);return u}function ss(n,c){var u=0;return n&&(u|=365),c&&(u|=146),u}var g={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(n,c={})=>{if(n=At.resolve(n),!n)return{path:"",node:null};var u={follow_mount:!0,recurse_count:0};if(c=Object.assign(u,c),c.recurse_count>8)throw new g.ErrnoError(32);for(var m=n.split("/").filter(ie=>!!ie),E=g.root,S="/",b=0;b<m.length;b++){var A=b===m.length-1;if(A&&c.parent)break;if(E=g.lookupNode(E,m[b]),S=De.join2(S,m[b]),g.isMountpoint(E)&&(!A||A&&c.follow_mount)&&(E=E.mounted.root),!A||c.follow)for(var k=0;g.isLink(E.mode);){var x=g.readlink(S);S=At.resolve(De.dirname(S),x);var K=g.lookupPath(S,{recurse_count:c.recurse_count+1});if(E=K.node,k++>40)throw new g.ErrnoError(32)}}return{path:S,node:E}},getPath:n=>{for(var c;;){if(g.isRoot(n)){var u=n.mount.mountpoint;return c?u[u.length-1]!=="/"?`${u}/${c}`:u+c:u}c=c?`${n.name}/${c}`:n.name,n=n.parent}},hashName:(n,c)=>{for(var u=0,m=0;m<c.length;m++)u=(u<<5)-u+c.charCodeAt(m)|0;return(n+u>>>0)%g.nameTable.length},hashAddNode:n=>{var c=g.hashName(n.parent.id,n.name);n.name_next=g.nameTable[c],g.nameTable[c]=n},hashRemoveNode:n=>{var c=g.hashName(n.parent.id,n.name);if(g.nameTable[c]===n)g.nameTable[c]=n.name_next;else for(var u=g.nameTable[c];u;){if(u.name_next===n){u.name_next=n.name_next;break}u=u.name_next}},lookupNode:(n,c)=>{var u=g.mayLookup(n);if(u)throw new g.ErrnoError(u,n);for(var m=g.hashName(n.id,c),E=g.nameTable[m];E;E=E.name_next){var S=E.name;if(E.parent.id===n.id&&S===c)return E}return g.lookup(n,c)},createNode:(n,c,u,m)=>{var E=new g.FSNode(n,c,u,m);return g.hashAddNode(E),E},destroyNode:n=>{g.hashRemoveNode(n)},isRoot:n=>n===n.parent,isMountpoint:n=>!!n.mounted,isFile:n=>(n&61440)===32768,isDir:n=>(n&61440)===16384,isLink:n=>(n&61440)===40960,isChrdev:n=>(n&61440)===8192,isBlkdev:n=>(n&61440)===24576,isFIFO:n=>(n&61440)===4096,isSocket:n=>(n&49152)===49152,flagsToPermissionString:n=>{var c=["r","w","rw"][n&3];return n&512&&(c+="w"),c},nodePermissions:(n,c)=>g.ignorePermissions?0:c.includes("r")&&!(n.mode&292)||c.includes("w")&&!(n.mode&146)||c.includes("x")&&!(n.mode&73)?2:0,mayLookup:n=>{var c=g.nodePermissions(n,"x");return c||(n.node_ops.lookup?0:2)},mayCreate:(n,c)=>{try{var u=g.lookupNode(n,c);return 20}catch(m){}return g.nodePermissions(n,"wx")},mayDelete:(n,c,u)=>{var m;try{m=g.lookupNode(n,c)}catch(S){return S.errno}var E=g.nodePermissions(n,"wx");if(E)return E;if(u){if(!g.isDir(m.mode))return 54;if(g.isRoot(m)||g.getPath(m)===g.cwd())return 10}else if(g.isDir(m.mode))return 31;return 0},mayOpen:(n,c)=>n?g.isLink(n.mode)?32:g.isDir(n.mode)&&(g.flagsToPermissionString(c)!=="r"||c&512)?31:g.nodePermissions(n,g.flagsToPermissionString(c)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var n=0;n<=g.MAX_OPEN_FDS;n++)if(!g.streams[n])return n;throw new g.ErrnoError(33)},getStreamChecked:n=>{var c=g.getStream(n);if(!c)throw new g.ErrnoError(8);return c},getStream:n=>g.streams[n],createStream:(n,c=-1)=>(g.FSStream||(g.FSStream=function(){this.shared={}},g.FSStream.prototype={},Object.defineProperties(g.FSStream.prototype,{object:{get(){return this.node},set(u){this.node=u}},isRead:{get(){return(this.flags&2097155)!==1}},isWrite:{get(){return(this.flags&2097155)!==0}},isAppend:{get(){return this.flags&1024}},flags:{get(){return this.shared.flags},set(u){this.shared.flags=u}},position:{get(){return this.shared.position},set(u){this.shared.position=u}}})),n=Object.assign(new g.FSStream,n),c==-1&&(c=g.nextfd()),n.fd=c,g.streams[c]=n,n),closeStream:n=>{g.streams[n]=null},chrdev_stream_ops:{open:n=>{var c=g.getDevice(n.node.rdev);n.stream_ops=c.stream_ops,n.stream_ops.open&&n.stream_ops.open(n)},llseek:()=>{throw new g.ErrnoError(70)}},major:n=>n>>8,minor:n=>n&255,makedev:(n,c)=>n<<8|c,registerDevice:(n,c)=>{g.devices[n]={stream_ops:c}},getDevice:n=>g.devices[n],getMounts:n=>{for(var c=[],u=[n];u.length;){var m=u.pop();c.push(m),u.push.apply(u,m.mounts)}return c},syncfs:(n,c)=>{typeof n=="function"&&(c=n,n=!1),g.syncFSRequests++,g.syncFSRequests>1&&Xe(`warning: ${g.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var u=g.getMounts(g.root.mount),m=0;function E(b){return g.syncFSRequests--,c(b)}function S(b){if(b)return S.errored?void 0:(S.errored=!0,E(b));++m>=u.length&&E(null)}u.forEach(b=>{if(!b.type.syncfs)return S(null);b.type.syncfs(b,n,S)})},mount:(n,c,u)=>{var m=u==="/",E=!u,S;if(m&&g.root)throw new g.ErrnoError(10);if(!m&&!E){var b=g.lookupPath(u,{follow_mount:!1});if(u=b.path,S=b.node,g.isMountpoint(S))throw new g.ErrnoError(10);if(!g.isDir(S.mode))throw new g.ErrnoError(54)}var A={type:n,opts:c,mountpoint:u,mounts:[]},k=n.mount(A);return k.mount=A,A.root=k,m?g.root=k:S&&(S.mounted=A,S.mount&&S.mount.mounts.push(A)),k},unmount:n=>{var c=g.lookupPath(n,{follow_mount:!1});if(!g.isMountpoint(c.node))throw new g.ErrnoError(28);var u=c.node,m=u.mounted,E=g.getMounts(m);Object.keys(g.nameTable).forEach(b=>{for(var A=g.nameTable[b];A;){var k=A.name_next;E.includes(A.mount)&&g.destroyNode(A),A=k}}),u.mounted=null;var S=u.mount.mounts.indexOf(m);u.mount.mounts.splice(S,1)},lookup:(n,c)=>n.node_ops.lookup(n,c),mknod:(n,c,u)=>{var m=g.lookupPath(n,{parent:!0}),E=m.node,S=De.basename(n);if(!S||S==="."||S==="..")throw new g.ErrnoError(28);var b=g.mayCreate(E,S);if(b)throw new g.ErrnoError(b);if(!E.node_ops.mknod)throw new g.ErrnoError(63);return E.node_ops.mknod(E,S,c,u)},create:(n,c)=>(c=c!==void 0?c:438,c&=4095,c|=32768,g.mknod(n,c,0)),mkdir:(n,c)=>(c=c!==void 0?c:511,c&=1023,c|=16384,g.mknod(n,c,0)),mkdirTree:(n,c)=>{for(var u=n.split("/"),m="",E=0;E<u.length;++E)if(!!u[E]){m+="/"+u[E];try{g.mkdir(m,c)}catch(S){if(S.errno!=20)throw S}}},mkdev:(n,c,u)=>(typeof u=="undefined"&&(u=c,c=438),c|=8192,g.mknod(n,c,u)),symlink:(n,c)=>{if(!At.resolve(n))throw new g.ErrnoError(44);var u=g.lookupPath(c,{parent:!0}),m=u.node;if(!m)throw new g.ErrnoError(44);var E=De.basename(c),S=g.mayCreate(m,E);if(S)throw new g.ErrnoError(S);if(!m.node_ops.symlink)throw new g.ErrnoError(63);return m.node_ops.symlink(m,E,n)},rename:(n,c)=>{var u=De.dirname(n),m=De.dirname(c),E=De.basename(n),S=De.basename(c),b,A,k;if(b=g.lookupPath(n,{parent:!0}),A=b.node,b=g.lookupPath(c,{parent:!0}),k=b.node,!A||!k)throw new g.ErrnoError(44);if(A.mount!==k.mount)throw new g.ErrnoError(75);var x=g.lookupNode(A,E),K=At.relative(n,m);if(K.charAt(0)!==".")throw new g.ErrnoError(28);if(K=At.relative(c,u),K.charAt(0)!==".")throw new g.ErrnoError(55);var ie;try{ie=g.lookupNode(k,S)}catch(ue){}if(x!==ie){var te=g.isDir(x.mode),Q=g.mayDelete(A,E,te);if(Q)throw new g.ErrnoError(Q);if(Q=ie?g.mayDelete(k,S,te):g.mayCreate(k,S),Q)throw new g.ErrnoError(Q);if(!A.node_ops.rename)throw new g.ErrnoError(63);if(g.isMountpoint(x)||ie&&g.isMountpoint(ie))throw new g.ErrnoError(10);if(k!==A&&(Q=g.nodePermissions(A,"w"),Q))throw new g.ErrnoError(Q);g.hashRemoveNode(x);try{A.node_ops.rename(x,k,S)}catch(ue){throw ue}finally{g.hashAddNode(x)}}},rmdir:n=>{var c=g.lookupPath(n,{parent:!0}),u=c.node,m=De.basename(n),E=g.lookupNode(u,m),S=g.mayDelete(u,m,!0);if(S)throw new g.ErrnoError(S);if(!u.node_ops.rmdir)throw new g.ErrnoError(63);if(g.isMountpoint(E))throw new g.ErrnoError(10);u.node_ops.rmdir(u,m),g.destroyNode(E)},readdir:n=>{var c=g.lookupPath(n,{follow:!0}),u=c.node;if(!u.node_ops.readdir)throw new g.ErrnoError(54);return u.node_ops.readdir(u)},unlink:n=>{var c=g.lookupPath(n,{parent:!0}),u=c.node;if(!u)throw new g.ErrnoError(44);var m=De.basename(n),E=g.lookupNode(u,m),S=g.mayDelete(u,m,!1);if(S)throw new g.ErrnoError(S);if(!u.node_ops.unlink)throw new g.ErrnoError(63);if(g.isMountpoint(E))throw new g.ErrnoError(10);u.node_ops.unlink(u,m),g.destroyNode(E)},readlink:n=>{var c=g.lookupPath(n),u=c.node;if(!u)throw new g.ErrnoError(44);if(!u.node_ops.readlink)throw new g.ErrnoError(28);return At.resolve(g.getPath(u.parent),u.node_ops.readlink(u))},stat:(n,c)=>{var u=g.lookupPath(n,{follow:!c}),m=u.node;if(!m)throw new g.ErrnoError(44);if(!m.node_ops.getattr)throw new g.ErrnoError(63);return m.node_ops.getattr(m)},lstat:n=>g.stat(n,!0),chmod:(n,c,u)=>{var m;if(typeof n=="string"){var E=g.lookupPath(n,{follow:!u});m=E.node}else m=n;if(!m.node_ops.setattr)throw new g.ErrnoError(63);m.node_ops.setattr(m,{mode:c&4095|m.mode&-4096,timestamp:Date.now()})},lchmod:(n,c)=>{g.chmod(n,c,!0)},fchmod:(n,c)=>{var u=g.getStreamChecked(n);g.chmod(u.node,c)},chown:(n,c,u,m)=>{var E;if(typeof n=="string"){var S=g.lookupPath(n,{follow:!m});E=S.node}else E=n;if(!E.node_ops.setattr)throw new g.ErrnoError(63);E.node_ops.setattr(E,{timestamp:Date.now()})},lchown:(n,c,u)=>{g.chown(n,c,u,!0)},fchown:(n,c,u)=>{var m=g.getStreamChecked(n);g.chown(m.node,c,u)},truncate:(n,c)=>{if(c<0)throw new g.ErrnoError(28);var u;if(typeof n=="string"){var m=g.lookupPath(n,{follow:!0});u=m.node}else u=n;if(!u.node_ops.setattr)throw new g.ErrnoError(63);if(g.isDir(u.mode))throw new g.ErrnoError(31);if(!g.isFile(u.mode))throw new g.ErrnoError(28);var E=g.nodePermissions(u,"w");if(E)throw new g.ErrnoError(E);u.node_ops.setattr(u,{size:c,timestamp:Date.now()})},ftruncate:(n,c)=>{var u=g.getStreamChecked(n);if((u.flags&2097155)===0)throw new g.ErrnoError(28);g.truncate(u.node,c)},utime:(n,c,u)=>{var m=g.lookupPath(n,{follow:!0}),E=m.node;E.node_ops.setattr(E,{timestamp:Math.max(c,u)})},open:(n,c,u)=>{if(n==="")throw new g.ErrnoError(44);c=typeof c=="string"?pc(c):c,u=typeof u=="undefined"?438:u,c&64?u=u&4095|32768:u=0;var m;if(typeof n=="object")m=n;else{n=De.normalize(n);try{var E=g.lookupPath(n,{follow:!(c&131072)});m=E.node}catch(k){}}var S=!1;if(c&64)if(m){if(c&128)throw new g.ErrnoError(20)}else m=g.mknod(n,u,0),S=!0;if(!m)throw new g.ErrnoError(44);if(g.isChrdev(m.mode)&&(c&=-513),c&65536&&!g.isDir(m.mode))throw new g.ErrnoError(54);if(!S){var b=g.mayOpen(m,c);if(b)throw new g.ErrnoError(b)}c&512&&!S&&g.truncate(m,0),c&=-131713;var A=g.createStream({node:m,path:g.getPath(m),flags:c,seekable:!0,position:0,stream_ops:m.stream_ops,ungotten:[],error:!1});return A.stream_ops.open&&A.stream_ops.open(A),e.logReadFiles&&!(c&1)&&(g.readFiles||(g.readFiles={}),n in g.readFiles||(g.readFiles[n]=1)),A},close:n=>{if(g.isClosed(n))throw new g.ErrnoError(8);n.getdents&&(n.getdents=null);try{n.stream_ops.close&&n.stream_ops.close(n)}catch(c){throw c}finally{g.closeStream(n.fd)}n.fd=null},isClosed:n=>n.fd===null,llseek:(n,c,u)=>{if(g.isClosed(n))throw new g.ErrnoError(8);if(!n.seekable||!n.stream_ops.llseek)throw new g.ErrnoError(70);if(u!=0&&u!=1&&u!=2)throw new g.ErrnoError(28);return n.position=n.stream_ops.llseek(n,c,u),n.ungotten=[],n.position},read:(n,c,u,m,E)=>{if(m<0||E<0)throw new g.ErrnoError(28);if(g.isClosed(n))throw new g.ErrnoError(8);if((n.flags&2097155)===1)throw new g.ErrnoError(8);if(g.isDir(n.node.mode))throw new g.ErrnoError(31);if(!n.stream_ops.read)throw new g.ErrnoError(28);var S=typeof E!="undefined";if(!S)E=n.position;else if(!n.seekable)throw new g.ErrnoError(70);var b=n.stream_ops.read(n,c,u,m,E);return S||(n.position+=b),b},write:(n,c,u,m,E,S)=>{if(m<0||E<0)throw new g.ErrnoError(28);if(g.isClosed(n))throw new g.ErrnoError(8);if((n.flags&2097155)===0)throw new g.ErrnoError(8);if(g.isDir(n.node.mode))throw new g.ErrnoError(31);if(!n.stream_ops.write)throw new g.ErrnoError(28);n.seekable&&n.flags&1024&&g.llseek(n,0,2);var b=typeof E!="undefined";if(!b)E=n.position;else if(!n.seekable)throw new g.ErrnoError(70);var A=n.stream_ops.write(n,c,u,m,E,S);return b||(n.position+=A),A},allocate:(n,c,u)=>{if(g.isClosed(n))throw new g.ErrnoError(8);if(c<0||u<=0)throw new g.ErrnoError(28);if((n.flags&2097155)===0)throw new g.ErrnoError(8);if(!g.isFile(n.node.mode)&&!g.isDir(n.node.mode))throw new g.ErrnoError(43);if(!n.stream_ops.allocate)throw new g.ErrnoError(138);n.stream_ops.allocate(n,c,u)},mmap:(n,c,u,m,E)=>{if((m&2)!==0&&(E&2)===0&&(n.flags&2097155)!==2)throw new g.ErrnoError(2);if((n.flags&2097155)===1)throw new g.ErrnoError(2);if(!n.stream_ops.mmap)throw new g.ErrnoError(43);return n.stream_ops.mmap(n,c,u,m,E)},msync:(n,c,u,m,E)=>n.stream_ops.msync?n.stream_ops.msync(n,c,u,m,E):0,munmap:n=>0,ioctl:(n,c,u)=>{if(!n.stream_ops.ioctl)throw new g.ErrnoError(59);return n.stream_ops.ioctl(n,c,u)},readFile:(n,c={})=>{if(c.flags=c.flags||0,c.encoding=c.encoding||"binary",c.encoding!=="utf8"&&c.encoding!=="binary")throw new Error(`Invalid encoding type "${c.encoding}"`);var u,m=g.open(n,c.flags),E=g.stat(n),S=E.size,b=new Uint8Array(S);return g.read(m,b,0,S,0),c.encoding==="utf8"?u=oi(b,0):c.encoding==="binary"&&(u=b),g.close(m),u},writeFile:(n,c,u={})=>{u.flags=u.flags||577;var m=g.open(n,u.flags,u.mode);if(typeof c=="string"){var E=new Uint8Array(si(c)+1),S=vn(c,E,0,E.length);g.write(m,E,0,S,void 0,u.canOwn)}else if(ArrayBuffer.isView(c))g.write(m,c,0,c.byteLength,void 0,u.canOwn);else throw new Error("Unsupported data type");g.close(m)},cwd:()=>g.currentPath,chdir:n=>{var c=g.lookupPath(n,{follow:!0});if(c.node===null)throw new g.ErrnoError(44);if(!g.isDir(c.node.mode))throw new g.ErrnoError(54);var u=g.nodePermissions(c.node,"x");if(u)throw new g.ErrnoError(u);g.currentPath=c.path},createDefaultDirectories:()=>{g.mkdir("/tmp"),g.mkdir("/home"),g.mkdir("/home/web_user")},createDefaultDevices:()=>{g.mkdir("/dev"),g.registerDevice(g.makedev(1,3),{read:()=>0,write:(m,E,S,b,A)=>b}),g.mkdev("/dev/null",g.makedev(1,3)),Lr.register(g.makedev(5,0),Lr.default_tty_ops),Lr.register(g.makedev(6,0),Lr.default_tty1_ops),g.mkdev("/dev/tty",g.makedev(5,0)),g.mkdev("/dev/tty1",g.makedev(6,0));var n=new Uint8Array(1024),c=0,u=()=>(c===0&&(c=no(n).byteLength),n[--c]);g.createDevice("/dev","random",u),g.createDevice("/dev","urandom",u),g.mkdir("/dev/shm"),g.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{g.mkdir("/proc");var n=g.mkdir("/proc/self");g.mkdir("/proc/self/fd"),g.mount({mount:()=>{var c=g.createNode(n,"fd",16895,73);return c.node_ops={lookup:(u,m)=>{var E=+m,S=g.getStreamChecked(E),b={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>S.path}};return b.parent=b,b}},c}},{},"/proc/self/fd")},createStandardStreams:()=>{e.stdin?g.createDevice("/dev","stdin",e.stdin):g.symlink("/dev/tty","/dev/stdin"),e.stdout?g.createDevice("/dev","stdout",null,e.stdout):g.symlink("/dev/tty","/dev/stdout"),e.stderr?g.createDevice("/dev","stderr",null,e.stderr):g.symlink("/dev/tty1","/dev/stderr");var n=g.open("/dev/stdin",0),c=g.open("/dev/stdout",1),u=g.open("/dev/stderr",1)},ensureErrnoError:()=>{g.ErrnoError||(g.ErrnoError=function(c,u){this.name="ErrnoError",this.node=u,this.setErrno=function(m){this.errno=m},this.setErrno(c),this.message="FS error"},g.ErrnoError.prototype=new Error,g.ErrnoError.prototype.constructor=g.ErrnoError,[44].forEach(n=>{g.genericErrors[n]=new g.ErrnoError(n),g.genericErrors[n].stack="<generic error, no stack>"}))},staticInit:()=>{g.ensureErrnoError(),g.nameTable=new Array(4096),g.mount(he,{},"/"),g.createDefaultDirectories(),g.createDefaultDevices(),g.createSpecialDirectories(),g.filesystems={MEMFS:he}},init:(n,c,u)=>{g.init.initialized=!0,g.ensureErrnoError(),e.stdin=n||e.stdin,e.stdout=c||e.stdout,e.stderr=u||e.stderr,g.createStandardStreams()},quit:()=>{g.init.initialized=!1;for(var n=0;n<g.streams.length;n++){var c=g.streams[n];!c||g.close(c)}},findObject:(n,c)=>{var u=g.analyzePath(n,c);return u.exists?u.object:null},analyzePath:(n,c)=>{try{var u=g.lookupPath(n,{follow:!c});n=u.path}catch(E){}var m={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var u=g.lookupPath(n,{parent:!0});m.parentExists=!0,m.parentPath=u.path,m.parentObject=u.node,m.name=De.basename(n),u=g.lookupPath(n,{follow:!c}),m.exists=!0,m.path=u.path,m.object=u.node,m.name=u.node.name,m.isRoot=u.path==="/"}catch(E){m.error=E.errno}return m},createPath:(n,c,u,m)=>{n=typeof n=="string"?n:g.getPath(n);for(var E=c.split("/").reverse();E.length;){var S=E.pop();if(!!S){var b=De.join2(n,S);try{g.mkdir(b)}catch(A){}n=b}}return b},createFile:(n,c,u,m,E)=>{var S=De.join2(typeof n=="string"?n:g.getPath(n),c),b=ss(m,E);return g.create(S,b)},createDataFile:(n,c,u,m,E,S)=>{var b=c;n&&(n=typeof n=="string"?n:g.getPath(n),b=c?De.join2(n,c):n);var A=ss(m,E),k=g.create(b,A);if(u){if(typeof u=="string"){for(var x=new Array(u.length),K=0,ie=u.length;K<ie;++K)x[K]=u.charCodeAt(K);u=x}g.chmod(k,A|146);var te=g.open(k,577);g.write(te,u,0,u.length,0,S),g.close(te),g.chmod(k,A)}return k},createDevice:(n,c,u,m)=>{var E=De.join2(typeof n=="string"?n:g.getPath(n),c),S=ss(!!u,!!m);g.createDevice.major||(g.createDevice.major=64);var b=g.makedev(g.createDevice.major++,0);return g.registerDevice(b,{open:A=>{A.seekable=!1},close:A=>{m&&m.buffer&&m.buffer.length&&m(10)},read:(A,k,x,K,ie)=>{for(var te=0,Q=0;Q<K;Q++){var ue;try{ue=u()}catch($e){throw new g.ErrnoError(29)}if(ue===void 0&&te===0)throw new g.ErrnoError(6);if(ue==null)break;te++,k[x+Q]=ue}return te&&(A.node.timestamp=Date.now()),te},write:(A,k,x,K,ie)=>{for(var te=0;te<K;te++)try{m(k[x+te])}catch(Q){throw new g.ErrnoError(29)}return K&&(A.node.timestamp=Date.now()),te}}),g.mkdev(E,S,b)},forceLoadFile:n=>{if(n.isDevice||n.isFolder||n.link||n.contents)return!0;if(typeof XMLHttpRequest!="undefined")throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(j)try{n.contents=Kt(j(n.url),!0),n.usedBytes=n.contents.length}catch(c){throw new g.ErrnoError(29)}else throw new Error("Cannot load without read() or XMLHttpRequest.")},createLazyFile:(n,c,u,m,E)=>{function S(){this.lengthKnown=!1,this.chunks=[]}if(S.prototype.get=function(Q){if(!(Q>this.length-1||Q<0)){var ue=Q%this.chunkSize,$e=Q/this.chunkSize|0;return this.getter($e)[ue]}},S.prototype.setDataGetter=function(Q){this.getter=Q},S.prototype.cacheLength=function(){var Q=new XMLHttpRequest;if(Q.open("HEAD",u,!1),Q.send(null),!(Q.status>=200&&Q.status<300||Q.status===304))throw new Error("Couldn't load "+u+". Status: "+Q.status);var ue=Number(Q.getResponseHeader("Content-length")),$e,qe=($e=Q.getResponseHeader("Accept-Ranges"))&&$e==="bytes",lt=($e=Q.getResponseHeader("Content-Encoding"))&&$e==="gzip",kt=1024*1024;qe||(kt=ue);var Ze=(tr,ui)=>{if(tr>ui)throw new Error("invalid range ("+tr+", "+ui+") or no bytes requested!");if(ui>ue-1)throw new Error("only "+ue+" bytes available! programmer error!");var pt=new XMLHttpRequest;if(pt.open("GET",u,!1),ue!==kt&&pt.setRequestHeader("Range","bytes="+tr+"-"+ui),pt.responseType="arraybuffer",pt.overrideMimeType&&pt.overrideMimeType("text/plain; charset=x-user-defined"),pt.send(null),!(pt.status>=200&&pt.status<300||pt.status===304))throw new Error("Couldn't load "+u+". Status: "+pt.status);return pt.response!==void 0?new Uint8Array(pt.response||[]):Kt(pt.responseText||"",!0)},fo=this;fo.setDataGetter(tr=>{var ui=tr*kt,pt=(tr+1)*kt-1;if(pt=Math.min(pt,ue-1),typeof fo.chunks[tr]=="undefined"&&(fo.chunks[tr]=Ze(ui,pt)),typeof fo.chunks[tr]=="undefined")throw new Error("doXHR failed!");return fo.chunks[tr]}),(lt||!ue)&&(kt=ue=1,ue=this.getter(0).length,kt=ue,Bt("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=ue,this._chunkSize=kt,this.lengthKnown=!0},typeof XMLHttpRequest!="undefined"){if(!T)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var b=new S;Object.defineProperties(b,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var A={isDevice:!1,contents:b}}else var A={isDevice:!1,url:u};var k=g.createFile(n,c,A,m,E);A.contents?k.contents=A.contents:A.url&&(k.contents=null,k.url=A.url),Object.defineProperties(k,{usedBytes:{get:function(){return this.contents.length}}});var x={},K=Object.keys(k.stream_ops);K.forEach(te=>{var Q=k.stream_ops[te];x[te]=function(){return g.forceLoadFile(k),Q.apply(null,arguments)}});function ie(te,Q,ue,$e,qe){var lt=te.node.contents;if(qe>=lt.length)return 0;var kt=Math.min(lt.length-qe,$e);if(lt.slice)for(var Ze=0;Ze<kt;Ze++)Q[ue+Ze]=lt[qe+Ze];else for(var Ze=0;Ze<kt;Ze++)Q[ue+Ze]=lt.get(qe+Ze);return kt}return x.read=(te,Q,ue,$e,qe)=>(g.forceLoadFile(k),ie(te,Q,ue,$e,qe)),x.mmap=(te,Q,ue,$e,qe)=>{g.forceLoadFile(k);var lt=dc(Q);if(!lt)throw new g.ErrnoError(48);return ie(te,Pe,lt,Q,ue),{ptr:lt,allocated:!0}},k.stream_ops=x,k}},mc=(n,c)=>n?oi(tt,n,c):"",Qe={DEFAULT_POLLMASK:5,calculateAt:function(n,c,u){if(De.isAbs(c))return c;var m;if(n===-100)m=g.cwd();else{var E=Qe.getStreamFromFD(n);m=E.path}if(c.length==0){if(!u)throw new g.ErrnoError(44);return m}return De.join2(m,c)},doStat:function(n,c,u){try{var m=n(c)}catch(A){if(A&&A.node&&De.normalize(c)!==De.normalize(g.getPath(A.node)))return-54;throw A}P[u>>2]=m.dev,P[u+4>>2]=m.mode,Me[u+8>>2]=m.nlink,P[u+12>>2]=m.uid,P[u+16>>2]=m.gid,P[u+20>>2]=m.rdev,He=[m.size>>>0,(ce=m.size,+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[u+24>>2]=He[0],P[u+28>>2]=He[1],P[u+32>>2]=4096,P[u+36>>2]=m.blocks;var E=m.atime.getTime(),S=m.mtime.getTime(),b=m.ctime.getTime();return He=[Math.floor(E/1e3)>>>0,(ce=Math.floor(E/1e3),+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[u+40>>2]=He[0],P[u+44>>2]=He[1],Me[u+48>>2]=E%1e3*1e3,He=[Math.floor(S/1e3)>>>0,(ce=Math.floor(S/1e3),+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[u+56>>2]=He[0],P[u+60>>2]=He[1],Me[u+64>>2]=S%1e3*1e3,He=[Math.floor(b/1e3)>>>0,(ce=Math.floor(b/1e3),+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[u+72>>2]=He[0],P[u+76>>2]=He[1],Me[u+80>>2]=b%1e3*1e3,He=[m.ino>>>0,(ce=m.ino,+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[u+88>>2]=He[0],P[u+92>>2]=He[1],0},doMsync:function(n,c,u,m,E){if(!g.isFile(c.node.mode))throw new g.ErrnoError(43);if(m&2)return 0;var S=tt.slice(n,n+u);g.msync(c,S,E,u,m)},varargs:void 0,get(){Qe.varargs+=4;var n=P[Qe.varargs-4>>2];return n},getStr(n){var c=mc(n);return c},getStreamFromFD:function(n){var c=g.getStreamChecked(n);return c}};function Cn(n,c,u){Qe.varargs=u;try{var m=Qe.getStreamFromFD(n);switch(c){case 0:{var E=Qe.get();if(E<0)return-28;var S;return S=g.createStream(m,E),S.fd}case 1:case 2:return 0;case 3:return m.flags;case 4:{var E=Qe.get();return m.flags|=E,0}case 5:{var E=Qe.get(),b=0;return Yt[E+b>>1]=2,0}case 6:case 7:return 0;case 16:case 8:return-28;case 9:return xt(28),-1;default:return-28}}catch(A){if(typeof g=="undefined"||A.name!=="ErrnoError")throw A;return-A.errno}}function ao(n,c,u,m){Qe.varargs=m;try{c=Qe.getStr(c),c=Qe.calculateAt(n,c);var E=m?Qe.get():0;return g.open(c,u,E).fd}catch(S){if(typeof g=="undefined"||S.name!=="ErrnoError")throw S;return-S.errno}}function hl(n,c,u,m,E){}function Dn(n){switch(n){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${n}`)}}function co(){for(var n=new Array(256),c=0;c<256;++c)n[c]=String.fromCharCode(c);hc=n}var hc=void 0;function Mt(n){for(var c="",u=n;tt[u];)c+=hc[tt[u++]];return c}var Er={},ni={},Ur={},Oi=void 0;function xe(n){throw new Oi(n)}var fc=void 0;function ns(n){throw new fc(n)}function uo(n,c,u){n.forEach(function(A){Ur[A]=c});function m(A){var k=u(A);k.length!==n.length&&ns("Mismatched type converter count");for(var x=0;x<n.length;++x)Tr(n[x],k[x])}var E=new Array(c.length),S=[],b=0;c.forEach((A,k)=>{ni.hasOwnProperty(A)?E[k]=ni[A]:(S.push(A),Er.hasOwnProperty(A)||(Er[A]=[]),Er[A].push(()=>{E[k]=ni[A],++b,b===S.length&&m(E)}))}),S.length===0&&m(E)}function Vr(n,c,u={}){var m=c.name;if(n||xe(`type "${m}" must have a positive integer typeid pointer`),ni.hasOwnProperty(n)){if(u.ignoreDuplicateRegistrations)return;xe(`Cannot register type '${m}' twice`)}if(ni[n]=c,delete Ur[n],Er.hasOwnProperty(n)){var E=Er[n];delete Er[n],E.forEach(S=>S())}}function Tr(n,c,u={}){if(!("argPackAdvance"in c))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Vr(n,c,u)}function fl(n,c,u,m,E){var S=Dn(u);c=Mt(c),Tr(n,{name:c,fromWireType:function(b){return!!b},toWireType:function(b,A){return A?m:E},argPackAdvance:8,readValueFromPointer:function(b){var A;if(u===1)A=Pe;else if(u===2)A=Yt;else if(u===4)A=P;else throw new TypeError("Unknown boolean type size: "+c);return this.fromWireType(A[b>>S])},destructorFunction:null})}function as(n){if(!(this instanceof Sr)||!(n instanceof Sr))return!1;for(var c=this.$$.ptrType.registeredClass,u=this.$$.ptr,m=n.$$.ptrType.registeredClass,E=n.$$.ptr;c.baseClass;)u=c.upcast(u),c=c.baseClass;for(;m.baseClass;)E=m.upcast(E),m=m.baseClass;return c===m&&u===E}function Nn(n){return{count:n.count,deleteScheduled:n.deleteScheduled,preservePointerOnDelete:n.preservePointerOnDelete,ptr:n.ptr,ptrType:n.ptrType,smartPtr:n.smartPtr,smartPtrType:n.smartPtrType}}function cs(n){function c(u){return u.$$.ptrType.registeredClass.name}xe(c(n)+" instance already deleted")}var wn=!1;function _c(n){}function xn(n){n.smartPtr?n.smartPtrType.rawDestructor(n.smartPtr):n.ptrType.registeredClass.rawDestructor(n.ptr)}function gc(n){n.count.value-=1;var c=n.count.value===0;c&&xn(n)}function Ec(n,c,u){if(c===u)return n;if(u.baseClass===void 0)return null;var m=Ec(n,c,u.baseClass);return m===null?null:u.downcast(m)}var Tc={};function ds(){return Object.keys(mo).length}function _l(){var n=[];for(var c in mo)mo.hasOwnProperty(c)&&n.push(mo[c]);return n}var lo=[];function Mn(){for(;lo.length;){var n=lo.pop();n.$$.deleteScheduled=!1,n.delete()}}var po=void 0;function Ir(n){po=n,lo.length&&po&&po(Mn)}function gl(){e.getInheritedInstanceCount=ds,e.getLiveInheritedInstances=_l,e.flushPendingDeletes=Mn,e.setDelayFunction=Ir}var mo={};function us(n,c){for(c===void 0&&xe("ptr should not be undefined");n.baseClass;)c=n.upcast(c),n=n.baseClass;return c}function Ic(n,c){return c=us(n,c),mo[c]}function ls(n,c){(!c.ptrType||!c.ptr)&&ns("makeClassHandle requires ptr and ptrType");var u=!!c.smartPtrType,m=!!c.smartPtr;return u!==m&&ns("Both smartPtrType and smartPtr must be specified"),c.count={value:1},ur(Object.create(n,{$$:{value:c}}))}function El(n){var c=this.getPointee(n);if(!c)return this.destructor(n),null;var u=Ic(this.registeredClass,c);if(u!==void 0){if(u.$$.count.value===0)return u.$$.ptr=c,u.$$.smartPtr=n,u.clone();var m=u.clone();return this.destructor(n),m}function E(){return this.isSmartPointer?ls(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:c,smartPtrType:this,smartPtr:n}):ls(this.registeredClass.instancePrototype,{ptrType:this,ptr:n})}var S=this.registeredClass.getActualType(c),b=Tc[S];if(!b)return E.call(this);var A;this.isConst?A=b.constPointerType:A=b.pointerType;var k=Ec(c,this.registeredClass,A.registeredClass);return k===null?E.call(this):this.isSmartPointer?ls(A.registeredClass.instancePrototype,{ptrType:A,ptr:k,smartPtrType:this,smartPtr:n}):ls(A.registeredClass.instancePrototype,{ptrType:A,ptr:k})}var ur=function(n){return typeof FinalizationRegistry=="undefined"?(ur=c=>c,n):(wn=new FinalizationRegistry(c=>{gc(c.$$)}),ur=c=>{var u=c.$$,m=!!u.smartPtr;if(m){var E={$$:u};wn.register(c,E,c)}return c},_c=c=>wn.unregister(c),ur(n))};function Tl(){if(this.$$.ptr||cs(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var n=ur(Object.create(Object.getPrototypeOf(this),{$$:{value:Nn(this.$$)}}));return n.$$.count.value+=1,n.$$.deleteScheduled=!1,n}function Sc(){this.$$.ptr||cs(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&xe("Object already scheduled for deletion"),_c(this),gc(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function yc(){return!this.$$.ptr}function On(){return this.$$.ptr||cs(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&xe("Object already scheduled for deletion"),lo.push(this),lo.length===1&&po&&po(Mn),this.$$.deleteScheduled=!0,this}function Il(){Sr.prototype.isAliasOf=as,Sr.prototype.clone=Tl,Sr.prototype.delete=Sc,Sr.prototype.isDeleted=yc,Sr.prototype.deleteLater=On}function Sr(){}var Sl=48,Ac=57;function ho(n){if(n===void 0)return"_unknown";n=n.replace(/[^a-zA-Z0-9_]/g,"$");var c=n.charCodeAt(0);return c>=Sl&&c<=Ac?`_${n}`:n}function Pn(n,c){return n=ho(n),{[n]:function(){return c.apply(this,arguments)}}[n]}function bc(n,c,u){if(n[c].overloadTable===void 0){var m=n[c];n[c]=function(){return n[c].overloadTable.hasOwnProperty(arguments.length)||xe(`Function '${u}' called with an invalid number of arguments (${arguments.length}) - expects one of (${n[c].overloadTable})!`),n[c].overloadTable[arguments.length].apply(this,arguments)},n[c].overloadTable=[],n[c].overloadTable[m.argCount]=m}}function yl(n,c,u){e.hasOwnProperty(n)?((u===void 0||e[n].overloadTable!==void 0&&e[n].overloadTable[u]!==void 0)&&xe(`Cannot register public name '${n}' twice`),bc(e,n,n),e.hasOwnProperty(u)&&xe(`Cannot register multiple overloads of a function with the same number of arguments (${u})!`),e[n].overloadTable[u]=c):(e[n]=c,u!==void 0&&(e[n].numArguments=u))}function vc(n,c,u,m,E,S,b,A){this.name=n,this.constructor=c,this.instancePrototype=u,this.rawDestructor=m,this.baseClass=E,this.getActualType=S,this.upcast=b,this.downcast=A,this.pureVirtualFunctions=[]}function Ot(n,c,u){for(;c!==u;)c.upcast||xe(`Expected null or instance of ${u.name}, got an instance of ${c.name}`),n=c.upcast(n),c=c.baseClass;return n}function Rc(n,c){if(c===null)return this.isReference&&xe(`null is not a valid ${this.name}`),0;c.$$||xe(`Cannot pass "${Vn(c)}" as a ${this.name}`),c.$$.ptr||xe(`Cannot pass deleted object as a pointer of type ${this.name}`);var u=c.$$.ptrType.registeredClass,m=Ot(c.$$.ptr,u,this.registeredClass);return m}function Al(n,c){var u;if(c===null)return this.isReference&&xe(`null is not a valid ${this.name}`),this.isSmartPointer?(u=this.rawConstructor(),n!==null&&n.push(this.rawDestructor,u),u):0;c.$$||xe(`Cannot pass "${Vn(c)}" as a ${this.name}`),c.$$.ptr||xe(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&c.$$.ptrType.isConst&&xe(`Cannot convert argument of type ${c.$$.smartPtrType?c.$$.smartPtrType.name:c.$$.ptrType.name} to parameter type ${this.name}`);var m=c.$$.ptrType.registeredClass;if(u=Ot(c.$$.ptr,m,this.registeredClass),this.isSmartPointer)switch(c.$$.smartPtr===void 0&&xe("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:c.$$.smartPtrType===this?u=c.$$.smartPtr:xe(`Cannot convert argument of type ${c.$$.smartPtrType?c.$$.smartPtrType.name:c.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:u=c.$$.smartPtr;break;case 2:if(c.$$.smartPtrType===this)u=c.$$.smartPtr;else{var E=c.clone();u=this.rawShare(u,ms.toHandle(function(){E.delete()})),n!==null&&n.push(this.rawDestructor,u)}break;default:xe("Unsupporting sharing policy")}return u}function bl(n,c){if(c===null)return this.isReference&&xe(`null is not a valid ${this.name}`),0;c.$$||xe(`Cannot pass "${Vn(c)}" as a ${this.name}`),c.$$.ptr||xe(`Cannot pass deleted object as a pointer of type ${this.name}`),c.$$.ptrType.isConst&&xe(`Cannot convert argument of type ${c.$$.ptrType.name} to parameter type ${this.name}`);var u=c.$$.ptrType.registeredClass,m=Ot(c.$$.ptr,u,this.registeredClass);return m}function ai(n){return this.fromWireType(P[n>>2])}function vl(n){return this.rawGetPointee&&(n=this.rawGetPointee(n)),n}function kn(n){this.rawDestructor&&this.rawDestructor(n)}function Rl(n){n!==null&&n.delete()}function Cl(){yr.prototype.getPointee=vl,yr.prototype.destructor=kn,yr.prototype.argPackAdvance=8,yr.prototype.readValueFromPointer=ai,yr.prototype.deleteObject=Rl,yr.prototype.fromWireType=El}function yr(n,c,u,m,E,S,b,A,k,x,K){this.name=n,this.registeredClass=c,this.isReference=u,this.isConst=m,this.isSmartPointer=E,this.pointeeType=S,this.sharingPolicy=b,this.rawGetPointee=A,this.rawConstructor=k,this.rawShare=x,this.rawDestructor=K,!E&&c.baseClass===void 0?m?(this.toWireType=Rc,this.destructorFunction=null):(this.toWireType=bl,this.destructorFunction=null):this.toWireType=Al}function Dl(n,c,u){e.hasOwnProperty(n)||ns("Replacing nonexistant public symbol"),e[n].overloadTable!==void 0&&u!==void 0?e[n].overloadTable[u]=c:(e[n]=c,e[n].argCount=u)}var Nl=(n,c,u)=>{var m=e["dynCall_"+n];return u&&u.length?m.apply(null,[c].concat(u)):m.call(null,c)},ps=[],Cc=n=>{var c=ps[n];return c||(n>=ps.length&&(ps.length=n+1),ps[n]=c=En.get(n)),c},wl=(n,c,u)=>{if(n.includes("j"))return Nl(n,c,u);var m=Cc(c).apply(null,u);return m},Dc=(n,c)=>{var u=[];return function(){return u.length=0,Object.assign(u,arguments),wl(n,c,u)}};function ci(n,c){n=Mt(n);function u(){return n.includes("j")?Dc(n,c):Cc(c)}var m=u();return typeof m!="function"&&xe(`unknown function pointer with signature ${n}: ${c}`),m}function Nc(n,c){var u=Pn(c,function(m){this.name=c,this.message=m;var E=new Error(m).stack;E!==void 0&&(this.stack=this.toString()+`
|
|
50
|
+
`+E.replace(/^Error(:[^\n]*)?\n/,""))});return u.prototype=Object.create(n.prototype),u.prototype.constructor=u,u.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},u}var wc=void 0;function Ln(n){var c=Mf(n),u=Mt(c);return di(c),u}function Un(n,c){var u=[],m={};function E(S){if(!m[S]&&!ni[S]){if(Ur[S]){Ur[S].forEach(E);return}u.push(S),m[S]=!0}}throw c.forEach(E),new wc(`${n}: `+u.map(Ln).join([", "]))}function xl(n,c,u,m,E,S,b,A,k,x,K,ie,te){K=Mt(K),S=ci(E,S),A&&(A=ci(b,A)),x&&(x=ci(k,x)),te=ci(ie,te);var Q=ho(K);yl(Q,function(){Un(`Cannot construct ${K} due to unbound types`,[m])}),uo([n,c,u],m?[m]:[],function(ue){ue=ue[0];var $e,qe;m?($e=ue.registeredClass,qe=$e.instancePrototype):qe=Sr.prototype;var lt=Pn(Q,function(){if(Object.getPrototypeOf(this)!==kt)throw new Oi("Use 'new' to construct "+K);if(Ze.constructor_body===void 0)throw new Oi(K+" has no accessible constructor");var pt=Ze.constructor_body[arguments.length];if(pt===void 0)throw new Oi(`Tried to invoke ctor of ${K} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(Ze.constructor_body).toString()}) parameters instead!`);return pt.apply(this,arguments)}),kt=Object.create(qe,{constructor:{value:lt}});lt.prototype=kt;var Ze=new vc(K,lt,kt,te,$e,S,A,x);Ze.baseClass&&(Ze.baseClass.__derivedClasses===void 0&&(Ze.baseClass.__derivedClasses=[]),Ze.baseClass.__derivedClasses.push(Ze));var fo=new yr(K,Ze,!0,!1,!1),tr=new yr(K+"*",Ze,!1,!1,!1),ui=new yr(K+" const*",Ze,!1,!0,!1);return Tc[n]={pointerType:tr,constPointerType:ui},Dl(Q,lt),[fo,tr,ui]})}function xc(n,c){for(var u=[],m=0;m<n;m++)u.push(Me[c+m*4>>2]);return u}function Ml(n){for(;n.length;){var c=n.pop(),u=n.pop();u(c)}}function Mc(n,c){if(!(n instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof n} which is not a function`);var u=Pn(n.name||"unknownFunctionName",function(){});u.prototype=n.prototype;var m=new u,E=n.apply(m,c);return E instanceof Object?E:m}function Oc(n,c,u,m,E,S){var b=c.length;b<2&&xe("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var A=c[1]!==null&&u!==null,k=!1,x=1;x<c.length;++x)if(c[x]!==null&&c[x].destructorFunction===void 0){k=!0;break}for(var K=c[0].name!=="void",ie="",te="",x=0;x<b-2;++x)ie+=(x!==0?", ":"")+"arg"+x,te+=(x!==0?", ":"")+"arg"+x+"Wired";var Q=`
|
|
51
51
|
return function ${ho(n)}(${ie}) {
|
|
52
52
|
if (arguments.length !== ${b-2}) {
|
|
53
53
|
throwBindingError('function ${n} called with ${arguments.length} arguments, expected ${b-2} args!');
|
|
@@ -60,14 +60,14 @@ void main() {
|
|
|
60
60
|
`,$e.push(lt+"_dtor"),qe.push(c[x].destructorFunction))}return K&&(Q+=`var ret = retType.fromWireType(rv);
|
|
61
61
|
return ret;
|
|
62
62
|
`),Q+=`}
|
|
63
|
-
`,$e.push(Q),Mc(Function,$e).apply(null,qe)}function Ol(n,c,u,m,E,S){var b=xc(c,u);E=ci(m,E),uo([],[n],function(A){A=A[0];var k=`constructor ${A.name}`;if(A.registeredClass.constructor_body===void 0&&(A.registeredClass.constructor_body=[]),A.registeredClass.constructor_body[c-1]!==void 0)throw new Oi(`Cannot register multiple constructors with identical number of parameters (${c-1}) for class '${A.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return A.registeredClass.constructor_body[c-1]=()=>{
|
|
63
|
+
`,$e.push(Q),Mc(Function,$e).apply(null,qe)}function Ol(n,c,u,m,E,S){var b=xc(c,u);E=ci(m,E),uo([],[n],function(A){A=A[0];var k=`constructor ${A.name}`;if(A.registeredClass.constructor_body===void 0&&(A.registeredClass.constructor_body=[]),A.registeredClass.constructor_body[c-1]!==void 0)throw new Oi(`Cannot register multiple constructors with identical number of parameters (${c-1}) for class '${A.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return A.registeredClass.constructor_body[c-1]=()=>{Un(`Cannot construct ${A.name} due to unbound types`,b)},uo([],b,function(x){return x.splice(1,0,null),A.registeredClass.constructor_body[c-1]=Oc(k,x,null,E,S),[]}),[]})}function Pl(n,c,u,m,E,S,b,A,k){var x=xc(u,m);c=Mt(c),S=ci(E,S),uo([],[n],function(K){K=K[0];var ie=`${K.name}.${c}`;c.startsWith("@@")&&(c=Symbol[c.substring(2)]),A&&K.registeredClass.pureVirtualFunctions.push(c);function te(){Un(`Cannot call ${ie} due to unbound types`,x)}var Q=K.registeredClass.instancePrototype,ue=Q[c];return ue===void 0||ue.overloadTable===void 0&&ue.className!==K.name&&ue.argCount===u-2?(te.argCount=u-2,te.className=K.name,Q[c]=te):(bc(Q,c,ie),Q[c].overloadTable[u-2]=te),uo([],x,function($e){var qe=Oc(ie,$e,K,S,b,k);return Q[c].overloadTable===void 0?(qe.argCount=u-2,Q[c]=qe):Q[c].overloadTable[u-2]=qe,[]}),[]})}function kl(){Object.assign(Pc.prototype,{get(n){return this.allocated[n]},has(n){return this.allocated[n]!==void 0},allocate(n){var c=this.freelist.pop()||this.allocated.length;return this.allocated[c]=n,c},free(n){this.allocated[n]=void 0,this.freelist.push(n)}})}function Pc(){this.allocated=[void 0],this.freelist=[]}var Pt=new Pc;function kc(n){n>=Pt.reserved&&--Pt.get(n).refcount===0&&Pt.free(n)}function Ll(){for(var n=0,c=Pt.reserved;c<Pt.allocated.length;++c)Pt.allocated[c]!==void 0&&++n;return n}function Ul(){Pt.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Pt.reserved=Pt.allocated.length,e.count_emval_handles=Ll}var ms={toValue:n=>(n||xe("Cannot use deleted val. handle = "+n),Pt.get(n).value),toHandle:n=>{switch(n){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Pt.allocate({refcount:1,value:n})}}};function Lc(n,c){c=Mt(c),Tr(n,{name:c,fromWireType:function(u){var m=ms.toValue(u);return kc(u),m},toWireType:function(u,m){return ms.toHandle(m)},argPackAdvance:8,readValueFromPointer:ai,destructorFunction:null})}function Vn(n){if(n===null)return"null";var c=typeof n;return c==="object"||c==="array"||c==="function"?n.toString():""+n}function Vl(n,c){switch(c){case 2:return function(u){return this.fromWireType(gn[u>>2])};case 3:return function(u){return this.fromWireType(oc[u>>3])};default:throw new TypeError("Unknown float type: "+n)}}function Uc(n,c,u){var m=Dn(u);c=Mt(c),Tr(n,{name:c,fromWireType:function(E){return E},toWireType:function(E,S){return S},argPackAdvance:8,readValueFromPointer:Vl(c,m),destructorFunction:null})}function Bl(n,c,u){switch(c){case 0:return u?function(E){return Pe[E]}:function(E){return tt[E]};case 1:return u?function(E){return Yt[E>>1]}:function(E){return Zt[E>>1]};case 2:return u?function(E){return P[E>>2]}:function(E){return Me[E>>2]};default:throw new TypeError("Unknown integer type: "+n)}}function Fl(n,c,u,m,E){c=Mt(c),E===-1&&(E=4294967295);var S=Dn(u),b=ie=>ie;if(m===0){var A=32-8*u;b=ie=>ie<<A>>>A}var k=c.includes("unsigned"),x=(ie,te)=>{},K;k?K=function(ie,te){return x(te,this.name),te>>>0}:K=function(ie,te){return x(te,this.name),te},Tr(n,{name:c,fromWireType:b,toWireType:K,argPackAdvance:8,readValueFromPointer:Bl(c,S,m!==0),destructorFunction:null})}function $l(n,c,u){var m=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],E=m[c];function S(b){b=b>>2;var A=Me,k=A[b],x=A[b+1];return new E(A.buffer,x,k)}u=Mt(u),Tr(n,{name:u,fromWireType:S,argPackAdvance:8,readValueFromPointer:S},{ignoreDuplicateRegistrations:!0})}var Hl=(n,c,u)=>vn(n,tt,c,u);function Wl(n,c){c=Mt(c);var u=c==="std::string";Tr(n,{name:c,fromWireType:function(m){var E=Me[m>>2],S=m+4,b;if(u)for(var A=S,k=0;k<=E;++k){var x=S+k;if(k==E||tt[x]==0){var K=x-A,ie=mc(A,K);b===void 0?b=ie:(b+=String.fromCharCode(0),b+=ie),A=x+1}}else{for(var te=new Array(E),k=0;k<E;++k)te[k]=String.fromCharCode(tt[S+k]);b=te.join("")}return di(m),b},toWireType:function(m,E){E instanceof ArrayBuffer&&(E=new Uint8Array(E));var S,b=typeof E=="string";b||E instanceof Uint8Array||E instanceof Uint8ClampedArray||E instanceof Int8Array||xe("Cannot pass non-string to std::string"),u&&b?S=si(E):S=E.length;var A=Ql(4+S+1),k=A+4;if(Me[A>>2]=S,u&&b)Hl(E,k,S+1);else if(b)for(var x=0;x<S;++x){var K=E.charCodeAt(x);K>255&&(di(k),xe("String has UTF-16 code units that do not fit in 8 bits")),tt[k+x]=K}else for(var x=0;x<S;++x)tt[k+x]=E[x];return m!==null&&m.push(di,A),A},argPackAdvance:8,readValueFromPointer:ai,destructorFunction:function(m){di(m)}})}var Bn=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,Gl=(n,c)=>{for(var u=n,m=u>>1,E=m+c/2;!(m>=E)&&Zt[m];)++m;if(u=m<<1,u-n>32&&Bn)return Bn.decode(tt.subarray(n,u));for(var S="",b=0;!(b>=c/2);++b){var A=Yt[n+b*2>>1];if(A==0)break;S+=String.fromCharCode(A)}return S},jl=(n,c,u)=>{if(u===void 0&&(u=2147483647),u<2)return 0;u-=2;for(var m=c,E=u<n.length*2?u/2:n.length,S=0;S<E;++S){var b=n.charCodeAt(S);Yt[c>>1]=b,c+=2}return Yt[c>>1]=0,c-m},Nf=n=>n.length*2,ql=(n,c)=>{for(var u=0,m="";!(u>=c/4);){var E=P[n+u*4>>2];if(E==0)break;if(++u,E>=65536){var S=E-65536;m+=String.fromCharCode(55296|S>>10,56320|S&1023)}else m+=String.fromCharCode(E)}return m},Ar=(n,c,u)=>{if(u===void 0&&(u=2147483647),u<4)return 0;for(var m=c,E=m+u-4,S=0;S<n.length;++S){var b=n.charCodeAt(S);if(b>=55296&&b<=57343){var A=n.charCodeAt(++S);b=65536+((b&1023)<<10)|A&1023}if(P[c>>2]=b,c+=4,c+4>E)break}return P[c>>2]=0,c-m},Fn=n=>{for(var c=0,u=0;u<n.length;++u){var m=n.charCodeAt(u);m>=55296&&m<=57343&&++u,c+=4}return c},Vc=function(n,c,u){u=Mt(u);var m,E,S,b,A;c===2?(m=Gl,E=jl,b=Nf,S=()=>Zt,A=1):c===4&&(m=ql,E=Ar,b=Fn,S=()=>Me,A=2),Tr(n,{name:u,fromWireType:function(k){for(var x=Me[k>>2],K=S(),ie,te=k+4,Q=0;Q<=x;++Q){var ue=k+4+Q*c;if(Q==x||K[ue>>A]==0){var $e=ue-te,qe=m(te,$e);ie===void 0?ie=qe:(ie+=String.fromCharCode(0),ie+=qe),te=ue+c}}return di(k),ie},toWireType:function(k,x){typeof x!="string"&&xe(`Cannot pass non-string to C++ string type ${u}`);var K=b(x),ie=Ql(4+K+c);return Me[ie>>2]=K>>A,E(x,ie+4,K+c),k!==null&&k.push(di,ie),ie},argPackAdvance:8,readValueFromPointer:ai,destructorFunction:function(k){di(k)}})};function zl(n,c){c=Mt(c),Tr(n,{isVoid:!0,name:c,argPackAdvance:0,fromWireType:function(){},toWireType:function(u,m){}})}var Jl={};function Bc(n){var c=Jl[n];return c===void 0?Mt(n):c}var $n=[];function hs(n,c,u,m){n=$n[n],c=ms.toValue(c),u=Bc(u),n(c,u,null,m)}function Fc(n){var c=$n.length;return $n.push(n),c}function f(n,c){var u=ni[n];return u===void 0&&xe(c+" has unknown type "+Ln(n)),u}function _(n,c){for(var u=new Array(n),m=0;m<n;++m)u[m]=f(Me[c+m*4>>2],"parameter "+m);return u}var I=[];function C(n,c){var u=_(n,c),m=u[0],E=m.name+"_$"+u.slice(1).map(function(ue){return ue.name}).join("_")+"$",S=I[E];if(S!==void 0)return S;for(var b=["retType"],A=[m],k="",x=0;x<n-1;++x)k+=(x!==0?", ":"")+"arg"+x,b.push("argType"+x),A.push(u[1+x]);for(var K=ho("methodCaller_"+E),ie="return function "+K+`(handle, name, destructors, args) {
|
|
64
64
|
`,te=0,x=0;x<n-1;++x)ie+=" var arg"+x+" = argType"+x+".readValueFromPointer(args"+(te?"+"+te:"")+`);
|
|
65
65
|
`,te+=u[x+1].argPackAdvance;ie+=" var rv = handle[name]("+k+`);
|
|
66
66
|
`;for(var x=0;x<n-1;++x)u[x+1].deleteObject&&(ie+=" argType"+x+".deleteObject(arg"+x+`);
|
|
67
67
|
`);m.isVoid||(ie+=` return retType.toWireType(destructors, rv);
|
|
68
68
|
`),ie+=`};
|
|
69
|
-
`,b.push(ie);var Q=Mc(Function,b).apply(null,A);return S=Fc(Q),I[E]=S,S}function M(n,c){return c+2097152>>>0<4194305-!!n?(n>>>0)+c*4294967296:NaN}var $=()=>{kr("")};function G(){return Date.now()}var U=()=>tt.length,ee=()=>U(),H=(n,c,u)=>tt.copyWithin(n,c,c+u),_e=n=>{kr("OOM")},ye=n=>{var c=tt.length;n>>>=0,_e(n)},Re={},ke=()=>d||"./this.program",Ye=()=>{if(!Ye.strings){var n=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",c={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:n,_:ke()};for(var u in Re)Re[u]===void 0?delete c[u]:c[u]=Re[u];var m=[];for(var u in c)m.push(`${u}=${c[u]}`);Ye.strings=m}return Ye.strings},Ft=(n,c)=>{for(var u=0;u<n.length;++u)Pe[c++>>0]=n.charCodeAt(u);Pe[c>>0]=0},bt=(n,c)=>{var u=0;return Ye().forEach(function(m,E){var S=c+u;Me[n+E*4>>2]=S,Ft(m,S),u+=m.length+1}),0},Br=(n,c)=>{var u=Ye();Me[n>>2]=u.length;var m=0;return u.forEach(function(E){m+=E.length+1}),Me[c>>2]=m,0};function $n(n){try{var c=Qe.getStreamFromFD(n);return g.close(c),0}catch(u){if(typeof g=="undefined"||u.name!=="ErrnoError")throw u;return u.errno}}function er(n,c){try{var u=0,m=0,E=0,S=Qe.getStreamFromFD(n),b=S.tty?2:g.isDir(S.mode)?3:g.isLink(S.mode)?7:4;return Pe[c>>0]=b,Yt[c+2>>1]=E,He=[u>>>0,(ce=u,+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[c+8>>2]=He[0],P[c+12>>2]=He[1],He=[m>>>0,(ce=m,+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[c+16>>2]=He[0],P[c+20>>2]=He[1],0}catch(A){if(typeof g=="undefined"||A.name!=="ErrnoError")throw A;return A.errno}}var Xl=(n,c,u,m)=>{for(var E=0,S=0;S<u;S++){var b=Me[c>>2],A=Me[c+4>>2];c+=8;var k=g.read(n,Pe,b,A,m);if(k<0)return-1;if(E+=k,k<A)break;typeof m!="undefined"&&(m+=k)}return E};function $c(n,c,u,m){try{var E=Qe.getStreamFromFD(n),S=Xl(E,c,u);return Me[m>>2]=S,0}catch(b){if(typeof g=="undefined"||b.name!=="ErrnoError")throw b;return b.errno}}function Hc(n,c,u,m,E){var S=M(c,u);try{if(isNaN(S))return 61;var b=Qe.getStreamFromFD(n);return g.llseek(b,S,m),He=[b.position>>>0,(ce=b.position,+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[E>>2]=He[0],P[E+4>>2]=He[1],b.getdents&&S===0&&m===0&&(b.getdents=null),0}catch(A){if(typeof g=="undefined"||A.name!=="ErrnoError")throw A;return A.errno}}var Wc=(n,c,u,m)=>{for(var E=0,S=0;S<u;S++){var b=Me[c>>2],A=Me[c+4>>2];c+=8;var k=g.write(n,Pe,b,A,m);if(k<0)return-1;E+=k,typeof m!="undefined"&&(m+=k)}return E};function FE(n,c,u,m){try{var E=Qe.getStreamFromFD(n),S=Wc(E,c,u);return Me[m>>2]=S,0}catch(b){if(typeof g=="undefined"||b.name!=="ErrnoError")throw b;return b.errno}}var wf=function(n,c,u,m){n||(n=this),this.parent=n,this.mount=n.mount,this.mounted=null,this.id=g.nextInode++,this.name=c,this.mode=u,this.node_ops={},this.stream_ops={},this.rdev=m},Gc=365,jc=146;Object.defineProperties(wf.prototype,{read:{get:function(){return(this.mode&Gc)===Gc},set:function(n){n?this.mode|=Gc:this.mode&=~Gc}},write:{get:function(){return(this.mode&jc)===jc},set:function(n){n?this.mode|=jc:this.mode&=~jc}},isFolder:{get:function(){return g.isDir(this.mode)}},isDevice:{get:function(){return g.isChrdev(this.mode)}}}),g.FSNode=wf,g.createPreloadedFile=lc,g.staticInit(),co(),Oi=e.BindingError=class extends Error{constructor(c){super(c),this.name="BindingError"}},fc=e.InternalError=class extends Error{constructor(c){super(c),this.name="InternalError"}},Il(),gl(),Cl(),wc=e.UnboundTypeError=Nc(Error,"UnboundTypeError"),kl(),Ul();var $E={p:cc,C:Rn,w:ao,t:hl,n:fl,r:xl,q:Ol,d:Pl,D:Lc,k:Uc,c:Fl,b:$l,j:Wl,f:Vc,o:zl,g:hs,m:kc,l:C,a:$,e:G,v:ee,A:H,u:ye,y:bt,z:Br,i:$n,x:er,B:$c,s:Hc,h:FE},RA=w(),HE=()=>(HE=Ge.F)(),Ql=n=>(Ql=Ge.G)(n),di=n=>(di=Ge.I)(n),xf=()=>(xf=Ge.J)(),Mf=n=>(Mf=Ge.K)(n),WE=e.__embind_initialize_bindings=()=>(WE=e.__embind_initialize_bindings=Ge.L)(),Of=n=>(Of=Ge.M)(n),GE=e.dynCall_jiji=(n,c,u,m,E)=>(GE=e.dynCall_jiji=Ge.N)(n,c,u,m,E),CA=e._ff_h264_cabac_tables=67061,qc;so=function n(){qc||Pf(),qc||(so=n)};function Pf(){if(se>0||(sl(),se>0))return;function n(){qc||(qc=!0,e.calledRun=!0,!fn&&(z(),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),nl()))}e.setStatus?(e.setStatus("Running..."),setTimeout(function(){setTimeout(function(){e.setStatus("")},1),n()},1)):n()}if(e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();return Pf(),t.ready}})(),Fg=vy;var Su=class extends Qr{constructor(t){super(Fg,t!=null&&t.wasmPath?fetch(t==null?void 0:t.wasmPath).then(e=>e.arrayBuffer()):void 0,t==null?void 0:t.workerMode,t==null?void 0:t.canvas,t==null?void 0:t.yuvMode)}};var Ry=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e=t,r,o;e.ready=new Promise((f,_)=>{r=f,o=_});var s=Object.assign({},e),a=[],d="./this.program",h=(f,_)=>{throw _},p=typeof window=="object",T=typeof importScripts=="function",y=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",R="";function N(f){return e.locateFile?e.locateFile(f,R):R+f}var j,W,F,Ie;(p||T)&&(T?R=self.location.href:typeof document!="undefined"&&document.currentScript&&(R=document.currentScript.src),i&&(R=i),R.indexOf("blob:")!==0?R=R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1):R="",j=f=>{var _=new XMLHttpRequest;return _.open("GET",f,!1),_.send(null),_.responseText},T&&(F=f=>{var _=new XMLHttpRequest;return _.open("GET",f,!1),_.responseType="arraybuffer",_.send(null),new Uint8Array(_.response)}),W=(f,_,I)=>{var C=new XMLHttpRequest;C.open("GET",f,!0),C.responseType="arraybuffer",C.onload=()=>{if(C.status==200||C.status==0&&C.response){_(C.response);return}I()},C.onerror=I,C.send(null)},Ie=f=>document.title=f);var Bt=e.print||console.log.bind(console),Xe=e.printErr||console.error.bind(console);Object.assign(e,s),s=null,e.arguments&&(a=e.arguments),e.thisProgram&&(d=e.thisProgram),e.quit&&(h=e.quit);var wt;e.wasmBinary&&(wt=e.wasmBinary);var fe=e.noExitRuntime||!0;typeof WebAssembly!="object"&&Ni("no native wasm support detected");var hn,Ge,fn=!1,il,ei,Pe,tt,Yt,Zt,P,Me,_n;function oc(){var f=hn.buffer;e.HEAP8=ei=new Int8Array(f),e.HEAP16=tt=new Int16Array(f),e.HEAP32=Zt=new Int32Array(f),e.HEAPU8=Pe=new Uint8Array(f),e.HEAPU16=Yt=new Uint16Array(f),e.HEAPU32=P=new Uint32Array(f),e.HEAPF32=Me=new Float32Array(f),e.HEAPF64=_n=new Float64Array(f)}var sc,gn=[],En=[],Tn=[],nc=!1;function ol(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)nl(e.preRun.shift());yn(gn)}function sl(){nc=!0,yn(En)}function z(){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)cl(e.postRun.shift());yn(Tn)}function nl(f){gn.unshift(f)}function al(f){En.unshift(f)}function cl(f){Tn.unshift(f)}var ti=0,se=null,ri=null;function so(f){ti++,e.monitorRunDependencies&&e.monitorRunDependencies(ti)}function Df(f){if(ti--,e.monitorRunDependencies&&e.monitorRunDependencies(ti),ti==0&&(se!==null&&(clearInterval(se),se=null),ri)){var _=ri;ri=null,_()}}function Ni(f){e.onAbort&&e.onAbort(f),f="Aborted("+f+")",Xe(f),fn=!0,il=1,f+=". Build with -sASSERTIONS for more info.";var _=new WebAssembly.RuntimeError(f);throw o(_),_}var is="data:application/octet-stream;base64,";function kr(f){return f.startsWith(is)}var wi;wi="videodec_simd.wasm",kr(wi)||(wi=N(wi));function In(f){if(f==wi&&wt)return new Uint8Array(wt);if(F)return F(f);throw"both async and sync fetching of the wasm failed"}function xi(f){return!wt&&(p||T)&&typeof fetch=="function"?fetch(f,{credentials:"same-origin"}).then(_=>{if(!_.ok)throw"failed to load wasm binary file at '"+f+"'";return _.arrayBuffer()}).catch(()=>In(f)):Promise.resolve().then(()=>In(f))}function Sn(f,_,I){return xi(f).then(C=>WebAssembly.instantiate(C,_)).then(C=>C).then(I,C=>{Xe("failed to asynchronously prepare wasm: "+C),Ni(C)})}function dl(f,_,I,C){return!f&&typeof WebAssembly.instantiateStreaming=="function"&&!kr(_)&&typeof fetch=="function"?fetch(_,{credentials:"same-origin"}).then(M=>{var $=WebAssembly.instantiateStreaming(M,I);return $.then(C,function(G){return Xe("wasm streaming compile failed: "+G),Xe("falling back to ArrayBuffer instantiation"),Sn(_,I,C)})}):Sn(_,I,C)}function ac(){var f={a:jl};function _(C,M){var $=C.exports;return Ge=$,hn=Ge.v,oc(),sc=Ge.z,al(Ge.w),Df("wasm-instantiate"),$}so("wasm-instantiate");function I(C){_(C.instance)}if(e.instantiateWasm)try{return e.instantiateWasm(f,_)}catch(C){Xe("Module.instantiateWasm callback failed with error: "+C),o(C)}return dl(wt,wi,f,I).catch(o),{}}var yn=f=>{for(;f.length>0;)f.shift()(e)};function w(f){this.excPtr=f,this.ptr=f-24,this.set_type=function(_){P[this.ptr+4>>2]=_},this.get_type=function(){return P[this.ptr+4>>2]},this.set_destructor=function(_){P[this.ptr+8>>2]=_},this.get_destructor=function(){return P[this.ptr+8>>2]},this.set_caught=function(_){_=_?1:0,ei[this.ptr+12>>0]=_},this.get_caught=function(){return ei[this.ptr+12>>0]!=0},this.set_rethrown=function(_){_=_?1:0,ei[this.ptr+13>>0]=_},this.get_rethrown=function(){return ei[this.ptr+13>>0]!=0},this.init=function(_,I){this.set_adjusted_ptr(0),this.set_type(_),this.set_destructor(I)},this.set_adjusted_ptr=function(_){P[this.ptr+16>>2]=_},this.get_adjusted_ptr=function(){return P[this.ptr+16>>2]},this.get_exception_ptr=function(){var _=Bc(this.get_type());if(_)return P[this.excPtr>>2];var I=this.get_adjusted_ptr();return I!==0?I:this.excPtr}}var ce=0,He=0;function An(f,_,I){var C=new w(f);throw C.init(_,I),ce=f,He++,ce}function ul(f,_,I,C,M){}function os(f){switch(f){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${f}`)}}function ll(){for(var f=new Array(256),_=0;_<256;++_)f[_]=String.fromCharCode(_);cc=f}var cc=void 0;function xt(f){for(var _="",I=f;Pe[I];)_+=cc[Pe[I++]];return _}var De={},ii={},no={},At=void 0;function Ne(f){throw new At(f)}var oi=void 0;function Mi(f){throw new oi(f)}function si(f,_,I){f.forEach(function(U){no[U]=_});function C(U){var ee=I(U);ee.length!==f.length&&Mi("Mismatched type converter count");for(var H=0;H<f.length;++H)Kt(f[H],ee[H])}var M=new Array(_.length),$=[],G=0;_.forEach((U,ee)=>{ii.hasOwnProperty(U)?M[ee]=ii[U]:($.push(U),De.hasOwnProperty(U)||(De[U]=[]),De[U].push(()=>{M[ee]=ii[U],++G,G===$.length&&C(M)}))}),$.length===0&&C(M)}function bn(f,_,I={}){var C=_.name;if(f||Ne(`type "${C}" must have a positive integer typeid pointer`),ii.hasOwnProperty(f)){if(I.ignoreDuplicateRegistrations)return;Ne(`Cannot register type '${C}' twice`)}if(ii[f]=_,delete no[f],De.hasOwnProperty(f)){var M=De[f];delete De[f],M.forEach($=>$())}}function Kt(f,_,I={}){if(!("argPackAdvance"in _))throw new TypeError("registerType registeredInstance requires argPackAdvance");return bn(f,_,I)}function pl(f,_,I,C,M){var $=os(I);_=xt(_),Kt(f,{name:_,fromWireType:function(G){return!!G},toWireType:function(G,U){return U?C:M},argPackAdvance:8,readValueFromPointer:function(G){var U;if(I===1)U=ei;else if(I===2)U=tt;else if(I===4)U=Zt;else throw new TypeError("Unknown boolean type size: "+_);return this.fromWireType(U[G>>$])},destructorFunction:null})}function Lr(f){if(!(this instanceof Vr)||!(f instanceof Vr))return!1;for(var _=this.$$.ptrType.registeredClass,I=this.$$.ptr,C=f.$$.ptrType.registeredClass,M=f.$$.ptr;_.baseClass;)I=_.upcast(I),_=_.baseClass;for(;C.baseClass;)M=C.upcast(M),C=C.baseClass;return _===C&&I===M}function dc(f){return{count:f.count,deleteScheduled:f.deleteScheduled,preservePointerOnDelete:f.preservePointerOnDelete,ptr:f.ptr,ptrType:f.ptrType,smartPtr:f.smartPtr,smartPtrType:f.smartPtrType}}function he(f){function _(I){return I.$$.ptrType.registeredClass.name}Ne(_(f)+" instance already deleted")}var vn=!1;function uc(f){}function ml(f){f.smartPtr?f.smartPtrType.rawDestructor(f.smartPtr):f.ptrType.registeredClass.rawDestructor(f.ptr)}function lc(f){f.count.value-=1;var _=f.count.value===0;_&&ml(f)}function pc(f,_,I){if(_===I)return f;if(I.baseClass===void 0)return null;var C=pc(f,_,I.baseClass);return C===null?null:I.downcast(C)}var ss={};function g(){return Object.keys(co).length}function mc(){var f=[];for(var _ in co)co.hasOwnProperty(_)&&f.push(co[_]);return f}var Qe=[];function Rn(){for(;Qe.length;){var f=Qe.pop();f.$$.deleteScheduled=!1,f.delete()}}var ao=void 0;function hl(f){ao=f,Qe.length&&ao&&ao(Rn)}function Cn(){e.getInheritedInstanceCount=g,e.getLiveInheritedInstances=mc,e.flushPendingDeletes=Rn,e.setDelayFunction=hl}var co={};function hc(f,_){for(_===void 0&&Ne("ptr should not be undefined");f.baseClass;)_=f.upcast(_),f=f.baseClass;return _}function Mt(f,_){return _=hc(f,_),co[_]}function Er(f,_){(!_.ptrType||!_.ptr)&&Mi("makeClassHandle requires ptr and ptrType");var I=!!_.smartPtrType,C=!!_.smartPtr;return I!==C&&Mi("Both smartPtrType and smartPtr must be specified"),_.count={value:1},Ur(Object.create(f,{$$:{value:_}}))}function ni(f){var _=this.getPointee(f);if(!_)return this.destructor(f),null;var I=Mt(this.registeredClass,_);if(I!==void 0){if(I.$$.count.value===0)return I.$$.ptr=_,I.$$.smartPtr=f,I.clone();var C=I.clone();return this.destructor(f),C}function M(){return this.isSmartPointer?Er(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:_,smartPtrType:this,smartPtr:f}):Er(this.registeredClass.instancePrototype,{ptrType:this,ptr:f})}var $=this.registeredClass.getActualType(_),G=ss[$];if(!G)return M.call(this);var U;this.isConst?U=G.constPointerType:U=G.pointerType;var ee=pc(_,this.registeredClass,U.registeredClass);return ee===null?M.call(this):this.isSmartPointer?Er(U.registeredClass.instancePrototype,{ptrType:U,ptr:ee,smartPtrType:this,smartPtr:f}):Er(U.registeredClass.instancePrototype,{ptrType:U,ptr:ee})}var Ur=function(f){return typeof FinalizationRegistry=="undefined"?(Ur=_=>_,f):(vn=new FinalizationRegistry(_=>{lc(_.$$)}),Ur=_=>{var I=_.$$,C=!!I.smartPtr;if(C){var M={$$:I};vn.register(_,M,_)}return _},uc=_=>vn.unregister(_),Ur(f))};function Oi(){if(this.$$.ptr||he(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var f=Ur(Object.create(Object.getPrototypeOf(this),{$$:{value:dc(this.$$)}}));return f.$$.count.value+=1,f.$$.deleteScheduled=!1,f}function xe(){this.$$.ptr||he(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),uc(this),lc(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function fc(){return!this.$$.ptr}function ns(){return this.$$.ptr||he(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),Qe.push(this),Qe.length===1&&ao&&ao(Rn),this.$$.deleteScheduled=!0,this}function uo(){Vr.prototype.isAliasOf=Lr,Vr.prototype.clone=Oi,Vr.prototype.delete=xe,Vr.prototype.isDeleted=fc,Vr.prototype.deleteLater=ns}function Vr(){}var Tr=48,fl=57;function as(f){if(f===void 0)return"_unknown";f=f.replace(/[^a-zA-Z0-9_]/g,"$");var _=f.charCodeAt(0);return _>=Tr&&_<=fl?`_${f}`:f}function Dn(f,_){return f=as(f),{[f]:function(){return _.apply(this,arguments)}}[f]}function cs(f,_,I){if(f[_].overloadTable===void 0){var C=f[_];f[_]=function(){return f[_].overloadTable.hasOwnProperty(arguments.length)||Ne(`Function '${I}' called with an invalid number of arguments (${arguments.length}) - expects one of (${f[_].overloadTable})!`),f[_].overloadTable[arguments.length].apply(this,arguments)},f[_].overloadTable=[],f[_].overloadTable[C.argCount]=C}}function Nn(f,_,I){e.hasOwnProperty(f)?((I===void 0||e[f].overloadTable!==void 0&&e[f].overloadTable[I]!==void 0)&&Ne(`Cannot register public name '${f}' twice`),cs(e,f,f),e.hasOwnProperty(I)&&Ne(`Cannot register multiple overloads of a function with the same number of arguments (${I})!`),e[f].overloadTable[I]=_):(e[f]=_,I!==void 0&&(e[f].numArguments=I))}function _c(f,_,I,C,M,$,G,U){this.name=f,this.constructor=_,this.instancePrototype=I,this.rawDestructor=C,this.baseClass=M,this.getActualType=$,this.upcast=G,this.downcast=U,this.pureVirtualFunctions=[]}function wn(f,_,I){for(;_!==I;)_.upcast||Ne(`Expected null or instance of ${I.name}, got an instance of ${_.name}`),f=_.upcast(f),_=_.baseClass;return f}function gc(f,_){if(_===null)return this.isReference&&Ne(`null is not a valid ${this.name}`),0;_.$$||Ne(`Cannot pass "${Pn(_)}" as a ${this.name}`),_.$$.ptr||Ne(`Cannot pass deleted object as a pointer of type ${this.name}`);var I=_.$$.ptrType.registeredClass,C=wn(_.$$.ptr,I,this.registeredClass);return C}function Ec(f,_){var I;if(_===null)return this.isReference&&Ne(`null is not a valid ${this.name}`),this.isSmartPointer?(I=this.rawConstructor(),f!==null&&f.push(this.rawDestructor,I),I):0;_.$$||Ne(`Cannot pass "${Pn(_)}" as a ${this.name}`),_.$$.ptr||Ne(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&_.$$.ptrType.isConst&&Ne(`Cannot convert argument of type ${_.$$.smartPtrType?_.$$.smartPtrType.name:_.$$.ptrType.name} to parameter type ${this.name}`);var C=_.$$.ptrType.registeredClass;if(I=wn(_.$$.ptr,C,this.registeredClass),this.isSmartPointer)switch(_.$$.smartPtr===void 0&&Ne("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:_.$$.smartPtrType===this?I=_.$$.smartPtr:Ne(`Cannot convert argument of type ${_.$$.smartPtrType?_.$$.smartPtrType.name:_.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:I=_.$$.smartPtr;break;case 2:if(_.$$.smartPtrType===this)I=_.$$.smartPtr;else{var M=_.clone();I=this.rawShare(I,ai.toHandle(function(){M.delete()})),f!==null&&f.push(this.rawDestructor,I)}break;default:Ne("Unsupporting sharing policy")}return I}function Tc(f,_){if(_===null)return this.isReference&&Ne(`null is not a valid ${this.name}`),0;_.$$||Ne(`Cannot pass "${Pn(_)}" as a ${this.name}`),_.$$.ptr||Ne(`Cannot pass deleted object as a pointer of type ${this.name}`),_.$$.ptrType.isConst&&Ne(`Cannot convert argument of type ${_.$$.ptrType.name} to parameter type ${this.name}`);var I=_.$$.ptrType.registeredClass,C=wn(_.$$.ptr,I,this.registeredClass);return C}function ds(f){return this.fromWireType(Zt[f>>2])}function _l(f){return this.rawGetPointee&&(f=this.rawGetPointee(f)),f}function lo(f){this.rawDestructor&&this.rawDestructor(f)}function xn(f){f!==null&&f.delete()}function po(){Ir.prototype.getPointee=_l,Ir.prototype.destructor=lo,Ir.prototype.argPackAdvance=8,Ir.prototype.readValueFromPointer=ds,Ir.prototype.deleteObject=xn,Ir.prototype.fromWireType=ni}function Ir(f,_,I,C,M,$,G,U,ee,H,_e){this.name=f,this.registeredClass=_,this.isReference=I,this.isConst=C,this.isSmartPointer=M,this.pointeeType=$,this.sharingPolicy=G,this.rawGetPointee=U,this.rawConstructor=ee,this.rawShare=H,this.rawDestructor=_e,!M&&_.baseClass===void 0?C?(this.toWireType=gc,this.destructorFunction=null):(this.toWireType=Tc,this.destructorFunction=null):this.toWireType=Ec}function gl(f,_,I){e.hasOwnProperty(f)||Mi("Replacing nonexistant public symbol"),e[f].overloadTable!==void 0&&I!==void 0?e[f].overloadTable[I]=_:(e[f]=_,e[f].argCount=I)}var mo=(f,_,I)=>{var C=e["dynCall_"+f];return I&&I.length?C.apply(null,[_].concat(I)):C.call(null,_)},us=[],Ic=f=>{var _=us[f];return _||(f>=us.length&&(us.length=f+1),us[f]=_=sc.get(f)),_},ls=(f,_,I)=>{if(f.includes("j"))return mo(f,_,I);var C=Ic(_).apply(null,I);return C},El=(f,_)=>{var I=[];return function(){return I.length=0,Object.assign(I,arguments),ls(f,_,I)}};function ur(f,_){f=xt(f);function I(){return f.includes("j")?El(f,_):Ic(_)}var C=I();return typeof C!="function"&&Ne(`unknown function pointer with signature ${f}: ${_}`),C}function Tl(f,_){var I=Dn(_,function(C){this.name=_,this.message=C;var M=new Error(C).stack;M!==void 0&&(this.stack=this.toString()+`
|
|
70
|
-
`+M.replace(/^Error(:[^\n]*)?\n/,""))});return I.prototype=Object.create(f.prototype),I.prototype.constructor=I,I.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},I}var Sc=void 0;function yc(f){var _=Vc(f),I=xt(_);return Ar(_),I}function
|
|
69
|
+
`,b.push(ie);var Q=Mc(Function,b).apply(null,A);return S=Fc(Q),I[E]=S,S}function M(n,c){return c+2097152>>>0<4194305-!!n?(n>>>0)+c*4294967296:NaN}var $=()=>{kr("")};function G(){return Date.now()}var U=()=>tt.length,ee=()=>U(),H=(n,c,u)=>tt.copyWithin(n,c,c+u),_e=n=>{kr("OOM")},ye=n=>{var c=tt.length;n>>>=0,_e(n)},Re={},ke=()=>d||"./this.program",Ye=()=>{if(!Ye.strings){var n=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",c={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:n,_:ke()};for(var u in Re)Re[u]===void 0?delete c[u]:c[u]=Re[u];var m=[];for(var u in c)m.push(`${u}=${c[u]}`);Ye.strings=m}return Ye.strings},Ft=(n,c)=>{for(var u=0;u<n.length;++u)Pe[c++>>0]=n.charCodeAt(u);Pe[c>>0]=0},bt=(n,c)=>{var u=0;return Ye().forEach(function(m,E){var S=c+u;Me[n+E*4>>2]=S,Ft(m,S),u+=m.length+1}),0},Br=(n,c)=>{var u=Ye();Me[n>>2]=u.length;var m=0;return u.forEach(function(E){m+=E.length+1}),Me[c>>2]=m,0};function Hn(n){try{var c=Qe.getStreamFromFD(n);return g.close(c),0}catch(u){if(typeof g=="undefined"||u.name!=="ErrnoError")throw u;return u.errno}}function er(n,c){try{var u=0,m=0,E=0,S=Qe.getStreamFromFD(n),b=S.tty?2:g.isDir(S.mode)?3:g.isLink(S.mode)?7:4;return Pe[c>>0]=b,Yt[c+2>>1]=E,He=[u>>>0,(ce=u,+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[c+8>>2]=He[0],P[c+12>>2]=He[1],He=[m>>>0,(ce=m,+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[c+16>>2]=He[0],P[c+20>>2]=He[1],0}catch(A){if(typeof g=="undefined"||A.name!=="ErrnoError")throw A;return A.errno}}var Xl=(n,c,u,m)=>{for(var E=0,S=0;S<u;S++){var b=Me[c>>2],A=Me[c+4>>2];c+=8;var k=g.read(n,Pe,b,A,m);if(k<0)return-1;if(E+=k,k<A)break;typeof m!="undefined"&&(m+=k)}return E};function $c(n,c,u,m){try{var E=Qe.getStreamFromFD(n),S=Xl(E,c,u);return Me[m>>2]=S,0}catch(b){if(typeof g=="undefined"||b.name!=="ErrnoError")throw b;return b.errno}}function Hc(n,c,u,m,E){var S=M(c,u);try{if(isNaN(S))return 61;var b=Qe.getStreamFromFD(n);return g.llseek(b,S,m),He=[b.position>>>0,(ce=b.position,+Math.abs(ce)>=1?ce>0?+Math.floor(ce/4294967296)>>>0:~~+Math.ceil((ce-+(~~ce>>>0))/4294967296)>>>0:0)],P[E>>2]=He[0],P[E+4>>2]=He[1],b.getdents&&S===0&&m===0&&(b.getdents=null),0}catch(A){if(typeof g=="undefined"||A.name!=="ErrnoError")throw A;return A.errno}}var Wc=(n,c,u,m)=>{for(var E=0,S=0;S<u;S++){var b=Me[c>>2],A=Me[c+4>>2];c+=8;var k=g.write(n,Pe,b,A,m);if(k<0)return-1;E+=k,typeof m!="undefined"&&(m+=k)}return E};function FE(n,c,u,m){try{var E=Qe.getStreamFromFD(n),S=Wc(E,c,u);return Me[m>>2]=S,0}catch(b){if(typeof g=="undefined"||b.name!=="ErrnoError")throw b;return b.errno}}var wf=function(n,c,u,m){n||(n=this),this.parent=n,this.mount=n.mount,this.mounted=null,this.id=g.nextInode++,this.name=c,this.mode=u,this.node_ops={},this.stream_ops={},this.rdev=m},Gc=365,jc=146;Object.defineProperties(wf.prototype,{read:{get:function(){return(this.mode&Gc)===Gc},set:function(n){n?this.mode|=Gc:this.mode&=~Gc}},write:{get:function(){return(this.mode&jc)===jc},set:function(n){n?this.mode|=jc:this.mode&=~jc}},isFolder:{get:function(){return g.isDir(this.mode)}},isDevice:{get:function(){return g.isChrdev(this.mode)}}}),g.FSNode=wf,g.createPreloadedFile=lc,g.staticInit(),co(),Oi=e.BindingError=class extends Error{constructor(c){super(c),this.name="BindingError"}},fc=e.InternalError=class extends Error{constructor(c){super(c),this.name="InternalError"}},Il(),gl(),Cl(),wc=e.UnboundTypeError=Nc(Error,"UnboundTypeError"),kl(),Ul();var $E={p:cc,C:Cn,w:ao,t:hl,n:fl,r:xl,q:Ol,d:Pl,D:Lc,k:Uc,c:Fl,b:$l,j:Wl,f:Vc,o:zl,g:hs,m:kc,l:C,a:$,e:G,v:ee,A:H,u:ye,y:bt,z:Br,i:Hn,x:er,B:$c,s:Hc,h:FE},RA=w(),HE=()=>(HE=Ge.F)(),Ql=n=>(Ql=Ge.G)(n),di=n=>(di=Ge.I)(n),xf=()=>(xf=Ge.J)(),Mf=n=>(Mf=Ge.K)(n),WE=e.__embind_initialize_bindings=()=>(WE=e.__embind_initialize_bindings=Ge.L)(),Of=n=>(Of=Ge.M)(n),GE=e.dynCall_jiji=(n,c,u,m,E)=>(GE=e.dynCall_jiji=Ge.N)(n,c,u,m,E),CA=e._ff_h264_cabac_tables=67061,qc;so=function n(){qc||Pf(),qc||(so=n)};function Pf(){if(se>0||(sl(),se>0))return;function n(){qc||(qc=!0,e.calledRun=!0,!_n&&(z(),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),nl()))}e.setStatus?(e.setStatus("Running..."),setTimeout(function(){setTimeout(function(){e.setStatus("")},1),n()},1)):n()}if(e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();return Pf(),t.ready}})(),Fg=vy;var Su=class extends Qr{constructor(t){super(Fg,t!=null&&t.wasmPath?fetch(t==null?void 0:t.wasmPath).then(e=>e.arrayBuffer()):void 0,t==null?void 0:t.workerMode,t==null?void 0:t.canvas,t==null?void 0:t.yuvMode)}};var Ry=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e=t,r,o;e.ready=new Promise((f,_)=>{r=f,o=_});var s=Object.assign({},e),a=[],d="./this.program",h=(f,_)=>{throw _},p=typeof window=="object",T=typeof importScripts=="function",y=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",R="";function N(f){return e.locateFile?e.locateFile(f,R):R+f}var j,W,F,Ie;(p||T)&&(T?R=self.location.href:typeof document!="undefined"&&document.currentScript&&(R=document.currentScript.src),i&&(R=i),R.indexOf("blob:")!==0?R=R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1):R="",j=f=>{var _=new XMLHttpRequest;return _.open("GET",f,!1),_.send(null),_.responseText},T&&(F=f=>{var _=new XMLHttpRequest;return _.open("GET",f,!1),_.responseType="arraybuffer",_.send(null),new Uint8Array(_.response)}),W=(f,_,I)=>{var C=new XMLHttpRequest;C.open("GET",f,!0),C.responseType="arraybuffer",C.onload=()=>{if(C.status==200||C.status==0&&C.response){_(C.response);return}I()},C.onerror=I,C.send(null)},Ie=f=>document.title=f);var Bt=e.print||console.log.bind(console),Xe=e.printErr||console.error.bind(console);Object.assign(e,s),s=null,e.arguments&&(a=e.arguments),e.thisProgram&&(d=e.thisProgram),e.quit&&(h=e.quit);var wt;e.wasmBinary&&(wt=e.wasmBinary);var fe=e.noExitRuntime||!0;typeof WebAssembly!="object"&&Ni("no native wasm support detected");var fn,Ge,_n=!1,il,ei,Pe,tt,Yt,Zt,P,Me,gn;function oc(){var f=fn.buffer;e.HEAP8=ei=new Int8Array(f),e.HEAP16=tt=new Int16Array(f),e.HEAP32=Zt=new Int32Array(f),e.HEAPU8=Pe=new Uint8Array(f),e.HEAPU16=Yt=new Uint16Array(f),e.HEAPU32=P=new Uint32Array(f),e.HEAPF32=Me=new Float32Array(f),e.HEAPF64=gn=new Float64Array(f)}var sc,En=[],Tn=[],In=[],nc=!1;function ol(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)nl(e.preRun.shift());An(En)}function sl(){nc=!0,An(Tn)}function z(){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)cl(e.postRun.shift());An(In)}function nl(f){En.unshift(f)}function al(f){Tn.unshift(f)}function cl(f){In.unshift(f)}var ti=0,se=null,ri=null;function so(f){ti++,e.monitorRunDependencies&&e.monitorRunDependencies(ti)}function Df(f){if(ti--,e.monitorRunDependencies&&e.monitorRunDependencies(ti),ti==0&&(se!==null&&(clearInterval(se),se=null),ri)){var _=ri;ri=null,_()}}function Ni(f){e.onAbort&&e.onAbort(f),f="Aborted("+f+")",Xe(f),_n=!0,il=1,f+=". Build with -sASSERTIONS for more info.";var _=new WebAssembly.RuntimeError(f);throw o(_),_}var is="data:application/octet-stream;base64,";function kr(f){return f.startsWith(is)}var wi;wi="videodec_simd.wasm",kr(wi)||(wi=N(wi));function Sn(f){if(f==wi&&wt)return new Uint8Array(wt);if(F)return F(f);throw"both async and sync fetching of the wasm failed"}function xi(f){return!wt&&(p||T)&&typeof fetch=="function"?fetch(f,{credentials:"same-origin"}).then(_=>{if(!_.ok)throw"failed to load wasm binary file at '"+f+"'";return _.arrayBuffer()}).catch(()=>Sn(f)):Promise.resolve().then(()=>Sn(f))}function yn(f,_,I){return xi(f).then(C=>WebAssembly.instantiate(C,_)).then(C=>C).then(I,C=>{Xe("failed to asynchronously prepare wasm: "+C),Ni(C)})}function dl(f,_,I,C){return!f&&typeof WebAssembly.instantiateStreaming=="function"&&!kr(_)&&typeof fetch=="function"?fetch(_,{credentials:"same-origin"}).then(M=>{var $=WebAssembly.instantiateStreaming(M,I);return $.then(C,function(G){return Xe("wasm streaming compile failed: "+G),Xe("falling back to ArrayBuffer instantiation"),yn(_,I,C)})}):yn(_,I,C)}function ac(){var f={a:jl};function _(C,M){var $=C.exports;return Ge=$,fn=Ge.v,oc(),sc=Ge.z,al(Ge.w),Df("wasm-instantiate"),$}so("wasm-instantiate");function I(C){_(C.instance)}if(e.instantiateWasm)try{return e.instantiateWasm(f,_)}catch(C){Xe("Module.instantiateWasm callback failed with error: "+C),o(C)}return dl(wt,wi,f,I).catch(o),{}}var An=f=>{for(;f.length>0;)f.shift()(e)};function w(f){this.excPtr=f,this.ptr=f-24,this.set_type=function(_){P[this.ptr+4>>2]=_},this.get_type=function(){return P[this.ptr+4>>2]},this.set_destructor=function(_){P[this.ptr+8>>2]=_},this.get_destructor=function(){return P[this.ptr+8>>2]},this.set_caught=function(_){_=_?1:0,ei[this.ptr+12>>0]=_},this.get_caught=function(){return ei[this.ptr+12>>0]!=0},this.set_rethrown=function(_){_=_?1:0,ei[this.ptr+13>>0]=_},this.get_rethrown=function(){return ei[this.ptr+13>>0]!=0},this.init=function(_,I){this.set_adjusted_ptr(0),this.set_type(_),this.set_destructor(I)},this.set_adjusted_ptr=function(_){P[this.ptr+16>>2]=_},this.get_adjusted_ptr=function(){return P[this.ptr+16>>2]},this.get_exception_ptr=function(){var _=Bc(this.get_type());if(_)return P[this.excPtr>>2];var I=this.get_adjusted_ptr();return I!==0?I:this.excPtr}}var ce=0,He=0;function bn(f,_,I){var C=new w(f);throw C.init(_,I),ce=f,He++,ce}function ul(f,_,I,C,M){}function os(f){switch(f){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${f}`)}}function ll(){for(var f=new Array(256),_=0;_<256;++_)f[_]=String.fromCharCode(_);cc=f}var cc=void 0;function xt(f){for(var _="",I=f;Pe[I];)_+=cc[Pe[I++]];return _}var De={},ii={},no={},At=void 0;function Ne(f){throw new At(f)}var oi=void 0;function Mi(f){throw new oi(f)}function si(f,_,I){f.forEach(function(U){no[U]=_});function C(U){var ee=I(U);ee.length!==f.length&&Mi("Mismatched type converter count");for(var H=0;H<f.length;++H)Kt(f[H],ee[H])}var M=new Array(_.length),$=[],G=0;_.forEach((U,ee)=>{ii.hasOwnProperty(U)?M[ee]=ii[U]:($.push(U),De.hasOwnProperty(U)||(De[U]=[]),De[U].push(()=>{M[ee]=ii[U],++G,G===$.length&&C(M)}))}),$.length===0&&C(M)}function vn(f,_,I={}){var C=_.name;if(f||Ne(`type "${C}" must have a positive integer typeid pointer`),ii.hasOwnProperty(f)){if(I.ignoreDuplicateRegistrations)return;Ne(`Cannot register type '${C}' twice`)}if(ii[f]=_,delete no[f],De.hasOwnProperty(f)){var M=De[f];delete De[f],M.forEach($=>$())}}function Kt(f,_,I={}){if(!("argPackAdvance"in _))throw new TypeError("registerType registeredInstance requires argPackAdvance");return vn(f,_,I)}function pl(f,_,I,C,M){var $=os(I);_=xt(_),Kt(f,{name:_,fromWireType:function(G){return!!G},toWireType:function(G,U){return U?C:M},argPackAdvance:8,readValueFromPointer:function(G){var U;if(I===1)U=ei;else if(I===2)U=tt;else if(I===4)U=Zt;else throw new TypeError("Unknown boolean type size: "+_);return this.fromWireType(U[G>>$])},destructorFunction:null})}function Lr(f){if(!(this instanceof Vr)||!(f instanceof Vr))return!1;for(var _=this.$$.ptrType.registeredClass,I=this.$$.ptr,C=f.$$.ptrType.registeredClass,M=f.$$.ptr;_.baseClass;)I=_.upcast(I),_=_.baseClass;for(;C.baseClass;)M=C.upcast(M),C=C.baseClass;return _===C&&I===M}function dc(f){return{count:f.count,deleteScheduled:f.deleteScheduled,preservePointerOnDelete:f.preservePointerOnDelete,ptr:f.ptr,ptrType:f.ptrType,smartPtr:f.smartPtr,smartPtrType:f.smartPtrType}}function he(f){function _(I){return I.$$.ptrType.registeredClass.name}Ne(_(f)+" instance already deleted")}var Rn=!1;function uc(f){}function ml(f){f.smartPtr?f.smartPtrType.rawDestructor(f.smartPtr):f.ptrType.registeredClass.rawDestructor(f.ptr)}function lc(f){f.count.value-=1;var _=f.count.value===0;_&&ml(f)}function pc(f,_,I){if(_===I)return f;if(I.baseClass===void 0)return null;var C=pc(f,_,I.baseClass);return C===null?null:I.downcast(C)}var ss={};function g(){return Object.keys(co).length}function mc(){var f=[];for(var _ in co)co.hasOwnProperty(_)&&f.push(co[_]);return f}var Qe=[];function Cn(){for(;Qe.length;){var f=Qe.pop();f.$$.deleteScheduled=!1,f.delete()}}var ao=void 0;function hl(f){ao=f,Qe.length&&ao&&ao(Cn)}function Dn(){e.getInheritedInstanceCount=g,e.getLiveInheritedInstances=mc,e.flushPendingDeletes=Cn,e.setDelayFunction=hl}var co={};function hc(f,_){for(_===void 0&&Ne("ptr should not be undefined");f.baseClass;)_=f.upcast(_),f=f.baseClass;return _}function Mt(f,_){return _=hc(f,_),co[_]}function Er(f,_){(!_.ptrType||!_.ptr)&&Mi("makeClassHandle requires ptr and ptrType");var I=!!_.smartPtrType,C=!!_.smartPtr;return I!==C&&Mi("Both smartPtrType and smartPtr must be specified"),_.count={value:1},Ur(Object.create(f,{$$:{value:_}}))}function ni(f){var _=this.getPointee(f);if(!_)return this.destructor(f),null;var I=Mt(this.registeredClass,_);if(I!==void 0){if(I.$$.count.value===0)return I.$$.ptr=_,I.$$.smartPtr=f,I.clone();var C=I.clone();return this.destructor(f),C}function M(){return this.isSmartPointer?Er(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:_,smartPtrType:this,smartPtr:f}):Er(this.registeredClass.instancePrototype,{ptrType:this,ptr:f})}var $=this.registeredClass.getActualType(_),G=ss[$];if(!G)return M.call(this);var U;this.isConst?U=G.constPointerType:U=G.pointerType;var ee=pc(_,this.registeredClass,U.registeredClass);return ee===null?M.call(this):this.isSmartPointer?Er(U.registeredClass.instancePrototype,{ptrType:U,ptr:ee,smartPtrType:this,smartPtr:f}):Er(U.registeredClass.instancePrototype,{ptrType:U,ptr:ee})}var Ur=function(f){return typeof FinalizationRegistry=="undefined"?(Ur=_=>_,f):(Rn=new FinalizationRegistry(_=>{lc(_.$$)}),Ur=_=>{var I=_.$$,C=!!I.smartPtr;if(C){var M={$$:I};Rn.register(_,M,_)}return _},uc=_=>Rn.unregister(_),Ur(f))};function Oi(){if(this.$$.ptr||he(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var f=Ur(Object.create(Object.getPrototypeOf(this),{$$:{value:dc(this.$$)}}));return f.$$.count.value+=1,f.$$.deleteScheduled=!1,f}function xe(){this.$$.ptr||he(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),uc(this),lc(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function fc(){return!this.$$.ptr}function ns(){return this.$$.ptr||he(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),Qe.push(this),Qe.length===1&&ao&&ao(Cn),this.$$.deleteScheduled=!0,this}function uo(){Vr.prototype.isAliasOf=Lr,Vr.prototype.clone=Oi,Vr.prototype.delete=xe,Vr.prototype.isDeleted=fc,Vr.prototype.deleteLater=ns}function Vr(){}var Tr=48,fl=57;function as(f){if(f===void 0)return"_unknown";f=f.replace(/[^a-zA-Z0-9_]/g,"$");var _=f.charCodeAt(0);return _>=Tr&&_<=fl?`_${f}`:f}function Nn(f,_){return f=as(f),{[f]:function(){return _.apply(this,arguments)}}[f]}function cs(f,_,I){if(f[_].overloadTable===void 0){var C=f[_];f[_]=function(){return f[_].overloadTable.hasOwnProperty(arguments.length)||Ne(`Function '${I}' called with an invalid number of arguments (${arguments.length}) - expects one of (${f[_].overloadTable})!`),f[_].overloadTable[arguments.length].apply(this,arguments)},f[_].overloadTable=[],f[_].overloadTable[C.argCount]=C}}function wn(f,_,I){e.hasOwnProperty(f)?((I===void 0||e[f].overloadTable!==void 0&&e[f].overloadTable[I]!==void 0)&&Ne(`Cannot register public name '${f}' twice`),cs(e,f,f),e.hasOwnProperty(I)&&Ne(`Cannot register multiple overloads of a function with the same number of arguments (${I})!`),e[f].overloadTable[I]=_):(e[f]=_,I!==void 0&&(e[f].numArguments=I))}function _c(f,_,I,C,M,$,G,U){this.name=f,this.constructor=_,this.instancePrototype=I,this.rawDestructor=C,this.baseClass=M,this.getActualType=$,this.upcast=G,this.downcast=U,this.pureVirtualFunctions=[]}function xn(f,_,I){for(;_!==I;)_.upcast||Ne(`Expected null or instance of ${I.name}, got an instance of ${_.name}`),f=_.upcast(f),_=_.baseClass;return f}function gc(f,_){if(_===null)return this.isReference&&Ne(`null is not a valid ${this.name}`),0;_.$$||Ne(`Cannot pass "${kn(_)}" as a ${this.name}`),_.$$.ptr||Ne(`Cannot pass deleted object as a pointer of type ${this.name}`);var I=_.$$.ptrType.registeredClass,C=xn(_.$$.ptr,I,this.registeredClass);return C}function Ec(f,_){var I;if(_===null)return this.isReference&&Ne(`null is not a valid ${this.name}`),this.isSmartPointer?(I=this.rawConstructor(),f!==null&&f.push(this.rawDestructor,I),I):0;_.$$||Ne(`Cannot pass "${kn(_)}" as a ${this.name}`),_.$$.ptr||Ne(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&_.$$.ptrType.isConst&&Ne(`Cannot convert argument of type ${_.$$.smartPtrType?_.$$.smartPtrType.name:_.$$.ptrType.name} to parameter type ${this.name}`);var C=_.$$.ptrType.registeredClass;if(I=xn(_.$$.ptr,C,this.registeredClass),this.isSmartPointer)switch(_.$$.smartPtr===void 0&&Ne("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:_.$$.smartPtrType===this?I=_.$$.smartPtr:Ne(`Cannot convert argument of type ${_.$$.smartPtrType?_.$$.smartPtrType.name:_.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:I=_.$$.smartPtr;break;case 2:if(_.$$.smartPtrType===this)I=_.$$.smartPtr;else{var M=_.clone();I=this.rawShare(I,ai.toHandle(function(){M.delete()})),f!==null&&f.push(this.rawDestructor,I)}break;default:Ne("Unsupporting sharing policy")}return I}function Tc(f,_){if(_===null)return this.isReference&&Ne(`null is not a valid ${this.name}`),0;_.$$||Ne(`Cannot pass "${kn(_)}" as a ${this.name}`),_.$$.ptr||Ne(`Cannot pass deleted object as a pointer of type ${this.name}`),_.$$.ptrType.isConst&&Ne(`Cannot convert argument of type ${_.$$.ptrType.name} to parameter type ${this.name}`);var I=_.$$.ptrType.registeredClass,C=xn(_.$$.ptr,I,this.registeredClass);return C}function ds(f){return this.fromWireType(Zt[f>>2])}function _l(f){return this.rawGetPointee&&(f=this.rawGetPointee(f)),f}function lo(f){this.rawDestructor&&this.rawDestructor(f)}function Mn(f){f!==null&&f.delete()}function po(){Ir.prototype.getPointee=_l,Ir.prototype.destructor=lo,Ir.prototype.argPackAdvance=8,Ir.prototype.readValueFromPointer=ds,Ir.prototype.deleteObject=Mn,Ir.prototype.fromWireType=ni}function Ir(f,_,I,C,M,$,G,U,ee,H,_e){this.name=f,this.registeredClass=_,this.isReference=I,this.isConst=C,this.isSmartPointer=M,this.pointeeType=$,this.sharingPolicy=G,this.rawGetPointee=U,this.rawConstructor=ee,this.rawShare=H,this.rawDestructor=_e,!M&&_.baseClass===void 0?C?(this.toWireType=gc,this.destructorFunction=null):(this.toWireType=Tc,this.destructorFunction=null):this.toWireType=Ec}function gl(f,_,I){e.hasOwnProperty(f)||Mi("Replacing nonexistant public symbol"),e[f].overloadTable!==void 0&&I!==void 0?e[f].overloadTable[I]=_:(e[f]=_,e[f].argCount=I)}var mo=(f,_,I)=>{var C=e["dynCall_"+f];return I&&I.length?C.apply(null,[_].concat(I)):C.call(null,_)},us=[],Ic=f=>{var _=us[f];return _||(f>=us.length&&(us.length=f+1),us[f]=_=sc.get(f)),_},ls=(f,_,I)=>{if(f.includes("j"))return mo(f,_,I);var C=Ic(_).apply(null,I);return C},El=(f,_)=>{var I=[];return function(){return I.length=0,Object.assign(I,arguments),ls(f,_,I)}};function ur(f,_){f=xt(f);function I(){return f.includes("j")?El(f,_):Ic(_)}var C=I();return typeof C!="function"&&Ne(`unknown function pointer with signature ${f}: ${_}`),C}function Tl(f,_){var I=Nn(_,function(C){this.name=_,this.message=C;var M=new Error(C).stack;M!==void 0&&(this.stack=this.toString()+`
|
|
70
|
+
`+M.replace(/^Error(:[^\n]*)?\n/,""))});return I.prototype=Object.create(f.prototype),I.prototype.constructor=I,I.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},I}var Sc=void 0;function yc(f){var _=Vc(f),I=xt(_);return Ar(_),I}function On(f,_){var I=[],C={};function M($){if(!C[$]&&!ii[$]){if(no[$]){no[$].forEach(M);return}I.push($),C[$]=!0}}throw _.forEach(M),new Sc(`${f}: `+I.map(yc).join([", "]))}function Il(f,_,I,C,M,$,G,U,ee,H,_e,ye,Re){_e=xt(_e),$=ur(M,$),U&&(U=ur(G,U)),H&&(H=ur(ee,H)),Re=ur(ye,Re);var ke=as(_e);wn(ke,function(){On(`Cannot construct ${_e} due to unbound types`,[C])}),si([f,_,I],C?[C]:[],function(Ye){Ye=Ye[0];var Ft,bt;C?(Ft=Ye.registeredClass,bt=Ft.instancePrototype):bt=Vr.prototype;var Br=Nn(ke,function(){if(Object.getPrototypeOf(this)!==Hn)throw new At("Use 'new' to construct "+_e);if(er.constructor_body===void 0)throw new At(_e+" has no accessible constructor");var Wc=er.constructor_body[arguments.length];if(Wc===void 0)throw new At(`Tried to invoke ctor of ${_e} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(er.constructor_body).toString()}) parameters instead!`);return Wc.apply(this,arguments)}),Hn=Object.create(bt,{constructor:{value:Br}});Br.prototype=Hn;var er=new _c(_e,Br,Hn,Re,Ft,$,U,H);er.baseClass&&(er.baseClass.__derivedClasses===void 0&&(er.baseClass.__derivedClasses=[]),er.baseClass.__derivedClasses.push(er));var Xl=new Ir(_e,er,!0,!1,!1),$c=new Ir(_e+"*",er,!1,!1,!1),Hc=new Ir(_e+" const*",er,!1,!0,!1);return ss[f]={pointerType:$c,constPointerType:Hc},gl(ke,Br),[Xl,$c,Hc]})}function Sr(f,_){for(var I=[],C=0;C<f;C++)I.push(P[_+C*4>>2]);return I}function Sl(f){for(;f.length;){var _=f.pop(),I=f.pop();I(_)}}function Ac(f,_){if(!(f instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof f} which is not a function`);var I=Nn(f.name||"unknownFunctionName",function(){});I.prototype=f.prototype;var C=new I,M=f.apply(C,_);return M instanceof Object?M:C}function ho(f,_,I,C,M,$){var G=_.length;G<2&&Ne("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var U=_[1]!==null&&I!==null,ee=!1,H=1;H<_.length;++H)if(_[H]!==null&&_[H].destructorFunction===void 0){ee=!0;break}for(var _e=_[0].name!=="void",ye="",Re="",H=0;H<G-2;++H)ye+=(H!==0?", ":"")+"arg"+H,Re+=(H!==0?", ":"")+"arg"+H+"Wired";var ke=`
|
|
71
71
|
return function ${as(f)}(${ye}) {
|
|
72
72
|
if (arguments.length !== ${G-2}) {
|
|
73
73
|
throwBindingError('function ${f} called with ${arguments.length} arguments, expected ${G-2} args!');
|
|
@@ -80,22 +80,22 @@ return ret;
|
|
|
80
80
|
`,Ft.push(Br+"_dtor"),bt.push(_[H].destructorFunction))}return _e&&(ke+=`var ret = retType.fromWireType(rv);
|
|
81
81
|
return ret;
|
|
82
82
|
`),ke+=`}
|
|
83
|
-
`,Ft.push(ke),Ac(Function,Ft).apply(null,bt)}function
|
|
83
|
+
`,Ft.push(ke),Ac(Function,Ft).apply(null,bt)}function Pn(f,_,I,C,M,$){var G=Sr(_,I);M=ur(C,M),si([],[f],function(U){U=U[0];var ee=`constructor ${U.name}`;if(U.registeredClass.constructor_body===void 0&&(U.registeredClass.constructor_body=[]),U.registeredClass.constructor_body[_-1]!==void 0)throw new At(`Cannot register multiple constructors with identical number of parameters (${_-1}) for class '${U.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return U.registeredClass.constructor_body[_-1]=()=>{On(`Cannot construct ${U.name} due to unbound types`,G)},si([],G,function(H){return H.splice(1,0,null),U.registeredClass.constructor_body[_-1]=ho(ee,H,null,M,$),[]}),[]})}function bc(f,_,I,C,M,$,G,U,ee){var H=Sr(I,C);_=xt(_),$=ur(M,$),si([],[f],function(_e){_e=_e[0];var ye=`${_e.name}.${_}`;_.startsWith("@@")&&(_=Symbol[_.substring(2)]),U&&_e.registeredClass.pureVirtualFunctions.push(_);function Re(){On(`Cannot call ${ye} due to unbound types`,H)}var ke=_e.registeredClass.instancePrototype,Ye=ke[_];return Ye===void 0||Ye.overloadTable===void 0&&Ye.className!==_e.name&&Ye.argCount===I-2?(Re.argCount=I-2,Re.className=_e.name,ke[_]=Re):(cs(ke,_,ye),ke[_].overloadTable[I-2]=Re),si([],H,function(Ft){var bt=ho(ye,Ft,_e,$,G,ee);return ke[_].overloadTable===void 0?(bt.argCount=I-2,ke[_]=bt):ke[_].overloadTable[I-2]=bt,[]}),[]})}function yl(){Object.assign(vc.prototype,{get(f){return this.allocated[f]},has(f){return this.allocated[f]!==void 0},allocate(f){var _=this.freelist.pop()||this.allocated.length;return this.allocated[_]=f,_},free(f){this.allocated[f]=void 0,this.freelist.push(f)}})}function vc(){this.allocated=[void 0],this.freelist=[]}var Ot=new vc;function Rc(f){f>=Ot.reserved&&--Ot.get(f).refcount===0&&Ot.free(f)}function Al(){for(var f=0,_=Ot.reserved;_<Ot.allocated.length;++_)Ot.allocated[_]!==void 0&&++f;return f}function bl(){Ot.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Ot.reserved=Ot.allocated.length,e.count_emval_handles=Al}var ai={toValue:f=>(f||Ne("Cannot use deleted val. handle = "+f),Ot.get(f).value),toHandle:f=>{switch(f){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Ot.allocate({refcount:1,value:f})}}};function vl(f,_){_=xt(_),Kt(f,{name:_,fromWireType:function(I){var C=ai.toValue(I);return Rc(I),C},toWireType:function(I,C){return ai.toHandle(C)},argPackAdvance:8,readValueFromPointer:ds,destructorFunction:null})}function kn(f){if(f===null)return"null";var _=typeof f;return _==="object"||_==="array"||_==="function"?f.toString():""+f}function Rl(f,_){switch(_){case 2:return function(I){return this.fromWireType(Me[I>>2])};case 3:return function(I){return this.fromWireType(gn[I>>3])};default:throw new TypeError("Unknown float type: "+f)}}function Cl(f,_,I){var C=os(I);_=xt(_),Kt(f,{name:_,fromWireType:function(M){return M},toWireType:function(M,$){return $},argPackAdvance:8,readValueFromPointer:Rl(_,C),destructorFunction:null})}function yr(f,_,I){switch(_){case 0:return I?function(M){return ei[M]}:function(M){return Pe[M]};case 1:return I?function(M){return tt[M>>1]}:function(M){return Yt[M>>1]};case 2:return I?function(M){return Zt[M>>2]}:function(M){return P[M>>2]};default:throw new TypeError("Unknown integer type: "+f)}}function Dl(f,_,I,C,M){_=xt(_),M===-1&&(M=4294967295);var $=os(I),G=ye=>ye;if(C===0){var U=32-8*I;G=ye=>ye<<U>>>U}var ee=_.includes("unsigned"),H=(ye,Re)=>{},_e;ee?_e=function(ye,Re){return H(Re,this.name),Re>>>0}:_e=function(ye,Re){return H(Re,this.name),Re},Kt(f,{name:_,fromWireType:G,toWireType:_e,argPackAdvance:8,readValueFromPointer:yr(_,$,C!==0),destructorFunction:null})}function Nl(f,_,I){var C=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],M=C[_];function $(G){G=G>>2;var U=P,ee=U[G],H=U[G+1];return new M(U.buffer,H,ee)}I=xt(I),Kt(f,{name:I,fromWireType:$,argPackAdvance:8,readValueFromPointer:$},{ignoreDuplicateRegistrations:!0})}var ps=(f,_,I,C)=>{if(!(C>0))return 0;for(var M=I,$=I+C-1,G=0;G<f.length;++G){var U=f.charCodeAt(G);if(U>=55296&&U<=57343){var ee=f.charCodeAt(++G);U=65536+((U&1023)<<10)|ee&1023}if(U<=127){if(I>=$)break;_[I++]=U}else if(U<=2047){if(I+1>=$)break;_[I++]=192|U>>6,_[I++]=128|U&63}else if(U<=65535){if(I+2>=$)break;_[I++]=224|U>>12,_[I++]=128|U>>6&63,_[I++]=128|U&63}else{if(I+3>=$)break;_[I++]=240|U>>18,_[I++]=128|U>>12&63,_[I++]=128|U>>6&63,_[I++]=128|U&63}}return _[I]=0,I-M},Cc=(f,_,I)=>ps(f,Pe,_,I),wl=f=>{for(var _=0,I=0;I<f.length;++I){var C=f.charCodeAt(I);C<=127?_++:C<=2047?_+=2:C>=55296&&C<=57343?(_+=4,++I):_+=3}return _},Dc=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,ci=(f,_,I)=>{for(var C=_+I,M=_;f[M]&&!(M>=C);)++M;if(M-_>16&&f.buffer&&Dc)return Dc.decode(f.subarray(_,M));for(var $="";_<M;){var G=f[_++];if(!(G&128)){$+=String.fromCharCode(G);continue}var U=f[_++]&63;if((G&224)==192){$+=String.fromCharCode((G&31)<<6|U);continue}var ee=f[_++]&63;if((G&240)==224?G=(G&15)<<12|U<<6|ee:G=(G&7)<<18|U<<12|ee<<6|f[_++]&63,G<65536)$+=String.fromCharCode(G);else{var H=G-65536;$+=String.fromCharCode(55296|H>>10,56320|H&1023)}}return $},Nc=(f,_)=>f?ci(Pe,f,_):"";function wc(f,_){_=xt(_);var I=_==="std::string";Kt(f,{name:_,fromWireType:function(C){var M=P[C>>2],$=C+4,G;if(I)for(var U=$,ee=0;ee<=M;++ee){var H=$+ee;if(ee==M||Pe[H]==0){var _e=H-U,ye=Nc(U,_e);G===void 0?G=ye:(G+=String.fromCharCode(0),G+=ye),U=H+1}}else{for(var Re=new Array(M),ee=0;ee<M;++ee)Re[ee]=String.fromCharCode(Pe[$+ee]);G=Re.join("")}return Ar(C),G},toWireType:function(C,M){M instanceof ArrayBuffer&&(M=new Uint8Array(M));var $,G=typeof M=="string";G||M instanceof Uint8Array||M instanceof Uint8ClampedArray||M instanceof Int8Array||Ne("Cannot pass non-string to std::string"),I&&G?$=wl(M):$=M.length;var U=Fn(4+$+1),ee=U+4;if(P[U>>2]=$,I&&G)Cc(M,ee,$+1);else if(G)for(var H=0;H<$;++H){var _e=M.charCodeAt(H);_e>255&&(Ar(ee),Ne("String has UTF-16 code units that do not fit in 8 bits")),Pe[ee+H]=_e}else for(var H=0;H<$;++H)Pe[ee+H]=M[H];return C!==null&&C.push(Ar,U),U},argPackAdvance:8,readValueFromPointer:ds,destructorFunction:function(C){Ar(C)}})}var Ln=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,Un=(f,_)=>{for(var I=f,C=I>>1,M=C+_/2;!(C>=M)&&Yt[C];)++C;if(I=C<<1,I-f>32&&Ln)return Ln.decode(Pe.subarray(f,I));for(var $="",G=0;!(G>=_/2);++G){var U=tt[f+G*2>>1];if(U==0)break;$+=String.fromCharCode(U)}return $},xl=(f,_,I)=>{if(I===void 0&&(I=2147483647),I<2)return 0;I-=2;for(var C=_,M=I<f.length*2?I/2:f.length,$=0;$<M;++$){var G=f.charCodeAt($);tt[_>>1]=G,_+=2}return tt[_>>1]=0,_-C},xc=f=>f.length*2,Ml=(f,_)=>{for(var I=0,C="";!(I>=_/4);){var M=Zt[f+I*4>>2];if(M==0)break;if(++I,M>=65536){var $=M-65536;C+=String.fromCharCode(55296|$>>10,56320|$&1023)}else C+=String.fromCharCode(M)}return C},Mc=(f,_,I)=>{if(I===void 0&&(I=2147483647),I<4)return 0;for(var C=_,M=C+I-4,$=0;$<f.length;++$){var G=f.charCodeAt($);if(G>=55296&&G<=57343){var U=f.charCodeAt(++$);G=65536+((G&1023)<<10)|U&1023}if(Zt[_>>2]=G,_+=4,_+4>M)break}return Zt[_>>2]=0,_-C},Oc=f=>{for(var _=0,I=0;I<f.length;++I){var C=f.charCodeAt(I);C>=55296&&C<=57343&&++I,_+=4}return _},Ol=function(f,_,I){I=xt(I);var C,M,$,G,U;_===2?(C=Un,M=xl,G=xc,$=()=>Yt,U=1):_===4&&(C=Ml,M=Mc,G=Oc,$=()=>P,U=2),Kt(f,{name:I,fromWireType:function(ee){for(var H=P[ee>>2],_e=$(),ye,Re=ee+4,ke=0;ke<=H;++ke){var Ye=ee+4+ke*_;if(ke==H||_e[Ye>>U]==0){var Ft=Ye-Re,bt=C(Re,Ft);ye===void 0?ye=bt:(ye+=String.fromCharCode(0),ye+=bt),Re=Ye+_}}return Ar(ee),ye},toWireType:function(ee,H){typeof H!="string"&&Ne(`Cannot pass non-string to C++ string type ${I}`);var _e=G(H),ye=Fn(4+_e+_);return P[ye>>2]=_e>>U,M(H,ye+4,_e+_),ee!==null&&ee.push(Ar,ye),ye},argPackAdvance:8,readValueFromPointer:ds,destructorFunction:function(ee){Ar(ee)}})};function Pl(f,_){_=xt(_),Kt(f,{isVoid:!0,name:_,argPackAdvance:0,fromWireType:function(){},toWireType:function(I,C){}})}var kl={};function Pc(f){var _=kl[f];return _===void 0?xt(f):_}var Pt=[];function kc(f,_,I,C){f=Pt[f],_=ai.toValue(_),I=Pc(I),f(_,I,null,C)}function Ll(f){var _=Pt.length;return Pt.push(f),_}function Ul(f,_){var I=ii[f];return I===void 0&&Ne(_+" has unknown type "+yc(f)),I}function ms(f,_){for(var I=new Array(f),C=0;C<f;++C)I[C]=Ul(P[_+C*4>>2],"parameter "+C);return I}var Lc=[];function Vn(f,_){var I=ms(f,_),C=I[0],M=C.name+"_$"+I.slice(1).map(function(Ye){return Ye.name}).join("_")+"$",$=Lc[M];if($!==void 0)return $;for(var G=["retType"],U=[C],ee="",H=0;H<f-1;++H)ee+=(H!==0?", ":"")+"arg"+H,G.push("argType"+H),U.push(I[1+H]);for(var _e=as("methodCaller_"+M),ye="return function "+_e+`(handle, name, destructors, args) {
|
|
84
84
|
`,Re=0,H=0;H<f-1;++H)ye+=" var arg"+H+" = argType"+H+".readValueFromPointer(args"+(Re?"+"+Re:"")+`);
|
|
85
85
|
`,Re+=I[H+1].argPackAdvance;ye+=" var rv = handle[name]("+ee+`);
|
|
86
86
|
`;for(var H=0;H<f-1;++H)I[H+1].deleteObject&&(ye+=" argType"+H+".deleteObject(arg"+H+`);
|
|
87
87
|
`);C.isVoid||(ye+=` return retType.toWireType(destructors, rv);
|
|
88
88
|
`),ye+=`};
|
|
89
|
-
`,G.push(ye);var ke=Ac(Function,G).apply(null,U);return $=Ll(ke),Lc[M]=$,$}var Vl=()=>{Ni("")},Uc;Uc=()=>performance.now();var Bl=(f,_,I)=>Pe.copyWithin(f,_,_+I),Fl=f=>{Ni("OOM")},$l=f=>{var _=Pe.length;f>>>=0,Fl(f)},Hl=[null,[],[]],Wl=(f,_)=>{var I=Hl[f];_===0||_===10?((f===1?Bt:Xe)(ci(I,0)),I.length=0):I.push(_)},Vn={varargs:void 0,get(){Vn.varargs+=4;var f=Zt[Vn.varargs-4>>2];return f},getStr(f){var _=Nc(f);return _}},Gl=(f,_,I,C)=>{for(var M=0,$=0;$<I;$++){var G=P[_>>2],U=P[_+4>>2];_+=8;for(var ee=0;ee<U;ee++)Wl(f,Pe[G+ee]);M+=U}return P[C>>2]=M,0};ll(),At=e.BindingError=class extends Error{constructor(_){super(_),this.name="BindingError"}},oi=e.InternalError=class extends Error{constructor(_){super(_),this.name="InternalError"}},uo(),Cn(),po(),Sc=e.UnboundTypeError=Tl(Error,"UnboundTypeError"),yl(),bl();var jl={o:An,r:ul,m:pl,q:Il,p:On,d:bc,u:vl,k:Cl,b:Dl,a:Nl,j:wc,g:Ol,n:Pl,e:kc,l:Rc,h:Un,f:Vl,c:Uc,t:Bl,s:$l,i:Gl},Nf=ac(),ql=()=>(ql=Ge.w)(),Ar=f=>(Ar=Ge.x)(f),Bn=f=>(Bn=Ge.y)(f),Vc=f=>(Vc=Ge.A)(f),zl=e.__embind_initialize_bindings=()=>(zl=e.__embind_initialize_bindings=Ge.B)(),Jl=()=>(Jl=Ge.__errno_location)(),Bc=f=>(Bc=Ge.C)(f),Fn=e.dynCall_jiji=(f,_,I,C,M)=>(Fn=e.dynCall_jiji=Ge.D)(f,_,I,C,M),hs;ri=function f(){hs||Fc(),hs||(ri=f)};function Fc(){if(ti>0||(ol(),ti>0))return;function f(){hs||(hs=!0,e.calledRun=!0,!fn&&(sl(),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),z()))}e.setStatus?(e.setStatus("Running..."),setTimeout(function(){setTimeout(function(){e.setStatus("")},1),f()},1)):f()}if(e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();return Fc(),t.ready}})(),$g=Ry;var yu=class extends Qr{constructor(t){super($g,t!=null&&t.wasmPath?fetch(t.wasmPath).then(e=>e.arrayBuffer()):void 0,t==null?void 0:t.workerMode,t==null?void 0:t.canvas,t==null?void 0:t.yuvMode)}};var ah=class{constructor(t){this.core=t;this.contextMap=new Map;this.decodeProcessorMap=new WeakMap;this.createDecoder=this.createDecoder.bind(this)}getAlias(){return"videoDecoder"}getGroup(t){return t!=null&&t.track?`${t.track.userId}${t.track.streamType}`:"*"}getName(){return ah.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return this.core.rtcDectection.isSIMDSupported()?new yu(me(J({},e),{wasmPath:`${this.core.assetsPath}videodec_simd.wasm`})):new Su(me(J({},e),{wasmPath:`${this.core.assetsPath}videodec.wasm`}));case"webCodecs":return new Di;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:a})=>{if(a!==t.track||s.type==="empty")return s;if(this.contextMap.has(a))return this.contextMap.get(a).decode(s);let d=this.core.room.videoManager.createDecodeContext(me(J({},t),{createDecoder:this.createDecoder}));return e(d.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:a})})),this.contextMap.set(a,d),d.decode(s)}}stop(t){if(!(t!=null&&t.track))this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});else{let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.contextMap.delete(t.track))}this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}update(t){let e=this.contextMap.get(t.track);if(!!e){if(t.type==="mock"){e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST);return}e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(me(J({},t),{createDecoder:this.createDecoder})))}}},Ja=ah;Ja.Name="TRTCVideoDecoder";function Oe(...i){}var Cy=i=>i();function dh(){this.dispose()}var Dy=()=>typeof __FASTRX_DEVTOOLS__!="undefined",Ny=1,Yr=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new ch(t,this,this.streamId++);return ut.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Ks=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Oe,this.error=Oe,this.next=Oe,this.dispose=Oe,this.subscribe=Oe,this.doDefer()}subscribe(t){return t instanceof Yr?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Cy),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},pe=class extends Ks{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},Au=class extends Ks{constructor(t,e=Oe,r=Oe,o=Oe){if(super(),this._next=e,this._error=r,this._complete=o,this.then=Oe,t instanceof Yr){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{ut.defer(s,0)}),ut.create(s),ut.pipe(s),this.sourceId=s.id,this.subscribe(t),ut.subscribe({id:s.id,end:!0}),e==Oe?this._next=a=>ut.next(s,0,a):this.next=a=>{ut.next(s,0,a),e(a)},o==Oe?this._complete=()=>ut.complete(s,0):this.complete=()=>{this.dispose(),ut.complete(s,0),o()},r==Oe?this._error=a=>ut.complete(s,0,a):this.error=a=>{this.dispose(),ut.complete(s,0,a),r()}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function Xt(i,...t){return t.reduce((e,r)=>r(e),i)}function Mr(i,t,e){if(Dy()){let r=Object.defineProperties(Object.setPrototypeOf(i,Yr.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});ut.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof Yr&&ut.addSource(r,s)}return r}return i}function Te(i,t){return function(...e){return r=>{if(r instanceof Yr){let o=Mr(s=>{let a=new i(s,...e);a.sourceId=o.id,a.subscribe(r)},t,arguments);return o.source=r,ut.pipe(o),o}else return o=>r(new i(o,...e))}}}function Zi(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var ch=class extends pe{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{ut.defer(this.source,this.id)})}next(t){ut.next(this.source,this.id,t),this.sink.next(t)}complete(){ut.complete(this.source,this.id),this.sink.complete()}error(t){ut.complete(this.source,this.id,t),this.sink.error(t)}},ut={addSource(i,t){Zi("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){Zi("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){Zi("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){Zi("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){Zi("defer",{id:i.id,streamId:t})},pipe(i){Zi("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){Zi("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=Ny++),Zi("create",{name:i.toString(),id:i.id})}},bu=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var uh=class extends Ks{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function Hg(){return i=>{let t=new uh(i);if(i instanceof Yr){let e=Mr(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,ut.pipe(e),e}return Mr(t.add.bind(t),"share",arguments)}}function wy(...i){return Mr(t=>{let e=i.length,r=e,o=e,s=new Array(e),a=()=>{--o===0&&t.complete()},d=(h,p)=>{let T=new pe(t);T.next=y=>{--r===0?(T.next=R=>{s[p]=R,t.next(s)},T.next(y)):s[p]=y},T.complete=a,T.subscribe(h)};i.forEach(d)},"combineLatest",arguments)}var lh=class extends pe{constructor(t,...e){super(t);let r=new pe(this.sink);r.next=o=>this.buffer=o,r.complete=Oe,r.subscribe(wy(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},KM=Te(lh,"withLatestFrom"),ph=class extends pe{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(t=>this.sink.next(t)),super.complete()}},eO=Te(ph,"bufferCount"),mh=class extends pe{constructor(t,e){super(t),this.buffer=[];let r=new pe(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=Oe,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},tO=Te(mh,"buffer");function en(i){let t=arguments,e=Hg()(Mr(r=>{e.next=o=>r.next(o),e.complete=()=>r.complete(),e.error=o=>r.error(o),i&&r.subscribe(i)},"subject",t));return e.next=Oe,e.complete=Oe,e.error=Oe,e}function hh(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function Qt(i,t){if("on"in i)return Mr(hh(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i)return Mr(hh(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return Mr(hh(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}var fh=class extends pe{constructor(t,e,r){super(t),this.f=e;let o=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=s=>{this.acc=s,this.complete=o,this.resetNext()}:(this.acc=r,this.complete=o)}next(t){this.acc=this.f(this.acc,t)}},xy=Te(fh,"reduce");var _h=class extends pe{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},pO=Te(_h,"filter"),gh=class extends pe{next(t){}},mO=Te(gh,"ignoreElements"),Eh=class extends pe{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},Wg=Te(Eh,"take"),Th=class extends pe{constructor(t,e){super(t);let r=new pe(t);r.next=()=>t.complete(),r.complete=dh,r.subscribe(e)}},Ki=Te(Th,"takeUntil"),Ih=class extends pe{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},hO=Te(Ih,"takeWhile");var Sh=class extends pe{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},fO=Te(Sh,"skip"),yh=class extends pe{constructor(t,e){super(t),t.next=Oe;let r=new pe(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=dh,r.subscribe(e)}},_O=Te(yh,"skipUntil"),Ah=class extends pe{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},gO=Te(Ah,"skipWhile"),My={leading:!0,trailing:!1},bh=class extends pe{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},vh=class extends pe{constructor(t,e,r=My){super(t),this.durationSelector=e,this.config=r,this._throttle=new bh(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=Oe,this._throttle.complete(),super.complete()}},EO=Te(vh,"throttle");var Rh=class extends pe{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ch=class extends pe{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Rh(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},TO=Te(Ch,"debounce");var Dh=class extends pe{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},IO=Te(Dh,"elementAt");var Nh=class extends pe{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},SO=Te(Nh,"findIndex"),wh=class extends pe{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},yO=Te(wh,"first"),xh=class extends pe{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},AO=Te(xh,"last"),Mh=class extends pe{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},bO=Te(Mh,"every");var Oh=class extends pe{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=o=>{this.acc=o,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},DO=Te(Oh,"scan"),Ph=class extends pe{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},NO=Te(Ph,"pairwise"),kh=class extends pe{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},Gg=Te(kh,"map");var tn=class extends pe{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},rn=class extends pe{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},vu=class extends tn{},Ru=class extends rn{next(t){this.subInner(t,vu),this.next=e=>{this.currentSink.dispose(),this.subInner(e,vu)}}},jg=Te(Ru,"switchMap");function wu(i){return(t,e)=>i(()=>t,e)}var qg=wu(Te(Ru,"switchMapTo")),Lh=class extends tn{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Cu=class extends rn{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),Lh),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},wO=Te(Cu,"concatMap"),xO=wu(Te(Cu,"concatMapTo")),Uh=class extends tn{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Du=class extends rn{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Uh),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},MO=Te(Du,"mergeMap"),OO=wu(Te(Du,"mergeMapTo")),Vh=class extends tn{dispose(){this.context.resetNext(),super.dispose()}},Nu=class extends rn{next(t){this.next=Oe,this.subInner(t,Vh)}},PO=Te(Nu,"exhaustMap"),kO=wu(Te(Nu,"exhaustMapTo")),Bh=class extends pe{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=en(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},LO=Te(Bh,"groupBy"),Fh=class extends pe{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},UO=Te(Fh,"timeInterval"),$h=class extends pe{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},VO=Te($h,"bufferTime"),Hh=class extends pe{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:o}=e;super.next(o),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},BO=Te(Hh,"delay"),Wh=class extends pe{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},FO=Te(Wh,"catchError");var cr=(i=Oe,t=Oe,e=Oe)=>r=>new Au(r,i,t,e),Gh=class extends pe{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},zg=Te(Gh,"tap"),jh=class extends pe{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new bu(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},WO=Te(jh,"timeout");function Xg(i,t=!1){let e=Object.defineProperties(en(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Oe,i.onmessageerror=Oe,i=o,r()}}});function r(){i.onmessage=o=>{o.data?o.ports.length||t?e.next(o):e.next(o.data):(e.complete(),i.close())},i.onmessageerror=o=>{e.error(o),i.close()}}return r(),e}var qh=class extends pe{constructor(t,e){super(t);let r=new pe(t);r.next=Oe,e(r)}},sP=Te(qh,"takeUntilComplete");var yt={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},Jh="__INLINE__WORKER__",Jg="__INLINE__WASM__",{debug:Qg}=console;yt.debug||(console.debug=()=>{});var zh=!Jh.startsWith("__");function Yg(){return`${yt.assetsPath?`${yt.assetsPath}/`:""}worker.js`}function Zg(){let i=Yg();return zh||i.startsWith("http")?URL.createObjectURL(new Blob([zh?atob(Jh):`importScripts('${i}')`])):i}function Kg(){let i=Yg();return zh?URL.createObjectURL(new Blob([atob(Jh)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var xu=Jg.startsWith("__")?`${yt.assetsPath?`${yt.assetsPath}/`:""}av_processing.wasm`:`data:application/octet-stream;base64,${Jg}`;var Xh=class{constructor(){this.playPortSent=!1;Xt(Qt(document,"mousedown"),Wg(1),cr(()=>this.resume().catch(t=>{console.error("audio worklet init failed:",t)}))),this.workletPromise=this.init()}resume(){return v(this,null,function*(){if(this.audioCtx){this.audioCtx.resume();return}})}init(){return v(this,null,function*(){this.audioCtx=new AudioContext({sampleRate:48e3});let t=Kg();V.info("AudioContext Created:",this.audioCtx,t),yield this.audioCtx.audioWorklet.addModule(typeof t=="string"?t:yield t);let e=yield fetch(xu).then(r=>r.arrayBuffer());return this.worklet=new AudioWorkletNode(this.audioCtx,"global-audio-player",{processorOptions:{wasm:e,flag:yt},numberOfInputs:2}),V.info("worklet created",this.audioCtx.state),this.worklet.connect(this.audioCtx.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return v(this,null,function*(){this.playPortSent||(this.playPortSent=!0,t(yield this.workletPromise))})}},eo=new Xh;var SE=Pi(Hi());function Qh({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Ce((r,o)=>{let s=new WeakMap;return B.on(O.ROOM_DESTROY,({room:a})=>s.delete(a)),function(...a){let d=s.get(this);if(d||(d={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,d)),d.timestamp===0?d.timestamp=Date.now():Date.now()-d.timestamp>1e3&&(d.timestamp=Date.now(),d.callCountInSecond=0,d.totalSizeInSecond=0),e&&(d.totalSizeInSecond+=e(...a)),d.timestamp!==0&&Date.now()-d.timestamp<1e3&&(d.callCountInSecond>=i||d.totalSizeInSecond>t))throw new de({code:Y.INVALID_OPERATION,message:ot({key:it.CALL_FREQUENCY_LIMIT,data:{isTimes:d.callCountInSecond>=i,isSize:d.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});d.callCountInSecond++,r.call(this,...a)}})}var Oy="2025-02-12 15:53:00",eE=!0,tE=function(){var i;eE&&(eE=!1,V.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Fr}/en/index.html`),console.info(`* Changelog: ${Fr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),V.info("TRTC Web SDK Version:",Ke),wr||V.debug("Build Time:",Oy),V.info("UA:",navigator.userAgent),V.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),ga().then(t=>{t&&V.info(Rr)}))};var gr={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var ne={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},Or=(w=>(w[w.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",w[w.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",w[w.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",w[w.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",w[w.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",w[w.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",w[w.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",w[w.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",w[w.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",w[w.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",w[w.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",w[w.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",w[w.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",w[w.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",w[w.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",w[w.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",w[w.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",w[w.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",w[w.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",w[w.INVALID_OPERATION=5100]="INVALID_OPERATION",w[w.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",w[w.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",w[w.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",w[w.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",w[w.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",w[w.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",w[w.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",w[w.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",w[w.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",w[w.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",w[w.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",w[w.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",w[w.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",w[w.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",w[w.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",w[w.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",w[w.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",w[w.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",w[w.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",w[w.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",w[w.DEVICE_ERROR=5300]="DEVICE_ERROR",w[w.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",w[w.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",w[w.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",w[w.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",w[w.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",w[w.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",w[w.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",w[w.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",w[w.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",w[w.SERVER_ERROR=5400]="SERVER_ERROR",w[w.NEED_TO_BUY=5401]="NEED_TO_BUY",w[w.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",w[w.OPERATION_FAILED=5500]="OPERATION_FAILED",w[w.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",w[w.REJOIN_FAILED=5502]="REJOIN_FAILED",w[w.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",w[w.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",w[w.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",w[w.OPERATION_ABORT=5998]="OPERATION_ABORT",w[w.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",w))(Or||{});function iE({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=Or[i];try{o=rE[s]}catch(a){o=rE.UNKNOWN_ERROR}return Ve(o)?r=o(t):Ae(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var rE=me(J({},jt),{INVALID_PARAMETER({fnName:i}){return`the parameters of the '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${o}' must be type of ${s} when calling ${e}(), received type: ${mt(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${o}' must be instanceof ${s} when calling ${e}(), received type: ${mt(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:i,rule:t,value:e}){return`the min value of ${i||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:i,rule:t,value:e}){return`the max value of ${i||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:i,fnName:t}){return`'${i}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:i,fnName:t,type:e}){return`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`},INVALID_STREAM_ID({key:i}){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:i}){return`'${i}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:i}){return`'${i}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:i}){return`'${i}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:i})=>`'streamType' is required when 'userId' is not '*', calling ${i}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:i}){return`the API '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:i}){return`cannot ${i} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing ${t.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:i}){return`you are already ${i}(), cannot repeated call '${i}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:i}){return`cannot call '${i}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:i}){return`cannot call '${i}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:i})=>`the buffer size of paramerter '${i}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>`role: '${"audience"}' cannot call this api.`,INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:i})=>`you need to call ${i}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:i}){return`the current browser does not support the capability of the function '${i}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:i}){return`cannot call ${i} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:i,error:t}){return`'${i}' got device exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`NotFoundError, no ${t} detected, please check your device and the configuration on '${i}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`NotAllowedError, you have disabled ${t} access, please allow the current application to use the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`NotReadableError, the ${t} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${t}, and it is recommended to turn on the ${t} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:i}){return`camera recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},MICROPHONE_RECOVER_FAILED({error:i}){return`microphone recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},OPERATION_FAILED({fnName:i,error:t}){return`'${i}' failed, reason: ${t==null?void 0:t.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:i}){return`an error was caught on trtc.on('${i}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:i,error:t}){return`video context error ${i} ${(t==null?void 0:t.name)||""} ${(t==null?void 0:t.message)||""}`},SERVER_ERROR({fnName:i,error:t}){return`'${i}' got server error: ${t==null?void 0:t.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:i,url:t}){return`You need to buy packages for ${i}. Refer to: ${t}`},ACCOUNT_NO_MONEY:({fnParams:i})=>`your TRTC account run out of credit, please recharge.${i.sdkAppId?` SDKAppId: ${i.sdkAppId}`:""}`,OPERATION_ABORT({fnName:i}){return`'${i}' abort`},UNKNOWN_ERROR({fnName:i,error:t}){return`'${i}' throw unknown exception${t?`, error: ${t.toString()}.`:"."}`}});function zo(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var Jo=class extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:a="",originError:d}){var p;let h;o?h=o:h=iE({code:e===ne.SERVER_ERROR?e:r||e,params:J({fnName:a,error:d},s)});super(h);l(this,"name","RtcError");l(this,"code");l(this,"extraCode");l(this,"functionName");l(this,"message");l(this,"handler");l(this,"originError");this.name=Or[e],this.code=e,this.extraCode=r,this.functionName=a,this.originError=d,this.message=h,this.extraCode===5302&&((p=this.originError)==null?void 0:p.message.includes("system"))&&(this.handler=()=>{let T={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},y={startLocalVideo:"webcam",startLocalAudio:"microphone"},R=document.createElement("a");Ao?R.href=`ms-settings:privacy-${y[this.functionName]}`:Nr&&(R.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${T[this.functionName]}`),R.href.length>0&&R.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof de){let{stack:a}=e,d={code:ne.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case Y.INVALID_PARAMETER:d.code=ne.INVALID_PARAMETER,d.message=e.message;break;case Y.INVALID_OPERATION:d.code=ne.INVALID_OPERATION;break;case Y.NOT_SUPPORTED:case Y.NOT_SUPPORTED_H264:d.code=ne.ENV_NOT_SUPPORTED,e.getCode()===Y.NOT_SUPPORTED_H264&&(d.extraCode=e.message.includes(jt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Y.JOIN_ROOM_FAILED:d.messageParams={fnParams:o};case Y.SERVER_TIMEOUT:case Y.SWITCH_ROLE_FAILED:d.code=ne.SERVER_ERROR,d.extraCode=e.getExtraCode();break;case Y.API_CALL_ABORTED:d.code=ne.OPERATION_ABORT;break;case Y.DEVICE_NOT_FOUND:case Y.DEVICE_AUTO_RECOVER_FAILED:case Y.INITIALIZE_FAILED:d.code=5300,e.name&&(d.extraCode=Py(e.name));break;case Y.UNKNOWN:break;default:d.code=ne.OPERATION_FAILED}s=new Jo(d),a&&(s.stack+=a.substr(a.indexOf(`
|
|
90
|
-
`)))}else{if(e instanceof Jo)return e;s=new Jo({code:ne.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function Py(i){let t;switch(i){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var oe=Jo;var oE={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},sE={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},on={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(Ae(i)&&!document.getElementById(i))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},nE={name:"userId",required:!0,type:"string"},aE={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[gr.AUDIO_PROFILE_STANDARD,gr.AUDIO_PROFILE_STANDARD_STEREO,gr.AUDIO_PROFILE_HIGH,gr.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Xa(i,t){if(!i)throw new oe({code:ne.INVALID_OPERATION,extraCode:5101,fnName:t})}function cE(i,t,e){if(!i)throw new oe({code:ne.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}var ok={type:"number",notLessThanZero:!0},ky={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(i,t,e){if(this._room.isJoined)throw new oe({code:ne.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(Ae(i.roomId))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(i.roomId))&&i.roomId<4294967295))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:t}})}else if(i.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i.strRoomId))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:t}})}else throw new oe({code:ne.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:on,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:oE},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&Ai())throw new oe({code:ne.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:me(J({},on),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:oE}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:aE},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&Ai())throw new oe({code:ne.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:aE}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:on,publish:{type:"boolean"},option:sE},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)&&Ai())throw new oe({code:ne.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ca())throw new oe({code:ne.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:on,publish:{type:"boolean"},option:sE}},muteRemoteAudio:[nE,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[nE,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:on,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(i,t,e){Xa(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(cE(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:ne.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:me(J({},on),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(i,t,e){Xa(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(cE(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:ne.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(i,t,e){if(i.userId!=="*"&&L(i.streamType))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){Xa(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(i,t,e,r){if(!xa)throw new oe({code:ne.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new oe({code:ne.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});Xa(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(i,t,e){if(!i&&!this._room.isMainStreamPublished||i&&!this._room.isAuxStreamPublished)throw new oe({code:ne.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(i,t,e,r){if(i.byteLength>1e3)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(Xa(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new oe({code:ne.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}}},Tt={TRTC:ky};var Dt=class extends Error{};function Ly(i,t){let e=Io(i);for(let r=0;r<t.length;r++)Wr(e[r],t[r]);return e}function Uy(i){this._resolve=Promise.resolve(i)}function Vy(i){this._reject=Promise.reject(i)}var Xo=class{constructor(t,e){this.instance=t;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=Ly;let r=Xo.instances.get(t);r?r.set(e,this):Xo.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=Xo.instances.get(t);return r&&r.get(e)||new Xo(t,e)}static gets(t,e){let r=Xo.instances.get(t),o=[];return r&&r.forEach((s,a)=>{e.test(a)&&o.push(s)}),o}action(t,e,r){let o=d=>{var h;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(h=this.currentOp)==null||h.action(),d},s=d=>{var h,p;throw this.ops.shift(),t===0&&((h=this.currentOp)==null?void 0:h.type)===2&&this.ops.shift().reject(new Dt("start failed")),(p=this.currentOp)==null||p.action(),d},a={type:t,action:()=>e(...a.args).then(o,s),args:r,resolve:Uy,reject:Vy};try{switch(this.state){case 1:if(t===0)throw new Dt("already started");break;case 4:if(t===2)throw new Dt("not started");break;default:return this.cacheOp(a)}}catch(d){return Promise.reject(d)}return this.ops.push(a),a.promise=e(...a.args).then(o,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Dt("already start");break;case 3:switch(t.type){case 2:throw new Dt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Dt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Dt("keep stop");if(this.ops.slice(1).forEach(o=>o.reject(r)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,t.args),this.lastOp.promise;case 3:throw new Dt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Dt("start not allowed after update");case 0:throw new Dt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Dt("keep start")),new Dt("already start")}}t.promise=new Promise((r,o)=>{t._resolve?t._resolve.then(r):t.resolve=r,t._reject?t._reject.catch(o):t.reject=o});let{action:e}=t;return t.action=()=>e().then(t.resolve,t.reject),this.ops.push(t),t.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},Zr=Xo;Zr.instances=new WeakMap;var Mu=new WeakMap,Ou=(i,t)=>{if(t instanceof Dt){let{stack:e}=t;t=new oe({code:ne.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
91
|
-
`)))}throw t};function to(i,t){return Ce((e,r)=>function(...o){let s=Zr.get(this,typeof i=="string"?i:i.call(this,...o));return s?(t&&(s.startSame=t.bind(this)),s.action(0,e.bind(this),o).catch(Ou.bind(null,r))):e.apply(this,o)})}function Qo(i,t){let{merge:e,debounce:r}=t||{};return Ce((o,s)=>function(...a){let d=Zr.get(this,typeof i=="string"?i:i.call(this,...a));if(!d)return o.apply(this,a);if(e&&(d.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,a)){let{delay:h,getKey:p}=r;return new Promise((T,y)=>{var j,W;let R=(j=Mu.get(this))==null?void 0:j.get(p(...a));if(R){let{timeoutId:F,resolve:Ie}=R;clearTimeout(F),Ie()}let N=setTimeout(()=>{if(d.state===3||d.state===4)return T();d.action(2,o.bind(this),a).catch(Ou.bind(null,s)).then(T,y)},h);Mu.has(this)?(W=Mu.get(this))==null||W.set(p(...a),{timeoutId:N,resolve:T}):Mu.set(this,new Map([[p(...a),{timeoutId:N,resolve:T}]]))})}return d.action(2,o.bind(this),a).catch(Ou.bind(null,s))})}function ro(i){return Ce((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(Zr.gets(this,o).map(a=>a.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=Zr.get(this,o);return s?s.action(3,t.bind(this),r).catch(Ou.bind(null,e)):t.apply(this,r)})}var re={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData"},dE=new Set([re.ERROR,re.AUTOPLAY_FAILED,re.KICKED_OUT,re.REMOTE_USER_ENTER,re.REMOTE_USER_EXIT,re.REMOTE_AUDIO_AVAILABLE,re.REMOTE_AUDIO_UNAVAILABLE,re.REMOTE_VIDEO_AVAILABLE,re.REMOTE_VIDEO_UNAVAILABLE,re.CONNECTION_STATE_CHANGED,re.PUBLISH_STATE_CHANGED,re.SCREEN_SHARE_STOPPED,re.DEVICE_CHANGED]);function Qa(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function Ya(i){return i===gr.QOS_PREFERENCE_CLEAR?"detail":i===gr.QOS_PREFERENCE_SMOOTH?"motion":""}var Zh={};li(Zh,{bytes2ms:()=>Xf,convertObjectNumberToInt:()=>
|
|
92
|
-
`));function Yo(i){nt(i)&&i!==Pu&&(Pu=i,V.info(`setIsNeedToSchedule ${i}`))}B.on("28",()=>Yo(!0));B.on("63",()=>Yo(!0));B.on("84",()=>Yo(!0));B.on("201",i=>{i.state==="RECONNECTING"&&Yo(!0)});B.on("202",i=>{i.state==="RECONNECTING"&&Yo(!0)});function By(i,t,e){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let o=performance.getEntriesByType("resource"),s=
|
|
89
|
+
`,G.push(ye);var ke=Ac(Function,G).apply(null,U);return $=Ll(ke),Lc[M]=$,$}var Vl=()=>{Ni("")},Uc;Uc=()=>performance.now();var Bl=(f,_,I)=>Pe.copyWithin(f,_,_+I),Fl=f=>{Ni("OOM")},$l=f=>{var _=Pe.length;f>>>=0,Fl(f)},Hl=[null,[],[]],Wl=(f,_)=>{var I=Hl[f];_===0||_===10?((f===1?Bt:Xe)(ci(I,0)),I.length=0):I.push(_)},Bn={varargs:void 0,get(){Bn.varargs+=4;var f=Zt[Bn.varargs-4>>2];return f},getStr(f){var _=Nc(f);return _}},Gl=(f,_,I,C)=>{for(var M=0,$=0;$<I;$++){var G=P[_>>2],U=P[_+4>>2];_+=8;for(var ee=0;ee<U;ee++)Wl(f,Pe[G+ee]);M+=U}return P[C>>2]=M,0};ll(),At=e.BindingError=class extends Error{constructor(_){super(_),this.name="BindingError"}},oi=e.InternalError=class extends Error{constructor(_){super(_),this.name="InternalError"}},uo(),Dn(),po(),Sc=e.UnboundTypeError=Tl(Error,"UnboundTypeError"),yl(),bl();var jl={o:bn,r:ul,m:pl,q:Il,p:Pn,d:bc,u:vl,k:Cl,b:Dl,a:Nl,j:wc,g:Ol,n:Pl,e:kc,l:Rc,h:Vn,f:Vl,c:Uc,t:Bl,s:$l,i:Gl},Nf=ac(),ql=()=>(ql=Ge.w)(),Ar=f=>(Ar=Ge.x)(f),Fn=f=>(Fn=Ge.y)(f),Vc=f=>(Vc=Ge.A)(f),zl=e.__embind_initialize_bindings=()=>(zl=e.__embind_initialize_bindings=Ge.B)(),Jl=()=>(Jl=Ge.__errno_location)(),Bc=f=>(Bc=Ge.C)(f),$n=e.dynCall_jiji=(f,_,I,C,M)=>($n=e.dynCall_jiji=Ge.D)(f,_,I,C,M),hs;ri=function f(){hs||Fc(),hs||(ri=f)};function Fc(){if(ti>0||(ol(),ti>0))return;function f(){hs||(hs=!0,e.calledRun=!0,!_n&&(sl(),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),z()))}e.setStatus?(e.setStatus("Running..."),setTimeout(function(){setTimeout(function(){e.setStatus("")},1),f()},1)):f()}if(e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();return Fc(),t.ready}})(),$g=Ry;var yu=class extends Qr{constructor(t){super($g,t!=null&&t.wasmPath?fetch(t.wasmPath).then(e=>e.arrayBuffer()):void 0,t==null?void 0:t.workerMode,t==null?void 0:t.canvas,t==null?void 0:t.yuvMode)}};var ah=class{constructor(t){this.core=t;this.contextMap=new Map;this.decodeProcessorMap=new WeakMap;this.createDecoder=this.createDecoder.bind(this)}getAlias(){return"videoDecoder"}getGroup(t){return t!=null&&t.track?`${t.track.userId}${t.track.streamType}`:"*"}getName(){return ah.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return this.core.rtcDectection.isSIMDSupported()?new yu(me(J({},e),{wasmPath:`${this.core.assetsPath}videodec_simd.wasm`})):new Su(me(J({},e),{wasmPath:`${this.core.assetsPath}videodec.wasm`}));case"webCodecs":return new Di;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:a})=>{if(a!==t.track||s.type==="empty")return s;if(this.contextMap.has(a))return this.contextMap.get(a).decode(s);let d=this.core.room.videoManager.createDecodeContext(me(J({},t),{createDecoder:this.createDecoder}));return e(d.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:a})})),this.contextMap.set(a,d),d.decode(s)}}stop(t){if(!(t!=null&&t.track))this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});else{let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.contextMap.delete(t.track))}this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}update(t){let e=this.contextMap.get(t.track);if(!!e){if(t.type==="mock"){e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST);return}e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(me(J({},t),{createDecoder:this.createDecoder})))}}},Ks=ah;Ks.Name="TRTCVideoDecoder";function Oe(...i){}var Cy=i=>i();function dh(){this.dispose()}var Dy=()=>typeof __FASTRX_DEVTOOLS__!="undefined",Ny=1,Yr=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new ch(t,this,this.streamId++);return ut.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},en=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Oe,this.error=Oe,this.next=Oe,this.dispose=Oe,this.subscribe=Oe,this.doDefer()}subscribe(t){return t instanceof Yr?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Cy),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},pe=class extends en{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},Au=class extends en{constructor(t,e=Oe,r=Oe,o=Oe){if(super(),this._next=e,this._error=r,this._complete=o,this.then=Oe,t instanceof Yr){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{ut.defer(s,0)}),ut.create(s),ut.pipe(s),this.sourceId=s.id,this.subscribe(t),ut.subscribe({id:s.id,end:!0}),e==Oe?this._next=a=>ut.next(s,0,a):this.next=a=>{ut.next(s,0,a),e(a)},o==Oe?this._complete=()=>ut.complete(s,0):this.complete=()=>{this.dispose(),ut.complete(s,0),o()},r==Oe?this._error=a=>ut.complete(s,0,a):this.error=a=>{this.dispose(),ut.complete(s,0,a),r()}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function Xt(i,...t){return t.reduce((e,r)=>r(e),i)}function Mr(i,t,e){if(Dy()){let r=Object.defineProperties(Object.setPrototypeOf(i,Yr.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});ut.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof Yr&&ut.addSource(r,s)}return r}return i}function Te(i,t){return function(...e){return r=>{if(r instanceof Yr){let o=Mr(s=>{let a=new i(s,...e);a.sourceId=o.id,a.subscribe(r)},t,arguments);return o.source=r,ut.pipe(o),o}else return o=>r(new i(o,...e))}}}function Zi(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var ch=class extends pe{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{ut.defer(this.source,this.id)})}next(t){ut.next(this.source,this.id,t),this.sink.next(t)}complete(){ut.complete(this.source,this.id),this.sink.complete()}error(t){ut.complete(this.source,this.id,t),this.sink.error(t)}},ut={addSource(i,t){Zi("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){Zi("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){Zi("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){Zi("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){Zi("defer",{id:i.id,streamId:t})},pipe(i){Zi("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){Zi("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=Ny++),Zi("create",{name:i.toString(),id:i.id})}},bu=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var uh=class extends en{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function Hg(){return i=>{let t=new uh(i);if(i instanceof Yr){let e=Mr(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,ut.pipe(e),e}return Mr(t.add.bind(t),"share",arguments)}}function wy(...i){return Mr(t=>{let e=i.length,r=e,o=e,s=new Array(e),a=()=>{--o===0&&t.complete()},d=(h,p)=>{let T=new pe(t);T.next=y=>{--r===0?(T.next=R=>{s[p]=R,t.next(s)},T.next(y)):s[p]=y},T.complete=a,T.subscribe(h)};i.forEach(d)},"combineLatest",arguments)}var lh=class extends pe{constructor(t,...e){super(t);let r=new pe(this.sink);r.next=o=>this.buffer=o,r.complete=Oe,r.subscribe(wy(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},KM=Te(lh,"withLatestFrom"),ph=class extends pe{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(t=>this.sink.next(t)),super.complete()}},eO=Te(ph,"bufferCount"),mh=class extends pe{constructor(t,e){super(t),this.buffer=[];let r=new pe(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=Oe,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},tO=Te(mh,"buffer");function tn(i){let t=arguments,e=Hg()(Mr(r=>{e.next=o=>r.next(o),e.complete=()=>r.complete(),e.error=o=>r.error(o),i&&r.subscribe(i)},"subject",t));return e.next=Oe,e.complete=Oe,e.error=Oe,e}function hh(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function Qt(i,t){if("on"in i)return Mr(hh(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i)return Mr(hh(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return Mr(hh(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}var fh=class extends pe{constructor(t,e,r){super(t),this.f=e;let o=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=s=>{this.acc=s,this.complete=o,this.resetNext()}:(this.acc=r,this.complete=o)}next(t){this.acc=this.f(this.acc,t)}},xy=Te(fh,"reduce");var _h=class extends pe{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},pO=Te(_h,"filter"),gh=class extends pe{next(t){}},mO=Te(gh,"ignoreElements"),Eh=class extends pe{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},Wg=Te(Eh,"take"),Th=class extends pe{constructor(t,e){super(t);let r=new pe(t);r.next=()=>t.complete(),r.complete=dh,r.subscribe(e)}},Ki=Te(Th,"takeUntil"),Ih=class extends pe{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},hO=Te(Ih,"takeWhile");var Sh=class extends pe{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},fO=Te(Sh,"skip"),yh=class extends pe{constructor(t,e){super(t),t.next=Oe;let r=new pe(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=dh,r.subscribe(e)}},_O=Te(yh,"skipUntil"),Ah=class extends pe{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},gO=Te(Ah,"skipWhile"),My={leading:!0,trailing:!1},bh=class extends pe{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},vh=class extends pe{constructor(t,e,r=My){super(t),this.durationSelector=e,this.config=r,this._throttle=new bh(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=Oe,this._throttle.complete(),super.complete()}},EO=Te(vh,"throttle");var Rh=class extends pe{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ch=class extends pe{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Rh(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},TO=Te(Ch,"debounce");var Dh=class extends pe{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},IO=Te(Dh,"elementAt");var Nh=class extends pe{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},SO=Te(Nh,"findIndex"),wh=class extends pe{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},yO=Te(wh,"first"),xh=class extends pe{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},AO=Te(xh,"last"),Mh=class extends pe{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},bO=Te(Mh,"every");var Oh=class extends pe{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=o=>{this.acc=o,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},DO=Te(Oh,"scan"),Ph=class extends pe{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},NO=Te(Ph,"pairwise"),kh=class extends pe{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},Gg=Te(kh,"map");var rn=class extends pe{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},on=class extends pe{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},vu=class extends rn{},Ru=class extends on{next(t){this.subInner(t,vu),this.next=e=>{this.currentSink.dispose(),this.subInner(e,vu)}}},jg=Te(Ru,"switchMap");function wu(i){return(t,e)=>i(()=>t,e)}var qg=wu(Te(Ru,"switchMapTo")),Lh=class extends rn{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Cu=class extends on{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),Lh),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},wO=Te(Cu,"concatMap"),xO=wu(Te(Cu,"concatMapTo")),Uh=class extends rn{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Du=class extends on{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Uh),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},MO=Te(Du,"mergeMap"),OO=wu(Te(Du,"mergeMapTo")),Vh=class extends rn{dispose(){this.context.resetNext(),super.dispose()}},Nu=class extends on{next(t){this.next=Oe,this.subInner(t,Vh)}},PO=Te(Nu,"exhaustMap"),kO=wu(Te(Nu,"exhaustMapTo")),Bh=class extends pe{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=tn(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},LO=Te(Bh,"groupBy"),Fh=class extends pe{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},UO=Te(Fh,"timeInterval"),$h=class extends pe{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},VO=Te($h,"bufferTime"),Hh=class extends pe{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:o}=e;super.next(o),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},BO=Te(Hh,"delay"),Wh=class extends pe{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},FO=Te(Wh,"catchError");var cr=(i=Oe,t=Oe,e=Oe)=>r=>new Au(r,i,t,e),Gh=class extends pe{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},zg=Te(Gh,"tap"),jh=class extends pe{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new bu(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},WO=Te(jh,"timeout");function Xg(i,t=!1){let e=Object.defineProperties(tn(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Oe,i.onmessageerror=Oe,i=o,r()}}});function r(){i.onmessage=o=>{o.data?o.ports.length||t?e.next(o):e.next(o.data):(e.complete(),i.close())},i.onmessageerror=o=>{e.error(o),i.close()}}return r(),e}var qh=class extends pe{constructor(t,e){super(t);let r=new pe(t);r.next=Oe,e(r)}},sP=Te(qh,"takeUntilComplete");var yt={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},Jh="__INLINE__WORKER__",Jg="__INLINE__WASM__",{debug:Qg}=console;yt.debug||(console.debug=()=>{});var zh=!Jh.startsWith("__");function Yg(){return`${yt.assetsPath?`${yt.assetsPath}/`:""}worker.js`}function Zg(){let i=Yg();return zh||i.startsWith("http")?URL.createObjectURL(new Blob([zh?atob(Jh):`importScripts('${i}')`])):i}function Kg(){let i=Yg();return zh?URL.createObjectURL(new Blob([atob(Jh)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}function xu(){return Jg.startsWith("__")?`${yt.assetsPath?`${yt.assetsPath}/`:""}av_processing.wasm`:`data:application/octet-stream;base64,${Jg}`}var Xh=class{constructor(){this.playPortSent=!1;Xt(Qt(document,"mousedown"),Wg(1),cr(()=>this.resume().catch(t=>{console.error("audio worklet init failed:",t)}))),this.workletPromise=this.init()}resume(){return v(this,null,function*(){if(this.audioCtx){this.audioCtx.resume();return}})}init(){return v(this,null,function*(){this.audioCtx=new AudioContext({sampleRate:48e3});let t=Kg();V.info("AudioContext Created:",this.audioCtx,t),yield this.audioCtx.audioWorklet.addModule(typeof t=="string"?t:yield t);let e=yield fetch(xu()).then(r=>r.arrayBuffer());return this.worklet=new AudioWorkletNode(this.audioCtx,"global-audio-player",{processorOptions:{wasm:e,flag:yt},numberOfInputs:2}),V.info("worklet created",this.audioCtx.state),this.worklet.connect(this.audioCtx.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return v(this,null,function*(){this.playPortSent||(this.playPortSent=!0,t(yield this.workletPromise))})}},eo=new Xh;var SE=Pi(Hi());function Qh({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Ce((r,o)=>{let s=new WeakMap;return B.on(O.ROOM_DESTROY,({room:a})=>s.delete(a)),function(...a){let d=s.get(this);if(d||(d={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,d)),d.timestamp===0?d.timestamp=Date.now():Date.now()-d.timestamp>1e3&&(d.timestamp=Date.now(),d.callCountInSecond=0,d.totalSizeInSecond=0),e&&(d.totalSizeInSecond+=e(...a)),d.timestamp!==0&&Date.now()-d.timestamp<1e3&&(d.callCountInSecond>=i||d.totalSizeInSecond>t))throw new de({code:Y.INVALID_OPERATION,message:ot({key:it.CALL_FREQUENCY_LIMIT,data:{isTimes:d.callCountInSecond>=i,isSize:d.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});d.callCountInSecond++,r.call(this,...a)}})}var Oy="2025-02-13 09:02:03",eE=!0,tE=function(){var i;eE&&(eE=!1,V.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Fr}/en/index.html`),console.info(`* Changelog: ${Fr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),V.info("TRTC Web SDK Version:",Ke),wr||V.debug("Build Time:",Oy),V.info("UA:",navigator.userAgent),V.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),Ea().then(t=>{t&&V.info(Rr)}))};var gr={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var ne={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},Or=(w=>(w[w.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",w[w.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",w[w.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",w[w.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",w[w.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",w[w.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",w[w.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",w[w.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",w[w.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",w[w.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",w[w.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",w[w.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",w[w.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",w[w.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",w[w.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",w[w.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",w[w.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",w[w.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",w[w.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",w[w.INVALID_OPERATION=5100]="INVALID_OPERATION",w[w.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",w[w.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",w[w.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",w[w.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",w[w.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",w[w.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",w[w.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",w[w.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",w[w.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",w[w.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",w[w.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",w[w.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",w[w.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",w[w.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",w[w.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",w[w.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",w[w.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",w[w.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",w[w.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",w[w.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",w[w.DEVICE_ERROR=5300]="DEVICE_ERROR",w[w.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",w[w.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",w[w.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",w[w.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",w[w.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",w[w.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",w[w.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",w[w.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",w[w.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",w[w.SERVER_ERROR=5400]="SERVER_ERROR",w[w.NEED_TO_BUY=5401]="NEED_TO_BUY",w[w.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",w[w.OPERATION_FAILED=5500]="OPERATION_FAILED",w[w.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",w[w.REJOIN_FAILED=5502]="REJOIN_FAILED",w[w.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",w[w.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",w[w.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",w[w.OPERATION_ABORT=5998]="OPERATION_ABORT",w[w.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",w))(Or||{});function iE({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=Or[i];try{o=rE[s]}catch(a){o=rE.UNKNOWN_ERROR}return Ve(o)?r=o(t):Ae(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var rE=me(J({},jt),{INVALID_PARAMETER({fnName:i}){return`the parameters of the '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${o}' must be type of ${s} when calling ${e}(), received type: ${mt(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${o}' must be instanceof ${s} when calling ${e}(), received type: ${mt(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:i,rule:t,value:e}){return`the min value of ${i||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:i,rule:t,value:e}){return`the max value of ${i||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:i,fnName:t}){return`'${i}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:i,fnName:t,type:e}){return`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`},INVALID_STREAM_ID({key:i}){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:i}){return`'${i}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:i}){return`'${i}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:i}){return`'${i}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:i})=>`'streamType' is required when 'userId' is not '*', calling ${i}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:i}){return`the API '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:i}){return`cannot ${i} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing ${t.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:i}){return`you are already ${i}(), cannot repeated call '${i}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:i}){return`cannot call '${i}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:i}){return`cannot call '${i}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:i})=>`the buffer size of paramerter '${i}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>`role: '${"audience"}' cannot call this api.`,INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:i})=>`you need to call ${i}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:i}){return`the current browser does not support the capability of the function '${i}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:i}){return`cannot call ${i} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:i,error:t}){return`'${i}' got device exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`NotFoundError, no ${t} detected, please check your device and the configuration on '${i}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`NotAllowedError, you have disabled ${t} access, please allow the current application to use the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`NotReadableError, the ${t} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${t}, and it is recommended to turn on the ${t} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:i,deviceType:t=zo(i),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:i}){return`camera recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},MICROPHONE_RECOVER_FAILED({error:i}){return`microphone recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},OPERATION_FAILED({fnName:i,error:t}){return`'${i}' failed, reason: ${t==null?void 0:t.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:i}){return`an error was caught on trtc.on('${i}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:i,error:t}){return`video context error ${i} ${(t==null?void 0:t.name)||""} ${(t==null?void 0:t.message)||""}`},SERVER_ERROR({fnName:i,error:t}){return`'${i}' got server error: ${t==null?void 0:t.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:i,url:t}){return`You need to buy packages for ${i}. Refer to: ${t}`},ACCOUNT_NO_MONEY:({fnParams:i})=>`your TRTC account run out of credit, please recharge.${i.sdkAppId?` SDKAppId: ${i.sdkAppId}`:""}`,OPERATION_ABORT({fnName:i}){return`'${i}' abort`},UNKNOWN_ERROR({fnName:i,error:t}){return`'${i}' throw unknown exception${t?`, error: ${t.toString()}.`:"."}`}});function zo(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var Jo=class extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:a="",originError:d}){var p;let h;o?h=o:h=iE({code:e===ne.SERVER_ERROR?e:r||e,params:J({fnName:a,error:d},s)});super(h);l(this,"name","RtcError");l(this,"code");l(this,"extraCode");l(this,"functionName");l(this,"message");l(this,"handler");l(this,"originError");this.name=Or[e],this.code=e,this.extraCode=r,this.functionName=a,this.originError=d,this.message=h,this.extraCode===5302&&((p=this.originError)==null?void 0:p.message.includes("system"))&&(this.handler=()=>{let T={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},y={startLocalVideo:"webcam",startLocalAudio:"microphone"},R=document.createElement("a");Ao?R.href=`ms-settings:privacy-${y[this.functionName]}`:Nr&&(R.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${T[this.functionName]}`),R.href.length>0&&R.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof de){let{stack:a}=e,d={code:ne.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case Y.INVALID_PARAMETER:d.code=ne.INVALID_PARAMETER,d.message=e.message;break;case Y.INVALID_OPERATION:d.code=ne.INVALID_OPERATION;break;case Y.NOT_SUPPORTED:case Y.NOT_SUPPORTED_H264:d.code=ne.ENV_NOT_SUPPORTED,e.getCode()===Y.NOT_SUPPORTED_H264&&(d.extraCode=e.message.includes(jt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Y.JOIN_ROOM_FAILED:d.messageParams={fnParams:o};case Y.SERVER_TIMEOUT:case Y.SWITCH_ROLE_FAILED:d.code=ne.SERVER_ERROR,d.extraCode=e.getExtraCode();break;case Y.API_CALL_ABORTED:d.code=ne.OPERATION_ABORT;break;case Y.DEVICE_NOT_FOUND:case Y.DEVICE_AUTO_RECOVER_FAILED:case Y.INITIALIZE_FAILED:d.code=5300,e.name&&(d.extraCode=Py(e.name));break;case Y.UNKNOWN:break;default:d.code=ne.OPERATION_FAILED}s=new Jo(d),a&&(s.stack+=a.substr(a.indexOf(`
|
|
90
|
+
`)))}else{if(e instanceof Jo)return e;s=new Jo({code:ne.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function Py(i){let t;switch(i){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var oe=Jo;var oE={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},sE={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},sn={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(Ae(i)&&!document.getElementById(i))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},nE={name:"userId",required:!0,type:"string"},aE={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[gr.AUDIO_PROFILE_STANDARD,gr.AUDIO_PROFILE_STANDARD_STEREO,gr.AUDIO_PROFILE_HIGH,gr.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Xa(i,t){if(!i)throw new oe({code:ne.INVALID_OPERATION,extraCode:5101,fnName:t})}function cE(i,t,e){if(!i)throw new oe({code:ne.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}var ok={type:"number",notLessThanZero:!0},ky={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(i,t,e){if(this._room.isJoined)throw new oe({code:ne.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(Ae(i.roomId))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(i.roomId))&&i.roomId<4294967295))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:t}})}else if(i.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i.strRoomId))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:t}})}else throw new oe({code:ne.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:sn,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:oE},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&Ai())throw new oe({code:ne.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:me(J({},sn),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:oE}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:aE},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&Ai())throw new oe({code:ne.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:aE}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:sn,publish:{type:"boolean"},option:sE},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)&&Ai())throw new oe({code:ne.ENV_NOT_SUPPORTED,extraCode:5201});if(!Da())throw new oe({code:ne.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:sn,publish:{type:"boolean"},option:sE}},muteRemoteAudio:[nE,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[nE,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:sn,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(i,t,e){Xa(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(cE(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:ne.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:me(J({},sn),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(i,t,e){Xa(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(cE(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:ne.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(i,t,e){if(i.userId!=="*"&&L(i.streamType))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){Xa(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(i,t,e,r){if(!Ma)throw new oe({code:ne.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new oe({code:ne.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});Xa(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(i,t,e){if(!i&&!this._room.isMainStreamPublished||i&&!this._room.isAuxStreamPublished)throw new oe({code:ne.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(i,t,e,r){if(i.byteLength>1e3)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(Xa(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new oe({code:ne.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}}},Tt={TRTC:ky};var Dt=class extends Error{};function Ly(i,t){let e=Io(i);for(let r=0;r<t.length;r++)Wr(e[r],t[r]);return e}function Uy(i){this._resolve=Promise.resolve(i)}function Vy(i){this._reject=Promise.reject(i)}var Xo=class{constructor(t,e){this.instance=t;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=Ly;let r=Xo.instances.get(t);r?r.set(e,this):Xo.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=Xo.instances.get(t);return r&&r.get(e)||new Xo(t,e)}static gets(t,e){let r=Xo.instances.get(t),o=[];return r&&r.forEach((s,a)=>{e.test(a)&&o.push(s)}),o}action(t,e,r){let o=d=>{var h;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(h=this.currentOp)==null||h.action(),d},s=d=>{var h,p;throw this.ops.shift(),t===0&&((h=this.currentOp)==null?void 0:h.type)===2&&this.ops.shift().reject(new Dt("start failed")),(p=this.currentOp)==null||p.action(),d},a={type:t,action:()=>e(...a.args).then(o,s),args:r,resolve:Uy,reject:Vy};try{switch(this.state){case 1:if(t===0)throw new Dt("already started");break;case 4:if(t===2)throw new Dt("not started");break;default:return this.cacheOp(a)}}catch(d){return Promise.reject(d)}return this.ops.push(a),a.promise=e(...a.args).then(o,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Dt("already start");break;case 3:switch(t.type){case 2:throw new Dt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Dt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Dt("keep stop");if(this.ops.slice(1).forEach(o=>o.reject(r)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,t.args),this.lastOp.promise;case 3:throw new Dt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Dt("start not allowed after update");case 0:throw new Dt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Dt("keep start")),new Dt("already start")}}t.promise=new Promise((r,o)=>{t._resolve?t._resolve.then(r):t.resolve=r,t._reject?t._reject.catch(o):t.reject=o});let{action:e}=t;return t.action=()=>e().then(t.resolve,t.reject),this.ops.push(t),t.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},Zr=Xo;Zr.instances=new WeakMap;var Mu=new WeakMap,Ou=(i,t)=>{if(t instanceof Dt){let{stack:e}=t;t=new oe({code:ne.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
91
|
+
`)))}throw t};function to(i,t){return Ce((e,r)=>function(...o){let s=Zr.get(this,typeof i=="string"?i:i.call(this,...o));return s?(t&&(s.startSame=t.bind(this)),s.action(0,e.bind(this),o).catch(Ou.bind(null,r))):e.apply(this,o)})}function Qo(i,t){let{merge:e,debounce:r}=t||{};return Ce((o,s)=>function(...a){let d=Zr.get(this,typeof i=="string"?i:i.call(this,...a));if(!d)return o.apply(this,a);if(e&&(d.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,a)){let{delay:h,getKey:p}=r;return new Promise((T,y)=>{var j,W;let R=(j=Mu.get(this))==null?void 0:j.get(p(...a));if(R){let{timeoutId:F,resolve:Ie}=R;clearTimeout(F),Ie()}let N=setTimeout(()=>{if(d.state===3||d.state===4)return T();d.action(2,o.bind(this),a).catch(Ou.bind(null,s)).then(T,y)},h);Mu.has(this)?(W=Mu.get(this))==null||W.set(p(...a),{timeoutId:N,resolve:T}):Mu.set(this,new Map([[p(...a),{timeoutId:N,resolve:T}]]))})}return d.action(2,o.bind(this),a).catch(Ou.bind(null,s))})}function ro(i){return Ce((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(Zr.gets(this,o).map(a=>a.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=Zr.get(this,o);return s?s.action(3,t.bind(this),r).catch(Ou.bind(null,e)):t.apply(this,r)})}var re={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData"},dE=new Set([re.ERROR,re.AUTOPLAY_FAILED,re.KICKED_OUT,re.REMOTE_USER_ENTER,re.REMOTE_USER_EXIT,re.REMOTE_AUDIO_AVAILABLE,re.REMOTE_AUDIO_UNAVAILABLE,re.REMOTE_VIDEO_AVAILABLE,re.REMOTE_VIDEO_UNAVAILABLE,re.CONNECTION_STATE_CHANGED,re.PUBLISH_STATE_CHANGED,re.SCREEN_SHARE_STOPPED,re.DEVICE_CHANGED]);function Qa(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function Ya(i){return i===gr.QOS_PREFERENCE_CLEAR?"detail":i===gr.QOS_PREFERENCE_SMOOTH?"motion":""}var Zh={};li(Zh,{bytes2ms:()=>Xf,convertObjectNumberToInt:()=>oa,copyProperties:()=>Jf,deepClone:()=>Io,deepMerge:()=>Wr,delay:()=>sa,fibonacci:()=>So,formatedTime:()=>nd,getConstructorName:()=>ra,getContainerFromElement:()=>i_,getEnv:()=>jf,getInternalVersion:()=>t_,getLoggerUrl:()=>fi,getMuteStateFromFlag:()=>ia,getNetworkType:()=>ea,getNumNetworkType:()=>id,getReconnectionTimeout:()=>Yf,getStringByteLength:()=>o_,getTurnServer:()=>r_,getUint32Version:()=>dd,getValueType:()=>mt,getViewListFromView:()=>ys,glog:()=>ta,ipv4ToUint32:()=>Ss,isArray:()=>rt,isAudioWorkletSupported:()=>e_,isBoolean:()=>nt,isConstructor:()=>Is,isEmpty:()=>sd,isFunction:()=>Ve,isLangChinese:()=>vr,isMediaStreamTrack:()=>Zf,isNumber:()=>Fe,isObject:()=>lr,isOverseaSdkAppId:()=>Kn,isPlainObject:()=>$t,isPortrait:()=>cd,isPromise:()=>Li,isRemoteTrack:()=>Kf,isString:()=>Ae,isUndefined:()=>L,loadImage:()=>As,ms2bytes:()=>Qf,ms2samples:()=>pp,performanceNow:()=>ge,promiseAny:()=>od,samples2ms:()=>lp,setNetworkType:()=>zf,stringify:()=>pr,stringifyIncludeValue:()=>ad,throttlePromise:()=>ud});var tf={};li(tf,{getAbilityConfigUrl:()=>Fy,getScheduleDomain:()=>Za,isNeedToSchedule:()=>Pu,scheduleProxy:()=>Pr,sendScheduleRequest:()=>ef,setIsNeedToSchedule:()=>Yo,setScheduleProxy:()=>ku});var Kh=null,Pu=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(hi).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
|
|
92
|
+
`));function Yo(i){nt(i)&&i!==Pu&&(Pu=i,V.info(`setIsNeedToSchedule ${i}`))}B.on("28",()=>Yo(!0));B.on("63",()=>Yo(!0));B.on("84",()=>Yo(!0));B.on("201",i=>{i.state==="RECONNECTING"&&Yo(!0)});B.on("202",i=>{i.state==="RECONNECTING"&&Yo(!0)});function By(i,t,e){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let o=performance.getEntriesByType("resource"),s=nn(i,D.MAIN),a=nn(i,D.BACKUP);for(let d of o)if(d.startTime>=e&&(d.name===s||d.name===a)&&d.transferSize>0){let h=d.name===s?D.MAIN:D.BACKUP,p=Math.round(d.duration),T=Math.round(d.domainLookupStart-d.startTime),y=d.redirectStart>0?Math.round(d.redirectEnd-d.redirectStart):0,R=d.fetchStart>0?Math.round(d.domainLookupStart-d.fetchStart):0,N=Math.round(d.domainLookupEnd-d.domainLookupStart),j=Math.round(d.requestStart-d.secureConnectionStart),W=Math.round(d.secureConnectionStart-d.connectStart),F=Math.round(d.responseStart-d.requestStart),Ie=Math.round(d.responseEnd-d.responseStart),Bt=[N,j,W,F,Ie];Le.uploadEvent({log:`stat-schedule-net:${p}(${T}(${y}->${R})->${Bt.join("->")}) ${h}`,userId:t}),r=me(J({},r),{totalCost:p,local:T,dns:N,tcp:W,tls:j,request:F,response:Ie});break}}catch(o){V.error("getScheduleDetailCost error",o)}return r}function ef(p){return v(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:a,role:d,latencyLevel:h}){if(!Pu&&Kh)return{isCached:!0,result:Kh};let T={delta:0,count:[1,1],msg:[],detail:[]};try{let y=new FormData;y.append("userId",String(i)),y.append("sdkAppId",String(t)),y.append("isStrGroupId",String(e)),y.append("groupId",String(r)),y.append("sdkVersion",s),y.append("userSig",String(o)),d&&y.append("role",String(d)),h&&y.append("latencyLevel",String(h)),a&&y.append("frameWorkType",String(a));let R=ge(),N=yield Hy(y,T,t);N.config&&(N.config.loggerDomain&&_o(N.config.loggerDomain),nt(N.config.scheduleCache)&&Yo(!N.config.scheduleCache)),T.delta=ge()-R;let j=By(Number(t),i,R);return Kh=N,{isCached:!1,result:N,detailCost:j}}catch(y){let R=rt(y)?y[0]:y,N=Fe(R.code)?R.code:0,j=`schedule failed${R.message?`: ${R.message}`:""}`,W=new de({code:Y.SCHEDULE_FAILED,extraCode:N,message:ot({key:it.JOIN_ROOM_FAILED,data:{error:j,code:N}})});throw V.error(j,N),W}})}var Pr={main:"",backup:""};function ku(i){rt(i)?(Pr.main=i[0],Pr.backup=i[1]):Pr.main=i}function nn(i,t=D.MAIN,e=!1){return`https://${Pr[t]||Za(i,t,e)}/api/v1/config`}function Fy(i,t=D.MAIN){return`https://${Pr[t]||Za(i,t)}/api/v1/trtcAutoConf`}function Za(i,t=D.MAIN,e=!1){let r;return Kn(i)?e?r=t===D.MAIN?hi.MAIN_OVERSEA_BACKUP:hi.BACKUP_OVERSEA:r=t===D.MAIN?hi.MAIN_OVERSEA:hi.BACKUP_OVERSEA:r=t===D.MAIN?hi.MAIN:hi.BACKUP,r}function $y(i,t,e){return new Promise((r,o)=>{_i({url:i,body:t,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?r(s.data.data):o({code:s.data.code,message:s.data.msg})}).catch(o)})}var uE=(i,t)=>Vi({retryFunction:$y,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function Hy(i,t,e){return new Promise((r,o)=>{let s=null;od([uE(a=>t.count[0]=a+1,({error:a,retry:d,retriedCount:h,retryFuncArgs:p})=>{t.msg[0]=a.message,s||(h>=1&&(p[0]=nn(e,D.MAIN,!0)),d())})(nn(e,D.MAIN),i,{get timeout(){return So(2+t.count[0])*1e3}}),uE(a=>t.count[1]=a+1,({error:a,retry:d,retriedCount:h,retryFuncArgs:p})=>{t.msg[1]=a.message,s||(h>=2&&(p[0]=nn(e,D.BACKUP,!0)),d())})(nn(e,D.BACKUP),i,{get timeout(){return So(2+t.count[1])*1e3}})]).then(a=>{s=a,r(s)}).catch(o)})}var Wy=i=>i.startsWith("data:application/octet-stream;base64,"),Gy=i=>i.startsWith("file://"),Lu=class{constructor(){l(this,"_log");this._log=V.createLogger({id:"fd"})}download(t,e){return v(this,null,function*(){let{type:r="blob"}=e||{};try{let o=ge(),s;if(Ve(fetch)?s=yield this.downloadWithFetch(t,r):s=yield this.downloadWithXHR(t,r),!s||!s.data)throw new Error("data is empty");let a=ge()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${a}ms`),X.addSuccessEvent({key:522700,cost:ge()-o}),s.data}catch(o){throw this._log.error(`failed to download: ${t}, error: ${o}`),X.addFailedEvent({key:522700,error:o}),o}})}downloadWithFetch(t,e){return v(this,null,function*(){this._log.info(`download with fetch: ${t}, return type: ${e}`);try{let r=yield fetch(t);if(!r.ok)throw new Error("network response was not ok");let o;return e==="arraybuffer"?o=yield r.arrayBuffer():o=yield r.blob(),{data:o}}catch(r){throw r}})}downloadWithXHR(t,e){return this._log.info(`download with xhr: ${t}, return type: ${e}`),new Promise((r,o)=>{let s=new XMLHttpRequest;s.open("GET",t,!0),s.responseType=e,s.onload=()=>{s.status===200||s.status===0&&s.response?r({data:s.response}):o(new Error("XHR failed"))},s.onerror=o,s.send(null)})}loadWasm(t,e){return v(this,null,function*(){this._log.info(`loadWasm ${t}, importObject: ${JSON.stringify(e)}`);let r=ge(),o=null,s=null;if(Ve(WebAssembly.instantiateStreaming)&&!Wy(t)&&!Gy(t)&&Ve(fetch))try{let a=fetch(t);o=(yield WebAssembly.instantiateStreaming(a,e)).instance}catch(a){s=a}if(!o)try{let a=yield this.download(t,{type:"arraybuffer"});o=(yield WebAssembly.instantiate(a,e)).instance}catch(a){s=a}if(o){let a=ge()-r;return this._log.info(`loadedWasm ${t}, cost: ${a}ms`),X.addSuccessEvent({key:522701,cost:a}),o}throw this._log.error(`failed to loadWasm ${t}, error: ${s}`),X.addFailedEvent({key:522701,error:s}),s})}};q([ji({settings:{timeout:0,retries:3},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],Lu.prototype,"download",1);var lE=new Lu;function pE({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,room:t,assetsPath:r,fileDownloader:lE,innerEmitter:B,constants:up,environment:ks,utils:Zh,eventLogger:Le,log:this.room.getLogger(),loggerManager:V,errorModule:e,kvStatManager:X,rtcDectection:Gi,trtc:this,rx:nh,enums:Gp,schedule:tf,clearStarted:(o,s)=>{let a=o.getAlias(),d=Zr.instances.get(this);if(!!d)if(s){let h=d.get(a+s);if(!h)return;h.started=!1}else d.forEach((h,p)=>{p.startsWith(a)&&(h.started=!1)})},startGetPCM:Wa,createAudioNode:mm}}var mE=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=ot({key:it.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return V.warn(`${s}
|
|
93
93
|
|
|
94
|
-
${o.stack}`),!1}},i};var nn=new WeakMap;function hE(i){let t=nn.get(i);t&&(t.forEach(e=>clearTimeout(e)),nn.delete(i))}function fE(i,t){return Ce((e,r)=>function(...o){let s=nn.get(this);s||(s=new Map,nn.set(this,s));let a=t(...o),d=s.get(a);if(!d||d<=0){e.apply(this,o);let h=setTimeout(()=>{var p;(p=nn.get(this))==null||p.delete(a)},i);s.set(a,h)}else{clearTimeout(d);let h=window.setTimeout(()=>{var p;e.apply(this,o),(p=nn.get(this))==null||p.delete(a)},i);s.set(a,h)}})}var _E="5.9.0-wasm.5";function Nt(...i){return Ce((t,e)=>function(...r){try{Vu.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function rf(...i){return Ce((t,e)=>function(...r){try{Vu.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function Vu(i,t,e,r){if(rt(i))for(let o=0;o<i.length;o++)Uu.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else Uu.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function Uu({rule:i,value:t,key:e,fnName:r,className:o}){function s(h){return{code:ne.INVALID_PARAMETER,extraCode:h,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(L(t)){if(i.required)throw new oe(s(5001));if(L(i.defaultValue)){Ve(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let h=!1;for(let p=0;p<i.type.length;p++)i.type[p]===null&&t===null&&(h=!0),Ve(i.type[p])&&t instanceof i.type[p]&&(h=!0),Ae(i.type[p])&&mt(t)===i.type[p].toLowerCase()&&(h=!0);if(!h)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(p=>Is(p)?ta(p):Ae(p)?p:mt(p))},value:t}})}else if(!L(i.type)&&mt(t)!==i.type)throw new oe(s(5002));if(i.allowEmpty===!1){let h=Fe(t)&&(t===0||Number.isNaN(t)),p=Ae(t)&&t.trim()==="";if(h||p)throw new oe(s(5003))}if(i.notLessThanZero&&Fe(t)&&t<0)throw new oe(s(5006));if(!L(i.min)&&Fe(t)&&t<i.min)throw new oe(s(5007));if(!L(i.max)&&Fe(t)&&t>i.max)throw new oe(s(5008));if(Ae(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new oe(s(5004))}else if(Ve(i.instanceOf)&&!(t instanceof i.instanceOf))throw new oe(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new oe(s(5005));let{properties:a}=i;$t(a)&&lr(t)&&Object.keys(a).forEach(h=>{Uu.call(this,{rule:a[h],value:t&&t[h],key:`${h}`,fnName:r,className:o})});let{arrayItem:d}=i;$t(d)&&rt(t)&&t.forEach((h,p)=>{Uu.call(this,{rule:d,value:h,key:`${e}[${p}]`,fnName:r,className:o})}),Ve(i.validate)&&i.validate.call(this,t,e,r,o,this)}function je(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o}=i;return Ce((s,a)=>function(...d){var y;function h(R,N,j){if(j&&j.includes(R))return"hided";if(e){let W=e(...d);if(d[W.argIndex]===N)return W.value}if(N===d||R in d)return N;try{return N instanceof HTMLElement?`id: ${N.id} type:${mt(N)}`:(JSON.stringify(N),N)}catch(W){return`type:${mt(N)}`}}let p=this._log||V;if(o!=null&&o(...d))return s.apply(this,d);d.length>0?p.info(`${a}() ${JSON.stringify(d,(R,N)=>h(R,N,["userSig","privateMapKey"]))}`):p.info(`${a}()`);let T=r?r(...d):Ud[a];try{let R=s.apply(this,d),N=ge();return Li(R)?R.then(j=>(p.info(`${a}() success ${t.call(this,...d)}`),X.addSuccessEvent({key:T,cost:ge()-N}),j)).catch(j=>{var Ie;j=oe.convertFrom.call(this,j,a,d.length===1?d[0]:d);let W=j.extraCode||j.code,F=(Ie=j.message)!=null&&Ie.includes(W)?"":` code:${W}`;throw p.error(`${a}() failed ${t.call(this,...d)} ${j}${F} params: ${JSON.stringify(d,h)}`),X.addFailedEvent({key:T,error:j}),j}):(X.addSuccessEvent({key:T}),R)}catch(R){R=oe.convertFrom.call(this,R,a);let N=R.extraCode||R.code,j=(y=R.message)!=null&&y.includes(N)?"":` code:${N}`;throw p.error(`${a}() failed ${R}${j} params: ${JSON.stringify(d,h)}`),X.addFailedEvent({key:T,error:R}),R}})}var Bu=i=>Ce((t,e)=>function(r,o){return v(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new oe({code:ne.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Ve(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new oe({code:ne.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return Vu.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Fu=0,of=class{constructor(t,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new Gs(e),t.url?(this.player=new Audio(t.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(t.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(t.track),this.mixInput.connect()}updateSettings(t){!this.player||(L(t.volume)||(this.volume=t.volume),L(t.loop)||(this.loop=t.loop),L(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(!!this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(t){!this.player||t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t)}play(){var t,e;return(t=this.publisher)==null||t.play(),(e=this.player)==null?void 0:e.play()}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function an(i,t){if(t&&typeof t!="function")throw new oe({code:ne.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var cn=class{constructor(t){this.core=t;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);Fu=Fu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Fu}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Fu}`),this.core=t}getName(){return cn.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return cn.startValidateRule;case"update":return cn.updateValidateRule;case"stop":return cn.stopValidateRule}}start(t){return v(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new of(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),this.mixedMusicMap.set(r,s),this.log.info(`start mix audio track ${r} success.`),X.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return v(this,null,function*(){let{id:e,operation:r,seekFrom:o,playbackRate:s}=t;this.log.info(`update music source, ${JSON.stringify(t)}`);let a=this.mixedMusicMap.get(e);if(!a){this.log.warn(`update music source failed, music id: ${e} not found.`);return}a.updateSettings(t),a.updateListener(t),L(r)||a.setOperation(r),L(o)||a.seek(o),this.kvUpload(t)})}stop(e){return v(this,arguments,function*({id:t}){var r;this.mixedMusicMap.has(t)&&(this.log.info(`remove music source, music id: ${t}`),(r=this.mixedMusicMap.get(t))==null||r.stop(),this.mixedMusicMap.delete(t)),t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:a,seekFrom:d,onTimeUpdate:h,onDurationChange:p,onEnded:T}=t;e&&X.addCount({key:502711}),r&&X.addCount({key:502703}),o&&X.addCount({key:502704}),s&&X.addCount({key:502705}),a&&X.addCount({key:502706}),d&&X.addCount({key:502707}),typeof h!="function"&&X.addCount({key:502709}),typeof T!="function"&&X.addCount({key:502710}),typeof p!="function"&&X.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},io=cn;l(io,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(t,e,r){if(t.url&&t.url!=="*"){let o=t.url.split("?")[0],s=["mp3","ogg","wav","flac"],a=o.split(".").pop(),d=s.indexOf(a)>=0,h=o.startsWith("blob"),p=o.startsWith("data");if(!(d||h||p))throw new oe({code:ne.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new oe({code:ne.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});an("onTimeUpdate",t.onTimeUpdate),an("onEnded",t.onEnded),an("onDurationChange",t.onDurationChange)}}),l(io,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(t,e,r){an("onTimeUpdate",t.onTimeUpdate),an("onEnded",t.onEnded),an("onDurationChange",t.onDurationChange)}}),l(io,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(io,"Name","AudioMixer");var $u=0,sf,dn=class{constructor(t){this.core=t;l(this,"log");l(this,"audioContext",qt("denoiser"));l(this,"workletNode");$u=$u+1,this.log=t.log.createChild({id:`${this.getAlias()}${$u}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${$u}`),t.assetsPath&&this.preload(`${t.assetsPath}/denoiser-wasm.js`)}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new oe({code:ne.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return sf||(sf=this.doPreload(t)),sf}doPreload(t){return v(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Po(this.audioContext,r)}finally{URL.revokeObjectURL(r)}})}getName(){return dn.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return dn.startValidateRule(this.core);case"update":return dn.updateValidateRule;case"stop":return dn.stopValidateRule}}start(t){return v(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${t.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:s,status:a,message:d}=yield zy(me(J({},t),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${o}. Message: ${d}`),new oe({code:ne.INVALID_PARAMETER,message:d});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:r,sign:s,status:a}}),this.workletNode.port.onmessage=h=>{let{data:p}=h;p.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${p.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return v(this,null,function*(){})}stop(){return v(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}destroy(){!this.workletNode||(this.workletNode.port.onmessage=null)}},Zo=dn;l(Zo,"updateValidateRule",{type:"object"}),l(Zo,"stopValidateRule",{type:"object"}),l(Zo,"Name","AIDenoiser");function qy(i,t=D.MAIN){return`https://${Pr[t]||Za(i,t)}/api/v1/audioAiAuth`}function zy(o){return v(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let a=`${qy(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,d=yield fetch(a),{data:{errCode:h,errMsg:p,sign:T,status:y}}=yield d.json();if(y==="1")return{auth:!0,sign:T,status:y,message:p};let R="Init RTCAIDenoiser failed.",N="";switch(h){case 1:N="Please check your params.";break;case 2:N="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:N="Server is invalid. Please contact our engineer. ";break;case 4:N="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:N="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:N="Your version is not supported.";break}return{auth:!1,status:y,message:p?`${R} Reason: ${p}. ${N}`:`${R}, ${N}`}})}var gE=Pi(Hi(),1);var nf=class extends gE.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return v(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!ft&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Le.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&V.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){Le.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},Jy=new nf,af=Jy;function Xy([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let d=0;d<r;d++)s.push(255);s.push(o);let a=new DataView(t);return s.push(...new Uint8Array(a.buffer)),s.push(128),new Lo(new DataView(new Uint8Array(s).buffer),!0)}function Qy(i){return i.type==="empty"||i.data.byteLength===0}function Yy(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function Zy(i){let t=0,e=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(t===2||t===3)&&e++,t=0;break;default:t=0;break}return e}function cf({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let e=Zy(i.data),r=9-e;if(r<=0)return i;let o=t.splice(0,r).reverse().map(Xy),s=o.reduce((T,y)=>T+y.dataView.byteLength,0),a=new ArrayBuffer(s+i.data.byteLength),d=new DataView(a),h=new DataView(i.data),p=0;for(let T=0;T<o.length;T++)for(let y=0;y<o[T].dataView.byteLength;y++)d.setInt8(p++,o[T].dataView.getInt8(y));for(let T=0;T<i.data.byteLength;T++)d.setInt8(p++,h.getInt8(T));return i.data=a,i}function df({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(Qy(i)||!Yy(e))return i;let r=[],o=0,s=-1,a=-1;for(let d=0;d<i.data.byteLength;d++){let h=e.getUint8(d);if(h===0)o++;else if(h===1){if(o===2||o===3){let p=d-o;if(s===-1?s=p:a===-1&&(a=p,r.push(new Lo(new DataView(e.buffer.slice(s,a)))),s=p,a=-1),!(e.getUint8(d+1)===6)){i.data=e.buffer.slice(p);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var uf=0,lf=class{constructor(t){this.core=t;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);uf++,this.log=t.log.createChild({id:`${this.getAlias()}${uf}`}),this.log.info(`[sei] created id=${this.getAlias()}${uf}`),this.core=t,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:t,mediaType:e}){try{let r=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return cf({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return df({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(re.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:wa?this.encode:cf,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:wa?this.decode:df,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:t,options:e}){var s;let r=[e.seiPayloadType,t],o=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(r):(this._seiMessageList.push(r),o&&this._smallSeiMessageList.push(r)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:r,isMain:!e.toSubStream,small:o})}getName(){return lf.Name}getAlias(){return"sei"}getGroup(){return"sei"}},un=lf;l(un,"autoStart",!0),l(un,"Name","SEI");function pf({frame:i,onDump:t}){return t==null||t(),i}function mf({frame:i,onDump:t}){return t==null||t(),i}var EE={"play() error: NotAllowedError:":{tips:i=>i.includes("main <video>")||i.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
94
|
+
${o.stack}`),!1}},i};var an=new WeakMap;function hE(i){let t=an.get(i);t&&(t.forEach(e=>clearTimeout(e)),an.delete(i))}function fE(i,t){return Ce((e,r)=>function(...o){let s=an.get(this);s||(s=new Map,an.set(this,s));let a=t(...o),d=s.get(a);if(!d||d<=0){e.apply(this,o);let h=setTimeout(()=>{var p;(p=an.get(this))==null||p.delete(a)},i);s.set(a,h)}else{clearTimeout(d);let h=window.setTimeout(()=>{var p;e.apply(this,o),(p=an.get(this))==null||p.delete(a)},i);s.set(a,h)}})}var _E="5.9.0-wasm.6";function Nt(...i){return Ce((t,e)=>function(...r){try{Vu.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function rf(...i){return Ce((t,e)=>function(...r){try{Vu.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function Vu(i,t,e,r){if(rt(i))for(let o=0;o<i.length;o++)Uu.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else Uu.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function Uu({rule:i,value:t,key:e,fnName:r,className:o}){function s(h){return{code:ne.INVALID_PARAMETER,extraCode:h,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(L(t)){if(i.required)throw new oe(s(5001));if(L(i.defaultValue)){Ve(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let h=!1;for(let p=0;p<i.type.length;p++)i.type[p]===null&&t===null&&(h=!0),Ve(i.type[p])&&t instanceof i.type[p]&&(h=!0),Ae(i.type[p])&&mt(t)===i.type[p].toLowerCase()&&(h=!0);if(!h)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(p=>Is(p)?ra(p):Ae(p)?p:mt(p))},value:t}})}else if(!L(i.type)&&mt(t)!==i.type)throw new oe(s(5002));if(i.allowEmpty===!1){let h=Fe(t)&&(t===0||Number.isNaN(t)),p=Ae(t)&&t.trim()==="";if(h||p)throw new oe(s(5003))}if(i.notLessThanZero&&Fe(t)&&t<0)throw new oe(s(5006));if(!L(i.min)&&Fe(t)&&t<i.min)throw new oe(s(5007));if(!L(i.max)&&Fe(t)&&t>i.max)throw new oe(s(5008));if(Ae(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new oe(s(5004))}else if(Ve(i.instanceOf)&&!(t instanceof i.instanceOf))throw new oe(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new oe(s(5005));let{properties:a}=i;$t(a)&&lr(t)&&Object.keys(a).forEach(h=>{Uu.call(this,{rule:a[h],value:t&&t[h],key:`${h}`,fnName:r,className:o})});let{arrayItem:d}=i;$t(d)&&rt(t)&&t.forEach((h,p)=>{Uu.call(this,{rule:d,value:h,key:`${e}[${p}]`,fnName:r,className:o})}),Ve(i.validate)&&i.validate.call(this,t,e,r,o,this)}function je(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o}=i;return Ce((s,a)=>function(...d){var y;function h(R,N,j){if(j&&j.includes(R))return"hided";if(e){let W=e(...d);if(d[W.argIndex]===N)return W.value}if(N===d||R in d)return N;try{return N instanceof HTMLElement?`id: ${N.id} type:${mt(N)}`:(JSON.stringify(N),N)}catch(W){return`type:${mt(N)}`}}let p=this._log||V;if(o!=null&&o(...d))return s.apply(this,d);d.length>0?p.info(`${a}() ${JSON.stringify(d,(R,N)=>h(R,N,["userSig","privateMapKey"]))}`):p.info(`${a}()`);let T=r?r(...d):Ud[a];try{let R=s.apply(this,d),N=ge();return Li(R)?R.then(j=>(p.info(`${a}() success ${t.call(this,...d)}`),X.addSuccessEvent({key:T,cost:ge()-N}),j)).catch(j=>{var Ie;j=oe.convertFrom.call(this,j,a,d.length===1?d[0]:d);let W=j.extraCode||j.code,F=(Ie=j.message)!=null&&Ie.includes(W)?"":` code:${W}`;throw p.error(`${a}() failed ${t.call(this,...d)} ${j}${F} params: ${JSON.stringify(d,h)}`),X.addFailedEvent({key:T,error:j}),j}):(X.addSuccessEvent({key:T}),R)}catch(R){R=oe.convertFrom.call(this,R,a);let N=R.extraCode||R.code,j=(y=R.message)!=null&&y.includes(N)?"":` code:${N}`;throw p.error(`${a}() failed ${R}${j} params: ${JSON.stringify(d,h)}`),X.addFailedEvent({key:T,error:R}),R}})}var Bu=i=>Ce((t,e)=>function(r,o){return v(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new oe({code:ne.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Ve(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new oe({code:ne.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return Vu.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Fu=0,of=class{constructor(t,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new Gs(e),t.url?(this.player=new Audio(t.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(t.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(t.track),this.mixInput.connect()}updateSettings(t){!this.player||(L(t.volume)||(this.volume=t.volume),L(t.loop)||(this.loop=t.loop),L(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(!!this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(t){!this.player||t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t)}play(){var t,e;return(t=this.publisher)==null||t.play(),(e=this.player)==null?void 0:e.play()}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function cn(i,t){if(t&&typeof t!="function")throw new oe({code:ne.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var dn=class{constructor(t){this.core=t;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);Fu=Fu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Fu}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Fu}`),this.core=t}getName(){return dn.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return dn.startValidateRule;case"update":return dn.updateValidateRule;case"stop":return dn.stopValidateRule}}start(t){return v(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new of(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),this.mixedMusicMap.set(r,s),this.log.info(`start mix audio track ${r} success.`),X.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return v(this,null,function*(){let{id:e,operation:r,seekFrom:o,playbackRate:s}=t;this.log.info(`update music source, ${JSON.stringify(t)}`);let a=this.mixedMusicMap.get(e);if(!a){this.log.warn(`update music source failed, music id: ${e} not found.`);return}a.updateSettings(t),a.updateListener(t),L(r)||a.setOperation(r),L(o)||a.seek(o),this.kvUpload(t)})}stop(e){return v(this,arguments,function*({id:t}){var r;this.mixedMusicMap.has(t)&&(this.log.info(`remove music source, music id: ${t}`),(r=this.mixedMusicMap.get(t))==null||r.stop(),this.mixedMusicMap.delete(t)),t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:a,seekFrom:d,onTimeUpdate:h,onDurationChange:p,onEnded:T}=t;e&&X.addCount({key:502711}),r&&X.addCount({key:502703}),o&&X.addCount({key:502704}),s&&X.addCount({key:502705}),a&&X.addCount({key:502706}),d&&X.addCount({key:502707}),typeof h!="function"&&X.addCount({key:502709}),typeof T!="function"&&X.addCount({key:502710}),typeof p!="function"&&X.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},io=dn;l(io,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(t,e,r){if(t.url&&t.url!=="*"){let o=t.url.split("?")[0],s=["mp3","ogg","wav","flac"],a=o.split(".").pop(),d=s.indexOf(a)>=0,h=o.startsWith("blob"),p=o.startsWith("data");if(!(d||h||p))throw new oe({code:ne.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new oe({code:ne.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});cn("onTimeUpdate",t.onTimeUpdate),cn("onEnded",t.onEnded),cn("onDurationChange",t.onDurationChange)}}),l(io,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(t,e,r){cn("onTimeUpdate",t.onTimeUpdate),cn("onEnded",t.onEnded),cn("onDurationChange",t.onDurationChange)}}),l(io,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(io,"Name","AudioMixer");var $u=0,sf,un=class{constructor(t){this.core=t;l(this,"log");l(this,"audioContext",qt("denoiser"));l(this,"workletNode");$u=$u+1,this.log=t.log.createChild({id:`${this.getAlias()}${$u}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${$u}`),t.assetsPath&&this.preload(`${t.assetsPath}/denoiser-wasm.js`)}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new oe({code:ne.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return sf||(sf=this.doPreload(t)),sf}doPreload(t){return v(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Po(this.audioContext,r)}finally{URL.revokeObjectURL(r)}})}getName(){return un.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return un.startValidateRule(this.core);case"update":return un.updateValidateRule;case"stop":return un.stopValidateRule}}start(t){return v(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${t.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:s,status:a,message:d}=yield zy(me(J({},t),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${o}. Message: ${d}`),new oe({code:ne.INVALID_PARAMETER,message:d});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:r,sign:s,status:a}}),this.workletNode.port.onmessage=h=>{let{data:p}=h;p.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${p.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return v(this,null,function*(){})}stop(){return v(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}destroy(){!this.workletNode||(this.workletNode.port.onmessage=null)}},Zo=un;l(Zo,"updateValidateRule",{type:"object"}),l(Zo,"stopValidateRule",{type:"object"}),l(Zo,"Name","AIDenoiser");function qy(i,t=D.MAIN){return`https://${Pr[t]||Za(i,t)}/api/v1/audioAiAuth`}function zy(o){return v(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let a=`${qy(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,d=yield fetch(a),{data:{errCode:h,errMsg:p,sign:T,status:y}}=yield d.json();if(y==="1")return{auth:!0,sign:T,status:y,message:p};let R="Init RTCAIDenoiser failed.",N="";switch(h){case 1:N="Please check your params.";break;case 2:N="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:N="Server is invalid. Please contact our engineer. ";break;case 4:N="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:N="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:N="Your version is not supported.";break}return{auth:!1,status:y,message:p?`${R} Reason: ${p}. ${N}`:`${R}, ${N}`}})}var gE=Pi(Hi(),1);var nf=class extends gE.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return v(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!ft&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Le.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&V.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){Le.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},Jy=new nf,af=Jy;function Xy([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let d=0;d<r;d++)s.push(255);s.push(o);let a=new DataView(t);return s.push(...new Uint8Array(a.buffer)),s.push(128),new Lo(new DataView(new Uint8Array(s).buffer),!0)}function Qy(i){return i.type==="empty"||i.data.byteLength===0}function Yy(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function Zy(i){let t=0,e=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(t===2||t===3)&&e++,t=0;break;default:t=0;break}return e}function cf({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let e=Zy(i.data),r=9-e;if(r<=0)return i;let o=t.splice(0,r).reverse().map(Xy),s=o.reduce((T,y)=>T+y.dataView.byteLength,0),a=new ArrayBuffer(s+i.data.byteLength),d=new DataView(a),h=new DataView(i.data),p=0;for(let T=0;T<o.length;T++)for(let y=0;y<o[T].dataView.byteLength;y++)d.setInt8(p++,o[T].dataView.getInt8(y));for(let T=0;T<i.data.byteLength;T++)d.setInt8(p++,h.getInt8(T));return i.data=a,i}function df({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(Qy(i)||!Yy(e))return i;let r=[],o=0,s=-1,a=-1;for(let d=0;d<i.data.byteLength;d++){let h=e.getUint8(d);if(h===0)o++;else if(h===1){if(o===2||o===3){let p=d-o;if(s===-1?s=p:a===-1&&(a=p,r.push(new Lo(new DataView(e.buffer.slice(s,a)))),s=p,a=-1),!(e.getUint8(d+1)===6)){i.data=e.buffer.slice(p);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var uf=0,lf=class{constructor(t){this.core=t;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);uf++,this.log=t.log.createChild({id:`${this.getAlias()}${uf}`}),this.log.info(`[sei] created id=${this.getAlias()}${uf}`),this.core=t,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:t,mediaType:e}){try{let r=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return cf({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return df({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(re.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:xa?this.encode:cf,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:xa?this.decode:df,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:t,options:e}){var s;let r=[e.seiPayloadType,t],o=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(r):(this._seiMessageList.push(r),o&&this._smallSeiMessageList.push(r)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:r,isMain:!e.toSubStream,small:o})}getName(){return lf.Name}getAlias(){return"sei"}getGroup(){return"sei"}},ln=lf;l(ln,"autoStart",!0),l(ln,"Name","SEI");function pf({frame:i,onDump:t}){return t==null||t(),i}function mf({frame:i,onDump:t}){return t==null||t(),i}var EE={"play() error: NotAllowedError:":{tips:i=>i.includes("main <video>")||i.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
95
95
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
96
96
|
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
|
|
97
97
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
98
|
-
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(i=>{EE[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var dL=Object.keys(EE);var Ky=0,Hu,hf=class{constructor(t){this.core=t;l(this,"_core");l(this,"log");l(this,"dumpLocalVideoMap",{});l(this,"dumpRemoteVideoMap",{});l(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++Ky}`}),this.log.info("created")}getName(){return hf.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(t){switch(t){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return v(this,null,function*(){!new URLSearchParams(location.search).has("trtcDebug")||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return v(this,null,function*(){try{if(Hu)yield Hu;else{let t=Date.now();Hu=this.loadScript(`https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@${Ke}.js`),yield Hu,this.log.info(`download debug dialog script cost: ${Date.now()-t}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(t){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(t))}})}closeDebugDiaLog(){var t;(t=this.dialog)==null||t.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):pf,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):mf,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return pf({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return mf({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}loadScript(t){return new Promise((e,r)=>{this.log.info(`loading debug dialog from ${t}`);let o=document.createElement("script");o.type="text/javascript",o.onload=e,o.onerror=r,o.crossOrigin="anonymous",o.src=t,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}},Ko=hf;l(Ko,"Name","Debug"),l(Ko,"autoStart",!0),q([ji({settings:{timeout:3e3,retries:3},onError(i,t,e){var r;(r=i==null?void 0:i.message)!=null&&r.includes("timeout")?t():e(i)}})],Ko.prototype,"loadScript",1);var TE=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Wu=class{constructor(t,e,r){l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"type","auto");l(this,"config");l(this,"decoder");l(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=Je(e,Z.INIT),this.stopOB=Jt(this.trackDoneOB),this.startOB=Jt(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let a=Jt(),d=h=>{let p=this.pipe(e);return a.next("STARTING"),e.log.info(`decoder type: ${this.type}`),We(p,gt(this.stopOB),dt(()=>{},T=>{e.log.error(T),o.addFailedEvent({key:TE(this.type),error:T}),h>4?this.startOB.error(T):this.startOB.next(h+1)})),We(p,xr(1),ja(Ho))};We(this.startOB,$o(0),Qi(d),gt(this.stopOB),dt(()=>{e.player.setOutput(),a.next("STARTED")},h=>{a.next("FAILED")},()=>{o.addSuccessEvent({key:TE(this.type)}),o.addSuccessEvent({key:504702})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}pipe(t){return Ri()(e=>v(this,null,function*(){this._decodeSink=e,e.defer(()=>{var o;(o=this.decoder)==null||o.close()});let{type:r}=this;try{switch(r){case"webCodecs":this.decoder=new AudioDecoder({error:o=>{t.log.error(o),e.error(4)},output:o=>{this.decodedFrameCount++,e.next(o),t.player.write(o)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(o){t.log.error(o),e.error(r==="webCodecs"?2:6)}}))}decodeFrame(t){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:t.data,timestamp:t.timestamp,type:"key"}))}},eA={type:"object"},Gu=class{constructor(t){this.core=t;l(this,"log");l(this,"contextMap",new Map);l(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Gu.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return Gu.Name}getValidateRule(t){return eA}start(t){let{track:e}=t;this.decodeProcessorMap.set(e,this.decode(t)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:r,track:o})=>this.decodeProcessorMap.has(o)?this.decodeProcessorMap.get(o)({frame:r,track:o}):r,type:3})}decode(t){return({frame:e,track:r})=>{if(r!==t.track)return e;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(e);let o=new Wu(this.core,r,t);return We(o.trackDoneOB,xr(1),dt(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:r})})),this.contextMap.set(r,o),o.decodeFrame(e)}}stop({track:t}){let e=this.contextMap.get(t);!e||(e.close("stop"),this.contextMap.delete(t),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(t){let e=this.contextMap.get(t.track);if(!!e){if(t.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(t.track,new Wu(this.core,t.track,t))}}},ln=Gu;l(ln,"Name","AudioDecoder");var IE=0,Ka=new Set,It=null;ep(_E);Ls.checkStorage();im();var tA={RtcError:oe,ErrorCode:ne,ErrorCodeDictionary:Or},dr=class extends SE.EventEmitter{constructor(e,r){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioVolumeMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",V.createLogger({id:`t${++IE}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");l(this,"_getPCMAbortCtrl");this._room=new e(J({logger:this._log,frameWorkType:dr.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,this._log.debug(`TRTC.create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(a=>a.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(io,r.assetsPath),this._use(Zo,r.assetsPath),this._use(ln,r.assetsPath||Jc),this._use(Ko),r.enableSEI&&xa&&this._use(un),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(re.AUDIO_VOLUME,{result:o.sort((s,a)=>a.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new oe({code:ne.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),mE(this,"trtc")}static create(e){}static _create(e,r){tE();let o=new dr(e,r||{});return Ka.add(o),o}get room(){return this._room}_listenEvents(){Rt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(re.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(re.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(re.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(re.ERROR,oe.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(re.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=me(J({},e),{uplinkRTT:Math.min(e.uplinkRTT,Qn),downlinkRTT:Math.min(e.downlinkRTT,Qn)});this.emit(re.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{Rt(o,o).add("player-state-changed",s=>{let a=me(J({},s),{userId:e.userId});o.kind===D.VIDEO&&(a.streamType=Qa(o.streamType)),this.emit(o.kind===D.AUDIO?re.AUDIO_PLAY_STATE_CHANGED:re.VIDEO_PLAY_STATE_CHANGED,a)}).add("error",s=>{s.getCode()===Y.PLAY_NOT_ALLOWED&&this.emit(re.AUTOPLAY_FAILED,{userId:o.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{ct(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,a=e.videoAvailable,{audioAvailable:d,videoAvailable:h}=r;d||this._remoteAudioConfigMap.delete(o),h||this._remoteVideoConfigMap.delete(`${o}_${"main"}`),r.hasAuxiliary||this._remoteVideoConfigMap.delete(`${o}_${"sub"}`),a!==h&&(h?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(h?re.REMOTE_VIDEO_AVAILABLE:re.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==d&&(d?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(d?re.REMOTE_AUDIO_AVAILABLE:re.REMOTE_AUDIO_UNAVAILABLE,{userId:o})),e.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:o,streamType:"sub"}):this._onVideoUnavailable({userId:o,streamType:"sub"}),this.emit(r.hasAuxiliary?re.REMOTE_VIDEO_AVAILABLE:re.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(re.SEI_MESSAGE,me(J({},e),{streamType:Qa(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(re.ERROR,new oe({code:ne.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,a,d,h,p,T,y;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((a=this._networkQuality)==null?void 0:a.uplinkRTT)||((d=this._networkQuality)==null?void 0:d.downlinkRTT)||0,Qn),upLoss:((h=this._networkQuality)==null?void 0:h.uplinkLoss)||0,downLoss:((p=this._networkQuality)==null?void 0:p.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((T=e.msg_up_stream_info.msg_audio_status)==null?void 0:T.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((y=e.msg_up_stream_info.msg_audio_status)==null?void 0:y.uint32_audio_level)||0)/Ii},video:e.msg_up_stream_info.msg_video_status.filter(R=>r[R.uint32_video_stream_type]).map(R=>({bitrate:(R.uint32_video_codec_bitrate||0)/1e3,width:R.uint32_video_width,height:R.uint32_video_height,frameRate:R.uint32_video_enc_fps,videoType:r[R.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(R=>({userId:R.msg_user_info.str_identifier,audio:{bitrate:(R.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(R.msg_audio_status.uint32_audio_level||0)/Ii},video:R.msg_video_status.map(N=>({bitrate:(N.uint32_video_codec_bitrate||0)/1e3,width:N.uint32_video_width,height:N.uint32_video_height,frameRate:N.uint32_video_dec_fps,videoType:r[N.uint32_video_stream_type]}))}))};this.emit(re.STATISTICS,o)}).add("custom-message",e=>{this.emit(re.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(re.LAYER_DATA,e)),Rt(this,_t).add("audioInputAdded",e=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>v(this,null,function*(){if(this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),It&&It.deviceId===Xn){let r=(yield qi()).find(o=>o.deviceId===Xn);r&&It.groupId!==r.groupId&&(It=r,this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>v(this,null,function*(){this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield qi())[0];if(!r||!It||It.groupId===r.groupId)return;let o=It.deviceId===e.deviceId,s=It.deviceId===Xn&&It.deviceId===r.deviceId;(o||s)&&(It=r,this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}))}use(e){let r,o;"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,this._use(r,o||Jc)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(pE.call(this,{TRTC:dr,room:this._room,errorModule:tA,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return v(this,null,function*(){var h,p;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:a=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Ae(e.proxy)&&e.proxy.turnServer&&((p=(h=this._room).setTurnServer)==null||p.call(h,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=a,nt(e.preferHW)&&(this._room.preferHW=e.preferHW);let d={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(d,r,dr.frameWorkType),this._checkTrackToPublish(),af.start()})}exitRoom(){return v(this,null,function*(){return yield this._exitRoom()})}switchRole(e,r){return v(this,null,function*(){r!=null&&r.privateMapKey&&(this._room.privateMapKey=r.privateMapKey),r!=null&&r.latencyLevel&&(this._room.latencyLevel=r.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){ct(this),this.removeAllListeners(),this._room.destroy(),Ka.delete(this),Ka.size===0&&af.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)})}startLocalAudio(){return v(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,option:s}=e,a=new ar(this._room.audioManager),d={},h={muted:!0};s&&(L(s.microphoneId)?L(s.audioTrack)||(d.customSource=s.audioTrack):d.deviceId=s.microphoneId,s&&Fe(s.captureVolume)&&a.setCaptureVolume(s.captureVolume),L(s.profile)||(Ae(s.profile)?Qc[s.profile]&&a.setProfile(Qc[s.profile]):a.setProfile(s.profile)),Fe(s.earMonitorVolume)&&(h.muted=!(s.earMonitorVolume>0),h.volume=s.earMonitorVolume),L(s.echoCancellation)||(a.profile.echoCancellation=s.echoCancellation),L(s.noiseSuppression)||(a.profile.noiseSuppression=s.noiseSuppression),L(s.autoGainControl)||(a.profile.autoGainControl=s.autoGainControl)),a.on("5",p=>{this.emit(re.ERROR,new oe({code:ne.DEVICE_ERROR,extraCode:5309,messageParams:{error:p}}))}),a.on("2",p=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"active",device:p})}),a.on("4",p=>{let T;p.error&&(T=oe.convertFrom(p.error)),this.emit(re.PUBLISH_STATE_CHANGED,me(J({},p),{error:T}))}),this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId),yield a.capture(d),L(o)||a.setMute(o),Rt(a,a).add("player-state-changed",p=>{this.emit(re.AUDIO_PLAY_STATE_CHANGED,me(J({},p),{userId:""}))}),this.listeners(re.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(p=>{this.emit(dr.EVENT.AUDIO_FRAME,{data:p})})),this._getPCMAbortCtrl&&a.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(p=>{this.emit(dr.EVENT.AUDIO_FRAME,{data:p})}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localAudioTrack=a,this._localAudioConfig=me(J({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:h,track:a})})}updateLocalAudio(e){return v(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,option:s}=e,a={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):L(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),L(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),L(s.earMonitorVolume)||(a.muted=!(s.earMonitorVolume>0),a.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!L(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),L(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:a,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Wr(this._localAudioConfig,e)})}stopLocalAudio(){return v(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ct(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return v(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,mute:s,option:a}=e,d=new hr(this._room.videoManager),h={},p={};a&&(a.cameraId?h.deviceId=a.cameraId:L(a.useFrontCamera)?L(a.videoTrack)||(h.customSource=a.videoTrack):h.facingMode=a.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,a.qosPreference&&(h.contentHint=Ya(a.qosPreference)),L(a.profile)||(Ae(a.profile)?$r[a.profile]&&d.setProfile($r[a.profile]):d.setProfile(a.profile)),L(a.fillMode)||(p.objectFit=a.fillMode),L(a.mirror)||(p.mirror=a.mirror),L(a.small)||(Da()?Ae(a.small)?d.small=$r[a.small]:a.small===!0?d.small=$r["120p"]:d.small=a.small:this._log.warn("small stream is not supported"))),d.on("5",T=>{this.emit(re.ERROR,new oe({code:ne.DEVICE_ERROR,extraCode:5308,messageParams:{error:T}}))}),d.on("2",T=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"active",device:T})}),d.on("4",T=>{let y;T.error&&(y=oe.convertFrom(T.error)),this.emit(re.PUBLISH_STATE_CHANGED,me(J({},T),{error:y}))}),this._listenOutputTrackChanged(d),yield d.capture(h),L(s)||(yield d.setMute(s)),Rt(d,d).add("player-state-changed",T=>{this.emit(re.VIDEO_PLAY_STATE_CHANGED,me(J({},T),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=me(J({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:p,track:d})})}updateLocalVideo(e){return v(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,option:a}=e,d={};if(a)if(L(a.profile)||(Ae(a.profile)?$r[a.profile]&&this._localVideoTrack.setProfile($r[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&L(a.useFrontCamera)&&this._localVideoTrack.applyProfile()),a.cameraId?yield this._localVideoTrack.switchDevice(a.cameraId):L(a.useFrontCamera)?L(a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a.videoTrack)):yield this._localVideoTrack.switchDevice(a.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT),L(a.fillMode)||(d.objectFit=a.fillMode),L(a.mirror)||(d.mirror=a.mirror),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Ya(a.qosPreference)),a.small){let h=!this._localVideoTrack.small;Da()?(a.small===!0?this._localVideoTrack.small=$r["120p"]:Ae(a.small)?this._localVideoTrack.small=$r[a.small]:this._localVideoTrack.small=a.small,this._room.videoManager.update(),h&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else a.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!L(o)&&(o&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!o&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),L(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Wr(this._localVideoConfig,e)})}stopLocalVideo(){return v(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),ct(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return v(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,option:s}=e,a=new Ji(this._room.videoManager);a.on("4",y=>{let R;y.error&&(R=oe.convertFrom(y.error)),this.emit(re.PUBLISH_STATE_CHANGED,me(J({},y),{error:R}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let d=null,h={},p={};s&&(L(s.profile)||(Ae(s.profile)?Yc[s.profile]&&a.setProfile(Yc[s.profile]):a.setProfile(s.profile)),s.systemAudio&&(h.systemAudio=!0,h.echoCancellation=s.echoCancellation,h.noiseSuppression=s.noiseSuppression,h.autoGainControl=s.autoGainControl),L(s.fillMode)||(p.objectFit=s.fillMode),s.videoTrack&&(h.videoTrack=s.videoTrack),s.audioTrack&&(h.audioTrack=s.audioTrack),s.captureElement&&(h.captureElement=s.captureElement),s.preferDisplaySurface&&(h.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(h.contentHint=Ya(s.qosPreference)));let T=yield a.capture(h);if(a.mediaTrack.addEventListener(D.ENDED,()=>{this._stopScreenShare(),this.emit(re.SCREEN_SHARE_STOPPED)}),T.getAudioTracks()[0]&&(d=new Uo(this._room.audioManager),yield d.setInputMediaStreamTrack(T.getAudioTracks()[0]),this._speakerId&&d.setAudioOutput(this._speakerId)),Rt(a,a).add("player-state-changed",y=>{this.emit(re.VIDEO_PLAY_STATE_CHANGED,me(J({},y),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let y=[a];d&&y.push(d),this._room.publish(...y).catch(()=>{})}this._localScreenTrack=a,this._localScreenAudioTrack=d,this._localScreenConfig=me(J({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:p,track:a})})}updateScreenShare(e){return v(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,a={};if(s&&(L(s.fillMode)||(a.objectFit=s.fillMode),s.qosPreference)){let d=Ya(s.qosPreference);this._localScreenTrack.setContentHint(d)}this._room.isJoined&&!L(o)&&(o&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!o&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Wr(this._localScreenConfig,e)})}stopScreenShare(){return v(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return v(this,null,function*(){let{view:r,userId:o,streamType:s,option:a}=e,d=`${o}_${s}`;if(this._remoteVideoConfigMap.has(d)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let h=this._room.remotePublishedUserMap.get(o);if(!h)return;let p={},T=s==="main"?h.remoteVideoTrack:h.remoteAuxiliaryTrack;this._listenOutputTrackChanged(T),a&&(L(a.fillMode)||(p.objectFit=a.fillMode),L(a.mirror)||(p.mirror=a.mirror),p.canvasRender=a.canvasRender,s==="main"&&!L(a.small)&&(h.remoteVideoTrack.setMediaType(a.small?8:4),this._room.changeType(a.small,T.user))),yield this._room.subscribe(T),yield this._enableVideoDecodeFallback(T,s),yield this._updateVideoPlayOption({view:r,playOption:p,track:T}),this._emitTrackEvent(T),this._remoteVideoConfigMap.set(d,{config:e}),a&&!L(a.receiveWhenViewVisible)&&this._observeView({remoteTrack:T,view:r,receiveWhenViewVisible:a.receiveWhenViewVisible,viewRoot:a==null?void 0:a.viewRoot})})}updateRemoteVideo(e){return v(this,null,function*(){var F,Ie;let{view:r,userId:o,streamType:s,option:a}=e,d=`${o}_${s}`,h=this._remoteVideoConfigMap.get(d);if(!h||!this._room.remotePublishedUserMap.has(o))return;let p={};a&&(L(a.fillMode)||(p.objectFit=a.fillMode),L(a.mirror)||(p.mirror=a.mirror));let T=null,y=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(y==null?void 0:y.muteState.hasVideo)&&(T=y.remoteVideoTrack),s==="sub"&&(y==null?void 0:y.muteState.hasAuxiliary)&&(T=y.remoteAuxiliaryTrack),!T)return;let{config:R}=h;s==="main"&&a&&!L(a.small)&&this._room.changeType(a.small,T.user),yield this._updateVideoPlayOption({view:r,playOption:p,track:T,prevConfig:R}),Wr(R,e);let N=L(a==null?void 0:a.receiveWhenViewVisible)?(F=R.option)==null?void 0:F.receiveWhenViewVisible:a.receiveWhenViewVisible,j=L(r)?R.view:r,W=L(a==null?void 0:a.viewRoot)?(Ie=R.option)==null?void 0:Ie.viewRoot:a.viewRoot;this._observeView({remoteTrack:T,view:j,receiveWhenViewVisible:N,viewRoot:W})})}stopRemoteVideo(e){return v(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return v(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:d,remoteVideoTrack:h,remoteAuxiliaryTrack:p}=s;e.streamType==="main"&&(h.stop(),d.hasVideo&&o.push(h)),e.streamType==="sub"&&(p.stop(),d.hasAuxiliary&&o.push(p))}for(let d of o)r&&(yield this._room.unsubscribe(d),this._mediaTrackMap.get(d.outMediaTrack)===d.userId&&this._mediaTrackMap.delete(d.outMediaTrack));let a=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);a&&a.observer&&a.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,r){return v(this,null,function*(){this._remoteAudioMuteMap.set(e,r);try{if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(o){throw this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return v(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return v(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return v(this,null,function*(){return e.stop(r)})}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}on(e,r,o){return this.listeners(e).includes(r)?this:(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),e===dr.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(dr.EVENT.AUDIO_FRAME,{data:s})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(dr.EVENT.AUDIO_FRAME,{data:s})}))})),this)}emit(e,...r){try{dE.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){var s,a;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(s=this._getPCMAbortCtrl)==null||s.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,r,o),e===dr.EVENT.AUDIO_FRAME&&((a=this._getPCMAbortCtrl)==null||a.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",a=!1;if(Ae(e)?r=e:(r=e.userId,a=e.processed===!0,e.streamType&&(s=e.streamType)),r){let d=this._room.remotePublishedUserMap.get(r);d&&(o=d.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?a&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,a=null;if(r==="")o==="main"&&this._localVideoTrack&&(a=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(a=this._localScreenTrack);else{let d=this._room.remotePublishedUserMap.get(r);d&&(a=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack)}return a?s&&a.outMediaTrack&&a.outMediaTrack!==a.mediaTrack?a.outMediaTrack.clone():a.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s==null?void 0:s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s==null?void 0:s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return v(this,null,function*(){(yield qi()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),It=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return v(this,null,function*(){let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},a=o.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{let d=this._remoteAudioVolumeMap.get(r),h=Fe(d)?d:100;s.volume=h,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(a),We(Je(a,"decode-failed"),gt(Je(a,Z.INIT)),dt(()=>{this.startPlugin(ln.Name,{track:a,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:a})}catch(d){throw this._remoteAudioConfigMap.delete(r),d}this._emitTrackEvent(a)})}_stopRemoteAudio(e,r=!0){return v(this,null,function*(){let o=this._room.remotePublishedUserMap.get(e.userId);o&&(o.remoteAudioTrack.stop(),o.muteState.hasAudio&&r&&(yield this._room.unsubscribe(o.remoteAudioTrack)),this._mediaTrackMap.get(o.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(o.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_enableVideoDecodeFallback(e,r){let o=this._room.videoDecodeFallbackType;!o||!this._plugins.has("TRTCVideoDecoder")||(this._log.info("remote video will fall back when decode failed"),We(Je(e,"decode-failed"),gt(Je(e,Z.INIT)),oh(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),Ga(Je(e,"decode-downgrade-state-changed")),dt(s=>{this.emit(re.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,me(J({},s),{streamType:r,userId:e.userId}))},s=>{this._log.error("fallback",s)},()=>this._log.info("fallback complete"))))}_updateVideoPlayOption(a){return v(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),L(e)&&s&&s.view&&!sd(r)){let d=ys(s.view);d.length>0&&(yield o.play(d,r))}if(!L(e)){let d=ys(e);d.length>0?yield o.play(d,r):o.stop()}})}_updateAudioPlayOption(s){return v(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(a){}L(e.muted)||r.setPlayerMute(e.muted),L(e.volume)||r.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,r=!0){let o=e.isRemote?e.userId:"";!e.outMediaTrack||r&&this._mediaTrackMap.get(e.outMediaTrack)===o||(this._mediaTrackMap.set(e.outMediaTrack,o),this.emit(re.TRACK,{userId:o,streamType:Qa(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var r,o,s;let e=[];if(((r=this._localAudioConfig)==null?void 0:r.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((o=this._localVideoConfig)==null?void 0:o.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(L(r))return;let a=this._remoteVideoConfigMap.get(`${e.userId}_${Qa(e.streamType)}`);if(!a)return;let d=a.observer||void 0;if(r===null||rt(r)&&r.length===0||!o){d==null||d.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let p=a.visibleViewMap||new Map,T=-1;(!d||d.root!==s)&&(d==null||d.disconnect(),p.clear(),d=new IntersectionObserver(R=>{R.forEach(N=>{p.set(N.target,N.isIntersecting)}),clearTimeout(T),T=window.setTimeout(()=>{[...p.values()].find(j=>j)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let y=new Set(ys(r));p.forEach((R,N)=>{y.has(N)||(d.unobserve(N),p.delete(N))}),y.forEach(R=>{p.set(R,!0),d.observe(R)}),d.takeRecords().forEach(R=>{p.set(R.target,R.isIntersecting)}),a.visibleViewMap=p,a.observer=d}_exitRoom(){return v(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),hE(this),this._room.remotePublishedUserMap.forEach(e=>{ct(e.remoteAudioTrack),ct(e.remoteVideoTrack),ct(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return v(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let r=[this._localScreenTrack];this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...r).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),ct(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return v(this,null,function*(){if(It&&!qs(It))this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:It});else{let e=yield qi();if(e[0]&&!qs(e[0]))It=e[0],this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let r=({track:o})=>{o.kind==="audio"&&(!It||qs(It))&&(this._initActiveSpeaker(),B.off("102",this._initActiveSpeaker))};B.on("102",r)}}})}_onAudioAvailable({userId:e}){let r=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(r===!1||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:r}){if(!this._room.autoReceiveVideo)return;let o=this._room.remotePublishedUserMap.get(e);if(o){let s=r==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack,a=[s];this._room.autoReceiveAudio&&a.push(o.remoteAudioTrack),this._room.subscribe(...a).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:r}){r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:r}){this._stopRemoteVideo({userId:e,streamType:r},!1).catch(()=>{})}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:me(J({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),X.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),X.addCount({key:500001,useUV:!0})}static setLogLevel(e,r){V.setLogLevel(e),L(r)||(r?V.enableUploadLog():V.disableUploadLog())}static isSupported(){return $d()}static getCameraList(e=!0){return sr(e)}static getMicrophoneList(e=!0){return zt(e)}static getSpeakerList(e=!0){return qi(e)}static setCurrentSpeaker(e){return v(this,null,function*(){if(ft&&(e===gr.SPEAKER||e===gr.HEADSET)){let o=yield dr.getMicrophoneList(),s="";if(o.forEach(a=>{a.label===e&&(s=a.deviceId)}),!s)return;Ka.forEach(a=>v(this,null,function*(){a._localAudioTrack&&(yield a.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield qi()).forEach(o=>{o.deviceId===e&&(Ka.forEach(s=>{s._setCurrentSpeaker(e),s.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),It=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:a,version:d}){switch(d&&(xo.version=d),e){case"count":xo.addCount({key:r,useUV:a});break;case"enum":xo.addEnum({key:r,value:o,useUV:a});break;case"number":xo.addNumber({key:r,value:o,split:s});break}}},Se=dr;l(Se,"_loggerManager",V),l(Se,"EVENT",re),l(Se,"ERROR_CODE",ne),l(Se,"TYPE",gr),l(Se,"frameWorkType",30),q([je({replaceArg:i=>({argIndex:0,value:{name:"plugin"in i?i.plugin.Name:i.Name,assetsPath:"assetsPath"in i?i==null?void 0:i.assetsPath:"default"}})})],Se.prototype,"use",1),q([Nt(Tt.TRTC.enterRoom),to("room",([i],[t])=>(i.roomId||i.strRoomId)===(t.roomId||t.strRoomId)&&i.userId===t.userId&&i.sdkAppId===t.sdkAppId),Ce(i=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),i.call(this,t)}),je()],Se.prototype,"enterRoom",1),q([je()],Se.prototype,"exitRoom",1),q([Nt(Tt.TRTC.switchRole),Qo("room",{merge:(i,t)=>t}),je()],Se.prototype,"switchRole",1),q([je()],Se.prototype,"destroy",1),q([Nt(Tt.TRTC.startLocalAudio),to("audio",([i],[t])=>{var e,r;return((e=i==null?void 0:i.option)==null?void 0:e.microphoneId)===((r=t==null?void 0:t.option)==null?void 0:r.microphoneId)}),je()],Se.prototype,"startLocalAudio",1),q([Nt(Tt.TRTC.updateLocalAudio),Qo("audio",{debounce:{delay:200,getKey:()=>`${IE}-localAudio`,isNeedToDebounce:i=>{var t;return!L((t=i.option)==null?void 0:t.captureVolume)}}}),je()],Se.prototype,"updateLocalAudio",1),q([ro("audio"),je()],Se.prototype,"stopLocalAudio",1),q([Nt(Tt.TRTC.startLocalVideo),to("video",([i],[t])=>{var e,r;return((e=i==null?void 0:i.option)==null?void 0:e.cameraId)===((r=t==null?void 0:t.option)==null?void 0:r.cameraId)}),je()],Se.prototype,"startLocalVideo",1),q([Nt(Tt.TRTC.updateLocalVideo),Qo("video"),je()],Se.prototype,"updateLocalVideo",1),q([ro("video"),je()],Se.prototype,"stopLocalVideo",1),q([Nt(Tt.TRTC.startScreenShare),to("screen",()=>!0),je()],Se.prototype,"startScreenShare",1),q([Nt(Tt.TRTC.updateScreenShare),Qo("screen"),je()],Se.prototype,"updateScreenShare",1),q([je()],Se.prototype,"stopScreenShare",1),q([Nt(Tt.TRTC.startRemoteVideo),to(i=>`v${i.userId}${i.streamType}`,()=>!0),je({getRemoteId:i=>`${i.userId}_${i.streamType}`})],Se.prototype,"startRemoteVideo",1),q([Nt(Tt.TRTC.updateRemoteVideo),Qo(i=>`v${i.userId}${i.streamType}`),je({getRemoteId:i=>`${i.userId}_${i.streamType}`})],Se.prototype,"updateRemoteVideo",1),q([Nt(Tt.TRTC.stopRemoteVideo),Ce(i=>function(t){return v(this,null,function*(){if(t.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(r=>{this._remoteVideoConfigMap.has(`${r.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:r.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${r.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:r.userId}).catch(()=>{}))}),Promise.all(e)}return i.call(this,t)})}),je({getRemoteId:i=>`${i.userId}_${i.streamType}`})],Se.prototype,"stopRemoteVideo",1),q([ro(i=>`v${i.userId}${i.streamType}`)],Se.prototype,"_stopRemoteVideo",1),q([Nt(...Tt.TRTC.muteRemoteAudio),je({getRemoteId:i=>i})],Se.prototype,"muteRemoteAudio",1),q([rf(...Tt.TRTC.setRemoteAudioVolume),fE(200,i=>i),je({getRemoteId:i=>i})],Se.prototype,"setRemoteAudioVolume",1),q([Bu("start"),zi(i=>{var t;return(t=i.afterStart)==null?void 0:t.call(i)}),to((i,t)=>i.disableRandomCall?null:i.getAlias()+i.getGroup(t)),je({replaceArg:i=>({argIndex:0,value:i.getName()}),getKVReportKey:i=>Jp[i.getName()],ignoreLog:i=>i.getName()==="Debug"})],Se.prototype,"startPlugin",1),q([Bu("update"),Qo((i,t)=>i.disableRandomCall?null:i.getAlias()+i.getGroup(t)),je({replaceArg:i=>({argIndex:0,value:i.getName()}),getKVReportKey:i=>Xp[i.getName()]})],Se.prototype,"updatePlugin",1),q([Bu("stop"),ro((i,t)=>{if(i.disableRandomCall)return null;let e=i.getGroup(t),r=i.getAlias();return e==="*"?new RegExp(`${r}.*`):r+e}),je({replaceArg:i=>({argIndex:0,value:i.getName()}),getKVReportKey:i=>Qp[i.getName()]})],Se.prototype,"stopPlugin",1),q([rf(...Tt.TRTC.enableAudioVolumeEvaluation)],Se.prototype,"enableAudioVolumeEvaluation",1),q([je()],Se.prototype,"getVideoSnapshot",1),q([je()],Se.prototype,"_setCurrentSpeaker",1),q([to(i=>`a${i.userId}`,()=>!0)],Se.prototype,"_startRemoteAudio",1),q([Ce(i=>function(t){return v(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(me(J({},t),{userId:e.userId})).catch(()=>{}))):i.call(this,t)})}),ro(i=>`a${i.userId}`)],Se.prototype,"_stopRemoteAudio",1),q([ro("room")],Se.prototype,"_exitRoom",1),q([ro("screen")],Se.prototype,"_stopScreenShare",1),q([Nt(...Tt.TRTC.sendSEIMessage),Qh({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...i)=>i[0].byteLength})],Se.prototype,"sendSEIMessage",1),q([Nt(Tt.TRTC.sendCustomMessage),Qh({timesInSecond:30,maxSizeInSecond:8e3,getSize:i=>i.data.byteLength})],Se.prototype,"sendCustomMessage",1),q([Nt(Tt.TRTC.create)],Se,"_create",1);var pn=Se;var ju=class{constructor(t,e){this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new Vo(t,this),this.remoteVideoTrack=new Yi(t,this),this.remoteAuxiliaryTrack=new Iu(t,this),this.flag=e.flag||0}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return ra(this.flag,this.userId)}get flag(){return this._flag}set flag(t){if(t===this._flag)return;let e,r=this.muteState;this._flag=t;let o=this.muteState;for(e in o)r[e]!=o[e]&&console.log(this.userId,e,r[e],"->",o[e]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}};var ff=class{constructor(){this._set=new Set;B.on(O.LEAVE_SUCCESS,this.delete,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,o){return`${r}_${e}_${t}_${o}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:o}){return o.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,o.useStringRoomId))}};function rA(){return v(this,null,function*(){let i,t;try{let y=yield zt();i=y&&y.length}catch(y){}try{let y=yield sr();t=y&&y.length}catch(y){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:a}=this.checkSystemResult.detail,d=Gi.basis(),h={webRTC:d.isWebRTCSupported,getUserMedia:d.isGetUserMediaSupported,webSocket:d.isWebSocketsSupported,screenShare:d.isScreenShareSupported,webAudio:d.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:a},p={browser:d.browser,os:d.os,trtc:h,devices:e},T={isWebCodecSupported:d.isWebCodecSupported,isMediaSessionSupported:d.isMediaSessionSupported,isWebTransportSupported:d.isWebTransportSupported};Le.uploadEvent({log:`trtcstats-${JSON.stringify(p)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(p)}`),Le.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(T)}`,userId:this.userId})})}function yE(){return Ce(i=>{let t=new ff;return function(e,r,o){return v(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new de({code:Y.INVALID_OPERATION,message:ot({key:it.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new de({code:Y.INVALID_OPERATION,message:ot({key:it.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),B.emit(O.JOIN_START,{room:this,roomId:s,params:e});let a=Gr.getEnv();a||(a=pi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Zc.OLD_CLOUD_LADDER)?a=pi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Zc.WEBRTC)&&(a=pi.WEBRTC))),Le.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Gi.checkSystemRequirementsInternal().then(d=>{this.checkSystemResult=d,rA.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Gr.getEnv()&&(yield this.schedule(e,o));let d=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Gr.performanceNow(),B.emit(O.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&Le.uploadEvent({log:`stat-conv-${Number(wr)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw t.delete({room:this,roomId:s}),B.emit(O.JOIN_FAILED,{room:this,error:d}),d}})}})}var AE=()=>Ce(i=>function(...t){return v(this,null,function*(){B.emit(O.LEAVE_START,{room:this}),yield i.call(this),B.emit(O.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function bE(){return Ce(i=>function(...t){return v(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="capture"),!t.length))return;B.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function vE(){return Ce(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function RE(){return Ce(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function iA({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return Li(r)?r.catch(o=>V.error(`${i.name}() error observed ${o}`)):r}catch(r){V.error(`${i.name}() error observed ${r}`)}}}var qu=class{constructor(t){l(this,"_frameWorkType");l(this,"_component");l(this,"_language");l(this,"connectionType");l(this,"_room");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});l(this,"_keyPrefix");l(this,"_log");l(this,"_intervalId");l(this,"_firstPublishedUserList");l(this,"_networkQuality");l(this,"_basicInfo");l(this,"_pathJoinRoom");l(this,"_pathLeaveRoom");l(this,"_pathMainVideoMap");l(this,"_pathMainAudioMap");l(this,"_pathAuxiliaryMap");l(this,"_remoteStreamStatMap");l(this,"_localStreamStat");l(this,"_eventMap",new Map);l(this,"_captureCostSum",0);l(this,"_captureCostCount",0);l(this,"isDestroyed",!1);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=V.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Ve(this[e])&&(this[e]=iA({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Ke,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,ga().then(t=>{this._basicInfo.string_os_version=vo(),t?this._basicInfo.string_device_name=t.mobile?t.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),B.on(t,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(O.JOIN_START,this.handleJoinStart).addEvent(O.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(O.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(O.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(O.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(O.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(O.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(O.JOIN_FAILED,this.handleJoinFailed).addEvent(O.LEAVE_START,this.handleLeaveStart).addEvent(O.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(O.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(O.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(O.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(O.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(O.PUBLISH_START,this.handlePublishStart).addEvent(O.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(O.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(O.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(O.PLAY_TRACK_START,this.handlePlayStart).addEvent(O.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(O.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===D.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(O.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(O.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(O.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(O.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let o=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,a=r.hasAudio||r.hasVideo||r.hasSmall,d=r.hasAuxiliary;!o&&a&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&d&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(O.SINGLE_CONNECTION_STAT,({room:t,stat:e})=>{this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((t,e)=>B.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Et.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(t){this.hitTest(t.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),t.params&&(L(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),L(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),L(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:t,detailCost:e}){if(this.hitTest(t)&&e){let{totalCost:r,local:o,dns:s,tcp:a,tls:d,request:h,response:p}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=a,this._pathJoinRoom.int32_schedule_tls=d,this._pathJoinRoom.int32_schedule_request=h,this._pathJoinRoom.int32_schedule_response=p}}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof de?Number(e.getExtraCode()||e.getCode()):Y.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){!this.hitTest(t)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:me(J({},oA),{msg_user_info:new ec({userId:t,tinyId:(o=this._room.remotePublishedUserMap.get(t))==null?void 0:o.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:o}){if(!this.hitTest(t))return;let{userId:s,tinyId:a,role:d}=e,h=new ec({userId:s,tinyId:a,role:d==="anchor"?20:21}),p=Date.now(),T=`${s}_${r}`,y=this._remoteStreamStatMap.get(T);y&&y.subscribeStartTime===0&&(y.subscribeStartTime=p),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(T)&&this._pathMainVideoMap.set(T,{statsToReport:{msg_user_info:h,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:p}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(T)&&this._pathMainAudioMap.set(T,{statsToReport:{msg_user_info:h,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:p})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(T)&&this._pathAuxiliaryMap.set(T,{sendSubscribeCMDTime:p})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(o&&(o.statsToReport.uint64_render_first_frame_time===0&&(o.statsToReport.uint64_render_first_frame_time=r),s)){let{statsToReport:d,playStreamTime:h,subscribedTime:p}=s;d.uint32_video_render_first===0&&h-p<=100&&(d.uint32_video_render_first=r-o.sendSubscribeCMDTime)}let a=this._pathAuxiliaryMap.get(e);if(a&&s){let{statsToReport:d,playStreamTime:h,subscribedTime:p}=s;d.uint32_video_render_first===0&&h-p<=100&&(d.uint32_video_render_first=r-a.sendSubscribeCMDTime)}}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:o,videoDelay:s,audioDelay:a})=>{let d=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(d)d.totalRTT+=e,d.totalLoss+=r,s&&(d.totalVideoDelay=(d.totalVideoDelay||0)+s,d.videoDelayCount=(d.videoDelayCount||0)+1),a&&(d.totalAudioDelay=(d.totalAudioDelay||0)+a,d.audioDelayCount=(d.audioDelayCount||0)+1),d.count++;else{let h,p,T,y;s&&(p=s,T=1),a&&(h=a,y=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:h,totalVideoDelay:p,audioDelayCount:y,videoDelayCount:T})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_device_info:e,msg_up_stream_info:r,msg_down_stream_info:o}=t.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:a,uint32_video_width:d,uint32_video_height:h}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=h,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/Ii*100)>0&&(this._localStreamStat.totalAudioLevel+=s/Ii,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:a,msg_audio_status:d,msg_video_status:h}=s,p=a.str_identifier,T=this._room.remotePublishedUserMap.get(p);if(h.forEach(y=>{let R=y.uint32_video_stream_type===2,N=y.uint32_video_stream_type===7,j=`${p}_${R?"main":"auxiliary"}`,W=this._remoteStreamStatMap.get(j);if(!!W&&(R&&(T==null?void 0:T.remoteVideoTrack.isSubscribed)||N&&(T==null?void 0:T.remoteAuxiliaryTrack))){W.totalVideoFPS+=y.uint32_video_receive_fps,W.totalVideoBitrate+=y.uint32_video_codec_bitrate,W.videoCount++,W.statsToReport.uint32_video_width===0&&(W.statsToReport.uint32_video_width=y.uint32_video_width),W.statsToReport.uint32_video_height===0&&(W.statsToReport.uint32_video_height=y.uint32_video_height);let F=R?T.remoteVideoTrack:T.remoteAuxiliaryTrack;F.stat.jitterBufferDelay&&(W.videoJitterBufferDelay=F.stat.jitterBufferDelay),F.stat.framesReceived&&(W.statsToReport.uint32_video_consume_render_rate=Math.floor(F.stat.framesDecoded/F.stat.framesReceived*Wn(10,6)))}}),d){let y=`${p}_${"main"}`,R=this._remoteStreamStatMap.get(y);this._remoteStreamStatMap.has(y)&&R&&(T==null?void 0:T.remoteAudioTrack.isSubscribed)&&(R.totalAudioBitrate+=d.uint32_audio_codec_bitrate,R.audioCount++,T.remoteAudioTrack.stat.jitterBufferDelay&&(R.audioJitterBufferDelay=T.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/Ii*100)>0&&(R.totalAudioLevel+=d.uint32_audio_level/Ii,R.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof de?e.getExtraCode()||e.getCode():Y.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=o,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=o,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&_s)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&gs)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Jn)>=0}hitTest(t){return t===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o){let{totalLoss:T,count:y,audioDelayCount:R,videoDelayCount:N,totalAudioDelay:j,totalVideoDelay:W}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(T/y),R&&j&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(j/R),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),N&&W&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(W/N))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,D.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,D.VIDEO)),t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,es);let{badCaseDetector:a}=this._room,{dataFreeze:d,count:h}=a.getDataFreezeDuration(e),{renderFreeze:p}=a.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=h,t.statsToReport.uint32_video_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(p,t.statsToReport.uint32_video_play_time),a.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0,(t.subscribeStartTime===0||t.subscribeStartTime-t.streamAddedTime>100||t.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),t.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>es&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+es)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>es&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+es)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>es&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+es)}getReportData(){this._basicInfo.uint32_networkType=id();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new ec({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ss(this._signalInfo.relayIp),uint32_client_ip:Ss(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Wn(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Ss(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return ia(t),t}report(){return v(this,null,function*(){try{this.prepareReport();let t=this.getReportData();yield this.upload(t),this.initData()}catch(t){this._log.warn(t)}finally{this.isDestroyed&&(this._room=null)}})}upload(t){return v(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield mp(t),o=r instanceof ArrayBuffer,s=`${fi(e,ki.KEY_POINT)}&gzip=${+o}`,a=!1;navigator.sendBeacon&&(a=navigator.sendBeacon(s,r));let d=[this.uploadKVStat(X),this.uploadKVStat(xo)];a||d.push(_i({url:s,body:r,priority:"low"})),yield Promise.all(d)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return v(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=me(J({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let r=yield mp(e),o=`${fi(+this._room.sdkAppId,ki.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||_i({url:o,body:r})})}};q([ji({settings:{timeout:500,retries:3}})],qu.prototype,"upload",1);var es=5e3,oA={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},ec=class{constructor(t){l(this,"str_identifier");l(this,"str_tinyid");l(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},CE=qu;var _f=class{constructor(){l(this,"_startTime");l(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=ge())}stop(){this._endTime===0&&(this._endTime=ge())}getDuration(){return this._endTime===0?ge()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},mn=_f;var gf=class{constructor(t){l(this,"_room",null);l(this,"_durationMap");l(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(O.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(O.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(O.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var a;let{userId:o}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${o}_${"main"}`,D.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_${"main"}`,D.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_${"auxiliary"}`,D.VIDEO);let s=(a=this._room)==null?void 0:a.remotePublishedUserMap.get(o);!s||(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,D.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>B.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>B.off(e,t,this)),this._eventMap.clear()}handleSubscribed({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;if(r.muteState.hasAudio&&e==="main")if(r.remoteAudioTrack.isSubscribed){let a=new mn,d=this._durationMap.get(s);d?this.isRecording(d.audio)||d.audio.push(a):this._durationMap.set(s,{userId:o,type:e,audio:[a],video:[]})}else this.stopDurationItem(s,D.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let a=new mn,d=this._durationMap.get(s);d?this.isRecording(d.video)||d.video.push(a):this._durationMap.set(s,{userId:o,type:e,audio:[],video:[a]})}else this.stopDurationItem(s,D.VIDEO)}handleStreamStopped({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDurationItem(s,D.AUDIO),this.stopDurationItem(s,D.VIDEO)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,r){let o=`${t}_${r}`,s=new mn,a=this._durationMap.get(o);a?this.isRecording(a[e])||a[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===D.AUDIO?[s]:[],video:e===D.AUDIO?[]:[s]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let o=this._durationMap.get(t)[e].find(s=>s.endTime===0);o&&o.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((o,s)=>o+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},DE=gf;var Ef=class{constructor(t){l(this,"_room");l(this,"_renderFreezeMap",new Map);l(this,"_isVideoPlayingEventFiredMap",new Map);l(this,"_dataFreezeMap",new Map);l(this,"_monitorFreezeData",new Map);l(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}installEvents(){this._eventMap.set(O.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(O.PLAY_TRACK_START,this.onPlayTrackStart).set(O.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:r})=>{if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDataFreeze({key:s,userId:o,type:e})}).set(O.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let{userId:o}=r;if(e.hasVideo&&!r.hasVideo){let s="main",a=`${r.userId}_${s}`;this.stopDataFreeze({key:a,userId:o,type:s})}if(e.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",a=`${r.userId}_${s}`;this.stopDataFreeze({key:a,userId:o,type:s})}}).set(O.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!this.hitTest(t.room)||o!==D.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===D.MUTE?this.onVideoTrackMuted(t):r===D.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(O.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>B.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>B.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`,s=this._dataFreezeMap.get(o),a=new mn;s?s.durationItemList.push(a):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[a],isFreezing(){let d=this.durationItemList[this.durationItemList.length-1];return d&&d.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){!this.hitTest(t)||e.msg_down_stream_info.forEach(r=>{let o=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!o)return;let{userId:s,muteState:a}=o;r.msg_video_status.forEach(d=>{d.uint32_video_stream_type===2&&a.hasVideo&&!a.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"main"}),d.uint32_video_stream_type===7&&a.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let a=s.getDuration();a>td?this._monitorFreezeData.set(t,{userId:e,type:r,duration:a}):o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}handleRenderFreeze(o){return v(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,a=this._renderFreezeMap.get(s);if(e<=2){let d=ge();a&&!a.isFreeze&&(a.freezeTimeline.push({startTime:d,endTime:0}),a.isFreeze=!0),a||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:d,endTime:0}],renderFreezeTotal:0})}else if(a&&a.isFreeze){a.isFreeze=!1;let d=a.freezeTimeline.pop();if(d){d.endTime=ge();let h=d.endTime-d.startTime;a.freezeTimeline.push(d),a.renderFreezeTotal+=Math.min(5e3,h)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==D.VIDEO||t.hasFlag)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},r=this._dataFreezeMap.get(t);if(r){if(r.isFreezing()){let o=r.durationItemList[r.durationItemList.length-1];o.stop(),o.getDuration()<td&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,o=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=ge(),a=e.freezeTimeline[e.freezeTimeline.length-1],d=s-a.startTime;r=e.renderFreezeTotal+Math.min(d,5e3),o=e.freezeTimeline.length}return{renderFreeze:r,count:o}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},NE=Ef;var xE=Pi(Hi(),1);var sA=[1,0,0,0,1,1,0,1],zu=class extends Vt{constructor(t,e){if(super(t,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),t instanceof st)try{this.setTexBuffer(sA)}catch(r){t.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}draw2d(t,e,r,o,s){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let a=super.draw2d(t,e,r,o,s);return this.ctx2d.restore(),a}return!1}render(t){var e;return(e=this.input)!=null&&e.requestFrame(t)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Tf=class{constructor(t,e){this.node=t;this.layout=e;l(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},Ju=class extends Vt{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:r});l(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new Tf(e,r);this.inputs[r.zIndex]=o}resize(e,r){let o=this.inputs.reduce((s,a)=>a?Object.assign(s,{width:Math.max(s.width,a.right),height:Math.max(s.height,a.bottom)}):s,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof st&&this.inputs.forEach(s=>{if(s){let a=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,a):s.positionBuffer=this.createBuffer(a)}})}connect(e,...r){return super.connect(e,...r),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(r=>(r==null?void 0:r.node)===e)]=void 0}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),!this.inputs.reduce((s,a)=>(!a||!a.node.requestFrame(e))&&s,!0)&&r){this.useProgram(),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let a=this.inputs[s];a&&(a.node.useTexture(),this.draw(a.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((o,s)=>(!s||!s.node.requestFrame(e))&&o,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let o=0;o<this.inputs.length;o++){let s=this.inputs[o];s&&this.draw2d(s.node.image,s.x,s.y,s.width,s.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:a,name:d}=this,h=Date.now(),p=(e-this.lastInfo.totalFrames)/((h-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:a,timestamp:h,fps:p,name:d},J({parent:this.inputs.filter(T=>T).map(T=>T.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var r,o;if(e&&((r=e.node)==null||r.disconnect(),e.positionBuffer&&this.context instanceof st))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var nA=`#version 300 es
|
|
98
|
+
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(i=>{EE[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var dL=Object.keys(EE);var Ky=0,Hu,hf=class{constructor(t){this.core=t;l(this,"_core");l(this,"log");l(this,"dumpLocalVideoMap",{});l(this,"dumpRemoteVideoMap",{});l(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++Ky}`}),this.log.info("created")}getName(){return hf.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(t){switch(t){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return v(this,null,function*(){!new URLSearchParams(location.search).has("trtcDebug")||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return v(this,null,function*(){try{if(Hu)yield Hu;else{let t=Date.now();Hu=this.loadScript(`https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@${Ke}.js`),yield Hu,this.log.info(`download debug dialog script cost: ${Date.now()-t}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(t){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(t))}})}closeDebugDiaLog(){var t;(t=this.dialog)==null||t.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):pf,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):mf,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return pf({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return mf({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}loadScript(t){return new Promise((e,r)=>{this.log.info(`loading debug dialog from ${t}`);let o=document.createElement("script");o.type="text/javascript",o.onload=e,o.onerror=r,o.crossOrigin="anonymous",o.src=t,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}},Ko=hf;l(Ko,"Name","Debug"),l(Ko,"autoStart",!0),q([ji({settings:{timeout:3e3,retries:3},onError(i,t,e){var r;(r=i==null?void 0:i.message)!=null&&r.includes("timeout")?t():e(i)}})],Ko.prototype,"loadScript",1);var TE=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Wu=class{constructor(t,e,r){l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"type","auto");l(this,"config");l(this,"decoder");l(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=Je(e,Z.INIT),this.stopOB=Jt(this.trackDoneOB),this.startOB=Jt(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let a=Jt(),d=h=>{let p=this.pipe(e);return a.next("STARTING"),e.log.info(`decoder type: ${this.type}`),We(p,gt(this.stopOB),dt(()=>{},T=>{e.log.error(T),o.addFailedEvent({key:TE(this.type),error:T}),h>4?this.startOB.error(T):this.startOB.next(h+1)})),We(p,xr(1),qa(Ho))};We(this.startOB,$o(0),Qi(d),gt(this.stopOB),dt(()=>{e.player.setOutput(),a.next("STARTED")},h=>{a.next("FAILED")},()=>{o.addSuccessEvent({key:TE(this.type)}),o.addSuccessEvent({key:504702})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}pipe(t){return Ri()(e=>v(this,null,function*(){this._decodeSink=e,e.defer(()=>{var o;(o=this.decoder)==null||o.close()});let{type:r}=this;try{switch(r){case"webCodecs":this.decoder=new AudioDecoder({error:o=>{t.log.error(o),e.error(4)},output:o=>{this.decodedFrameCount++,e.next(o),t.player.write(o)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(o){t.log.error(o),e.error(r==="webCodecs"?2:6)}}))}decodeFrame(t){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:t.data,timestamp:t.timestamp,type:"key"}))}},eA={type:"object"},Gu=class{constructor(t){this.core=t;l(this,"log");l(this,"contextMap",new Map);l(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Gu.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return Gu.Name}getValidateRule(t){return eA}start(t){let{track:e}=t;this.decodeProcessorMap.set(e,this.decode(t)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:r,track:o})=>this.decodeProcessorMap.has(o)?this.decodeProcessorMap.get(o)({frame:r,track:o}):r,type:3})}decode(t){return({frame:e,track:r})=>{if(r!==t.track)return e;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(e);let o=new Wu(this.core,r,t);return We(o.trackDoneOB,xr(1),dt(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:r})})),this.contextMap.set(r,o),o.decodeFrame(e)}}stop({track:t}){let e=this.contextMap.get(t);!e||(e.close("stop"),this.contextMap.delete(t),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(t){let e=this.contextMap.get(t.track);if(!!e){if(t.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(t.track,new Wu(this.core,t.track,t))}}},pn=Gu;l(pn,"Name","AudioDecoder");var IE=0,Ka=new Set,It=null;ep(_E);Ls.checkStorage();im();var tA={RtcError:oe,ErrorCode:ne,ErrorCodeDictionary:Or},dr=class extends SE.EventEmitter{constructor(e,r){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioVolumeMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",V.createLogger({id:`t${++IE}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");l(this,"_getPCMAbortCtrl");this._room=new e(J({logger:this._log,frameWorkType:dr.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,this._log.debug(`TRTC.create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(a=>a.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(io,r.assetsPath),this._use(Zo,r.assetsPath),this._use(pn,r.assetsPath||Jc),this._use(Ko),r.enableSEI&&Ma&&this._use(ln),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(re.AUDIO_VOLUME,{result:o.sort((s,a)=>a.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new oe({code:ne.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),mE(this,"trtc")}static create(e){}static _create(e,r){tE();let o=new dr(e,r||{});return Ka.add(o),o}get room(){return this._room}_listenEvents(){Rt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(re.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(re.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(re.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(re.ERROR,oe.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(re.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=me(J({},e),{uplinkRTT:Math.min(e.uplinkRTT,Yn),downlinkRTT:Math.min(e.downlinkRTT,Yn)});this.emit(re.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{Rt(o,o).add("player-state-changed",s=>{let a=me(J({},s),{userId:e.userId});o.kind===D.VIDEO&&(a.streamType=Qa(o.streamType)),this.emit(o.kind===D.AUDIO?re.AUDIO_PLAY_STATE_CHANGED:re.VIDEO_PLAY_STATE_CHANGED,a)}).add("error",s=>{s.getCode()===Y.PLAY_NOT_ALLOWED&&this.emit(re.AUTOPLAY_FAILED,{userId:o.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{ct(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,a=e.videoAvailable,{audioAvailable:d,videoAvailable:h}=r;d||this._remoteAudioConfigMap.delete(o),h||this._remoteVideoConfigMap.delete(`${o}_${"main"}`),r.hasAuxiliary||this._remoteVideoConfigMap.delete(`${o}_${"sub"}`),a!==h&&(h?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(h?re.REMOTE_VIDEO_AVAILABLE:re.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==d&&(d?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(d?re.REMOTE_AUDIO_AVAILABLE:re.REMOTE_AUDIO_UNAVAILABLE,{userId:o})),e.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:o,streamType:"sub"}):this._onVideoUnavailable({userId:o,streamType:"sub"}),this.emit(r.hasAuxiliary?re.REMOTE_VIDEO_AVAILABLE:re.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(re.SEI_MESSAGE,me(J({},e),{streamType:Qa(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(re.ERROR,new oe({code:ne.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,a,d,h,p,T,y;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((a=this._networkQuality)==null?void 0:a.uplinkRTT)||((d=this._networkQuality)==null?void 0:d.downlinkRTT)||0,Yn),upLoss:((h=this._networkQuality)==null?void 0:h.uplinkLoss)||0,downLoss:((p=this._networkQuality)==null?void 0:p.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((T=e.msg_up_stream_info.msg_audio_status)==null?void 0:T.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((y=e.msg_up_stream_info.msg_audio_status)==null?void 0:y.uint32_audio_level)||0)/Ii},video:e.msg_up_stream_info.msg_video_status.filter(R=>r[R.uint32_video_stream_type]).map(R=>({bitrate:(R.uint32_video_codec_bitrate||0)/1e3,width:R.uint32_video_width,height:R.uint32_video_height,frameRate:R.uint32_video_enc_fps,videoType:r[R.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(R=>({userId:R.msg_user_info.str_identifier,audio:{bitrate:(R.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(R.msg_audio_status.uint32_audio_level||0)/Ii},video:R.msg_video_status.map(N=>({bitrate:(N.uint32_video_codec_bitrate||0)/1e3,width:N.uint32_video_width,height:N.uint32_video_height,frameRate:N.uint32_video_dec_fps,videoType:r[N.uint32_video_stream_type]}))}))};this.emit(re.STATISTICS,o)}).add("custom-message",e=>{this.emit(re.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(re.LAYER_DATA,e)),Rt(this,_t).add("audioInputAdded",e=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>v(this,null,function*(){if(this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),It&&It.deviceId===Qn){let r=(yield qi()).find(o=>o.deviceId===Qn);r&&It.groupId!==r.groupId&&(It=r,this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>v(this,null,function*(){this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield qi())[0];if(!r||!It||It.groupId===r.groupId)return;let o=It.deviceId===e.deviceId,s=It.deviceId===Qn&&It.deviceId===r.deviceId;(o||s)&&(It=r,this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}))}use(e){let r,o;"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,this._use(r,o||Jc)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(pE.call(this,{TRTC:dr,room:this._room,errorModule:tA,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return v(this,null,function*(){var h,p;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:a=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Ae(e.proxy)&&e.proxy.turnServer&&((p=(h=this._room).setTurnServer)==null||p.call(h,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=a,nt(e.preferHW)&&(this._room.preferHW=e.preferHW);let d={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(d,r,dr.frameWorkType),this._checkTrackToPublish(),af.start()})}exitRoom(){return v(this,null,function*(){return yield this._exitRoom()})}switchRole(e,r){return v(this,null,function*(){r!=null&&r.privateMapKey&&(this._room.privateMapKey=r.privateMapKey),r!=null&&r.latencyLevel&&(this._room.latencyLevel=r.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){ct(this),this.removeAllListeners(),this._room.destroy(),Ka.delete(this),Ka.size===0&&af.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)})}startLocalAudio(){return v(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,option:s}=e,a=new ar(this._room.audioManager),d={},h={muted:!0};s&&(L(s.microphoneId)?L(s.audioTrack)||(d.customSource=s.audioTrack):d.deviceId=s.microphoneId,s&&Fe(s.captureVolume)&&a.setCaptureVolume(s.captureVolume),L(s.profile)||(Ae(s.profile)?Qc[s.profile]&&a.setProfile(Qc[s.profile]):a.setProfile(s.profile)),Fe(s.earMonitorVolume)&&(h.muted=!(s.earMonitorVolume>0),h.volume=s.earMonitorVolume),L(s.echoCancellation)||(a.profile.echoCancellation=s.echoCancellation),L(s.noiseSuppression)||(a.profile.noiseSuppression=s.noiseSuppression),L(s.autoGainControl)||(a.profile.autoGainControl=s.autoGainControl)),a.on("5",p=>{this.emit(re.ERROR,new oe({code:ne.DEVICE_ERROR,extraCode:5309,messageParams:{error:p}}))}),a.on("2",p=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"active",device:p})}),a.on("4",p=>{let T;p.error&&(T=oe.convertFrom(p.error)),this.emit(re.PUBLISH_STATE_CHANGED,me(J({},p),{error:T}))}),this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId),yield a.capture(d),L(o)||a.setMute(o),Rt(a,a).add("player-state-changed",p=>{this.emit(re.AUDIO_PLAY_STATE_CHANGED,me(J({},p),{userId:""}))}),this.listeners(re.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(p=>{this.emit(dr.EVENT.AUDIO_FRAME,{data:p})})),this._getPCMAbortCtrl&&a.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(p=>{this.emit(dr.EVENT.AUDIO_FRAME,{data:p})}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localAudioTrack=a,this._localAudioConfig=me(J({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:h,track:a})})}updateLocalAudio(e){return v(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,option:s}=e,a={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):L(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),L(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),L(s.earMonitorVolume)||(a.muted=!(s.earMonitorVolume>0),a.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!L(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),L(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:a,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Wr(this._localAudioConfig,e)})}stopLocalAudio(){return v(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ct(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return v(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,mute:s,option:a}=e,d=new hr(this._room.videoManager),h={},p={};a&&(a.cameraId?h.deviceId=a.cameraId:L(a.useFrontCamera)?L(a.videoTrack)||(h.customSource=a.videoTrack):h.facingMode=a.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,a.qosPreference&&(h.contentHint=Ya(a.qosPreference)),L(a.profile)||(Ae(a.profile)?$r[a.profile]&&d.setProfile($r[a.profile]):d.setProfile(a.profile)),L(a.fillMode)||(p.objectFit=a.fillMode),L(a.mirror)||(p.mirror=a.mirror),L(a.small)||(Na()?Ae(a.small)?d.small=$r[a.small]:a.small===!0?d.small=$r["120p"]:d.small=a.small:this._log.warn("small stream is not supported"))),d.on("5",T=>{this.emit(re.ERROR,new oe({code:ne.DEVICE_ERROR,extraCode:5308,messageParams:{error:T}}))}),d.on("2",T=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"active",device:T})}),d.on("4",T=>{let y;T.error&&(y=oe.convertFrom(T.error)),this.emit(re.PUBLISH_STATE_CHANGED,me(J({},T),{error:y}))}),this._listenOutputTrackChanged(d),yield d.capture(h),L(s)||(yield d.setMute(s)),Rt(d,d).add("player-state-changed",T=>{this.emit(re.VIDEO_PLAY_STATE_CHANGED,me(J({},T),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=me(J({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:p,track:d})})}updateLocalVideo(e){return v(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,option:a}=e,d={};if(a)if(L(a.profile)||(Ae(a.profile)?$r[a.profile]&&this._localVideoTrack.setProfile($r[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&L(a.useFrontCamera)&&this._localVideoTrack.applyProfile()),a.cameraId?yield this._localVideoTrack.switchDevice(a.cameraId):L(a.useFrontCamera)?L(a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a.videoTrack)):yield this._localVideoTrack.switchDevice(a.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT),L(a.fillMode)||(d.objectFit=a.fillMode),L(a.mirror)||(d.mirror=a.mirror),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Ya(a.qosPreference)),a.small){let h=!this._localVideoTrack.small;Na()?(a.small===!0?this._localVideoTrack.small=$r["120p"]:Ae(a.small)?this._localVideoTrack.small=$r[a.small]:this._localVideoTrack.small=a.small,this._room.videoManager.update(),h&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else a.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!L(o)&&(o&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!o&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),L(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Wr(this._localVideoConfig,e)})}stopLocalVideo(){return v(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),ct(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return v(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,option:s}=e,a=new Ji(this._room.videoManager);a.on("4",y=>{let R;y.error&&(R=oe.convertFrom(y.error)),this.emit(re.PUBLISH_STATE_CHANGED,me(J({},y),{error:R}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let d=null,h={},p={};s&&(L(s.profile)||(Ae(s.profile)?Yc[s.profile]&&a.setProfile(Yc[s.profile]):a.setProfile(s.profile)),s.systemAudio&&(h.systemAudio=!0,h.echoCancellation=s.echoCancellation,h.noiseSuppression=s.noiseSuppression,h.autoGainControl=s.autoGainControl),L(s.fillMode)||(p.objectFit=s.fillMode),s.videoTrack&&(h.videoTrack=s.videoTrack),s.audioTrack&&(h.audioTrack=s.audioTrack),s.captureElement&&(h.captureElement=s.captureElement),s.preferDisplaySurface&&(h.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(h.contentHint=Ya(s.qosPreference)));let T=yield a.capture(h);if(a.mediaTrack.addEventListener(D.ENDED,()=>{this._stopScreenShare(),this.emit(re.SCREEN_SHARE_STOPPED)}),T.getAudioTracks()[0]&&(d=new Uo(this._room.audioManager),yield d.setInputMediaStreamTrack(T.getAudioTracks()[0]),this._speakerId&&d.setAudioOutput(this._speakerId)),Rt(a,a).add("player-state-changed",y=>{this.emit(re.VIDEO_PLAY_STATE_CHANGED,me(J({},y),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let y=[a];d&&y.push(d),this._room.publish(...y).catch(()=>{})}this._localScreenTrack=a,this._localScreenAudioTrack=d,this._localScreenConfig=me(J({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:p,track:a})})}updateScreenShare(e){return v(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,a={};if(s&&(L(s.fillMode)||(a.objectFit=s.fillMode),s.qosPreference)){let d=Ya(s.qosPreference);this._localScreenTrack.setContentHint(d)}this._room.isJoined&&!L(o)&&(o&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!o&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Wr(this._localScreenConfig,e)})}stopScreenShare(){return v(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return v(this,null,function*(){let{view:r,userId:o,streamType:s,option:a}=e,d=`${o}_${s}`;if(this._remoteVideoConfigMap.has(d)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let h=this._room.remotePublishedUserMap.get(o);if(!h)return;let p={},T=s==="main"?h.remoteVideoTrack:h.remoteAuxiliaryTrack;this._listenOutputTrackChanged(T),a&&(L(a.fillMode)||(p.objectFit=a.fillMode),L(a.mirror)||(p.mirror=a.mirror),p.canvasRender=a.canvasRender,s==="main"&&!L(a.small)&&(h.remoteVideoTrack.setMediaType(a.small?8:4),this._room.changeType(a.small,T.user))),yield this._room.subscribe(T),yield this._enableVideoDecodeFallback(T,s),yield this._updateVideoPlayOption({view:r,playOption:p,track:T}),this._emitTrackEvent(T),this._remoteVideoConfigMap.set(d,{config:e}),a&&!L(a.receiveWhenViewVisible)&&this._observeView({remoteTrack:T,view:r,receiveWhenViewVisible:a.receiveWhenViewVisible,viewRoot:a==null?void 0:a.viewRoot})})}updateRemoteVideo(e){return v(this,null,function*(){var F,Ie;let{view:r,userId:o,streamType:s,option:a}=e,d=`${o}_${s}`,h=this._remoteVideoConfigMap.get(d);if(!h||!this._room.remotePublishedUserMap.has(o))return;let p={};a&&(L(a.fillMode)||(p.objectFit=a.fillMode),L(a.mirror)||(p.mirror=a.mirror));let T=null,y=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(y==null?void 0:y.muteState.hasVideo)&&(T=y.remoteVideoTrack),s==="sub"&&(y==null?void 0:y.muteState.hasAuxiliary)&&(T=y.remoteAuxiliaryTrack),!T)return;let{config:R}=h;s==="main"&&a&&!L(a.small)&&this._room.changeType(a.small,T.user),yield this._updateVideoPlayOption({view:r,playOption:p,track:T,prevConfig:R}),Wr(R,e);let N=L(a==null?void 0:a.receiveWhenViewVisible)?(F=R.option)==null?void 0:F.receiveWhenViewVisible:a.receiveWhenViewVisible,j=L(r)?R.view:r,W=L(a==null?void 0:a.viewRoot)?(Ie=R.option)==null?void 0:Ie.viewRoot:a.viewRoot;this._observeView({remoteTrack:T,view:j,receiveWhenViewVisible:N,viewRoot:W})})}stopRemoteVideo(e){return v(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return v(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:d,remoteVideoTrack:h,remoteAuxiliaryTrack:p}=s;e.streamType==="main"&&(h.stop(),d.hasVideo&&o.push(h)),e.streamType==="sub"&&(p.stop(),d.hasAuxiliary&&o.push(p))}for(let d of o)r&&(yield this._room.unsubscribe(d),this._mediaTrackMap.get(d.outMediaTrack)===d.userId&&this._mediaTrackMap.delete(d.outMediaTrack));let a=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);a&&a.observer&&a.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,r){return v(this,null,function*(){this._remoteAudioMuteMap.set(e,r);try{if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(o){throw this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return v(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return v(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return v(this,null,function*(){return e.stop(r)})}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}on(e,r,o){return this.listeners(e).includes(r)?this:(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),e===dr.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(dr.EVENT.AUDIO_FRAME,{data:s})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(dr.EVENT.AUDIO_FRAME,{data:s})}))})),this)}emit(e,...r){try{dE.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){var s,a;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(s=this._getPCMAbortCtrl)==null||s.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,r,o),e===dr.EVENT.AUDIO_FRAME&&((a=this._getPCMAbortCtrl)==null||a.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",a=!1;if(Ae(e)?r=e:(r=e.userId,a=e.processed===!0,e.streamType&&(s=e.streamType)),r){let d=this._room.remotePublishedUserMap.get(r);d&&(o=d.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?a&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,a=null;if(r==="")o==="main"&&this._localVideoTrack&&(a=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(a=this._localScreenTrack);else{let d=this._room.remotePublishedUserMap.get(r);d&&(a=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack)}return a?s&&a.outMediaTrack&&a.outMediaTrack!==a.mediaTrack?a.outMediaTrack.clone():a.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s==null?void 0:s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s==null?void 0:s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return v(this,null,function*(){(yield qi()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),It=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return v(this,null,function*(){let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},a=o.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{let d=this._remoteAudioVolumeMap.get(r),h=Fe(d)?d:100;s.volume=h,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(a),We(Je(a,"decode-failed"),gt(Je(a,Z.INIT)),dt(()=>{this.startPlugin(pn.Name,{track:a,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:a})}catch(d){throw this._remoteAudioConfigMap.delete(r),d}this._emitTrackEvent(a)})}_stopRemoteAudio(e,r=!0){return v(this,null,function*(){let o=this._room.remotePublishedUserMap.get(e.userId);o&&(o.remoteAudioTrack.stop(),o.muteState.hasAudio&&r&&(yield this._room.unsubscribe(o.remoteAudioTrack)),this._mediaTrackMap.get(o.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(o.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_enableVideoDecodeFallback(e,r){let o=this._room.videoDecodeFallbackType;!o||!this._plugins.has("TRTCVideoDecoder")||(this._log.info("remote video will fall back when decode failed"),We(Je(e,"decode-failed"),gt(Je(e,Z.INIT)),oh(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),ja(Je(e,"decode-downgrade-state-changed")),dt(s=>{this.emit(re.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,me(J({},s),{streamType:r,userId:e.userId}))},s=>{this._log.error("fallback",s)},()=>this._log.info("fallback complete"))))}_updateVideoPlayOption(a){return v(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),L(e)&&s&&s.view&&!sd(r)){let d=ys(s.view);d.length>0&&(yield o.play(d,r))}if(!L(e)){let d=ys(e);d.length>0?yield o.play(d,r):o.stop()}})}_updateAudioPlayOption(s){return v(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(a){}L(e.muted)||r.setPlayerMute(e.muted),L(e.volume)||r.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,r=!0){let o=e.isRemote?e.userId:"";!e.outMediaTrack||r&&this._mediaTrackMap.get(e.outMediaTrack)===o||(this._mediaTrackMap.set(e.outMediaTrack,o),this.emit(re.TRACK,{userId:o,streamType:Qa(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var r,o,s;let e=[];if(((r=this._localAudioConfig)==null?void 0:r.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((o=this._localVideoConfig)==null?void 0:o.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(L(r))return;let a=this._remoteVideoConfigMap.get(`${e.userId}_${Qa(e.streamType)}`);if(!a)return;let d=a.observer||void 0;if(r===null||rt(r)&&r.length===0||!o){d==null||d.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let p=a.visibleViewMap||new Map,T=-1;(!d||d.root!==s)&&(d==null||d.disconnect(),p.clear(),d=new IntersectionObserver(R=>{R.forEach(N=>{p.set(N.target,N.isIntersecting)}),clearTimeout(T),T=window.setTimeout(()=>{[...p.values()].find(j=>j)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let y=new Set(ys(r));p.forEach((R,N)=>{y.has(N)||(d.unobserve(N),p.delete(N))}),y.forEach(R=>{p.set(R,!0),d.observe(R)}),d.takeRecords().forEach(R=>{p.set(R.target,R.isIntersecting)}),a.visibleViewMap=p,a.observer=d}_exitRoom(){return v(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),hE(this),this._room.remotePublishedUserMap.forEach(e=>{ct(e.remoteAudioTrack),ct(e.remoteVideoTrack),ct(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return v(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let r=[this._localScreenTrack];this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...r).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),ct(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return v(this,null,function*(){if(It&&!qs(It))this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:It});else{let e=yield qi();if(e[0]&&!qs(e[0]))It=e[0],this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let r=({track:o})=>{o.kind==="audio"&&(!It||qs(It))&&(this._initActiveSpeaker(),B.off("102",this._initActiveSpeaker))};B.on("102",r)}}})}_onAudioAvailable({userId:e}){let r=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(r===!1||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:r}){if(!this._room.autoReceiveVideo)return;let o=this._room.remotePublishedUserMap.get(e);if(o){let s=r==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack,a=[s];this._room.autoReceiveAudio&&a.push(o.remoteAudioTrack),this._room.subscribe(...a).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:r}){r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:r}){this._stopRemoteVideo({userId:e,streamType:r},!1).catch(()=>{})}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:me(J({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),X.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),X.addCount({key:500001,useUV:!0})}static setLogLevel(e,r){V.setLogLevel(e),L(r)||(r?V.enableUploadLog():V.disableUploadLog())}static isSupported(){return $d()}static getCameraList(e=!0){return sr(e)}static getMicrophoneList(e=!0){return zt(e)}static getSpeakerList(e=!0){return qi(e)}static setCurrentSpeaker(e){return v(this,null,function*(){if(ft&&(e===gr.SPEAKER||e===gr.HEADSET)){let o=yield dr.getMicrophoneList(),s="";if(o.forEach(a=>{a.label===e&&(s=a.deviceId)}),!s)return;Ka.forEach(a=>v(this,null,function*(){a._localAudioTrack&&(yield a.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield qi()).forEach(o=>{o.deviceId===e&&(Ka.forEach(s=>{s._setCurrentSpeaker(e),s.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),It=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:a,version:d}){switch(d&&(xo.version=d),e){case"count":xo.addCount({key:r,useUV:a});break;case"enum":xo.addEnum({key:r,value:o,useUV:a});break;case"number":xo.addNumber({key:r,value:o,split:s});break}}},Se=dr;l(Se,"_loggerManager",V),l(Se,"EVENT",re),l(Se,"ERROR_CODE",ne),l(Se,"TYPE",gr),l(Se,"frameWorkType",30),q([je({replaceArg:i=>({argIndex:0,value:{name:"plugin"in i?i.plugin.Name:i.Name,assetsPath:"assetsPath"in i?i==null?void 0:i.assetsPath:"default"}})})],Se.prototype,"use",1),q([Nt(Tt.TRTC.enterRoom),to("room",([i],[t])=>(i.roomId||i.strRoomId)===(t.roomId||t.strRoomId)&&i.userId===t.userId&&i.sdkAppId===t.sdkAppId),Ce(i=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),i.call(this,t)}),je()],Se.prototype,"enterRoom",1),q([je()],Se.prototype,"exitRoom",1),q([Nt(Tt.TRTC.switchRole),Qo("room",{merge:(i,t)=>t}),je()],Se.prototype,"switchRole",1),q([je()],Se.prototype,"destroy",1),q([Nt(Tt.TRTC.startLocalAudio),to("audio",([i],[t])=>{var e,r;return((e=i==null?void 0:i.option)==null?void 0:e.microphoneId)===((r=t==null?void 0:t.option)==null?void 0:r.microphoneId)}),je()],Se.prototype,"startLocalAudio",1),q([Nt(Tt.TRTC.updateLocalAudio),Qo("audio",{debounce:{delay:200,getKey:()=>`${IE}-localAudio`,isNeedToDebounce:i=>{var t;return!L((t=i.option)==null?void 0:t.captureVolume)}}}),je()],Se.prototype,"updateLocalAudio",1),q([ro("audio"),je()],Se.prototype,"stopLocalAudio",1),q([Nt(Tt.TRTC.startLocalVideo),to("video",([i],[t])=>{var e,r;return((e=i==null?void 0:i.option)==null?void 0:e.cameraId)===((r=t==null?void 0:t.option)==null?void 0:r.cameraId)}),je()],Se.prototype,"startLocalVideo",1),q([Nt(Tt.TRTC.updateLocalVideo),Qo("video"),je()],Se.prototype,"updateLocalVideo",1),q([ro("video"),je()],Se.prototype,"stopLocalVideo",1),q([Nt(Tt.TRTC.startScreenShare),to("screen",()=>!0),je()],Se.prototype,"startScreenShare",1),q([Nt(Tt.TRTC.updateScreenShare),Qo("screen"),je()],Se.prototype,"updateScreenShare",1),q([je()],Se.prototype,"stopScreenShare",1),q([Nt(Tt.TRTC.startRemoteVideo),to(i=>`v${i.userId}${i.streamType}`,()=>!0),je({getRemoteId:i=>`${i.userId}_${i.streamType}`})],Se.prototype,"startRemoteVideo",1),q([Nt(Tt.TRTC.updateRemoteVideo),Qo(i=>`v${i.userId}${i.streamType}`),je({getRemoteId:i=>`${i.userId}_${i.streamType}`})],Se.prototype,"updateRemoteVideo",1),q([Nt(Tt.TRTC.stopRemoteVideo),Ce(i=>function(t){return v(this,null,function*(){if(t.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(r=>{this._remoteVideoConfigMap.has(`${r.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:r.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${r.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:r.userId}).catch(()=>{}))}),Promise.all(e)}return i.call(this,t)})}),je({getRemoteId:i=>`${i.userId}_${i.streamType}`})],Se.prototype,"stopRemoteVideo",1),q([ro(i=>`v${i.userId}${i.streamType}`)],Se.prototype,"_stopRemoteVideo",1),q([Nt(...Tt.TRTC.muteRemoteAudio),je({getRemoteId:i=>i})],Se.prototype,"muteRemoteAudio",1),q([rf(...Tt.TRTC.setRemoteAudioVolume),fE(200,i=>i),je({getRemoteId:i=>i})],Se.prototype,"setRemoteAudioVolume",1),q([Bu("start"),zi(i=>{var t;return(t=i.afterStart)==null?void 0:t.call(i)}),to((i,t)=>i.disableRandomCall?null:i.getAlias()+i.getGroup(t)),je({replaceArg:i=>({argIndex:0,value:i.getName()}),getKVReportKey:i=>Jp[i.getName()],ignoreLog:i=>i.getName()==="Debug"})],Se.prototype,"startPlugin",1),q([Bu("update"),Qo((i,t)=>i.disableRandomCall?null:i.getAlias()+i.getGroup(t)),je({replaceArg:i=>({argIndex:0,value:i.getName()}),getKVReportKey:i=>Xp[i.getName()]})],Se.prototype,"updatePlugin",1),q([Bu("stop"),ro((i,t)=>{if(i.disableRandomCall)return null;let e=i.getGroup(t),r=i.getAlias();return e==="*"?new RegExp(`${r}.*`):r+e}),je({replaceArg:i=>({argIndex:0,value:i.getName()}),getKVReportKey:i=>Qp[i.getName()]})],Se.prototype,"stopPlugin",1),q([rf(...Tt.TRTC.enableAudioVolumeEvaluation)],Se.prototype,"enableAudioVolumeEvaluation",1),q([je()],Se.prototype,"getVideoSnapshot",1),q([je()],Se.prototype,"_setCurrentSpeaker",1),q([to(i=>`a${i.userId}`,()=>!0)],Se.prototype,"_startRemoteAudio",1),q([Ce(i=>function(t){return v(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(me(J({},t),{userId:e.userId})).catch(()=>{}))):i.call(this,t)})}),ro(i=>`a${i.userId}`)],Se.prototype,"_stopRemoteAudio",1),q([ro("room")],Se.prototype,"_exitRoom",1),q([ro("screen")],Se.prototype,"_stopScreenShare",1),q([Nt(...Tt.TRTC.sendSEIMessage),Qh({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...i)=>i[0].byteLength})],Se.prototype,"sendSEIMessage",1),q([Nt(Tt.TRTC.sendCustomMessage),Qh({timesInSecond:30,maxSizeInSecond:8e3,getSize:i=>i.data.byteLength})],Se.prototype,"sendCustomMessage",1),q([Nt(Tt.TRTC.create)],Se,"_create",1);var mn=Se;var ju=class{constructor(t,e){this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new Vo(t,this),this.remoteVideoTrack=new Yi(t,this),this.remoteAuxiliaryTrack=new Iu(t,this),this.flag=e.flag||0}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return ia(this.flag,this.userId)}get flag(){return this._flag}set flag(t){if(t===this._flag)return;let e,r=this.muteState;this._flag=t;let o=this.muteState;for(e in o)r[e]!=o[e]&&console.log(this.userId,e,r[e],"->",o[e]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}};var ff=class{constructor(){this._set=new Set;B.on(O.LEAVE_SUCCESS,this.delete,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,o){return`${r}_${e}_${t}_${o}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:o}){return o.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,o.useStringRoomId))}};function rA(){return v(this,null,function*(){let i,t;try{let y=yield zt();i=y&&y.length}catch(y){}try{let y=yield sr();t=y&&y.length}catch(y){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:a}=this.checkSystemResult.detail,d=Gi.basis(),h={webRTC:d.isWebRTCSupported,getUserMedia:d.isGetUserMediaSupported,webSocket:d.isWebSocketsSupported,screenShare:d.isScreenShareSupported,webAudio:d.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:a},p={browser:d.browser,os:d.os,trtc:h,devices:e},T={isWebCodecSupported:d.isWebCodecSupported,isMediaSessionSupported:d.isMediaSessionSupported,isWebTransportSupported:d.isWebTransportSupported};Le.uploadEvent({log:`trtcstats-${JSON.stringify(p)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(p)}`),Le.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(T)}`,userId:this.userId})})}function yE(){return Ce(i=>{let t=new ff;return function(e,r,o){return v(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new de({code:Y.INVALID_OPERATION,message:ot({key:it.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new de({code:Y.INVALID_OPERATION,message:ot({key:it.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),B.emit(O.JOIN_START,{room:this,roomId:s,params:e});let a=Gr.getEnv();a||(a=pi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Zc.OLD_CLOUD_LADDER)?a=pi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Zc.WEBRTC)&&(a=pi.WEBRTC))),Le.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Gi.checkSystemRequirementsInternal().then(d=>{this.checkSystemResult=d,rA.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Gr.getEnv()&&(yield this.schedule(e,o));let d=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Gr.performanceNow(),B.emit(O.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&Le.uploadEvent({log:`stat-conv-${Number(wr)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw t.delete({room:this,roomId:s}),B.emit(O.JOIN_FAILED,{room:this,error:d}),d}})}})}var AE=()=>Ce(i=>function(...t){return v(this,null,function*(){B.emit(O.LEAVE_START,{room:this}),yield i.call(this),B.emit(O.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function bE(){return Ce(i=>function(...t){return v(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="capture"),!t.length))return;B.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function vE(){return Ce(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function RE(){return Ce(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function iA({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return Li(r)?r.catch(o=>V.error(`${i.name}() error observed ${o}`)):r}catch(r){V.error(`${i.name}() error observed ${r}`)}}}var qu=class{constructor(t){l(this,"_frameWorkType");l(this,"_component");l(this,"_language");l(this,"connectionType");l(this,"_room");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});l(this,"_keyPrefix");l(this,"_log");l(this,"_intervalId");l(this,"_firstPublishedUserList");l(this,"_networkQuality");l(this,"_basicInfo");l(this,"_pathJoinRoom");l(this,"_pathLeaveRoom");l(this,"_pathMainVideoMap");l(this,"_pathMainAudioMap");l(this,"_pathAuxiliaryMap");l(this,"_remoteStreamStatMap");l(this,"_localStreamStat");l(this,"_eventMap",new Map);l(this,"_captureCostSum",0);l(this,"_captureCostCount",0);l(this,"isDestroyed",!1);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=V.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Ve(this[e])&&(this[e]=iA({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Ke,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Ea().then(t=>{this._basicInfo.string_os_version=vo(),t?this._basicInfo.string_device_name=t.mobile?t.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),B.on(t,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(O.JOIN_START,this.handleJoinStart).addEvent(O.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(O.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(O.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(O.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(O.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(O.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(O.JOIN_FAILED,this.handleJoinFailed).addEvent(O.LEAVE_START,this.handleLeaveStart).addEvent(O.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(O.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(O.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(O.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(O.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(O.PUBLISH_START,this.handlePublishStart).addEvent(O.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(O.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(O.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(O.PLAY_TRACK_START,this.handlePlayStart).addEvent(O.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(O.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===D.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(O.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(O.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(O.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(O.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let o=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,a=r.hasAudio||r.hasVideo||r.hasSmall,d=r.hasAuxiliary;!o&&a&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&d&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(O.SINGLE_CONNECTION_STAT,({room:t,stat:e})=>{this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((t,e)=>B.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Et.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(t){this.hitTest(t.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),t.params&&(L(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),L(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),L(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:t,detailCost:e}){if(this.hitTest(t)&&e){let{totalCost:r,local:o,dns:s,tcp:a,tls:d,request:h,response:p}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=a,this._pathJoinRoom.int32_schedule_tls=d,this._pathJoinRoom.int32_schedule_request=h,this._pathJoinRoom.int32_schedule_response=p}}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof de?Number(e.getExtraCode()||e.getCode()):Y.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){!this.hitTest(t)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:me(J({},oA),{msg_user_info:new ec({userId:t,tinyId:(o=this._room.remotePublishedUserMap.get(t))==null?void 0:o.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:o}){if(!this.hitTest(t))return;let{userId:s,tinyId:a,role:d}=e,h=new ec({userId:s,tinyId:a,role:d==="anchor"?20:21}),p=Date.now(),T=`${s}_${r}`,y=this._remoteStreamStatMap.get(T);y&&y.subscribeStartTime===0&&(y.subscribeStartTime=p),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(T)&&this._pathMainVideoMap.set(T,{statsToReport:{msg_user_info:h,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:p}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(T)&&this._pathMainAudioMap.set(T,{statsToReport:{msg_user_info:h,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:p})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(T)&&this._pathAuxiliaryMap.set(T,{sendSubscribeCMDTime:p})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(o&&(o.statsToReport.uint64_render_first_frame_time===0&&(o.statsToReport.uint64_render_first_frame_time=r),s)){let{statsToReport:d,playStreamTime:h,subscribedTime:p}=s;d.uint32_video_render_first===0&&h-p<=100&&(d.uint32_video_render_first=r-o.sendSubscribeCMDTime)}let a=this._pathAuxiliaryMap.get(e);if(a&&s){let{statsToReport:d,playStreamTime:h,subscribedTime:p}=s;d.uint32_video_render_first===0&&h-p<=100&&(d.uint32_video_render_first=r-a.sendSubscribeCMDTime)}}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:o,videoDelay:s,audioDelay:a})=>{let d=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(d)d.totalRTT+=e,d.totalLoss+=r,s&&(d.totalVideoDelay=(d.totalVideoDelay||0)+s,d.videoDelayCount=(d.videoDelayCount||0)+1),a&&(d.totalAudioDelay=(d.totalAudioDelay||0)+a,d.audioDelayCount=(d.audioDelayCount||0)+1),d.count++;else{let h,p,T,y;s&&(p=s,T=1),a&&(h=a,y=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:h,totalVideoDelay:p,audioDelayCount:y,videoDelayCount:T})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_device_info:e,msg_up_stream_info:r,msg_down_stream_info:o}=t.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:a,uint32_video_width:d,uint32_video_height:h}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=h,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/Ii*100)>0&&(this._localStreamStat.totalAudioLevel+=s/Ii,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:a,msg_audio_status:d,msg_video_status:h}=s,p=a.str_identifier,T=this._room.remotePublishedUserMap.get(p);if(h.forEach(y=>{let R=y.uint32_video_stream_type===2,N=y.uint32_video_stream_type===7,j=`${p}_${R?"main":"auxiliary"}`,W=this._remoteStreamStatMap.get(j);if(!!W&&(R&&(T==null?void 0:T.remoteVideoTrack.isSubscribed)||N&&(T==null?void 0:T.remoteAuxiliaryTrack))){W.totalVideoFPS+=y.uint32_video_receive_fps,W.totalVideoBitrate+=y.uint32_video_codec_bitrate,W.videoCount++,W.statsToReport.uint32_video_width===0&&(W.statsToReport.uint32_video_width=y.uint32_video_width),W.statsToReport.uint32_video_height===0&&(W.statsToReport.uint32_video_height=y.uint32_video_height);let F=R?T.remoteVideoTrack:T.remoteAuxiliaryTrack;F.stat.jitterBufferDelay&&(W.videoJitterBufferDelay=F.stat.jitterBufferDelay),F.stat.framesReceived&&(W.statsToReport.uint32_video_consume_render_rate=Math.floor(F.stat.framesDecoded/F.stat.framesReceived*Gn(10,6)))}}),d){let y=`${p}_${"main"}`,R=this._remoteStreamStatMap.get(y);this._remoteStreamStatMap.has(y)&&R&&(T==null?void 0:T.remoteAudioTrack.isSubscribed)&&(R.totalAudioBitrate+=d.uint32_audio_codec_bitrate,R.audioCount++,T.remoteAudioTrack.stat.jitterBufferDelay&&(R.audioJitterBufferDelay=T.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/Ii*100)>0&&(R.totalAudioLevel+=d.uint32_audio_level/Ii,R.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof de?e.getExtraCode()||e.getCode():Y.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=o,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=o,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&_s)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&gs)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Xn)>=0}hitTest(t){return t===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o){let{totalLoss:T,count:y,audioDelayCount:R,videoDelayCount:N,totalAudioDelay:j,totalVideoDelay:W}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(T/y),R&&j&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(j/R),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),N&&W&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(W/N))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,D.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,D.VIDEO)),t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,es);let{badCaseDetector:a}=this._room,{dataFreeze:d,count:h}=a.getDataFreezeDuration(e),{renderFreeze:p}=a.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=h,t.statsToReport.uint32_video_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(p,t.statsToReport.uint32_video_play_time),a.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0,(t.subscribeStartTime===0||t.subscribeStartTime-t.streamAddedTime>100||t.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),t.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>es&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+es)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>es&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+es)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>es&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+es)}getReportData(){this._basicInfo.uint32_networkType=id();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new ec({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ss(this._signalInfo.relayIp),uint32_client_ip:Ss(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Gn(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Ss(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return oa(t),t}report(){return v(this,null,function*(){try{this.prepareReport();let t=this.getReportData();yield this.upload(t),this.initData()}catch(t){this._log.warn(t)}finally{this.isDestroyed&&(this._room=null)}})}upload(t){return v(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield mp(t),o=r instanceof ArrayBuffer,s=`${fi(e,ki.KEY_POINT)}&gzip=${+o}`,a=!1;navigator.sendBeacon&&(a=navigator.sendBeacon(s,r));let d=[this.uploadKVStat(X),this.uploadKVStat(xo)];a||d.push(_i({url:s,body:r,priority:"low"})),yield Promise.all(d)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return v(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=me(J({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let r=yield mp(e),o=`${fi(+this._room.sdkAppId,ki.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||_i({url:o,body:r})})}};q([ji({settings:{timeout:500,retries:3}})],qu.prototype,"upload",1);var es=5e3,oA={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},ec=class{constructor(t){l(this,"str_identifier");l(this,"str_tinyid");l(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},CE=qu;var _f=class{constructor(){l(this,"_startTime");l(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=ge())}stop(){this._endTime===0&&(this._endTime=ge())}getDuration(){return this._endTime===0?ge()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},hn=_f;var gf=class{constructor(t){l(this,"_room",null);l(this,"_durationMap");l(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(O.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(O.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(O.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var a;let{userId:o}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${o}_${"main"}`,D.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_${"main"}`,D.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_${"auxiliary"}`,D.VIDEO);let s=(a=this._room)==null?void 0:a.remotePublishedUserMap.get(o);!s||(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,D.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>B.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>B.off(e,t,this)),this._eventMap.clear()}handleSubscribed({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;if(r.muteState.hasAudio&&e==="main")if(r.remoteAudioTrack.isSubscribed){let a=new hn,d=this._durationMap.get(s);d?this.isRecording(d.audio)||d.audio.push(a):this._durationMap.set(s,{userId:o,type:e,audio:[a],video:[]})}else this.stopDurationItem(s,D.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let a=new hn,d=this._durationMap.get(s);d?this.isRecording(d.video)||d.video.push(a):this._durationMap.set(s,{userId:o,type:e,audio:[],video:[a]})}else this.stopDurationItem(s,D.VIDEO)}handleStreamStopped({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDurationItem(s,D.AUDIO),this.stopDurationItem(s,D.VIDEO)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,r){let o=`${t}_${r}`,s=new hn,a=this._durationMap.get(o);a?this.isRecording(a[e])||a[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===D.AUDIO?[s]:[],video:e===D.AUDIO?[]:[s]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let o=this._durationMap.get(t)[e].find(s=>s.endTime===0);o&&o.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((o,s)=>o+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},DE=gf;var Ef=class{constructor(t){l(this,"_room");l(this,"_renderFreezeMap",new Map);l(this,"_isVideoPlayingEventFiredMap",new Map);l(this,"_dataFreezeMap",new Map);l(this,"_monitorFreezeData",new Map);l(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}installEvents(){this._eventMap.set(O.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(O.PLAY_TRACK_START,this.onPlayTrackStart).set(O.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:r})=>{if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDataFreeze({key:s,userId:o,type:e})}).set(O.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let{userId:o}=r;if(e.hasVideo&&!r.hasVideo){let s="main",a=`${r.userId}_${s}`;this.stopDataFreeze({key:a,userId:o,type:s})}if(e.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",a=`${r.userId}_${s}`;this.stopDataFreeze({key:a,userId:o,type:s})}}).set(O.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!this.hitTest(t.room)||o!==D.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===D.MUTE?this.onVideoTrackMuted(t):r===D.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(O.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>B.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>B.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`,s=this._dataFreezeMap.get(o),a=new hn;s?s.durationItemList.push(a):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[a],isFreezing(){let d=this.durationItemList[this.durationItemList.length-1];return d&&d.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){!this.hitTest(t)||e.msg_down_stream_info.forEach(r=>{let o=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!o)return;let{userId:s,muteState:a}=o;r.msg_video_status.forEach(d=>{d.uint32_video_stream_type===2&&a.hasVideo&&!a.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"main"}),d.uint32_video_stream_type===7&&a.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let a=s.getDuration();a>td?this._monitorFreezeData.set(t,{userId:e,type:r,duration:a}):o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}handleRenderFreeze(o){return v(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,a=this._renderFreezeMap.get(s);if(e<=2){let d=ge();a&&!a.isFreeze&&(a.freezeTimeline.push({startTime:d,endTime:0}),a.isFreeze=!0),a||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:d,endTime:0}],renderFreezeTotal:0})}else if(a&&a.isFreeze){a.isFreeze=!1;let d=a.freezeTimeline.pop();if(d){d.endTime=ge();let h=d.endTime-d.startTime;a.freezeTimeline.push(d),a.renderFreezeTotal+=Math.min(5e3,h)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==D.VIDEO||t.hasFlag)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},r=this._dataFreezeMap.get(t);if(r){if(r.isFreezing()){let o=r.durationItemList[r.durationItemList.length-1];o.stop(),o.getDuration()<td&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,o=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=ge(),a=e.freezeTimeline[e.freezeTimeline.length-1],d=s-a.startTime;r=e.renderFreezeTotal+Math.min(d,5e3),o=e.freezeTimeline.length}return{renderFreeze:r,count:o}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},NE=Ef;var xE=Pi(Hi(),1);var sA=[1,0,0,0,1,1,0,1],zu=class extends Vt{constructor(t,e){if(super(t,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),t instanceof st)try{this.setTexBuffer(sA)}catch(r){t.destroy(new de({code:Y.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}draw2d(t,e,r,o,s){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let a=super.draw2d(t,e,r,o,s);return this.ctx2d.restore(),a}return!1}render(t){var e;return(e=this.input)!=null&&e.requestFrame(t)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Tf=class{constructor(t,e){this.node=t;this.layout=e;l(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},Ju=class extends Vt{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:r});l(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new Tf(e,r);this.inputs[r.zIndex]=o}resize(e,r){let o=this.inputs.reduce((s,a)=>a?Object.assign(s,{width:Math.max(s.width,a.right),height:Math.max(s.height,a.bottom)}):s,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof st&&this.inputs.forEach(s=>{if(s){let a=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,a):s.positionBuffer=this.createBuffer(a)}})}connect(e,...r){return super.connect(e,...r),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(r=>(r==null?void 0:r.node)===e)]=void 0}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),!this.inputs.reduce((s,a)=>(!a||!a.node.requestFrame(e))&&s,!0)&&r){this.useProgram(),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let a=this.inputs[s];a&&(a.node.useTexture(),this.draw(a.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((o,s)=>(!s||!s.node.requestFrame(e))&&o,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let o=0;o<this.inputs.length;o++){let s=this.inputs[o];s&&this.draw2d(s.node.image,s.x,s.y,s.width,s.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:a,name:d}=this,h=Date.now(),p=(e-this.lastInfo.totalFrames)/((h-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:a,timestamp:h,fps:p,name:d},J({parent:this.inputs.filter(T=>T).map(T=>T.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var r,o;if(e&&((r=e.node)==null||r.disconnect(),e.positionBuffer&&this.context instanceof st))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var nA=`#version 300 es
|
|
99
99
|
in vec2 a_position;
|
|
100
100
|
in vec2 a_texCoord;
|
|
101
101
|
out vec2 v_texCoord;
|
|
@@ -136,4 +136,4 @@ void main() {
|
|
|
136
136
|
void main() {
|
|
137
137
|
gl_Position = vertexPos;
|
|
138
138
|
textureCoord = texturePos;
|
|
139
|
-
}`});l(this,"yTextureRef");l(this,"uTextureRef");l(this,"vTextureRef");l(this,"Y");l(this,"U");l(this,"V");this.useProgram();let r=this.context.ctx;r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,r){let o=this.context.ctx,s=o.createTexture();return o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),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.bindTexture(o.TEXTURE_2D,null),o.uniform1i(o.getUniformLocation(this.program,e),r),s}render(e){let r=this.context.ctx,o=this.width,s=this.height;return this.useProgram(),r.viewport(0,0,o,s),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o,s,r.LUMINANCE,r.UNSIGNED_BYTE,this.Y),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.U),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,r){super.resize(e,r);let o=this.context.ctx;o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,this.yTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e,r,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE1),o.bindTexture(o.TEXTURE_2D,this.uTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this.vTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}};var If=[i=>{i.codec="avc1.420028"},i=>{delete i.hardwareAcceleration}],wE=(i,t)=>{switch(i){case"webCodecs":return t==="videoFrame"?514705:514706;case"wasm":return t==="webgl"?514707:t==="videoFrame"?514708:514709}throw new Error("decoder type not supported")},Yu=class{constructor(t){l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"decoder");l(this,"videoContext");l(this,"gop",0);l(this,"gop_helper",0);l(this,"waitFirstKeyFrame",!0);l(this,"startTimestamp",0);l(this,"startTime",0);l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"downgradeLevel",0);l(this,"config");l(this,"videoElement");l(this,"type","wasm");l(this,"renderer","2d");l(this,"wasmOption");l(this,"createDecoder");l(this,"_decodeSink");let{track:e,createDecoder:r}=t;if(this.createDecoder=r,this.wasmOption={yuvMode:t.renderer==="webgl",wasmPath:t.wasmPath,workerMode:t.workerMode,canvas:t.canvas},this.config=t.config,this.videoElement=t.videoElement,this.renderer=t.renderer,this.trackDoneOB=Je(e,Z.INIT),this.stopOB=Jt(this.trackDoneOB),t.type==="auto"){switch(t.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=t.type;this.changeRenderer(this.renderer),this.startOB=Jt();let o=Jt(),s;We(o,th((d,h)=>(d!==h&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:s,prevState:d,state:h}),h),"INITIALIZED"),gt(this.stopOB),dt());let a=d=>{let h=this.pipe(e);return o.next("STARTING"),e.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`),We(h,gt(this.stopOB),dt(()=>{e.stat.framesDecoded++},p=>{if(e.log.error(p),X.addFailedEvent({key:wE(this.type,this.renderer),error:p}),d>4)this.startOB.error(p);else{switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.startOB.next(d+1)}})),We(h,xr(1),ja(Ho))};We(this.startOB,$o(0),Qi(a),gt(this.stopOB),dt(()=>{e.player.handlePlaying("canvas"),o.next("STARTED")},d=>{s=d,o.next("FAILED")},()=>{X.addSuccessEvent({key:wE(this.type,this.renderer)}),X.addSuccessEvent({key:514704})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}changeRenderer(t){this.renderer=t,this.renderer==="videoFrame"&&!em()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t){var s;if(this.inputFrameCount++,((s=this.decoder)==null?void 0:s.state)!=="configured")return t;let e=new Uint8Array(t.data)[4]&31,r=!1;switch(e){case 5:case 7:r=!0;break}let{timestamp:o}=t;if(r?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(r)this.waitFirstKeyFrame=!1,this.startTimestamp=o,this.startTime=Date.now();else return;let a=(o-this.startTimestamp)/90,h=Date.now()-this.startTime-a,p=h<500?0:h/1e3>>0;switch(r&&(p>0?this.downgradeLevel++:this.downgradeLevel>3&&this.downgradeLevel--),this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}this.decoder.decode(t);return}return t}pipe(t){return Ri()(e=>v(this,null,function*(){this._decodeSink=e,e.defer(()=>{var s,a;(s=this.decoder)==null||s.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:r,type:o}=this;try{switch(o){case"wasm":this.decoder=this.createDecoder(o,this.wasmOption);break;case"webCodecs":for(let s=0;s<=If.length;s++){let{supported:a}=yield VideoDecoder.isConfigSupported(this.config);if(a)break;if(s===If.length){e.error(3);return}If[s](this.config)}this.decoder=this.createDecoder(o);break;case"mse":throw new Error("not supported yet")}if(this.decoder.on("videoFrame",s=>{this.decodedFrameCount++,e.next(s)}),this.decoder.on("error",s=>{t.log.error(s),e.error(o==="webCodecs"?4:8)}),yield this.decoder.initialize(this.videoElement),this.decoder.configure(this.config),o==="wasm"&&r==="webgl"){this.videoContext=new st({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(st.UNAVAILABLE,a=>{t.log.error(a),e.error(7)});let s=new Qu(this.videoContext);this.decoder.on("videoCodecInfo",a=>s.resize(a.width,a.height)),this.decoder.on("videoFrame",a=>{[s.Y,s.U,s.V]=a,this.downgradeLevel===1?this.decodedFrameCount%2===0&&s.render(this.decodedFrameCount):s.render(this.decodedFrameCount)}),t.source=s,t.player.setCanvas(this.videoContext._canvas,2)}else if(r==="videoFrame"){t.player.setCanvas();let s=new MediaStreamTrackGenerator({kind:"video"}),a=s.writable.getWriter();t.setInputMediaStreamTrack(s),this.decoder.on("videoFrame",d=>{a.write(d)}),s.onmute=()=>{e.error(o==="webCodecs"?5:9)},e.defer(()=>s.onmute=null)}else{this.videoContext=new Ct({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let s=this.videoContext.createVideoImageSource();this.decoder.on("videoFrame",d=>{s.image=d,s.update()});let a=new jo(this.videoContext,{name:"remotePlayer",logger:t.log});s.connect(a),t.source=s,t.player.setCanvas(this.videoContext._canvas,2)}}catch(s){t.log.error(s),e.error(o==="webCodecs"?2:6)}}))}};var Zu=class extends xE.EventEmitter{constructor(e){super();this.room=e;l(this,"videoContext");l(this,"_glVideoContext");l(this,"_2dVideoContext");l(this,"destination");l(this,"smallVideoContext");l(this,"smallDestination");l(this,"smallTrackSource");l(this,"smallImageSource");l(this,"_isMirror",!1);l(this,"cameraTrack");l(this,"cameraNode");l(this,"mirrorNode");l(this,"mixNode");l(this,"screenTrack");l(this,"screenNode");l(this,"selfModel",!1);l(this,"blurRadius",3);l(this,"arTrack");l(this,"Wasm");l(this,"waterMarkNode");l(this,"_waterMarkOption");l(this,"watermarkImageList",[]);l(this,"_beautyParams");l(this,"isUsingArTrack",!1);l(this,"_isMixScreen",!1);l(this,"_virtualBackground");l(this,"_virtualBackgroundAbortCallback");l(this,"virtualBackgroundInstance");l(this,"_bgAssetPath");l(this,"log",V.createLogger({id:"vm"}));l(this,"_checkId",0);l(this,"_use2d",!1);l(this,"_autoSwitchRenderMode",!0);l(this,"_selfieSegmentation");l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Ct({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let r=e==="2d";this._use2d!==r&&(this._use2d=r,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Ct({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new st({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("unavailable",e=>{var r;this.emit("error",e),this.log.warn("video context unavailable",e),(r=this._virtualBackgroundAbortCallback)==null||r.call(this,e),this.update()})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=Et.run(To,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,r;(e=this._2dVideoContext)==null||e.destroy(),(r=this._glVideoContext)==null||r.destroy(),this.smallVideoContext.destroy(),Et.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Bi||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?X.addFailedEvent({key:o,error:r}):X.addSuccessEvent({key:o})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let r=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(r)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new st({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,settings:a,player:d}=o;s?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Tu(this.smallVideoContext,s,this.log)),this.smallVideoContext.frameRate=s.frameRate,this.smallDestination.resolution=s,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=a.width,this.smallTrackSource.height=a.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Bi&&d.setCanvas(e);let h=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),h=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${h?h.label:"no output track"}`),o.setOutputMediaStreamTrack(h)}catch(o){this.log.error("set main output failed",o)}}update(){return v(this,null,function*(){var o,s;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),ir===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Ci?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Ci?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(e.width,e.height)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new Eu(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new Xu(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let a=this.cameraNode;a.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new zu(this.videoContext,this.log)),a=a.connect(this.mirrorNode),a.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new Ju(this.videoContext,this.log),a.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(o=this.waterMarkNode)==null||o.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(s=this.screenNode)==null||s.connect(this.mixNode,{zIndex:0}),a=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),a.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var r,o,s,a;if(e instanceof Ji)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof hr)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof Yi){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let d=e.mediaTrack;return e.setOutputMediaStreamTrack(d)}this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var r;e instanceof Ji?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof hr?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Yi&&e.source&&e.source.context.destroy()}setCameraTrack(e){return v(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,r){return v(this,null,function*(){let o=document.createElement("canvas");r&&e&&(o.height=r,o.width=e);let s=o.getContext("2d");if(!s)throw new de({code:Y.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((a,d)=>a.zIndex-d.zIndex),this.watermarkImageList.forEach(({image:a,x:d,y:h,width:p,height:T})=>{s.drawImage(a,d,h,p,T)}),As(o.toDataURL())})}pushWaterMarkImageList(e){let{type:r}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex)||((r==="mute"||r==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==r)),this.watermarkImageList.push(e))}setBeautyParams(e){return v(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return v(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return v(this,null,function*(){var y,R;let r;try{r=yield As((e==null?void 0:e.imageElement)||e.imageUrl)}catch(N){throw new de({code:Y.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:a=r.width,height:d=r.height,type:h="watermark",zIndex:p=2}=e;this.watermarkImageList.some(N=>N.type===h)?(this.watermarkImageList=this.watermarkImageList.filter(N=>N.type!==h),this.pushWaterMarkImageList({x:o,y:s,width:a,height:d,image:r,zIndex:p,type:h,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage((y=this.cameraTrack)==null?void 0:y.settings.width,(R=this.cameraTrack)==null?void 0:R.settings.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:o,y:s,width:a,height:d,image:r,zIndex:p,type:h,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(N,j)=>N==="imageUrl"?void 0:j))})}deleteWatermark(e="watermark"){return v(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(r=>r.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(r,o)=>r==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return v(this,null,function*(){var r,o,s;(r=this.waterMarkNode)==null||r.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((o=this.cameraTrack)==null?void 0:o.settings.width,(s=this.cameraTrack)==null?void 0:s.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return v(this,null,function*(){if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield As(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new de({code:Y.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var r;this._isMixScreen=e,this._isMixScreen||((r=this.screenNode)==null||r.close(),delete this.screenNode),this.update()}set mirror(e){var r;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((r=this.mirrorNode)==null||r.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return v(this,null,function*(){var e;!((e=this.cameraTrack)!=null&&e.mediaTrack)||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new Yu(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};var cA=0;var Ku=class extends Z{constructor(e){super("room");this.seq=++cA;this.role="anchor";this.joinParams=null;this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.checkSystemResult={result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}};this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this._isUsingCachedSchedule=!1;this._log=V.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this.isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,nt(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),nt(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),nt(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new CE({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new DE({room:this}),this.badCaseDetector=new NE({room:this}),this.audioManager=new ru(this),this.videoManager=new Zu(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return v(this,null,function*(){return this.publish(e)})}removeTrack(e){return v(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return v(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Ae(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if($t(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:a,unifiedProxy:d}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=d,d?(ku([d,d]),_o(`https://${d}`)):(s&&_o(s),a&&ku(a))}B.once(O.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Pr.main,sched_back_domain:Pr.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return v(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return v(this,null,function*(){var r;let e={rtt:((r=this.quality)==null?void 0:r.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)e.downlinksRTT[o.userId]=o.rtt;return e})}getRemoteVideoStats(){return v(this,arguments,function*(e="main"){let r={};return this.remotePublishedUserMap.forEach(o=>{let s=e==="auxiliary"?o.remoteAuxiliaryTrack:o.remoteVideoTrack;r[o.userId]=s.stat}),r})}checkDestroy(){if(this.isDestroyed)throw new de({code:Y.INVALID_OPERATION,message:ot({key:it.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(jt.INVALID_DESTROY),new de({code:Y.INVALID_OPERATION,message:ot({key:it.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,B.emit(O.ROOM_DESTROY,{room:this})}schedule(e,r){return v(this,null,function*(){var s,a,d;let o=ge();try{let{isCached:h,result:p,detailCost:T}=yield ef({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Ke,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=h,this._log.info(`schedule cache:${+h} ${pr(p,{keysToExclude:["username","credential"]})}`),h&&B.once(O.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=J(J({},this.scheduleResult),p),Fe((s=p.config)==null?void 0:s.retryCount)&&sp(p.config.retryCount),Ae((a=p.config)==null?void 0:a.loggerDomain)&&_o(p.config.loggerDomain),this.videoDecodeFallbackType=((d=p.config)==null?void 0:d.videoDecodeFallback)||this.videoDecodeFallbackType,B.emit(O.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:T}),X.addSuccessEvent({key:521700,cost:ge()-o,split:50})}catch(h){throw X.addFailedEvent({key:521700,error:h}),h}})}sendAbilityStatus(e){}enableInsertableStreams(){}};var Sf=(()=>{if(typeof self=="undefined")return!1;if("top"in self&&self!==top)try{}catch(i){return!1}else if("showOpenFilePicker"in self)return"showOpenFilePicker";return!1})(),vB=Sf?Promise.resolve().then(function(){return pA}):Promise.resolve().then(function(){return EA});var RB=Sf?Promise.resolve().then(function(){return hA}):Promise.resolve().then(function(){return IA});var dA=Sf?Promise.resolve().then(function(){return _A}):Promise.resolve().then(function(){return yA});function yf(...i){return v(this,null,function*(){return(yield dA).default(...i)})}var uA=i=>v(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),lA=(...t)=>v(void 0,[...t],function*(i=[{}]){Array.isArray(i)||(i=[i]);let e=[];i.forEach((s,a)=>{e[a]={description:s.description||"Files",accept:{}},s.mimeTypes?s.mimeTypes.map(d=>{e[a].accept[d]=s.extensions||[]}):e[a].accept["*/*"]=s.extensions||[]});let r=yield window.showOpenFilePicker({id:i[0].id,startIn:i[0].startIn,types:e,multiple:i[0].multiple||!1,excludeAcceptAllOption:i[0].excludeAcceptAllOption||!1}),o=yield Promise.all(r.map(uA));return i[0].multiple?o:o[0]}),pA={__proto__:null,default:lA};function el(i){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var r=e.done;return Promise.resolve(e.value).then(function(o){return{value:o,done:r}})}return el=function(e){this.s=e,this.n=e.next},el.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return r===void 0?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return r===void 0?Promise.reject(e):t(r.apply(this.s,arguments))}},new el(i)}var ME=(o,s,...a)=>v(void 0,[o,s,...a],function*(i,t,e=i.name,r){let d=[],h=[];var p,T=!1,y=!1;try{for(var R,N=function(j){var W,F,Ie,Bt=2;for(typeof Symbol!="undefined"&&(F=Symbol.asyncIterator,Ie=Symbol.iterator);Bt--;){if(F&&(W=j[F])!=null)return W.call(j);if(Ie&&(W=j[Ie])!=null)return new el(W.call(j));F="@@asyncIterator",Ie="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());T=!(R=yield N.next()).done;T=!1){let j=R.value,W=`${e}/${j.name}`;j.kind==="file"?h.push(j.getFile().then(F=>(F.directoryHandle=i,F.handle=j,Object.defineProperty(F,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>W})))):j.kind!=="directory"||!t||r&&r(j)||d.push(ME(j,t,W,r))}}catch(j){y=!0,p=j}finally{try{T&&N.return!=null&&(yield N.return())}finally{if(y)throw p}}return[...(yield Promise.all(d)).flat(),...yield Promise.all(h)]}),mA=(...t)=>v(void 0,[...t],function*(i={}){i.recursive=i.recursive||!1,i.mode=i.mode||"read";let e=yield window.showDirectoryPicker({id:i.id,startIn:i.startIn,mode:i.mode});return ME(e,i.recursive,void 0,i.skipDirectory)}),hA={__proto__:null,default:mA},fA=(s,...a)=>v(void 0,[s,...a],function*(i,t=[{}],e=null,r=!1,o=null){Array.isArray(t)||(t=[t]),t[0].fileName=t[0].fileName||"Untitled";let d=[],h=null;if(i instanceof Blob&&i.type?h=i.type:i.headers&&i.headers.get("content-type")&&(h=i.headers.get("content-type")),t.forEach((y,R)=>{d[R]={description:y.description||"Files",accept:{}},y.mimeTypes?(R===0&&h&&y.mimeTypes.push(h),y.mimeTypes.map(N=>{d[R].accept[N]=y.extensions||[]})):h?d[R].accept[h]=y.extensions||[]:d[R].accept["*/*"]=y.extensions||[]}),e)try{yield e.getFile()}catch(y){if(e=null,r)throw y}let p=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:d,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(p);let T=yield p.createWritable();return"stream"in i?(yield i.stream().pipeTo(T),p):"body"in i?(yield i.body.pipeTo(T),p):(yield T.write(yield i),yield T.close(),p)}),_A={__proto__:null,default:fA},gA=(...t)=>v(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),new Promise((e,r)=>{let o=document.createElement("input");o.type="file";let s=[...i.map(p=>p.mimeTypes||[]),...i.map(p=>p.extensions||[])].join();o.multiple=i[0].multiple||!1,o.accept=s||"",o.style.display="none",document.body.append(o);let a=p=>{typeof d=="function"&&d(),e(p)},d=i[0].legacySetup&&i[0].legacySetup(a,()=>d(r),o),h=()=>{window.removeEventListener("focus",h),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",h)}),o.addEventListener("change",()=>{window.removeEventListener("focus",h),o.remove(),a(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),EA={__proto__:null,default:gA},TA=(...t)=>v(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),i[0].recursive=i[0].recursive||!1,new Promise((e,r)=>{let o=document.createElement("input");o.type="file",o.webkitdirectory=!0;let s=d=>{typeof a=="function"&&a(),e(d)},a=i[0].legacySetup&&i[0].legacySetup(s,()=>a(r),o);o.addEventListener("change",()=>{let d=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(d=d.filter(h=>h.webkitRelativePath.split("/").every(p=>!i[0].skipDirectory({name:p,kind:"directory"})))):d=d.filter(h=>h.webkitRelativePath.split("/").length===2),s(d)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),IA={__proto__:null,default:TA},SA=(e,...r)=>v(void 0,[e,...r],function*(i,t={}){Array.isArray(t)&&(t=t[0]);let o=document.createElement("a"),s=i;"body"in i&&(s=yield function(h,p){return v(this,null,function*(){let T=h.getReader(),y=new ReadableStream({start:j=>function W(){return v(this,null,function*(){return T.read().then(({done:F,value:Ie})=>{if(!F)return j.enqueue(Ie),W();j.close()})})}()}),R=new Response(y),N=yield R.blob();return T.releaseLock(),new Blob([N],{type:p})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let a=()=>{typeof d=="function"&&d()},d=t.legacySetup&&t.legacySetup(a,()=>d(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),a()}),o.click(),null}),yA={__proto__:null,default:SA};var Af=class{constructor(t){this.name=t;l(this,"ready");l(this,"worker");l(this,"ports");l(this,"ids",1);l(this,"transactions",new Map);l(this,"log");l(this,"addTransaction",t=>(this.transactions.set(++this.ids,t),this.ids))}postMessage(t,e){var r;(r=this.worker)==null||r.postMessage(t,e)}create(t){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=new Worker(Zg(),{name:t});return this.worker=e,this.ready=new Promise((r,o)=>{e.onmessage=({data:{id:s,type:a,payload:d}})=>{var h;if(s)(h=this.transactions.get(s))==null||h(d),this.transactions.delete(s);else switch(a){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",d),o(d);break;case"ready":console.timeEnd(`createWorker_${t}`),r(this);break;case"updateAFSM":if(d.value){let p=typeof d.old=="string"?d.old:`${d.old.action}ing`,T=typeof d.value=="string"?d.value:`${d.value.action}ing`;console.log(nd(),d.group,d.name,p,"\u{1F449}",T)}break;case"log":console.log(d);break;case"glog":window.dispatchEvent(new CustomEvent(a,{detail:d}));break}},e.postMessage({wasm:xu,flag:yt},this.ports)})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},bf=class{constructor(t,e,r){this.worker=t;l(this,"channel",new MessageChannel);l(this,"ready");this.ready=new Promise((o,s)=>{this.worker.postMessage({id:this.worker.addTransaction(o),payload:e},[this.channel.port2])}).then(o=>(o.err===0&&(this.worker.sessionCount++,this.channel.port1.onmessage=r),o))}postMessage(...t){this.channel.port1.postMessage(...t)}destroy(){--this.worker.sessionCount===0&&this.worker.destroy()}},tc=class extends Af{constructor(){super("main");l(this,"switchValue",new Map);l(this,"extendChannel");l(this,"sessionCount",0)}setSwitchValue(e,r){var o;this.switchValue.set(e,r),(o=this.extendChannel)==null||o.port1.postMessage([e,r])}create(){return v(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Lt(tc.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},oo=new tc,ts,AA=-1;function OE(i){return console.log(i),ts.push(i.slice()),ts.length>1e3&&ts.shift(),i}function PE(i){return v(this,null,function*(){switch(AA){case 0:this.edpl.willDecodeAudio=OE;break;case 2:this.edpl.didEncodeAudio=OE;break}yield oo.create(),B.emit(O.JOIN_SEND_CMD,{room:this});let t=new bf(oo,i,o=>{let s=o.data;if(typeof s=="string")this.onWorkerEvent(s);else if(s==null)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:a,payload:d}=s;this.onWorkerEvent(a,d)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(B.emit(O.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new de({code:Y.JOIN_ROOM_FAILED,extraCode:Number(e),message:ot({key:it.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:vf},useWt:{set:bA},enableDebug:{set(i){console.debug=i?Qg:()=>{},oo.setSwitchValue("enableDebug",i)}},useV2:{set:Rf},dump:{value(){if(ts||(console.warn("dump audio will be activated at next time join room"),ts=[]),!ts.length){console.warn("no audio data to dump,try it later");return}let i=[];return ts.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),yf(new Blob(i),{fileName:"audio dump hex",extensions:[".hex"]})}},dumpAudio:{value(i="audio",t=2e3){let e=[],r=new Promise(o=>{let s=new MessageChannel;oo.extendChannel.port1.postMessage(["dump",i],[s.port1]),s.port2.onmessage=({data:a})=>{console.log(a),e.push(a),e.length>t&&(s.port2.onmessage=null,oo.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return yf(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:yt.useHardDecoder="prefer-hardware";break;case!1:yt.useHardDecoder="prefer-software";break;default:yt.useHardDecoder="no-preference"}}}});function vf(i){return v(this,null,function*(){oo.setSwitchValue("useAINS",i)})}function Rf(i){return v(this,null,function*(){oo.setSwitchValue("useV2",i)})}function bA(i){return v(this,null,function*(){oo.setSwitchValue("useWt",i)})}function kE(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function LE(i){return v(this,null,function*(){var r;this._log.info("pull video",i);let t=Date.now(),e=new MessageChannel;this.postMessage({cmd:"pullVideo",payload:{mediaType:i.mediaType,tinyId:i.tinyId}},[e.port1]),(r=i.stat).framesReceived||(r.framesReceived=0),Xt(Xg(e.port2),Ki(Qt(i,Z.INIT)),cr(o=>{let{data:s,packetsReceived:a}=o;i.stat.packetsReceived=a,i.stat.framesReceived++;let d=s[4]&31,h;switch(d){case 5:case 7:h="key";break;default:h="delta";break}i.decodeFrame({data:s.buffer,type:h,timestamp:(Date.now()-t)*1e3})},()=>{},()=>{e.port2.postMessage(null),e.port2.close()}))})}var tl=[];function VE(i){var h;let t=en();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let p=0;p<=tl.length;p++)if(!tl[p]){tl[p]=this,this.index=p;break}let e=i.profile;this._log.info("start push audio",this.index,e);let r=new MessageChannel,o=i.enableEncodeFrame?new MessageChannel:null;(h=this.session)==null||h.postMessage({cmd:"pushAudio",payload:J({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=p=>{p.data==null||(typeof p.data=="number"?t.next(p.data):o&&o.port1.postMessage(me(J({},p.data),{data:new Uint8Array(i.encodeFrame({data:p.data.data.buffer,timestamp:p.data.timestamp}).data)})))};let s=new MediaStream,a,d=p=>{let T=s.getAudioTracks()[0];T&&(a.disconnect(),s.removeTrack(T)),s.addTrack(p),this._log.info("push audio track:",p.readyState,p.getSettings().deviceId),a=eo.audioCtx.createMediaStreamSource(s),a.connect(eo.worklet,0,this.index)};Xt(Qt(i,"output-media-track-changed"),Ki(Qt(i,"capture")),cr(d,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,a.disconnect(),tl[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),Xt(t,zg(p=>i.volume=p),qg(gu(1e3)),cr(()=>{i.volume=0})),d(i.outMediaTrack)}var tF=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Cf=class{constructor(t,e,r,o){this.localTrack=t;this.type=e;this.config=r;this.port=o;l(this,"track");l(this,"label");l(this,"insertKeyFrame",!0);l(this,"encoder");l(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){let o=this.recreate(r);e.signal.addEventListener("abort",()=>{o.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(a,d)=>{o.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(a),s++,d.enqueue(a))}}),e)}encode(t){this.encoder.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){let o=this.recreate(r),s=0;t.pipeTo(new WritableStream({write:a=>{o.state==="configured"&&(s<10&&console.log(`capture ${this.label} track frame:`,s,Date.now(),a.timestamp,a.displayWidth,a.displayHeight),(a.displayWidth!==this.config.width||a.displayHeight!==this.config.height)&&(console.log("resize video track frame:",a.displayWidth,a.displayHeight,this.config.width,this.config.height),this.configure({width:a.displayWidth,height:a.displayHeight})),this.tsMap.set(s,Date.now()),this.encode(a),s<10&&console.log(`encode ${this.label} track frame:`,s),s++,a.close())}}),e).catch(a=>{console.warn(a),o.close()})}recreate(t,e=0){let r=0,o=new VideoEncoder({output:s=>{let a=this.tsMap.get(r);if(this.tsMap.delete(s.timestamp),r<10&&(r===0&&e===0&&B.emit(O.SEND_FIRST_VIDEO_FRAME,{room:t}),console.log(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,this.track.enabled===!1)return;let d=null;if(this.localTrack.enableEncodeFrame){d=new Uint8Array(s.byteLength),s.copyTo(d);let h=this.localTrack.encodeFrame({data:d.buffer},this.type===3);d=new Uint8Array(h.data)}d?(this.localTrack.stat.bytesSent+=d.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:d,duration:s.duration},timestamp:a},[d.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:a}))},error:s=>{console.warn(s,this.config),setTimeout(()=>this.recreate(t,e+1),100)}});return this.encoder=o,this.configure({}),o}configure(t){var e;(e=this.encoder)==null||e.configure(Object.assign(this.config,t))}close(){this.port.postMessage(null),this.port.close()}};function rl(i,t){return v(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",avc:{format:"annexb"},hardwareAcceleration:yt.useHardEncoder,width:t.profile.width,height:t.profile.height,framerate:t.profile.frameRate,bitrate:t.profile.bitrate*1e3},s=new MessageChannel;this.postMessage({cmd:"pushVideo",payload:t},[s.port1]);let a=new Cf(i,t.type,o,s.port2);return s.port2.onmessage=d=>{if(d.data===260)a.insertKeyFrame=!0;else if(!e){let{bitrate:h}=d.data;ea({configureBr:[d.data.bitrate,h]}),a.configure({bitrate:h})}},this._log.info("start push",r,t),a})}function BE(i){return v(this,null,function*(){let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera"};!t&&i.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(r.trackType="canvas");let{trackType:o}=r,{width:s,height:a}=i.outMediaTrack.getSettings();r.profile.width=s,r.profile.height=a;let d=yield rl.call(this,i,r);this._log.info("VideoEncoder created",r);let h,p=T=>v(this,null,function*(){if(h==null||h.abort("track changed"),!T)return;h=new AbortController;let{width:y,height:R,displaySurface:N}=T.getSettings();y&&(d.config.width=y),R&&(d.config.height=R);let j=rr.match(/Chrome\/(\d+)/);(j==null?void 0:j[1])==="114"&&N==="browser"&&delete d.config.hardwareAcceleration,this._log.info("push",e,"track:",T.readyState,T.getSettings());let W=new MediaStreamTrackProcessor({track:T}).readable,F="small"in i&&i.small;F?(this.smallEncoder||(this.smallEncoder=yield rl.call(this,i,{profile:F,type:3,trackType:o})),this.smallEncoder.track=T,this.smallEncoder.label="small",W=this.smallEncoder.trans(W,h,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),d.track=T,d.label=e,d.start(W,h,this)});return Xt(Qt(i,"output-media-track-changed"),Ki(Qt(i,"capture")),cr(p,console.error,()=>{var T;this._log.info("stop push",e,r),h.abort("unpublish"),d.close(),(T=this.smallEncoder)==null||T.close()})),p(i.outMediaTrack)})}var ic=class extends Z{constructor(e){var r,o;super((o=(r=e.roomid)==null?void 0:r.toString())!=null?o:e.name,"volumeEvaluation");this.room=e;l(this,"enableInBackground",!1);l(this,"interval",400);e.on("joined",()=>{this.emit(ic.INTERVALCHANGED,this.interval)}),Xt(Qt(this,ic.INTERVALCHANGED),jg(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):Xt(Ug(s),Gg(()=>[]))),cr(s=>{s.forEach(a=>{this.room.remotePublishedUserMap.has(a.userId)&&(this.room.remotePublishedUserMap.get(a.userId).remoteAudioTrack.volume=a.volume)}),(!document.hidden||this.enableInBackground)&&this.state==Z.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(ic.INTERVALCHANGED,this.interval)}stop(){}},rs=ic;l(rs,"INTERVALCHANGED","intervalChanged"),q([be([Z.INIT,Z.OFF],Z.ON)],rs.prototype,"start",1),q([be([],Z.OFF)],rs.prototype,"stop",1);var Kr=class extends Ku{constructor(e){super(e);this.index=0;this.remotePublishedUserMap=new Map;this.audioVolumeEvalution=new rs(this);this.enableAIVoice=vf;this.AbilityOption={AVLimit:{EncVideoCodec:"H265",EncVideoWidth:0,EncVideoHeight:0,EncVideoBr:"0",EncVideoFps:0,EncAudioCodec:"opus",EncAudioFS:0,EncAudioCh:0,EncAudioBr:"0"},GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:navigator.platform,uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:Dp(),uint32_device_type:0,str_os_verion:Np(),uint32_link_type:1,str_client_version:Ke,uint32_net_type:go[Gr.getNetworkType()],ua:navigator.userAgent,version:""}};this.joinAbortController=new AbortController;e.tinyId&&(this.tinyId=e.tinyId,Rf(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return v(this,null,function*(){})}getLogger(){return this._log}postMessage(e,r){!this.session||(e?typeof e=="string"?this.session.postMessage({cmd:e,payload:r}):this.session.postMessage(e,r):this.session.postMessage(null))}sendMessage(e,r){return new Promise((o,s)=>{this.state!="joined"&&s("join room first");let a=new MessageChannel;this.postMessage({cmd:e,payload:r},[a.port1]),a.port2.onmessageerror=s,a.port2.onmessage=d=>{a.port2.close(),o(d.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var a;let s=new MessageChannel;s.port2.onmessage=d=>{d.data?o.next(d.data):o.complete()},s.port2.onmessageerror=d=>o.error(d),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(a=this.session)==null||a.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return v(this,null,function*(){if(e!==this.role)return this._log.info(`switchRole() => switch role to: ${e}`),e=="audience"&&this.unpublish(...this.localTracks),this.sendMessage("switchRole",e=="audience"?21:20).then(r=>{this.role=e})})}join(e,r,o){return v(this,null,function*(){var h,p,T;let s=Gr.getEnv(),a=Bd(),d={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(h=this.proxy_wt)==null?void 0:h.replace("https://",""),proxy_ws:(p=this.proxy_ws)==null?void 0:p.replace("wss://",""),proxy_cloud:(T=this.scheduleResult.iceServers)!=null&&T.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:Ps(),browserInfo:Bd(),tinyId:this.tinyId,joinReq:{useStrRoomid:!!this.useStringRoomId,roomid:String(e.roomId||e.strRoomId),sdkAppID:String(e.sdkAppId),userSig:e.userSig,privMapEncrypt:e.privateMapKey||"",privMap:"",pstnBizType:0,role:"user",jsSdkVersion:Ke,browserVersion:a.browserName+a.browserVersion,closeLocalMedia:!0,trtcscene:r==="live"?2:1,trtcrole:e.role,bussinessInfo:e.businessInfo||this.bussinessInfo||"",isAuxUser:0,autoSubscribe:this.autoReceiveAudio&&this.autoReceiveVideo,AbilityOption:this.AbilityOption}};yield PE.call(this,d),console.log(this),eo.playAudio(y=>this.postMessage({cmd:"setAudioWorkletPort"},[y])),this.checkDestroy()})}_leave(e=0){return v(this,null,function*(){console.log(this.userId,"leave",e),this.remotePublishedUserMap.forEach(r=>{r.remoteAudioTrack.close(),r.remoteAuxiliaryTrack.close(),r.remoteVideoTrack.close()}),this.postMessage(null),this.remotePublishedUserMap.clear(),this.localTracks.forEach((r,o)=>o.unpublish())})}leave(){return v(this,null,function*(){return this._leave()})}getSignalInfo(){return{tinyId:this.tinyid,clientIp:this.clientip,signalIp:"",relayIp:this.relayip,relayInnerIp:"",relayPort:0}}enableAudioVolumeEvaluation(e=2e3,r=!1){e<=0?this.audioVolumeEvalution.stop():this.audioVolumeEvalution.start(e,r)}getLocalAudioStats(){return this.sendMessage("getLocalAudioStats")}getLocalVideoStats(){return this.sendMessage("getLocalVideoStats")}afterJoin(){return v(this,null,function*(){let e=Ki(Qt(this,"left"));Xt(r=>v(this,null,function*(){let o=new MessageChannel;o.port2.onmessage=s=>{s.data?r.next({data:s.data,port:o.port2}):r.complete()},o.port2.onmessageerror=s=>r.error(s),r.defer(()=>{o.port2.postMessage(null),o.port2.close()}),this.postMessage({cmd:"decodeAudio",payload:!!this.audioManager.decodePipeline[0]},[o.port1])}),e,cr(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.buffer}});o.postMessage(new Uint8Array(s.data),[s.data])}))})}onWorkerEvent(e,r){switch(e!=="network-quality"&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(r)),e){case O.RECEIVED_PUBLISHED_USER_LIST:B.emit(e,J({room:this},r));return;case"1":if(r.userId===this.userId)return;this.emit("peer-join",r);return;case"2":this.emit("peer-leave",r);return;case"3":let o=new ju(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let y=r,R=this.remotePublishedUserMap.get(y);R&&(R.remoteVideoTrack.close(),R.remoteAuxiliaryTrack.close(),R.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(y),this.emit("remote-unpublished",R))}return;case"banned":switch(this._leave(r),r){case 8:this.emit("banned",{reason:"kick",message:""});break;case 2:case 6:case 4:this.emit("banned",{reason:"banned",message:""});case 7:case 5:this.emit("banned",{reason:"room_disband",message:""})}break;case"6":{let{prevMuteState:y,muteState:R,flag:N}=r,j=this.remotePublishedUserMap.get(R.userId);if(!j){this.emit("remote-publish-state-changed",r);return}j.flag=N}B.emit(O.REMOTE_PUBLISH_STATE_CHANGED,J({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"network-quality":this.quality=J({},r);let{uplinkLoss:s,uplinkRTT:a,uplinkInfo:d,downlinkInfo:h,msg_down_stream_info:p}=r,T={str_sdk_version:Ke,uint64_datetime:Date.now(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyid},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:go[Kn()]},msg_event_msg:Vg(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:d,msg_down_stream_info:p};B.emit(O.HEARTBEAT_REPORT,{room:this,report:T}),this.emit("heartbeat-report",T),B.emit(O.NETWORK_QUALITY,{room:this,uplink:{rtt:a,loss:s},downlinks:h}),delete r.downlinkInfo;break;case"signal-connection-state-changed":B.emit(O.SIGNAL_CONNECTION_STATE_CHANGED,J({room:this},r));return}this.emit(e,r)}sendStartPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("publishCdn",e)}sendStopPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("stopPublishCdn",e)}sendStartMixTranscode(e){return this.sendMessage("startMcuMix",e)}sendStopMixTranscode(e){return this.sendMessage("stopMcuMix",e)}publish(...e){return v(this,null,function*(){let r=e.reduce((d,h)=>h.mediaType|d,0),o=this.sendMessage("publish",r).then(d=>d.err!==0?Promise.reject(d.err):d),s=0,a=d=>v(this,null,function*(){switch(yield o,d.muted&&(s|=d.mediaType),Rt(d,d).add("mute",()=>{this.postMessage("mute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),d.mediaType){case 1:VE.call(this,d);break;default:yield BE.call(this,d)}});yield Promise.all(e.map(a)),s&&this.postMessage("mute",{mediaType:s,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(...e){return v(this,null,function*(){e.forEach(ct)})}subscribe(...e){return v(this,null,function*(){let r=e.reduce((y,R)=>R.mediaType|y,0),{userId:o,tinyId:s,streamType:a}=e[0],d=this.remotePublishedUserMap.get(o),h=J({},d.subscribeState),p=Object.assign(new ya,h);p.mediaType|=r,B.emit(O.SUBSCRIBE_START,{room:this,streamType:a,remotePublishedUser:d,subscribeState:p});let T=yield this.sendMessage("subscribe",{mediaType:p.mediaType,userId:o,srctinyid:s,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(y=>p.mediaType&y).map(y=>({mediaType:y,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",T),yield Promise.all(e.filter(y=>!y.isSubscribed).map(y=>{switch(y.mediaType){case 1:return kE.call(this,y);default:return LE.call(this,y)}})),B.emit(O.SUBSCRIBE_SUCCESS,{room:this,streamType:a,remotePublishedUser:d})})}unsubscribe(...e){return v(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType,o.unsubscribe();if(e.length){let{userId:o,streamType:s,tinyId:a}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:a,userId:o}),B.emit(O.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return v(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield rl.call(this,o,{profile:o.small,type:3,trackType:"camera"});let s=new MediaStreamTrackProcessor({track:this.videoManager.smallTrack}).readable;this.smallEncoder.track=this.videoManager.smallTrack,this.smallEncoder.label="small",this.smallAbortCtrl=new AbortController,this.smallEncoder.start(s,this.smallAbortCtrl,this),this._log.info("push small")}}else(r=this.smallAbortCtrl)==null||r.abort("stop"),this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder)})}changeType(e,r){let o=this.remotePublishedUserMap.get(r.userId),s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let a={srctinyid:r.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(d=>s&d).map(d=>({mediaType:d,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};o.remoteVideoTrack.mediaType=a.mediaType,this.postMessage("changetype",a)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};q([zi(Kr.prototype.afterJoin),be(["left",Z.INIT],"joined"),yE()],Kr.prototype,"join",1),q([be("joined","left",{ignoreError:!0}),AE()],Kr.prototype,"_leave",1),q([Kd((...i)=>0),bE()],Kr.prototype,"publish",1),q([Kd((...i)=>0),vE()],Kr.prototype,"unpublish",1),q([Kd((...i)=>i[0].userId),RE()],Kr.prototype,"subscribe",1);pn.frameWorkType=37;pn.create=function(i){let t=pn._create.call(this,Kr,i);return t._use(Ja,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(yt.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",Ke,"created",yt),t};Object.assign(pn.prototype,{_setCurrentSpeaker(i){var t;return(t=eo.audioCtx)!=null&&t.setSinkId?eo.audioCtx.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return v(this,null,function*(){return this.startPlugin("TRTCVideoDecoder",{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.420028"},fallback:"wasm"}),new Promise((e,r)=>{We(Je(i,"decode-downgrade-state-changed"),Go(o=>o.state==="STARTED"),xr(1),sh(5e3),gt(Je(i,Z.INIT)),dt(e,r))})})}});var S$=pn;export{S$ as default};
|
|
139
|
+
}`});l(this,"yTextureRef");l(this,"uTextureRef");l(this,"vTextureRef");l(this,"Y");l(this,"U");l(this,"V");this.useProgram();let r=this.context.ctx;r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,r){let o=this.context.ctx,s=o.createTexture();return o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),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.bindTexture(o.TEXTURE_2D,null),o.uniform1i(o.getUniformLocation(this.program,e),r),s}render(e){let r=this.context.ctx,o=this.width,s=this.height;return this.useProgram(),r.viewport(0,0,o,s),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o,s,r.LUMINANCE,r.UNSIGNED_BYTE,this.Y),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.U),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,r){super.resize(e,r);let o=this.context.ctx;o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,this.yTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e,r,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE1),o.bindTexture(o.TEXTURE_2D,this.uTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this.vTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}};var If=[i=>{i.codec="avc1.420028"},i=>{delete i.hardwareAcceleration}],wE=(i,t)=>{switch(i){case"webCodecs":return t==="videoFrame"?514705:514706;case"wasm":return t==="webgl"?514707:t==="videoFrame"?514708:514709}throw new Error("decoder type not supported")},Yu=class{constructor(t){l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"decoder");l(this,"videoContext");l(this,"gop",0);l(this,"gop_helper",0);l(this,"waitFirstKeyFrame",!0);l(this,"startTimestamp",0);l(this,"startTime",0);l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"downgradeLevel",0);l(this,"config");l(this,"videoElement");l(this,"type","wasm");l(this,"renderer","2d");l(this,"wasmOption");l(this,"createDecoder");l(this,"_decodeSink");let{track:e,createDecoder:r}=t;if(this.createDecoder=r,this.wasmOption={yuvMode:t.renderer==="webgl",wasmPath:t.wasmPath,workerMode:t.workerMode,canvas:t.canvas},this.config=t.config,this.videoElement=t.videoElement,this.renderer=t.renderer,this.trackDoneOB=Je(e,Z.INIT),this.stopOB=Jt(this.trackDoneOB),t.type==="auto"){switch(t.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=t.type;this.changeRenderer(this.renderer),this.startOB=Jt();let o=Jt(),s;We(o,th((d,h)=>(d!==h&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:s,prevState:d,state:h}),h),"INITIALIZED"),gt(this.stopOB),dt());let a=d=>{let h=this.pipe(e);return o.next("STARTING"),e.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`),We(h,gt(this.stopOB),dt(()=>{e.stat.framesDecoded++},p=>{if(e.log.error(p),X.addFailedEvent({key:wE(this.type,this.renderer),error:p}),d>4)this.startOB.error(p);else{switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.startOB.next(d+1)}})),We(h,xr(1),qa(Ho))};We(this.startOB,$o(0),Qi(a),gt(this.stopOB),dt(()=>{e.player.handlePlaying("canvas"),o.next("STARTED")},d=>{s=d,o.next("FAILED")},()=>{X.addSuccessEvent({key:wE(this.type,this.renderer)}),X.addSuccessEvent({key:514704})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}changeRenderer(t){this.renderer=t,this.renderer==="videoFrame"&&!em()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t){var s;if(this.inputFrameCount++,((s=this.decoder)==null?void 0:s.state)!=="configured")return t;let e=new Uint8Array(t.data)[4]&31,r=!1;switch(e){case 5:case 7:r=!0;break}let{timestamp:o}=t;if(r?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(r)this.waitFirstKeyFrame=!1,this.startTimestamp=o,this.startTime=Date.now();else return;let a=(o-this.startTimestamp)/90,h=Date.now()-this.startTime-a,p=h<500?0:h/1e3>>0;switch(r&&(p>0?this.downgradeLevel++:this.downgradeLevel>3&&this.downgradeLevel--),this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}this.decoder.decode(t);return}return t}pipe(t){return Ri()(e=>v(this,null,function*(){this._decodeSink=e,e.defer(()=>{var s,a;(s=this.decoder)==null||s.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:r,type:o}=this;try{switch(o){case"wasm":this.decoder=this.createDecoder(o,this.wasmOption);break;case"webCodecs":for(let s=0;s<=If.length;s++){let{supported:a}=yield VideoDecoder.isConfigSupported(this.config);if(a)break;if(s===If.length){e.error(3);return}If[s](this.config)}this.decoder=this.createDecoder(o);break;case"mse":throw new Error("not supported yet")}if(this.decoder.on("videoFrame",s=>{this.decodedFrameCount++,e.next(s)}),this.decoder.on("error",s=>{t.log.error(s),e.error(o==="webCodecs"?4:8)}),yield this.decoder.initialize(this.videoElement),this.decoder.configure(this.config),o==="wasm"&&r==="webgl"){this.videoContext=new st({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(st.UNAVAILABLE,a=>{t.log.error(a),e.error(7)});let s=new Qu(this.videoContext);this.decoder.on("videoCodecInfo",a=>s.resize(a.width,a.height)),this.decoder.on("videoFrame",a=>{[s.Y,s.U,s.V]=a,this.downgradeLevel===1?this.decodedFrameCount%2===0&&s.render(this.decodedFrameCount):s.render(this.decodedFrameCount)}),t.source=s,t.player.setCanvas(this.videoContext._canvas,2)}else if(r==="videoFrame"){t.player.setCanvas();let s=new MediaStreamTrackGenerator({kind:"video"}),a=s.writable.getWriter();t.setInputMediaStreamTrack(s),this.decoder.on("videoFrame",d=>{a.write(d)}),s.onmute=()=>{e.error(o==="webCodecs"?5:9)},e.defer(()=>s.onmute=null)}else{this.videoContext=new Ct({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let s=this.videoContext.createVideoImageSource();this.decoder.on("videoFrame",d=>{s.image=d,s.update()});let a=new jo(this.videoContext,{name:"remotePlayer",logger:t.log});s.connect(a),t.source=s,t.player.setCanvas(this.videoContext._canvas,2)}}catch(s){t.log.error(s),e.error(o==="webCodecs"?2:6)}}))}};var Zu=class extends xE.EventEmitter{constructor(e){super();this.room=e;l(this,"videoContext");l(this,"_glVideoContext");l(this,"_2dVideoContext");l(this,"destination");l(this,"smallVideoContext");l(this,"smallDestination");l(this,"smallTrackSource");l(this,"smallImageSource");l(this,"_isMirror",!1);l(this,"cameraTrack");l(this,"cameraNode");l(this,"mirrorNode");l(this,"mixNode");l(this,"screenTrack");l(this,"screenNode");l(this,"selfModel",!1);l(this,"blurRadius",3);l(this,"arTrack");l(this,"Wasm");l(this,"waterMarkNode");l(this,"_waterMarkOption");l(this,"watermarkImageList",[]);l(this,"_beautyParams");l(this,"isUsingArTrack",!1);l(this,"_isMixScreen",!1);l(this,"_virtualBackground");l(this,"_virtualBackgroundAbortCallback");l(this,"virtualBackgroundInstance");l(this,"_bgAssetPath");l(this,"log",V.createLogger({id:"vm"}));l(this,"_checkId",0);l(this,"_use2d",!1);l(this,"_autoSwitchRenderMode",!0);l(this,"_selfieSegmentation");l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Ct({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let r=e==="2d";this._use2d!==r&&(this._use2d=r,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Ct({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new st({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("unavailable",e=>{var r;this.emit("error",e),this.log.warn("video context unavailable",e),(r=this._virtualBackgroundAbortCallback)==null||r.call(this,e),this.update()})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=Et.run(To,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,r;(e=this._2dVideoContext)==null||e.destroy(),(r=this._glVideoContext)==null||r.destroy(),this.smallVideoContext.destroy(),Et.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Bi||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?X.addFailedEvent({key:o,error:r}):X.addSuccessEvent({key:o})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let r=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(r)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new st({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,settings:a,player:d}=o;s?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Tu(this.smallVideoContext,s,this.log)),this.smallVideoContext.frameRate=s.frameRate,this.smallDestination.resolution=s,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=a.width,this.smallTrackSource.height=a.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Bi&&d.setCanvas(e);let h=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),h=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${h?h.label:"no output track"}`),o.setOutputMediaStreamTrack(h)}catch(o){this.log.error("set main output failed",o)}}update(){return v(this,null,function*(){var o,s;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),ir===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Ci?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Ci?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(e.width,e.height)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new Eu(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new Xu(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let a=this.cameraNode;a.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new zu(this.videoContext,this.log)),a=a.connect(this.mirrorNode),a.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new Ju(this.videoContext,this.log),a.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(o=this.waterMarkNode)==null||o.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(s=this.screenNode)==null||s.connect(this.mixNode,{zIndex:0}),a=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),a.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var r,o,s,a;if(e instanceof Ji)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof hr)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof Yi){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let d=e.mediaTrack;return e.setOutputMediaStreamTrack(d)}this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var r;e instanceof Ji?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof hr?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Yi&&e.source&&e.source.context.destroy()}setCameraTrack(e){return v(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,r){return v(this,null,function*(){let o=document.createElement("canvas");r&&e&&(o.height=r,o.width=e);let s=o.getContext("2d");if(!s)throw new de({code:Y.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((a,d)=>a.zIndex-d.zIndex),this.watermarkImageList.forEach(({image:a,x:d,y:h,width:p,height:T})=>{s.drawImage(a,d,h,p,T)}),As(o.toDataURL())})}pushWaterMarkImageList(e){let{type:r}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex)||((r==="mute"||r==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==r)),this.watermarkImageList.push(e))}setBeautyParams(e){return v(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return v(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return v(this,null,function*(){var y,R;let r;try{r=yield As((e==null?void 0:e.imageElement)||e.imageUrl)}catch(N){throw new de({code:Y.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:a=r.width,height:d=r.height,type:h="watermark",zIndex:p=2}=e;this.watermarkImageList.some(N=>N.type===h)?(this.watermarkImageList=this.watermarkImageList.filter(N=>N.type!==h),this.pushWaterMarkImageList({x:o,y:s,width:a,height:d,image:r,zIndex:p,type:h,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage((y=this.cameraTrack)==null?void 0:y.settings.width,(R=this.cameraTrack)==null?void 0:R.settings.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:o,y:s,width:a,height:d,image:r,zIndex:p,type:h,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(N,j)=>N==="imageUrl"?void 0:j))})}deleteWatermark(e="watermark"){return v(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(r=>r.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(r,o)=>r==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return v(this,null,function*(){var r,o,s;(r=this.waterMarkNode)==null||r.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((o=this.cameraTrack)==null?void 0:o.settings.width,(s=this.cameraTrack)==null?void 0:s.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return v(this,null,function*(){if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield As(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new de({code:Y.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var r;this._isMixScreen=e,this._isMixScreen||((r=this.screenNode)==null||r.close(),delete this.screenNode),this.update()}set mirror(e){var r;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((r=this.mirrorNode)==null||r.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return v(this,null,function*(){var e;!((e=this.cameraTrack)!=null&&e.mediaTrack)||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new Yu(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};var cA=0;var Ku=class extends Z{constructor(e){super("room");this.seq=++cA;this.role="anchor";this.joinParams=null;this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.checkSystemResult={result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}};this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this._isUsingCachedSchedule=!1;this._log=V.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this.isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,nt(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),nt(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),nt(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new CE({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new DE({room:this}),this.badCaseDetector=new NE({room:this}),this.audioManager=new ru(this),this.videoManager=new Zu(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return v(this,null,function*(){return this.publish(e)})}removeTrack(e){return v(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return v(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Ae(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if($t(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:a,unifiedProxy:d}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=d,d?(ku([d,d]),_o(`https://${d}`)):(s&&_o(s),a&&ku(a))}B.once(O.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Pr.main,sched_back_domain:Pr.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return v(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return v(this,null,function*(){var r;let e={rtt:((r=this.quality)==null?void 0:r.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)e.downlinksRTT[o.userId]=o.rtt;return e})}getRemoteVideoStats(){return v(this,arguments,function*(e="main"){let r={};return this.remotePublishedUserMap.forEach(o=>{let s=e==="auxiliary"?o.remoteAuxiliaryTrack:o.remoteVideoTrack;r[o.userId]=s.stat}),r})}checkDestroy(){if(this.isDestroyed)throw new de({code:Y.INVALID_OPERATION,message:ot({key:it.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(jt.INVALID_DESTROY),new de({code:Y.INVALID_OPERATION,message:ot({key:it.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,B.emit(O.ROOM_DESTROY,{room:this})}schedule(e,r){return v(this,null,function*(){var s,a,d;let o=ge();try{let{isCached:h,result:p,detailCost:T}=yield ef({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Ke,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=h,this._log.info(`schedule cache:${+h} ${pr(p,{keysToExclude:["username","credential"]})}`),h&&B.once(O.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=J(J({},this.scheduleResult),p),Fe((s=p.config)==null?void 0:s.retryCount)&&sp(p.config.retryCount),Ae((a=p.config)==null?void 0:a.loggerDomain)&&_o(p.config.loggerDomain),this.videoDecodeFallbackType=((d=p.config)==null?void 0:d.videoDecodeFallback)||this.videoDecodeFallbackType,B.emit(O.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:T}),X.addSuccessEvent({key:521700,cost:ge()-o,split:50})}catch(h){throw X.addFailedEvent({key:521700,error:h}),h}})}sendAbilityStatus(e){}enableInsertableStreams(){}};var Sf=(()=>{if(typeof self=="undefined")return!1;if("top"in self&&self!==top)try{}catch(i){return!1}else if("showOpenFilePicker"in self)return"showOpenFilePicker";return!1})(),vB=Sf?Promise.resolve().then(function(){return pA}):Promise.resolve().then(function(){return EA});var RB=Sf?Promise.resolve().then(function(){return hA}):Promise.resolve().then(function(){return IA});var dA=Sf?Promise.resolve().then(function(){return _A}):Promise.resolve().then(function(){return yA});function yf(...i){return v(this,null,function*(){return(yield dA).default(...i)})}var uA=i=>v(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),lA=(...t)=>v(void 0,[...t],function*(i=[{}]){Array.isArray(i)||(i=[i]);let e=[];i.forEach((s,a)=>{e[a]={description:s.description||"Files",accept:{}},s.mimeTypes?s.mimeTypes.map(d=>{e[a].accept[d]=s.extensions||[]}):e[a].accept["*/*"]=s.extensions||[]});let r=yield window.showOpenFilePicker({id:i[0].id,startIn:i[0].startIn,types:e,multiple:i[0].multiple||!1,excludeAcceptAllOption:i[0].excludeAcceptAllOption||!1}),o=yield Promise.all(r.map(uA));return i[0].multiple?o:o[0]}),pA={__proto__:null,default:lA};function el(i){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var r=e.done;return Promise.resolve(e.value).then(function(o){return{value:o,done:r}})}return el=function(e){this.s=e,this.n=e.next},el.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return r===void 0?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return r===void 0?Promise.reject(e):t(r.apply(this.s,arguments))}},new el(i)}var ME=(o,s,...a)=>v(void 0,[o,s,...a],function*(i,t,e=i.name,r){let d=[],h=[];var p,T=!1,y=!1;try{for(var R,N=function(j){var W,F,Ie,Bt=2;for(typeof Symbol!="undefined"&&(F=Symbol.asyncIterator,Ie=Symbol.iterator);Bt--;){if(F&&(W=j[F])!=null)return W.call(j);if(Ie&&(W=j[Ie])!=null)return new el(W.call(j));F="@@asyncIterator",Ie="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());T=!(R=yield N.next()).done;T=!1){let j=R.value,W=`${e}/${j.name}`;j.kind==="file"?h.push(j.getFile().then(F=>(F.directoryHandle=i,F.handle=j,Object.defineProperty(F,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>W})))):j.kind!=="directory"||!t||r&&r(j)||d.push(ME(j,t,W,r))}}catch(j){y=!0,p=j}finally{try{T&&N.return!=null&&(yield N.return())}finally{if(y)throw p}}return[...(yield Promise.all(d)).flat(),...yield Promise.all(h)]}),mA=(...t)=>v(void 0,[...t],function*(i={}){i.recursive=i.recursive||!1,i.mode=i.mode||"read";let e=yield window.showDirectoryPicker({id:i.id,startIn:i.startIn,mode:i.mode});return ME(e,i.recursive,void 0,i.skipDirectory)}),hA={__proto__:null,default:mA},fA=(s,...a)=>v(void 0,[s,...a],function*(i,t=[{}],e=null,r=!1,o=null){Array.isArray(t)||(t=[t]),t[0].fileName=t[0].fileName||"Untitled";let d=[],h=null;if(i instanceof Blob&&i.type?h=i.type:i.headers&&i.headers.get("content-type")&&(h=i.headers.get("content-type")),t.forEach((y,R)=>{d[R]={description:y.description||"Files",accept:{}},y.mimeTypes?(R===0&&h&&y.mimeTypes.push(h),y.mimeTypes.map(N=>{d[R].accept[N]=y.extensions||[]})):h?d[R].accept[h]=y.extensions||[]:d[R].accept["*/*"]=y.extensions||[]}),e)try{yield e.getFile()}catch(y){if(e=null,r)throw y}let p=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:d,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(p);let T=yield p.createWritable();return"stream"in i?(yield i.stream().pipeTo(T),p):"body"in i?(yield i.body.pipeTo(T),p):(yield T.write(yield i),yield T.close(),p)}),_A={__proto__:null,default:fA},gA=(...t)=>v(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),new Promise((e,r)=>{let o=document.createElement("input");o.type="file";let s=[...i.map(p=>p.mimeTypes||[]),...i.map(p=>p.extensions||[])].join();o.multiple=i[0].multiple||!1,o.accept=s||"",o.style.display="none",document.body.append(o);let a=p=>{typeof d=="function"&&d(),e(p)},d=i[0].legacySetup&&i[0].legacySetup(a,()=>d(r),o),h=()=>{window.removeEventListener("focus",h),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",h)}),o.addEventListener("change",()=>{window.removeEventListener("focus",h),o.remove(),a(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),EA={__proto__:null,default:gA},TA=(...t)=>v(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),i[0].recursive=i[0].recursive||!1,new Promise((e,r)=>{let o=document.createElement("input");o.type="file",o.webkitdirectory=!0;let s=d=>{typeof a=="function"&&a(),e(d)},a=i[0].legacySetup&&i[0].legacySetup(s,()=>a(r),o);o.addEventListener("change",()=>{let d=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(d=d.filter(h=>h.webkitRelativePath.split("/").every(p=>!i[0].skipDirectory({name:p,kind:"directory"})))):d=d.filter(h=>h.webkitRelativePath.split("/").length===2),s(d)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),IA={__proto__:null,default:TA},SA=(e,...r)=>v(void 0,[e,...r],function*(i,t={}){Array.isArray(t)&&(t=t[0]);let o=document.createElement("a"),s=i;"body"in i&&(s=yield function(h,p){return v(this,null,function*(){let T=h.getReader(),y=new ReadableStream({start:j=>function W(){return v(this,null,function*(){return T.read().then(({done:F,value:Ie})=>{if(!F)return j.enqueue(Ie),W();j.close()})})}()}),R=new Response(y),N=yield R.blob();return T.releaseLock(),new Blob([N],{type:p})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let a=()=>{typeof d=="function"&&d()},d=t.legacySetup&&t.legacySetup(a,()=>d(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),a()}),o.click(),null}),yA={__proto__:null,default:SA};var Af=class{constructor(t){this.name=t;l(this,"ready");l(this,"worker");l(this,"ports");l(this,"ids",1);l(this,"transactions",new Map);l(this,"log");l(this,"addTransaction",t=>(this.transactions.set(++this.ids,t),this.ids))}postMessage(t,e){var r;(r=this.worker)==null||r.postMessage(t,e)}create(t){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=new Worker(Zg(),{name:t});return this.worker=e,this.ready=new Promise((r,o)=>{e.onmessage=({data:{id:s,type:a,payload:d}})=>{var h;if(s)(h=this.transactions.get(s))==null||h(d),this.transactions.delete(s);else switch(a){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",d),o(d);break;case"ready":console.timeEnd(`createWorker_${t}`),r(this);break;case"updateAFSM":if(d.value){let p=typeof d.old=="string"?d.old:`${d.old.action}ing`,T=typeof d.value=="string"?d.value:`${d.value.action}ing`;console.log(nd(),d.group,d.name,p,"\u{1F449}",T)}break;case"log":console.log(d);break;case"glog":window.dispatchEvent(new CustomEvent(a,{detail:d}));break}},e.postMessage({wasm:xu(),flag:yt},this.ports)})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},bf=class{constructor(t,e,r){this.worker=t;l(this,"channel",new MessageChannel);l(this,"ready");this.ready=new Promise((o,s)=>{this.worker.postMessage({id:this.worker.addTransaction(o),payload:e},[this.channel.port2])}).then(o=>(o.err===0&&(this.worker.sessionCount++,this.channel.port1.onmessage=r),o))}postMessage(...t){this.channel.port1.postMessage(...t)}destroy(){--this.worker.sessionCount===0&&this.worker.destroy()}},tc=class extends Af{constructor(){super("main");l(this,"switchValue",new Map);l(this,"extendChannel");l(this,"sessionCount",0)}setSwitchValue(e,r){var o;this.switchValue.set(e,r),(o=this.extendChannel)==null||o.port1.postMessage([e,r])}create(){return v(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Lt(tc.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},oo=new tc,ts,AA=-1;function OE(i){return console.log(i),ts.push(i.slice()),ts.length>1e3&&ts.shift(),i}function PE(i){return v(this,null,function*(){switch(AA){case 0:this.edpl.willDecodeAudio=OE;break;case 2:this.edpl.didEncodeAudio=OE;break}yield oo.create(),B.emit(O.JOIN_SEND_CMD,{room:this});let t=new bf(oo,i,o=>{let s=o.data;if(typeof s=="string")this.onWorkerEvent(s);else if(s==null)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:a,payload:d}=s;this.onWorkerEvent(a,d)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(B.emit(O.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new de({code:Y.JOIN_ROOM_FAILED,extraCode:Number(e),message:ot({key:it.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:vf},useWt:{set:bA},enableDebug:{set(i){console.debug=i?Qg:()=>{},oo.setSwitchValue("enableDebug",i)}},useV2:{set:Rf},dump:{value(){if(ts||(console.warn("dump audio will be activated at next time join room"),ts=[]),!ts.length){console.warn("no audio data to dump,try it later");return}let i=[];return ts.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),yf(new Blob(i),{fileName:"audio dump hex",extensions:[".hex"]})}},dumpAudio:{value(i="audio",t=2e3){let e=[],r=new Promise(o=>{let s=new MessageChannel;oo.extendChannel.port1.postMessage(["dump",i],[s.port1]),s.port2.onmessage=({data:a})=>{console.log(a),e.push(a),e.length>t&&(s.port2.onmessage=null,oo.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return yf(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:yt.useHardDecoder="prefer-hardware";break;case!1:yt.useHardDecoder="prefer-software";break;default:yt.useHardDecoder="no-preference"}}}});function vf(i){return v(this,null,function*(){oo.setSwitchValue("useAINS",i)})}function Rf(i){return v(this,null,function*(){oo.setSwitchValue("useV2",i)})}function bA(i){return v(this,null,function*(){oo.setSwitchValue("useWt",i)})}function kE(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function LE(i){return v(this,null,function*(){var r;this._log.info("pull video",i);let t=Date.now(),e=new MessageChannel;this.postMessage({cmd:"pullVideo",payload:{mediaType:i.mediaType,tinyId:i.tinyId}},[e.port1]),(r=i.stat).framesReceived||(r.framesReceived=0),Xt(Xg(e.port2),Ki(Qt(i,Z.INIT)),cr(o=>{let{data:s,packetsReceived:a}=o;i.stat.packetsReceived=a,i.stat.framesReceived++;let d=s[4]&31,h;switch(d){case 5:case 7:h="key";break;default:h="delta";break}i.decodeFrame({data:s.buffer,type:h,timestamp:(Date.now()-t)*1e3})},()=>{},()=>{e.port2.postMessage(null),e.port2.close()}))})}var tl=[];function VE(i){var h;let t=tn();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let p=0;p<=tl.length;p++)if(!tl[p]){tl[p]=this,this.index=p;break}let e=i.profile;this._log.info("start push audio",this.index,e);let r=new MessageChannel,o=i.enableEncodeFrame?new MessageChannel:null;(h=this.session)==null||h.postMessage({cmd:"pushAudio",payload:J({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=p=>{p.data==null||(typeof p.data=="number"?t.next(p.data):o&&o.port1.postMessage(me(J({},p.data),{data:new Uint8Array(i.encodeFrame({data:p.data.data.buffer,timestamp:p.data.timestamp}).data)})))};let s=new MediaStream,a,d=p=>{let T=s.getAudioTracks()[0];T&&(a.disconnect(),s.removeTrack(T)),s.addTrack(p),this._log.info("push audio track:",p.readyState,p.getSettings().deviceId),a=eo.audioCtx.createMediaStreamSource(s),a.connect(eo.worklet,0,this.index)};Xt(Qt(i,"output-media-track-changed"),Ki(Qt(i,"capture")),cr(d,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,a.disconnect(),tl[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),Xt(t,zg(p=>i.volume=p),qg(gu(1e3)),cr(()=>{i.volume=0})),d(i.outMediaTrack)}var tF=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Cf=class{constructor(t,e,r,o){this.localTrack=t;this.type=e;this.config=r;this.port=o;l(this,"track");l(this,"label");l(this,"insertKeyFrame",!0);l(this,"encoder");l(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){let o=this.recreate(r);e.signal.addEventListener("abort",()=>{o.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(a,d)=>{o.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(a),s++,d.enqueue(a))}}),e)}encode(t){this.encoder.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){let o=this.recreate(r),s=0;t.pipeTo(new WritableStream({write:a=>{o.state==="configured"&&(s<10&&console.log(`capture ${this.label} track frame:`,s,Date.now(),a.timestamp,a.displayWidth,a.displayHeight),(a.displayWidth!==this.config.width||a.displayHeight!==this.config.height)&&(console.log("resize video track frame:",a.displayWidth,a.displayHeight,this.config.width,this.config.height),this.configure({width:a.displayWidth,height:a.displayHeight})),this.tsMap.set(s,Date.now()),this.encode(a),s<10&&console.log(`encode ${this.label} track frame:`,s),s++,a.close())}}),e).catch(a=>{console.warn(a),o.close()})}recreate(t,e=0){let r=0,o=new VideoEncoder({output:s=>{let a=this.tsMap.get(r);if(this.tsMap.delete(s.timestamp),r<10&&(r===0&&e===0&&B.emit(O.SEND_FIRST_VIDEO_FRAME,{room:t}),console.log(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,this.track.enabled===!1)return;let d=null;if(this.localTrack.enableEncodeFrame){d=new Uint8Array(s.byteLength),s.copyTo(d);let h=this.localTrack.encodeFrame({data:d.buffer},this.type===3);d=new Uint8Array(h.data)}d?(this.localTrack.stat.bytesSent+=d.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:d,duration:s.duration},timestamp:a},[d.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:a}))},error:s=>{console.warn(s,this.config),setTimeout(()=>this.recreate(t,e+1),100)}});return this.encoder=o,this.configure({}),o}configure(t){var e;(e=this.encoder)==null||e.configure(Object.assign(this.config,t))}close(){this.port.postMessage(null),this.port.close()}};function rl(i,t){return v(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",avc:{format:"annexb"},hardwareAcceleration:yt.useHardEncoder,width:t.profile.width,height:t.profile.height,framerate:t.profile.frameRate,bitrate:t.profile.bitrate*1e3},s=new MessageChannel;this.postMessage({cmd:"pushVideo",payload:t},[s.port1]);let a=new Cf(i,t.type,o,s.port2);return s.port2.onmessage=d=>{if(d.data===260)a.insertKeyFrame=!0;else if(!e){let{bitrate:h}=d.data;ta({configureBr:[d.data.bitrate,h]}),a.configure({bitrate:h})}},this._log.info("start push",r,t),a})}function BE(i){return v(this,null,function*(){let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera"};!t&&i.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(r.trackType="canvas");let{trackType:o}=r,{width:s,height:a}=i.outMediaTrack.getSettings();r.profile.width=s,r.profile.height=a;let d=yield rl.call(this,i,r);this._log.info("VideoEncoder created",r);let h,p=T=>v(this,null,function*(){if(h==null||h.abort("track changed"),!T)return;h=new AbortController;let{width:y,height:R,displaySurface:N}=T.getSettings();y&&(d.config.width=y),R&&(d.config.height=R);let j=rr.match(/Chrome\/(\d+)/);(j==null?void 0:j[1])==="114"&&N==="browser"&&delete d.config.hardwareAcceleration,this._log.info("push",e,"track:",T.readyState,T.getSettings());let W=new MediaStreamTrackProcessor({track:T}).readable,F="small"in i&&i.small;F?(this.smallEncoder||(this.smallEncoder=yield rl.call(this,i,{profile:F,type:3,trackType:o})),this.smallEncoder.track=T,this.smallEncoder.label="small",W=this.smallEncoder.trans(W,h,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),d.track=T,d.label=e,d.start(W,h,this)});return Xt(Qt(i,"output-media-track-changed"),Ki(Qt(i,"capture")),cr(p,console.error,()=>{var T;this._log.info("stop push",e,r),h.abort("unpublish"),d.close(),(T=this.smallEncoder)==null||T.close()})),p(i.outMediaTrack)})}var ic=class extends Z{constructor(e){var r,o;super((o=(r=e.roomid)==null?void 0:r.toString())!=null?o:e.name,"volumeEvaluation");this.room=e;l(this,"enableInBackground",!1);l(this,"interval",400);e.on("joined",()=>{this.emit(ic.INTERVALCHANGED,this.interval)}),Xt(Qt(this,ic.INTERVALCHANGED),jg(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):Xt(Ug(s),Gg(()=>[]))),cr(s=>{s.forEach(a=>{this.room.remotePublishedUserMap.has(a.userId)&&(this.room.remotePublishedUserMap.get(a.userId).remoteAudioTrack.volume=a.volume)}),(!document.hidden||this.enableInBackground)&&this.state==Z.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(ic.INTERVALCHANGED,this.interval)}stop(){}},rs=ic;l(rs,"INTERVALCHANGED","intervalChanged"),q([be([Z.INIT,Z.OFF],Z.ON)],rs.prototype,"start",1),q([be([],Z.OFF)],rs.prototype,"stop",1);var Kr=class extends Ku{constructor(e){super(e);this.index=0;this.remotePublishedUserMap=new Map;this.audioVolumeEvalution=new rs(this);this.enableAIVoice=vf;this.AbilityOption={AVLimit:{EncVideoCodec:"H265",EncVideoWidth:0,EncVideoHeight:0,EncVideoBr:"0",EncVideoFps:0,EncAudioCodec:"opus",EncAudioFS:0,EncAudioCh:0,EncAudioBr:"0"},GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:navigator.platform,uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:Dp(),uint32_device_type:0,str_os_verion:Np(),uint32_link_type:1,str_client_version:Ke,uint32_net_type:go[Gr.getNetworkType()],ua:navigator.userAgent,version:""}};this.joinAbortController=new AbortController;e.tinyId&&(this.tinyId=e.tinyId,Rf(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return v(this,null,function*(){})}getLogger(){return this._log}postMessage(e,r){!this.session||(e?typeof e=="string"?this.session.postMessage({cmd:e,payload:r}):this.session.postMessage(e,r):this.session.postMessage(null))}sendMessage(e,r){return new Promise((o,s)=>{this.state!="joined"&&s("join room first");let a=new MessageChannel;this.postMessage({cmd:e,payload:r},[a.port1]),a.port2.onmessageerror=s,a.port2.onmessage=d=>{a.port2.close(),o(d.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var a;let s=new MessageChannel;s.port2.onmessage=d=>{d.data?o.next(d.data):o.complete()},s.port2.onmessageerror=d=>o.error(d),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(a=this.session)==null||a.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return v(this,null,function*(){if(e!==this.role)return this._log.info(`switchRole() => switch role to: ${e}`),e=="audience"&&this.unpublish(...this.localTracks),this.sendMessage("switchRole",e=="audience"?21:20).then(r=>{this.role=e})})}join(e,r,o){return v(this,null,function*(){var h,p,T;let s=Gr.getEnv(),a=Bd(),d={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(h=this.proxy_wt)==null?void 0:h.replace("https://",""),proxy_ws:(p=this.proxy_ws)==null?void 0:p.replace("wss://",""),proxy_cloud:(T=this.scheduleResult.iceServers)!=null&&T.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:Ps(),browserInfo:Bd(),tinyId:this.tinyId,joinReq:{useStrRoomid:!!this.useStringRoomId,roomid:String(e.roomId||e.strRoomId),sdkAppID:String(e.sdkAppId),userSig:e.userSig,privMapEncrypt:e.privateMapKey||"",privMap:"",pstnBizType:0,role:"user",jsSdkVersion:Ke,browserVersion:a.browserName+a.browserVersion,closeLocalMedia:!0,trtcscene:r==="live"?2:1,trtcrole:e.role,bussinessInfo:e.businessInfo||this.bussinessInfo||"",isAuxUser:0,autoSubscribe:this.autoReceiveAudio&&this.autoReceiveVideo,AbilityOption:this.AbilityOption}};yield PE.call(this,d),console.log(this),eo.playAudio(y=>this.postMessage({cmd:"setAudioWorkletPort"},[y])),this.checkDestroy()})}_leave(e=0){return v(this,null,function*(){console.log(this.userId,"leave",e),this.remotePublishedUserMap.forEach(r=>{r.remoteAudioTrack.close(),r.remoteAuxiliaryTrack.close(),r.remoteVideoTrack.close()}),this.postMessage(null),this.remotePublishedUserMap.clear(),this.localTracks.forEach((r,o)=>o.unpublish())})}leave(){return v(this,null,function*(){return this._leave()})}getSignalInfo(){return{tinyId:this.tinyid,clientIp:this.clientip,signalIp:"",relayIp:this.relayip,relayInnerIp:"",relayPort:0}}enableAudioVolumeEvaluation(e=2e3,r=!1){e<=0?this.audioVolumeEvalution.stop():this.audioVolumeEvalution.start(e,r)}getLocalAudioStats(){return this.sendMessage("getLocalAudioStats")}getLocalVideoStats(){return this.sendMessage("getLocalVideoStats")}afterJoin(){return v(this,null,function*(){let e=Ki(Qt(this,"left"));Xt(r=>v(this,null,function*(){let o=new MessageChannel;o.port2.onmessage=s=>{s.data?r.next({data:s.data,port:o.port2}):r.complete()},o.port2.onmessageerror=s=>r.error(s),r.defer(()=>{o.port2.postMessage(null),o.port2.close()}),this.postMessage({cmd:"decodeAudio",payload:!!this.audioManager.decodePipeline[0]},[o.port1])}),e,cr(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.buffer}});o.postMessage(new Uint8Array(s.data),[s.data])}))})}onWorkerEvent(e,r){switch(e!=="network-quality"&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(r)),e){case O.RECEIVED_PUBLISHED_USER_LIST:B.emit(e,J({room:this},r));return;case"1":if(r.userId===this.userId)return;this.emit("peer-join",r);return;case"2":this.emit("peer-leave",r);return;case"3":let o=new ju(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let y=r,R=this.remotePublishedUserMap.get(y);R&&(R.remoteVideoTrack.close(),R.remoteAuxiliaryTrack.close(),R.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(y),this.emit("remote-unpublished",R))}return;case"banned":switch(this._leave(r),r){case 8:this.emit("banned",{reason:"kick",message:""});break;case 2:case 6:case 4:this.emit("banned",{reason:"banned",message:""});case 7:case 5:this.emit("banned",{reason:"room_disband",message:""})}break;case"6":{let{prevMuteState:y,muteState:R,flag:N}=r,j=this.remotePublishedUserMap.get(R.userId);if(!j){this.emit("remote-publish-state-changed",r);return}j.flag=N}B.emit(O.REMOTE_PUBLISH_STATE_CHANGED,J({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"network-quality":this.quality=J({},r);let{uplinkLoss:s,uplinkRTT:a,uplinkInfo:d,downlinkInfo:h,msg_down_stream_info:p}=r,T={str_sdk_version:Ke,uint64_datetime:Date.now(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyid},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:go[ea()]},msg_event_msg:Vg(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:d,msg_down_stream_info:p};B.emit(O.HEARTBEAT_REPORT,{room:this,report:T}),this.emit("heartbeat-report",T),B.emit(O.NETWORK_QUALITY,{room:this,uplink:{rtt:a,loss:s},downlinks:h}),delete r.downlinkInfo;break;case"signal-connection-state-changed":B.emit(O.SIGNAL_CONNECTION_STATE_CHANGED,J({room:this},r));return}this.emit(e,r)}sendStartPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("publishCdn",e)}sendStopPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("stopPublishCdn",e)}sendStartMixTranscode(e){return this.sendMessage("startMcuMix",e)}sendStopMixTranscode(e){return this.sendMessage("stopMcuMix",e)}publish(...e){return v(this,null,function*(){let r=e.reduce((d,h)=>h.mediaType|d,0),o=this.sendMessage("publish",r).then(d=>d.err!==0?Promise.reject(d.err):d),s=0,a=d=>v(this,null,function*(){switch(yield o,d.muted&&(s|=d.mediaType),Rt(d,d).add("mute",()=>{this.postMessage("mute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),d.mediaType){case 1:VE.call(this,d);break;default:yield BE.call(this,d)}});yield Promise.all(e.map(a)),s&&this.postMessage("mute",{mediaType:s,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(...e){return v(this,null,function*(){e.forEach(ct)})}subscribe(...e){return v(this,null,function*(){let r=e.reduce((y,R)=>R.mediaType|y,0),{userId:o,tinyId:s,streamType:a}=e[0],d=this.remotePublishedUserMap.get(o),h=J({},d.subscribeState),p=Object.assign(new Aa,h);p.mediaType|=r,B.emit(O.SUBSCRIBE_START,{room:this,streamType:a,remotePublishedUser:d,subscribeState:p});let T=yield this.sendMessage("subscribe",{mediaType:p.mediaType,userId:o,srctinyid:s,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(y=>p.mediaType&y).map(y=>({mediaType:y,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",T),yield Promise.all(e.filter(y=>!y.isSubscribed).map(y=>{switch(y.mediaType){case 1:return kE.call(this,y);default:return LE.call(this,y)}})),B.emit(O.SUBSCRIBE_SUCCESS,{room:this,streamType:a,remotePublishedUser:d})})}unsubscribe(...e){return v(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType,o.unsubscribe();if(e.length){let{userId:o,streamType:s,tinyId:a}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:a,userId:o}),B.emit(O.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return v(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield rl.call(this,o,{profile:o.small,type:3,trackType:"camera"});let s=new MediaStreamTrackProcessor({track:this.videoManager.smallTrack}).readable;this.smallEncoder.track=this.videoManager.smallTrack,this.smallEncoder.label="small",this.smallAbortCtrl=new AbortController,this.smallEncoder.start(s,this.smallAbortCtrl,this),this._log.info("push small")}}else(r=this.smallAbortCtrl)==null||r.abort("stop"),this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder)})}changeType(e,r){let o=this.remotePublishedUserMap.get(r.userId),s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let a={srctinyid:r.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(d=>s&d).map(d=>({mediaType:d,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};o.remoteVideoTrack.mediaType=a.mediaType,this.postMessage("changetype",a)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};q([zi(Kr.prototype.afterJoin),be(["left",Z.INIT],"joined"),yE()],Kr.prototype,"join",1),q([be("joined","left",{ignoreError:!0}),AE()],Kr.prototype,"_leave",1),q([Kd((...i)=>0),bE()],Kr.prototype,"publish",1),q([Kd((...i)=>0),vE()],Kr.prototype,"unpublish",1),q([Kd((...i)=>i[0].userId),RE()],Kr.prototype,"subscribe",1);mn.frameWorkType=37;mn.create=function(i){let t=mn._create.call(this,Kr,i);return t._use(Ks,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(yt.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",Ke,"created",yt),t};Object.assign(mn.prototype,{_setCurrentSpeaker(i){var t;return(t=eo.audioCtx)!=null&&t.setSinkId?eo.audioCtx.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return v(this,null,function*(){return this.startPlugin(Ks.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.420028"},fallback:"wasm"}),new Promise((e,r)=>{We(Je(i,"decode-downgrade-state-changed"),Go(o=>o.state==="STARTED"),xr(1),sh(5e3),gt(Je(i,Z.INIT)),dt(e,r))})})}});var S$=mn;export{S$ as default};
|